diff --git "a/3714.jsonl" "b/3714.jsonl" new file mode 100644--- /dev/null +++ "b/3714.jsonl" @@ -0,0 +1,798 @@ +{"seq_id":"120559292","text":"#!/bin/python3\n\nimport sys\nfrom scyllaso import common\nfrom scyllaso.cs import CassandraStress\nfrom scyllaso.common import Iteration\nfrom scyllaso.scylla import Scylla\nfrom scyllaso.hdr import parse_profile_summary_file\nfrom scyllaso.cassandra import Cassandra\nfrom datetime import datetime\n\nprint(\"Test started at:\", datetime.now().strftime(\"%H:%M:%S\"))\n\nif len(sys.argv) < 2:\n raise Exception(\"Usage: ./benchmark_latency_throughput.py [PROFILE_NAME]\")\n\n# Load properties\nprofile_name = sys.argv[1]\nprops = common.load_yaml(f'{profile_name}.yml')\nenv = common.load_yaml(f'environment_{profile_name}.yml')\ncluster_private_ips = env['cluster_private_ips']\ncluster_string = \",\".join(cluster_private_ips)\ncluster_public_ips = env['cluster_public_ips']\nloadgenerator_public_ips = env['loadgenerator_public_ips']\nloadgenerator_count = len(loadgenerator_public_ips)\n\n# Run parameters\n\n# Row size of default cassandra-stress workload.\n# Measured experimentally.\nROW_SIZE_BYTES = 210 * 1024 * 1024 * 1024 / 720_000_000\n\n# 1TB per node\n#TARGET_DATASET_SIZE = len(cluster_private_ips) * 1024 * 1024 * 1024 * 1024\nTARGET_DATASET_SIZE = props['target_dataset_size_gb'] * 1024 * 1024 * 1024\n\nREPLICATION_FACTOR = 3\nCOMPACTION_STRATEGY = props['compaction_strategy']\nROW_COUNT = int(TARGET_DATASET_SIZE / ROW_SIZE_BYTES / REPLICATION_FACTOR)\n\nSTART_RATE = props['start_rate'] #10000\nRATE_INCREMENT = props['rate_increment'] #10000\nDURATION_MINUTES = props['duration_minutes']\n\nMAX_90_PERCENTILE_LATENCY = 1000.0\n\nWRITE_COUNT = props['write_count']\nREAD_COUNT = props['read_count']\n\n# Start Scylla/Cassandra nodes\nif props['cluster_type'] == 'scylla':\n cluster = Scylla(env['cluster_public_ips'], env['cluster_private_ips'], env['cluster_private_ips'][0], props)\n cluster.install()\n cluster.start()\nelse:\n cluster = Cassandra(env['cluster_public_ips'], env['cluster_private_ips'], env['cluster_private_ips'][0], props)\n cluster.install()\n cluster.start()\n\nprint(\"Nodes started at:\", datetime.now().strftime(\"%H:%M:%S\"))\n\ncs = CassandraStress(env['loadgenerator_public_ips'], props)\ncs.install()\ncs.prepare()\n\nprint(\"Loading started at:\", datetime.now().strftime(\"%H:%M:%S\"))\n\nTHROTTLE = (100000 * 5 // loadgenerator_count) if props['cluster_type'] == 'scylla' else (56000 * 9 // loadgenerator_count)\n\ncs.stress_seq_range(ROW_COUNT, 'write cl=QUORUM', f'-schema \"replication(strategy=SimpleStrategy,replication_factor={REPLICATION_FACTOR})\" \"compaction(strategy={COMPACTION_STRATEGY})\" -log hdrfile=profile.hdr -graph file=report.html title=benchmark revision=benchmark-0 -mode native cql3 maxPending=1024 -rate \"threads=700 throttle={THROTTLE}/s\" -node {cluster_string}')\n\ncluster.nodetool(\"flush\")\n\nconfirm = input(\"Has compaction finished? Input 'yes':\")\nwhile confirm != 'yes':\n confirm = input(\"Has compaction finished? Input 'yes':\") \n\nprint(\"Run started at:\", datetime.now().strftime(\"%H:%M:%S\"))\n\nrate = START_RATE\n\nwhile True:\n print(\"Run iteration started at:\", datetime.now().strftime(\"%H:%M:%S\"))\n\n iteration = Iteration(f'{profile_name}/cassandra-stress-{rate}', ignore_git=True)\n\n cs.stress(f'mixed ratio\\\\(write={WRITE_COUNT},read={READ_COUNT}\\\\) duration={DURATION_MINUTES}m cl=QUORUM -pop dist=UNIFORM\\\\(1..{ROW_COUNT}\\\\) -log hdrfile=profile.hdr -graph file=report.html title=benchmark revision=benchmark-0 -mode native cql3 maxPending=1024 -rate \"threads=500 fixed={rate // loadgenerator_count}/s\" -node {cluster_string}')\n\n cs.collect_results(iteration.dir)\n\n if WRITE_COUNT > 0:\n write_profile_summary = parse_profile_summary_file(f'{iteration.dir}/profile-summary.txt', 'WRITE')\n print('WRITE_PROFILE', write_profile_summary)\n\n if READ_COUNT > 0:\n read_profile_summary = parse_profile_summary_file(f'{iteration.dir}/profile-summary.txt', 'READ')\n print('READ_PROFILE', read_profile_summary)\n\n with open(f'{iteration.dir}/parsed_profile_summary_file.txt', 'a') as writer:\n if WRITE_COUNT > 0:\n writer.write(f'WRITE_PROFILE: {write_profile_summary}\\n')\n if READ_COUNT > 0:\n writer.write(f'READ_PROFILE: {read_profile_summary}\\n')\n\n if WRITE_COUNT > 0 and write_profile_summary.p90_latency_ms > MAX_90_PERCENTILE_LATENCY:\n break\n if READ_COUNT > 0 and read_profile_summary.p90_latency_ms > MAX_90_PERCENTILE_LATENCY:\n break\n\n rate += RATE_INCREMENT\n\nprint(\"Run ended at:\", datetime.now().strftime(\"%H:%M:%S\"))\n","sub_path":"scyllaso/benchmarks/cassandra4-scylla-comparison/benchmark_latency_throughput_5x.py","file_name":"benchmark_latency_throughput_5x.py","file_ext":"py","file_size_in_byte":4452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"638035919","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef h( x, th0, th1 ):\r\n return th0 + th1 * x \r\n\r\ndef cost( th0, th1, x, y ):\r\n m = x.shape[0]\r\n return 1/(2*m) * np.sum( (y - h( x, th0, th1 ))**2 )\r\n\r\ndef DcostDth0(th0, th1, x, y):\r\n m = x.shape[0]\r\n return -1/m * np.sum( ( y - h( x, th0, th1 ) ) * 1 )\r\n\r\ndef DcostDth1(th0, th1, x, y):\r\n m = x.shape[0]\r\n return -1/m * np.sum( ( y - h( x, th0, th1 ) ) * x )\r\n\r\n\r\n#数据\r\nx_data = np.arange(10).reshape(10,1)\r\n\r\nnoise = np.random.uniform( low = -2, high = 2, size = (10,1) )\r\n\r\ny_data = -2 * x_data + 3 + noise\r\n\r\n#参数随机初始化\r\nthe_random_th = np.random.rand(1,2)\r\n\r\nth0 = the_random_th[0][0]\r\nth1 = the_random_th[0][1]\r\n\r\n\r\n#画图\r\nfig = plt.figure()\r\nax = fig.add_subplot(1, 1, 1)\r\nax.scatter(x_data, y_data) # 蓝色散点是数据点 \r\nlines = ax.plot(x_data, th1 * x_data + th0 ,c = 'r')\r\nplt.ion()\r\nplt.show()\r\n\r\n\r\n\r\nalpha = 0.01\r\nfor i in range(1000):\r\n th0 -= alpha * DcostDth0(th0, th1, x_data, y_data)\r\n th1 -= alpha * DcostDth1(th0, th1, x_data, y_data)\r\n if i %50 == 0:\r\n print('cost=', cost(th0, th1, x_data, y_data))\r\n ax.lines.remove(lines[0])\r\n lines = ax.plot(x_data,th1 * x_data + th0 ,c = 'r')\r\n plt.pause(0.1)\r\nprint('th1, th0 =',th1, th0)\r\n","sub_path":"practicePy/04梯度下降.py","file_name":"04梯度下降.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"333796470","text":"import logging\n\nfrom time import time\n\nimport pandas as pd\nfrom traitlets import Bool, Dict, Int, List, Unicode, observe\nfrom ipywidgets import register, widget_serialization\n\nfrom regulus import default_inverse_regression, HasTree\n\nfrom .core.axis import AxisTraitType\nfrom .core.trait_types import TypedTuple\nfrom .core.base import RegulusDOMWidget\nimport ipyregulus.utils as utils\n\nlogger = logging.getLogger(__name__)\n\n\ndef convert(data, cy, scaler):\n def values(i):\n v = [0] * cy\n for c in range(cols):\n v[c] = data[c]['x'][i]\n if scaler is not None:\n v = list(scaler.transform([v])[0])\n v.append(data[0]['y'][i])\n return v\n\n cols = len(data)\n n = len(data[0]['x'])\n line = [dict(id=i, values=values(i)) for i in range(n)]\n return line\n\n\n@register\nclass GraphView(HasTree, RegulusDOMWidget):\n _model_name = Unicode('GraphModel').tag(sync=True)\n _view_name = Unicode('GraphView').tag(sync=True)\n\n axes = TypedTuple(trait=AxisTraitType()).tag(sync=True, **widget_serialization)\n color = Unicode().tag(sync=True)\n graph = Dict().tag(sync=True)\n show = List(Int()).tag(sync=True)\n highlight = Int(-1).tag(sync=True)\n selected = List((Int())).tag(sync=True)\n show_inverse = Bool(True).tag(sync=True)\n _add_inverse = Dict(allow_none=True).tag(sync=True)\n\n def __init__(self, tree=None, **kwargs):\n super().__init__(**kwargs)\n self._dataset = None\n self._tree = None\n self.tree = tree\n self._cache = set()\n self._msg = None\n self._show_inverse = True\n\n def update(self, tree):\n super().update(tree)\n if tree is None:\n self.axes = []\n self.graph = dict(pts=[], partitions=[])\n self._dataset = None\n self._cache = set()\n return\n elif self._tree.regulus != self._dataset:\n dataset = self._dataset = self._tree.regulus\n nx = len(list(dataset.x))\n cy = list(dataset.pts.values).index(dataset.measure)\n self.axes = utils.create_axes(dataset.x, cols=range(nx)) + utils.create_axes(dataset.y, cols=[nx+cy])\n pts = pd.merge(left=dataset.pts.x,\n right=dataset.pts.values,\n left_index=True,\n right_index=True)\n pts = [dict(id=i, values=list(v)) for i, v in zip(pts.index, pts.values)]\n self.reset_inverse()\n else:\n pts = self.graph.get('pts', None)\n partitions = self._get_partitions()\n self.graph = dict(pts=pts, partitions=partitions)\n\n def reset_inverse(self):\n self._cache.clear()\n self._add_inverse = dict(topic='reset')\n self._show({'new': self.show})\n\n def _get_partitions(self):\n partitions = []\n if self._tree is not None:\n for node in self.tree:\n p = node.data\n min_idx, max_idx = p.minmax_idx\n base_born = self._dataset.partition(p.base).persistence\n is_selected = p.id in self.selected\n partitions.append(dict(\n pid=p.id,\n base_born=base_born,\n born=p.persistence,\n die=node.parent.data.persistence,\n life=node.parent.data.persistence-base_born,\n size=p.size(),\n min_idx=min_idx,\n max_idx=max_idx,\n index=p.idx,\n base=p.base,\n selected=is_selected\n ))\n return partitions\n\n @observe('show')\n def _show(self, change):\n show = change['new']\n logger.info('show')\n if self._tree is not None:\n scaler = self._dataset.pts.scaler\n if not self._tree.regulus.attr.has('inverse_regression'):\n self._tree.regulus.add_attr(default_inverse_regression, name='inverse_regression')\n t_start = time()\n cy = len(list(self._dataset.x)) + list(self._dataset.values).index(self._dataset.measure)\n data = {}\n pids = filter(lambda pid: pid not in self._cache, show)\n t0 = time()\n for node in self._dataset.find_nodes(pids):\n line = self._tree.attr['inverse_regression'][node]\n data[node.id] = convert(line, cy, scaler)\n self._cache.add(node.id)\n if time() - t0 > 0.5:\n logger.debug(f'{time() - t0}')\n # send partial data by assigning value and then set to None\n self._add_inverse = dict(topic='add', data=data)\n self._add_inverse = None\n data = {}\n t0 = time()\n if len(data) > 0:\n logger.debug(f'{time() - t0}')\n # send partial data by assigning value and then set to None\n self._add_inverse = dict(topic='add', data=data)\n self._add_inverse = None\n logger.debug(f' total={time() - t_start}')\n\n","sub_path":"ipyregulus/graph_view.py","file_name":"graph_view.py","file_ext":"py","file_size_in_byte":5136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"319325107","text":"from __future__ import print_function\n\nclass pointsList(object):\n def __init__(self):\n self.List = {}\n\n def addPoint(self, start, end):\n \n if start in self.List.keys():\n self.List[start].append(end)\n else:\n self.List[start] = [end]\n\n def printList(self):\n for i in self.List:\n print((i,'->',' -> '.join([str(j) for j in self.List[i]])))\n\nif __name__ == '__main__':\n lst = pointsList()\n lst.addPoint(0, 5)\n \n lst.addPoint(0, 5)\n lst.addPoint(4, 1)\n lst.addPoint(2, 3)\n lst.addPoint(2, 0)\n lst.addPoint(2, 4)\n \n lst.printList()\n \n","sub_path":"algo.py","file_name":"algo.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"520167126","text":"import networkx as nx\nimport torch.nn as nn\nfrom utils.NetworkBlock import ConvBn, Upsamp_Block, Out_Layer, Add_Block, PretrainedConvBn, ResidualBlock, myConvBn\nfrom utils.NetworkBlock import SkipBlock, DilSepConvBlock, SepConvBlock, ResBlock, ResMaker, ConvAddBlock\nimport torch\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport io\nimport torch.nn.functional as F\n\n\nnode_format = '{}_{}'\nconn_format = '{}_{}-{}_{}'\ndef_params = [640, 480]\n\npretrained =True\n\n\ndef draw_deterministic_graph(model,title=None,weights=None):\n # colormap = plt.cm.YlGnBu\n plt.close()\n\n graph_object = model.graph_object\n output_node_keys = model.output_node_keys\n\n # if weights is None: weights = np.ones(len(self.full_graph.edges))\n # for k, v in full_graph.positions.items():\n # node_positions[k] = [int(k[2]), self.num_rows - int(k[0])]\n\n node_labels = {k: k for k in graph_object.positions.keys() if k not in output_node_keys}\n\n plt.title('Deterministic CNF Lattice')\n\n for node in output_node_keys:\n x, y = graph_object.positions[node]\n plt.text(x, y, s=node, )\n\n nx.draw_networkx_nodes(graph_object.full_graph, pos=graph_object.positions)\n nx.draw_networkx_labels(graph_object.full_graph, pos=graph_object.positions, labels=node_labels)\n nx.draw_networkx_edges(graph_object.full_graph, pos=graph_object.positions, width=5,\n arrows=False, with_labels=True)\n\n img_data = io.StringIO()\n plt.subplots_adjust(right=2.0)\n plt.savefig(img_data, format='svg', bbox_inches=\"tight\")\n return img_data\n\n\ndef draw_stochastic_graph(graph_object, weights, title=None):\n colormap = plt.cm.YlGnBu\n plt.close()\n\n output_node_keys = graph_object.output_node_keys\n\n # if weights is None: weights = np.array([p.data.numpy()[0] for p in param_dict.values()])\n\n node_labels = {k: k for k in graph_object.positions.keys() if k not in output_node_keys}\n\n\n fig, ax = plt.subplots()\n ax.set_title(title)\n ax.set_xticks([])\n ax.set_yticks([])\n ax.axis('off')\n\n for node in output_node_keys:\n x,y = graph_object.positions[node]\n ax.text(x, y, s=node)\n\n nx.draw_networkx_nodes(graph_object.full_graph, pos=graph_object.positions)\n nx.draw_networkx_labels(graph_object.full_graph, pos=graph_object.positions, labels=node_labels)\n\n if 'True Paths' in title:\n elist = [edge for edge_index, edge in enumerate(graph_object.full_graph.edges) if weights[edge_index] > 0]\n res = nx.draw_networkx_edges(graph_object.full_graph, pos=graph_object.positions, edgelist=elist, width=5,\n arrows=False, with_labels=True,\n edge_vmin=weights.min(), edge_vax=5 * weights.min())\n elif 'Probs' in title:\n res = nx.draw_networkx_edges(graph_object.full_graph, pos=graph_object.positions, width=5,\n arrows=False, with_labels=True, edge_color=weights,\n edge_cmap=colormap, edge_vmin=float(weights.min()) - 0.1,\n edge_vax=5 * weights.min())\n\n fig.colorbar(res, pad = 0.1)\n\n img_data = io.StringIO()\n plt.savefig(img_data, format='svg')\n return img_data\n\n\ndef get_layer_functions(pretrained, residual):\n\n if pretrained is True:\n layer_class = PretrainedConvBn # pretrained_layer\n else:\n layer_class = myConvBn # normal_layer\n\n if residual:\n layer_class = ResidualBlock # residual_layer\n\n return layer_class\n\n\ndef get_drawing_function(stochastic):\n if stochastic is True:\n drawing_function = draw_stochastic_graph\n else:\n drawing_function = draw_deterministic_graph\n return drawing_function\n\nclass GeneralCNF:\n\n def __init__(self, network_properties):\n\n self.input_node_key = '0_0'\n self.network_properties = network_properties\n\n self.node_dict = nn.ModuleDict()\n\n self.module_edge_dicts = nn.ModuleDict() \n self.module_param_dicts = nn.ModuleDict()\n\n self.mod_type_dict = {'sep': SepConvBlock, 'dilsep': DilSepConvBlock, 'skip': SkipBlock, 'residual':ResidualBlock}\n\n if self.network_properties.layer_scaling is True:\n self.layer_chans = {0:64, 1:128, 2:256, 3:512}\n else:\n chans = self.network_properties.layer_channels\n self.layer_chans = {0: chans, 1: chans, 2: chans, 3: chans}\n\n if 'res' in self.network_properties.module_types:\n self.resmaker = ResMaker(self.network_properties.numrows, self.network_properties.numcols)\n self.mod_type_dict['res'] = ResMaker.make_resnet_layer\n self.layer_chans = {0:64, 1:128, 2:256, 3:512} #{0:256, 1:512, 2:1024, 3:2048}#\n for mod in network_properties.module_types:\n self.module_edge_dicts[mod] = nn.ModuleDict()\n self.module_param_dicts[mod] = nn.ParameterDict()\n\n\n self.param_index = {}\n\n self.graph_object = GraphMaker(self.network_properties.numcols,\n self.network_properties.numrows,\n self.network_properties.outputs)\n\n self.full_graph = self.graph_object.full_graph\n self.positions = self.graph_object.positions\n\n self.output_node_keys = set()\n\n self.make_output_layer()\n\n\n # self.downsampling_layer, self.samesampling_layer, \\\n # self.upsampling_layer = get_layer_functions(self.network_properties.layer_scaling, self.network_properties.residual)\n\n self.layer_function = get_layer_functions(self.network_properties.layer_scaling,\n self.network_properties.residual)\n\n self.successors = {node: [succ for succ in self.full_graph.successors(node)] for node in self.full_graph.nodes}\n\n self.assign_modules()\n self.draw = get_drawing_function(self.network_properties.stochastic)\n\n self.traversal_order = list(nx.lexicographical_topological_sort(self.full_graph))\n self.num_edges = len(self.full_graph.edges)\n\n def make_output_layer(self):\n\n # We use the head_count variable to track the number of heads that are attached to the top right node\n # We cannot simply enumerate the outputs, because then a classification node would lead to the heads being out\n # of order.\n # This is relevant for positioning.\n head_count = 0\n\n for output in self.network_properties.outputs:\n if output=='cl':\n self.add_output_node(output, row_index=self.network_properties.numrows-1, task_index=self.network_properties.numrows-1)\n else:\n self.add_output_node(output, row_index=0, task_index=head_count)\n head_count += 1\n\n def add_output_node(self, output, row_index=0, task_index=0):\n\n out_node = output+'_'+ node_format.format(row_index, self.network_properties.numcols)\n\n self.full_graph.add_node(out_node, row_index=row_index, col_index = self.network_properties.numcols)\n\n self.full_graph.add_edge(node_format.format(row_index, self.network_properties.numcols-1), out_node, layer_type='output')\n\n self.positions[out_node] = (self.network_properties.numcols, self.network_properties.numrows- task_index)\n\n self.output_node_keys.add(out_node)\n\n def assign_modules(self):\n\n self.assign_input_module()\n\n for mod_idx, mod in enumerate(self.network_properties.module_types):\n\n self.param_index[mod] = {}\n\n for edge_idx, edge in enumerate(self.full_graph.edges(data=True)):\n\n\n\n self.assign_edge_module(edge, mod)\n self.assign_edge_parameter(edge, mod)\n\n self.param_index[mod][edge[0] + '_' + edge[1]] = len(self.param_index[mod])\n\n\n # self.param_dict[edge[0] + '_' + edge[1]] = #edge[2]['sampling_param']\n # self.param_index[edge[0] + '_' + edge[1]] = len(self.param_index)\n # self.module_edge_dicts[mod][edge[0]+'_'+edge[1]] = self.full_graph[edge[0]][edge[1]]['module']\n\n\n\n\n for node in self.output_node_keys:\n self.output_node_function(node)\n\n for node_idx, node in enumerate(self.full_graph.nodes(data=True)):\n if node[0]==self.graph_object.input_node_key:\n self.node_dict[node[0]] = node[1]['module']\n elif node[0] in self.output_node_keys:\n self.node_dict[node[0]] = node[1]['module']\n else:\n preds = len(list(self.full_graph.predecessors(node[0])))\n ridx = min(3, int(node[0][0]))\n chans = self.layer_chans[ridx]\n self.node_dict[node[0]] = ConvAddBlock(preds*chans, chans)\n\n def assign_input_module(self):\n\n # NOTE THAT THE INPUT NODE HAS A CONV LAYER TO ACT AS AN ADAPTER FOR THE NUMBER OF INPUT CHANNELS\n # self.full_graph.nodes[self.graph_object.input_node_key]['module'] = \\\n # ConvBn(self.network_properties.input_channels,\n # self.network_properties.layer_channels,\n # relu=False,\n # k_size=self.network_properties.kdim,\n # bias=self.network_properties.bias)\n if self.network_properties.layer_scaling is True:\n\n self.full_graph.nodes[self.graph_object.input_node_key]['module'] = \\\n PretrainedConvBn(self.network_properties.input_channels,\n self.network_properties.layer_channels,\n self.network_properties.kdim,\n stride=1,\n bias=self.network_properties.bias,\n row_index=0, col_index=0, layer_type='input')\n\n\n else:\n\n self.full_graph.nodes[self.graph_object.input_node_key]['module'] = \\\n ConvBn(self.network_properties.input_channels,\n self.network_properties.layer_channels,\n self.network_properties.kdim,\n stride=1,\n bias=self.network_properties.bias)\n if 'res' in self.network_properties.module_types:\n self.full_graph.nodes[self.graph_object.input_node_key]['module'] = self.resmaker.make_input_block()\n\n def assign_edge_module(self, edge, mod):\n\n # For readability, we extract them from the netprops class\n layer_channels = self.network_properties.layer_channels\n kdim = self.network_properties.kdim\n bias = self.network_properties.bias\n\n\n ridx, cidx = int(edge[0][0]),int(edge[0][2])\n\n # def __init__(self, in_chan, out_chan, k_size=3, padding=1, layer_type='samesampling', norm_type='batch'):\n\n\n # if edge[2]['layer_type'] == 'output':\n # self.module_edge_dicts[mod][edge[0] + '_' + edge[1]] = self.layer_function(self.layer_chans[ridx],\n # self.layer_chans[ridx],\n # kdim, bias,\n # row_index=ridx, col_index=cidx,\n # layer_type='samesampling',\n # norm_type=self.network_properties.norm_type\n # )\n # self.full_graph[edge[0]][edge[1]]['module'] \\\n\n\n if (edge[2]['layer_type'] == 'upsampling') and (mod=='skip'):\n pass\n\n elif mod == 'res':\n\n ridx = min(ridx, 3)\n if edge[1] not in self.output_node_keys:\n target_ridx = min(int(edge[1][0]), 3)\n else:\n target_ridx = ridx\n\n cidx = int(edge[0][2])\n\n if target_ridx >= ridx: self.module_edge_dicts[mod][edge[0] + '_' + edge[1]] = self.mod_type_dict[mod](self.resmaker,\n ridx=ridx,\n target_ridx=target_ridx,\n cidx=cidx\n )\n else:\n self.module_edge_dicts[mod][edge[0] + '_' + edge[1]] = self.resmaker.make_upsamp_block(self.layer_chans[ridx], self.layer_chans[target_ridx])\n\n\n else:\n ridx = min(ridx, 3)\n if edge[1] not in self.output_node_keys:\n target_ridx = min(int(edge[1][0]), 3)\n else:\n target_ridx = ridx\n\n self.module_edge_dicts[mod][edge[0] + '_' + edge[1]] = self.mod_type_dict[mod](self.layer_chans[ridx],\n self.layer_chans[target_ridx],\n layer_type=edge[2]['layer_type'],\n norm_type=self.network_properties.norm_type\n )\n\n\n\n def output_node_function(self,node):\n\n output_channels = self.network_properties.output_channels\n # for key, val in output_channels.items():\n # val[1:] = val[1:] * 2 ** (-1 * self.network_properties.numrows-1) # +1 for the initial /4 in first node\n\n node_data = self.full_graph.nodes[node]\n\n ridx = node_data['row_index']\n ridx = min(ridx, 3)\n if 'seg' in node:\n aspp=True\n node_data['module'] = Out_Layer(self.layer_chans[ridx], output_channels['seg'],\n bias=True, nonlinearity=F.softmax,aspp=aspp)\n\n elif 'edge' in node:\n node_data['module'] = Out_Layer(self.layer_chans[ridx], output_channels['edge'],\n bias=True, nonlinearity=torch.sigmoid)\n\n elif 'auto' in node:\n node_data['module'] = Out_Layer(self.layer_chans[ridx], output_channels['auto'],\n bias=True, nonlinearity=torch.sigmoid)\n\n elif 'cl' in node:\n node_data['module'] = Out_Layer(self.layer_chans[ridx], output_channels['cl'],\n bias=True, nonlinearity=F.adaptive_avg_pool2d)\n\n elif 'dep' in node:\n node_data['module'] = Out_Layer(self.layer_chans[ridx], output_channels['dep'],\n bias=True, nonlinearity=F.relu)\n\n else:\n raise ValueError('Invalid Node key for output node')\n\n def assign_edge_parameter(self, edge, mod):\n\n default_param = torch.Tensor([3.0])\n\n if edge[2]['layer_type'] == 'output':\n self.module_param_dicts[mod][edge[0] + '_' + edge[1]] = nn.Parameter(torch.Tensor([np.inf]), requires_grad=False)\n\n # self.full_graph[edge[0] + '_' + edge[1]]['sampling_param'] = np.inf\n # nn.Parameter(torch.Tensor([np.inf]), requires_grad=False)\n\n # elif edge[2]['layer_type'] == 'downsampling':\n # self.full_graph[edge[0]][edge[1]]['sampling_param'] = nn.Parameter(default_param, requires_grad=True)\n\n else:\n self.module_param_dicts[mod][edge[0] + '_' + edge[1]] = nn.Parameter(default_param, requires_grad=True)\n\n # return nn.Parameter(default_param, requires_grad=True)\n # self.full_graph[edge[0]][edge[1]]['sampling_param'] = default_param\n # nn.Parameter(default_param, requires_grad=True)\n\n # self.graph_sampling_parameters.append(self.full_graph[edge[0]][edge[1]]['sampling_param'])\n\n\n\n def get_successor_dict(self):\n\n self.successors = {node:[self.full_graph.successors(node)] for node in self.full_graph.nodes}\n\n\n\n\nclass GraphMaker:\n\n def __init__(self, numcols, numrows, outputs):\n\n self.input_node_key = '0_0'\n\n self.num_cols = numcols\n self.num_rows = numrows\n self.outputs = outputs\n\n self.layer_list = self.make_graph_nodes()\n self.full_graph = self.join_graphs()\n self.positions = self.make_positions()\n\n self.make_all_edges()\n\n def make_final_column(self):\n output_layer_types = {'cl': 'zip_down', 'seg': 'zip_up'}\n\n for output in self.outputs:\n if output != 'cl':\n return [Layer(self.num_rows, self.num_cols - 1, output_layer_types['seg'])]\n\n return [Layer(self.num_rows, self.num_cols - 1, output_layer_types['cl'])]\n\n def make_graph_nodes(self):\n\n layer_list = []\n\n layer_list.append(Layer(self.num_rows, 0, 'input'))\n\n for j in range(1, self.num_cols - 1):\n layer_list.append(Layer(self.num_rows, j))\n\n layer_list += self.make_final_column()\n\n return layer_list\n\n def join_graphs(self):\n return nx.compose_all([l.graph for l in self.layer_list])\n\n def make_positions(self):\n\n positions = {}\n\n for row in range(self.num_rows):\n for col in range(self.num_cols):\n position_key = node_format.format(row, col)\n positions[position_key] = (col, self.num_rows-row)\n\n return positions\n\n def make_edge(self, ri, ci):\n\n edges = []\n\n if ri > 0:\n edges.append(\n (node_format.format(ri - 1, ci - 1), node_format.format(ri, ci), {'layer_type': 'downsampling'}))\n\n edges.append((node_format.format(ri, ci - 1), node_format.format(ri, ci), {'layer_type': 'samesampling'}))\n\n if ri < self.num_rows - 1:\n edges.append(\n (node_format.format(ri + 1, ci - 1), node_format.format(ri, ci), {'layer_type': 'upsampling'}))\n\n return edges\n\n def make_all_edges(self):\n\n for row_index in range(self.num_rows):\n\n for col_index in range(1,self.num_cols):\n\n edges = self.make_edge(row_index, col_index)\n self.full_graph.add_edges_from(edges)\n\nclass Layer:\n\n def __init__(self, num_rows, col_index, layer_type='middle'):\n self.scale = num_rows\n self.graph = nx.DiGraph()\n self.layer_col_index = col_index\n self.ltype = layer_type\n\n self.node_list = [node_format.format(row_index,self.layer_col_index) for row_index in range(self.scale)]\n self.node_pairs = [(self.node_list[node_idx],self.node_list[node_idx+1]) for node_idx in range(self.scale-1)]\n\n self.make_nodes()\n assert len(self.graph.nodes) == self.scale\n\n # If an input layer, we send all of the edges down\n if self.ltype == 'input':\n self.make_down_edges()\n assert len(self.graph.edges) == self.scale - 1\n\n # If our output is image size, i.e. for sem. seg. we pass all activations back up\n elif self.ltype == 'zip_up':\n self.make_up_edges()\n assert len(self.graph.edges) == (self.scale - 1)\n\n # If our output is 1x1 filters, i.e. for classification we pass all activations down\n elif self.ltype == 'zip_down':\n self.make_down_edges()\n assert len(self.graph.edges) == (self.scale - 1)\n\n def make_nodes(self):\n for node in self.node_list:\n self.graph.add_node(node, add_module=Add_Block(), row_index = int(node[0]), col_index = int(node[2]))\n\n def make_down_edges(self):\n for node_pair in self.node_pairs:\n self.graph.add_edge(node_pair[0], node_pair[1], layer_type='downsampling')\n\n def make_up_edges(self):\n for node_pair in self.node_pairs:\n self.graph.add_edge(node_pair[1], node_pair[0], layer_type='upsampling')\n\n\n\n","sub_path":"code/GraphObjects.py","file_name":"GraphObjects.py","file_ext":"py","file_size_in_byte":20237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"171456113","text":"from django.conf.urls import url\n\nfrom . import views\nfrom django.contrib.auth import views as auth_views\n\nurlpatterns = [\n url(\n regex=r'^$',\n view=views.HomePageView.as_view(),\n name='home'\n ),\n url(\n regex=r'^list$',\n view=views.UserListView.as_view(),\n name='list'\n ),\n url(\n regex=r'^list/(?P[\\w.@+-]+)/(?P(approve|unapprove))/$',\n view=views.approve_user,\n name='approve_user'\n ),\n url(\n regex=r'^~redirect/$',\n view=views.UserRedirectView.as_view(),\n name='redirect'\n ),\n url(\n regex=r'^~update/$',\n view=views.UserUpdateView.as_view(),\n name='update'\n ),\n url(\n regex=r'^~emailupdate/$',\n view=views.UserUpdateEmailView.as_view(),\n name='update_email'\n ),\n url(\n regex=r'^~passwordupdate/$',\n view=views.UserUpdatePasswordView.as_view(),\n name='update_password'\n ),\n url(\n regex=r'^~updateteam/(?P\\d+)/$',\n view=views.UserUpdateTeamView.as_view(),\n name='update_team'\n ),\n url(\n regex=r'^signup/$',\n view=views.signup,\n name='signup'\n ),\n url(\n r'^login/$',\n auth_views.login,\n {'template_name':'users/login.html'},\n name='login'\n ),\n url(\n r'^logout/$',\n auth_views.logout,\n {'template_name':'users/logout.html'},\n name='logout'\n ),\n url(\n regex=r'^create_team/$',\n view=views.create_team,\n name='create_team'\n ),\n url(\n regex=r'^(?P[\\w.@+-]+)/$',\n view=views.UserDetailView.as_view(),\n name='detail'\n ),\n]\n","sub_path":"voting/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"384255945","text":"import matplotlib.pyplot as plt\nfrom openpyxl import load_workbook\nimport numpy as np\nfrom tkinter import *\nfrom tkinter import ttk\nimport matplotlib\nmatplotlib.use('TkAgg')\nfrom matplotlib.figure import Figure\nfrom matplotlib import style\nfrom nltk.tokenize import word_tokenize\nfrom matplotlib import rc\nimport pandas as pd\n# import copy\n'''************************************************* Intro + Window ***********************************************'''\n\n\n# rc('font', **{'family':'sans-serif', 'sans-serif':['Helvetica']})\nrc('text', usetex=True)\n\nstyle.use('seaborn-ticks') # seaborn- : muted, darkgrid, paper, ticks\nfig = plt.figure()\n\nwindow = Tk()\n\nOut = Entry(window)\nOut.get()\nOut.pack()\n\n'''************************************************* End *****************************************************'''\n\n'''*************************************************Récupération des résultats**************************************'''\nwith open(\"Mage_fin.ini\",'r') as file:\n contenu=file.read()\n\n#print(contenu)\nliste=contenu.split(\"\\n\")\nMyman=[nb.split(' ') for nb in liste]\ndel Myman[0:8]\ndel Myman[len(Myman)-1]\ndel Myman[0][0:3]\ndel Myman[1:len(Myman)-1][0:5]\nData=[]\nfor nb in Myman:\n B=[elt for elt in nb if elt!='']\n del B[0:2]\n Data.append(B)\n\ndel Data[0]\n\n# raw results\n\nL =[nb[5] for nb in Data]\nZ_berge= L[:99]\nL3 =[nb[4] for nb in Data]\nZ_berge.extend(L3[100:])\nZ_berge = np.array(Z_berge)\n\n\n\nL =[nb[3] for nb in Data]\nZ_fond= L[:99]\nL3 =[nb[2] for nb in Data]\nZ_fond.extend(L3[99:])\nZ_fond = np.array((Z_fond),float)*1000\n\nL =[nb[4] for nb in Data]\nZ_moyen= L[:99]\nL3 =[nb[3] for nb in Data]\nZ_moyen.extend(L3[99:])\nZ_moyen = np.array((Z_moyen),float)*1000\n\n\nL =[nb[2] for nb in Data]\nPm= L[:99]\nL3 =[nb[1] for nb in Data]\nPm.extend(L3[99:])\nPm = np.array((Pm),float)\n\n\nL =[nb[6] for nb in Data]\nHauteur= L[:99]\nL3 =[nb[5] for nb in Data]\nHauteur.extend(L3[99:])\nHauteur = np.array((Hauteur), float) * 1000\n\n\nL =[nb[1] for nb in Data]\nCote= L[:99]\nL3 =[nb[0] for nb in Data]\nCote.extend(L3[99:])\nCote = np.array((Cote), float) * 1000\n\n\n# Pm = np.array([nb[2] for nb in Data if nb[2]!= ''],float)\n# Z_fond = np.array([nb[3] for nb in Data if nb[3]!= ''],float)*1000\n# Hauteur = np.array([nb[6].split(' #')[0] for nb in Data if nb[6] != ''], float)*1000\n# Z_moyen = np.array([nb[4] for nb in Data if nb[4]!= ''],float)*1000\n# Cote = np.array([nb[1] for nb in Data if nb[1]!= ''],float)*1000\n\n\n# Hauteur = Cote- Z_fond\nQ=.164* np.ones(len(Hauteur))\nQl = np.array([nb[12] for nb in Data if nb[12]!= ''],float)\nQ_mineur = np.array([nb[13] for nb in Data if nb[13]!= ''],float)\nQr = np.array([nb[14] for nb in Data if nb[14]!= ''],float)\n\n# calculated results\nhmc = Hauteur - Z_fond\nhfp = Hauteur - Z_moyen\nhr = hfp / hmc\n\n\n\nData_Sim = {'Q': Q, 'Hauteur': Hauteur, 'Pm': Pm, 'Z_fond' : Z_fond, 'Z_moyen': Z_moyen, 'Z_berge': Z_berge, 'Ql': Ql,\n 'Q_mineur': Q_mineur, 'Qr': Qr, 'hmc' : hmc, 'hfp': hfp, 'hr': hr}\n'''*************************************************Récupération finie**********************************************'''\n\n'''*************************************************Récupération des données****************************************'''\nctn = load_workbook('Data.xlsx', data_only=True)\n\n\n'''Data Dupuis CM'''\nsheet = ctn.get_sheet_by_name(\"CM\")\n\nX_CM = np.array([sheet.cell(row=i, column=2).value for i in range(2, 500) if sheet.cell(row=i, column=2).value != None])\nhmc_CM = np.array([sheet.cell(row=i, column=15).value for i in range(2, 500) if sheet.cell(row=i, column=15).value != None])\nhfp_CM = np.array([sheet.cell(row=i, column=16).value for i in range(2, 500) if sheet.cell(row=i, column=16).value != None])\n #Calcul...\n\nhr_CM=hfp_CM/hmc_CM\nData_CM = {'X_CM': X_CM, 'hmc_CM': hmc_CM, 'hfp_CM': hfp_CM, 'hr_CM': hr_CM}\n\n\n'''Data Dupuis CW'''\nsheet = ctn.get_sheet_by_name(\"CW\")\n\nX_CW = np.array([sheet.cell(row=i, column=2).value for i in range(2, 500) if sheet.cell(row=i, column=2).value != None])\nhmc_CW = np.array([sheet.cell(row=i, column=15).value for i in range(2, 500) if sheet.cell(row=i, column=15).value != None])\nhfp_CW = np.array([sheet.cell(row=i, column=16).value for i in range(2, 500) if sheet.cell(row=i, column=16).value != None])\n #Calcul...\n\nhr_CW=hfp_CW/hmc_CW\nData_CW = {'X_CW': X_CW, 'hmc_CW': hmc_CW, 'hfp_CW': hfp_CW, 'hr_CW': hr_CW}\n\n'''Data Dupuis CMW'''\nsheet = ctn.get_sheet_by_name(\"CMW\")\n\nX_CMW = np.array([sheet.cell(row=i, column=2).value for i in range(2, 500) if sheet.cell(row=i, column=2).value != None])\nhmc_CMW = np.array([sheet.cell(row=i, column=15).value for i in range(2, 500) if sheet.cell(row=i, column=15).value != None])\nhfp_CMW = np.array([sheet.cell(row=i, column=16).value for i in range(2, 500) if sheet.cell(row=i, column=16).value != None])\nQfp_CMW = np.array([sheet.cell(row=i, column=19).value for i in range(2, 500) if sheet.cell(row=i, column=19).value != None])\nQmc_CMW = np.array([sheet.cell(row=i, column=20).value for i in range(2, 500) if sheet.cell(row=i, column=20).value != None])\nTau_CMW = np.array([sheet.cell(row=i, column=9).value for i in range(2, 500) if sheet.cell(row=i, column=9).value != None])\n #Calcul...\n\nhr_CMW=hfp_CMW/hmc_CMW\nQrel_CMW = 2*Qfp_CMW/(Qmc_CMW+2*Qfp_CMW)\n\nData_CMW = {'X_CMW': X_CMW, 'hmc_CMW': hmc_CMW, 'hfp_CMW': hfp_CMW, 'hr_CMW': hr_CMW, 'Qfp_CMW': Qfp_CMW,\n 'Qmc_CMW': Qmc_CMW, 'Qrel_CMW': Qrel_CMW, 'Tau_CMW': Tau_CMW}\n\n'''Data Dupuis CWM'''\nsheet = ctn.get_sheet_by_name(\"CWM\")\n\nX_CWM = np.array([sheet.cell(row=i, column=2).value for i in range(2, 500) if sheet.cell(row=i, column=2).value != None])\nhmc_CWM = np.array([sheet.cell(row=i, column=15).value for i in range(2, 500) if sheet.cell(row=i, column=15).value != None])\nhfp_CWM = np.array([sheet.cell(row=i, column=16).value for i in range(2, 500) if sheet.cell(row=i, column=16).value != None])\nQfp_CWM = np.array([sheet.cell(row=i, column=19).value for i in range(2, 500) if sheet.cell(row=i, column=19).value != None])\nQmc_CWM = np.array([sheet.cell(row=i, column=20).value for i in range(2, 500) if sheet.cell(row=i, column=20).value != None])\nTau_CWM = np.array([sheet.cell(row=i, column=9).value for i in range(2, 500) if sheet.cell(row=i, column=9).value != None])\n #Calcul...\n\nhr_CWM=hfp_CWM/hmc_CWM\nQrel_CWM = 2*Qfp_CWM/(Qmc_CWM+2*Qfp_CWM)\n\nData_CWM = {'X_CWM': X_CWM, 'hmc_CWM': hmc_CWM, 'hfp_CWM': hfp_CWM, 'hr_CWM': hr_CWM, 'Qfp_CWM': Qfp_CWM,\n 'Qmc_CWM': Qmc_CWM, 'Qrel_CWM': Qrel_CWM, 'Tau_CWM': Tau_CWM}\n\n\n# Lits simples:\n\n'''Data Dupuis M'''\nsheet = ctn.get_sheet_by_name(\"M\")\n\nX_M = np.array([sheet.cell(row=i, column=2).value for i in range(3, 500) if sheet.cell(row=i, column=2).value != None])\nh7_M = np.array([sheet.cell(row=i, column=3).value for i in range(3, 500) if sheet.cell(row=i, column=3).value != None])\nh15_M = np.array([sheet.cell(row=i, column=4).value for i in range(3, 500) if sheet.cell(row=i, column=4).value != None])\nh50_M = np.array([sheet.cell(row=i, column=5).value for i in range(3, 500) if sheet.cell(row=i, column=5).value != None])\n\n\nData_M = {'X_M': X_M, 'h7_M': h7_M, 'h15_M': h15_M, 'h50_M': h50_M}\n\n'''Data Dupuis W'''\nsheet = ctn.get_sheet_by_name(\"W\")\n\nX_W = np.array([sheet.cell(row=i, column=2).value for i in range(3, 500) if sheet.cell(row=i, column=2).value != None])\nh7_W = np.array([sheet.cell(row=i, column=3).value for i in range(3, 500) if sheet.cell(row=i, column=3).value != None])\nh15_W = np.array([sheet.cell(row=i, column=4).value for i in range(3, 500) if sheet.cell(row=i, column=4).value != None])\nh21_W = np.array([sheet.cell(row=i, column=5).value for i in range(3, 500) if sheet.cell(row=i, column=5).value != None])\n\nData_W = {'X_W': X_W, 'h7_W': h7_W, 'h15_W': h15_W, 'h21_W': h21_W}\n\n'''Data Dupuis MW'''\nsheet = ctn.get_sheet_by_name(\"MW\")\n\nX_MW = np.array([sheet.cell(row=i, column=2).value for i in range(3, 500) if sheet.cell(row=i, column=2).value != None])\nh7_MW = np.array([sheet.cell(row=i, column=3).value for i in range(3, 500) if sheet.cell(row=i, column=3).value != None])\nh15_MW = np.array([sheet.cell(row=i, column=4).value for i in range(3, 500) if sheet.cell(row=i, column=4).value != None])\nh21_MW = np.array([sheet.cell(row=i, column=5).value for i in range(3, 500) if sheet.cell(row=i, column=5).value != None])\n\n\nData_MW = {'X_MW': X_MW, 'h7_MW': h7_MW, 'h15_MW': h15_MW, 'h21_MW': h21_MW}\n'''Data Dupuis WM'''\nsheet = ctn.get_sheet_by_name(\"WM\")\n\nX_WM = np.array([sheet.cell(row=i, column=2).value for i in range(3, 500) if sheet.cell(row=i, column=2).value != None])\nh7_WM = np.array([sheet.cell(row=i, column=3).value for i in range(3, 500) if sheet.cell(row=i, column=3).value != None])\nh15_WM = np.array([sheet.cell(row=i, column=4).value for i in range(3, 500) if sheet.cell(row=i, column=4).value != None])\nh50_WM = np.array([sheet.cell(row=i, column=5).value for i in range(3, 500) if sheet.cell(row=i, column=5).value != None])\n\n\nData_WM = {'X_WM': X_WM, 'h7_WM': h7_WM, 'h15_WM': h15_WM, 'h50_WM': h50_WM}\n\n'''*************************************************Récupération finie****************************************'''\n\n'''************************************************* Plotting **********************************************'''\n\nData_all = {**Data_Sim, **Data_CM, **Data_CW, **Data_CMW, **Data_CWM, **Data_M, **Data_W, **Data_MW, **Data_WM}\nData_Dupuis = {**Data_CM, **Data_CW, **Data_CMW, **Data_CWM, **Data_M, **Data_W, **Data_MW, **Data_WM}\n\ndef separe(char):\n char2 = char.split('=f(')\n last = char2[1]\n len_last = len(last)\n return [char2[0],last.replace(last[len_last-1],'')]\n\n# Trouver les abscisses correspondantes dans les lites ('X_CM' et 'X_CW')\n\n\n\ndef GiveX(var):\n for e in list(Data_Sim):\n if var==e:\n return Data_all['Pm']\n\n for e in list(Data_W):\n if var==e:\n return Data_all['X_W']\n\n\n for e in list(Data_M):\n if var == e:\n return Data_all['X_M']\n\n for e in list(Data_MW):\n if var==e:\n return Data_all['X_MW']\n\n for e in list(Data_WM):\n if var == e:\n return Data_all['X_WM']\n\n for e in list(Data_CM):\n if var == e:\n return Data_all['X_CM']\n\n for e in list(Data_CW):\n if var == e:\n return Data_all['X_CW']\n\n for e in list(Data_CMW):\n if var == e:\n return Data_all['X_CMW']\n\n for e in list(Data_CWM):\n if var == e:\n return Data_all['X_CWM']\n\n\ndef affiche():\n\n input = word_tokenize(Out.get())\n # plt.figure(figsize=(10, 5))\n if 'compare' in input:\n\n # Trouver les paramètres qu'on compare en caractère (ex: 'h_CM' et 'h_CW')\n Chosen = [z for z in input for word in Data_all.keys() if z == word]\n\n ChosenX = Data_all[Chosen[0]]\n ChosenY = Data_all[Chosen[1]]\n\n # Tracer les expériences en points +\n if Chosen[0] in Data_Dupuis:\n plt.plot(GiveX(Chosen[0]), ChosenX, 'g^', label=Chosen[0], color='dodgerblue')\n plt.plot(GiveX(Chosen[1]), ChosenY, label=Chosen[1], LineWidth='2', color='chocolate')\n elif Chosen[1] in Data_Dupuis:\n plt.plot(GiveX(Chosen[0]), ChosenX, label=Chosen[0], LineWidth='2', color='chocolate')\n plt.plot(GiveX(Chosen[1]), ChosenY, 'g^', label=Chosen[1], color='dodgerblue')\n else:\n plt.plot(GiveX(Chosen[0]), ChosenX, label=Chosen[0], LineWidth='2', color='chocolate')\n plt.plot(GiveX(Chosen[1]), ChosenY, label=Chosen[1], LineWidth='2', color='dodgerblue')\n # ,'g^'\n plt.xlabel('Abscisse (m)')\n plt.ylabel('hauteur (mm)')\n plt.legend()\n plt.ylim(ymin=np.mean(ChosenY)-7, ymax=np.mean(ChosenY)+3)\n plt.title(\"Comparaison des hauteurs, cas: $DRG= 0.975$, $K_1=67 s.m^{-1/3}$\")\n\n df1 = pd.DataFrame({'x1': GiveX(Chosen[0]), 'y1': ChosenX})\n df2 = pd.DataFrame({'x2': GiveX(Chosen[1]), 'y2': ChosenY})\n df = pd.DataFrame(columns=['df1', 'df2'], index=np.linspace(0,17,40))\n df['df1']=np.interp(df.index, df1.x1, df1.y1)\n df['df2'] = np.interp(df.index, df2.x2, df2.y2)\n RMSE = np.round(np.sqrt(((1-df.df2.values/df.df1.values)**2).mean()),2)*100\n STD =np.round((df.df1.values-df.df2.values).std(),3)\n print(RMSE, STD)\n # print((1-df.df2.values/df.df1.values)**2)\n\n plt.text(13.5, 114, r'RMSE={} \\%'.format(RMSE)+'\\n' + r'$\\sigma={}$'.format(STD),\\\n size=13, bbox={'facecolor': 'white', 'alpha': .8})\n\n plt.grid(True)\n plt.show()\n\n\n\n else:\n [x, y] = separe(Out.get())\n\n for elt in Data_all.keys():\n if y==elt:\n ChosenX = Data_all[elt]\n Labelx = elt\n elif x==elt:\n ChosenY = Data_all[elt]\n Labely = elt\n\n\n if x in Data_Dupuis:\n plt.plot(ChosenX, ChosenY, 'g^', color='dodgerblue')\n\n else:\n plt.plot(ChosenX, ChosenY, LineWidth='2', color='dodgerblue')\n\n plt.xlabel(Labelx)\n plt.ylabel(Labely)\n\n plt.show()\n\n\n# df= pd.Series(Hauteur, Pm)\n\n# print(Hauteur, h50_WM)\n\n# writer = pd.ExcelWriter('output.xlsx')\n# df.to_excel(writer,'Feuil1')\n# writer.save()\n\n\nBoutton = ttk.Button(window, text=\"Go?\", command=lambda: affiche())\nBoutton.pack()\n\n\nwindow.mainloop()","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":13319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"429654216","text":"#!/usr/bin/python3.7\n\n\nclass A:\n def __init__(self):\n self._idade = 0\n \n @property\n def idade(self):\n return self._idade\n \n @idade.setter\n def idade(self, var):\n if var >= 0:\n self._idade = var\n else:\n print('valor deve ser maior ou igual zero!!')\n\na = A()\na.idade = -1\nprint(a.idade)\n","sub_path":"POO_python/propriedades.py","file_name":"propriedades.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"285674786","text":"\"\"\"empty message\n\nRevision ID: 8179554f9881\nRevises: 7e1d098b29de\nCreate Date: 2019-04-08 11:23:24.190824\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects.postgresql import UUID, JSON\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\nSession = sessionmaker()\nBase = declarative_base()\n\n# revision identifiers, used by Alembic.\nrevision = '8179554f9881'\ndown_revision = '7e1d098b29de'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n\n op.add_column('local_plan', sa.Column('housing_numbers_found', sa.Boolean(), nullable=True))\n op.add_column('local_plan', sa.Column('plan_period_found', sa.Boolean(), nullable=True))\n\n class LocalPlan(Base):\n __tablename__ = 'local_plan'\n\n id = sa.Column(UUID(as_uuid=True), primary_key=True)\n plan_start_year = sa.Column(sa.Date())\n plan_end_year = sa.Column(sa.Date())\n housing_numbers = sa.Column(JSON)\n plan_period_found = sa.Column(sa.Boolean)\n housing_numbers_found = sa.Column(sa.Boolean)\n\n bind = op.get_bind()\n session = Session(bind=bind)\n\n for plan in session.query(LocalPlan):\n if plan.housing_numbers is not None:\n plan.housing_numbers_found = True\n if plan.plan_start_year is not None and plan.plan_end_year is not None:\n plan.plan_period_found = True\n\n session.add(plan)\n session.commit()\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('local_plan', 'plan_period_found')\n op.drop_column('local_plan', 'housing_numbers_found')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/8179554f9881_.py","file_name":"8179554f9881_.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"191875062","text":"import ast\nimport configparser\nimport os\nimport sys\nfrom glob import glob\n\nimport numpy as np\nimport scipy\nimport scipy.stats\n\nif not (len(sys.argv) == 3 and os.path.isfile(sys.argv[1])):\n print('Usage: python \"%s\" [config file] [survival estimators file]'\n % sys.argv[0])\n sys.exit()\n\nexperiment_idx = 0\n\nconfig = configparser.ConfigParser()\nconfig.read(sys.argv[1])\ncross_val_n_folds = int(config['DEFAULT']['cross_val_n_folds'])\ndatasets = ast.literal_eval(config['DEFAULT']['datasets'])\n# coverage_range = \\\n# ast.literal_eval(config['DEFAULT']['conformal_prediction_CI_coverage'])\ncoverage_range = [0.6, 0.7, 0.8, 0.9, 0.95]\noutput_dir = config['DEFAULT']['output_dir']\n\nsurvival_estimator_names = []\nestimator_display_names = []\nwith open(sys.argv[2], 'r') as f:\n for line in f.readlines():\n line = line.strip()\n if not line.startswith('#'):\n pieces = line.split(' : ')\n if len(pieces) == 2:\n survival_estimator_names.append(pieces[0])\n estimator_display_names.append(pieces[1])\n\n\nestimator_display_name_to_LaTeX = {\n 'Cox': \"\\\\textsc{cox}\",\n 'RSF': \"\\\\textsc{rsf}\",\n 'DeepSurv': \"\\\\textsc{deepsurv}\",\n 'DeepHit': \"\\\\textsc{deephit}\",\n 'MTLR': \"\\\\textsc{mtlr}\",\n 'Nnet-survival': \"\\\\textsc{nnet-survival}\",\n 'Cox-CC': \"\\\\textsc{cox-cc}\",\n 'Cox-Time': \"\\\\textsc{cox-time}\",\n 'PC-Hazard': \"\\\\textsc{pc-hazard}\",\n 'NKS-Basic': \"\\\\textsc{nks-basic}\",\n 'NKS-Diag': \"\\\\textsc{nks-diag}\",\n 'NKS-Res-Basic': \"\\\\textsc{nks-res-basic}\",\n 'NKS-Res-Diag': \"\\\\textsc{nks-res-diag}\",\n 'NKS-MLP': \"\\\\textsc{nks-mlp}\",\n 'NKS-MLP (init: RSF)': \"\\\\textsc{nks-mlp} (init: \\\\textsc{rsf})\",\n 'NKS-MLP (init: DeepHit)': \"\\\\textsc{nks-mlp} (init: \\\\textsc{deephit})\",\n}\n\n# method for translating survival curve into single survival time estimate\nsurvival_time_method = 'median'\n\n# use all calibration data\ncalib_frac = 1.0\n\nn_estimators = len(survival_estimator_names)\nn_datasets = len(datasets)\nfor what in ['qhats', 'coverages']:\n for target_coverage in coverage_range:\n centers = np.zeros((n_estimators, n_datasets))\n spreads = np.zeros((n_estimators, n_datasets))\n\n for dataset_idx, dataset in enumerate(datasets):\n for estimator_idx, survival_estimator_name \\\n in enumerate(survival_estimator_names):\n matches = list(glob(\n os.path.join(\n output_dir,\n 'split_conformal_prediction',\n '%s_%s_exp%d_*%s_calib%f_%s.txt'\n % (survival_estimator_name, dataset, experiment_idx,\n survival_time_method, calib_frac, what))))\n if len(matches) != 1:\n print(\"\\n\".join(matches))\n assert len(matches) == 1\n match = matches[0]\n coverages = np.loadtxt(match)\n for row in coverages:\n if row[0] == target_coverage:\n if what == 'qhats':\n if dataset == 'support2_onehot':\n centers[estimator_idx, dataset_idx] \\\n = np.mean(row[1:]) / 30.42 * 2\n spreads[estimator_idx, dataset_idx] \\\n = np.std(row[1:]) / 30.42 * 2\n else:\n centers[estimator_idx, dataset_idx] \\\n = np.mean(row[1:]) * 2\n spreads[estimator_idx, dataset_idx] \\\n = np.std(row[1:]) * 2\n else:\n centers[estimator_idx, dataset_idx] \\\n = np.mean(row[1:])\n spreads[estimator_idx, dataset_idx] \\\n = np.std(row[1:])\n\n if what == 'coverages':\n print('[Empirical coverages for target coverage level %f]'\n % target_coverage)\n print()\n row_strings = []\n for estimator_idx in range(n_estimators):\n row_string = \\\n estimator_display_name_to_LaTeX[\n estimator_display_names[estimator_idx]]\n for dataset_idx in range(n_datasets):\n row_string += \\\n \" & $%0.3f\\\\pm%0.3f$\" \\\n % (centers[estimator_idx, dataset_idx],\n spreads[estimator_idx, dataset_idx])\n row_string += \" \\\\tabularnewline\"\n row_strings.append(row_string)\n print(\"\\n\\\\hline\\n\".join(row_strings))\n\n elif what == 'qhats':\n\n print('[Prediction interval widths for target coverage level %f]'\n % target_coverage)\n print()\n\n # figure out what estimator achieves the minimum q_hat per dataset;\n # we will be bolding these numbers\n arg_mins = [np.argmin(centers[:, dataset_idx])\n for dataset_idx in range(n_datasets)]\n\n # note: we multiply the numbers all by 2 in the table to get widths\n # rather than radii\n\n row_strings = []\n for estimator_idx in range(n_estimators):\n row_string = \\\n estimator_display_name_to_LaTeX[\n estimator_display_names[estimator_idx]]\n for dataset_idx in range(n_datasets):\n if estimator_idx == arg_mins[dataset_idx]:\n row_string += \\\n \" & $\\\\mathbf{%0.3f}\\\\pm%0.3f$\" \\\n % (centers[estimator_idx, dataset_idx],\n spreads[estimator_idx, dataset_idx])\n else:\n row_string += \\\n \" & $%0.3f\\\\pm%0.3f$\" \\\n % (centers[estimator_idx, dataset_idx],\n spreads[estimator_idx, dataset_idx])\n row_string += \" \\\\tabularnewline\"\n row_strings.append(row_string)\n print(\"\\n\\\\hline\\n\".join(row_strings))\n print()\n\n print()\n print()\n\n","sub_path":"visualization/print_LaTeX_tables_marginal.py","file_name":"print_LaTeX_tables_marginal.py","file_ext":"py","file_size_in_byte":6348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"606767520","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 ('usuarios', '0003_articulo_titulo'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='articulo',\n name='cualquiera',\n field=models.CharField(default='prueba', max_length=150),\n preserve_default=False,\n ),\n ]\n","sub_path":"chatgrafico/chatgrafico/apps/usuarios/migrations/0004_articulo_cualquiera.py","file_name":"0004_articulo_cualquiera.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"387406210","text":"pedidos = []\n\n\ndef adiciona(nome, sabor, observacao=None):\n pedido = {}\n pedido['nome'] = nome\n pedido['sabor'] = sabor\n pedido['observacao'] = observacao\n return pedido\n\npedidos.append(adiciona('Mario', 'Pepperoni'))\npedidos.append(adiciona('Caio', 'Soja de Soja', 'O cara das algas'))\n\nfor pedido in pedidos:\n template = 'Nome: {nome}\\nSabor: {sabor}'\n print(template.format(**pedido))\n if pedido['observacao']:\n print('Observacao: {}'.format(pedido['observacao']))\n","sub_path":"pyexamples/pedidos.py","file_name":"pedidos.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"498890068","text":"import tkinter as tk \r\nimport tkinter.ttk as ttk \r\nfrom PIL import ImageTk, Image\r\nfrom tkinter.messagebox import askyesno\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n# python script \r\nimport main as home \r\n\r\n#-----Computer System-------------\r\nimport laptops_page\r\nimport setting_account\r\nimport workstations_page\r\nimport mainframes_page\r\nimport servers_page\r\nimport desktops_page\r\n#-------------------------------\r\n\r\n\r\n#-------Popular Computers Page---\r\nimport generalized_item\r\n#------------------------------\r\n\r\n\r\n\r\n#----------Purpose Section Page------------\r\nimport purpose_computer_page\r\n#-----------------------------------------\r\n\r\n#-----------OS Section Page--------\r\nimport OS_computer_page\r\n#----------------------------------\r\n\r\n#-----------Arch Section Page-----\r\nimport Arch_computer_page\r\n#---------------------------------\r\n\r\n#-----------Computer Parts Page-----\r\nimport computer_parts_page\r\n#-----------------------------------\r\n\r\n#-----------Email Page------------\r\nimport emails_page\r\n#---------------------------------\r\n\r\n#------------Check out Page------\r\nimport check_out \r\n#--------------------------------\r\n\r\nclass customer_page(tk.Frame):\r\n\r\n def __init__(self, customer_name, customer_username, customer_Id, master = None):\r\n tk.Frame.__init__(self, master)\r\n \r\n self.customer_name = customer_name \r\n self.customer_username = customer_username\r\n self.customer_Id = customer_Id \r\n \r\n self.master.title( \"Customer_Page\" )\r\n self.master.geometry( \"1350x676\" )\r\n self.master.configure( background = \"light blue\" )\r\n self.create_widgets()\r\n\r\n def create_widgets(self):\r\n self.top = self.winfo_toplevel()\r\n self.style = tk.ttk.Style()\r\n\r\n #--------------------Lenovo Icon Image---------------------\r\n image_tempo = Image.open( \"images/lenovo_icon_2.png\" )\r\n self.my_image = ImageTk.PhotoImage( image_tempo )\r\n \r\n self.label_image = tk.Label( image = self.my_image )\r\n self.label_image.image = self.my_image \r\n self.label_image.place( x = 0, y = 0 )\r\n #----------------------------------------------------------\r\n\r\n \r\n #------------------------Title----------------------------- \r\n \r\n self.style.configure( \"LabelTitle.TLabel\", \r\n relief=tk.SUNKEN,\r\n anchor = \"left\", \r\n font = (\"Helvetica\", 20),\r\n background = '#49A' \r\n )\r\n self.LabelTitle = tk.ttk.Label( self.top, \r\n text = f\" HOME PAGE\\nWelcome {self.customer_name}!\", \r\n style = \"LabelTitle.TLabel\" \r\n )\r\n self.LabelTitle.place( relx = 0.4, rely = 0, \r\n relwidth = 0.3 , relheight = 0.15 \r\n )\r\n #------------------------------------------------------------\r\n\r\n\r\n\r\n #--------------------Computer System Label-----------------------\r\n self.style.configure( \"Computer_System_Label.TLabel\", \r\n relief = tk.SUNKEN,\r\n anchor = \"center\", \r\n font = (\"Helvetica\", 16),\r\n background = '#49A' \r\n )\r\n self.Computer_System_Label = tk.ttk.Label( self.top, \r\n text = \"Recommended Computer Systems\", \r\n style = \"Computer_System_Label.TLabel\" \r\n )\r\n self.Computer_System_Label.place( relx = 0, rely = 0.2, \r\n relwidth = 0.410 , relheight = 0.1 \r\n )\r\n #-----------------------------------------------------------------\r\n\r\n\r\n\r\n #-----------------3 Computer System--------------------------\r\n \r\n #--------Read the 3 Computer System chosen by Lenovo Admin--------\r\n self.computer_systems = self.manager_system_inputs()\r\n #-----------------------------------------------------------------\r\n \r\n plus_x = 0 \r\n plus_relx = 0 \r\n\r\n self.system_images = []\r\n self.System_Buttons = []\r\n\r\n for i in range( len(self.computer_systems) ):\r\n system_name = self.computer_systems[i]\r\n \r\n image_tempo = Image.open( f\"images/computer_systems/{system_name}.png\" )\r\n \r\n image_tempo = image_tempo.resize( (160,160), Image.ANTIALIAS)\r\n \r\n self.system_images.append(None)\r\n self.system_images[i] = ImageTk.PhotoImage( image_tempo )\r\n \r\n self.System_Buttons.append(None)\r\n\r\n self.System_Buttons[i] = tk.Button( self.top, text = f\"{system_name}\", fg = \"black\",\r\n command = lambda name_system = system_name: self.command_button_system(name_system),\r\n image = self.system_images[i], activebackground = \"light blue\", compound = \"top\")\r\n \r\n self.System_Buttons[i].place( relx = 0 + plus_relx, rely = 0.32, \r\n relwidth = 0.13, relheight = 0.26 )\r\n plus_relx += 0.14\r\n\r\n \r\n #-----------------------------------------------------------------\r\n\r\n #----------------------3 Most popular computers Section--------------------\r\n\r\n #-----------------3 Most popular computers LABEL----------------\r\n self.style.configure( \"Popular_Computers_Label.TLabel\", \r\n relief = tk.SUNKEN,\r\n anchor = \"left\", \r\n font = (\"Helvetica\", 16),\r\n background = '#49A' \r\n )\r\n self.Popular_Computers_Label = tk.ttk.Label( self.top, \r\n text = \"Top 3 Best Selling Computers\", \r\n style = \"Popular_Computers_Label.TLabel\" \r\n )\r\n\r\n self.Popular_Computers_Label.place( relx = 0.43, rely = 0.2, \r\n relwidth = 0.580 , relheight = 0.1 \r\n )\r\n \r\n #-------------------------------------------------------------\r\n\r\n #---------Get the most popular(best selling computers)------------\r\n df = pd.read_excel( \"csv_files/items.xlsx\" )\r\n df_all_computers = df[ df['Type'] != \"Computer Part\" ]\r\n\r\n df_all_computers = df_all_computers.sort_values( by = \"Number of Sales\", ascending = False) \r\n popular_computers = df_all_computers[:3]\r\n\r\n #---------------------------------------------------------------------\r\n\r\n plus_x = 0 \r\n plus_y = 0 \r\n plus_relx = 0 \r\n\r\n self.lenovo_images = []\r\n self.Computer_Buttons = []\r\n for i in range(len(popular_computers)):\r\n computer_name = popular_computers.iloc[i]['Name']\r\n computer_type = popular_computers.iloc[i]['Type']\r\n\r\n if computer_type == 'Desktop':\r\n image_tempo = Image.open( f\"images/Lenovo_Desktops/{computer_name}.png\" )\r\n elif computer_type == 'Laptop':\r\n image_tempo = Image.open( f\"images/Lenovo_Laptops/{computer_name}.png\" )\r\n elif computer_type == 'workstation':\r\n image_tempo = Image.open( f\"images/workstations/{computer_name}.png\" )\r\n elif computer_type == \"server\":\r\n image_tempo = Image.open( f\"images/servers/{computer_name}.png\" )\r\n elif computer_type == \"mainframe\":\r\n image_tempo = Image.open( f\"images/mainframes/{computer_name}.png\" )\r\n \r\n image_tempo = image_tempo.resize( (220,160), Image.ANTIALIAS )\r\n self.lenovo_images.append(None)\r\n\r\n self.lenovo_images[i] = ImageTk.PhotoImage( image_tempo )\r\n self.Computer_Buttons.append(None)\r\n \r\n self.Computer_Buttons[i] = tk.Button( self.top, \r\n command = lambda name = computer_name, type_ = computer_type : self.command_computers(name,type_), \r\n text = f\"{computer_name}\", fg = \"black\", image = self.lenovo_images[i],\r\n activebackground = \"light blue\", compound = \"top\")\r\n\r\n self.Computer_Buttons[i].place( relx = 0.4315 + plus_relx, rely = 0.32, \r\n relwidth = 0.175, relheight = 0.26)\r\n plus_relx += 0.19 \r\n\r\n #---------------------------------------------------------------------------------\r\n\r\n\r\n\r\n #------------------------Operating System Section--------------------------------\r\n\r\n #--------------------Label for operating system: Mac, Windows, Linux-------------------\r\n self.style.configure( \"Popular_Computers_Label.TLabel\", \r\n relief = tk.SUNKEN,\r\n anchor = \"left\", \r\n font = (\"Helvetica\", 16),\r\n background = '#49A' \r\n )\r\n\r\n self.Popular_Computers_Label = tk.ttk.Label( self.top, \r\n text = \"Operating\\nSystems:\", \r\n style = \"Popular_Computers_Label.TLabel\" \r\n )\r\n\r\n self.Popular_Computers_Label.place( relx = 0, rely = 0.6, \r\n relwidth = 0.09 , relheight = 0.175 \r\n )\r\n #---------------------------------------------------------------------------------------\r\n\r\n #----------------------Picture windows-mac-linux----------------------------------------\r\n image_tempo = Image.open( f\"images/operating_systems/mac_linux_windows_banner.png\" )\r\n image_tempo = image_tempo.resize( (400,115), Image.ANTIALIAS )\r\n self.operating_systems = ImageTk.PhotoImage( image_tempo )\r\n \r\n self.label_operating_systems = tk.Label( image = self.operating_systems )\r\n self.label_operating_systems.image = self.operating_systems \r\n self.label_operating_systems.place( x = 120, y = 404 )\r\n #---------------------------------------------------------------------------------------\r\n\r\n \r\n OS_list = ['Windows', 'Linux', 'Mac' ] \r\n self.OS_Buttons = list()\r\n plus_relx = 0 \r\n for i in range( len(OS_list) ):\r\n OS_name = OS_list[i]\r\n self.style.configure( f\"{OS_name}_bt.TButton\", \r\n anchor = \"center\", \r\n font = ( \"Helvetica\", 8 ),\r\n background = \"green\",\r\n foreground = \"black\" \r\n )\r\n self.OS_Buttons.append(None) \r\n\r\n self.OS_Buttons[i] = tk.ttk.Button( self.top, \r\n text = f\"{OS_name}\" ,\r\n command = lambda name_OS = OS_name: self.command_OS(name_OS) , \r\n style = f\"{OS_name}_bt.TButton\" \r\n )\r\n\r\n self.OS_Buttons[i].place( relx = 0.3 + plus_relx, rely = 0.72,\r\n relwidth = 0.08, relheight = 0.04)\r\n \r\n plus_relx -= 0.1\r\n\r\n \r\n #-------------------------------------------------------------------------------\r\n\r\n\r\n\r\n #------------------Architecture Section------------------------------\r\n\r\n #---------------------Label for architecture---------------------\r\n self.style.configure( \"Architecture_Label.TLabel\", \r\n relief = tk.SUNKEN,\r\n anchor = \"left\", \r\n font = (\"Helvetica\", 15),\r\n background = '#49A' \r\n )\r\n\r\n self.Architecture_Label = tk.ttk.Label( self.top, \r\n text = \"Architecture:\", \r\n style = \"Architecture_Label.TLabel\" \r\n )\r\n \r\n self.Architecture_Label.place( relx = 0, rely = 0.77, \r\n relwidth = 0.09 , relheight = 0.2 \r\n )\r\n #-----------------------------------------------------------------\r\n\r\n\r\n\r\n\r\n #---------------------Picture Intell Arm logo-------------------------\r\n image_tempo = Image.open( f\"images/architecture/intel_amd3.png\" )\r\n image_tempo = image_tempo.resize( (400,115), Image.ANTIALIAS )\r\n self.architecture = ImageTk.PhotoImage( image_tempo )\r\n \r\n self.label_architecture = tk.Label( image = self.architecture )\r\n self.label_architecture.image = self.architecture \r\n self.label_architecture.place( x = 120, y = 524 )\r\n #----------------------------------------------------------------------\r\n\r\n \r\n Architecture_List = ['AMD Ryzen', 'Intel']\r\n\r\n plus_relx = 0 \r\n self.Arch_Buttons = list()\r\n for i in range( len(Architecture_List) ):\r\n arch_name = Architecture_List[i]\r\n\r\n self.style.configure( f\"{arch_name}_bt.TButton\", \r\n anchor = \"center\", \r\n font = ( \"Helvetica\", 8 ),\r\n background = \"green\",\r\n foreground = \"black\" \r\n )\r\n \r\n self.Arch_Buttons.append(None)\r\n self.Arch_Buttons[i] = tk.ttk.Button( self.top, \r\n text = f\"{arch_name}\" ,\r\n command = lambda name_arch = arch_name: self.command_arch(name_arch) , \r\n style = f\"{arch_name}_bt.TButton\" \r\n )\r\n\r\n self.Arch_Buttons[i].place( relx = 0.142 + plus_relx, rely = 0.9,\r\n relwidth = 0.07, relheight = 0.04 )\r\n plus_relx += 0.12\r\n\r\n\r\n #--------------------------------------------------------------------\r\n\r\n #-----------------------Check out Section-------------------------------\r\n image_tempo = Image.open( f\"images/checkout.png\" )\r\n image_tempo = image_tempo.resize( (70,35), Image.ANTIALIAS )\r\n self.checkout_pic = ImageTk.PhotoImage( image_tempo )\r\n \r\n df_orders = pd.read_excel(\"csv_files/orders.xlsx\")\r\n\r\n df_user_shopping_cart = df_orders[ (df_orders[\"Username\"] == self.customer_username) & (df_orders['Order_Status'] == \"in cart\") ]\r\n\r\n items_in_cart = len(df_user_shopping_cart)\r\n if items_in_cart == 0: \r\n checkout_button = tk.Button(self.top, \r\n command = self.command_checkout,\r\n text = \"\", image = self.checkout_pic,\r\n compound = \"bottom\")\r\n checkout_button.place(relx = 0.79, rely= 0.095, relwidth= 0.07, relheight=0.1)\r\n else:\r\n checkout_button = tk.Button(self.top, \r\n command = self.command_checkout,\r\n text = f\"{items_in_cart} items\", image = self.checkout_pic,\r\n compound = \"bottom\")\r\n checkout_button.place(relx = 0.79, rely= 0.095, relwidth= 0.07, relheight=0.1)\r\n #-----------------------------------------------------------------------\r\n\r\n\r\n\r\n\r\n\r\n #---------------------Computer Parts Section-------------------------------------\r\n image_tempo = Image.open( f\"images/computer_parts/cpu_gpu.png\" )\r\n self.image_part = image_tempo.resize( (300,220), Image.ANTIALIAS )\r\n \r\n self.computer_parts_image = ImageTk.PhotoImage( self.image_part )\r\n self.computer_parts_image.image = self.image_part\r\n \r\n self.button_computer_parts_ = tk.Button( self.top, \r\n text = \"Computer Parts\",\r\n command = self.command_computer_parts, \r\n image = self.computer_parts_image,\r\n compound = \"top\"\r\n )\r\n self.button_computer_parts_.place( relx = 0.752, rely = 0.61,\r\n relwidth = 0.235, relheight = 0.36 )\r\n #----------------------------------------------------------------------------------\r\n\r\n\r\n\r\n\r\n #-----------------------------------------------------------------------\r\n\r\n\r\n\r\n #---------------------Main Purpose Section------------------------------\r\n\r\n #-------------------Image for main purpose computer--------------------\r\n image_tempo = Image.open( f\"images/main_purpose/main_purpose.png\" )\r\n image_tempo = image_tempo.resize( (400,240), Image.ANTIALIAS )\r\n self.gpu_cpu = ImageTk.PhotoImage( image_tempo )\r\n \r\n self.label_gpu_cpu = tk.Label( image = self.gpu_cpu )\r\n self.label_gpu_cpu.image = self.gpu_cpu\r\n self.label_gpu_cpu.place( x = 553, y = 411 )\r\n #-----------------------------------------------------------------------\r\n\r\n \r\n Purpose_list = [ 'Gaming', 'Scientific', 'Business' ] \r\n \r\n plus_relx = 0 \r\n plus_rely = 0\r\n flag_row = True \r\n self.Purpose_Buttons = list()\r\n\r\n for i in range( len(Purpose_list) ):\r\n purpose_name = Purpose_list[i] \r\n\r\n self.style.configure( f\"{purpose_name}_bt.TButton\", \r\n anchor = \"center\", \r\n font = ( \"Helvetica\", 8 ),\r\n background = \"green\",\r\n foreground = \"black\" \r\n )\r\n \r\n self.Purpose_Buttons.append(None) \r\n self.Purpose_Buttons[i] = tk.ttk.Button( self.top, \r\n text = f\"{purpose_name} Computers\",\r\n command = lambda name_purpose = purpose_name :self.command_purpose_computers(name_purpose), \r\n style = f\"{purpose_name}_bt.TButton\" \r\n )\r\n self.Purpose_Buttons[i].place( relx = 0.5 + plus_relx, rely = 0.735 + plus_rely,\r\n relwidth = 0.086, relheight = 0.04 )\r\n plus_relx += 0.15\r\n if plus_relx == 0.3:\r\n plus_rely += 0.17\r\n plus_relx = 0.15\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 #-------------------------Log out----------------------------\r\n image_tempo = Image.open( f\"images/icons/sign_out.png\" )\r\n image_tempo = image_tempo.resize( (25,25), Image.ANTIALIAS )\r\n \r\n self.image_sign_out = ImageTk.PhotoImage( image_tempo)\r\n\r\n self.sign_out_button = tk.Button( self.top, text = \"Sign out\", \r\n image = self.image_sign_out, command = self.log_out, compound = \"left\")\r\n\r\n self.sign_out_button.place( relx = 0.870, rely = 0.15, relwidth = 0.12, relheight = 0.05)\r\n\r\n\r\n #-----------------------------------------------------------\r\n\r\n\r\n #-------------------------Settings Button----------------------------\r\n \r\n image_tempo = Image.open( f\"images/icons/settings.png\" )\r\n image_tempo = image_tempo.resize( (25,25), Image.ANTIALIAS )\r\n \r\n self.image_settings = ImageTk.PhotoImage( image_tempo)\r\n\r\n self.settings_button = tk.Button( self.top, text = \"Settings\", \r\n image = self.image_settings, command = self.command_Settings, compound = \"left\")\r\n\r\n self.settings_button.place( relx = 0.870, rely = 0.095, relwidth = 0.12, relheight = 0.05)\r\n\r\n #------------------------------------------------------------------------------------\r\n\r\n\r\n #-----------------------Email Section-----------------------------------------------------\r\n df_emails = pd.read_excel(\"csv_files/emails.xlsx\")\r\n df_emails_user = df_emails[ (df_emails[\"for_username\"] == self.customer_username) & (df_emails[\"Status\"] == \"unread\" ) ]\r\n unread_mails_n = len(df_emails_user)\r\n if len(df_emails_user) == 0:\r\n image_tempo = Image.open( f\"images/icons/closed_mailbox.png\" )\r\n image_tempo = image_tempo.resize( (70,35), Image.ANTIALIAS )\r\n self.email_pic = ImageTk.PhotoImage( image_tempo )\r\n \r\n email_button = tk.Button(self.top, \r\n command = self.command_email,\r\n text = \"\", image = self.email_pic,\r\n compound = \"bottom\")\r\n email_button.place(relx = 0.71, rely= 0.095, relwidth= 0.07, relheight=0.1)\r\n else:\r\n image_tempo = Image.open( f\"images/icons/open_mailbox.png\" )\r\n image_tempo = image_tempo.resize( (70,35), Image.ANTIALIAS )\r\n self.email_pic = ImageTk.PhotoImage( image_tempo )\r\n \r\n mail_ = \"mail\" if unread_mails_n == 1 else \"mails\"\r\n email_button = tk.Button(self.top, \r\n command = self.command_email,\r\n text = f\"{unread_mails_n} new {mail_}\", foreground = \"red\",\r\n image = self.email_pic, compound = \"bottom\")\r\n email_button.place(relx = 0.71, rely= 0.095, relwidth= 0.07, relheight=0.1)\r\n\r\n #----------------------------------------------------------------------------------------------\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n def log_out(self, event=None):\r\n if askyesno(\"Log out\", f\"{self.customer_name}, are you sure you want to log out?\"):\r\n self.top.destroy()\r\n home.HomePage() \r\n\r\n \r\n def command_Settings(self):\r\n self.top.destroy()\r\n setting_account.setting_account(customer_name = self.customer_name , \r\n customer_Id = self.customer_Id, customer_username = self.customer_username )\r\n \r\n\r\n #------------ Commands for the 3 systems chosen by the manager--------------\r\n def command_button_system(self, system_name):\r\n system_selected = system_name\r\n\r\n if system_selected == \"laptops\": \r\n self.top.destroy() \r\n laptops_page.laptops_page(customer_name= self.customer_name, \r\n customer_Id = self.customer_Id, customer_username = self.customer_username)\r\n elif system_selected == \"mainframes\":\r\n self.top.destroy()\r\n mainframes_page.mainframes_page( customer_name= self.customer_name, \r\n customer_Id = self.customer_Id, customer_username = self.customer_username)\r\n elif system_selected == \"workstations\":\r\n self.top.destroy()\r\n workstations_page.workstations_page(customer_name = self.customer_name, \r\n customer_username = self.customer_username, customer_Id = self.customer_Id)\r\n elif system_selected == \"servers\":\r\n self.top.destroy()\r\n servers_page.servers_page(customer_name = self.customer_name, \r\n customer_username = self.customer_username, customer_Id = self.customer_Id)\r\n elif system_selected == \"desktops\":\r\n self.top.destroy()\r\n desktops_page.desktops_page(customer_name = self.customer_name, \r\n customer_username = self.customer_username, customer_Id = self.customer_Id)\r\n\r\n #-------------------------------------------------------------------------\r\n\r\n\r\n\r\n #----------------- Commands for the most popular computers---------\r\n \r\n def command_computers(self, computer_name, computer_type):\r\n self.top.destroy()\r\n generalized_item.generalized_item( coming_from = \"Main_Page\", \r\n item_name = computer_name, customer_name = self.customer_name, \r\n customer_Id = self.customer_Id, customer_username = self.customer_username)\r\n \r\n #-------------------------------------------------------------------\r\n\r\n \r\n #-------------Commands for the OS: Windows, Mac, Linux-----------\r\n def command_OS(self, OS_name_):\r\n self.top.destroy()\r\n\r\n if OS_name_ == \"Windows\":\r\n OS_computer_page.OS_computers_page(OS_name = \"Windows\", \r\n customer_name = self.customer_name, customer_Id = self.customer_Id, \r\n customer_username = self.customer_username)\r\n \r\n elif OS_name_ == \"Mac\":\r\n OS_computer_page.OS_computers_page(OS_name = \"Mac\", \r\n customer_name = self.customer_name, customer_Id = self.customer_Id, \r\n customer_username = self.customer_username)\r\n \r\n elif OS_name_ == \"Linux\":\r\n OS_computer_page.OS_computers_page(OS_name = \"Linux\",\r\n customer_name = self.customer_name, customer_Id = self.customer_Id, \r\n customer_username = self.customer_username)\r\n \r\n #------------------------------------------------------------------\r\n\r\n #-----------------Commands for architectures: Intel and Arm--------\r\n def command_arch(self, arch_name_):\r\n self.top.destroy()\r\n if arch_name_ == \"Intel\":\r\n Arch_computer_page.Arch_computers_page(Arch_name = \"Intel\",\r\n customer_name = self.customer_name, customer_Id = self.customer_Id, \r\n customer_username = self.customer_username)\r\n elif arch_name_ == \"AMD Ryzen\":\r\n Arch_computer_page.Arch_computers_page(Arch_name = \"AMD Ryzen\",\r\n customer_name = self.customer_name, customer_Id = self.customer_Id, \r\n customer_username = self.customer_username)\r\n \r\n #------------------------------------------------------------------ \r\n\r\n\r\n #-----------------Command for Computer Parts-----------------\r\n def command_computer_parts(self):\r\n self.top.destroy()\r\n computer_parts_page.computer_parts_page( customer_name = self.customer_name,\r\n customer_Id = self.customer_Id, customer_username = self.customer_username)\r\n \r\n #---------------------------------------------------------------\r\n\r\n #--------------------Command Main Purpose-----------------------\r\n def command_purpose_computers(self, purpose_name_):\r\n self.top.destroy()\r\n if purpose_name_ == \"Gaming\":\r\n purpose_computer_page.purpose_computers_page( purpose_name = \"Gaming\", \r\n customer_name = self.customer_name, customer_username = self.customer_username, \r\n customer_Id = self.customer_Id) \r\n elif purpose_name_ == \"Business\":\r\n purpose_computer_page.purpose_computers_page( purpose_name = \"Business\", \r\n customer_name = self.customer_name, customer_username = self.customer_username, \r\n customer_Id = self.customer_Id)\r\n elif purpose_name_ == \"Scientific\":\r\n purpose_computer_page.purpose_computers_page( purpose_name = \"Scientific\", \r\n customer_name = self.customer_name, customer_username = self.customer_username, \r\n customer_Id = self.customer_Id)\r\n #---------------------------------------------------------------\r\n\r\n #----------------Check out Command-----------------------------------\r\n def command_checkout(self):\r\n df2 = pd.read_excel( \"csv_files/registered_customers.xlsx\" )\r\n\r\n df_user = df2[ df2['Username'] == self.customer_username]\r\n\r\n if df_user['Credit card account'].iloc[-1] == 'empty':\r\n tk.messagebox.showerror( \"Error\", \r\n \"There is no credit card linked to your account.\\n\" + \r\n \"A credit card account is necessary for making a purchase\" )\r\n elif float(df_user['Balance'].iloc[-1] ) == 0.00:\r\n tk.messagebox.showerror(\"Error\",\r\n \"Your current balance is $ 0.00\\n\" + \r\n \"Go to Settings to provide funds to your account\")\r\n elif df_user['Status'].iloc[-1] != 'active':\r\n tk.messagebox.showerror( \"Error\", \r\n \"You are suspended and cannot complete any check out orders.\" )\r\n else:\r\n self.top.destroy()\r\n check_out.check_out(coming_from = \"Main_Page2\", item_name = None, \r\n customer_name = self.customer_name, \r\n customer_Id = self.customer_Id, customer_username = self.customer_username) \r\n \r\n\r\n #--------------------------------------------------------------------\r\n\r\n\r\n #---------------------Email Section--------------------------------------\r\n def command_email(self):\r\n self.top.destroy()\r\n emails_page.emails_page( customer_name = self.customer_name,\r\n customer_Id = self.customer_Id, customer_username = self.customer_username)\r\n #-------------------------------------------------------------------------\r\n\r\n\r\n #------------Manager deciding what system should be on the homepage-------\r\n def manager_system_inputs(self):\r\n df = pd.read_excel( \"csv_files/suggested_systems.xlsx\" )\r\n System1 = str(df.iloc[0,0])\r\n System2 = str(df.iloc[1,0])\r\n System3 = str(df.iloc[2,0])\r\n return System1, System2, System3 \r\n\r\n #-------------------------------------------------------------------------- \r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"customer_page.py","file_name":"customer_page.py","file_ext":"py","file_size_in_byte":29366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"122410850","text":"from django.shortcuts import render, render_to_response\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.template.context_processors import csrf\nfrom django.contrib.auth.decorators import login_required\nfrom userprofile.forms import UserProfileForm\n\n\n# Create your views here.\n@login_required\ndef user_profile(request):\n args = {}\n if request.method == 'POST':\n form = UserProfileForm(request.POST, instance=request.user.profile)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect('/accounts/loggedin')\n else:\n user = request.user\n profile = user.profile\n form = UserProfileForm(instance=profile)\n\n args.update(csrf(request))\n args['form'] = form\n return render_to_response('body/profile.html', args)","sub_path":"userprofile/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"286142242","text":"# Copyright 2021\n# Apache 2.0\n\nimport torch\nimport torch.nn as nn\nfrom .L2 import L2\nfrom .CrossEntropy import CrossEntropy\nfrom .LFMMIOnly import ChainLoss as LFMMI\nfrom .InfoNCEOnly import InfoNCELoss as InfoNCE\nfrom .EnergyObjective import EnergyLoss\nfrom .InfoNCE2pass import InfoNCELoss as InfoNCE2pass\n\n\nOBJECTIVES = {\n 'CrossEntropy': CrossEntropy,\n 'LFMMIOnly': LFMMI,\n 'Energy': EnergyLoss,\n 'InfoNCE': InfoNCE,\n 'InfoNCE2pass': InfoNCE2pass,\n 'L2': L2,\n}\n\n\nclass MultitaskLoss(nn.Module):\n @staticmethod\n def add_args(parser):\n parser.add_argument('--multitask-losses', type=str, required=True,\n default=\"[('LFMMIOnly', 1.0, 0), ('L2', 0.0001, 0)]\", \n )\n losses_args, extra = parser.parse_known_args()\n for l in eval(losses_args.multitask_losses):\n OBJECTIVES[l[0]].add_args(parser)\n\n @classmethod\n def build_objective(cls, conf):\n losses = {}\n for loss in eval(conf['multitask_losses']): \n name, weight, branch = loss[0], loss[1], loss[2]\n loss_class = OBJECTIVES[name].build_objective(conf)\n losses[name] = {'class': loss_class, 'weight': weight, 'branch': branch} \n return MultitaskLoss(losses)\n\n @classmethod\n def add_state_dict(cls, s1, s2, fraction, iteration=None):\n new_losses = {} \n for name, loss in s1.items():\n state_dict_class = OBJECTIVES[name]\n new_losses[name] = state_dict_class.add_state_dict(\n loss, s2[name], fraction, iteration=iteration\n )\n return new_losses\n \n def __init__(self, losses):\n super(MultitaskLoss, self).__init__() \n self.losses = nn.ModuleDict({l: losses[l]['class'] for l in losses})\n self.weights, self.branches = {}, {}\n max_branch = 0\n for l, v in losses.items():\n self.weights[l], self.branches[l] = v['weight'], v['branch']\n max_branch = v['branch'] if v['branch'] > max_branch else max_branch\n \n # The branches are 0 indexed\n self.num_branches = 1 + max_branch\n \n def forward(self, model, sample, precomputed=None):\n if precomputed is None:\n x = model(sample)\n else:\n x = precomputed\n if len(x) < self.num_branches:\n raise ValueError('The number of model branches does not match the '\n ' number of branches used in the multitask loss')\n \n # See which objfs to use \n objf_names = sample.metadata.get('objf_names', None)\n if objf_names is None:\n objf_names = self.losses.keys() \n losses = []\n for n in objf_names:\n loss = self.losses[n]\n weight, branch = self.weights[n], self.branches[n]\n if weight > 0:\n loss_value, _ = loss(model, sample, precomputed=x[branch])\n print(f'{n}: {loss_value.data.item()}', end=' ') \n losses.append(weight * loss_value)\n return sum(losses), None\n\n def state_dict(self):\n return { n: v.state_dict() for n, v in self.losses.items()}\n \n def load_state_dict(self, state_dict):\n for n, v in state_dict.items():\n self.losses[n].load_state_dict(v)\n \n def decorrupt(self, *args, **kwargs):\n for n, v in self.losses.items():\n if hasattr(v, 'decorrupt'):\n return v.decorrupt(*args, **kwargs)\n raise RuntimeError(\"No objective function was capable of decorruption\")\n\n def generate_from_buffer(self):\n for n, v in self.losses.items():\n if hasattr(v, 'generate_from_buffer'):\n return v.generate_from_buffer()\n raise RuntimeError(\"No objective function was capable of generating \"\n \"from a buffer\")\n","sub_path":"nnet_pytorch/objectives/Multitask.py","file_name":"Multitask.py","file_ext":"py","file_size_in_byte":3815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"123564984","text":"from django.views import View\nfrom django.shortcuts import redirect, render\nfrom chit_app.forms import *\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.models import User\n\nclass LoginView(View):\n def get(self, request):\n if request.user.is_authenticated:\n return redirect('chit_app:chitlist')\n form = LoginForm()\n return render(request = request, template_name='login.html', context={'form': form})\n\n def post(self, request):\n form = LoginForm(request.POST)\n if form.is_valid():\n user = authenticate(request = request,\n username = form.cleaned_data['username'],\n password = form.cleaned_data['password'])\n if user is not None:\n login(request, user)\n return redirect('chit_app:chitlist')\n else:\n return redirect('chit_app:login')\n\ndef Logout(request):\n logout(request)\n return redirect('chit_app:firstpage')\n\nclass SignUp(View):\n def get(self, request):\n form = SignUpForm()\n return render(request=request, template_name='signup.html', context={'form':form})\n\n def post(self, request):\n form = SignUpForm(request.POST)\n if form.is_valid():\n User.objects.create_user(**form.cleaned_data)\n user = authenticate(request,\n username = form.cleaned_data['username'],\n password = form.cleaned_data['password'])\n if user is not None:\n login(request, user)\n return redirect('chit_app:chitlist')\n else:\n return redirect('chit_app:firstpage')","sub_path":"chit_app/views/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"63172851","text":"import os\n\nclient_filename = \"clients.txt\"\ntransaction_filename = \"transactions.txt\"\n\ndef add_client(client_name):\n try:\n with open(client_filename, 'a') as fi:\n fi.write(str(client_name) + '\\n')\n print('Client added: ' + client_name)\n\n except:\n print('Error: Client not added')\n\ndef add_transaction(debtor, creditor, amount):\n dca = str(debtor) + \", \" + str(creditor) + \", \" + str(amount) + \"\\n\"\n with open(\"transactions.txt\", \"a\") as f:\n \tf.write(dca)\n return \":)\"\n \n\ndef get_clients():\n return(list(map(lambda x:x.strip(), open(client_filename,'r').readlines())))\n\ndef get_transactions():\n with open(\"transactions.txt\", \"r\") as f:\n trans = list(map(lambda x: x.strip().split(), f.readlines()))\n return trans\n\n","sub_path":"file_manager.py","file_name":"file_manager.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"632015022","text":"import cProfile\nimport sys\nfrom PySide.QtCore import *\nfrom PySide.QtGui import *\nimport icons\nfrom datatree import *\nfrom dictionarytree import *\nfrom database import *\nfrom actions import *\nfrom apimodules import * \nfrom help import *\nfrom presets import *\nfrom timer import *\n\nclass MainWindow(QMainWindow):\n \n def __init__(self,central=None):\n super(MainWindow,self).__init__()\n \n self.setWindowTitle(\"Facepager 3.3\") \n self.setWindowIcon(QIcon(\":/icons/icon_facepager.png\")) \n self.setMinimumSize(900,700)\n self.move(QDesktopWidget().availableGeometry().center() - self.frameGeometry().center()-QPoint(0,100))\n #self.setStyleSheet(\"* {font-size:18px;}\")\n #self.deleteSettings()\n self.readSettings() \n self.createActions()\n self.createUI()\n self.createDB()\n \n self.updateUI()\n \n def createDB(self): \n self.database = Database(self)\n lastpath = self.settings.value(\"lastpath\")\n if lastpath and os.path.isfile(lastpath):\n self.database.connect(self.settings.value(\"lastpath\")) \n \n self.tree.loadData(self.database)\n self.actions.actionShowColumns.trigger()\n \n\n def createActions(self):\n self.actions=Actions(self) \n\n \n def createUI(self):\n \n self.helpwindow=HelpWindow(self)\n self.presetWindow=PresetWindow(self)\n self.timerWindow=TimerWindow(self)\n \n self.timerWindow.timerstarted.connect(self.timerStarted)\n self.timerWindow.timerstopped.connect(self.timerStopped)\n self.timerWindow.timercountdown.connect(self.timerCountdown)\n self.timerWindow.timerfired.connect(self.timerFired)\n self.timerStatus = QLabel(\"Timer stopped \")\n self.statusBar().addPermanentWidget(self.timerStatus) \n self.toolbar=Toolbar(parent=self,mainWindow=self)\n self.addToolBar(Qt.TopToolBarArea,self.toolbar) \n \n self.selectionStatus = QLabel(\"0 node(s) selected \")\n self.statusBar().addPermanentWidget(self.selectionStatus) \n self.statusBar().showMessage('No database connection')\n self.statusBar().setSizeGripEnabled(False) \n \n #dummy widget to contain the layout manager\n #self.mainWidget=QWidget(self) \n self.mainWidget=QSplitter(self)\n self.mainWidget.setOrientation(Qt.Vertical) \n self.setCentralWidget(self.mainWidget) \n \n #top widget\n topWidget=QWidget(self)\n self.mainWidget.addWidget(topWidget)\n\n bottomWidget=QWidget(self)\n self.mainWidget.addWidget(bottomWidget)\n self.mainWidget.setStretchFactor(0, 1);\n \n #mainLayout=QVBoxLayout()\n #self.mainWidget.setLayout(mainLayout) \n \n \n dataLayout=QHBoxLayout()\n topWidget.setLayout(dataLayout)\n dataSplitter = QSplitter(self)\n dataLayout.addWidget(dataSplitter)\n \n requestLayout=QHBoxLayout()\n bottomWidget.setLayout(requestLayout)\n\n \n #tree \n self.tree=DataTree(self.mainWidget,self)\n dataSplitter.addWidget(self.tree)\n dataSplitter.setStretchFactor(0, 1);\n\n \n #right sidebar\n detailWidget=QWidget()\n detailLayout=QVBoxLayout()\n detailLayout.setContentsMargins(11,0,0,11)\n detailWidget.setLayout(detailLayout)\n dataSplitter.addWidget(detailWidget) \n dataSplitter.setStretchFactor(1, 0);\n \n self.detailTree=DictionaryTree(self.mainWidget,self)\n detailLayout.addWidget(self.detailTree)\n\n buttonLayout=QHBoxLayout()\n detailLayout.addLayout(buttonLayout)\n \n button=QPushButton(\"Add Column\")\n button.clicked.connect(self.actions.actionAddColumn.trigger)\n buttonLayout.addWidget(button)\n\n button=QPushButton(\"Unpack list\")\n button.clicked.connect(self.actions.actionUnpack.trigger)\n buttonLayout.addWidget(button) \n \n #requests\n actionlayout=QVBoxLayout()\n requestLayout.addLayout(actionlayout,1)\n \n self.RequestTabs=QTabWidget()\n actionlayout.addWidget(self.RequestTabs) \n loadTabs(self)\n \n \n #fetch data \n f=QFont()\n f.setPointSize(11)\n\n \n fetchdata=QHBoxLayout()\n fetchdata.setContentsMargins(10,0,10,0)\n actionlayout.addLayout(fetchdata) \n #fetchdata.addStretch(1) \n \n #-Level\n self.levelEdit=QSpinBox(self.mainWidget)\n self.levelEdit.setMinimum(1)\n self.levelEdit.setFont(f)\n self.levelEdit.setMinimumHeight(35)\n label=QLabel(\"For all selected nodes and \\ntheir children of level\")\n #label.setFont(f) \n \n #label.setWordWrap(True)\n #label.setMaximumWidth(100)\n fetchdata.addWidget(label,0)\n fetchdata.addWidget(self.levelEdit,0)\n \n #-button\n button=QPushButton(QIcon(\":/icons/fetch.png\"),\"Fetch Data\", self.mainWidget)\n button.setMinimumSize(QSize(120,40))\n button.setIconSize(QSize(32,32))\n button.clicked.connect(self.actions.actionQuery.trigger)\n button.setFont(f)\n fetchdata.addWidget(button,1)\n \n #-timer button\n button=QToolButton(self.mainWidget)\n button.setIcon(QIcon(\":/icons/timer.png\"))\n button.setMinimumSize(QSize(40,40))\n button.setIconSize(QSize(25,25))\n button.clicked.connect(self.actions.actionTimer.trigger)\n fetchdata.addWidget(button,1)\n \n #Status\n statusLayout=QVBoxLayout() \n requestLayout.addLayout(statusLayout,2)\n\n detailGroup=QGroupBox(\"Status Log\")\n groupLayout=QVBoxLayout()\n detailGroup.setLayout(groupLayout)\n statusLayout.addWidget(detailGroup,1)\n \n self.loglist=QTextEdit()\n self.loglist.setLineWrapMode(QTextEdit.NoWrap)\n self.loglist.setWordWrapMode(QTextOption.NoWrap)\n self.loglist.acceptRichText=False\n self.loglist.clear()\n groupLayout.addWidget(self.loglist)\n\n #fields\n detailGroup=QGroupBox(\"Custom Table Columns (one key per line)\")\n requestLayout.addWidget(detailGroup)\n groupLayout=QVBoxLayout()\n detailGroup.setLayout(groupLayout)\n \n self.fieldList=QTextEdit() \n self.fieldList.setLineWrapMode(QTextEdit.NoWrap)\n self.fieldList.setWordWrapMode(QTextOption.NoWrap)\n self.fieldList.acceptRichText=False\n self.fieldList.clear()\n self.fieldList.append('name')\n self.fieldList.append('message')\n self.fieldList.append('type')\n self.fieldList.append('metadata.type')\n self.fieldList.append('talking_about_count')\n self.fieldList.append('likes') \n self.fieldList.append('likes.count') \n self.fieldList.append('shares.count')\n self.fieldList.append('comments.count')\n self.fieldList.append('created_time')\n self.fieldList.append('updated_time')\n \n self.fieldList.setPlainText(self.settings.value('columns',self.fieldList.toPlainText())) \n \n groupLayout.addWidget(self.fieldList) \n \n button=QPushButton(\"Apply Column Setup\")\n button.clicked.connect(self.actions.actionShowColumns.trigger)\n groupLayout.addWidget(button) \n \n def updateUI(self):\n #disable buttons that do not work without an opened database \n self.actions.databaseActions.setEnabled(self.database.connected)\n \n if self.database.connected:\n self.statusBar().showMessage(self.database.filename)\n else:\n self.statusBar().showMessage('No database connection') \n \n @Slot() \n def timerStarted(self,time):\n self.timerStatus.setStyleSheet(\"QLabel {color:red;}\")\n self.timerStatus.setText(\"Timer will be fired at \"+time.toString(\"d MMM yyyy - hh:mm\")+\" \")\n\n @Slot()\n def timerStopped(self):\n self.timerStatus.setStyleSheet(\"QLabel {color:black;}\")\n self.timerStatus.setText(\"Timer stopped \")\n\n @Slot()\n def timerCountdown(self,countdown):\n self.timerStatus.setStyleSheet(\"QLabel {color:red;}\")\n self.timerStatus.setText(\"Timer will be fired in \"+str(countdown)+ \" seconds \")\n \n @Slot()\n def timerFired(self,data): \n self.timerStatus.setText(\"Timer fired \")\n self.timerStatus.setStyleSheet(\"QLabel {color:red;}\")\n self.actions.queryNodes(data.get('indexes',[]),data.get('module',None),data.get('options',{}).copy() )\n \n \n \n def writeSettings(self):\n QCoreApplication.setOrganizationName(\"Keyling\")\n QCoreApplication.setApplicationName(\"Facepager\")\n\n self.settings = QSettings() \n self.settings.beginGroup(\"MainWindow\")\n self.settings.setValue(\"size\", self.size())\n self.settings.setValue(\"pos\", self.pos()) \n self.settings.setValue(\"version\",\"3.0\")\n self.settings.endGroup()\n \n self.settings.setValue('columns',self.fieldList.toPlainText())\n \n for i in range(self.RequestTabs.count()):\n self.RequestTabs.widget(i).saveSettings()\n \n def readSettings(self):\n QSettings.setDefaultFormat(QSettings.IniFormat)\n QCoreApplication.setOrganizationName(\"Keyling\")\n QCoreApplication.setApplicationName(\"Facepager\")\n self.settings = QSettings() \n self.settings.beginGroup(\"MainWindow\")\n \n #self.resize(self.settings.value(\"size\", QSize(800, 800)))\n #self.move(self.settings.value(\"pos\", QPoint(200, 10)))\n self.settings.endGroup() \n \n def deleteSettings(self): \n self.settings = QSettings(\"Keyling\", \"Facepager\")\n self.settings.beginGroup(\"MainWindow\")\n self.settings.remove(\"\")\n self.settings.endGroup()\n self.settings.remove(\"lastpath\")\n\n def closeEvent(self, event=QCloseEvent()):\n if self.close():\n self.writeSettings()\n event.accept()\n else:\n event.ignore()\n \n @Slot(str) \n def logmessage(self,message):\n self.loglist.append(str(datetime.now())+\" \"+message)\n QApplication.processEvents() \n\n def showProgress(self,current = None,maximum = None,message = None): \n if not hasattr(self, 'progresswindow') or (self.progresswindow is None):\n if message == None: message = \"\"\n self.progresswindow = QProgressDialog(message, \"Abort\", 0, 0,self)\n self.progresswindow.setWindowModality(Qt.WindowModal)\n self.progresswindow.setMinimumDuration(0)\n self.progresswindow.forceShow()\n \n if maximum != None: self.progresswindow.setMaximum(maximum) \n if current != None: self.progresswindow.setValue(current)\n if message != None: self.progresswindow.setLabelText(message)\n QApplication.processEvents()\n \n \n def progressCanceled(self):\n return (not self.progresswindow) or (self.progresswindow.wasCanceled()) \n \n def hideProgress(self):\n self.progresswindow.cancel()\n self.progresswindow = None\n \n \n \nclass Toolbar(QToolBar):\n '''\n Initialize the main toolbar for the facepager - that provides the central interface and functions.\n '''\n def __init__(self,parent=None,mainWindow=None):\n super(Toolbar,self).__init__(parent)\n self.mainWindow=mainWindow\n self.setToolButtonStyle(Qt.ToolButtonTextBesideIcon);\n self.setIconSize(QSize(24,24))\n \n self.addActions(self.mainWindow.actions.basicActions.actions()) \n self.addSeparator()\n self.addActions(self.mainWindow.actions.databaseActions.actions())\n \n self.addSeparator()\n self.addAction(self.mainWindow.actions.actionExpandAll) \n self.addAction(self.mainWindow.actions.actionCollapseAll)\n self.addAction(self.mainWindow.actions.actionLoadPreset)\n self.addAction(self.mainWindow.actions.actionHelp)\n \n\n \ndef startMain():\n app = QApplication(sys.argv)\n\n main=MainWindow() \n main.show()\n \n sys.exit(app.exec_()) \n\n \nif __name__ == \"__main__\":\n #cProfile.run('startMain()')\n startMain()\n\n","sub_path":"src/Facepager.py","file_name":"Facepager.py","file_ext":"py","file_size_in_byte":12895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"582141430","text":"#!/usr/bin/env python\n\nfrom os.path import join, realpath\nimport sys;\n\n\nsys.path.insert(0, realpath(join(__file__, \"../../\")))\nfrom hummingsim.backtest.bittrex_order_book_loader import BittrexOrderBookLoader\nimport logging\n\nimport pandas as pd\nfrom typing import (\n List,\n Optional)\nimport unittest\n\nimport hummingsim\nfrom hummingsim.backtest.huobi_order_book_loader import HuobiOrderBookLoader\nfrom wings.clock import (\n Clock,\n ClockMode\n)\nfrom wings.events import (\n OrderBookTradeEvent,\n OrderBookEvent,\n)\nfrom wings.order_book import OrderBook\nfrom wings.order_book_message import (\n OrderBookMessage,\n OrderBookMessageType\n)\n\nfrom test import OrderBookUtils\nfrom wings.event_logger import EventLogger\n\n\nclass BittrexOrderBookLoaderUnitTest(unittest.TestCase):\n start_time: float = pd.Timestamp(\"2018-12-11\", tz=\"UTC\").timestamp()\n end_time: float = pd.Timestamp(\"2018-12-12\", tz=\"UTC\").timestamp()\n snapshot_time: float = pd.Timestamp(\"2018-12-11 01:00:00.444000\", tz=\"UTC\").timestamp()\n\n def setUp(self):\n self.clock: Clock = Clock(ClockMode.BACKTEST, start_time=self.start_time, end_time=self.end_time)\n self.order_book_loader: BittrexOrderBookLoader = BittrexOrderBookLoader(\"USDT-BTC\", \"BTC\", \"USDT\")\n self.order_book: OrderBook = self.order_book_loader.order_book\n self.clock.add_iterator(self.order_book_loader)\n\n def tearDown(self):\n self.order_book_loader.close()\n\n def test_order_book_snapshots(self):\n self.clock.backtest_til(int(self.snapshot_time))\n pre_bids, pre_asks = self.order_book.snapshot\n self.clock.backtest_til(int(self.snapshot_time) + 1)\n post_bids, post_asks = self.order_book.snapshot\n\n matching, total = OrderBookUtils.compare_books(pre_bids, post_bids)\n self.assertLess(total - matching, 50)\n\n matching, total = OrderBookUtils.compare_books(pre_asks, post_asks)\n self.assertLess(total - matching, 50)\n\n def test_order_book_diffs(self):\n \"\"\"\n test multiple timeframe each right after hourly snapshots\n \"\"\"\n\n def _test_order_book_diffs(start: int, end: int):\n \"\"\"\n Test 1: last non-zero amount (removed) order message appears correctly in the end snapshot.\n\n Test 2: last zero amount order message are valid if both start and end snapshot do not have it,\n or the end snapshot shows that it is removed.\n\n \"\"\"\n bid_message: Optional[OrderBookMessage] = None\n ask_message: Optional[OrderBookMessage] = None\n last_bid_diffs: Optional[pd.DataFrame] = pd.DataFrame()\n last_ask_diffs: Optional[pd.DataFrame] = pd.DataFrame()\n\n self.clock.backtest_til(start)\n pre_bids, pre_asks = self.order_book.snapshot\n self.clock.backtest_til(end)\n post_bids, post_asks = self.order_book.snapshot\n\n compare_bids: pd.DataFrame = OrderBookUtils.get_compare_df(pre_bids, post_bids, n_rows=800, diffs_only=True)\n compare_asks: pd.DataFrame = OrderBookUtils.get_compare_df(pre_asks, post_asks, n_rows=800, diffs_only=True)\n compare_bids.fillna(value=0.0, inplace=True)\n compare_asks.fillna(value=0.0, inplace=True)\n\n bid_messages: List[OrderBookMessage] = [\n message for message in self.order_book_loader.fetch_order_book_messages(start, end)\n if message.type is OrderBookMessageType.DIFF\n and len(message.content[\"bids\"]) > 0\n ]\n ask_messages: List[OrderBookMessage] = [\n message for message in self.order_book_loader.fetch_order_book_messages(start, end)\n if message.type is OrderBookMessageType.DIFF\n and len(message.content[\"asks\"]) > 0\n ]\n\n if len(bid_messages) > 0:\n bid_message = bid_messages[-1]\n if len(ask_messages) > 0:\n ask_message = ask_messages[-1]\n\n if bid_message and bid_message.timestamp > start:\n last_bid_diffs: pd.DataFrame = pd.DataFrame.from_records(\n data=[[float(row[0]), float(row[1])] for row in bid_message.content[\"bids\"]],\n columns=[\"price\", \"amount\"],\n index=\"price\"\n )\n self.assertGreater(len(compare_bids), 0)\n\n if ask_message and ask_message.timestamp > start:\n last_ask_diffs: pd.DataFrame = pd.DataFrame.from_records(\n data=[[float(row[0]), float(row[1])] for row in ask_message.content[\"asks\"]],\n columns=[\"price\", \"amount\"],\n index=\"price\"\n )\n self.assertGreater(len(compare_asks), 0)\n\n for row in last_bid_diffs.itertuples():\n if row.amount == 0:\n self.assertTrue(\n (row.Index not in pre_bids.price and row.Index not in post_bids.price)\n or row.Index in compare_bids.Index\n )\n continue\n\n self.assertTrue(row.Index in set(post_bids.price))\n self.assertEqual(post_bids.loc[post_bids[\"price\"] == row.Index].amount.values[0], row.amount)\n\n for row in last_ask_diffs.itertuples():\n if row.amount == 0:\n self.assertTrue(\n (row.Index not in pre_asks.price and row.Index not in post_asks.price)\n or row.Index in compare_asks.Index\n )\n continue\n\n self.assertTrue(row.Index in set(post_asks.price))\n self.assertEqual(post_asks.loc[post_asks[\"price\"] == row.Index].amount.values[0], row.amount)\n\n for hour in range(6):\n start: int = int(self.snapshot_time) + hour*60*60\n end: int = start + 60\n _test_order_book_diffs(start, end)\n\n def test_order_book_trades(self):\n start: int = int(self.snapshot_time) + 1\n end: int = int(self.snapshot_time) + 60\n self.clock.backtest_til(start)\n\n event_recorder: EventLogger = EventLogger()\n self.order_book.add_listener(OrderBookEvent.TradeEvent, event_recorder)\n self.clock.backtest_til(end)\n\n trade_messages: List[OrderBookMessage] = [\n message\n for message in self.order_book_loader.fetch_order_book_messages(start, end)\n if message.type is OrderBookMessageType.TRADE\n ]\n\n events: List[OrderBookTradeEvent] = event_recorder.event_log\n self.assertEqual(len(trade_messages), len(events))\n for trade_message, trade_event in zip(trade_messages, events):\n self.assertAlmostEqual(trade_message.timestamp, trade_event.timestamp)\n self.assertAlmostEqual(float(trade_message.content[\"price\"]), trade_event.price)\n self.assertAlmostEqual(float(trade_message.content[\"amount\"]), trade_event.amount)\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO)\n hummingsim.set_data_path(realpath(join(__file__, \"../../data\")))\n unittest.main()\n\n","sub_path":"test/test_bittrex_order_book_loader.py","file_name":"test_bittrex_order_book_loader.py","file_ext":"py","file_size_in_byte":7192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"405366820","text":"import sys\nsys.path.append('.')\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport warnings\nfrom agents import Buyer, Seller\nfrom environments import MarketEnvironment\nimport tensorflow as tf\nfrom info_settings import BlackBoxSetting,FullInformationSetting\nfrom matchers import MyRandomMatcher\nimport gym\nimport time\nimport argparse\nimport scipy.stats as stats\nparser = argparse.ArgumentParser()\nparser.add_argument('--reward_mode', type=int, default=1, help='1:sparse reward; 2:discontinuous reward; 3:linear_peak; 4:squared function; 5:gaussian function; please see section 4.2 in the report for more details' )\nparser.add_argument('--his_len', type=int, default=1, help='history length' )\nparser.add_argument('--noise', type=int, default=0, help='noise' )\nARGS = parser.parse_args()\nnp.random.seed(1)\ntf.set_random_seed(1)\n\n##################### hyper parameters ####################\nHIS_LEN=ARGS.his_len\nNUM_SELLER=1\nNUM_BUYER=1\nNUM_AGENT=2\nMAX_EPISODES = 1\nMAX_EP_STEPS = 5000\nLR_A = 0.0003 # learning rate for actor\nLR_C = 0.0001 # learning rate for critic\nGAMMA = 0.8 # reward discount\naction_bound = 1\nSCALE=100\nREPLACEMENT = [\n dict(name='soft', tau=0.01),\n dict(name='hard', rep_iter_a=600, rep_iter_c=500)\n][0] # you can try different target replacement strategies\nMEMORY_CAPACITY = 100\nBATCH_SIZE = 32\n\nRENDER = False\nOUTPUT_GRAPH = True\nENV_NAME = 'Pendulum-v0'\n\n############################### Actor ####################################\n\n\nclass Actor(object):\n def __init__(self, sess, action_dim, action_bound, learning_rate, replacement,name):\n self.sess = sess\n self.a_dim = action_dim\n self.action_bound = action_bound\n self.lr = learning_rate\n self.replacement = replacement\n self.t_replace_counter = 0\n self.name_=name\n with tf.variable_scope('Actor'):\n # input s, output a\n self.a = self._build_net(S, scope='eval_net', trainable=True)\n\n # input s_, output a, get a_ for critic\n self.a_ = self._build_net(S_, scope='target_net', trainable=False)\n\n self.e_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.name_+'/Actor/eval_net')\n self.t_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.name_+'/Actor/target_net')\n\n if self.replacement['name'] == 'hard':\n self.t_replace_counter = 0\n self.hard_replace = [tf.assign(t, e) for t, e in zip(self.t_params, self.e_params)]\n else:\n self.soft_replace = [tf.assign(t, (1 - self.replacement['tau']) * t + self.replacement['tau'] * e)\n for t, e in zip(self.t_params, self.e_params)]\n\n def _build_net(self, s, scope, trainable):\n with tf.variable_scope(scope):\n init_w = tf.random_normal_initializer(0.001, 0.05)\n init_b = tf.constant_initializer(0.001)\n net = tf.layers.dense(s, 10, activation=tf.nn.elu,\n kernel_initializer=init_w, bias_initializer=init_b, name='l1',\n trainable=trainable)\n with tf.variable_scope('a'):\n actions = tf.layers.dense(net, self.a_dim, activation=tf.nn.elu, kernel_initializer=init_w,\n bias_initializer=init_b, name='a', trainable=trainable)\n # actions=actions/SCALE\n scaled_a = tf.multiply(actions, self.action_bound, name='scaled_a') # Scale output to -action_bound to action_bound\n return scaled_a\n\n def learn(self, s): # batch update\n _, policy_grad = self.sess.run([self.train_op, self.policy_grads], feed_dict={S: s})\n # print(\"actor policy_grad\", policy_grad)\n if self.replacement['name'] == 'soft':\n self.sess.run(self.soft_replace)\n else:\n if self.t_replace_counter % self.replacement['rep_iter_a'] == 0:\n self.sess.run(self.hard_replace)\n self.t_replace_counter += 1\n\n def choose_action(self, s):\n s = s[np.newaxis, :] # single state\n return self.sess.run(self.a, feed_dict={S: s})[0] # single action\n\n def add_grad_to_graph(self, a_grads):\n with tf.variable_scope('policy_grads'):\n # ys = policy;\n # xs = policy's parameters;\n # a_grads = the gradients of the policy to get more Q\n # tf.gradients will calculate dys/dxs with a initial gradients for ys, so this is dq/da * da/dparams\n self.policy_grads = tf.gradients(ys=self.a, xs=self.e_params, grad_ys=a_grads)\n #print(self.a)\n\n #print(a_grads)\n with tf.variable_scope('A_train'):\n opt = tf.train.AdamOptimizer(-self.lr) # (- learning rate) for ascent policy\n \n # self.train_op = opt.apply_gradients(zip(self.policy_grads, self.e_params))\n\n # gvs = zip(self.policy_grads, self.e_params)\n # capped_gvs = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gvs]\n gradients, _ = tf.clip_by_global_norm(self.policy_grads, 1.0)\n self.train_op = opt.apply_gradients(zip(gradients, self.e_params))\n\n############################### Critic ####################################\n\nclass Critic(object):\n def __init__(self, sess, state_dim, action_dim, learning_rate, gamma, replacement, a, a_,name):\n self.sess = sess\n self.s_dim = state_dim\n self.a_dim = action_dim\n self.lr = learning_rate\n self.gamma = gamma\n self.replacement = replacement\n self.name_=name\n self.raw_a=a\n with tf.variable_scope('Critic'):\n # Input (s, a), output q\n self.a = a\n #self.a = tf.stop_gradient(a) # stop critic update flows to actor\n self.q = self._build_net(S, self.a, 'eval_net', trainable=True)\n\n # Input (s_, a_), output q_ for q_target\n self.q_ = self._build_net(S_, a_, 'target_net', trainable=False) # target_q is based on a_ from Actor's target_net\n\n self.e_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.name_+'/Critic/eval_net')\n self.t_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.name_+'/Critic/target_net')\n\n with tf.variable_scope('target_q'):\n self.target_q = R + self.gamma * self.q_\n\n with tf.variable_scope('TD_error'):\n self.loss = tf.reduce_mean(tf.squared_difference(self.target_q, self.q))\n\n with tf.variable_scope('C_train'):\n # self.train_op = tf.train.RMSPropOptimizer(self.lr).minimize(self.loss)\n optimizer = tf.train.AdamOptimizer(self.lr)\n self.gradients, variables = zip(*optimizer.compute_gradients(self.loss))\n # capped_gvs = [(tf.clip_by_value(grad, -10000., 100000.), var) for grad, var in gvs]\n gradients, _ = tf.clip_by_global_norm(self.gradients, 1.0)\n self.train_op = optimizer.apply_gradients(zip(gradients, variables))\n\n with tf.variable_scope('a_grad'):\n self.a_grads = tf.gradients(self.q, self.a)[0] # tensor of gradients of each sample (None, a_dim)\n #print(self.q)\n #print(a)\n #print(self.a_grads)\n if self.replacement['name'] == 'hard':\n self.t_replace_counter = 0\n self.hard_replacement = [tf.assign(t, e) for t, e in zip(self.t_params, self.e_params)]\n else:\n self.soft_replacement = [tf.assign(t, (1 - self.replacement['tau']) * t + self.replacement['tau'] * e)\n for t, e in zip(self.t_params, self.e_params)]\n\n def _build_net(self, s, a, scope, trainable):\n with tf.variable_scope(scope):\n init_w = tf.random_normal_initializer(0., 0.5)\n init_b = tf.constant_initializer(1)\n\n with tf.variable_scope('l1'):\n n_l1 = 10\n w1_s = tf.get_variable('w1_s', [self.s_dim, n_l1], initializer=init_w, trainable=trainable)\n w1_a = tf.get_variable('w1_a', [self.a_dim, n_l1], initializer=init_w, trainable=trainable)\n b1 = tf.get_variable('b1', [1, n_l1], initializer=init_b, trainable=trainable)\n net = tf.nn.elu(tf.matmul(s, w1_s) + tf.matmul(a, w1_a) + b1)\n\n with tf.variable_scope('q'):\n q = tf.layers.dense(net, 1, kernel_initializer=init_w, bias_initializer=init_b, trainable=trainable) # Q(s,a)\n return q\n\n def learn(self, s, a, r, s_):\n print(a.shape)\n self.raw_a =tf.convert_to_tensor(a)\n _,los,q, q_, a_gradd =self.sess.run([self.train_op,self.loss, self.q, self.q_, self.a_grads], feed_dict={S: s, self.a: a, R: r, S_: s_})\n print(\"loss\", los, \"a_grad\", a_gradd, \"r\", r, \"q\", q, \"q_\",q_)\n #print('TTTTTT gradient',gradienttt)\n if self.replacement['name'] == 'soft':\n self.sess.run(self.soft_replacement)\n else:\n if self.t_replace_counter % self.replacement['rep_iter_c'] == 0:\n self.sess.run(self.hard_replacement)\n self.t_replace_counter += 1\n\n\n##################### Memory ####################\n\nclass Memory(object):\n def __init__(self, capacity, dims):\n self.capacity = capacity\n self.data = np.zeros((capacity, dims))\n self.pointer = 0\n\n def store_transition(self, s, a, r, s_):\n transition = np.hstack((s, a, [r], s_))\n index = self.pointer % self.capacity # replace the old memory with new memory\n\n self.data[index, :] = transition\n self.pointer += 1\n def print_transition(self):\n for i in range(self.capacity):\n print(self.data[i,:])\n def sample(self, n):\n assert self.pointer >= self.capacity, 'Memory has not been fulfilled'\n indices = np.random.choice(self.capacity, size=n)\n return self.data[indices, :]\n\ndef format_deal_history(observation):\n '''\n Takes in observation from the agent enviroment and returns a NUM_SELLER * HIS_LEN length numpy array.\n observation example\n {'Seller John': array([115. , 105. , 120. , 95. , 105.36013271, 0. ]),\n 'Seller Nick': array([115. , 105. , 120. , 95. , 105.36013271, 0. ]),\n 'Buyer Alex': array([115. , 105. , 120. , 95. , 105.36013271, 0. ]),\n 'Buyer Kevin': array([115. , 105. , 120. , 95. , 105.36013271, 0. ])}\n '''\n recent_history = []\n for agent in observation.keys()[: NUM_SELLER]:\n recent_history.append(observation[agent][-HIS_LEN:])\n return np.array(recent_history)\n\nalex = Buyer('0', 90/SCALE)\nbuyers = [alex]\nsellers = []\n'''for i in range(1, NUM_BUYER+1):\n buyers.append(Buyer(str(i), 120))\nfor i in range(NUM_BUYER+1, NUM_AGENT):\n sellers.append(Seller(str(i), 120))'''\nnick = Seller('1', 30/SCALE)\nsellers=[nick]\n\n\n# Robustness: 4 market structures.\n# Control: Regular.\n# 10 rounds, 10 buyers and 10 sellers.\n# 3 Variations: (i) Asymmetric buy-side. (ii) Asymmetric sell-side. (iii) Long.\n# (i) 10 rounds, 20 buyers and 10 sellers.\n# (ii) 10 rounds, 10 buyers and 20 sellers.\n# (iii) 50 rounds, 10 buyers and 10 sellers.\n\n# the dratf.pdf have maximum 50 rounds in each episode\nwarnings.simplefilter(\"ignore\")\nenv = MarketEnvironment(sellers=sellers, buyers=buyers, max_steps=50,\n matcher=MyRandomMatcher(), setting=FullInformationSetting)\n#gym.make(ENV_NAME)\n#env = env.unwrapped\n#env.seed(1)\n\nstate_dim = HIS_LEN*(NUM_AGENT) + 1 # extra one for his own valuation price\naction_dim = 1\n\n\n# all placeholder for tf\nwith tf.name_scope('S'):\n S = tf.placeholder(tf.float32, shape=[None, state_dim], name='s')\nwith tf.name_scope('R'):\n R = tf.placeholder(tf.float32, [None, 1], name='r')\nwith tf.name_scope('S_'):\n S_ = tf.placeholder(tf.float32, shape=[None, state_dim], name='s_')\n\n\nsess = tf.Session()\n# Create actor and critic.\n# They are actually connected to each other, details can be seen in tensorboard or in this picture:\nwith tf.variable_scope('0'):\n actor_0 = Actor(sess, action_dim, action_bound, LR_A, REPLACEMENT,name='0')\n critic_0 = Critic(sess, state_dim, action_dim, LR_C, GAMMA, REPLACEMENT, actor_0.a, actor_0.a_,name='0')\n #print(critic_0.a_grads)\n actor_0.add_grad_to_graph(critic_0.a_grads)\n'''with tf.variable_scope('1'):\n actor_1 = Actor(sess, action_dim, action_bound, LR_A, REPLACEMENT,name='1')\n critic_1 = Critic(sess, state_dim, action_dim, LR_C, GAMMA, REPLACEMENT, actor_1.a, actor_1.a_,name='1')\n actor_1.add_grad_to_graph(critic_1.a_grads)'''\n#print(\"jellp\")\nsess.run(tf.global_variables_initializer())\n\nM_0 = Memory(MEMORY_CAPACITY, dims=2 * state_dim + action_dim + 1)\n#M_1 = Memory(MEMORY_CAPACITY, dims=2 * state_dim + action_dim + 1)\nif OUTPUT_GRAPH:\n tf.summary.FileWriter(\"logs/\", sess.graph)\n\nvar = ARGS.noise/SCALE\n#0/SCALE # control exploration\nprice_list_0=[]\nprice_list_1=[]\nprice_list_2=[]\ntime_list=[]\nt=0\nt1 = time.time()\nep_reward=0\nfor i in range(MAX_EPISODES):\n observation = env.reset()\n recent_history=[]\n #for agent in observation.keys()[: NUM_SELLER]:\n #recent_history.append(observation[agent][-HIS_LEN:])\n #for m in range(NUM_AGENT * HIS_LEN):\n #recent_history.append(100*np.random.rand())\n for m in range(HIS_LEN):\n recent_history.append(40/SCALE)\n price_list_0.append(40/SCALE)\n price_list_2.append(40/SCALE)\n time_list.append(40/SCALE)\n t=t+1\n for m in range(HIS_LEN):\n recent_history.append((100-m/2)/SCALE)\n price_list_1.append((100-m/2)/SCALE)\n \n #time_list.append(t)\n #t=t+1\n\n #### TO-DO: might change alex nick\n buyer_s0 = np.array(recent_history + [alex.reservation_price])\n seller_s1 = np.array(recent_history + [nick.reservation_price])\n #for i in range(NUM_SELLER):\n #for j in range(HIS_LEN):\n\n ep_reward_0 = 0\n ep_reward_1 = 0\n\n for j in range(MAX_EP_STEPS):\n\n #if RENDER:\n #env.render()\n\n # Add exploration noise\n a = actor_0.choose_action(buyer_s0)\n print(\"a\",a)\n price_list_2.append(float(a))\n #a=np.random.normal(a, var)\n #print(a)\n a = np.clip(np.random.normal(a,var), -1, 1) \n # a = np.clip(np.random.normal(a,var), 0, 1) # add randomness to action selection for exploration\n print(\"aa\",a)\n step_offers = {}\n step_offers['0']=float(a)\n\n #n = actor_1.choose_action(seller_s1)\n #a=np.random.normal(a, var)\n #print(a)\n #print(n)\n #nn = np.clip(np.random.normal(n, var), nick.reservation_price/SCALE, 1) # add randomness to action selection for exploration\n #print(nn)\n n=0.45\n nn=n\n step_offers['1']=float(nn)\n #print(\"n\",n)\n #print(\"nn\", nn)\n price_list_0.append(float(a))\n price_list_1.append(float(n))\n \n\n time_list.append(t)\n t=t+1\n #alex.reservation_price-np.random.rand()*alex.reservation_price\n\n #####################################################################\n # load data. once the agent succeeded in the previous time step,\n # since the sellers and buyers might quit the markets at anytime, so the state space is actually varying in length\n # to keep the state space a fixed length variable, we decide to\n # increase the offer price to large price 10000 for Sellers and decrease the offer prcie to 0 for Buyers\n # once they are matched\n #\n #0 is agent 1-9 other buyer 10-19 seller\n\n curr_offer = np.zeros((NUM_AGENT,1))\n for buyer in buyers:\n curr_offer[int(buyer.agent_id)] = step_offers[buyer.agent_id]\n for seller in sellers:\n curr_offer[int(seller.agent_id)] = step_offers[seller.agent_id]\n\n '''for buyer in buyers:\n # print(\"buyer\", buyer.agent_id)\n if (buyer.agent_id != '0'):\n step_offers[buyer.agent_id]=buyer.reservation_price+np.random.rand()*buyer.reservation_price\n curr_offer[int(buyer.agent_id)] = step_offers[buyer.agent_id]\n \n\n for seller in sellers:\n # print(\"seller\", seller.agent_id)\n if (seller.agent_id != '0'):\n step_offers[seller.agent_id]=seller.reservation_price+np.random.rand()*seller.reservation_price\n curr_offer[int(seller.agent_id)] = step_offers[seller.agent_id]'''\n\n #####################################################################\n\n observation, rewards, done, _ = env.step(step_offers)\n print(step_offers)\n print(\"=============rewards\", rewards)\n s_ = np.hstack((buyer_s0[:-1].reshape((NUM_AGENT, -1))[:, 1:], curr_offer)).flatten()\n #print(\"----s\",s_)\n buyer_s0_ = np.hstack((s_, alex.reservation_price))\n seller_s1_= np.hstack((s_, nick.reservation_price))\n\n r_0 = rewards['0']\n r_1=rewards['1']\n print(done)\n done_=True\n for boolen in done.values():\n if not boolen:\n done_=False\n \n if ARGS.reward_mode==1:\n reward_suc=float(alex.reservation_price-a)\n reward_fail=0\n elif ARGS.reward_mode==2:\n reward_suc=float(alex.reservation_price-a)\n reward_fail=-float(nn-a)\n elif ARGS.reward_mode==3:\n reward_suc=float(alex.reservation_price-a)\n reward_fail=float(alex.reservation_price+a-2*nn)\n elif ARGS.reward_mode==4:\n reward_suc=-8 * ((float(a) - nn) **2) + 1-0.6\n reward_fail=-8 * ((float(a) - nn) **2) + 1-0.6\n elif ARGS.reward_mode==5:\n reward_suc=0.1*stats.norm.pdf(float(a), nn, 0.1)\n reward_fail=0.1*stats.norm.pdf(float(a), nn, 0.1)\n #reward_func = -8 * ((float(a) - 45/SCALE) **2) + 1\n \n print(\"Rewards\", reward_suc,reward_fail)\n\n if done_:\n #print(\"al\",alex.reservation_price)\n #print(\"a\",a)ss\n #print(10*float(alex.reservation_price-a))\n M_0.store_transition(buyer_s0, a, reward_suc , buyer_s0_)\n ep_reward+=float(alex.reservation_price-a)\n #M_1.store_transition(seller_s1, nn, r_1 , seller_s1_)\n else:\n #print('Buyer:', a,'Seller:', nn, 'diff:', a-nn )\n M_0.store_transition(buyer_s0, a, reward_fail, buyer_s0_)\n #print(int(min(n-nick.reservation_price,-1)))\n #M_1.store_transition(s, n, 10*int(min(n-nick.reservation_price,-1)), s_)\n #M_1.store_transition(s, n, s.reshape((NUM_AGENT, -1))[1][-1]-nick.reservation_price, s_)\n #M_1.store_transition(seller_s1, nn, -float(nn-a), seller_s1_)\n if M_0.pointer > MEMORY_CAPACITY:\n var *= .999 # decay the action randomness\n b_M = M_0.sample(BATCH_SIZE)\n b_s = b_M[:, :state_dim]\n b_a = b_M[:, state_dim: state_dim + action_dim]\n b_r = b_M[:, -state_dim - 1: -state_dim]\n b_s_ = b_M[:, -state_dim:]\n # print(\"state_old\", b_s)\n # print(\"state_new\",b_s_)\n # if done_:\n # print(np.expand_dims([10*float(alex.reservation_price-a)],axis=0).shape)\n # critic_0.learn(np.expand_dims(buyer_s0,axis=0), np.expand_dims(a,axis=0), np.expand_dims([reward_func],axis=0), np.expand_dims(buyer_s0_,axis=0))\n # else:\n # print(np.expand_dims( [0],axis=0).shape)\n # #critic_0.learn(np.expand_dims(buyer_s0,axis=0), np.expand_dims(a,axis=0), np.expand_dims(10*float(alex.reservation_price-a),axis=0), np.expand_dims(buyer_s0_,axis=0))\n # critic_0.learn(np.expand_dims(buyer_s0,axis=0), np.expand_dims(a,axis=0), np.expand_dims( [reward_func],axis=0), np.expand_dims(buyer_s0_,axis=0))\n # actor_0.learn(np.expand_dims(buyer_s0,axis=0))\n critic_0.learn(b_s, b_a, b_r, b_s_)\n actor_0.learn(b_s)\n\n '''if M_1.pointer > MEMORY_CAPACITY:\n var *= .9995 # decay the action randomness\n b_M = M_1.sample(BATCH_SIZE)\n b_s = b_M[:, :state_dim]\n b_a = b_M[:, state_dim: state_dim + action_dim]\n b_r = b_M[:, -state_dim - 1: -state_dim]\n b_s_ = b_M[:, -state_dim:]\n #print('reward',b_r)\n critic_1.learn(b_s, b_a, b_r, b_s_)\n actor_1.learn(b_s)'''\n\n buyer_s0 = buyer_s0_\n seller_s1 = seller_s1_\n\n ep_reward_0 += r_0\n ep_reward_1 += r_1\n \n print('Episode:', i, ' Reward_0: %i' % int(ep_reward_0), ' Reward_1: %i' % int(ep_reward_1), 'Explore: %.2f' % var,)\n\n # if done_:\n # print('Episode:', i, ' Reward_0: %i' % int(ep_reward_0),' Reward_1: %i' % int(ep_reward_1), 'Explore: %.2f' % var,)\n # #print(j)\n # # break\n # if j == MAX_EP_STEPS-1:\n # print('Episode:', i, ' Reward_0: %i' % int(ep_reward_0),' Reward_1: %i' % int(ep_reward_1), 'Explore: %.2f' % var,)\n # if ep_reward_0 > -300:\n # RENDER = True\n # # break\n \n #\n #M_0.print_transition()\nprint('Running time: ', time.time()-t1)\nprint(\"hislength:\",HIS_LEN)\nprint(\"noise:\",ARGS.noise)\nprint(\"setting:\",ARGS.reward_mode)\nprint(\"reward:\",ep_reward)\nplt.axis([0, MAX_EPISODES*MAX_EP_STEPS+HIS_LEN*MAX_EPISODES, -1, 200/SCALE])\n#plt.plot(x, y, color=\"r\", linestyle=\"-\", linewidth=0.5)\nplt.scatter(range(len(price_list_1)), price_list_0,color=\"r\",label=\"buyer_noise\", s=1)\nplt.scatter(range(len(price_list_1)), price_list_1,color=\"b\",label=\"seller\", s=3)\nplt.scatter(range(len(price_list_1)), price_list_2,color=\"g\",label=\"buyer_true\", s=1)\n#print(price_list_2)\n#print(price_list_0)\n#print(price_list_1)\nplt.legend(loc='upper left', bbox_to_anchor=(0.2, 0.95))\nplt.savefig(\"mode_%i_hislen_%i_var_%i.png\"%(ARGS.reward_mode,ARGS.his_len,ARGS.noise) ,dpi=500)\n\n# plt.axis([0, 200, 0, 1.1])\n# plt.scatter(range(200), price_list_0[0:200],color=\"g\",label=\"buyer_true\", s=1)\n# plt.scatter(range(200), price_list_2[0:200],color=\"r\",label=\"buyer_true\", s=1)\n# plt.scatter(range(200), price_list_1[0:200],color=\"b\",label=\"buyer_true\", s=1)\n# plt.savefig(\"bug.png\", dpi=500)\n","sub_path":"code/ddpg_combine_reward.py","file_name":"ddpg_combine_reward.py","file_ext":"py","file_size_in_byte":22356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"440455780","text":"from urllib import error\r\nfrom bs4 import BeautifulSoup\r\nfrom time import sleep\r\nimport random\r\nimport re\r\nimport requests\r\n\r\nmy_headers = {'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\r\n 'accept-encoding': 'gzip, deflate, br',\r\n 'accept-language': 'zh-CN,zh;q=0.9',\r\n 'cache-control': 'max-age=0',\r\n 'cookie': '_ga=GA1.2.830116670.1528858409; _gid=GA1.2.324051695.1528858409; cookieconsent_dismissed=yes',\r\n 'upgrade-insecure-requests': '1',\r\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '\r\n 'Chrome/67.0.3396.62 Safari/537.36'}\r\n\r\ncategory = ['Algebra and Number Theory', 'Analysis', 'Applied Mathematics', 'Computational Mathematics',\r\n 'Control and Optimization', 'Discrete Mathematics and Combinatorics', 'Geometry and Topology', 'Logic',\r\n 'Mathematical Physics', 'Mathematics (miscellaneous)', 'Modeling and Simulation', 'Numerical Analysis',\r\n 'Statistics and Probability', 'Theoretical Computer Science']\r\n\r\nf = open('ip.txt')\r\nlines = f.readlines()\r\ni = 0\r\nproxys = []\r\nfor line in lines:\r\n proxys.append(line.split('\\n')[0])\r\nf.close()\r\nj = 0\r\nfor i in range(2602, 2615):\r\n url_1 = 'https://www.scimagojr.com/journalrank.php?area=2600&category=' + str(i)\r\n page_1 = requests.get(url_1, proxies={'http': random.choice(proxys)}, headers=my_headers)\r\n soup_1 = BeautifulSoup(page_1.text, 'html.parser')\r\n page_total_string = soup_1.find('div', attrs={'class': 'pagination'}).get_text()\r\n page_total = int(re.findall(r'\\d+$', page_total_string)[0])\r\n\r\n try:\r\n tbody = soup_1.find('div', attrs={'class': 'table_wrap'}).tbody\r\n titles = tbody.find_all('td', attrs={'class': 'tit'})\r\n for title in titles:\r\n# print(j, title.get_text(), category[i - 2602])\r\n with open('title.txt', 'a', encoding='utf-8') as f:\r\n strr = str(j) + ', ' + title.get_text() + ', ' + category[i - 2602]\r\n f.writelines(strr)\r\n f.writelines('\\n')\r\n j = j + 1\r\n f.close()\r\n sleep(3 + random.randint(3, 5))\r\n except error.URLError as e:\r\n continue\r\n\r\n for page in range(2, int(page_total / 50) + 2):\r\n try:\r\n url_2 = 'https://www.scimagojr.com/journalrank.php?category=' + str(i) + '&area=2600&page=' + str(\r\n page) + '&total_size=' + str(page_total)\r\n page_2 = requests.get(url_2, proxies={'http': random.choice(proxys)}, headers=my_headers)\r\n soup_2 = BeautifulSoup(page_2.text, 'html.parser')\r\n tbody = soup_2.find('div', attrs={'class': 'table_wrap'}).tbody\r\n titles = tbody.find_all('td', attrs={'class': 'tit'})\r\n for title in titles:\r\n# print(j, title.get_text(), category[i - 2602])\r\n with open('title.txt', 'a', encoding='utf-8') as f:\r\n strr = str(j) + ', ' + title.get_text() + ', ' + category[i - 2602]\r\n f.writelines(strr)\r\n f.writelines('\\n')\r\n j = j + 1\r\n f.close()\r\n sleep(4 + random.randint(3, 5))\r\n except error.URLError as e:\r\n continue\r\n\r\n\r\n","sub_path":"reptile.py","file_name":"reptile.py","file_ext":"py","file_size_in_byte":3379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"316969627","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/1/29 17:01\n# @Author : Brady\n# @Email : acheng_69@163.com\n# @File : index.py\n# @Software: PyCharm\n\nimport requests\nimport os\n\ndef saveImg(root, url, path):\n try:\n if not os.path.exists(root):\n os.mkdir(root)\n if not os.path.exists(path):\n r = requests.get(url)\n r.raise_for_status()\n with open(path, 'wb') as f:\n f.write(r.content)\n f.close()\n print('文件保存成功')\n else:\n print('文件已存在')\n except IOError:\n print('爬取失败')\n\n\nif __name__ == '__main__':\n root = 'E://pics//'\n url = 'http://picm.bbzhi.com/fengjingbizhi/alasijiahenanjizhoufeng/show_fengjingou_239550_m.jpg'\n path = root + url.split('/')[-1]\n saveImg(root, url, path)\n","sub_path":"网络爬虫/Requests库/获取网络图片并保存/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"228501951","text":"from data.config.models import Config\nfrom .base import DataMixin\n\n\nclass ConfigMixin(DataMixin):\n\n schema = {\n 'config': {\n 'model': Config,\n 'provider': True\n }\n }\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.facade_index['02_config'] = self._config\n\n\n def parse_config_value(self, optional = False, help_text = 'environment configuration value'):\n self.parse_variable('config_value', optional, str, help_text,\n value_label = 'VALUE'\n )\n\n @property\n def config_value(self):\n return self.options.get('config_value', None)\n\n\n def parse_config_value_type(self, optional = '--type', help_text = 'environment configuration type (default str)'):\n self.parse_variable('config_value_type', optional, str, help_text,\n value_label = 'TYPE'\n )\n\n @property\n def config_value_type(self):\n return self.options.get('config_value_type', None)\n\n\n def get_config(self, name, default = None, required = False):\n if not name:\n return default\n\n config = self.get_instance(self._config, name, required = required)\n if config is None:\n return default\n\n return config.value\n","sub_path":"app/systems/command/mixins/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"377827909","text":"import json\nimport logging\nimport os\n\nimport boto3\nfrom botocore.exceptions import ClientError\n\n\nclass AwsConnector(object):\n\n\n @staticmethod\n def delete_file(file_name):\n s3_bucket = os.environ.get('S3_BUCKET')\n\n s3_client = boto3.resource(\"s3\").Bucket(s3_bucket)\n\n response = s3_client.Object(file_name).delete()\n\n return response['ResponseMetadata']\n\n @staticmethod\n def create_presigned_post_file_upload(file_name):\n s3_bucket = os.environ.get('S3_BUCKET_INPUT')\n return json.dumps(AwsConnector.create_presigned_post(s3_bucket, file_name))\n\n\n\n @staticmethod\n def create_presigned_post(bucket_name, object_name,\n fields=None, conditions=None, expiration=3600):\n \"\"\"Generate a presigned URL S3 POST request to upload a file\n\n :param bucket_name: string\n :param object_name: string\n :param fields: Dictionary of prefilled form fields\n :param conditions: List of conditions to include in the policy\n :param expiration: Time in seconds for the presigned URL to remain valid\n :return: Dictionary with the following keys:\n url: URL to post to\n fields: Dictionary of form fields and values to submit with the POST\n :return: None if error.\n \"\"\"\n\n # Generate a presigned S3 POST URL\n s3_client = boto3.client('s3')\n try:\n response = s3_client.generate_presigned_post(bucket_name,\n object_name,\n Fields=fields,\n Conditions=conditions,\n ExpiresIn=expiration)\n except ClientError as e:\n logging.error(e)\n return None\n\n # The response contains the presigned URL and required fields\n return response\n\n\n @staticmethod\n def create_presigned_url_file_download(file_name):\n s3_bucket = os.environ.get('S3_BUCKET')\n return AwsConnector.create_presigned_url(s3_bucket, file_name)\n\n\n @staticmethod\n def create_presigned_url(bucket_name, object_name, expiration=3600):\n \"\"\"Generate a presigned URL to share an S3 object\n\n :param bucket_name: string\n :param object_name: string\n :param expiration: Time in seconds for the presigned URL to remain valid\n :return: Presigned URL as string. If error, returns None.\n \"\"\"\n\n # Generate a presigned URL for the S3 object\n s3_client = boto3.client('s3')\n try:\n response = s3_client.generate_presigned_url('get_object',\n Params={'Bucket': bucket_name,\n 'Key': object_name},\n ExpiresIn=expiration)\n except ClientError as e:\n logging.error(e)\n return None\n\n # The response contains the presigned URL\n return response\n","sub_path":"AwsConnector.py","file_name":"AwsConnector.py","file_ext":"py","file_size_in_byte":3124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"455948683","text":"import numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom sklearn.model_selection import StratifiedKFold\nfrom MasterProject.data_Preprocessing.Datasets import get_data\nfrom MasterProject.data_Preprocessing.model import get_model\n\nimport os\n\n#-----load the training datasets----\n\ndata = get_data.Datasets()\n\ntrain_data = data.get_train_data()\ntest_data = data.get_test_data()\nunlabeled_data = data.get_unlabeled_data()\n\n\n#----------load the model-------------\nmodel_oper = get_model.model()\nindex = \"400features_30minwords_10window\"\n\nword2vec_model = model_oper.find_model(index)\nprint(word2vec_model)\n\n\ndimension = 200\n\n\n#--------------------------getcleandatastes-------------------------------------\n\nseed = 2000\n\nx_train = train_data[\"review\"]\ny_train = train_data[\"sentiment\"]\n\n\ntrain_cleaned_reviews = data.get_clean_review_lists(x_train)\n\n#dimensinon=300\nx_train = data.return_total_vector(train_cleaned_reviews, word2vec_model, dimension)\n\n\n#print(ytrain = np.array(train_data[\"sentiment\"]))\n\ny_train = np.array(y_train)\n\n#---------using K-fold to evaluate the model----------------------------\n\nseed1 = 7\n\n#define 10 fold cross validation\nkfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=seed1)\nacc_scores = []\n\nfor train, validation in kfold.split(x_train,y_train):\n #interate test model\n #define model\n model = Sequential()\n model.add(Dense(128, activation='relu', input_dim=200))\n model.add(Dense(1, activation='sigmoid'))\n model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\n model.fit(x_train[train], y_train[train], epochs=10, batch_size=20, verbose=0)\n\n #evaluate the model\n scores = model.evaluate(x_train[validation],y_train[validation],verbose=0)\n print(\"%s: %.2f%%\" % (model.metrics_names[1],scores[1]*100))\n acc_scores.append(scores[1]*100)\n\n#average\nprint(\"%.2f%% (+/- %.2f%%)\" % (np.mean(acc_scores), np.std(acc_scores)))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"MasterProject/data_Preprocessing/evaluation/K_fold_for_evaluation.py","file_name":"K_fold_for_evaluation.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"229219898","text":"import pandas as pd\n\n# --Input columns to dataframe\n# (disincluding outputs columns -- political compass targets)\n# (disincluding anything you can't get data for from census)\nX= pd.read_csv(\n '~/btn/btn/btNeutral/algorithm/formatted_data.csv',\n usecols =[0,1,2,3,4,6,7,8,9,10,11,12,13,14,15,16,17,18])\n\n# Convert Target column (what you are predicting) to dataframe\ntarget_column = pd.read_csv(\n '~/btn/btn/btNeutral/algorithm/formatted_data.csv',\n usecols =[21])\n\n# Convert Target Column dataframe to array\nY = []\nfor i in target_column['party']:\n Y.append(i)\n\n##### -------Troubleshooting------- #####\n### check if inputs and tagets are all numbers\n# import numpy as np\n# print(np.isnan(X).any())\n# print(np.isnan(Y).any())\n### check if inputs and targets are all finite\n# print(np.isfinite(X).any())\n# print(np.isfinite(Y).any())\n### Rehshape input, target, or test vectors to 2D\n### array.reshape(-1, 1) if your data has a single feature\n### array.reshape(1, -1) if it contains a single sample\n# import numpy as np\n# testVec = np.array([1,6,1,52,0,1,0,0,0,0,0,0,0,0,1,-3,0,-2])\n# properly_formmated_testVec = testVec.reshape(1, -1)","sub_path":"automation-scripts/p/CSV_formatting_tools/convertCSV.py","file_name":"convertCSV.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"243771690","text":"from django.http import HttpResponse, Http404\nfrom coup_bot.bot_player import RandomBot\nimport json\n\n\nbot_player = RandomBot()\n\n\ndef __decode_data(request):\n if request.method == 'POST':\n return json.loads(request.body)\n else:\n raise Http404\n\n\ndef __encode_data(response):\n return json.dumps(response)\n\n'''\n cards: list\n coins: integer,\n players: list\n'''\n\n\ndef start(request):\n data = __decode_data(request)\n cards = data['cards']\n coins = data['coins']\n you = data['you']\n players = data['players']\n bot_player.start(you, cards, coins, players)\n return HttpResponse()\n\n'''\n must_coup: bool\n'''\n\n\ndef play(request):\n must_coup = request.META['HTTP_MUST_COUP'] == 'true'\n response = bot_player.play(must_coup)\n print(response)\n return HttpResponse(__encode_data(response))\n\n'''\n card: string \n'''\n\n\ndef new_card(request):\n data = __decode_data(request)\n old_card = data['old_card']\n new_card = data['new_card']\n bot_player.new_card(old_card, new_card)\n return HttpResponse()\n\n'''\n action: int\n player: string\n'''\n\n\ndef tries_to_block(request):\n action = request.META['HTTP_ACTION']\n player = request.META['HTTP_PLAYER']\n response = bot_player.tries_to_block(action, player)\n print(response)\n return HttpResponse(__encode_data(response))\n\n'''\n action: int\n player: string\n card: string\n'''\n\n\ndef challenge(request):\n action = request.META['HTTP_ACTION']\n player = request.META['HTTP_PLAYER']\n card = request.META['HTTP_CARD']\n response = bot_player.challenge(action, player, card)\n print(response)\n return HttpResponse(__encode_data(response))\n\n'''\n'''\n\n\ndef lose_influence(request):\n response = bot_player.lose_influence()\n print(response)\n return HttpResponse(__encode_data(response))\n\n'''\n player: string\n card: string\n'''\n\n\ndef inquisitor(request, action):\n if action == 'give_card_to_inquisitor':\n player = request.META['HTTP_PLAYER']\n response = bot_player.give_card_to_inquisitor(player)\n elif action == 'show_card_to_inquisitor':\n player = request.META['HTTP_PLAYER']\n card = request.META['HTTP_CARD']\n response = bot_player.show_card_to_inquisitor(player, card)\n elif action == 'choose_card_to_return':\n card = request.META['HTTP_CARD']\n response = bot_player.choose_card_to_return(card)\n elif action == 'card_returned_from_investigation':\n data = __decode_data(request)\n player = data['player']\n same_card = data['same_card']\n card = data['card']\n response = bot_player.card_returned_from_investigation(player, same_card, card)\n else:\n raise Http404\n print(response)\n return HttpResponse(__encode_data(response))\n\n'''\n players: list\n player_acting: string,\n action\": int\n player_blocking: string,\n challenger: int,\n challenged: int,\n card: string\n'''\n\n\ndef status(request, action):\n data = __decode_data(request)\n if action == 'status':\n players = data['players']\n bot_player.signal_status(players)\n elif action == 'new_turn':\n player = data['opponent']\n bot_player.signal_new_turn(player)\n elif action == 'blocking':\n player_acting = data['player_acting']\n action = data['action']\n player = data['opponent']\n card = data['card']\n bot_player.signal_blocking(player_acting, action, player, card)\n elif action == 'lost_influence':\n player = data['player']\n card = data['card']\n bot_player.signal_lost_influence(player, card)\n elif action == 'challenge':\n challenger = data['challenger']\n challenged = data['challenged']\n card = data['card']\n bot_player.signal_challenge(challenger, challenged, card)\n elif action == 'action':\n player = data['opponent']\n action = data['action']\n player_targeted = data['player_targeted']\n bot_player.signal_action(player, action, player_targeted)\n else:\n raise Http404\n return HttpResponse()\n","sub_path":"coup_bot/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"412523488","text":"from functools import cache\n\nclass Solution:\n def jump(self, nums: List[int]) -> int:\n @cache\n def traverse(i: int) -> int:\n if i >= len(nums): return 2*len(nums)\n if i == len(nums)-1: return 0\n if nums[i] == 0: return 2*len(nums)\n min_jumps = 2*len(nums)\n for j in range(1, nums[i]+1):\n if i+j >= len(nums): continue\n min_jumps = min(min_jumps, 1+traverse(i+j))\n return min_jumps\n return traverse(0)\n","sub_path":"Practice-2021/May/Daily/Python3/jump_game_ii.py","file_name":"jump_game_ii.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"238787967","text":"from .HostBase import HostBase\nfrom direct.directnotify.DirectNotifyGlobal import directNotify\nfrom direct.distributed2.ClientRepository import ClientRepository\n\nfrom panda3d.core import GraphicsEngine, GraphicsPipeSelection\n\nclass ClientBase(HostBase):\n \"\"\" Main routine for client process \"\"\"\n\n notify = directNotify.newCategory(\"ClientBase\")\n\n def __init__(self):\n HostBase.__init__(self)\n\n # Initialize rendering things\n self.graphicsEngine = GraphicsEngine.getGlobalPtr()\n self.pipeSelection = GraphicsPipeSelection.getGlobalPtr()\n self.pipe = self.pipeSelection.makeDefaultPipe()\n self.win = None\n\n # Camera things\n self.camera = None\n self.cam = None\n self.camLens = None\n self.camNode = None\n\n # Scene things\n self.render = None\n self.render2d = None\n self.aspect2d = None\n self.hidden = None\n\n self.cl = self.createClientRepository()\n\n def createClientRepository(self):\n return ClientRepository()\n","sub_path":"bsp/src/bspbase/ClientBase.py","file_name":"ClientBase.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"271648253","text":"# This is your project's main settings file that can be committed to your\n# repo. If you need to override a setting locally, use settings_local.py\n\nimport json\nimport os\nfrom funfactory.settings_base import *\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(ROOT, 'inapp_pay_test.db'),\n 'USER': '',\n 'PASSWORD': '',\n 'HOST': '',\n 'PORT': '',\n 'OPTIONS': {},\n 'TEST_CHARSET': 'utf8',\n 'TEST_COLLATION': 'utf8_general_ci',\n },\n}\n\nif os.environ.get('VCAP_APPLICATION'):\n VCAP_APP = json.loads(os.environ['VCAP_APPLICATION'])\nelse:\n VCAP_APP = None\n\n# True if we running as a Stackato instance.\nSTACKATO = bool(VCAP_APP)\n\n# This must match what you see in your URL bar when you run the website.\n# TODO(Kumar): check for https?\nSITE_URL = ('http://%s' % VCAP_APP['uris'][0] if VCAP_APP\n else 'http://localhost:8000')\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash if there is a path component (optional in other cases).\n# Examples: \"http://media.lawrence.com\", \"http://example.com/media/\"\nMEDIA_URL = '/media/'\n\n# Bundles is a dictionary of two dictionaries, css and js, which list css files\n# and js files that can be bundled together by the minify app.\nMINIFY_BUNDLES = {\n 'css': {\n 'example_css': (\n 'css/examples/main.css',\n ),\n 'example_mobile_css': (\n 'css/examples/mobile.css',\n ),\n 'app_payments': (\n 'css/app_payments/base.css',\n ),\n },\n 'js': {\n 'example_js': (\n 'js/examples/libs/jquery-1.4.4.min.js',\n 'js/examples/libs/jquery.cookie.js',\n 'js/examples/init.js',\n ),\n 'app_payments': (\n 'js/libs/jquery-1.4.4.min.js',\n 'js/app_payments.js',\n ),\n }\n}\n\n# jingo-minify: Style sheet media attribute default\nCSS_MEDIA_DEFAULT = 'all'\n\n# Tell jingo-minify to use the media URL instead.\nJINGO_MINIFY_USE_STATIC = False\n\n# LESS CSS OPTIONS (Debug only)\nLESS_PREPROCESS = False # Compile LESS with Node, rather than client-side JS?\nLESS_LIVE_REFRESH = False # Refresh the CSS on save?\nLESS_BIN = 'lessc'\nUGLIFY_BIN = 'uglifyjs'\nCLEANCSS_BIN = 'cleancss'\n\n# Defines the views served for root URLs.\nROOT_URLCONF = 'inapp_pay_test.urls'\n\nINSTALLED_APPS = list(INSTALLED_APPS) + [\n # Application base, containing global templates.\n 'inapp_pay_test.base',\n 'inapp_pay_test.app_payments',\n 'moz_inapp_pay.djangoapp',\n\n 'django.contrib.admin',\n]\n\nMIDDLEWARE_CLASSES = (\n 'inapp_pay_test.base.middleware.LocaleMiddleware',\n 'multidb.middleware.PinningRouterMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'session_csrf.CsrfMiddleware', # Must be after auth middleware.\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'commonware.middleware.FrameOptionsHeader',\n 'mobility.middleware.DetectMobileMiddleware',\n 'mobility.middleware.XMobileMiddleware',\n 'inapp_pay_test.base.middleware.LogExceptionsMiddleware'\n)\n\n\n# Because Jinja2 is the default template loader, add any non-Jinja templated\n# apps here:\nJINGO_EXCLUDE_APPS = [\n 'admin',\n]\n\n# Tells the extract script what files to look for L10n in and what function\n# handles the extraction. The Tower library expects this.\n\n# # Use this if you have localizable HTML files:\n# DOMAIN_METHODS['lhtml'] = [\n# ('**/templates/**.lhtml',\n# 'tower.management.commands.extract.extract_tower_template'),\n# ]\n\n# # Use this if you have localizable HTML files:\n# DOMAIN_METHODS['javascript'] = [\n# # Make sure that this won't pull in strings from external libraries you\n# # may use.\n# ('media/js/**.js', 'javascript'),\n# ]\n\n# Paths that don't require a locale code in the URL.\nSUPPORTED_NONLOCALES = [\n 'media',\n 'admin',\n 'manifest.webapp',\n 'postback',\n 'chargeback',\n]\n\nLOGGING = {'loggers': {'playdoh': {'level': logging.INFO,\n 'handlers': ['console']},\n 'moz_inapp_pay': {'level': logging.DEBUG,\n 'handlers': ['console'],\n 'propagate': True},\n # Root logger.\n '': {'level': logging.INFO,\n 'handlers': ['console']}}}\n\n# URL to the JS file for the app to include to make in-app payments.\n# By default this is the local reference implementation.\nINAPP_PAYMENTS_JS = 'https://marketplace-dev-cdn.allizom.org/mozmarket.js'\n\n# After registering an app for in-app payments\n# on https://marketplace.mozilla.org/\n# fill these in from the Manage In-app Payments screen.\n#\n# set these in settings/local.py\n#\n# **DO NOT** commit your app secret to github :)\n#\nMOZ_APP_KEY = ''\nMOZ_APP_SECRET = ''\n# The audience of the JWT.\nMOZ_INAPP_AUD = 'firefox.marketplace.com'\nMOZ_INAPP_TYP = 'mozilla/payments/pay/v1'\n\nif STACKATO:\n # Currently, Mozilla's Stackato only has a self-signed https cert.\n # TODO: fix this when we have https support.\n SESSION_COOKIE_SECURE = False\n # TODO: remove this when we have a way to see exceptions on Stackato.\n DEBUG = TEMPLATE_DEBUG = True\n","sub_path":"inapp_pay_test/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":5439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"447249540","text":"from queue import PriorityQueue\nclass Solution:\n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n q = PriorityQueue()\n \n head = point = ListNode(0)\n \n for l in lists:\n if l:\n q.put((l.val,l))\n \n while q:\n val,node = q.get()\n \n point.next = ListNode(val)\n point = point.next\n node =node.next\n if node:\n q.put((node.val,node))\n return head.next\n \nclass Solution:\n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n heap = []\n head = ListNode(0)\n curr = head\n [heapq.heappush(heap,(l.val,i)) for i,l in enumerate(lists) if l]\n while heap:\n pop = heapq.heappop(heap)\n ind = pop[1]\n curr.next = lists[ind]\n curr= curr.next\n if lists[ind].next:\n lists[ind] = lists[ind].next\n heapq.heappush(heap,(lists[ind].val,ind))\n return head.next\n \nclass Solution:\n def mergeKLists(self, lists):\n \"\"\"\n :type lists: List[ListNode]\n :rtype: ListNode\n \"\"\"\n h = [(l.val, idx) for idx, l in enumerate(lists) if l]\n heapq.heapify(h)\n head = cur = ListNode(None)\n while h:\n val, idx = heapq.heappop(h)\n cur.next = ListNode(val)\n cur = cur.next\n node = lists[idx] = lists[idx].next\n if node:\n heapq.heappush(h, (node.val, idx))\n return head.next\n \n \n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\nfrom queue import PriorityQueue\nclass Solution:\n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n \n class NodeCompare:\n def __init__(self,node):\n self.node = node\n def __lt__(self,other):\n return self.node.val < other.node.val\n \n head = point = ListNode(0)\n \n q = PriorityQueue()\n \n for l in lists:\n if l:\n q.put(NodeCompare(l))\n \n while not q.empty():\n node = q.get().node\n point.next = node\n point = point.next\n node = node.next\n if node:\n q.put(NodeCompare(node))\n \n return head.next \n ","sub_path":"leetcode/amazon/mergeKLists.py","file_name":"mergeKLists.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"645156136","text":"# -*- coding: utf-8 -*-\n\"\"\"Annotating vector neighborhoods.\n\nThis module provides functionality for annotating vector neighborhoods\nobtained from a number of word embeddings.\n\nThis is the second (and most important) step in LDT analysis default_workflow. The\ninput is pre-computed vector neighborhood files that are prepared with\n:class:`~ldt.experiments.neighbors.VectorNeighborhoods` class. See the\ndocumentation of that class for more details.\n\nThe output is saved in the experiments/neighbors_annotated/your_experiment_name\nsubfolder of the ldt resource folder specified in the configuration file.\nThese are tab-separated data files with columns indicating the presence of a\nbinary relation in target_neighbor word pairs (e.g. whether they are\nsynonyns), or a numerical indicator of a relationship (e.g. the distance\nbetween them in an ontology). See the full list of available scores `here\n`_.\n\nTodo:\n\n * parsing arguments from command line\n * ldt resource settings saved to metadata\n * add progressbars\n * multicore processing\n\n\"\"\"\n\nimport os\nimport uuid\n\nimport pandas as pd\n# import progressbar\nfrom tqdm import tqdm\n\nfrom vecto.utils.data import load_json\n\nfrom ldt.experiments.metadata import Experiment\nfrom ldt.load_config import config\nfrom ldt.dicts.normalize import Normalization\nfrom ldt.dicts.derivation.meta import DerivationAnalyzer\nfrom ldt.dicts.semantics.metadictionary import MetaDictionary\nfrom ldt.relations.pair import RelationsInPair\n\nfrom ldt.load_config import config\n\nclass AnnotateVectorNeighborhoods(Experiment):\n \"\"\"This class provides a simple interface for annotating pre-computed top_n\n vector neighborhoods for a given vocabulary sample.\n Vecto-style metadata is also generated.\"\"\"\n\n #pylint: disable=too-many-arguments\n def __init__(self, experiment_name=config[\"experiments\"][\"experiment_name\"],\n extra_metadata=None,\n overwrite=config[\"experiments\"][\"overwrite\"], ld_scores=\"all\",\n output_dir=os.path.join(config[\"path_to_resources\"],\n \"experiments\"),\n ldt_analyzer=None, gdeps=False, cooccurrence=False):\n\n \"\"\" Annotating pre-computed top *n* neighbors for a given vocab sample\n\n Args:\n experiment_name (str): the human-readable name for the\n current experiment, which will be used to make a subfolder\n storing the generated data. If None, the folder will be simply\n timestamped.\n extra_metadata (dict): any extra fields to be added to the\n experiment metadata (overwriting any previously existing fields)\n output_dir (str): the *existing* path for saving the *subfolder*\n named with the specified experiment_name, where the output data\n and metadata.json file will be saved.\n overwrite (bool): if True, any previous data for the same\n experiment will be overwritten, and the experiment will be\n re-started.\n ldt_analyzer: :class:`~ldt.relations.pair.RelationsInPair`\n instance, with lexicographic, morphological and normalization\n resources set up as desired (see tutorial and\n class documentation). If None, default settings for English\n will be used.\n gdeps (bool): whether to use google dependency cooccurrence data\n (memory-intensive, off by default)\n cooccurrence (bool): whether to use corpus cooccurrence data\n (memory-intensive, off by default)\n ld_scores (str or list of str): \"all\" for all supported scores,\n or a list of ld_scores. Supported values are:\n\n - \"SharedPOS\",\n - \"SharedMorphForm\",\n - \"SharedDerivation\",\n - \"NonCooccurring\",\n - \"GDeps\",\n - \"TargetFrequency\",\n - \"NeighborFrequency\",\n - \"Associations\",\n - \"ShortestPath\",\n - \"Synonyms\",\n - \"Antonyms\",\n - \"Meronyms\",\n - \"Hyponyms\",\n - \"Hypernyms\",\n - \"OtherRelations\",\n - \"Numbers\",\n - \"ProperNouns\",\n - \"Noise\",\n - \"URLs\",\n - \"Filenames\",\n - \"ForeignWords\",\n - \"Hashtags\"\n - 'TargetFrequency',\n - 'NeighborFrequency'.\n\n See more details for these scores `here\n `_.\n\n Returns:\n (None): the annotated neighbors file will be written to disk\n together with the experiment metadata.\n\n \"\"\"\n\n super(AnnotateVectorNeighborhoods, self).__init__(\n experiment_name=experiment_name, extra_metadata=extra_metadata, \\\n overwrite=overwrite, embeddings=None, output_dir=output_dir,\n dataset=None, experiment_subfolder=\"neighbors_annotated\")\n\n self._metadata[\"task\"] = \"annotate_neighbors\"\n self._metadata[\"uuid\"] = str(uuid.uuid4())\n self._metadata[\"ldt_config\"] = config\n self._load_dataset(dataset=None)\n neighbors_metadata_path = self.output_dir.replace(\n \"neighbors_annotated\", \"neighbors\")\n neighbors_metadata_path = os.path.join(neighbors_metadata_path,\n \"metadata.json\")\n if not os.path.isfile(neighbors_metadata_path):\n raise IOError(\"The metadata for the neighborhood generation task \"\n \"was not found at \"+neighbors_metadata_path)\n else:\n neighbors_metadata = load_json(neighbors_metadata_path)\n self._metadata[\"embeddings\"] = neighbors_metadata[\"embeddings\"]\n self.embeddings = []\n for embedding in self._metadata[\"embeddings\"]:\n self.embeddings.append(embedding[\"path\"])\n\n self.message = \"Starting LD annotation. This will take a while for \" \\\n \"the first files, but the remainder should go faster, \" \\\n \"because many neighbor pairs will be the same.\"\n\n self._metadata[\"failed_pairs\"] = []\n self._metadata[\"missed_pairs\"] = []\n self._metadata[\"total_pairs\"] = 0\n\n self.supported_vars = [\"SharedPOS\", \"SharedMorphForm\",\n \"SharedDerivation\", \"NonCooccurring\",\n \"GDeps\", \"TargetFrequency\",\n \"NeighborFrequency\", \"Associations\",\n \"ShortestPath\", \"Synonyms\", \"Antonyms\",\n \"Meronyms\", \"Hyponyms\", \"Hypernyms\",\n \"OtherRelations\", \"Numbers\", \"ProperNouns\",\n \"Misspellings\", \"URLs\", \"Filenames\",\n \"ForeignWords\", \"Hashtags\", \"Noise\"]\n\n self.continuous_vars = ['ShortestPath', 'TargetFrequency',\n 'NeighborFrequency']\n\n self.binary_vars = [x for x in self.supported_vars if not \\\n x in self.continuous_vars]\n\n ld_scores_error = \"The ld_scores argument is invalid. It should be \" \\\n \"'all' for all supported relations, or a list with \" \\\n \"one or more of the following values:\\n\" + \\\n \", \".join(self.supported_vars)\n\n if ld_scores == \"all\":\n self._ld_scores = self.supported_vars\n if not gdeps:\n self._ld_scores.remove(\"GDeps\")\n if not cooccurrence:\n self._ld_scores.remove(\"NonCooccurring\")\n else:\n if isinstance(ld_scores, list):\n unsupported = [x for x in ld_scores if not\n x in self.supported_vars]\n if unsupported:\n raise ValueError(ld_scores_error)\n else:\n self._ld_scores = [x for x in self.supported_vars if x\n in ld_scores]\n else:\n raise ValueError(ld_scores_error)\n\n self._metadata[\"annotated_information\"] = self._ld_scores\n\n if ldt_analyzer:\n self.analyzer = ldt_analyzer\n else:\n # setting up default ldt resources to be used\n normalizer = Normalization(language=\"English\",\n order=(\"wordnet\", \"custom\"),\n lowercasing=True)\n derivation = DerivationAnalyzer()\n lex_dict = MetaDictionary()\n\n self.analyzer = RelationsInPair(normalizer=normalizer,\n derivation_dict=derivation,\n lex_dict=lex_dict, gdeps=gdeps,\n cooccurrence=cooccurrence)\n\n def _load_dataset(self, dataset):\n \"\"\"Dataset for generating vector neighborhoods was already processed in\n the previous stage of the experiment, so nothing needs to be done\n here.\"\"\"\n pass\n\n def _process(self, embeddings_path):\n\n prior_data = collect_prior_data(self.output_dir)\n\n filename = self.get_fname_for_embedding(embeddings_path)\n neighbor_file_path = os.path.join(self.output_dir.replace(\n \"neighbors_annotated\", \"neighbors\"), filename+\".tsv\")\n print(\"Annotating \"+neighbor_file_path)\n\n input_df = pd.read_csv(neighbor_file_path, header=0, sep=\"\\t\")\n self._metadata[\"total_pairs\"] += len(input_df)\n dicts = input_df.to_dict(orient=\"records\")\n\n for i in tqdm(range(len(dicts))):\n col_dict = dicts[i]\n neighbor = col_dict[\"Neighbor\"]\n target = col_dict[\"Target\"]\n if target+\":\"+neighbor in prior_data:\n col_dict.update(prior_data[target+\":\"+neighbor])\n else:\n relations = self.analyzer.analyze(target, neighbor)\n if not relations:\n self._metadata[\"failed_pairs\"].append(tuple([target, neighbor]))\n else:\n if not \"Missing\" in relations:\n to_check_continuous = self.continuous_vars\n to_check_binary = self.binary_vars\n else:\n to_check_binary = [\"NonCooccurring\", \"GDeps\"]\n to_check_continuous = [\"TargetFrequency\",\n \"NeighborFrequency\"]\n self._metadata[\"missed_pairs\"].append(\n tuple([target, neighbor]))\n for i in to_check_continuous:\n if i in relations:\n col_dict[i] = relations[i]\n for i in to_check_binary:\n col_dict[i] = i in relations\n\n output_df = pd.DataFrame(dicts,\n columns=[\"Target\", \"Rank\", \"Neighbor\",\n \"Similarity\"]+self._ld_scores)\n output_df.to_csv(os.path.join(self.output_dir, filename+\".tsv\"),\n index=False, sep=\"\\t\")\n\n def _postprocess_metadata(self):\n \"\"\"Helper method for logging unique failed target:neighbor pairs and\n calculating the overall coverage (considered as number of non-unique\n pairs for which dictionary data was successfully found).\"\"\"\n\n total_fails = self._metadata[\"failed_pairs\"]+self._metadata[\n \"missed_pairs\"]\n total_fails = list(set(total_fails))\n self._metadata[\"coverage\"] = \\\n 1 - round(len(total_fails)/self._metadata[\"total_pairs\"], 2)\n\n\ndef collect_prior_data(output_dir):\n \"\"\"Helper for collecting all the previously processed data (useful in\n case a large experiment is interrupted in the middle, as many word pairs\n repeat across different embeddings).\n\n Args:\n output_dir (str): the path where the previous results have been saved.\n\n Returns:\n (dict): a dictionary with previously computed word relations,\n with similarity and rank data removed. The keys are target:neighbor\n pairs.\n\n \"\"\"\n processed_files = os.listdir(output_dir)\n if \"metadata.json\" in processed_files:\n processed_files.remove(\"metadata.json\")\n prior_res = {}\n for f in processed_files:\n input_df = pd.read_csv(os.path.join(output_dir, f), header=0, sep=\"\\t\")\n del input_df[\"Rank\"]\n del input_df[\"Similarity\"]\n dicts = input_df.to_dict(orient=\"records\")\n for pair in dicts:\n prior_res[pair[\"Target\"]+\":\"+pair[\"Neighbor\"]] = pair\n return prior_res\n\n\n\n\nif __name__ == '__main__':\n annotation = AnnotateVectorNeighborhoods(experiment_name=\"testing\",\n overwrite=True)\n annotation.get_results()\n","sub_path":"ldt/experiments/annotate.py","file_name":"annotate.py","file_ext":"py","file_size_in_byte":13181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"470434876","text":"import csv\nimport pathlib\nfrom collections import OrderedDict\n\nimport nltk\nimport numpy as np\nimport pandas as pd\nimport torch\nimport transformers\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\nfrom torch.utils import data\nfrom transformers import RobertaTokenizer\n\nfrom src.model import model\n\ninput_fields = [\n 'qa_id',\n 'question_title',\n 'question_body',\n 'question_user_name',\n 'question_user_page',\n 'answer',\n 'answer_user_name',\n 'answer_user_page',\n 'url',\n 'category',\n 'host'\n]\n\nfeature_fields = [\n 'input_ids',\n 'attention_mask',\n 'category',\n 'host',\n 'sentence_lengths',\n 'newlines',\n 'similarity',\n 'hyperlinks',\n 'first_person',\n 'latex',\n 'brackets',\n 'sentiment',\n 'spell',\n 'punctuation',\n 'question_mark',\n 'exclamation',\n 'yes_no',\n 'numeric_answer',\n 'short_keyword',\n 'consequence',\n 'how',\n 'choice',\n 'comparison',\n 'comma',\n 'period',\n 'instruction',\n 'self_reference',\n 'parts_of_speech',\n 'language',\n 'sonic',\n 'reference',\n 'word_part',\n]\n\ntarget_fields = [\n 'question_asker_intent_understanding',\n 'question_body_critical',\n 'question_conversational',\n 'question_expect_short_answer',\n 'question_fact_seeking',\n 'question_has_commonly_accepted_answer',\n 'question_interestingness_others',\n 'question_interestingness_self',\n 'question_multi_intent',\n 'question_not_really_a_question',\n 'question_opinion_seeking',\n 'question_type_choice',\n 'question_type_compare',\n 'question_type_consequence',\n 'question_type_definition',\n 'question_type_entity',\n 'question_type_instructions',\n 'question_type_procedure',\n 'question_type_reason_explanation',\n 'question_type_spelling',\n 'question_well_written',\n 'answer_helpful',\n 'answer_level_of_information',\n 'answer_plausible',\n 'answer_relevance',\n 'answer_satisfaction',\n 'answer_type_instructions',\n 'answer_type_procedure',\n 'answer_type_reason_explanation',\n 'answer_well_written'\n]\n\nid_field = 'qa_id'\n\n\ndef tokenize(strings, tokenizer):\n output = []\n for string in strings:\n output.append(tokenizer.tokenize(string))\n return output\n\n\ndef clip_or_pad(titles, questions, answers, max_length):\n texts = []\n masks = []\n token_ids = []\n\n for idx, (title, question, answer) in enumerate(zip(titles, questions,\n answers)):\n extra = (len(title)\n + len(question)\n + len(answer)\n + len(['CLS]', '[SEP]', '[SEP]'])\n - max_length\n )\n\n if extra > 0:\n clip1 = int(extra * len(question) / (len(question) + len(answer)))\n clip2 = extra - clip1\n if clip1 > 0:\n question = question[:-clip1]\n if clip2 > 0:\n answer = answer[:-clip2]\n pad = []\n else:\n pad = ['[PAD]' for _ in range(0, -extra)]\n\n title = ['[CLS]'] + title\n answer = ['[SEP]'] + answer + ['[SEP]']\n\n title_mask = [1] * len(title)\n title_token_ids = [0] * len(title)\n\n question_mask = [1] * len(question)\n question_token_ids = [0] * len(question)\n\n answer_mask = [1] * len(answer)\n answer_token_ids = [0] + [1] * (len(answer) - 1)\n\n pad_mask = [0] * len(pad)\n pad_token_ids = [1] * len(pad)\n\n text = title + question + answer + pad\n text_mask = title_mask + question_mask + answer_mask + pad_mask\n text_token_ids = title_token_ids + question_token_ids + \\\n answer_token_ids + pad_token_ids\n\n texts.append(text)\n masks.append(text_mask)\n token_ids.append(text_token_ids)\n\n return texts, masks, token_ids\n\n\ndef one_hot_encode(category_list):\n output = []\n oh_dict = {\n 'SCIENCE': [1.0, 0.0, 0.0, 0.0, 0.0],\n 'CULTURE': [0.0, 1.0, 0.0, 0.0, 0.0],\n 'LIFE_ARTS': [0.0, 0.0, 1.0, 0.0, 0.0],\n 'STACKOVERFLOW': [0.0, 0.0, 0.0, 1.0, 0.0],\n 'TECHNOLOGY': [0.0, 0.0, 0.0, 0.0, 1.0]\n }\n for row in category_list:\n output.append(oh_dict[row])\n\n return output\n\n\ndef encode(strings, tokenizer):\n output = []\n for string in strings:\n output.append(tokenizer.convert_tokens_to_ids(string))\n return output\n\n\ndef bert_tokens(titles, questions, answers):\n bert_token_size = 512\n\n tokenizer = RobertaTokenizer.from_pretrained('roberta-base',\n sep_token='[SEP]',\n pad_token='[PAD]',\n cls_token='[CLS]')\n\n title_tks = tokenize(titles, tokenizer)\n quest_tks = tokenize(questions, tokenizer)\n ans_tks = tokenize(answers, tokenizer)\n concat, _, _ = clip_or_pad(title_tks, quest_tks, ans_tks, bert_token_size)\n output = encode(concat, tokenizer)\n return output\n\n\ndef target_vector_label(target_dict):\n print(\"Creating label vector.\")\n for idx0, (_, data) in enumerate(target_dict.items()):\n if idx0 == 0:\n samples = len(data)\n features = len(target_dict)\n label = [[0.0 for _ in range(features)] for _ in range(samples)]\n for idx1, row in enumerate(data):\n label[idx1][idx0] = float(row)\n\n return label\n\n\ndef input_ids_feature(input_dict):\n print(\"Creating text input.\")\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n text = bert_tokens(titles, questions, answers)\n\n return text\n\n\ndef attention_mask_feature(input_dict):\n print(\"Creating attention mask.\")\n bert_tkn_size = 512\n\n tokenizer = RobertaTokenizer.from_pretrained('roberta-base',\n sep_token='[SEP]',\n pad_token='[PAD]',\n cls_token='[CLS]')\n\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n title_tks = tokenize(titles, tokenizer)\n quest_tks = tokenize(questions, tokenizer)\n ans_tks = tokenize(answers, tokenizer)\n\n _, masks, _ = clip_or_pad(title_tks, quest_tks, ans_tks, bert_tkn_size)\n\n return masks\n\n\ndef token_type_ids_feature(input_dict):\n print(\"Creating token_ids mask.\")\n bert_tkn_size = 512\n\n tokenizer = RobertaTokenizer.from_pretrained('roberta-base',\n sep_token='[SEP]',\n pad_token='[PAD]',\n cls_token='[CLS]')\n\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n title_tks = tokenize(titles, tokenizer)\n quest_tks = tokenize(questions, tokenizer)\n ans_tks = tokenize(answers, tokenizer)\n\n _, _, token_ids = clip_or_pad(title_tks, quest_tks, ans_tks, bert_tkn_size)\n\n return token_ids\n\n\ndef category_feature(input_dict):\n print(\"One hot encoding category.\")\n category_list = input_dict['category']\n category = one_hot_encode(category_list)\n return category\n\n\ndef sentence_lengths_feature(input_dict):\n print('Calulating title, question, and answer lengths.')\n lengths = []\n\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n for title, question, answer in zip(titles, questions, answers):\n title_length = len(title.split())\n question_length = len(question.split())\n answer_length = len(answer.split())\n\n lengths.append([title_length, question_length, answer_length])\n\n return lengths\n\n\ndef newlines_feature(input_dict):\n print('Counting the number of lines.')\n count = []\n questions = input_dict['question_body']\n answers = input_dict['answer']\n for question, answer in zip(questions, answers):\n count.append([question.count('\\n'), answer.count('\\n')])\n return count\n\n\ndef similarity_feature(input_dict):\n print('Calculating word similarity.')\n similarity = []\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for title, question, answer in zip(titles, questions, answers):\n qandt = set(title.lower().split()) | set(question.lower().split())\n answer = set(answer.lower().split())\n similarity.append([len(qandt & answer)])\n\n return similarity\n\n\ndef hyperlinks_feature(input_dict):\n print('Counting the number of hyperlinks.')\n links = []\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for question, answer in zip(questions, answers):\n counts = [question.count('https://') + question.count('http://'),\n answer.count('https://') + answer.count('http://')]\n links.append(counts)\n\n return links\n\n\ndef first_person_feature(input_dict):\n print('Counting first-person pronouns.')\n counts = []\n words = [' i ', ' me ', ' my ', ' mine ', ' we ', ' us ', ' ours ']\n\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for title, question, answer in zip(titles, questions, answers):\n count = [0, 0]\n for word in words:\n count[0] += title.lower().count(word)\n count[0] += question.lower().count(word)\n count[1] += answer.lower().count(word)\n counts.append(count)\n\n return counts\n\n\ndef latex_feature(input_dict):\n print('Detecting the use of mathematical formulas.')\n maths = []\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for question, answer in zip(questions, answers):\n count = [question.count('$') // 2, answer.count('$') // 2]\n maths.append(count)\n\n return maths\n\n\ndef line_lengths_feature(input_dict):\n print('Measuring average line length.')\n lengths = []\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for question, answer in zip(questions, answers):\n qlines = question.splitlines()\n alines = question.splitlines()\n qmean = sum(len(line) for line in qlines) / len(qlines)\n amean = sum(len(line) for line in alines) / len(alines)\n\n lengths.append([qmean, amean])\n\n return lengths\n\n\ndef brackets_feature(input_dict):\n print('Counting bracket use.')\n code = []\n questions = input_dict['question_body']\n answers = input_dict['answer']\n brackets = ['{', '}', '[', ']', '(', ')']\n for question, answer in zip(questions, answers):\n count = [sum(question.count(symbol) for symbol in brackets) // 2,\n sum(answer.count(symbol) for symbol in brackets) // 2]\n code.append(count)\n\n return code\n\n\ndef sentiment_feature(input_dict):\n print('Measuring sentiment.')\n sentiments = []\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n nltk.download('vader_lexicon')\n sid = SentimentIntensityAnalyzer()\n for title, question, answer in zip(titles, questions, answers):\n sentiment = [sid.polarity_scores(title)['compound'],\n sid.polarity_scores(question)['compound'],\n sid.polarity_scores(answer)['compound']\n ]\n sentiments.append(sentiment)\n return sentiments\n\n\ndef spell_feature(input_dict):\n print('Counting words that relating to spelling.')\n mentions = []\n words = [' spell ', ' spelled ', ' spells ', ' spelling ', ' grammar ',\n ' spelt ', ' speller ']\n\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for title, question, answer in zip(titles, questions, answers):\n count = [0, 0, 0]\n for word in words:\n count[0] += title.lower().count(word)\n count[1] += question.lower().count(word)\n count[2] += answer.lower().count(word)\n mentions.append(count)\n\n return mentions\n\n\ndef host_feature(input_dict):\n sites = {'blender.stackexchange.com': 0, 'ell.stackexchange.com': 1,\n 'gamedev.stackexchange.com': 2,\n 'graphicdesign.stackexchange.com': 3,\n 'mechanics.stackexchange.com': 4,\n 'softwarerecs.stackexchange.com': 5,\n 'meta.math.stackexchange.com': 6, 'gaming.stackexchange.com': 7,\n 'serverfault.com': 8, 'music.stackexchange.com': 9,\n 'biology.stackexchange.com': 10, 'bicycles.stackexchange.com': 11,\n 'mathoverflow.net': 12, 'askubuntu.com': 13,\n 'ux.stackexchange.com': 14,\n 'cs.stackexchange.com': 15, 'meta.askubuntu.com': 16,\n 'rpg.stackexchange.com': 17, 'raspberrypi.stackexchange.com': 18,\n 'movies.stackexchange.com': 19,\n 'meta.christianity.stackexchange.com': 20,\n 'math.stackexchange.com': 21, 'diy.stackexchange.com': 22,\n 'programmers.stackexchange.com': 23,\n 'webapps.stackexchange.com': 24,\n 'money.stackexchange.com': 25,\n 'expressionengine.stackexchange.com': 26,\n 'electronics.stackexchange.com': 27,\n 'judaism.stackexchange.com': 28,\n 'codereview.stackexchange.com': 29,\n 'boardgames.stackexchange.com': 30,\n 'sharepoint.stackexchange.com': 31,\n 'crypto.stackexchange.com': 32,\n 'gis.stackexchange.com': 33, 'physics.stackexchange.com': 34,\n 'academia.stackexchange.com': 35, 'unix.stackexchange.com': 36,\n 'superuser.com': 37, 'mathematica.stackexchange.com': 38,\n 'travel.stackexchange.com': 39, 'dsp.stackexchange.com': 40,\n 'cooking.stackexchange.com': 41,\n 'salesforce.stackexchange.com': 42,\n 'android.stackexchange.com': 43, 'stats.stackexchange.com': 44,\n 'anime.stackexchange.com': 45, 'scifi.stackexchange.com': 46,\n 'chemistry.stackexchange.com': 47,\n 'webmasters.stackexchange.com': 48,\n 'meta.codereview.stackexchange.com': 49,\n 'drupal.stackexchange.com': 50,\n 'security.stackexchange.com': 51, 'dba.stackexchange.com': 52,\n 'magento.stackexchange.com': 53,\n 'wordpress.stackexchange.com': 54,\n 'stackoverflow.com': 55, 'tex.stackexchange.com': 56,\n 'robotics.stackexchange.com': 57, 'photo.stackexchange.com': 58,\n 'christianity.stackexchange.com': 59,\n 'english.stackexchange.com': 60,\n 'apple.stackexchange.com': 61, 'meta.stackexchange.com': 62}\n\n websites = []\n hosts = input_dict['host']\n for host in hosts:\n oh = [0.0] * len(sites)\n oh[sites[host]] = 1.0\n websites.append(oh)\n\n return websites\n\n\ndef self_reference_feature(input_dict):\n counter = []\n questions = input_dict['question_body']\n answers = input_dict['answer']\n hosts = input_dict['host']\n for host, question, answer in zip(hosts, questions, answers):\n count = [0, 0]\n count[0] += question.lower().count(host)\n count[1] += answer.lower().count(host)\n counter.append(count)\n return counter\n\n\ndef punctuation_feature(input_dict):\n characters = ['\"', ':', ';', '?', '!', '-']\n punctuation = []\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for title, question, answer in zip(titles, questions, answers):\n count = [0, 0, 0]\n for char in characters:\n count[0] += title.count(char)\n count[1] += question.count(char)\n count[2] += answer.count(char)\n punctuation.append(count)\n\n return punctuation\n\n\ndef question_mark_feature(input_dict):\n counter = []\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for title, question, answer in zip(titles, questions, answers):\n count = [0, 0, 0]\n\n count[0] += title.count('?')\n count[1] += question.count('?')\n count[2] += answer.count('?')\n counter.append(count)\n\n return counter\n\n\ndef exclamation_feature(input_dict):\n exclaim = []\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for title, question, answer in zip(titles, questions, answers):\n count = [0, 0, 0]\n\n count[0] += title.count('!')\n count[1] += question.count('!')\n count[2] += answer.count('!')\n exclaim.append(count)\n\n return exclaim\n\n\ndef yes_no_feature(input_dict):\n words = ['does ', 'can ', 'has ', 'have ', 'had ', 'is this ',\n 'is that ']\n counter = []\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for title, question, answer in zip(titles, questions, answers):\n count = [0, 0, 0]\n for word in words:\n count[0] += title.lower().count(word)\n count[1] += question.lower().count(word)\n count[2] += answer.lower().count(word)\n counter.append(count)\n\n return counter\n\n\ndef numeric_answer_feature(input_dict):\n words = ['how many', 'how much', 'when ', 'the number ']\n counter = []\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for title, question, answer in zip(titles, questions, answers):\n count = [0, 0, 0]\n for word in words:\n count[0] += title.lower().count(word)\n count[1] += question.lower().count(word)\n count[2] += answer.lower().count(word)\n counter.append(count)\n\n return counter\n\n\ndef short_keyword_feature(input_dict):\n words = ['where ', 'who ']\n counter = []\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for title, question, answer in zip(titles, questions, answers):\n count = [0, 0, 0]\n for word in words:\n count[0] += title.lower().count(word)\n count[1] += question.lower().count(word)\n count[2] += answer.lower().count(word)\n counter.append(count)\n\n return counter\n\n\ndef consequence_feature(input_dict):\n words = ['what happens ', 'what will happen ', 'what has happened ',\n 'consequence ', 'result ', 'what happened ']\n counter = []\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for title, question, answer in zip(titles, questions, answers):\n count = [0, 0, 0]\n for word in words:\n count[0] += title.lower().count(word)\n count[1] += question.lower().count(word)\n count[2] += answer.lower().count(word)\n counter.append(count)\n\n return counter\n\n\ndef how_feature(input_dict):\n words = ['how']\n counter = []\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for title, question, answer in zip(titles, questions, answers):\n count = [0, 0, 0]\n for word in words:\n count[0] += title.lower().count(word)\n count[1] += question.lower().count(word)\n count[2] += answer.lower().count(word)\n counter.append(count)\n\n return counter\n\n\ndef thanks_feature(input_dict):\n words = ['thanks', 'thank you', 'i appreciate']\n counter = []\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for title, question, answer in zip(titles, questions, answers):\n count = [0, 0, 0]\n for word in words:\n count[0] += title.lower().count(word)\n count[1] += question.lower().count(word)\n count[2] += answer.lower().count(word)\n counter.append(count)\n\n return counter\n\n\ndef choice_feature(input_dict):\n words = ['which', 'or ', 'instead ', 'either', 'other']\n counter = []\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for title, question, answer in zip(titles, questions, answers):\n count = [0, 0, 0]\n for word in words:\n count[0] += title.lower().count(word)\n count[1] += question.lower().count(word)\n count[2] += answer.lower().count(word)\n counter.append(count)\n\n return counter\n\n\ndef comparison_feature(input_dict):\n words = ['same', 'different', 'equal', 'opposite', 'like', 'better'\n 'worse']\n counter = []\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for title, question, answer in zip(titles, questions, answers):\n count = [0, 0, 0]\n for word in words:\n count[0] += title.lower().count(word)\n count[1] += question.lower().count(word)\n count[2] += answer.lower().count(word)\n counter.append(count)\n\n return counter\n\n\ndef comma_feature(input_dict):\n counter = []\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for title, question, answer in zip(titles, questions, answers):\n count = [0, 0, 0]\n\n count[0] += title.count(',')\n count[1] += question.count(',')\n count[2] += answer.count(',')\n counter.append(count)\n\n return counter\n\n\ndef period_feature(input_dict):\n counter = []\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for title, question, answer in zip(titles, questions, answers):\n count = [0, 0, 0]\n\n count[0] += title.count('.')\n count[1] += question.count('.')\n count[2] += answer.count('.')\n counter.append(count)\n\n return counter\n\n\ndef instruction_feature(input_dict):\n words = ['first', 'second', 'third', 'last', 'next', 'before',\n 'you should']\n counter = []\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for title, question, answer in zip(titles, questions, answers):\n count = [0, 0, 0]\n for word in words:\n count[0] += title.lower().count(word)\n count[1] += question.lower().count(word)\n count[2] += answer.lower().count(word)\n counter.append(count)\n\n return counter\n\n\ndef parts_of_speech_feature(input_dict):\n words = ['noun', 'verb', 'adjective', 'adverb', 'pronoun', 'preposition',\n 'conjunction', 'interjection', 'article', 'parts of speech']\n counter = []\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for title, question, answer in zip(titles, questions, answers):\n count = [0, 0, 0]\n for word in words:\n count[0] += title.lower().count(word)\n count[1] += question.lower().count(word)\n count[2] += answer.lower().count(word)\n counter.append(count)\n\n return counter\n\n\ndef language_feature(input_dict):\n words = ['mandarin', 'chinese', 'spanish', 'english', 'hindi', 'hindustani'\n 'bengali',\n 'portuguese', 'russian', 'japanese', 'punjabi',\n 'turkish', 'korean', 'french', 'german', 'italian', 'vietnamese'\n 'arabic',\n 'polish', 'dutch', 'romainian', 'greek', 'latin']\n counter = []\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for title, question, answer in zip(titles, questions, answers):\n count = [0, 0, 0]\n for word in words:\n count[0] += title.lower().count(word)\n count[1] += question.lower().count(word)\n count[2] += answer.lower().count(word)\n counter.append(count)\n\n return counter\n\n\ndef sonic_feature(input_dict):\n words = ['sound', 'pronounce', 'pronunciation', 'enunciate', 'enunciation',\n 'hear', 'accent', 'tone', 'voice', 'silent', 'say', 'speak'\n 'utter',\n 'stress', 'voice', 'tone', 'intonation', 'phonetic',\n 'sonic']\n counter = []\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for title, question, answer in zip(titles, questions, answers):\n count = [0, 0, 0]\n for word in words:\n count[0] += title.lower().count(word)\n count[1] += question.lower().count(word)\n count[2] += answer.lower().count(word)\n counter.append(count)\n\n return counter\n\n\ndef reference_feature(input_dict):\n words = ['book', 'dictionary', 'thesarus', 'dictionaries', 'corpus', 'text'\n 'oxford',\n 'literature', 'poem', 'essay', 'paragraph',\n 'vocabulary', 'author', 'shakespeare', 'ngram', 'etymology']\n counter = []\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for title, question, answer in zip(titles, questions, answers):\n count = [0, 0, 0]\n for word in words:\n count[0] += title.lower().count(word)\n count[1] += question.lower().count(word)\n count[2] += answer.lower().count(word)\n counter.append(count)\n\n return counter\n\n\ndef word_part_feature(input_dict):\n words = ['suffix', 'vowel', 'consonant', 'root', 'prefix', 'syllable']\n counter = []\n titles = input_dict['question_title']\n questions = input_dict['question_body']\n answers = input_dict['answer']\n\n for title, question, answer in zip(titles, questions, answers):\n count = [0, 0, 0]\n for word in words:\n count[0] += title.lower().count(word)\n count[1] += question.lower().count(word)\n count[2] += answer.lower().count(word)\n counter.append(count)\n\n return counter\n\n\ndef preprocess(data_path):\n with data_path.open(mode='r') as f:\n csv_reader = csv.DictReader(f)\n ids = []\n\n input_dict = OrderedDict()\n target_dict = OrderedDict()\n feature_dict = OrderedDict()\n\n for field in input_fields:\n input_dict[field] = []\n\n for field in target_fields:\n target_dict[field] = []\n for row in csv_reader:\n\n ids.append(row[id_field])\n for field in input_fields:\n if field == 'question_title':\n item = ' ' + row[field]\n else:\n item = row[field]\n input_dict[field].append(item)\n\n for field in feature_fields:\n feature_function = getattr(preprocess, f\"{field}_feature\")\n feature_dict[field] = feature_function(input_dict)\n\n yield ids, input_dict, feature_dict\n\n\nclass KaggleQuestDataset(data.Dataset):\n def __init__(self, csv_path):\n ids, inputs, features = preprocess(csv_path)\n self.data = features\n self.ids = ids\n\n def __len__(self):\n return len(self.ids)\n\n def __getitem__(self, index):\n output = {}\n for field in self.data:\n output[field] = torch.tensor(self.data[field][index])\n return self.ids[index], output\n\nclass RobertaForQUEST(transformers.BertPreTrainedModel):\n def __init__(self, config):\n super(RobertaForQUEST, self).__init__(config)\n model_name = 'roberta-base'\n self.bert = transformers.RobertaModel.from_pretrained(model_name,\n config=config)\n self.embedding = torch.nn.Linear(5, 5)\n self.embedding2 = torch.nn.Linear(63, 10)\n self.linear_layer1 = torch.nn.Linear(3160, 2000)\n self.linear_layer2 = torch.nn.Linear(2000, 1000)\n self.linear_layer3 = torch.nn.Linear(1000, 500)\n self.dropout = torch.nn.Dropout(config.hidden_dropout_prob)\n self.classifier = torch.nn.Linear(500, config.num_labels)\n\n for param in self.bert.parameters():\n param.requires_grad = False\n\n def forward(self,\n input_ids=None,\n attention_mask=None,\n head_mask=None,\n inputs_embeds=None,\n labels=None,\n category=None,\n sentence_lengths=None,\n newlines=None,\n similarity=None,\n hyperlinks=None,\n first_person=None,\n latex=None,\n brackets=None,\n sentiment=None,\n spell=None,\n token_type_ids=None,\n punctuation=None,\n question_mark=None,\n exclamation=None,\n yes_no=None,\n numeric_answer=None,\n short_keyword=None,\n consequence=None,\n how=None,\n choice=None,\n comparison=None,\n comma=None,\n period=None,\n instruction=None,\n host=None,\n self_reference=None,\n parts_of_speech=None,\n language=None,\n sonic=None,\n reference=None,\n word_part=None\n ):\n outputs = self.bert(input_ids,\n token_type_ids=token_type_ids,\n attention_mask=attention_mask,\n )\n\n hidden_states = outputs[2]\n\n h6 = torch.mean(hidden_states[-1], 1).reshape((-1, 1, 768))\n h5 = torch.mean(hidden_states[-2], 1).reshape((-1, 1, 768))\n h4 = torch.mean(hidden_states[-3], 1).reshape((-1, 1, 768))\n h3 = torch.mean(hidden_states[-4], 1).reshape((-1, 1, 768))\n\n embedding = self.embedding(category)\n embedding2 = self.embedding2(host)\n\n e = embedding.view(-1, 1, 5)\n e2 = embedding2.view(-1, 1, 10)\n sl = sentence_lengths.view(-1, 1, 3)\n n = newlines.view(-1, 1, 2)\n s = similarity.view(-1, 1, 1)\n h = hyperlinks.view(-1, 1, 2)\n fp = first_person.view(-1, 1, 2)\n l = latex.view(-1, 1, 2)\n b = brackets.view(-1, 1, 2)\n sp = spell.view(-1, 1, 3)\n\n p = punctuation.view(-1, 1, 3)\n q = question_mark.view(-1, 1, 3)\n ex = exclamation.view(-1, 1, 3)\n y = yes_no.view(-1, 1, 3)\n na = numeric_answer.view(-1, 1, 3)\n sk = short_keyword.view(-1, 1, 3)\n c = consequence.view(-1, 1, 3)\n\n hw = how.view(-1, 1, 3)\n ch = choice.view(-1, 1, 3)\n co = comparison.view(-1, 1, 3)\n cm = comma.view(-1, 1, 3)\n pd = period.view(-1, 1, 3)\n i = instruction.view(-1, 1, 3)\n\n sr = self_reference.view(-1, 1, 2)\n ps = parts_of_speech.view(-1, 1, 3)\n la = language.view(-1, 1, 3)\n sn = sonic.view(-1, 1, 3)\n rf = reference.view(-1, 1, 3)\n wp = word_part.view(-1, 1, 3)\n\n hcat = torch.cat([h3, h4, h5, h6], 2)\n\n fcat = torch.cat(\n [e, e2, sl, s, n, h, fp, l, b, sp, p, q, ex, y, na, sk,\n c, hw, ch, co, cm, pd, i, sr, ps, la, sn, rf, wp], 2)\n\n cat = torch.cat([hcat, fcat], 2)\n cat = torch.nn.ReLU()(cat)\n\n layer1 = self.linear_layer1(cat)\n layer1 = torch.nn.LeakyReLU()(layer1)\n layer2 = self.linear_layer2(layer1)\n layer2 = torch.nn.LeakyReLU()(layer2)\n layer3 = self.linear_layer3(layer2)\n layer3 = torch.nn.LeakyReLU()(layer3)\n logits = self.classifier(layer3)\n\n return torch.squeeze(logits)\n\n\nif __name__ == '__main__':\n\n test_dir = pathlib.Path('/home/scott/Projects/kaggle__google_quest_q_and_a_labeling/data/test.csv')\n test_model = pathlib.Path('/home/scott/Projects/kaggle__google_quest_q_and_a_labeling/data/saved_models/load_model')\n output_path = pathlib.Path('/home/scott/Projects/kaggle__google_quest_q_and_a_labeling/data/results.csv')\n\n GPU_CAP_TEST = 50\n\n use_cuda = torch.cuda.is_available()\n device = torch.device(\"cuda:0\" if use_cuda else \"cpu\")\n print(f\"Using {device}.\")\n\n model_name = 'roberta-base'\n model_config = transformers.RobertaConfig.from_pretrained(\n model_name,\n output_hidden_states=True,\n num_labels=30,\n )\n\n bnet = model.RobertaForQUEST(config=model_config)\n\n state_dict_path = None\n\n for filepath in test_dir.iterdir():\n state_dict_path = filepath.resolve().as_posix()\n if state_dict_path:\n print('Loading saved model.')\n state_dict = torch.load(state_dict_path)\n bnet.load_state_dict(state_dict)\n\n bnet.to(device)\n\n dataset = KaggleQuestDataset(test_dir)\n\n testloader = torch.utils.data.DataLoader(dataset,\n batch_size=GPU_CAP_TEST,\n shuffle=True,\n num_workers=0\n )\n offset = 0\n predicted = np.zeros((len(dataset), len(target_fields)))\n ids = []\n for data in testloader:\n entry_id, features = data\n ids.append(entry_id)\n for field in features:\n features[field] = features[field].to(device)\n\n output = bnet(**features)\n\n predicted[offset: offset + output.size()[0], :] = \\\n output.cpu().numpy()\n\n df_ids = pd.DataFrame(ids)\n df_data = pd.DataFrame(predicted)\n df_data.columns(target_fields)\n df_data.insert(0,'qa_id',df_ids)\n df_data.to_csv(ouput_dir)","sub_path":"src/model/test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":34465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"235704084","text":"from django.conf.urls import url\nfrom . import views\n\n# Warning: No comma for the last url entry\nurlpatterns = [\n url(r\"^$\", views.book_welcome, name=\"bookwelcome\"),\n url(r\"^overview$\", views.book_overview, name=\"bookoverview\"),\n url(r\"^add_book$\", views.add_book, name=\"addbook\"),\n url(r\"^statistics$\", views.show_statistics, name=\"statistics\"),\n url(r\"^query$\", views.search_book, name=\"search\"),\n url(r\"^edit$\", views.edit_book, name=\"editbook\"),\n url(r\"^delete/bookid=\\d{1,}$\", views.delete_book, name=\"deletebook\"),\n url(r\"^details/bookid=\\d{1,}$\", views.book_details, name=\"bookdetails\")\n]\n","sub_path":"book/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"22573559","text":"#!/usr/bin/env python3\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nimport unittest\n\nfrom common.base_image_layout_test import BaseImageLayoutTest\nfrom utils.test_utils import qemu_check\n\n@unittest.skip(\"Skip until test is updated\")\nclass ImageLayoutTest(BaseImageLayoutTest):\n IMAGE_LAYOUT = {\n \"spi0.0\": {\n \"meta_name\": \"metaro\",\n \"mapping\": {\n # dmesg name: mtd name\n \"rom\": \"spl\",\n \"recovery\": \"rec-u-boot\",\n \"metaro\": \"image-meta\",\n \"fitro\": \"os-fit\",\n },\n },\n \"spi0.1\": {\n \"meta_name\": \"meta\",\n \"mapping\": {\n \"romx\": \"spl\",\n \"meta\": \"image-meta\",\n \"fit\": \"os-fit\",\n \"env\": \"u-boot-env\",\n },\n },\n }\n\n @unittest.skipIf(qemu_check(), \"test env is QEMU, skipped\")\n def test_spi_1_mtd(self):\n \"\"\"\n Test actual image layout on spi0.1 matches image meta data\n \"\"\"\n super().test_spi_1_mtd()\n","sub_path":"tests2/tests/bletchley/test_image_layout.py","file_name":"test_image_layout.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"615438636","text":"import ConfigParser\nimport pyodbc\nimport os\nfrom utility import user\n\nclass dataconnect:\n def __init__(self):\n self._config = ConfigParser.ConfigParser()\n configFile = os.path.dirname(__file__) + \"/../../main.cfg\"\n self._config.read(configFile)\n conn = self._config.get(\"Main\", \"localdb\")\n self._conn = pyodbc.connect(conn)\n \n def __del__(self):\n self._conn.close()\n del self._config\n\n def assignHost(self, userid, date):\n query = 'SELECT assignhost(?, ?)'\n cursor = self._conn.cursor()\n cursor.execute(query, userid, date)\n row = cursor.fetchone()\n cursor.close()\n self._conn.commit()\n if row.assignhost == \"0\": return False\n return True\n\n def getSelectable(self, classType):\n status = {}\n query = 'SELECT id, name FROM getselectable(?)'\n cursor = self._conn.cursor()\n cursor.execute(query, classType)\n for row in cursor:\n status[row.id] = row.name\n cursor.close()\n return status\n\n def getReportable(self, classType):\n status = {}\n query = 'SELECT id, name FROM getreportable(?)'\n cursor = self._conn.cursor()\n cursor.execute(query, classType)\n for row in cursor:\n status[row.id] = row.name\n status[\"assigned\"] = \"Assigned\" # create pseudo assigned status that users in other statuses can also be in\n cursor.close()\n return status \n\n def getAvailable(self, first, next, classType):\n available = {}\n unavailable = self.getUnavailableStatus(classType)\n query = 'SELECT * FROM getavailable(?, ?, ?, ?)'\n cursor = self._conn.cursor()\n cursor.execute(query, first, next, classType, unavailable)\n for row in cursor:\n day = row.day.toordinal()\n if not available.has_key(day):\n available[day] = {}\n if row.status != unavailable:\n if not available[day].has_key(row.status):\n available[day][row.status] = []\n userInfo = user(row) #TODO: don't duplicate storage of this\n available[day][row.status].append(userInfo)\n assigned = row.assigned\n if assigned == None:\n assigned = 0\n else:\n assigned = int(row.assigned)\n if assigned: #treat assigned as a pseudo status\n if not available[day].has_key(\"assigned\"):\n available[day][\"assigned\"] = []\n userInfo = user(row) #TODO: don't duplicate storage of this\n available[day][\"assigned\"].append(userInfo) \n cursor.close()\n return available\n\n def getAvailability(self, userid, first, next, classType):\n availability = {}\n query = 'SELECT day, status FROM getavailability(?, ?, ?, ?)'\n cursor = self._conn.cursor()\n cursor.execute(query, userid, first, next, classType)\n for row in cursor:\n availability[row.day.toordinal()]=row.status\n cursor.close()\n return availability\n\n def updateAvailability(self, userid, date, status, classType):\n query = 'SELECT updateavailability(?, ?, ?, ?)'\n cursor = self._conn.cursor()\n cursor.execute(query, userid, date, status, classType)\n row = cursor.fetchone()\n cursor.close()\n self._conn.commit()\n if row.updateavailability == \"0\": return False\n return True\n \n\n def getHosts(self, first, next):\n hosts = {}\n query = 'SELECT day, hosts FROM gethosts(?, ?)'\n cursor = self._conn.cursor()\n cursor.execute(query, first, next)\n cursor.close()\n return hosts\n\n def updateHosts(self, date, hosts):\n query = 'SELECT updatehosts(?, ?)'\n cursor = self._conn.cursor()\n cursor.execute(query, date, hosts)\n cursor.close()\n self._conn.commit()\n \n def getUnavailableStatus(self, classType):\n query = 'SELECT id FROM getunavailablestatus(?)'\n cursor = self._conn.cursor()\n cursor.execute(query, classType)\n row = cursor.fetchone()\n value = row.id\n cursor.close()\n return value\n \n def getClassName(self, classType):\n query = 'SELECT name FROM getclassinfo(?)'\n cursor = self._conn.cursor()\n cursor.execute(query, classType)\n row = cursor.fetchone()\n value = row.name\n cursor.close()\n return value\n \n def getUser(self, username):\n userInfo = None\n query = 'SELECT * FROM getuser(?)'\n cursor = self._conn.cursor()\n cursor.execute(query, username)\n row = cursor.fetchone()\n if row != None: userInfo = user(row)\n cursor.close()\n return userInfo\n\n","sub_path":"src/web/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":4842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"460074367","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nn = 10\nT_north = 30\nT_south = 20\nT_east = 10\nT_west = 10\n\n\n# Initializing boundary value matrix to zero\nboundaries = np.zeros((n, n))\n\n# Setting edge values\nfor i in range(n):\n boundaries[0][i] = T_south\n boundaries[i][0] = T_west\n boundaries[n-1][i] = T_north\n boundaries[i][n-1] = T_east\n\n# Setting corner values to avg. of edges\nboundaries[0][0] = (boundaries[0][1] + boundaries[1][0]) / 2\nboundaries[0][n-1] = (boundaries[0][n-2] + boundaries[1][n-1]) / 2\nboundaries[n-1][0] = (boundaries[n-2][0] + boundaries[n-1][1]) / 2\nboundaries[n-1][n-1] = (boundaries[n-1][n-2] + boundaries[n-2][n-1]) / 2\n\n\n# Constructing 2D difference matrix T applying the 5-point scheme\n# and using left-to-right equation numbering\nA = np.zeros((n, n)) # 1D Difference matrix\nfor i in range(n):\n for j in range(n):\n if i == j and i < n-1 and j < n-1:\n A[i][j] = 2\n A[i][j+1] = -1\n A[i+1][j] = -1\n if i == j:\n A[i][j] = 2\n\nI = np.identity(n) # identity matrix\nT = np.kron(A, I) + np.kron(I, A) # 2D Difference matrix\n\n\n# Right side b matrix, initiall zeros\nb = np.zeros(n**2)\n\n\n# Applying boundary conditions by manipulating the transformation\n# matrix and right-side b-vector.\nfor i in range(n):\n for j in range(n):\n if i == 0 or j == 0 or i == (n-1) or j == (n-1):\n b[i*n+j] = boundaries[i][j]\n T[i*n+j] = np.zeros(n*n)\n T[i*n+j][i*n+j] = 1\n\n\n# Solving the system\nu = np.linalg.solve(T, b)\n\n\n# Map the n*n vector onto a n x n 2D grid by reversing the\n# left-to-right equation numbering.\ntemps = np.zeros((n, n))\nfor i in range(n):\n for j in range(n):\n temps[i][j] = u[i*n+j]\n\n\n#Visualitzation of results\nx = np.arange(0, 1, n**(-1))\ny = np.arange(0, 1, n**(-1))\nfig = plt.figure(1)\nCS2 = plt.contourf(x, y, temps, levels=np.arange(10, 30, 0.1))\ncb = plt.colorbar(orientation='vertical')\n\nfig.savefig('temps.pdf')\n\nplt.show()\n","sub_path":"exercises/pex3/code/tensorlaplace.py","file_name":"tensorlaplace.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"365987622","text":"#-*- coding:utf-8 -*-\n#!python3\n#定位位置\nimport webbrowser,sys,pyperclip\nif len(sys.argv)>1:\n address=' '.capitalizejoin(sys.argv[1:])\nelse:\n address=pyperclip.paste()\nwebbrowser.open('http://www.google.com/maps/place/'+address)\nprint('1*'*20)\n\n#用requests从web下载文件\nimport requests\n#用requests.get()下载一个网页\n#status_code属性返回状态\nres=requests.get('http://www.sina.com.cn')\nprint(res.status_code)\nprint('2*'*20)\n\n#raise_for_status()方法下载错误会异常,下载正确什么也不做\n\n#iter_content()方法循环返回一段内容,都是bytes类型,可以指定包含字节数\n\n#用beautifulsoup处理html\nimport bs4\ncontent=bs4.BeautifulSoup(res.text,\"html.parser\")\nprint('3*'*20)\n\n#sellect()方法的选择器\n'''\nsoup.select('div')所有名为
的元素\nsoup.select('#author')带有id属性为author的元素\nsoup.select('.notice')所有使用CSS class属性名为notice的元素\nsoup.select('div span')所有在
元素之内的元素\nsoup.select('div>span')所���直接在
元素之内的元素,中间没有其他元素\nsoup.select('input[name]')所有名为,并有一个name属性,其值无所谓的元素\nsoup.select('input[type=\"button\"]')所有名为并有一个type属性,其值为button的元素\n'''\n#getText()方法可以取得内容\nelem=content.select('p')\nstr(elem[0])\nprint(elem[0].getText())\nprint('4*'*20)\n","sub_path":"从web抓取信息.py","file_name":"从web抓取信息.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"507384355","text":"import os\nimport json\nimport random\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, HiddenField, RadioField\nfrom wtforms.validators import InputRequired\nfrom flask import Flask, render_template, request\n\n# Импортируем данные для передачи их в шаблон\nimport data\n\nclass BookingForm(FlaskForm):\n name = StringField('name', [InputRequired()])\n phone = StringField('phone', [InputRequired()])\n time = HiddenField('time')\n day = HiddenField('day')\n\nclass RequestForm(FlaskForm):\n lesson = RadioField('lesson', choices=[('1', 'Для путешествий'), ('2', 'Для школы'), ('3', 'Для работы'), ('4','Для переезда')])\n time_has = RadioField('time_has', choices=[('1', '1-2 часа в неделю'),('2','3-5 часов в неделю'),('3', '5-7 часов в неделю'),('4','7-10 часов в неделю')])\n name = StringField('name', [InputRequired()])\n phone = StringField('phone', [InputRequired()])\n\n\napp = Flask(__name__)\nSECRET_KEY = os.urandom(32)\napp.config['SECRET_KEY'] = SECRET_KEY\n\n\n@app.route('/')\ndef index():\n teachers = []\n for i in range(0,6):\n teachers.append(random.choice(data.teachers))\n return render_template('index.html', teachers=teachers)\n\n\n@app.route('/goal/')\ndef goal(type):\n teachers = []\n for v in data.teachers:\n if type in v['goals']:\n teachers.append(v)\n\n return render_template('goal.html', teachers=teachers, goal=data.goals[type])\n\n\n@app.route('/profile/')\ndef profile(id):\n # формируем данные о преподавателе\n goals = []\n for t in data.teachers:\n if t['id'] == id:\n teacher = t\n for g in t['goals']:\n goals.append(data.goals[g])\n return render_template('profile.html', teacher=teacher, goals=goals)\n return 'Преподаватель не найден'\n\n\n@app.route('/booking///')\ndef booking(id, day, time):\n for t in data.teachers:\n if t['id'] == id:\n teacher = t\n break\n\n form = BookingForm(time=time, day=day)\n\n return render_template('booking.html',\n teacher=teacher,\n time=time,\n weekday=data.weekday[day],\n form=form)\n\n@app.route('/booking_done', methods=[\"GET\",\"POST\"])\ndef booking_done():\n form = BookingForm()\n # Обновляем json файл с заявками\n if request.method == 'POST':\n append_dict = {\n 'name': form.name.data,\n 'phone': form.phone.data,\n 'time': form.time.data,\n 'day': data.weekday[form.day.data]\n }\n\n insert_dict = {}\n key = hash(str(form.name.data)+'\\\\'+str(form.phone.data)+'\\\\'+str(form.time.data)+'\\\\'+str(data.weekday[form.day.data]))\n insert_dict[key] = append_dict\n\n with open('booking.json') as f:\n book = json.load(f)\n book.update(insert_dict)\n\n with open('booking.json', 'w') as f:\n json.dump(book, f)\n return render_template('booking_done.html', append_dict=append_dict)\n else:\n return 'Ошибка'\n\n@app.route('/request')\ndef request_action():\n form = RequestForm()\n return render_template('request.html', form=form)\n\n@app.route('/request_done', methods=[\"GET\",\"POST\"])\ndef request_done():\n form = RequestForm()\n if request.method == 'POST':\n value = form.lesson.data\n choices = dict(form.lesson.choices)\n lesson = choices[value]\n\n value = form.time_has.data\n choices = dict(form.time_has.choices)\n time_has = choices[value]\n\n append_dict = {\n 'name': form.name.data,\n 'phone': form.phone.data,\n 'lesson': lesson,\n 'time_has': time_has\n }\n\n\n insert_dict = {}\n key = hash(str(form.name.data)+'\\\\'+str(form.phone.data)+'\\\\'+str(lesson)+'\\\\'+str(time_has))\n insert_dict[key] = append_dict\n\n with open('request.json') as f:\n req = json.load(f)\n req.update(insert_dict)\n with open('request.json', 'w') as f:\n json.dump(req, f)\n\n return render_template('request_done.html', append_dict=append_dict)\n else:\n return 'Ошибка'\n\nif __name__ == '__main__':\n app.run('0.0.0.0',7000)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"411642784","text":"from __future__ import division\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport basic_hiresmag as hdr\r\nimport mytools as my\r\nimport max_likelihood_estimate as mle\r\nreload(mle)\r\nimport mjtools as mj\r\nfrom scipy.integrate import cumtrapz\r\nfrom scipy.optimize import curve_fit\r\nfrom scipy import interpolate\r\nimport matplotlib.gridspec as gridspec\r\nfrom matplotlib.ticker import AutoMinorLocator\r\n\r\n#from matplotlib.ticker import MultipleLocator, FormatStrFormatter\r\n\r\nminorLocator = AutoMinorLocator(10) # leads to a single minor tick\r\n#ml = MultipleLocator(5)\r\n#minorLocator = MultipleLocator(10)\r\n\r\ngs = gridspec.GridSpec(4,1)\r\nplt.rc('text', usetex=True)\r\nplt.rcParams['text.latex.preamble']=[r'\\boldmath']\r\n\r\n \r\nday = '072617'#'101918'\r\nshot =75\r\n\r\nfrange1= [1.2e5, 1.6e6]\r\ntext_box_x = [1e6, 5e5, 4.5e5]\r\ntext_box_y = [1e-8, 1e-6, 5e-6]\r\n\r\nt0 = 40\r\ntf = 70\r\npath = 'Data\\\\2017\\\\'+day+'\\\\'+day+'-Analysed\\\\'\r\naxis = ['x', 'y', 'z']\r\ncolor = ['blue', 'red', 'green']\r\n\r\ndata=hdr.getMjMagData(day+'r'+str(shot))#x, y and z components of the 15th probe\r\n ##### changing from 15x, 15y and 15z to 6x, 6y and 6z\r\nB = np.zeros([3, len(data.time[:-1])])\r\nB[0,:] =cumtrapz(data.unCalibData[0,14,:]-mj.get_gaussian_moving_avg(data.time, data.unCalibData[0,14,:], 15), data.time)/7.63e-4\r\nB[1,:] =cumtrapz(data.unCalibData[1,14,:]-mj.get_gaussian_moving_avg(data.time, data.unCalibData[1,14,:], 15), data.time)/8.06e-4\r\nB[2,:]=cumtrapz(data.unCalibData[2,2,:]-mj.get_gaussian_moving_avg(data.time, data.unCalibData[2,2,:], 15), data.time)/6.76e-4\r\n# B[0,:]=cumtrapz(data.unCalibData[0,5,:]-mj.get_gaussian_moving_avg(data.time, data.unCalibData[0,5,:], 15), data.time)/7.63e-4\r\n# B[1,:]=cumtrapz(data.unCalibData[1,5,:]-mj.get_gaussian_moving_avg(data.time, data.unCalibData[1,5,:], 15), data.time)/8.06e-4\r\n# B[2,:]=cumtrapz(data.unCalibData[2,1,:]-mj.get_gaussian_moving_avg(data.time, data.unCalibData[2,1,:], 15), data.time)/6.76e-4\r\ntimeB=data.time-data.time[0]-2\r\ntimeB= timeB[:-1]\r\n \r\nmodB=np.sqrt((B[0,:]**2)+(B[1,:]**2)+(B[2,:]**2))\r\n\r\nplt.close('all')\r\nfig=plt.figure(num=1,figsize=(8.5,6),facecolor='w',edgecolor='k')#, dpi=600)\r\nfig.subplots_adjust(top=0.95, bottom=0.11, left = 0.14, right=0.96, hspace=0.2)\r\nax1=plt.subplot(1,1,1)\r\nfor i in range(3):\r\n plt.plot(timeB, B[i,:], lw =1, color = color[i], label = 'B$_{%s}$'%axis[i])\r\n\r\nplt.plot(timeB, modB,color='k', lw =2, label = '$|B|$')\r\nplt.legend().draggable()\r\nplt.ylabel(r'$|B|\\ (G)$',fontsize=20, weight='bold')\r\n#ax.set_xticklabels([])\r\n#ax.xaxis.set_tick_params(labeltop='on',labelsize=20)\r\nplt.setp(ax1.spines.values(), linewidth=2)\r\nax1.get_yaxis().set_label_coords(-0.11,0.6)\r\nax1.tick_params(axis='both', direction='in', length=7, width =2, labelsize = 20) \r\nax1.tick_params(axis='x', which='minor', direction='in', length=5, width =1)\r\nax1.xaxis.set_minor_locator(minorLocator)\r\nplt.xlim(20,100)\r\nplt.xlabel(r'$Time\\ (\\mu s)$',fontsize=20, weight='bold')\r\n\r\nfig2=plt.figure(num=2,figsize=(8.5,6),facecolor='w',edgecolor='k')#, dpi=600)\r\n#plt.clf()\r\nfig2.subplots_adjust(top=0.95, bottom=0.11, left = 0.14, right=0.96, hspace=0.2)\r\nax2=plt.subplot(1,1,1)\r\ntotal_spec = np.zeros([])\r\nfor i in range(3):\r\n freq,freq2,comp,spectra,mag,phase2,cos_phase,dt = my.windowed_fft(B[i,:]-np.mean(B[i,:]), timeB*1e-6, window= 'hanning')\r\n plt.loglog(freq,spectra, color = color[i], linewidth=1, label='B$_{%s, 15}$'%axis[i])\r\n total_spec = total_spec + spectra\r\nplt.loglog(freq,total_spec, color = 'magenta', linewidth=2, label='B$_{total}$')\r\n# plt.legend(fontsize = 16).draggable() \r\nlegend = plt.legend(fontsize = 20, loc = 'lower left')#.draggable()\r\nlegend.get_frame().set_facecolor('none') # makes the legend background blank (i.e. transparent, not white) \r\nlegend.get_frame().set_linewidth(0.0) # removes only the border of the box of the legend\r\n\r\nax2 = plt.gca()\r\nfindex1, freq1 = my.fix_bounds(frange1, freq)\r\n# max_alpha1,alpha1,L_vals1,sigma1 = mle.mle_werr(spectra,freq,findex1[0],findex1[-1])\r\n# func = (freq**(-max_alpha1))\r\n# scale_dat1 = spectra[findex1[-1]]\r\nmax_alpha1,alpha1,L_vals1,sigma1 = mle.mle_werr(total_spec,freq,findex1[0],findex1[-1])\r\nfunc = (freq**(-max_alpha1))\r\nscale_dat1 = total_spec[findex1[-1]]\r\nscale_fit1 = func[findex1[-1]]\r\nratio1 = scale_dat1/scale_fit1\r\nplt.loglog(freq1,50*ratio1*func[findex1],linestyle='dotted',color= 'black',linewidth=2)#,label='Fixed Range Fit: -'+str(max_alpha) )\r\nsigma1 = np.round(sigma1,decimals=2)\r\nplt.text(text_box_x[2], text_box_y[2],r'$Index = - $ '+str(max_alpha1),fontsize=16,color= 'k')\r\n# plt.text(text_box_x[1], text_box_y[1],r'$Slope = - 11/3$',fontsize=12,color= 'k')\r\n\r\nplt.xlim([6e3, 3e7])\r\nplt.ylim([1e-19, 2e-2])\r\nplt.title(day+'r'+str(shot)+': Power spectrum for B field components')\r\nplt.ylabel('Power',fontsize=20)#, weight='bold')\r\nplt.xlabel('Frequency (Hz)',fontsize=20)#, weight='bold')\r\n\r\nplt.tick_params(axis='both', direction='in', length=7, width =2, labelsize = 20) \r\nax2.tick_params(axis='both', which='minor', direction='in', length=5, width =1)\r\nplt.setp(ax2.spines.values(), linewidth=2)#changing the axis linewidth\r\n\r\n########### PDF of Increments stuff #############\r\nT_ini = 2700\r\nT_fini = 4700\r\n\r\nt1 = 10\r\nt2 = 65\r\nt3 = 130\r\nt4 = 500\r\nt5 = 1000\r\nn1, bins1, list1 = plt.hist(data.unCalibData[0,14,T_ini+t1:T_fini+t1]-data.unCalibData[0,14,T_ini:T_fini], 100)\r\nn2, bins2, list2 = plt.hist(data.unCalibData[0,14,T_ini+t2:T_fini+t2]-data.unCalibData[0,14,T_ini:T_fini], 100)\r\nn3, bins3, list3 = plt.hist(data.unCalibData[0,14,T_ini+t3:T_fini+t3]-data.unCalibData[0,14,T_ini:T_fini], 100)\r\nn4, bins4, list4 = plt.hist(data.unCalibData[0,14,T_ini+t4:T_fini+t4]-data.unCalibData[0,14,T_ini:T_fini], 100)\r\nn5, bins5, list5 = plt.hist(data.unCalibData[0,14,T_ini+t5:T_fini+t5]-data.unCalibData[0,14,T_ini:T_fini], 100)\r\n\r\n# sigma1 = np.std(data.unCalibData[0,14,2700+t1:4700+t1]-data.unCalibData[0,14,2700:4700])\r\n# sigma2 = np.std(data.unCalibData[0,14,2700+t2:4700+t2]-data.unCalibData[0,14,2700:4700])\r\n# sigma3 = np.std(data.unCalibData[0,14,2700+t3:4700+t3]-data.unCalibData[0,14,2700:4700])\r\n# sigma4 = np.std(data.unCalibData[0,14,2700+t4:4700+t4]-data.unCalibData[0,14,2700:4700])\r\n# sigma5 = np.std(data.unCalibData[0,14,2700+t5:4700+t5]-data.unCalibData[0,14,2700:4700])\r\nsigma1 = np.std(data.unCalibData[0,14,T_ini :T_fini])\r\nsigma2 = np.std(data.unCalibData[0,14,T_ini :T_fini])\r\nsigma3 = np.std(data.unCalibData[0,14,T_ini :T_fini])\r\nsigma4 = np.std(data.unCalibData[0,14,T_ini :T_fini])\r\nsigma5 = np.std(data.unCalibData[0,14,T_ini :T_fini])\r\na = 1\r\nb = 10\r\nc = 100\r\nd = 1000\r\ne = 10000\r\nfig3=plt.figure(num=3,figsize=(8.5,10),facecolor='w',edgecolor='k')#, dpi=600)\r\nfig3.subplots_adjust(top=0.95, bottom=0.11, left = 0.14, right=0.96, hspace=0.2)\r\nax3=plt.subplot(1,1,1)\r\n\r\nplt.scatter(bins1[:-1]/sigma1, (n1+0.1)*a,marker ='o', color = 'blue', linewidth = 2, label = '$\\Delta t = %0.2f \\mu s$'%(timeB[t1]-timeB[0]))\r\nplt.scatter(bins2[:-1]/sigma2, (n2+0.1)*b,marker = '^', color = 'r', linewidth = 2, label = '$\\Delta t = %0.1f \\mu s$'%(timeB[t2]-timeB[0]))\r\nplt.scatter(bins3[:-1]/sigma3, (n3+0.1)*c,marker ='v', color = 'magenta', linewidth = 2, label = '$\\Delta t = %0.1f \\mu s$'%(timeB[t3]-timeB[0]))\r\nplt.scatter(bins4[:-1]/sigma4, (n4+0.1)*d,marker ='d', color = 'green', linewidth = 2, label = '$\\Delta t = %0.1f \\mu s$'%(timeB[t4]-timeB[0]))\r\nplt.scatter(bins5[:-1]/sigma5, (n5+0.1)*e,marker ='s', color = 'dodgerblue', linewidth = 2, label = '$\\Delta t = %0.1f \\mu s$'%(timeB[t5]-timeB[0]))\r\n\r\nplt.plot(bins1[:-1]/sigma1, (n1+0.1)*a, '--',color = 'blue', linewidth = 1)#, label = '$\\Delta t = $%0.1f'%(timeB[t1]-timeB[0]))\r\nplt.plot(bins2[:-1]/sigma2, (n2+0.1)*b,'--', color = 'r', linewidth = 1)#, label = '$\\Delta t = $%0.1f'%(timeB[t2]-timeB[0]))\r\nplt.plot(bins3[:-1]/sigma3, (n3+0.1)*c,'--', color = 'magenta', linewidth = 1)#, label = '$\\Delta t = $%0.1f'%(timeB[t3]-timeB[0]))\r\nplt.plot(bins4[:-1]/sigma4, (n4+0.1)*d,'--', color = 'green', linewidth = 1)#, label = '$\\Delta t = $%0.1f'%(timeB[t4]-timeB[0]))\r\nplt.plot(bins5[:-1]/sigma5, (n5+0.1)*e,'--', color = 'dodgerblue', linewidth = 1)#, label = '$\\Delta t = $%0.1f'%(timeB[t5]-timeB[0]))\r\n\r\n#### exponential fitting for finding efolding time ####\r\ndef Gauss(x, a, x0, sigma):\r\n return a * np.exp(-(x - x0)**2 / (2 * sigma**2))\r\n\r\nx1 = bins1[:-1]/sigma2\r\ny1 = (n1+0.1)*b\r\n\r\nmean1 = sum(x1 * y1) * 1. / sum(y1) #note this correction\r\nsigma1 = np.sqrt(sum(y1 * (x1 - mean1)**2) / sum(y1)) #note this correction\r\n\r\npopt1,pcov1 = curve_fit(Gauss, x1, y1, p0=[max(y1), mean1, sigma1])\r\n\r\n# #plt.plot(t_corr, func(x, *popt), 'b', linewidth=2, label=\"%0.1fexp(-x/%0.2f)+%0.2f\"%(popt[0], popt[1], popt[2]))\r\nplt.semilogy(x1, 0.1*Gauss(x1, *popt1), 'blue', linewidth=2)#, label=\"$\\sigma = $%0.2f\"%(popt1[2]))\r\n \r\nx2 = bins2[:-1]/sigma2\r\ny2 = (n2+0.1)*b\r\n\r\nmean2 = sum(x2 * y2) * 1. / sum(y2) #note this correction\r\nsigma2 = np.sqrt(sum(y2 * (x2 - mean2)**2) / sum(y2)) #note this correction\r\n\r\npopt2,pcov2 = curve_fit(Gauss, x2, y2, p0=[max(y2), mean2, sigma2])\r\n\r\n# #plt.plot(t_corr, func(x, *popt), 'b', linewidth=2, label=\"%0.1fexp(-x/%0.2f)+%0.2f\"%(popt[0], popt[1], popt[2]))\r\nplt.semilogy(x2, Gauss(x2, *popt2), 'r', linewidth=2)#, label=\"$\\sigma = $%0.2f\"%(popt2[2]))\r\n\r\nax3.text(0.87, 0.8, 'X 1/10000', transform=ax3.transAxes, color = 'dodgerblue', fontsize=14)\r\nax3.text(0.87, 0.67, '1/1000', transform=ax3.transAxes, color = 'green', fontsize=14)\r\nax3.text(0.8, 0.5, '1/100', transform=ax3.transAxes, color = 'magenta', fontsize=14)\r\nax3.text(0.87, 0.25, '1/10', transform=ax3.transAxes, color = 'red', fontsize=14)\r\n\r\nlegend = plt.legend(fontsize = 14, loc = 'lower left')#.draggable()\r\nlegend.get_frame().set_facecolor('none') # makes the legend background blank (i.e. transparent, not white) \r\nlegend.get_frame().set_linewidth(0.0) # removes only the border of the box of the legend\r\n\r\nax3 = fig3.gca()\r\nax3.set_yscale('log')\r\nax3.xaxis.set_minor_locator(minorLocator)\r\nax3.tick_params(axis='both', direction='in', length=7, width =2, labelsize = 20)\r\nax3.tick_params(axis='both', which='minor', direction='in', length=5, width =1)\r\nplt.setp(ax3.spines.values(), linewidth=2)\r\nax3.set_title('072618r75: PDF of Increments for different $\\Delta t$', fontsize = 18)\r\nax3.set_xlabel('$\\Delta \\dot B / \\sigma _{\\dot B}$', fontsize = 20)\r\nax3.set_ylabel('PDF', fontsize = 20)\r\nplt.ylim(8e-2, 3e6)\r\nplt.show() \r\n\r\n\r\n################ Fluctuation studies ###########\r\nfig4=plt.figure(num=4,figsize=(8.5,6),facecolor='w',edgecolor='k')#, dpi=600)\r\nfig4.subplots_adjust(top=0.95, bottom=0.11, left = 0.14, right=0.96, hspace=0.2)\r\nax4=plt.subplot(1,1,1)\r\n\r\nlength_x = np.load('New_Arrays_corrected\\\\072617\\\\75_wavelet_x.npy') \r\nlength_y = np.load('New_Arrays_corrected\\\\072617\\\\75_wavelet_y.npy') \r\n\r\ntime_x = np.load('New_Arrays_corrected\\\\072617\\\\75_wavelet_tx.npy') \r\ntime_y = np.load('New_Arrays_corrected\\\\072617\\\\75_wavelet_ty.npy') \r\n\r\ntime = np.load('New_Arrays_corrected\\\\072617\\\\75_time.npy') \r\nn = np.load('New_Arrays_corrected\\\\072617\\\\75_n.npy') \r\nT = np.load('New_Arrays_corrected\\\\072617\\\\75_T.npy') \r\n\r\nmy.lineplot(4,time_x, length_x, '-', 'Time ($\\mu$s)', 'Length', 'Length in time', 'l$_x$(t)', (30, 80), (10, 40), 'r', \r\n 20, 2, '072617r75_Length_in_Time.png', 'o', scatter = False, horzline = False)#, saveFig=False)\r\n\r\nN = 10\r\nBmx, Bmy, Bmz= my.three_moving_avg(B[0,:], B[1,:], B[2,:], N)\r\nBrmsx, Brmsy, Brmsz = my.three_moving_avg((B[0,:]-Bmx)**2, (B[1,:]-Bmy)**2, (B[2,:]-Bmz)**2, N)\r\nax4=ax4.twinx()#make second y axis (while duplicating/twin x)\r\nax4.plot(timeB[2130:5300], np.sqrt(Brmsx[2130:5300]), linewidth =2, color = 'green', label = 'B$_x$ fluctuations')\r\nlegend = plt.legend(fontsize = 14, loc = 'lower left').draggable()\r\nax4.tick_params(axis='both', direction='in', length=7, width =2, labelsize = 20)\r\nax4.tick_params(axis='both', which='minor', direction='in', length=5, width =1)\r\nplt.setp(ax4.spines.values(), linewidth=2)\r\nax4.set_ylabel('B$_{rms}$ fluctuations', fontsize = 20)\r\n\r\n\r\n\r\nfig5=plt.figure(num=5,figsize=(8.5,6),facecolor='w',edgecolor='k')#, dpi=600)\r\nfig5.subplots_adjust(top=0.95, bottom=0.11, left = 0.14, right=0.96, hspace=0.2)\r\nax5= plt.subplot(1,1,1)\r\nmy.lineplot(5,time_y, length_y, '-', 'Time ($\\mu$s)', 'Length', '072617r75', 'l$_y$(t)', (30, 80), (10, 40), 'blue', \r\n 20, 2, '072617r75_Length_in_Time.png', 'o', scatter = False, horzline = False)#, saveFig=False)\r\n\r\nax5=ax5.twinx()#make second y axis (while duplicating/twin x)\r\nax5.plot(timeB[2130:5300], np.sqrt(Brmsy[2130:5300]), linewidth =2, color = 'orange', label = 'B$_y$ fluctuations')\r\nlegend = plt.legend(fontsize = 14, loc = 'lower left').draggable()\r\nax5.tick_params(axis='both', direction='in', length=7, width =2, labelsize = 20)\r\nax5.tick_params(axis='both', which='minor', direction='in', length=5, width =1)\r\nplt.setp(ax5.spines.values(), linewidth=2)\r\nax5.set_ylabel('B$_{rms}$ fluctuations', fontsize = 20)\r\n\r\n######### Plot of np.sqrt(Brmsx[2130:5300]) versus llength_x\r\n# t_ini = time_x[0]\r\n# t_fini = time_x[-1]\r\n# t_bounds1 = [time_x[0], time_x[-1]]\r\nt_bounds1 = [time_x[0], 70]\r\nt_bounds2 = [65.15, 66.65]\r\ntindex1, t_inpo1 = my.fix_bounds(t_bounds1,timeB)\r\ntindex2, t_inpo2 = my.fix_bounds(t_bounds2,timeB)\r\n\r\nsamplingFrequency = 100 #Use frequency at which B is sampled 65MHz\r\nnumPoints = int((time_x[-1] - time_x[0])*samplingFrequency) #len(tindex)#\r\nTIME1 = np.linspace(t_inpo1[0],t_inpo1[-1],numPoints)\r\nTIME2 = np.linspace(t_inpo2[0],t_inpo2[-1],numPoints)\r\n\r\nleng_x = interpolate.interp1d(time_x,length_x,kind = 'slinear')\r\n# dens = interpolate.interp1d(time, n, kind = 'slinear')\r\n# temperature = interpolate.interp1d(time, T, kind = 'slinear')(TIME)\r\ndensity = interpolate.interp1d(time, n, fill_value=\"extrapolate\")\r\ntemperature = interpolate.interp1d(time, T, fill_value=\"extrapolate\")\r\nBx_rms = interpolate.interp1d(timeB,np.sqrt(np.array(Brmsx)),kind = 'slinear')\r\n\r\n# density = dens(TIME)\r\n\r\nfig6=plt.figure(num=6,figsize=(8.5,10),facecolor='w',edgecolor='k')#, dpi=600)\r\nfig6.subplots_adjust(top=0.95, bottom=0.11, left = 0.14, right=0.96, hspace=0.2)\r\nax61= plt.subplot(211)\r\nplt.plot(leng_x(TIME1), Bx_rms(TIME1), color = 'blue', linewidth = 2)\r\nplt.plot(leng_x(TIME2), Bx_rms(TIME2), color = 'red', linewidth = 2)\r\nplt.title(day+'r'+str(shot)+': Averaging of %0.2f $\\mu$s for rms determination'%(timeB[N]-timeB[0]), fontsize = 16)\r\nax61.tick_params(axis='both', direction='in', length=7, width =2, labelsize = 20)\r\nax61.tick_params(axis='both', which='minor', direction='in', length=5, width =1)\r\nplt.setp(ax61.spines.values(), linewidth=2)\r\nax61.set_ylabel('$\\delta$B$_{rms}$ (Gauss)', fontsize = 20)\r\nplt.xlabel('Length (cm)', fontsize = 20)\r\n\r\n\r\nax62= plt.subplot(212)\r\npressure1 = density(TIME1)*temperature(TIME1)\r\npressure2 = density(TIME2)*temperature(TIME2)\r\nplt.plot(pressure1, Bx_rms(TIME1), color = 'blue', linewidth = 2)\r\nplt.plot(pressure2, Bx_rms(TIME2), color = 'red', linewidth = 2)\r\nax62.tick_params(axis='both', direction='in', length=7, width =2, labelsize = 20)\r\nax62.tick_params(axis='both', which='minor', direction='in', length=5, width =1)\r\nplt.setp(ax62.spines.values(), linewidth=2)\r\nax62.set_ylabel('$\\delta$B$_{rms}$ (Gauss)', fontsize = 20)\r\nplt.xlabel('Pressure (kPa)', fontsize = 20)\r\n\r\nplt.show()","sub_path":"B_fluctuation_analysis_in_SFC_.py","file_name":"B_fluctuation_analysis_in_SFC_.py","file_ext":"py","file_size_in_byte":15363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"427288542","text":"from flask import request, Response\nfrom json import dumps\nfrom functools import wraps\n\ndef token_required(f):\n\t@wraps(f)\n\tdef wrapper(*args, **kwargs):\n\t\tif \"token\" in request.headers and \"username\" in request.headers:\n\t\t\ttoken = request.headers['token']\n\t\t\tusername = request.headers['username']\n\t\t\ttry:\n\t\t\t\tdecode(token, username)\n\t\t\t\treturn f(*args, **kwargs)\n\t\t\texcept:\n\t\t\t\terrorObj = {\n\t\t\t\t\t\"status\": \"failure\",\n\t\t\t\t\t\"message\": \"Invalid access, please sign-in first to view this page.\"\n\t\t\t\t}\n\t\t\t\treturn Response(dumps(errorObj), 401, mimetype=\"application/json\")\n\t\telse:\n\t\t\terrorObj = {\n\t\t\t\t\"status\": \"failure\",\n\t\t\t\t\"message\": \"Invalid access, please sign-in first to view this page.\"\n\t\t\t}\n\t\t\treturn Response(dumps(errorObj), 401, mimetype=\"application/json\")\n\treturn wrapper\n","sub_path":"decorators/token_validator.py","file_name":"token_validator.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"380577644","text":"import json\nimport os\n\nfrom core.managers.filemanager import FileManager\n\nfrom core.entities.tile import Tile\nfrom core.entities.tilemap import TileMap\nfrom core.entities.building import Building\nfrom core.entities.unit import Unit\n\nclass MapLoader:\n\t_initialized = False\n\t_map = None\n\n\tdef __init__(self, map_name):\n\t\t# load map file into json_map json dict\n\t\tmap_path = FileManager.mod_path() + \"base/maps/\" + map_name + \".json\"\n\t\tmap_string = FileManager.read_file(map_path)\n\t\tif (map_string == \"\"):\n\t\t\treturn None\n\t\tjson_map = json.loads(map_string)\n\n\t\t# create and fill TileMap\n\t\tself._map = TileMap()\n\t\tself._map._name = map_name\n\t\tself.fill_map_properties(json_map)\n\t\tself.fill_map_tiles(json_map)\n\t\tself.fill_buildings(json_map)\n\t\tself._initialized = True\n\n\t# fill map properties for self._map\n\tdef fill_map_properties(self, json_map):\n\t\tself._map.name = json_map[\"name\"]\n\t\tself._map.name_de = json_map[\"name_de\"]\n\t\tself._map.size_x = int(json_map[\"size\"].split(\"x\")[0])\n\t\tself._map.size_y = int(json_map[\"size\"].split(\"x\")[1])\n\n\t# fill tiles for self._map\n\tdef fill_map_tiles(self, json_map):\n\t\t# get tile_map string and real map size\n\t\trow_array = json_map[\"tile_map\"]\n\t\tsize_x = self._map.size_x\n\t\tsize_y = self._map.size_y\n\n\t\t# add _map.tiles and _map.tile_at\n\t\tcursor_x = 0\n\t\tcursor_y = 0\n\t\twhile cursor_y < size_y:\n\t\t\trow = row_array[cursor_y]\n\t\t\twhile cursor_x < size_x:\n\t\t\t\tpos_x = cursor_x\n\t\t\t\tpos_y = cursor_y\n\t\t\t\tlandscape = row[cursor_x]\n\t\t\t\ttile = Tile(pos_x, pos_y, landscape)\n\t\t\t\tself._map.add_tile(tile)\n\t\t\t\tcursor_x += 1\n\t\t\tcursor_x = 0\n\t\t\tcursor_y += 1\n\n\tdef fill_buildings(self, json_map):\n\t\tbuildings = json_map[\"buildings\"]\n\t\tfor bld_row in buildings:\n\t\t\tbld_data = bld_row.split()\n\t\t\t# create new building with building name (bld_data[1])\n\t\t\tbld = Building(bld_data[1])\n\t\t\tbld.playerId = bld_data[0]\n\t\t\t# set building position (x=bld_data[2]; y=bld_data[3])\n\t\t\tbld.set_position((bld_data[2], bld_data[3]))\n\t\tself._map.buildings = buildings\n\n\t# returns the loaded map\n\tdef get_map(self):\n\t\tif self._initialized:\n\t\t\treturn self._map\n\t\telse:\n\t\t\tprint (\"Error: map is null!\")\n\t\t\treturn None\n","sub_path":"core/tools/maploader.py","file_name":"maploader.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"85696896","text":"import hashlib\nimport logging\nimport os\nimport sys\nimport time\nfrom threading import Thread\n\n# append project dir to python path\nfrom labchain.network import networking\nfrom labchain.datastructure.transaction import Transaction\nfrom tests.test_account import MockCryptoHelper\nfrom labchain.network.networking import ServerNetworkInterface, JsonRpcClient\n\nproject_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))\nif project_dir not in sys.path:\n sys.path.append(project_dir)\n\n# change to DEBUG to see more output\nLOG_LEVEL = logging.INFO\n# change the polling interval\nPOLL_INTERVAL = 10\n\nTRANSACTION = Transaction('some sender', 'some_receiver', 'some_payload', 'some_signature')\nRECEIVED_TRANSACTIONS = {}\n\n\ndef get_transaction(transaction_hash):\n if transaction_hash in RECEIVED_TRANSACTIONS:\n return RECEIVED_TRANSACTIONS[transaction_hash], 'fake_block_hash'\n return None, None\n\n\ndef on_transaction_received(received_transaction):\n transaction_hash = hashlib.sha256(received_transaction.get_json().encode())\n RECEIVED_TRANSACTIONS[transaction_hash] = received_transaction\n logging.warning('Received transaction: {}'.format(received_transaction))\n\n\ndef empty_function():\n \"\"\"Empty function for unneeded functionality.\"\"\"\n pass\n\n\ndef create_network_interface(port, initial_peers=None):\n if initial_peers is None:\n initial_peers = {}\n return ServerNetworkInterface(JsonRpcClient(), initial_peers, MockCryptoHelper(), empty_function,\n on_transaction_received, empty_function, empty_function, get_transaction, port)\n\n\ndef configure_logging():\n logging.basicConfig(level=logging.WARNING, format='%(threadName)s: %(message)s')\n logging.getLogger(networking.__name__).setLevel(LOG_LEVEL)\n\n\nif __name__ == '__main__':\n configure_logging()\n\n # two interfaces: one without peers and one with the other as peer\n interface1 = create_network_interface(8080)\n interface2 = create_network_interface(8081, initial_peers={'127.0.0.1': {8080: {}}})\n\n # start the web servers for receiving JSON-RPC calls\n logging.debug('Starting web server threads...')\n webserver_thread1 = Thread(name='Web Server #1', target=interface1.start_listening, args=(False,))\n webserver_thread1.start()\n logging.debug('Done')\n\n while True:\n logging.warning('Sending transaction: {}'.format(str(TRANSACTION)))\n interface2.sendTransaction(TRANSACTION)\n time.sleep(POLL_INTERVAL)\n","sub_path":"examples/network/send_transaction.py","file_name":"send_transaction.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"11972595","text":"###################Import functions from libraries######################\nimport os\nimport pandas as pd\nimport numpy as np\nfrom sklearn import preprocessing\nimport matplotlib.pyplot as plt \nplt.rc(\"font\", size=14)\n\nfrom sklearn import datasets\nfrom sklearn.feature_selection import RFE\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import roc_curve\nimport seaborn as sns\n\nsns.set(style=\"white\")\nsns.set(style=\"whitegrid\", color_codes=True)\n\n###################Set working directory######################\nos.getcwd()\nos.chdir('C:\\\\Users\\\\abinash\\\\.spyder-py3')\n\n###################Read model dataset######################\ndata = pd.read_csv('banking.csv',header=0)\ndata = data.dropna()\nprint(data.shape)\nprint(list(data.columns))\n\n\n###################Create dummy vars from categorical vars######################\ncat_vars=['job','marital','education','default','housing','loan','contact','month','day_of_week','poutcome']\nfor var in cat_vars:\n cat_list='var'+'_'+var\n cat_list = pd.get_dummies(data[var], prefix=var)\n data1=data.join(cat_list)\n data=data1\n \ncat_vars=['job','marital','education','default','housing','loan','contact','month','day_of_week','poutcome']\ndata_vars=data.columns.values.tolist()\nto_keep=[i for i in data_vars if i not in cat_vars]\n\ndata_final=data[to_keep]\ndata_final.columns.values\n\ndata_final_vars=data_final.columns.values.tolist()\ny=['y']\nX=[i for i in data_final_vars if i not in y]\n\n###################Recursive Feature Elimination: selecting top 18 features here######################\nlogreg = LogisticRegression()\nrfe = RFE(logreg, 18)\nrfe = rfe.fit(data_final[X], data_final[y] )\nprint(rfe.support_)\nprint(rfe.ranking_)\n\ncols=[\"previous\", \"euribor3m\", \"job_blue-collar\", \"job_retired\", \"job_services\", \"job_student\", \"default_no\", \n \"month_aug\", \"month_dec\", \"month_jul\", \"month_nov\", \"month_oct\", \"month_sep\", \"day_of_week_fri\", \"day_of_week_wed\", \n \"poutcome_failure\", \"poutcome_nonexistent\", \"poutcome_success\"] \nX=data_final[cols]\ny=data_final['y']\n\n###################Train the Model######################\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)\nfrom sklearn import metrics\nlogreg = LogisticRegression()\nlogreg.fit(X_train, y_train)\n\n###################Preict on validation dataset######################\ny_pred = logreg.predict(X_test) #value 1 or 0\ny_pred_prob = logreg.predict_proba(X_test) #Probability scores\n\n\n###################Accuracy percentage######################\nprint('Accuracy of logistic regression classifier on test set: {:.2f}'.format(logreg.score(X_test, y_test)))\n\n###################AUROC######################\nlogit_roc_auc = roc_auc_score(y_test, logreg.predict(X_test))\nfpr, tpr, thresholds = roc_curve(y_test, logreg.predict_proba(X_test)[:,1])\nplt.figure()\nplt.plot(fpr, tpr, label='Logistic Regression (area = %0.2f)' % logit_roc_auc)\nplt.plot([0, 1], [0, 1],'r--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver operating characteristic')\nplt.legend(loc=\"lower right\")\nplt.savefig('Log_ROC')\nplt.show()\n\n","sub_path":"logreg.py","file_name":"logreg.py","file_ext":"py","file_size_in_byte":3252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"35678375","text":"#!/usr/bin/env python\n\n# Copyright 2018 Francis Y. Yan, Jestin Ma\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport argparse\nimport project_root\nimport numpy as np\nimport tensorflow as tf\nfrom os import path\nfrom env.sender import Sender\nfrom models import DaggerLSTM\nfrom helpers.helpers import normalize, one_hot, softmax\n\n\nclass Learner(object):\n def __init__(self, sender, state_dim, restore_vars):\n self.aug_state_dim = state_dim + 1#action_cnt\n self.prev_action = 0\n self.sender = sender\n with tf.variable_scope('global'):\n self.model = DaggerLSTM(\n state_dim=self.aug_state_dim, dwnd=Sender.dwnd)\n\n self.lstm_state = self.model.zero_init_state(1)\n\n self.sess = tf.Session()\n\n # restore saved variables\n saver = tf.train.Saver(self.model.trainable_vars)\n saver.restore(self.sess, restore_vars)\n\n # init the remaining vars, especially those created by optimizer\n uninit_vars = set(tf.global_variables())\n uninit_vars -= set(self.model.trainable_vars)\n self.sess.run(tf.variables_initializer(uninit_vars))\n\n\n def policy(self, state):\n \"\"\" Given a state buffer in the past step, returns an action\n to perform.\n\n Appends to the state/action buffers the state and the\n \"correct\" action to take according to the expert.\n \"\"\"\n\n aug_state = state + [self.prev_action]\n self.sender.update_decision_window(aug_state)\n\n # Get probability of each action from the local network.\n pi = self.model\n feed_dict = {\n pi.input: [self.sender.decision_window],\n pi.state_in: self.lstm_state,\n }\n ops_to_run = [pi.actions, pi.state_out]\n actions, self.lstm_state = self.sess.run(ops_to_run, feed_dict)\n\n # Choose an action to take and update current LSTM state\n if len(self.sender.decision_window) <= 1:\n action = actions\n else:\n action = actions[-1]\n # print(\"actions shape:\" + str(actions.shape))\n # print(\"in policy(): action is: \" + str(action))\n self.prev_action = action\n\n return action\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('port', type=int)\n parser.add_argument('--debug', action='store_true')\n args = parser.parse_args()\n\n sender = Sender(args.port, debug=args.debug)\n\n model_path = path.join(project_root.DIR, 'dagger', 'model', 'model')\n\n learner = Learner(sender=sender,\n state_dim=Sender.state_dim,\n restore_vars=model_path)\n\n sender.set_policy(learner.policy)\n\n try:\n sender.handshake()\n sender.run()\n except KeyboardInterrupt:\n pass\n finally:\n sender.cleanup()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"dagger/run_sender.py","file_name":"run_sender.py","file_ext":"py","file_size_in_byte":3340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"30342143","text":"from typing import Hashable, Iterable, Optional, Union\nimport pandas_flavor as pf\nimport pandas as pd\nimport numpy as np\n\nfrom janitor.utils import check_column\n\n\n@pf.register_dataframe_method\ndef flag_nulls(\n df: pd.DataFrame,\n column_name: Optional[Hashable] = \"null_flag\",\n columns: Optional[Union[str, Iterable[str], Hashable]] = None,\n) -> pd.DataFrame:\n \"\"\"Creates a new column to indicate whether you have null values in a given\n row. If the columns parameter is not set, looks across the entire\n DataFrame, otherwise will look only in the columns you set.\n\n This method does not mutate the original DataFrame.\n\n Example:\n\n >>> import pandas as pd\n >>> import janitor\n >>> df = pd.DataFrame({\n ... \"a\": [\"w\", \"x\", None, \"z\"], \"b\": [5, None, 7, 8],\n ... })\n >>> df.flag_nulls()\n a b null_flag\n 0 w 5.0 0\n 1 x NaN 1\n 2 None 7.0 1\n 3 z 8.0 0\n >>> df.flag_nulls(columns=\"b\")\n a b null_flag\n 0 w 5.0 0\n 1 x NaN 1\n 2 None 7.0 0\n 3 z 8.0 0\n\n :param df: Input pandas DataFrame.\n :param column_name: Name for the output column.\n :param columns: List of columns to look at for finding null values. If you\n only want to look at one column, you can simply give its name. If set\n to None (default), all DataFrame columns are used.\n :returns: Input dataframe with the null flag column.\n :raises ValueError: if `column_name` is already present in the\n DataFrame.\n :raises ValueError: if any column within `columns` is not present in\n the DataFrame.\n\n \n \"\"\"\n # Sort out columns input\n if isinstance(columns, str):\n columns = [columns]\n elif columns is None:\n columns = df.columns\n elif not isinstance(columns, Iterable):\n # catches other hashable types\n columns = [columns]\n\n # Input sanitation checks\n check_column(df, columns)\n check_column(df, [column_name], present=False)\n\n # This algorithm works best for n_rows >> n_cols. See issue #501\n null_array = np.zeros(len(df))\n for col in columns:\n null_array = np.logical_or(null_array, pd.isna(df[col]))\n\n df = df.copy()\n df[column_name] = null_array.astype(int)\n return df\n","sub_path":"janitor/functions/flag_nulls.py","file_name":"flag_nulls.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"318956635","text":"import os, sys, tarfile, pickle, multiprocessing\nfrom multiprocessing.pool import ThreadPool\n\n\ndef untar(filename):\n print('extracting {}'.format(filename))\n dirname = filename.split('.')[0]\n print(\"making dir {}\".format(dirname))\n os.makedirs(dirname)\n tar = tarfile.open(filename)\n tar.extractall(path=dirname)\n tar.close()\n\n\nif __name__ == '__main__':\n pool = ThreadPool(multiprocessing.cpu_count())\n\n #directories = [d for d in os.listdir(\"/media/akasha/My Passport/imagenet/\") if os.path.isdir(d)]\n tars = [tar for tar in os.listdir('.') if '.tar' in tar]\n #tars2extract = [tar for tar in tars if not tar in directories]\n results = []\n \n for tar in tars:\n results.append(pool.apply_async(untar, (tar,)))\n \n pool.close()\n pool.join()\n \n","sub_path":"data/extract_tars.py","file_name":"extract_tars.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"233121843","text":"import socket\nimport os\n\nCHUNK_SIZE = 8 * 1024\nport = 9001\n\nserver = socket.socket()\nserver.bind((socket.gethostname(), port))\n\nwhile True:\n server.listen(5)\n\n connection, address = server.accept()\n print('Got connection from', address)\n\n print('Receiving file...')\n received_file = open('receive.c', 'wb')\n file_buffer = connection.recv(CHUNK_SIZE)\n while (file_buffer):\n received_file.write(file_buffer)\n file_buffer = connection.recv(CHUNK_SIZE)\n received_file.close()\n\n print('Compiling...')\n os.system('g++ receive.c')\n binary_file = open('a.out', 'rb')\n\n print('Sending binary...')\n buffer = binary_file.read(CHUNK_SIZE)\n while (buffer):\n connection.send(buffer)\n buffer = binary_file.read(CHUNK_SIZE)\n connection.shutdown(socket.SHUT_WR)\n binary_file.close()\n\n print('Done sending binary')\n connection.close()\n","sub_path":"Server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"284175310","text":"import torch\nimport torch.nn as nn\nfrom torchvision.models.segmentation import fcn_resnet50\n\nCOLORS = 50\n\nclass Model(nn.Module):\n def __init__(self):\n super().__init__()\n self.layers = fcn_resnet50(pretrained=True)\n for param in self.parameters():\n param.requires_grad = False\n\n self.layers.backbone.conv1 = nn.Conv2d(1, 64, kernel_size=(7,7), stride=(2,2), padding=(3,3), bias=False)\n self.layers.classifier[-1] = nn.Conv2d(512, COLORS, kernel_size=(1, 1), stride=(1, 1))\n self.layers.aux_classifier[-1] = nn.Conv2d(256, COLORS, kernel_size=(1, 1), stride=(1, 1))\n self.loss_criterion = nn.MSELoss()\n \n def forward(self, x):\n return self.layers(x)\n ","sub_path":"src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"263670840","text":"from django.shortcuts import render\nfrom django.http import HttpResponseRedirect\nfrom django.utils import timezone\nfrom .models import Producto\nfrom .forms import ComentarioForm\n\n# Create your views here.\n\ndef index(request):\n return render(request, 'spa/index.html')\n\ndef contacto(request):\n form = ComentarioForm()\n if request.method == \"POST\":\n form = ComentarioForm(request.POST)\n print (form)\n if form.is_valid():\n print(\"Form is valid\")\n comentario = form.save(commit=False)\n comentario.fecha_comentario = timezone.now()\n comentario.save()\n return HttpResponseRedirect('/contacto/')\n else:\n print (\"Form is INVALID\")\n\n return render(request, 'spa/contacto.html', {'form' : form})\n\ndef servicios(request):\n productos_masajes = Producto.objects.filter(categoria='Masajes')\n productos_faciales = Producto.objects.filter(categoria='Faciales')\n productos_manos = Producto.objects.filter(categoria='Manos')\n productos_reductivos = Producto.objects.filter(categoria='Reductivos')\n return render(request, 'spa/servicios.html', {'productos_masajes' : productos_masajes,\n 'productos_faciales' : productos_faciales,\n 'productos_manos' : productos_manos,\n 'productos_reductivos' : productos_reductivos})","sub_path":"spa/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"109947198","text":"import pygame\n\n\nclass Player(pygame.sprite.Sprite):\n def __init__(self, local, pos):\n pygame.sprite.Sprite.__init__(self)\n self.local = local\n self.speed = 8\n self.pos = [pos[0], pos[1]]\n self.mov = [0, 0]\n self.sprite = [0, 0]\n self.rect = pygame.Rect(self.pos[0] + 9, self.pos[1] + 5, 16, 25)\n self.quest = []\n\n def newQuest(self, quest):\n self.quest.append(quest)\n\n def spriteSheet(self):\n sprite_sheet = pygame.image.load(self.local)\n image = pygame.Surface([32, 32])\n image.set_colorkey((0, 0, 0), pygame.RLEACCEL)\n image.blit(sprite_sheet, (self.sprite[0], self.sprite[1]))\n return image\n\n def movePlayer(self, limites):\n left = self.pos[0] + self.mov[0]\n right = self.pos[0] + self.mov[0] + 32\n up = self.pos[1] + self.mov[1]\n down = self.pos[1] + self.mov[1] + 32\n\n if left > limites[3] and right < limites[1]:\n self.pos[0] += self.mov[0]\n if up > limites[0] and down < limites[2]:\n self.pos[1] += self.mov[1]\n\n self.rect = pygame.Rect(self.pos[0] + 9, self.pos[1] + 5, 16, 25)\n self.mov[0] = 0\n self.mov[1] = 0\n","sub_path":"data/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"427572012","text":"import json, urllib\r\nfrom bs4 import BeautifulSoup as bs\r\n\r\nfrom linebot.models import (\r\n MessageEvent, TextMessage, TextSendMessage, ImageMessage, ImageSendMessage\r\n)\r\n\r\n\r\n# Showing internship info\r\ndef intern_info(line_api, event, text):\r\n result = \"\"\r\n image = \"\"\r\n company = open(\"intern_data.json\", \"r\")\r\n company_data = json.load(company)\r\n\r\n # for debug purposes\r\n print(company_data)\r\n\r\n if text.lower() == 'list':\r\n result = \"Cara pakai: ketik {!internnama perusahaan}\\n\"\\\r\n \"contoh: !intern bukalapak\\n\\n\"\\\r\n \"Company lists:\\n\\n\"\r\n \r\n for i in range(len(company_data[0][\"list\"])):\r\n result = result + str(i+1) + '. ' + company_data[0][\"list\"][i][\"company\"] + '\\n'\r\n \r\n else:\r\n for i in range(len(company_data[0][\"list\"])):\r\n if text.lower() == company_data[0][\"list\"][i][\"company\"]:\r\n for j in range(len(company_data[0][\"list\"][i][\"content\"])):\r\n result = result + company_data[0][\"list\"][i][\"content\"][j] + '\\n'\r\n result = result + '\\n'\r\n if len(company_data[0][\"list\"][i]) > 2:\r\n image = company_data[0][\"list\"][i][\"image\"]\r\n\r\n if text.lower() == 'bukalapak':\r\n with urllib.request.urlopen(\"https://careers.bukalapak.com/jobs\") as url:\r\n data = json.loads(url.read().decode())\r\n\r\n for i in range(len(data)):\r\n for j in range(len(data[i][\"list\"])):\r\n if data[i][\"list\"][j][\"type\"] == \"Internship\":\r\n result = result + ('Category: ' + data[i][\"category\"] + '\\n')\r\n result = result + ('Role: ' + data[i][\"list\"][j]['title'] + '\\n')\r\n result = result + ('url: ' + data[i][\"list\"][j]['url'] + '\\n\\n')\r\n \r\n elif text.lower() == 'tokopedia':\r\n url = 'https://www.tokopedia.com/careers/function/internship/'\r\n page = urllib.request.urlopen(url)\r\n soup = bs(page, 'html.parser')\r\n for title in soup.find_all('h4', attrs={'class': 'list-div__h4'}):\r\n result = result + '- ' + title.text + '\\n'\r\n \r\n elif text.lower() == 'suitmedia':\r\n url = 'https://suitmedia.com/careers'\r\n page = urllib.request.urlopen(url)\r\n soup = bs(page, 'html.parser')\r\n for title in soup.find_all('a', attrs={'class': 'detail-job-trigger'}):\r\n if 'intern' in (title.text.lstrip(' ')).lower():\r\n result = result + '- ' + title.text.lstrip('\\n').lstrip(' ')\r\n \r\n print(result)\r\n\r\n if len(image) == 0:\r\n line_api.reply_message(\r\n event.reply_token, TextSendMessage(text=result)\r\n )\r\n else:\r\n line_api.reply_message(\r\n event.reply_token, \r\n [\r\n TextSendMessage(text=result),\r\n ImageSendMessage(original_content_url=image, preview_image_url=image)\r\n ]\r\n )\r\n\r\n\r\n# Showing job sites\r\ndef intern_site(line_api, event):\r\n result = \"\"\r\n company = open(\"intern_data.json\", \"r\")\r\n company_data = json.load(company)\r\n\r\n result = \"Situs pencari lowongan kerja:\\n\\n\"\\\r\n\r\n for i in range(len(company_data[1][\"list\"])):\r\n result = result + str(i+1) + \". \" + company_data[1][\"list\"][i] + '\\n'\r\n \r\n line_api.reply_message(\r\n event.reply_token, TextSendMessage(text=result)\r\n )\r\n \r\n\r\n# Showing internship tips\r\ndef intern_tips(line_api, event, text):\r\n result = \"\"\r\n\r\n if text == 'cv':\r\n result = \"Guide: https://www.careercup.com/resume\\n\" \\\r\n \"Advice (good to read): https://codeburst.io/competitive-programming-label-from-an-employers-perspective-5209d6843e2a\\n\" \\\r\n \"Lumayan penting (terutama kalau ga ikut lomba/aktif di komunitas teknologi) : Side projects (project yang dikerjain sendiri, bukan dari tugas kuliah)\"\r\n elif text == 'interview':\r\n result = \"Mayoritas ngetes kemampuan problem solving menggunakan ilmu dari materi algoritma dan struktur data\\n\" \\\r\n \"Contoh soal: Implementasikan queue menggunakan 2 buah stack, dengan queue memiliki 2 method, yaitu enqueue dan dequeue\\n\" \\\r\n \"Beberapa perusahaan ngetes hal lain juga, contoh: SQL, System Design, CSS, Common technologies (co: LAMP stack)\\n\" \\\r\n \"\\nGood to know:\\n\" \\\r\n \" - Data structures: Stack, Queue, Linkedlist, Graph, Hashtable, etc\\n\" \\\r\n \" - Algorithms/Paradigm: BFS, DFS, Dynamic Programming, Greedy, etc\\n\" \\\r\n \"\\nStudy source:\\n\" \\\r\n \" - Hackerrank - https://www.hackerrank.com/ \\n\" \\\r\n \" - CS Academy - https://csacademy.com/ \\n\" \\\r\n \" - Leetcode - https://leetcode.com/ \\n\" \\\r\n \" - Kuliah\"\r\n elif text == 'materi':\r\n result = \"Recommended books to read (so far, IMO, CMIIW):\\n\"\\\r\n \"- Clean Code - A Handbook of Agile Software Craftsmanship\\n\"\\\r\n \"- Cracking the Coding Interview, 6th Edition 189 Programming Questions and Solutions\\n\"\\\r\n \"- The Algorithm Design Manual by Steven S. Skiena\\n\"\\\r\n \"- The Google Resume\\n\"\r\n\r\n\r\n \r\n line_api.reply_message(\r\n event.reply_token, TextSendMessage(text=result)\r\n )\r\n","sub_path":"Commands/Intern.py","file_name":"Intern.py","file_ext":"py","file_size_in_byte":5414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"177520660","text":"# Using Python 3\n\n'''\nApproach:\n - Iterate each number through the list:\n - Calculate then cache the result of k - number.\n - Using a hash table to store the result of k - number.\n - If number is in the hash table, return True (found the sum)\n - Otherwise, save the result of k - number to the hash table, along with the number's index in the array.\n - After iteration, return False (no sum is found).\n\nRuntime: O(n)\nSpace: O(n)\n'''\n\nfrom nose.tools import assert_equal, assert_raises\n\nclass TwoSum(object):\n def solve(self, nums, k):\n if nums is None or k is None:\n raise TypeError('Input array should not be None!')\n\n if len(nums) == 0:\n raise ValueError('Input array should not be emptied!')\n\n cache = dict()\n for index, num in enumerate(nums):\n cache_num = k - num\n if num in cache:\n return True\n else:\n cache[cache_num] = index\n\n return False\n\n\nclass TestTwoSum(object):\n def test_empty_array(self):\n solution = TwoSum()\n assert_raises(TypeError, solution.solve, None, None)\n assert_raises(ValueError, solution.solve, [], 0)\n\n def test_success_two_sum(self):\n solution = TwoSum()\n target = 17\n nums = [10, 15, 3, 7]\n\n assert_equal(solution.solve(nums, target), True)\n\n def test_failed_two_sum(self):\n solution = TwoSum()\n target = 10\n nums = [1, 2, 3, 4]\n\n assert_equal(solution.solve(nums, target), False)\n\ndef main():\n test = TestTwoSum()\n test.test_empty_array()\n test.test_success_two_sum()\n test.test_failed_two_sum()\n\nif __name__ == '__main__':\n main()\n","sub_path":"coding_challenges/two_sum/two_sum.py","file_name":"two_sum.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"215282062","text":"# time: O(n^3) space: O(1)\nclass Solution(object):\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n longestPal = ''\n for i in range(len(s)):\n for j in range(len(s), i, -1):\n if len(longestPal) >= j-i:\n break\n elif s[i:j] == s[i:j][::-1]:\n longestPal = s[i:j]\n break\n return longestPal\n\n# time: O(n^2) space: O(1)\nclass Solution(object):\n def longestPalindrome(self, string):\n currentLongest = [0, 1]\n for i in range(len(string)):\n odd = self.getLongestPalindrome(string, i - 1, i + 1)\n even = self.getLongestPalindrome(string, i - 1, i)\n longest = max(odd, even, key = lambda x: x[1] - x[0])\n currentLongest = max(longest, currentLongest, key = lambda x: x[1] - x[0])\n return string[currentLongest[0]:currentLongest[1]]\n\t\t\n def getLongestPalindrome(self, string, leftIdx, rightIdx):\n while leftIdx >= 0 and rightIdx < len(string):\n if string[leftIdx] != string[rightIdx]:\n break\n leftIdx -= 1\n rightIdx += 1\n return [leftIdx + 1, rightIdx]","sub_path":"2.22/longest_palidrom.py","file_name":"longest_palidrom.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"506732294","text":"# -*- coding: utf-8 -*-\n\"\"\"\nGloVe\n\nCreated on Wed Apr 19 14:33:46 2017\n@author: hzxieshukun\n参看https://www.kaggle.com/lystdo/quora-question-pairs/lstm-with-word2vec-embeddings\nMAX_NB_WORDS = 200000\nnum_lstm = np.random.randint(175, 275)\nnum_dense = np.random.randint(100, 150)\nEPOCHS = 200\nBATCH_SIZE = 2048\n\"\"\"\n\nimport csv\nimport codecs\nimport numpy as np\nimport time\n\nfrom gensim.models import KeyedVectors\n\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.layers import Dense, Input, LSTM, Embedding, Dropout, Activation\nfrom keras.layers.merge import concatenate\nfrom keras.models import Model\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\n\nfrom util import text_to_wordlist\n\n#import sys\n#reload(sys)\n#sys.setdefaultencoding('utf-8')\n\n##set directories and parameters\nBASE_DIR = 'data/'\nEMBEDDING_FILE = BASE_DIR + 'glove.6B/glove.6B.100d.txt'\nTRAIN_DATA_FILE = BASE_DIR + 'train.csv'\nTEST_DATA_FILE = BASE_DIR + 'test.csv'\nMAX_SEQUENCE_LENGTH = 30\nMAX_NB_WORDS = 200000\nSET_NB_WORDS = 200000\nEMBEDDING_DIM = 100\nVALIDATION_SPLIT = 0.1\nEPOCHS = 2\nBATCH_SIZE = 500\n\n#num_lstm = 5 #np.random.randint(5, 10)\n#num_dense = 5 #np.random.randint(5, 10)\n#rate_drop_lstm = 0\n#rate_drop_dense = 0\nnum_lstm = np.random.randint(175, 275)\nnum_dense = np.random.randint(100, 150)\nrate_drop_lstm = 0.15 + np.random.rand() * 0.25\nrate_drop_dense = 0.15 + np.random.rand() * 0.25\n\nact = 'relu'\n\n# whether to re-weight classes to fit the 17.5% share in test set\nre_weight = True\n\nSTAMP = 'lstm_%d_%d_%.2f_%.2f_glove' % (num_lstm, num_dense, rate_drop_lstm, rate_drop_dense)\n\n\n\n##process texts in datasets\nprint('Processing text dataset')\n\n## read train data\nt1 = time.time()\ntexts_1 = []\ntexts_2 = []\nlabels = []\nline_num = 0\nwith codecs.open(TRAIN_DATA_FILE, encoding = 'utf-8') as f:\n reader = csv.reader(f, delimiter = ',')\n header = next(reader)\n for values in reader:\n texts_1.append(text_to_wordlist(values[3]))\n texts_2.append(text_to_wordlist(values[4]))\n labels.append(int(values[5]))\n line_num += 1\n #if line_num > 10000:\n # break\nprint('Found %s texts in train.csv' % len(texts_1))\nt2 = time.time()\nprint(\"load train data use %ss\" % (t2 - t1))\n\n## read test data\nt1 = time.time()\ntest_texts_1 = []\ntest_texts_2 = []\ntest_ids = []\nwith codecs.open(TEST_DATA_FILE, encoding = 'utf-8') as f:\n reader = csv.reader(f, delimiter = ',')\n header = next(reader)\n for values in reader:\n test_texts_1.append(text_to_wordlist(values[1]))\n test_texts_2.append(text_to_wordlist(values[2]))\n test_ids.append(values[0])\nprint('Found %s texts in test.csv' % len(test_texts_1))\nt2 = time.time()\nprint(\"load test data use %ss\" % (t2 - t1))\n\n## transfer words to sequences\nt1 = time.time()\ntokenizer = Tokenizer(num_words=SET_NB_WORDS)\n#tokenizer.fit_on_texts(texts_1 + texts_2)\ntokenizer.fit_on_texts(texts_1 + texts_2 + test_texts_1 + test_texts_2)\nsequences_1 = tokenizer.texts_to_sequences(texts_1)\nsequences_2 = tokenizer.texts_to_sequences(texts_2)\n#test_sequences_1 = tokenizer.texts_to_sequences(test_texts_1)\n#test_sequences_2 = tokenizer.texts_to_sequences(test_texts_2)\ntest_texts_1 = []\ntest_texts_2 = []\ntest_ids = []\nword_index = tokenizer.word_index\nprint('Foud %s unique tokens' % len(word_index))\nt2 = time.time()\nprint('transfer words to sequences use %ss' % (t2 - t1))\n\n\n##unify the sequences length to MAX_SEQUENCE_LENGTH\ndata_1 = pad_sequences(sequences_1, maxlen = MAX_SEQUENCE_LENGTH)\ndata_2 = pad_sequences(sequences_2, maxlen = MAX_SEQUENCE_LENGTH)\nlabels = np.array(labels)\nprint(\"Shape of data tensor:\", data_1.shape)\nprint(\"Shape of label tensor:\", labels.shape)\n\n#test_data_1 = pad_sequences(test_sequences_1, maxlen = MAX_SEQUENCE_LENGTH)\n#test_data_2 = pad_sequences(test_sequences_2, maxlen = MAX_SEQUENCE_LENGTH)\n#test_ids = np.array(test_ids)\n\n\n##index word vectors\nt1 = time.time()\nprint(\"Indexing word vectors\")\nembeddings_index = {}\nf = open(EMBEDDING_FILE)\nfor line in f:\n values = line.split()\n word = values[0]\n coefs = np.asarray(values[1:], dtype = 'float32')\n embeddings_index[word] = coefs\nf.close()\nprint('Found %s word vectors of glove.6B' % len(embeddings_index))\nt2 = time.time()\nprint('index word vectors init use %ss' % (t2 - t1))\n\n##prepare embeddings\nprint('Preparing embedding marrix')\nt1 = time.time()\nnb_words = min(MAX_NB_WORDS, len(word_index)) + 1\nembedding_matrix = np.zeros((nb_words, EMBEDDING_DIM))\nfor word, i in word_index.items():\n embedding_vector = embeddings_index.get(word)\n if embedding_vector is not None:\n embedding_matrix[i] = embedding_vector\nprint('Null word embddings: %d' % np.sum(np.sum(embedding_matrix, axis = 1) == 0))\nt2 = time.time()\nprint(\"prepare embeddings use %ss\" % (t2 -t1))\n\n\n##sample train/validation data -- shuffle the data\nt1 = time.time()\nperm = np.random.permutation(len(data_1))\nidx_train = perm[:int(len(data_1) * (1 - VALIDATION_SPLIT))]\nidx_val = perm[int(len(data_1) * (1 - VALIDATION_SPLIT)):]\n\ndata_1_train = np.vstack((data_1[idx_train], data_2[idx_train]))\ndata_2_train = np.vstack((data_2[idx_train], data_1[idx_train]))\nlabels_train = np.concatenate((labels[idx_train], labels[idx_train]))\n\ndata_1_val = np.vstack((data_1[idx_val], data_2[idx_val]))\ndata_2_val = np.vstack((data_2[idx_val], data_1[idx_val]))\nlabels_val = np.concatenate((labels[idx_val], labels[idx_val]))\n\nweight_val = np.ones(len(labels_val))\nif re_weight:\n weight_val *= 0.472001959\n weight_val[labels_val == 0] = 1.309028344\nt2 = time.time()\nprint(\"data_1_train shape:\", data_1_train.shape)\nprint(\"data_1_train example:\")\nprint(data_1_train[1])\nprint(\"sample train/val data use %ss\" % (t2 -t1))\nword2vec = None\n\n##define the model structure\nembedding_layer = Embedding(input_dim = nb_words,\n output_dim = EMBEDDING_DIM,\n weights = [embedding_matrix],\n input_length = MAX_SEQUENCE_LENGTH,\n trainable = False)\nlstm_layer = LSTM(num_lstm, dropout = rate_drop_lstm, recurrent_dropout = rate_drop_lstm)\n\nsequence_1_input = Input(shape=(MAX_SEQUENCE_LENGTH,), dtype = 'int32')\nembedded_sequences_1 = embedding_layer(sequence_1_input)\nx1 = lstm_layer(embedded_sequences_1)\n\nsequence_2_input = Input(shape = (MAX_SEQUENCE_LENGTH,), dtype = 'int32')\nembedded_sequences_2 = embedding_layer(sequence_2_input)\ny1 = lstm_layer(embedded_sequences_2)\n\nmerged = concatenate([x1, y1])\nmerged = Dropout(rate_drop_dense)(merged)\nmerged = BatchNormalization()(merged)\n\nmerged = Dense(num_dense, activation = act)(merged)\nmerged = Dropout(rate_drop_dense)(merged)\nmerged = BatchNormalization()(merged)\n\npreds = Dense(1, activation = 'sigmoid')(merged)\n\n###add class weight\nif re_weight:\n class_weight = {0: 1.309028344, 1: 0.472001959}\nelse:\n class_weight = None\n\n##train the model\nmodel = Model(inputs=[sequence_1_input, sequence_2_input], outputs = preds)\nmodel.compile(loss = 'binary_crossentropy',\n optimizer = 'nadam',\n metrics = ['acc'])\nprint(STAMP)\n\nearly_stopping = EarlyStopping(monitor = 'val_loss', patience = 3)\nbst_model_path = 'model/' + STAMP + '.h5'\nmodel_checkpoint = ModelCheckpoint(bst_model_path, verbose=0, monitor = 'val_acc', save_best_only = True, save_weights_only = False, mode = 'max')\n\nt1 = time.time()\nhist = model.fit([data_1_train, data_2_train], labels_train, \\\n validation_data = ([data_1_val, data_2_val], labels_val, weight_val), \\\n epochs = EPOCHS, batch_size = BATCH_SIZE, shuffle = True, \\\n class_weight = class_weight, callbacks = [model_checkpoint])\n#model.save_weights(bst_model_path)\n#model.load_weights(bst_model_path)\nt2 = time.time()\nprint(\"lstm run use %s\" % (t2 - t1))\nbst_val_score = min(hist.history['val_loss'])\nbst_val_acc = max(hist.history['val_acc'])\nprint(\"best_val_score:\", bst_val_score)\nprint(\"baset_val_acc:\", bst_val_acc)\nprint(\"SET_NB_WORDS\\tEMBEDDING_DIM\\tEPOCHS\\tBATCH_SIZE\\tnum_lstm\\tnum_dense\\t\\\n rate_drop_lstm\\trate_drop_dense\\tVal_loss\\tval_acc\")\nprint(\"%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\" % (SET_NB_WORDS, EMBEDDING_DIM, EPOCHS, BATCH_SIZE, num_lstm, num_dense, \\\n rate_drop_lstm, rate_drop_dense, bst_val_score, bst_val_acc))","sub_path":"kaggle/lstm_train_glove.py","file_name":"lstm_train_glove.py","file_ext":"py","file_size_in_byte":8268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"335207770","text":"from collections.abc import Iterator, Iterable\n\n\ndef main():\n l = [1, 2, 3]\n print(str.format(\n 'Список {} является итерируемым: {}', l, isinstance(l, Iterable)\n ))\n\n print(str.format(\n 'Список {} является итератором: {}', l, isinstance(l, Iterator)\n ))\n\n print(str.format(\n 'iter(l) является итератором: {}', isinstance(iter(l), Iterator)\n ))\n\n [print(item) for item in dir(l) if '__next__' in item]\n [print(item) for item in dir(l) if '__iter__' in item]\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"spl/collections_abc_module/app2.py","file_name":"app2.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"357848799","text":"class Utils:\n\n @staticmethod\n def set_bit(num: int, bit_mask: int, value: bool) -> int:\n if value: # bit is 1\n return num | bit_mask\n else: # bit is 0\n return num & ~bit_mask\n\n @staticmethod\n def is_bit_set(bits: int, bit_mask: int) -> bool:\n return bits & bit_mask != 0\n\n @staticmethod\n def calc_checksum(byte_buffer: bytes) -> bytes:\n \"\"\"\n Calculates checksum using the algorithm described in\n https://tools.ietf.org/html/rfc793#section-3.1\n\n The following algorithm is applied for IPv4, TCP, UDP protocols:\n - Split input byte sequence to 16 bits words\n - Compute sum of these words\n - Compute sum one's complement\n\n :param: byte_buffer: input byte sequence\n :return: calculated checksum (16 bits value)\n \"\"\"\n if len(byte_buffer) % 2 != 0:\n byte_buffer += b'\\0'\n checksum = 0\n for i in range(0, len(byte_buffer), 2):\n # pair two bytes into 16-bits value\n paired_bytes = (byte_buffer[i] << 8) + byte_buffer[i + 1]\n checksum += paired_bytes\n checksum += (checksum >> 16)\n checksum = ~checksum & 0xffff\n # split 16-bits checksum into two 8-bits values\n checksum_bytes = checksum.to_bytes(2, byteorder=\"big\")\n return checksum_bytes\n","sub_path":"nally/core/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"209568166","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nNUM_MON_SITES = 100\nNUM_MON_INST_TEST = 30\nNUM_MON_INST_TRAIN = 60\nNUM_MON_INST = NUM_MON_INST_TEST + NUM_MON_INST_TRAIN\nNUM_UNMON_SITES_TEST = 5500\nNUM_UNMON_SITES_TRAIN = 3500\nNUM_UNMON_SITES = NUM_UNMON_SITES_TEST + NUM_UNMON_SITES_TRAIN\n\n\ndef find_accuracy(predictions, actual, min_confidence):\n \"\"\"Compute TPR and FPR based on softmax output predictions, one-hot encodings for the correct classes,\n and the minimum confidence threshold.\"\"\"\n\n # calculate class with highest probability\n uncertain_predictions = np.argmax(predictions, axis=1)\n actual = np.argmax(actual, axis=1)\n\n # adjust predicted classes to reflect min_confidence\n certain_predictions = np.zeros(uncertain_predictions.shape)\n for i in range(0, len(certain_predictions)):\n # if classified as sens with not high-enough probability, re-classify as insens\n predicted_class = uncertain_predictions[i]\n if predicted_class < NUM_MON_SITES and predictions[i][predicted_class] < min_confidence:\n certain_predictions[i] = NUM_MON_SITES\n else:\n certain_predictions[i] = predicted_class\n\n # compute TPR and FPR\n sens_correct = 0\n insens_as_sens = 0\n for i in range(len(actual)):\n if actual[i] == NUM_MON_SITES: # insens site\n if certain_predictions[i] < NUM_MON_SITES: # but predicted as a sens site\n insens_as_sens += 1\n else: # sens site\n if actual[i] == certain_predictions[i]: # prediction matches up\n sens_correct += 1\n\n tpr = sens_correct / (NUM_MON_SITES * NUM_MON_INST_TEST) * 100\n if NUM_UNMON_SITES == 0: # closed-world\n fpr = 0\n else:\n fpr = insens_as_sens / NUM_UNMON_SITES_TEST * 100\n\n return \"TPR: %f, FPR: %f\" % (tpr, fpr)\n\n\ndef main(num_mon_sites, num_mon_inst_test, num_mon_inst_train, num_unmon_sites_test, num_unmon_sites_train):\n global NUM_MON_SITES\n global NUM_MON_INST_TEST\n global NUM_MON_INST_TRAIN\n global NUM_MON_INST\n global NUM_UNMON_SITES_TEST\n global NUM_UNMON_SITES_TRAIN\n global NUM_UNMON_SITES\n\n NUM_MON_SITES = num_mon_sites\n NUM_MON_INST_TEST = num_mon_inst_test\n NUM_MON_INST_TRAIN = num_mon_inst_train\n NUM_MON_INST = num_mon_inst_test + num_mon_inst_train\n NUM_UNMON_SITES_TEST = num_unmon_sites_test\n NUM_UNMON_SITES_TRAIN = num_unmon_sites_train\n NUM_UNMON_SITES = num_unmon_sites_test + num_unmon_sites_train\n\n prediction_dir = \"/home/liyanzeng/git/Var-CNN--DynaFlow/predictions\"\n data_dir = \"/home/liyanzeng/git/Var-CNN--DynaFlow/preprocess\"\n\n # read in data from numpy files\n time_predictions = np.load(r\"%s/time_model.npy\" % prediction_dir)\n dir_predictions = np.load(r\"%s/dir_model.npy\" % prediction_dir)\n test_labels = np.load(r\"%s/test_labels.npy\" % data_dir)\n\n # Var-CNN ensemble predictions are just a simple average of Var-CNN time and direction softmax outputs\n ensemble_predictions = np.add(time_predictions, dir_predictions)\n ensemble_predictions = np.divide(ensemble_predictions, 2)\n\n if NUM_UNMON_SITES == 0: # closed-world\n print(\"min_confidence=\", 0.)\n print(\"time model results:\", find_accuracy(time_predictions, test_labels, 0.))\n print(\"dir model results:\", find_accuracy(dir_predictions, test_labels, 0.))\n print(\"ensemble results:\", find_accuracy(ensemble_predictions, test_labels, 0.))\n else:\n for conf in range(0, 11):\n conf *= 0.1\n print(\"min_confidence=\", conf)\n print(\"time model results:\", find_accuracy(time_predictions, test_labels, conf))\n print(\"dir model results:\", find_accuracy(dir_predictions, test_labels, conf))\n print(\"ensemble results:\", find_accuracy(ensemble_predictions, test_labels, conf))\n\n\nif __name__ == '__main__':\n main(100, 30, 60, 5500, 3500)\n","sub_path":"evaluate_ensemble.py","file_name":"evaluate_ensemble.py","file_ext":"py","file_size_in_byte":3978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"557580054","text":"import unittest\n\nimport os, sys\nsys.path.append(os.path.abspath(sys.path[0]) + '/../')\nimport analyseren\nfrom lib import graph\nfrom lib import config\n\n\n\nclass TestAnalyseren( unittest.TestCase ):\n\tdef setUp( self ):\n\t\tself.large_dict = {'A': {'C': 4, 'B': 9}, 'C': {'H': 45, 'D': 5}, 'B': {'C': 3, 'D': 6}, 'E': {'A': 33, 'B': 3, 'F': 3}, 'D': {'A': 5, 'C': 3}, 'G': {'H': 14}, 'F': {'A': 12, 'E': 2, 'D': 7, 'G': 2}, 'I': {'H': 2, 'J': 2}, 'H': {'I': 2, 'C': 45, 'J': 2}, 'K': {'J': 15, 'L' : 4 }, 'J': {'I': 2, 'H': 2, 'K': 15}}\n\t\tself.large_graph = graph.graph( self.large_dict )\n\t\tself.example_dict = { 'A' : { 'B' : 5, 'D' : 5, 'E' : 7 }, 'B' : { 'C' : 4 }, 'C' : { 'D' : 8 , 'E' : 2 }, 'D' : { 'C' : 8, 'E' : 6 }, 'E':{'B':3} }\n\t\tself.example_graph = graph.graph( self.example_dict )\n\t\t# AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7\n\n\n\t\t# self.empty_dict = {}\n\t\t# self.empty_list = []\n\n\tdef _test_strings_of_paths_are_equal( self, list_1, list_2 , msg ):\n\t\tlist_of_first_items = list_1.split( ', ' )\n\t\tlist_of_second_items = list_2.split( ', ' )\n\t\tself.assertCountEqual( list_1, list_2, msg )\n\n\tdef test_execute_command_shortest_path( self ):\n\t\texpected_output = '14'\n\t\ttest_output\t= analyseren.execute_command( 'AEBC l' , self.example_graph )\n\t\tself.assertEqual( expected_output, test_output, 'execute_command() shortest path ' )\n\n\t\texpected_output = config.NO_ROUTE_TO_USER_STRING\n\t\ttest_output\t= analyseren.execute_command( 'ZABC l' , self.example_graph )\n\t\tself.assertEqual( expected_output, test_output, 'execute_command() shortest path no route' )\n\n\t\texpected_output = '18'\n\t\ttest_output\t= analyseren.execute_command( 'ADEBC l' , self.example_graph )\n\t\tself.assertEqual( expected_output, test_output, 'execute_command() shortest path' )\n\n\t\texpected_output = '21'\n\t\ttest_output\t= analyseren.execute_command( 'CDEBC l' , self.example_graph )\n\t\tself.assertEqual( expected_output, test_output, 'execute_command() shortest path start == end' )\n\n\n\tdef test_execute_command_max_stops( self ):\n\t\texpected_output = '11'\n\t\ttest_output\t= analyseren.execute_command( 'EC 5ms' , self.large_graph )\n\t\tself._test_strings_of_paths_are_equal( expected_output, test_output, 'execute_command() max stops checks' )\n\n\t\texpected_output = config.NO_ROUTE_TO_USER_STRING\n\t\ttest_output\t= analyseren.execute_command( 'EC 2ms' , self.large_graph )\n\t\tself.assertEqual( expected_output, test_output, 'execute_command() max stops checks stops exist, but more than max ' )\n\n\t\texpected_output = '2'\n\t\ttest_output\t= analyseren.execute_command( 'EC 3ms' , self.large_graph )\n\t\tself._test_strings_of_paths_are_equal( expected_output, test_output, 'execute_command() max stops checks stops exist, but some more than max ' )\n\n\n\n\tdef test_execute_command_n_stops( self ):\n\t\texpected_output = '5'\n\t\ttest_output\t= analyseren.execute_command( 'EC 5s' , self.large_graph )\n\t\tself.assertEqual( expected_output, test_output, 'execute_command() only X stops checks' )\n\n\t\texpected_output = '1'\n\t\ttest_output\t= analyseren.execute_command( 'AB 2s' , self.large_graph )\n\t\tself.assertEqual( expected_output, test_output, 'execute_command() only X stops checks' )\n\n\t\texpected_output = config.NO_ROUTE_TO_USER_STRING\n\t\ttest_output\t= analyseren.execute_command( 'EL 6s' , self.large_graph )\n\t\tself.assertEqual( expected_output, test_output, 'execute_command() only X stops checks, none' )\n\n\n\n\tdef test_execute_max_distance( self ):\n\t\texpected_output = '11'\n\t\ttest_output\t= analyseren.execute_command( 'EC 50d' , self.large_graph )\n\t\tself.assertEqual( expected_output, test_output, 'execute_command() max distance test we got ' + test_output )\n\n\t\texpected_output = '6'\n\t\ttest_output\t= analyseren.execute_command( 'EC 20d' , self.large_graph )\n\t\tself.assertEqual( expected_output, test_output, 'execute_command() max distance test longer routes exist but are not shown' )\n\n\t\texpected_output = config.NO_ROUTE_TO_USER_STRING\n\t\ttest_output\t= analyseren.execute_command( 'EC 5d' , self.large_graph )\n\t\tself.assertEqual( expected_output, test_output, 'execute_command() max distance test no routes found ' )\n\n\n\tdef test_execute_length_of_path( self ):\n\t\texpected_output = '33'\n\t\ttest_output\t= analyseren.execute_command( 'EFABDC l' , self.large_graph )\n\t\tself.assertEqual( expected_output, test_output, 'execute_command() path len 1/2' )\n\t\t\n\t\texpected_output = '19'\n\t\ttest_output\t= analyseren.execute_command( 'EFAC l' , self.large_graph )\n\t\tself.assertEqual( expected_output, test_output, 'execute_command() path len 2/2' )\n\n\t\texpected_output = config.NO_ROUTE_TO_USER_STRING\n\t\ttest_output\t= analyseren.execute_command( 'IAE l' , self.large_graph )\n\t\tself.assertEqual( expected_output, test_output, 'execute_command() path len path no exist' )\n\n\t\texpected_output = '5'\n\t\ttest_output\t= analyseren.execute_command( 'EFE l' , self.large_graph )\n\t\tself._test_strings_of_paths_are_equal( expected_output, test_output, 'execute_command() path len start == end' )\n\n\n\n\n\n\t## ## ## ## ## ## ## ##\n\t## input errors\n\t## ## ## ## ## ## ## ##\n\tdef test_execute_command_input_errors( self ):\n\n\t\texpected_output = 'Unknown Command: ZEEDMORE'\n\t\ttest_output\t= analyseren.execute_command( 'ZEEDMORE' , self.example_graph )\n\t\tself.assertEqual( expected_output, test_output, 'execute_command() input error' )\n\n\t\texpected_output = 'Unknown Command: ZEE'\n\t\ttest_output\t= analyseren.execute_command( 'ZEE' , self.example_graph )\n\t\tself.assertEqual( expected_output, test_output, 'execute_command() input error' )\n\n\t\texpected_output = 'Unknown Command: 333'\n\t\ttest_output\t= analyseren.execute_command( '333' , self.example_graph )\n\t\tself.assertEqual( expected_output, test_output, 'execute_command() input error' )\n\n\t\texpected_output = 'Unknown Command: AE 333' # so close\n\t\ttest_output\t= analyseren.execute_command( 'AE 333' , self.example_graph )\n\t\tself.assertEqual( expected_output, test_output, 'execute_command() input error' )\n\n\n","sub_path":"test/TestAnalyseren.py","file_name":"TestAnalyseren.py","file_ext":"py","file_size_in_byte":5873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"38338545","text":"import math\r\nimport numpy as np\r\n\r\ndef y(n, y0, dt):\r\n if(n == 0):\r\n return y0\r\n else:\r\n return (y(n-1, y0, dt)+dt*(y(n-1,y0,dt))**2)\r\n \r\ndef yFor(N): \r\n y0=-10.0\r\n dt = 1/N\r\n y_ = np.array([y0 for _ in range(N+1)])\r\n\r\n for i in range(N):\r\n y_[i+1] = y_[i]+dt*(y_[i])**2\r\n return y_[N]\r\n\r\ndef zFor(N): \r\n z0=-10.0\r\n dt = 1/N\r\n z_ = np.array([z0 for _ in range(N+1)])\r\n\r\n for i in range(N):\r\n z_[i+1] = 1/(2*dt)*(1-np.sqrt(1-4*dt*z_[i]))\r\n return z_[N]\r\n\r\ndef exacta(t):\r\n return -10/(1+10*t)\r\n\r\ndef exacta2():\r\n r0 = 1/2\r\n a = 1\r\n t = 1\r\n R = 1\r\n return (r0)/(r0+math.e**(-a*t)*(R-r0))\r\n\r\ndef ynLog(N):\r\n y0 = 1/2\r\n dt = 1/N\r\n R = 1\r\n a = 1\r\n y_ = np.array([y0 for _ in range(N+1)])\r\n for i in range(N):\r\n y_[i+1] = a*y_[i]*(1-(y_[i]/R))*dt+y_[i]\r\n return y_[N]\r\n\r\ndef znLog(N):\r\n z0 = 1/2\r\n dt = 1/N\r\n z_ = np.array([z0 for _ in range(N+1)])\r\n for i in range(N):\r\n z_[i+1] = ((-1*(1-dt)+math.sqrt(((1-dt)**2-4*(dt)*(-z_[i]))))/(2*dt))\r\n return z_[N]\r\n\r\n\r\n\r\nprint(\"-----------------------\")\r\nnum = 10\r\nfor i in range(100):\r\n if(i==0): \r\n print(\"Explícito: \", ynLog(1)) \r\n print(\"Implícito: \", znLog(1)) \r\n print(\"Exacta: \", exacta2()) \r\n print(\"Valor de N: \", 1)\r\n print(\"\")\r\n print(\"-----------------------\")\r\n else:\r\n \r\n print(\"Explícito: \", ynLog(num)) \r\n print(\"Implícito: \", znLog(num)) \r\n print(\"Exacta: \", exacta2()) \r\n print(\"Valor de N: \", num)\r\n print(\"\")\r\n print(\"-----------------------\")\r\n num += 10\r\n","sub_path":"T-1/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"577472793","text":"import time\nimport urllib.request, json\nfrom subprocess import call\nimport datetime\nimport logging\nimport sys\n#from vigia import serverstatusteleg\n\ndef checknode():\n\n vurl=\"http://myhost/v1/chain/get_info\"\n with urllib.request.urlopen(vurl) as url:\n data = json.loads(url.read().decode())\n return(data) \n \n \nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nhandler = logging.FileHandler('logvig.log')\nhandler.setFormatter(formatter)\nlogger.addHandler(handler) \n\nwhile True: \n try:\n a=checknode() \n print(a)\n print(datetime.datetime.now())\n #serverstatusteleg.telegram(\"Everything OK\")\n time.sleep(900) \n\n except:\n print(\"error \")\n print(datetime.datetime.now())\n logger.error(sys.exc_info())\n serverstatusteleg.telegram(\"We are going to relaunch node\")\n call([\"./start.sh\"])\n #serverstatusteleg.telegram(\"Node just relaunched\")\n time.sleep(100)\n \n","sub_path":"vigia.py","file_name":"vigia.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"62996067","text":"# -*- coding:utf-8 -*-\nfrom django.db import models\n\n\nclass Executor(models.Model):\n class Meta:\n verbose_name = \"Исполнитель кода\"\n verbose_name_plural = \"Исполнители кода\"\n\n AVAILABLE_EXECUTORS = (\n (0, \"Python 3.6\"),\n (1, \"Test 1\"),\n (2, \"Test 2\"),\n )\n name = models.IntegerField(\n verbose_name=\"Наименование\",\n unique=True,\n choices=AVAILABLE_EXECUTORS,\n )\n\n def __str__(self):\n return self.AVAILABLE_EXECUTORS[self.name][1]\n","sub_path":"project/executors/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"375191455","text":"#coding:utf-8\nfrom socket import * \nfrom multiprocessing import Process\n\ns = socket(AF_INET, SOCK_STREAM)\nlocaladd = ('', 8001)\ns.bind(localadd)\ns.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\ns.listen(5)\n\ndef sockethandler(clientSocket, clientAddr):\n\twhile True:\n\t\trecvData = clientSocket.recv(1024)\n\t\tif len(recvData) > 0:\n\t\t\tprint('recv:%s from %s' % (recvData, str(clientAddr)))\n\t\t\tclientSocket.send(recvData)\t\n\t\telse:\n\t\t\tprint('close %s' % str(clientAddr))\n\t\t\tclientSocket.close()\n\t\t\tbreak;\n\nwhile True:\n\tprint('--等待客户链接--')\n\tnews, newaddr = s.accept()\n\tp = Process(target=sockethandler, args=(news,newaddr,))\n\tp.start()\n\n\t#注意主线程需要关闭 news. 复制后会有两个socket\n\t# news.close()\n\n","sub_path":"code/day06-socket/01/mulsocketser.py","file_name":"mulsocketser.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"517266050","text":"'''\n 私聊功能\n 将发送的消息从data变成data + user(自己) + chat(聊天对象)\n 这里用了取巧的方法, 虽然是私聊但实际上所有客户端都能收到消息\n 通过接收的消息里包含的user和chat判断是否将消息打印出来达到私聊的效果\n 限制了窗口大小\n'''\n\nimport socket\nimport threading\nimport json # json.dumps(some)打包 json.loads(some)解包\nimport tkinter\nimport tkinter.messagebox\n\nIP = ''\nPORT = ''\nuser = ''\nlistbox1 = '' # 用于显示在线用户的列表框\nii = 0 # 用于判断是开还是关闭列表框\nusers = [] # 在线用户列表\nchat = '----------群聊----------' # 聊天对象, 默认为群聊\n\n## 登录窗口\nroot1 = tkinter.Tk()\nroot1.title('登录')\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='服务器地址')\nlabelIP.place(x=30, y=10, width=80, height=20)\n\nentryIP = tkinter.Entry(root1, width=80, textvariable=IP1)\nentryIP.place(x=120, y=10, width=130, height=20)\n\n# 用户名标签\nlabelUser = tkinter.Label(root1, text='用户名')\nlabelUser.place(x=30, y=40, width=80, height=20)\n\nentryUser = tkinter.Entry(root1, width=80, textvariable=User)\nentryUser.place(x=120, y=40, width=130, height=20)\n\n\n# 登录按钮\ndef login(*args):\n global IP, PORT, user\n IP, PORT = entryIP.get().split(':') # 获取IP和端口号\n PORT = int(PORT) # 端口号需要为int类型\n user = entryUser.get()\n root1.destroy() # 关闭窗口\n\n\nroot1.bind('', login) # 回车绑定登录功能\n\nbut = tkinter.Button(root1, text='登录', command=login)\nbut.place(x=100, y=70, width=70, height=30)\n\nroot1.mainloop()\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((IP, PORT))\nif user:\n s.send(user.encode()) # 发送用户名\nelse:\n s.send('no'.encode()) # 没有输入用户名则标记no\n\n# 如果没有用户名则将ip和端口号设置为用户名\naddr = s.getsockname() # 获取客户端ip和端口号\naddr = addr[0] + ':' + str(addr[1])\nif user == '':\n user = addr\n\n## 聊天窗口\n# 创建图形界面\nroot = tkinter.Tk()\nroot.title(user) # 窗口命名为用户名\nroot['height'] = 420\nroot['width'] = 580\nroot.resizable(0, 0) # 限制窗口大小\n\n# 滚动条\n# scrolly = tkinter.Scrollbar(root)\n# scrolly.pack(side=tkinter.RIGHT, fill=tkinter.Y)\n\n# 创建多行文本框\nlistbox = tkinter.Listbox(root) # , yscrollcommand=scrolly.set\nlistbox.place(x=5, y=0, width=570, height=365)\n# scrolly.config(command=listbox.yview)\n\n# 创建输入文本框和关联变量\na = tkinter.StringVar()\na.set('')\nentry = tkinter.Entry(root, width=120, textvariable=a)\nentry.place(x=5, y=375, width=420, height=30)\n\n\ndef send(*args):\n # 没有添加的话发送信息时会提示没有聊天对象\n users.append('----------群聊----------')\n if chat not in users:\n tkinter.messagebox.showerror('发送失败', message='没有聊天对象!')\n return\n if chat == user:\n tkinter.messagebox.showerror('发送失败', message='不能私聊自己!')\n return\n mes = entry.get() + ':;' + user + ':;' + chat # 添加聊天对象标记\n s.send(mes.encode())\n a.set('') # 发送后清空文本框\n\n\n# 创建发送按钮\nbutton = tkinter.Button(root, text='发送', command=send)\nbutton.place(x=435, y=375, width=60, height=30)\nroot.bind('', send) # 绑定回车发送信息\n\n# 创建多行文本框, 显示在线用户\nlistbox1 = tkinter.Listbox(root)\nlistbox1.place(x=445, y=0, width=130, height=365)\n\n\ndef users():\n global listbox1, ii\n if ii == 1:\n listbox1.place(x=445, y=0, width=130, height=365)\n ii = 0\n else:\n listbox1.place_forget() # 隐藏控件\n ii = 1\n\n\n# 查看在线用户按钮\nbutton1 = tkinter.Button(root, text='在线用户', command=users)\nbutton1.place(x=505, y=375, width=70, height=30)\n\n\ndef private(*args):\n global chat\n # 获取点击的索引然后得到内容(用户名)\n indexs = listbox1.curselection()\n index = indexs[0]\n chat = listbox1.get(index)\n # 修改客户端名称\n if chat == '----------群聊----------':\n root.title(user)\n return\n ti = user + ' --> ' + chat\n root.title(ti)\n\n\n# 在显示用户列表框上设置绑定事件\nlistbox1.bind('', private)\n\n\n# 用于时刻接收服务端发送的信息并打印,\ndef recv():\n global users\n while True:\n data = s.recv(1024)\n data = data.decode()\n # 没有捕获到异常则表示接收到的是在线用户列表\n try:\n data = json.loads(data)\n users = data\n listbox1.delete(0, tkinter.END) # 清空列表框\n number = (' 在线人数: ' + str(len(data)) + ' 人')\n listbox1.insert(tkinter.END, number)\n listbox1.itemconfig(tkinter.END, fg='green', bg=\"#f0f0ff\")\n listbox1.insert(tkinter.END, '----------群聊----------')\n listbox1.itemconfig(tkinter.END, fg='green')\n for i in range(len(data)):\n listbox1.insert(tkinter.END, (data[i]))\n listbox1.itemconfig(tkinter.END, fg='green')\n except:\n data = data.split(':;')\n data1 = data[0] # 消息\n data2 = data[1] # 发送信息的用户名\n data3 = data[2] # 聊天对象\n if data3 == '----------群聊----------':\n listbox.insert(tkinter.END, data1) # END将信息加在最后一行\n listbox.see(tkinter.END) # 显示在最后\n u = data1.split(':')[0] # 截取消息中的用户名\n if u == ' ' + user: # 如果是自己则将则字体变为蓝色\n listbox.itemconfig(tkinter.END, fg='blue')\n elif data2 == user or data3 == user: # 显示私聊\n listbox.insert(tkinter.END, data1) # END将信息加在最后一行\n listbox.see(tkinter.END) # 显示在最后\n listbox.itemconfig(tkinter.END, fg='red')\n\n\nr = threading.Thread(target=recv)\nr.start() # 开始线程接收信息\n\nroot.mainloop()\ns.close() # 关闭图形界面后关闭TCP连接","sub_path":"python核心编程/网络编程/ciltend_1.py","file_name":"ciltend_1.py","file_ext":"py","file_size_in_byte":6360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"73936491","text":"import numpy as np\nimport face_recognition\nfrom skimage import transform\n\n\ndef has_one_face(np_image):\n\t\"\"\"\n\tobj: return true if the an image has a single face\n\t\"\"\"\n\tface_landmarks = face_recognition.face_landmarks(np_image)\n\treturn len(face_landmarks) == 1\n\n\ndef align_face(np_image, face_zoom, final_image_height=None, final_image_width=None):\n\t\"\"\"\n\tobj: align a face to proper position and dimension\n\t\timage constraints:\n\t\t\t- must have one face\n\t\t\t- must be colored\n\t\"\"\"\n\tif len(np_image.shape) != 3:\n\t\traise ValueError('Image array must be colored (have 3 channels)')\n\n\tif not has_one_face(np_image):\n\t\traise ValueError('Image array must have one face.')\n\n\tfinal_image_height = final_image_height or np_image.shape[0]\n\tfinal_image_width = final_image_width or np_image.shape[1]\n\n\tif final_image_height > np_image.shape[0]:\n\t\traise ValueError(f'final_image_height of {final_image_height} cannot exceed original image height of {np_image.shape[0]}.')\n\n\tif final_image_width > np_image.shape[1]:\n\t\traise ValueError(f'final_image_height of {final_image_width} cannot exceed original image height of {np_image.shape[1]}.')\n\n\tdesired_x = int(np_image.shape[1] / 2)\n\tdesired_y = int(np_image.shape[0] / 2)\n\n\tface_landmarks = face_recognition.face_landmarks(np_image)\n\n\tdef average_landmark_position(face, landmark):\n\t\tcum = np.zeros(2)\n\t\tfor point in face[landmark]:\n\t\t\tcum[0] += point[0]\n\t\t\tcum[1] += point[1]\n\t\treturn cum / len(face[landmark])\n\n\tleft_eye_position = average_landmark_position(face_landmarks[0], 'left_eye')\n\tright_eye_position = average_landmark_position(face_landmarks[0], 'right_eye')\n\tmouth_position = average_landmark_position(face_landmarks[0], 'bottom_lip')\n\tcenter_eye_position = (left_eye_position + right_eye_position) / 2\n\n\tface_width = np.linalg.norm(left_eye_position - right_eye_position)\n\tface_height = np.linalg.norm(center_eye_position - mouth_position)\n\n\tface_size = (face_width + face_height) / 2\n\tto_scale_factor = face_size / face_zoom\n\tto_x_shift = (center_eye_position[0])\n\tto_y_shift = (center_eye_position[1])\n\tto_rotate_factor = np.arctan2(right_eye_position[1] - left_eye_position[1], right_eye_position[0] - left_eye_position[0])\n\trotate_t = transform.SimilarityTransform(scale=to_scale_factor, rotation=to_rotate_factor, translation=(to_x_shift, to_y_shift))\n\tmove_t = transform.SimilarityTransform(scale=1, rotation=0, translation=(-desired_x, -desired_y))\n\taligned_face = transform.warp(image=np_image, inverse_map=(move_t + rotate_t))\n\th, w, _ = aligned_face.shape\n\tupper_left_corner_x, upper_left_corner_y = int((w / 2) - (final_image_width / 2)), int((h / 2) - (final_image_height / 2))\n\taligned_face_size_limited = aligned_face[upper_left_corner_y:upper_left_corner_y + final_image_height,\n\t upper_left_corner_x:final_image_width + upper_left_corner_x]\n\t# swap channel 2 with 1\n\t# aligned_face[:, :, [0, 2]] = aligned_face[:, :, [2, 0]]\n\treturn aligned_face_size_limited\n\n\ndef make_average_face(numpy_frames):\n\treturn np.mean(([frame for frame in numpy_frames]), axis=0)\n","sub_path":"mltoolbox/mltoolbox/cv/face.py","file_name":"face.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"69313603","text":"def findTarget(self, root, k):\r\n \"\"\"\r\n :type root: TreeNode\r\n :type k: int\r\n :rtype: bool\r\n \"\"\"\r\n if not root:\r\n return False\r\n\r\n return self._findTarget(root, set(), k)\r\n\r\n\r\ndef _findTarget(self, node, nodes, k):\r\n if not node:\r\n return False\r\n\r\n complement = k - node.val\r\n if complement in nodes:\r\n return True\r\n\r\n nodes.add(node.val)\r\n\r\n return self._findTarget(node.left, nodes, k) or self._findTarget(node.right, nodes, k)","sub_path":"653twoSum.py","file_name":"653twoSum.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"285129122","text":"\r\n\r\n# from datadb import *\r\nfrom clock import *\r\nimport os\r\n\r\nnewConnection = DataDB()\r\n\r\nclass Launch:\r\n\r\n def main(self,id):\r\n # hr12 = ('%I:%M:%S')\r\n # hr24 = ('%H:%M:%S')\r\n\r\n c1 = Clock(id)\r\n\r\n\r\n def getId(self):\r\n try:\r\n id = int(input(\"Please enter an integer to create and track your clock: \"))\r\n self.main(id)\r\n assert type(id) == type(1), \"id is not an integer: %r\" % id\r\n except:\r\n print(\"Clock ID must be an integer, try again\")\r\n self.getId()\r\n\r\n\r\n def firstRun(self):\r\n\r\n if os.path.isfile(\"hasrun.dat\"):\r\n self.getId()\r\n else:\r\n print(\"\"\"\r\n First run hints:\r\n\r\n * Change the clock settings (12hr or 24hr).\r\n * The program keeps settings in a database so they'll persist\r\n * Feel free to make as many clocks as you like!\r\n\r\n \"\"\")\r\n open(\"hasrun.dat\",\"w\").close()\r\n self.getId()\r\n\r\nlauncher = Launch()\r\nlauncher.firstRun()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"14162544","text":"import random\r\n\r\nimport numpy as np\r\n\r\nfrom GeneticAlgorithm.tools import crossover\r\nfrom GeneticAlgorithm.tools import selection\r\n\r\n\r\ndef breed_uniform(individuals, parents, n_children, co_prob):\r\n \"\"\"\r\n Parents are chosen in an uniform matter to produce children for the next generation.\r\n Note a pair of parents produce only one child (child1).\r\n :param individuals: List of floats\r\n :param parents: List of integers (index of individuals to mate)\r\n :param n_children: Integer\r\n :param co_prob: Float\r\n :return: Tuple of lists\r\n \"\"\"\r\n children = ()\r\n sample_size = 2\r\n for i in range(n_children):\r\n parent1, parent2 = random.sample(parents, sample_size)\r\n child1, child2 = crossover.co_uniform(individuals[parent1], individuals[parent2], co_prob)\r\n children += (child1,)\r\n return children\r\n\r\n\r\ndef breed_roulette(individuals, parents, parents_fitness, n_children, co_prob):\r\n \"\"\"\r\n Parents are chosen in a roulette fashion to produce children for the next generation.\r\n Note a pair of parents produce only one child (child1).\r\n :param individuals: List of floats\r\n :param parents: List of integers (index of individuals to mate)\r\n :param parents_fitness: List of floats\r\n :param n_children: Integer\r\n :param co_prob: Float\r\n :return: Tuple of lists\r\n \"\"\"\r\n children = ()\r\n sample_size = 2\r\n for i in range(n_children):\r\n index = selection.sel_roulette(parents_fitness, sample_size) # Select parent index through roulette selection\r\n parent1, parent2 = parents[index[0]], parents[index[1]]\r\n child1, child2 = crossover.co_uniform(individuals[parent1], individuals[parent2], co_prob)\r\n children += (child1,)\r\n return children\r\n\r\n\r\ndef breed_uniform_one_point(individuals, parents, n_children):\r\n \"\"\"\r\n Parents selected uniformly and uses one point crossover to produce children for the next generation.\r\n :param individuals: List of floats\r\n :param parents: List of integers (index of individuals to mate)\r\n :param n_children: Integer\r\n :return: Tuple of lists\r\n \"\"\"\r\n children = ()\r\n sample_size = 2\r\n for i in range(n_children):\r\n parent1, parent2 = random.sample(parents, sample_size)\r\n child1, child2 = crossover.co_one_point(individuals[parent1], individuals[parent2])\r\n children += (child1,)\r\n return children\r\n\r\n\r\ndef breed_unique(individuals, parents):\r\n \"\"\"\r\n Breed all parents once.\r\n :param individuals:\r\n :param parents:\r\n :return:\r\n \"\"\"\r\n if len(parents) % 2 != 0:\r\n print(\"The number of parents are not even\")\r\n children = ()\r\n for i, parent in enumerate(parents):\r\n if i < np.floor(len(parents) / 2):\r\n child1, child2 = crossover.co_uniform(individuals[parents[i]], individuals[parents[-i-1]], co_prob=0.5)\r\n children += (child1,)\r\n\r\n return children\r\n\r\n\r\ndef breed_copy(individuals, parents):\r\n \"\"\"\r\n Copy the parents\r\n :param individuals: List\r\n :param parents: List of integers (indexes)\r\n :return: List\r\n \"\"\"\r\n children = ()\r\n for parent in parents:\r\n children += (list(individuals[parent]),)\r\n return children\r\n","sub_path":"tools/breed.py","file_name":"breed.py","file_ext":"py","file_size_in_byte":3217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"152239115","text":"# Copyright 2017 Battelle Energy Alliance, LLC\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 Created on May 8, 2018\n\n @author: talbpaul\n Originally from SupervisedLearning.py, split in PR #650 in July 2018\n Specific ROM implementation for SciKitLearn ROMs\n\"\"\"\n#for future compatibility with Python 3--------------------------------------------------------------\nfrom __future__ import division, print_function, unicode_literals, absolute_import\n#End compatibility block for Python 3----------------------------------------------------------------\n\n#Internal Modules (Lazy Importer)--------------------------------------------------------------------\nfrom utils.importerUtils import importModuleLazy\n#Internal Modules (Lazy Importer) End----------------------------------------------------------------\n\n#External Modules------------------------------------------------------------------------------------\nnp = importModuleLazy(\"numpy\")\nimport ast\n#External Modules End--------------------------------------------------------------------------------\n\n#Internal Modules------------------------------------------------------------------------------------\nfrom .SupervisedLearning import supervisedLearning\nfrom utils import utils\n#Internal Modules End--------------------------------------------------------------------------------\n\nclass SciKitLearn(supervisedLearning):\n \"\"\"\n An Interface to the ROMs provided by skLearn\n \"\"\"\n # the normalization strategy is defined through the Boolean value in the dictionary below:\n # {mainClass:{subtype:(classPointer,Output type (float or int), boolean -> External Z-normalization needed)}\n ROMtype = 'SciKitLearn'\n\n ## This seems more manual than it needs to be, why not use something like:\n # import os, sys, pkgutil, inspect\n # import sklearn\n\n # # sys.modules['sklearn']\n # sklearnSubmodules = [name for _,name,_ in pkgutil.iter_modules([os.path.dirname(sklearn.__file__)])]\n # loadedSKL = []\n\n # sklLibrary = {}\n # for key,mod in globals().items():\n # if key in sklearnSubmodules:\n # members = inspect.getmembers(mod, inspect.isclass)\n # for mkey,member in members:\n # sklLibrary[key+'|'+mkey] = member\n\n ## Now sklLibrary holds keys that are the same as what the user inputs, and\n ## the values are the classes that can be directly instantiated. One would\n ## still need the float/int and boolean designations, but my suspicion is that\n ## these \"special\" cases are just not being handled in a generic enough\n ## fashion. This doesn't seem like something we should be tracking.\n\n\n availImpl = {} # dictionary of available ROMs {mainClass:{subtype:(classPointer,Output type (float or int), boolean -> External Z-normalization needed)}\n\n def __init__(self,messageHandler,**kwargs):\n \"\"\"\n A constructor that will appropriately initialize a supervised learning object\n @ In, messageHandler, MessageHandler object, it is in charge of raising errors, and printing messages\n @ In, kwargs, dict, an arbitrary list of kwargs\n @ Out, None\n \"\"\"\n supervisedLearning.__init__(self,messageHandler,**kwargs)\n import sklearn\n import sklearn.linear_model\n import sklearn.svm\n import sklearn.multiclass\n import sklearn.naive_bayes\n import sklearn.neighbors\n import sklearn.tree\n import sklearn.gaussian_process\n import sklearn.discriminant_analysis\n import sklearn.neural_network\n\n if len(self.availImpl) == 0:\n self.availImpl['lda'] = {} #Linear Discriminant Analysis\n self.availImpl['qda'] = {} #Quadratic Discriminant Analysis\n self.availImpl['lda']['LDA' ] = (sklearn.discriminant_analysis.LinearDiscriminantAnalysis , 'int' , False) #Linear Discriminant Analysis (LDA)\n self.availImpl['qda']['QDA' ] = (sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis , 'int' , False) #Quadratic Discriminant Analysis (QDA)\n self.availImpl['linear_model'] = {} #Generalized Linear Models\n self.availImpl['linear_model']['ARDRegression' ] = (sklearn.linear_model.ARDRegression , 'float' , False) #Bayesian ARD regression.\n self.availImpl['linear_model']['BayesianRidge' ] = (sklearn.linear_model.BayesianRidge , 'float' , False) #Bayesian ridge regression\n self.availImpl['linear_model']['ElasticNet' ] = (sklearn.linear_model.ElasticNet , 'float' , False) #Linear Model trained with L1 and L2 prior as regularizer\n self.availImpl['linear_model']['ElasticNetCV' ] = (sklearn.linear_model.ElasticNetCV , 'float' , False) #Elastic Net model with iterative fitting along a regularization path\n self.availImpl['linear_model']['Lars' ] = (sklearn.linear_model.Lars , 'float' , False) #Least Angle Regression model a.k.a.\n self.availImpl['linear_model']['LarsCV' ] = (sklearn.linear_model.LarsCV , 'float' , False) #Cross-validated Least Angle Regression model\n self.availImpl['linear_model']['Lasso' ] = (sklearn.linear_model.Lasso , 'float' , False) #Linear Model trained with L1 prior as regularizer (aka the Lasso)\n self.availImpl['linear_model']['LassoCV' ] = (sklearn.linear_model.LassoCV , 'float' , False) #Lasso linear model with iterative fitting along a regularization path\n self.availImpl['linear_model']['LassoLars' ] = (sklearn.linear_model.LassoLars , 'float' , False) #Lasso model fit with Least Angle Regression a.k.a.\n self.availImpl['linear_model']['LassoLarsCV' ] = (sklearn.linear_model.LassoLarsCV , 'float' , False) #Cross-validated Lasso, using the LARS algorithm\n self.availImpl['linear_model']['LassoLarsIC' ] = (sklearn.linear_model.LassoLarsIC , 'float' , False) #Lasso model fit with Lars using BIC or AIC for model selection\n self.availImpl['linear_model']['LinearRegression' ] = (sklearn.linear_model.LinearRegression , 'float' , False) #Ordinary least squares Linear Regression.\n self.availImpl['linear_model']['LogisticRegression' ] = (sklearn.linear_model.LogisticRegression , 'float' , True ) #Logistic Regression (aka logit, MaxEnt) classifier.\n self.availImpl['linear_model']['MultiTaskLasso' ] = (sklearn.linear_model.MultiTaskLasso , 'float' , False) #Multi-task Lasso model trained with L1/L2 mixed-norm as regularizer\n self.availImpl['linear_model']['MultiTaskElasticNet' ] = (sklearn.linear_model.MultiTaskElasticNet , 'float' , False) #Multi-task ElasticNet model trained with L1/L2 mixed-norm as regularizer\n self.availImpl['linear_model']['OrthogonalMatchingPursuit' ] = (sklearn.linear_model.OrthogonalMatchingPursuit , 'float' , False) #Orthogonal Mathching Pursuit model (OMP)\n self.availImpl['linear_model']['OrthogonalMatchingPursuitCV' ] = (sklearn.linear_model.OrthogonalMatchingPursuitCV , 'float' , False) #Cross-validated Orthogonal Mathching Pursuit model (OMP)\n self.availImpl['linear_model']['PassiveAggressiveClassifier' ] = (sklearn.linear_model.PassiveAggressiveClassifier , 'int' , True ) #Passive Aggressive Classifier\n self.availImpl['linear_model']['PassiveAggressiveRegressor' ] = (sklearn.linear_model.PassiveAggressiveRegressor , 'float' , True ) #Passive Aggressive Regressor\n self.availImpl['linear_model']['Perceptron' ] = (sklearn.linear_model.Perceptron , 'float' , True ) #Perceptron\n self.availImpl['linear_model']['Ridge' ] = (sklearn.linear_model.Ridge , 'float' , False) #Linear least squares with l2 regularization.\n self.availImpl['linear_model']['RidgeClassifier' ] = (sklearn.linear_model.RidgeClassifier , 'float' , False) #Classifier using Ridge regression.\n self.availImpl['linear_model']['RidgeClassifierCV' ] = (sklearn.linear_model.RidgeClassifierCV , 'int' , False) #Ridge classifier with built-in cross-validation.\n self.availImpl['linear_model']['RidgeCV' ] = (sklearn.linear_model.RidgeCV , 'float' , False) #Ridge regression with built-in cross-validation.\n self.availImpl['linear_model']['SGDClassifier' ] = (sklearn.linear_model.SGDClassifier , 'int' , True ) #Linear classifiers (SVM, logistic regression, a.o.) with SGD training.\n self.availImpl['linear_model']['SGDRegressor' ] = (sklearn.linear_model.SGDRegressor , 'float' , True ) #Linear model fitted by minimizing a regularized empirical loss with SGD\n\n self.availImpl['svm'] = {} #support Vector Machines\n self.availImpl['svm']['LinearSVC' ] = (sklearn.svm.LinearSVC , 'bool' , True ) #Linear Support vector classifier\n self.availImpl['svm']['SVC' ] = (sklearn.svm.SVC , 'bool' , True ) #Support vector classifier\n self.availImpl['svm']['NuSVC' ] = (sklearn.svm.NuSVC , 'bool' , True ) #Nu Support vector classifier\n self.availImpl['svm']['SVR' ] = (sklearn.svm.SVR , 'float' , True ) #Support vector regressor\n\n self.availImpl['multiClass'] = {} #Multiclass and multilabel classification\n self.availImpl['multiClass']['OneVsRestClassifier' ] = (sklearn.multiclass.OneVsRestClassifier , 'int' , False) # One-vs-the-rest (OvR) multiclass/multilabel strategy\n self.availImpl['multiClass']['OneVsOneClassifier' ] = (sklearn.multiclass.OneVsOneClassifier , 'int' , False) # One-vs-one multiclass strategy\n self.availImpl['multiClass']['OutputCodeClassifier' ] = (sklearn.multiclass.OutputCodeClassifier , 'int' , False) # (Error-Correcting) Output-Code multiclass strategy\n\n self.availImpl['naiveBayes'] = {}\n self.availImpl['naiveBayes']['GaussianNB' ] = (sklearn.naive_bayes.GaussianNB , 'float' , True )\n self.availImpl['naiveBayes']['MultinomialNB' ] = (sklearn.naive_bayes.MultinomialNB , 'float' , False)\n self.availImpl['naiveBayes']['BernoulliNB' ] = (sklearn.naive_bayes.BernoulliNB , 'float' , True )\n\n self.availImpl['neighbors'] = {}\n self.availImpl['neighbors']['KNeighborsClassifier' ] = (sklearn.neighbors.KNeighborsClassifier , 'int' , True )# Classifier implementing the k-nearest neighbors vote.\n self.availImpl['neighbors']['RadiusNeighbors' ] = (sklearn.neighbors.RadiusNeighborsClassifier , 'int' , True )# Classifier implementing a vote among neighbors within a given radius\n self.availImpl['neighbors']['KNeighborsRegressor' ] = (sklearn.neighbors.KNeighborsRegressor , 'float' , True )# Regression based on k-nearest neighbors.\n self.availImpl['neighbors']['RadiusNeighborsRegressor' ] = (sklearn.neighbors.RadiusNeighborsRegressor , 'float' , True )# Regression based on neighbors within a fixed radius.\n self.availImpl['neighbors']['NearestCentroid' ] = (sklearn.neighbors.NearestCentroid , 'int' , True )# Nearest centroid classifier.\n self.availImpl['neighbors']['BallTree' ] = (sklearn.neighbors.BallTree , 'float' , True )# BallTree for fast generalized N-point problems\n self.availImpl['neighbors']['KDTree' ] = (sklearn.neighbors.KDTree , 'float' , True )# KDTree for fast generalized N-point problems\n\n self.availImpl['tree'] = {}\n self.availImpl['tree']['DecisionTreeClassifier' ] = (sklearn.tree.DecisionTreeClassifier , 'int' , True )# A decision tree classifier.\n self.availImpl['tree']['DecisionTreeRegressor' ] = (sklearn.tree.DecisionTreeRegressor , 'float' , True )# A tree regressor.\n self.availImpl['tree']['ExtraTreeClassifier' ] = (sklearn.tree.ExtraTreeClassifier , 'int' , True )# An extremely randomized tree classifier.\n self.availImpl['tree']['ExtraTreeRegressor' ] = (sklearn.tree.ExtraTreeRegressor , 'float' , True )# An extremely randomized tree regressor.\n\n self.availImpl['GaussianProcess'] = {}\n self.availImpl['GaussianProcess']['GaussianProcess' ] = (sklearn.gaussian_process.GaussianProcessRegressor , 'float' , False)\n # Neural network models (supervised)\n # To be removed when the supported minimum version of sklearn is moved to 0.18\n if int(sklearn.__version__.split(\".\")[1]) > 17:\n self.availImpl['neural_network'] = {}\n self.availImpl['neural_network']['MLPClassifier' ] = (sklearn.neural_network.MLPClassifier , 'int' , True) # Multi-layer perceptron classifier.\n self.availImpl['neural_network']['MLPRegressor' ] = (sklearn.neural_network.MLPRegressor , 'float' , True) # Multi-layer perceptron regressor.\n\n #test if a method to estimate the probability of the prediction is available\n self.__class__.qualityEstTypeDict = {}\n for key1, myDict in self.availImpl.items():\n self.__class__.qualityEstTypeDict[key1] = {}\n for key2 in myDict:\n self.__class__.qualityEstTypeDict[key1][key2] = []\n if callable(getattr(myDict[key2][0], \"predict_proba\", None)):\n self.__class__.qualityEstTypeDict[key1][key2] += ['probability']\n elif callable(getattr(myDict[key2][0], \"score\" , None)):\n self.__class__.qualityEstTypeDict[key1][key2] += ['score']\n else:\n self.__class__.qualityEstTypeDict[key1][key2] = False\n\n name = self.initOptionDict.pop('name','')\n # some keywords aren't useful for this ROM\n if 'pivotParameter' in self.initOptionDict:\n # remove pivot parameter if present\n self.initOptionDict.pop('pivotParameter',None)\n self.initOptionDict.pop('paramInput',None)\n self.printTag = 'SCIKITLEARN'\n if 'SKLtype' not in self.initOptionDict.keys():\n self.raiseAnError(IOError,'to define a scikit learn ROM the SKLtype keyword is needed (from ROM \"'+name+'\")')\n SKLtype, SKLsubType = self.initOptionDict['SKLtype'].split('|')\n self.subType = SKLsubType\n self.intrinsicMultiTarget = 'MultiTask' in self.initOptionDict['SKLtype']\n self.initOptionDict.pop('SKLtype')\n if not SKLtype in self.__class__.availImpl.keys():\n self.raiseAnError(IOError,'not known SKLtype \"' + SKLtype +'\" (from ROM \"'+name+'\")')\n if not SKLsubType in self.__class__.availImpl[SKLtype].keys():\n self.raiseAnError(IOError,'not known SKLsubType \"' + SKLsubType +'\" (from ROM \"'+name+'\")')\n\n self.__class__.returnType = self.__class__.availImpl[SKLtype][SKLsubType][1]\n self.externalNorm = self.__class__.availImpl[SKLtype][SKLsubType][2]\n self.__class__.qualityEstType = self.__class__.qualityEstTypeDict[SKLtype][SKLsubType]\n\n if 'estimator' in self.initOptionDict.keys():\n estimatorDict = self.initOptionDict['estimator']\n self.initOptionDict.pop('estimator')\n estimatorSKLtype, estimatorSKLsubType = estimatorDict['SKLtype'].split('|')\n estimator = self.__class__.availImpl[estimatorSKLtype][estimatorSKLsubType][0]()\n if self.intrinsicMultiTarget:\n self.ROM = [self.__class__.availImpl[SKLtype][SKLsubType][0](estimator)]\n else:\n self.ROM = [self.__class__.availImpl[SKLtype][SKLsubType][0](estimator) for _ in range(len(self.target))]\n else:\n if self.intrinsicMultiTarget:\n self.ROM = [self.__class__.availImpl[SKLtype][SKLsubType][0]()]\n else:\n self.ROM = [self.__class__.availImpl[SKLtype][SKLsubType][0]() for _ in range(len(self.target))]\n\n for key,value in self.initOptionDict.items():\n try:\n self.initOptionDict[key] = ast.literal_eval(value)\n except:\n pass\n\n for index in range(len(self.ROM)):\n self.ROM[index].set_params(**self.initOptionDict)\n\n def _readdressEvaluateConstResponse(self,edict):\n \"\"\"\n Method to re-address the evaluate base class method in order to avoid wasting time\n in case the training set has an unique response (e.g. if 10 points in the training set,\n and the 10 outcomes are all == to 1, this method returns one without the need of an\n evaluation)\n @ In, edict, dict, prediction request. Not used in this method (kept the consistency with evaluate method)\n @ Out, returnDict, dict, dictionary with the evaluation (in this case, the constant number)\n \"\"\"\n returnDict = {}\n #get the number of inputs provided to this ROM to evaluate\n numInputs = len(utils.first(edict.values()))\n #fill the target values\n for index,target in enumerate(self.target):\n returnDict[target] = np.ones(numInputs)*self.myNumber[index]\n return returnDict\n\n def _readdressEvaluateRomResponse(self,edict):\n \"\"\"\n Method to re-address the evaluate base class method to its original method\n @ In, edict, dict, prediction request. Not used in this method (kept the consistency with evaluate method)\n @ Out, evaluate, float, the evaluation\n \"\"\"\n return self.__class__.evaluate(self,edict)\n\n def __trainLocal__(self,featureVals,targetVals):\n \"\"\"\n Perform training on samples in featureVals with responses y.\n For an one-class model, +1 or -1 is returned.\n @ In, featureVals, {array-like, sparse matrix}, shape=[n_samples, n_features],\n an array of input feature values\n @ Out, targetVals, array, shape = [n_samples,n_targets], an array of output target\n associated with the corresponding points in featureVals\n \"\"\"\n #If all the target values are the same no training is needed and the moreover the self.evaluate could be re-addressed to this value\n if self.intrinsicMultiTarget:\n self.ROM[0].fit(featureVals,targetVals)\n else:\n # if all targets only have a single unique value, just store that value, no need to fit/train\n if all([len(np.unique(targetVals[:,index])) == 1 for index in range(len(self.ROM))]):\n self.myNumber = [np.unique(targetVals[:,index])[0] for index in range(len(self.ROM)) ]\n self.evaluate = self._readdressEvaluateConstResponse\n else:\n for index in range(len(self.ROM)):\n self.ROM[index].fit(featureVals,targetVals[:,index])\n self.evaluate = self._readdressEvaluateRomResponse\n\n def __confidenceLocal__(self,featureVals):\n \"\"\"\n This should return an estimation of the quality of the prediction.\n @ In, featureVals, 2-D numpy array, [n_samples,n_features]\n @ Out, confidenceDict, dict, dict of the dictionary for each target\n \"\"\"\n confidenceDict = {}\n if 'probability' in self.__class__.qualityEstType:\n for index, target in enumerate(self.ROM):\n confidenceDict[target] = self.ROM[index].predict_proba(featureVals)\n else:\n self.raiseAnError(IOError,'the ROM '+str(self.initOptionDict['name'])+'has not the an method to evaluate the confidence of the prediction')\n return confidenceDict\n\n def __evaluateLocal__(self,featureVals):\n \"\"\"\n Evaluates a point.\n @ In, featureVals, np.array, list of values at which to evaluate the ROM\n @ Out, returnDict, dict, dict of all the target results\n \"\"\"\n returnDict = {}\n if not self.intrinsicMultiTarget:\n for index, target in enumerate(self.target):\n returnDict[target] = self.ROM[index].predict(featureVals)\n else:\n outcome = self.ROM[0].predict(featureVals)\n for index, target in enumerate(self.target):\n returnDict[target] = outcome[:,index]\n return returnDict\n\n def __resetLocal__(self):\n \"\"\"\n Reset ROM. After this method the ROM should be described only by the initial parameter settings\n @ In, None\n @ Out, None\n \"\"\"\n for index in range(len(self.ROM)):\n self.ROM[index] = self.ROM[index].__class__(**self.initOptionDict)\n\n def __returnInitialParametersLocal__(self):\n \"\"\"\n Returns a dictionary with the parameters and their initial values\n @ In, None\n @ Out, params, dict, dictionary of parameter names and initial values\n \"\"\"\n params = self.ROM[-1].get_params()\n return params\n\n def __returnCurrentSettingLocal__(self):\n \"\"\"\n Returns a dictionary with the parameters and their current values\n @ In, None\n @ Out, params, dict, dictionary of parameter names and current values\n \"\"\"\n self.raiseADebug('here we need to collect some info on the ROM status')\n params = {}\n return params\n\n def _localNormalizeData(self,values,names,feat):\n \"\"\"\n Overwrites default normalization procedure.\n @ In, values, list(float), unused\n @ In, names, list(string), unused\n @ In, feat, string, feature to (not) normalize\n @ Out, None\n \"\"\"\n if not self.externalNorm:\n self.muAndSigmaFeatures[feat] = (0.0,1.0)\n else:\n super(SciKitLearn, self)._localNormalizeData(values,names,feat)\n\n","sub_path":"framework/SupervisedLearning/SciKitLearn.py","file_name":"SciKitLearn.py","file_ext":"py","file_size_in_byte":22887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"221755557","text":"import tensorflow as tf\n\n# input : 输入的要做卷积的图片,要求为一个张量,shape为 [ batch, in_height, in_weight, in_channel ],\n# 其中batch为图片的数量,in_height 为图片高度,in_weight 为图片宽度,in_channel 为图片的通道数,灰度图该值为1,彩色图为3(rgb)。(也可以用其它值,但是具体含义不是很理解)\n# filter: 卷积核,要求也是一个张量,shape为 [ filter_height, filter_weight, in_channel, out_channels ],\n# 其中 filter_height 为卷积核高度,filter_weight 为卷积核宽度,in_channel 是图像通道数 ,和 input 的 in_channel 要保持一致,out_channel 是卷积核数量。\n# strides: 卷积时在图像每一维的步长,这是一个一维的向量,[ 1, strides, strides, 1],第一位和最后一位固定必须是1\n# padding: string类型,值为“SAME” 和 “VALID”,表示的是卷积的形式,是否考虑边界。\"SAME\"是考虑边界,不足的时候用0去填充周围,\"VALID\"则不考虑\n# use_cudnn_on_gpu: bool类型,是否使用cudnn加速,默认为true\n\n# case 1\n# 输入是1张 3*3 大小的图片,图像通道数是5,卷积核是 1*1 大小,数量是1\n# 步长是[1,1,1,1]最后得到一个 3*3 的feature map\n# 1张图最后输出就是一个 shape为[1,3,3,1] 的张量\ninput = tf.Variable(tf.random_normal([1, 3, 3, 5]))\nfilter = tf.Variable(tf.random_normal([1, 1, 5, 1]))\nop1 = tf.nn.conv2d(input, filter, strides=[1, 1, 1, 1], padding='SAME')\n\n# case 2\n# 输入是1张 3*3 大小的图片,图像通道数是5,卷积核是 2*2 大小,数量是1\n# 步长是[1,1,1,1]最后得到一个 3*3 的feature map\n# 1张图最后输出就是一个 shape为[1,3,3,1] 的张量\ninput = tf.Variable(tf.random_normal([1, 3, 3, 5]))\nfilter = tf.Variable(tf.random_normal([2, 2, 5, 1]))\nop2 = tf.nn.conv2d(input, filter, strides=[1, 1, 1, 1], padding='SAME')\n\n# case 3\n# 输入是1张 3*3 大小的图片,图像通道数是5,卷积核是 3*3 大小,数量是1\n# 步长是[1,1,1,1]最后得到一个 1*1 的feature map (不考虑边界)\n# 1张图最后输出就是一个 shape为[1,1,1,1] 的张量\ninput = tf.Variable(tf.random_normal([1, 3, 3, 5]))\nfilter = tf.Variable(tf.random_normal([3, 3, 5, 1]))\nop3 = tf.nn.conv2d(input, filter, strides=[1, 1, 1, 1], padding='VALID')\n\n# case 4\n# 输入是1张 5*5 大小的图片,图像通道数是5,卷积核是 3*3 大小,数量是1\n# 步长是[1,1,1,1]最后得到一个 3*3 的feature map (不考虑边界)\n# 1张图最后输出就是一个 shape为[1,3,3,1] 的张量\ninput = tf.Variable(tf.random_normal([1, 5, 5, 5]))\nfilter = tf.Variable(tf.random_normal([3, 3, 5, 1]))\nop4 = tf.nn.conv2d(input, filter, strides=[1, 1, 1, 1], padding='VALID')\n\n# case 5\n# 输入是1张 5*5 大小的图片,图像通道数是5,卷积核是 3*3 大小,数量是1\n# 步长是[1,1,1,1]最后得到一个 5*5 的feature map (考虑边界)\n# 1张图最后输出就是一个 shape为[1,5,5,1] 的张量\ninput = tf.Variable(tf.random_normal([1, 5, 5, 5]))\nfilter = tf.Variable(tf.random_normal([3, 3, 5, 1]))\nop5 = tf.nn.conv2d(input, filter, strides=[1, 1, 1, 1], padding='SAME')\n\n# case 6\n# 输入是1张 5*5 大小的图片,图像通道数是5,卷积核是 3*3 大小,数量是7\n# 步长是[1,1,1,1]最后得到一个 5*5 的feature map (考虑边界)\n# 1张图最后输出就是一个 shape为[1,5,5,7] 的张量\ninput = tf.Variable(tf.random_normal([1, 5, 5, 5]))\nfilter = tf.Variable(tf.random_normal([3, 3, 5, 7]))\nop6 = tf.nn.conv2d(input, filter, strides=[1, 1, 1, 1], padding='SAME')\n\n# case 7\n# 输入是1张 5*5 大小的图片,图像通道数是5,卷积核是 3*3 大小,数量是7\n# 步长是[1,2,2,1]最后得到7个 3*3 的feature map (考虑边界)\n# 1张图最后输出就是一个 shape为[1,3,3,7] 的张量\ninput = tf.Variable(tf.random_normal([1, 5, 5, 5]))\nfilter = tf.Variable(tf.random_normal([3, 3, 5, 7]))\nop7 = tf.nn.conv2d(input, filter, strides=[1, 2, 2, 1], padding='SAME')\n\n# case 8\n# 输入是10 张 5*5 大小的图片,图像通道数是5,卷积核是 3*3 大小,数量是7\n# 步长是[1,2,2,1]最后每张图得到7个 3*3 的feature map (考虑边界)\n# 10张图最后输出就是一个 shape为[10,3,3,7] 的张量\ninput = tf.Variable(tf.random_normal([10, 5, 5, 5]))\nfilter = tf.Variable(tf.random_normal([3, 3, 5, 7]))\nop8 = tf.nn.conv2d(input, filter, strides=[1, 2, 2, 1], padding='SAME')\n\ninit = tf.initialize_all_variables()\nwith tf.Session() as sess:\n sess.run(init)\n print('*' * 20 + ' op1 ' + '*' * 20)\n print(sess.run(op1))\n print('*' * 20 + ' op2 ' + '*' * 20)\n print(sess.run(op2))\n print('*' * 20 + ' op3 ' + '*' * 20)\n print(sess.run(op3))\n print('*' * 20 + ' op4 ' + '*' * 20)\n print(sess.run(op4))\n print('*' * 20 + ' op5 ' + '*' * 20)\n print(sess.run(op5))\n print('*' * 20 + ' op6 ' + '*' * 20)\n print(sess.run(op6))\n print('*' * 20 + ' op7 ' + '*' * 20)\n print(sess.run(op7))\n print('*' * 20 + ' op8 ' + '*' * 20)\n print(sess.run(op8))\n","sub_path":"tf/conv.py","file_name":"conv.py","file_ext":"py","file_size_in_byte":5064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"594827799","text":"'''\n@author: Al Sweigart (Automate Boring Stuffs with Python)\n'''\nfrom nis import cat\n\n'''Lesson 13: The List Data Type '''\n\n# A list is a value that contains multiple values. The values in a list\n# are also called items. You can access item in a list with its integer index\nspam = ['cat', 'bat', 'rat', 'elephant']\nprint(spam[1]) # 'bat'\n\n# List of lists\nspam = [['cat', 'bat'], [10, 20, 30, 40]]\nprint(spam[0][0]) # 'cat'\n\n# Negative index (-1 = last, -2 next to last)\nspam = ['cat', 'bat', 'rat', 'elephant']\nprint(spam[-1], spam[-2]) # 'elephant rat'\n\n# Slice - return a new list\nprint(spam[1:3]) # ['bat', 'rat']\n# Slice shortcuts\nspam = ['cat', 'bat', 'rat', 'elephant']\nspam[:2] # ['cat', 'bat']\nspam[1:] # ['bat', 'rat', 'elephant']\n\n# Changing list value\nspam = [10, 20, 30]\nspam[1] = 'Hello'\nprint(spam) # [10, 'Hello', 30]\n\n# Changing list values with list slice\nspam = [10, 'Hello', 30]\nspam[1:3] = ['CAT', 'DOG', 'MOUSE']\nprint(spam) # [10, 'CAT', 'DOG', 'MOUSE']\n\n# Delete elements from a list using del\nspam = ['cat', 'bat', 'rat', 'elephant']\ndel spam[2] # spam now equals ['cat', 'bat', 'elephant']\n\n# the len() function\nspam = ['cat', 'bat', 'rat', 'elephant']\nprint(len(spam)) # 4\n\n# List concatenation with '+'\nprint([1, 2, 3] + [4, 5, 6]) # [1, 2, 3, 4, 5, 6]\n\n# List replecation with '*'\nprint([1, 2, 3]*3)\n\n# Converting a value into a list by passing it to the list() function\nspam = list('Hello')\nprint(spam) # ['H', 'e', 'l', 'l', 'o']\n\n# The in and not in operators returns True or False\nprint('howdy' in ['hello', 'hi', 'howdy', 'heyas']) # True\nprint('howdy' not in ['hello', 'hi', 'howdy', 'heyas']) # True\n\n'''Lesson 14: For Loops with Lists, Multiple Assignment, and Augmented Operators, p86 - p88'''\n# The range() function returns a list-like value, which can be passed to the list() function\n# if you need an actual list value.\nfor i in range(4):\n print(i)\nfor i in [0, 1, 2, 3]:\n print(i)\n \nlist(range(4)) # [0, 1, 2, 3]\nlist(range(0, 10, 2)) # [0, 2, 4, 6, 8]\n\n# Iterating over a list with range(len(somelist))\nsupplies = ['pens', 'staplers', 'binders']\nfor i in range(len(supplies)):\n print(\"Index of \" + str(i) + \" in supplies is: \" + supplies[i])\n\n# Multiple assignment\ncat = ['fat', 'orange', 'loud']\n# size = cat[0]\n# color = cat[1]\n# disposition = cat[2]\nsize, color, disposition = cat[0], cat[1], cat[2] # same as previous 3 lines of code\nsize, color, disposition = cat # same as previous line\nsize, color, disposition = 'skinny', 'black', 'quiet'\n\n# Swapping Variables\na = 'AAA'\nb = 'BBB'\na, b = b, a\n\n# Augmented assignment operator like += are used as shortcuts\nspam = 42\nspam = spam + 1 # increment by 1\nspam += 1 # same as previous line of code\n\n'''Lesson 15: List Methods, p89-p92'''\n# Methods are functions that are called on values (list.method())\n# whereas functions are called like this function(list) such as len(list)\n\n# index() method returns the index of the first find\nspam = ['hello', 'hi', 'howdy', 'hey']\nprint(spam.index('hello')) # 0\n\nspam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka']\nspam.index('Pooka') # 1\n\n# append() method adds a value to the end of a list\nspam = ['cat', 'dog', 'bat']\nspam.append('moose') # ['cat', 'dog', 'bat', 'moose']\n\n# insert() method adds a value anywhere inside a list\nspam = ['cat', 'dog', 'bat']\nspam.insert(1, 'chicken') # ['cat', 'chicken', 'dog', 'bat']\n\n# remove() method\nspam = ['cat', 'dog', 'bat', 'elephant']\nspam.remove('bat')\n\nspam = ['cat', 'dog', 'bat', 'elephant', 'cat']\nspam.remove('cat') # [dog', 'bat', 'elephant', 'cat'] - only remove the first item that matches 'cat'\n\n# the sort() method\n# Note: Cannot sort list that contains both number and string\nspam = [2, 5, 3.14, 1, -7]\nspam.sort() # [-7, 1, 2, 3.14, 5]\nspam = ['ants', 'cats', 'dogs', 'badgers']\nspam.sort() # ['ants', 'badgers', 'cats', 'dogs']\nspam.sort(reverse=True) # ['dogs', 'cats', 'badgers', 'ants']\n\n# ASCII order (uppercase before lowercase)\nspam = ['A', 'Z', 'a', 'z']\nspam.sort() # ['A', 'Z', 'a', 'z']\n# spam.sort(key=str.lower) # ['A', 'a', 'Z', 'z']\n\n'''Lesson 16: Similarities Between Lists and Strings (p93 - p103)'''\n'''1. List is mutable whereas string is immutable'''\nname = 'Zophie a cat'\nnewName = name[0:7] + 'the' + name[8:]\nprint(newName)\n\n'''2. Reference\n- When creating a new list, assign the list to a reference variable\n'''\n\n# Passing list in function calls\ndef egg(someParam):\n someParam.append('Hello')\n\nspam = [1, 2, 3]\negg(spam)\nprint(spam) # [1, 2, 3, 'Hello']\n\n# The copy.deepcopy() function\nimport copy\nspam = ['A', 'B', 'C', 'D']\ncheese = copy.deepcopy(spam)\ncheese[1] = 42 # ['A', 42, 'C', 'D']\n\n# list definition spans multiple lines\nspam = ['apples',\n 'oranges',\n 'bananas']\n\n# line continuation with \\\nprint('Four scores and seven' + \\\n 'years ago.')\n\n# Ned Batchelder - Facts and Myths about Python names and values - PyCon 2015 \n# https://www.youtube.com/watch?v=_AEJHKGk9ns\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Python3/AlSweigart/Lists_Lesson13to16.py","file_name":"Lists_Lesson13to16.py","file_ext":"py","file_size_in_byte":4938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"540923919","text":"\n\n# quick and EXTREMELY messy hack to run nascentorder functions in beyondchaos\n# hopefully, this will allow updates on one end to easily copypasta\n# to the other.\nimport configparser, os.path, re\nfrom copy import copy\n\nfrom utils import (utilrandom as rng, open_mei_fallback as open)\nfrom mml2mfvi import mml_to_akao\n\ntry:\n from sys import _MEIPASS\n MEI = True\nexcept ImportError:\n MEI = False\n \nHIROM = 0xC00000\nMUSIC_PATH = os.path.join('custom','music')\nINST_METADATA_OFFSET = 0x310000 #0x600 bytes\nCONFIG = configparser.RawConfigParser({\n 'free_rom_space': '310600-380000',\n 'allow_music_repeats': 'False',\n 'preserve_song_data': 'False',\n 'battle_music_lookup': 'battle1, boss2, boss3, battle2, battle3, 3B, battle4, boss1',\n 'battle_music_ids': '24, new, new, new',\n 'boss_music_ids': 'new, 14, 33',\n 'pause_current_song': 'battle1, battle2, battle3, battle4, boss1',\n 'songcount': '53C5E',\n 'brrpointers': '53C5F, 53D1B',\n 'brrloops': '53D1C, 53D99',\n 'brrpitch': '53D9A, 53E17',\n 'brradsr': '53E18, 53E95',\n 'songpointers': '53E96, 53F94',\n 'instruments': '53F95, 54A34',\n 'brrpointerpointer': '50222, 50228, 5022E',\n 'brrlooppointer': '5041C',\n 'brrpitchpointer': '5049C',\n 'brradsrpointer': '504DE',\n 'songpointerpointer': '50538',\n 'instrumentpointer': '501E3',\n 'songdata': '85C7A, 9FDFF',\n 'pausesongs': '506F9, 506FD',\n 'battlesongs': '2BF3B, 2BF42'\n })\nCONFIG.add_section('Music')\nCONFIG.add_section('MusicPtr')\nCONFIG.add_section('General')\n\nfreespace = None\nspoiler = {}\nf_tellmewhy = False\nDEBUG = False\nFLAGS = set()\n\ndef safepath(vpath):\n if not MEI:\n return vpath\n return [vpath, os.path.join(_MEIPASS, vpath)]\n\ndef isfile(fn):\n if not MEI:\n return os.path.isfile(fn)\n \n if os.path.isfile(fn):\n return True\n elif os.path.isfile(os.path.join(_MEIPASS, fn)):\n return True\n else:\n return False\n \n#compatibility stubs\ndef to_default(cfgname): \n return CONFIG[cfgname]\n\ndef despoil(t=\"\"):\n pass\n\ndef dprint(t):\n pass\n\n### begin functions shared with nascentorder\n\ndef byte_insert(data, position, newdata, maxlength=0, end=0):\n while position > len(data):\n data = data + b\"\\x00\"\n if end:\n maxlength = end - position + 1\n if maxlength and len(data) > maxlength:\n newdata = newdata[:maxlength]\n return data[:position] + newdata + data[position+len(newdata):]\n\n \ndef int_insert(data, position, newdata, length, reversed=True):\n n = int(newdata)\n l = []\n while len(l) < length:\n l.append(n & 0xFF)\n n = n >> 8\n if n: dprint(\"WARNING: tried to insert {} into {} bytes, truncated\".format(hex(newdata), length))\n if not reversed: l.reverse()\n return byte_insert(data, position, bytes(l), length)\n\ndef bytes_to_int(data, reversed=True):\n n = 0\n for i, d in enumerate(data):\n if reversed:\n n = n + (d << (8 * i))\n else:\n n = (n << (8 * i)) + d\n return n\n \ndef put_somewhere(romdata, newdata, desc, f_silent=False):\n global freespace, spoiler\n if freespace is None:\n init_freespace()\n success = False\n for i, (start, end) in enumerate(freespace):\n room = end-start\n if room < len(newdata):\n continue\n else:\n romdata = byte_insert(romdata, start, newdata)\n freespace[i] = (start+len(newdata), end)\n if 'ROM Map' not in spoiler: spoiler['ROM Map'] = []\n spoiler['ROM Map'].append(\" 0x{:x} -- {}\".format(start, desc))\n success= True\n break\n if not success:\n if not silent: print(\"ERROR: not enough free space to insert {}\\n\\n\".format(desc))\n assert False\n return (romdata, start, end)\n \ndef init_freespace():\n global freespace\n fs = CONFIG.get('General', 'free_rom_space').split()\n freespace = []\n while not freespace:\n for t in fs:\n if '-' not in t: continue\n try:\n start, end = [int(n,16) for n in t.split('-')[0:2]]\n except ValueError:\n continue\n if start >= end: continue\n freespace.append((start, end))\n if not freespace:\n to_default('free_rom_space')\n continue\n break\n\ndef free_space(start, end):\n global freespace\n if freespace is None:\n init_freespace()\n freespace.append((start, end))\n \n newfs = []\n for i, (start, end) in enumerate(sorted(freespace)):\n if newfs:\n laststart, lastend = newfs[-1][0], newfs[-1][1]\n if start <= lastend + 1:\n newfs[-1] = (laststart, end)\n else:\n newfs.append((start, end))\n else:\n newfs.append((start, end))\n freespace = newfs\n\ndef claim_space(startc, endc):\n global freespace\n if freespace is None: return\n if startc > endc: return\n newfs = []\n for i, (start, end) in enumerate(sorted(freespace)):\n if startc <= start and endc >= end:\n pass\n elif startc <= start and endc >= start:\n newstart = endc+1\n if newstart < end:\n newfs.append((newstart, end))\n elif startc <= end and endc >= end:\n newend = startc-1\n if newend > start:\n newfs.append((start, newend))\n elif startc >= start and endc <= end:\n newend = startc-1\n newstart = endc+1\n if newend > start:\n newfs.append((start, newend))\n if newstart > end:\n newfs.append((newstart, end))\n else:\n newfs.append((start, end))\n freespace = newfs\n \ndef insert_instruments(data_in, metadata_pos= False):\n data = data_in\n samplecfg = configparser.ConfigParser()\n samplecfg.read(safepath(os.path.join('tables', 'samples.txt')))\n \n #pull out instrument infos\n sampleptrs = [int(s.strip(),16) for s in CONFIG.get('MusicPtr', 'brrpointers').split(',')]\n if len(sampleptrs) != 2: sampleptrs = to_default('brrpointers')\n ptrdata = data[sampleptrs[0]:sampleptrs[1]+1]\n \n looplocs = [int(s.strip(),16) for s in CONFIG.get('MusicPtr', 'brrloops').split(',')]\n if len(looplocs) != 2: looplocs = to_default('brrloops')\n loopdata = data[looplocs[0]:looplocs[1]+1]\n \n pitchlocs = [int(s.strip(),16) for s in CONFIG.get('MusicPtr', 'brrpitch').split(',')]\n if len(pitchlocs) != 2: pitchlocs = to_default('brrpitch')\n pitchdata = data[pitchlocs[0]:pitchlocs[1]+1]\n \n adsrlocs = [int(s.strip(),16) for s in CONFIG.get('MusicPtr', 'brradsr').split(',')]\n if len(adsrlocs) != 2: adsrlocs = to_default('brradsr')\n adsrdata = data[adsrlocs[0]:adsrlocs[1]+1]\n \n for id, smp in samplecfg.items('Samples'):\n id = int(id, 16)\n \n inst = [i.strip() for i in smp.split(',')]\n if len(inst) < 4:\n print(\"WARNING: malformed instrument info '{}'\".format(smp))\n continue\n name, loop, pitch, adsr = inst[0:4]\n filename = name + '.brr'\n \n try:\n with open(os.path.join('samples', filename), 'rb') as f:\n sdata = f.read()\n except IOError:\n print(\"WARNING: couldn't load sample file {}\".format(filename))\n continue\n \n try:\n loop = bytes([int(loop[0:2], 16), int(loop[2:4], 16)])\n except (ValueError, IndexError):\n print(\"WARNING: malformed loop info in '{}', using default\".format(smp))\n loop = b\"\\x00\\x00\"\n try:\n pitch = bytes([int(pitch[0:2], 16), int(pitch[2:4], 16)])\n except (ValueError, IndexError):\n print(\"WARNING: malformed pitch info in '{}', using default\".format(smp))\n pitch = b\"\\x00\\x00\"\n if adsr:\n try:\n attack, decay, sustain, release = [int(p,16) for p in adsr.split()[0:4]]\n assert attack < 16\n assert decay < 8\n assert sustain < 8\n assert release < 32\n ad = 1 << 7\n ad += decay << 4\n ad += attack\n sr = sustain << 5\n sr += release\n adsr = bytes([ad, sr])\n except (AssertionError, ValueError, IndexError):\n print(\"WARNING: malformed ADSR info in '{}', disabling envelope\".format(smp))\n adsr = b\"\\x00\\x00\"\n else:\n adsr = b\"\\x00\\x00\"\n \n data, s, e = put_somewhere(data, sdata, \"(sample) [{:02x}] {}\".format(id, name))\n ptrdata = int_insert(ptrdata, (id-1)*3, s + HIROM, 3)\n loopdata = byte_insert(loopdata, (id-1)*2, loop, 2)\n pitchdata = byte_insert(pitchdata, (id-1)*2, pitch, 2)\n adsrdata = byte_insert(adsrdata, (id-1)*2, adsr, 2)\n \n data = byte_insert(data, sampleptrs[0], ptrdata)\n CONFIG.set('MusicPtr', 'brrpointers', \"{:x}, {:x}\".format(sampleptrs[0], sampleptrs[0]+len(data)))\n if metadata_pos:\n p = metadata_pos\n metadata = b\"\\x00\"*0x600\n metadata = byte_insert(metadata, 0x0, loopdata)\n metadata = byte_insert(metadata, 0x200, pitchdata)\n metadata = byte_insert(metadata, 0x400, adsrdata)\n \n CONFIG.set('MusicPtr', 'brrloops', \"{:x}, {:x}\".format(0+p, 0x1FF+p))\n CONFIG.set('MusicPtr', 'brrpitch', \"{:x}, {:x}\".format(0x200+p, 0x3FF+p))\n CONFIG.set('MusicPtr', 'brradsr', \"{:x}, {:x}\".format(0x400+p, 0x5FF+p))\n \n loc = int(CONFIG.get('MusicPtr', 'brrlooppointer'),16)\n data = int_insert(data, loc, 0+p+HIROM, 3)\n loc = int(CONFIG.get('MusicPtr', 'brrpitchpointer'),16)\n data = int_insert(data, loc, 0x200+p+HIROM, 3)\n loc = int(CONFIG.get('MusicPtr', 'brradsrpointer'),16)\n data = int_insert(data, loc, 0x400+p+HIROM, 3)\n \n data = byte_insert(data, p, metadata)\n else:\n data, s, e = put_somewhere(data, loopdata, \"INSTRUMENT LOOP DATA\")\n CONFIG.set('MusicPtr', 'brrloops', \"{:x}, {:x}\".format(s, e))\n loc = int(CONFIG.get('MusicPtr', 'brrlooppointer'),16)\n data = int_insert(data, loc, s + HIROM, 3)\n\n data, s, e = put_somewhere(data, pitchdata, \"INSTRUMENT PITCH DATA\")\n CONFIG.set('MusicPtr', 'brrpitch', \"{:x}, {:x}\".format(s, e))\n loc = int(CONFIG.get('MusicPtr', 'brrpitchpointer'),16)\n data = int_insert(data, loc, s + HIROM, 3)\n\n data, s, e = put_somewhere(data, adsrdata, \"INSTRUMENT ADSR DATA\")\n CONFIG.set('MusicPtr', 'brradsr', \"{:x}, {:x}\".format(s, e))\n loc = int(CONFIG.get('MusicPtr', 'brradsrpointer'),16)\n data = int_insert(data, loc, s + HIROM, 3)\n \n return data\n\ndef process_custom_music(data_in, eventmodes=\"\", f_randomize=True, f_battleprog=True, f_mchaos=False, f_altsonglist=False):\n global freespace\n data = data_in\n freespacebackup = freespace\n f_repeat = CONFIG.getboolean('Music', 'allow_music_repeats')\n f_preserve = CONFIG.getboolean('Music', 'preserve_song_data')\n isetlocs = [int(s.strip(),16) for s in CONFIG.get('MusicPtr', 'instruments').split(',')]\n if len(isetlocs) != 2: isetlocs = to_default('instruments')\n songdatalocs = [int(s.strip(),16) for s in CONFIG.get('MusicPtr', 'songdata').split(',')]\n starts = songdatalocs[::2]\n ends = songdatalocs[1::2]\n if len(ends) < len(starts): ends.append(0x3FFFFF)\n songdatalocs = list(zip(starts, ends))\n native_prefix = \"ff6_\"\n isetsize = 0x20\n \n def spoil(txt):\n global spoiler\n if 'Music' not in spoiler: spoiler['Music'] = []\n spoiler['Music'].append(txt)\n \n def spooler(txt):\n global spoiler, f_tellmewhy\n if f_tellmewhy:\n if 'MusicPools' not in spoiler: spoiler['MusicPools'] = []\n spoiler['MusicPools'].append(txt)\n \n def usage_id(name):\n if name.count(\"_\") <= 1:\n return name\n return \"_\".join(name.split(\"_\")[0:2])\n \n class SongSlot:\n def __init__(self, id, chance=0, is_pointer=True, data=b\"\\x00\\x00\\x00\"):\n self.id = id\n self.chance = chance\n self.choices = []\n self.changeto = \"\"\n self.is_pointer = is_pointer\n self.data = data\n self.inst = b\"\"\n \n # figure out what instruments are available\n sampleptrs = [s.strip() for s in CONFIG.get('MusicPtr', 'brrpointers').split(',')]\n if len(sampleptrs) != 2: sampleptrs = to_default('brrpointers')\n instcount = (int(sampleptrs[1],16) + 1 - int(sampleptrs[0],16)) // 3\n \n ## figure out what music to use\n # build dict of original music from ROM\n try: songcountloc = int(CONFIG.get('MusicPtr', 'songcount'), 16)\n except ValueError: songcountloc = to_default('songcount')\n songptraddrs = [s.strip() for s in CONFIG.get('MusicPtr', 'songpointers').split(',')]\n if len(songptraddrs) != 2: songptraddrs = to_default('songpointers')\n songptraddrs = [int(p, 16) for p in songptraddrs]\n songptrdata = data[songptraddrs[0]:songptraddrs[1]+1]\n songptrs = []\n i = 0\n \n songcount = [data[songcountloc]]\n while i < songcount[0]:\n try: p = songptrdata[i*3:i*3+3]\n except IndexError: p = b'\\x00\\x00\\x00'\n songptrs.append(bytes_to_int(p) - HIROM)\n i += 1\n \n # build identifier table\n songconfig = configparser.ConfigParser()\n songconfig.read(safepath(os.path.join('tables','defaultsongs.txt')))\n songconfig.read(safepath(os.path.join('custom', 'songs.txt' if not f_altsonglist else 'songs_alt.txt')))\n songtable = {}\n for ss in songconfig.items('SongSlots'):\n vals = [s.strip() for s in ss[1].split(',')]\n songtable[vals[0]] = SongSlot(int(ss[0],16), chance=int(vals[1]))\n \n tierboss = dict(songconfig.items('TierBoss'))\n \n # determine which songs change\n used_songs = []\n songs_to_change = []\n for ident, s in songtable.items():\n if rng.randint(1, 100) > s.chance:\n if not f_repeat: used_songs.append(native_prefix + ident)\n songtable[ident].changeto = native_prefix + ident\n else:\n songs_to_change.append((ident, s))\n if f_mchaos and len(songconfig.items('Imports')) < len(songtable):\n if not songconfig.has_option('Imports', ident):\n songconfig.set('Imports', native_prefix + ident, \"\")\n \n # build choice lists\n intensitytable = {}\n for song in songconfig.items('Imports'):\n canbe = [s.strip() for s in song[1].split(',')]\n intense, epic = 0, 0\n event_mults = {}\n if f_mchaos:\n for ident, s in songtable.items():\n if ident.endswith(\"_tr\"): continue\n if ident.endswith(\"_dm\"): continue\n if ident.endswith(\"_vic\"): continue\n s.choices.append(song[0])\n for c in canbe:\n if not c: continue\n if c[0] in eventmodes and \":\" not in c:\n try:\n event_mults[c[0]] = int(c[1:])\n except ValueError:\n print(\"WARNING: in songs.txt: could not interpret '{}'\".format(c))\n static_mult = 1\n for k, v in event_mults.items():\n static_mult *= v\n for c in canbe:\n if not c: continue\n if \":\" in c and c[0] in eventmodes:\n c = c.split(':', 1)[1]\n if c[0] == \"I\":\n intense = int(c[1:])\n elif c[0] == \"E\" or c[0] == \"G\":\n epic = int(c[1:])\n elif not f_mchaos:\n if \"*\" in c:\n ch = c.split('*')\n mult = int(ch[1])\n ch = ch[0]\n else:\n ch = c\n mult = 1 \n if ch in songtable:\n songtable[ch].choices.extend([song[0]]*mult*static_mult)\n intense = max(0, min(intense, 99))\n epic = max(0, min(epic, 99))\n if (intense or epic):\n intensitytable[song[0]] = (intense, epic)\n \n for ident, s in songtable.items():\n spooler(\"{} pool ({}/{}): {}\".format(ident, len([i for i in s.choices if i == native_prefix + ident]), len(s.choices), s.choices))\n \n # battle select\n def process_battleprog():\n newsongs = 0\n nextsongid = songcount[0]\n battleids = [s.strip() for s in CONFIG.get('Music', 'battle_music_ids').split(',')]\n bossids = [s.strip() for s in CONFIG.get('Music', 'boss_music_ids').split(',')]\n newidx = 0\n old_method = False if \"battlebylevel\" not in FLAGS else True\n if not old_method:\n if len(battleids) != 4 or len(bossids) != 3:\n print(\"WARNING: Improper song ID configuration for default method (by area)\")\n print(\" Falling back to old method (by level)\")\n old_method = True\n FLAGS.append(\"battlebylevel\")\n \n for i, id in enumerate(battleids):\n if str(id).lower() == \"new\":\n songtable['NaObattle' + str(newidx)] = SongSlot(nextsongid, chance=100)\n battleids[i] = nextsongid\n nextsongid += 1\n newidx += 1\n else:\n battleids[i] = int(id, 16)\n newidx = 0\n for i, id in enumerate(bossids):\n if str(id).lower() == \"new\":\n songtable['NaOboss' + str(newidx)] = SongSlot(nextsongid, chance=100)\n bossids[i] = nextsongid\n nextsongid += 1\n newidx += 1\n else:\n bossids[i] = int(id, 16)\n claim_space(songptraddrs[0], songptraddrs[0] + 3*len(songtable))\n \n # what this is trying to do is:\n # we judge songs by pure INTENSITY or by combined INTENSITY and GRANDEUR\n # old method: all songs separated by pure intensity into battle and boss\n # within these categories they are set in combined rating order\n # new method: uses subsets of the I/G grid as pools for songs.\n # 1. event-battle (boss0) is chosen from I>33, G<33\n # 2. boss2 is chosen from I>min(boss0,60), G>66\n # 3. boss1 is chosen from I>boss0, boss0battle1\n def intensity_subset(imin=0, gmin=0, imax=99, gmax=99):\n return {k: v for k, v in intensitytable.items() if v[0] >= imin and v[0] <= imax and v[1] >= gmin and v[1] <= gmax and usage_id(k) not in used_songs}\n \n battlecount = len(battleids) + len(bossids)\n while len(intensitytable) < battlecount:\n dprint(\"WARNING: not enough battle songs marked, adding random song to pool\")\n newsong = rng.choice([k[0] for k in songconfig.items('Imports') if k not in intensitytable])\n intensitytable[newsong] = (rng.randint(0,9), rng.randint(0,9))\n\n if old_method:\n retry = True\n while retry:\n retry = False\n battlechoices = rng.sample([(k, sum(intensitytable[k]), intensitytable[k][0]) for k in intensitytable.keys()], battlecount)\n for c in battlechoices:\n if usage_id(battlechoices[0]) in used_songs: retry = True\n battlechoices.sort(key=operator.itemgetter(1))\n battleprog = [None]*len(battleids)\n bossprog = [None]*len(bossids)\n bosschoices = []\n battlechoices.sort(key=operator.itemgetter(2))\n for i in range(0, len(bossids)):\n bosschoices.append(battlechoices.pop(-1))\n bosschoices.sort(key=operator.itemgetter(1))\n while None in bossprog:\n bossprog[bossprog.index(None)] = bosschoices.pop(-1)\n bossprog.reverse()\n battlechoices.sort(key=operator.itemgetter(1))\n while None in battleprog:\n battleprog[battleprog.index(None)] = battlechoices.pop(0)\n battleprog = [b[0] for b in battleprog]\n bossprog = [b[0] for b in bossprog]\n else:\n tries=0\n while True:\n try:\n event, (ei, eg) = rng.choice(list(intensity_subset(imin=33, gmax=33).items()))\n bt = min(ei,60) \n\n super, (si, sg) = rng.choice(list(intensity_subset(imin=bt, gmin=66).items()))\n boss, (bi, bg) = rng.choice(list(intensity_subset(imin=bt, gmin=max(22,eg), gmax=sg).items()))\n wt = min(80,max(bg, 50))\n balance = rng.sample(list(intensity_subset(imax=bt, gmax=wt).items()), 2)\n if balance[0][1][0] + balance[0][1][1] > balance[1][1][0] + balance[1][1][1]:\n boutside, (boi, bog) = balance[1]\n binside, (bii, big) = balance[0]\n else:\n boutside, (boi, bog) = balance[0]\n binside, (bii, big) = balance[1]\n ruin = rng.sample(list(intensity_subset(imax=min(bi, si), gmin=max(bog,big)).items()), 2)\n if ruin[0][1][0] + ruin[0][1][1] > ruin[1][1][0] + ruin[1][1][1]:\n routside, (roi, rog) = ruin[1]\n rinside, (rii, rig) = ruin[0]\n else:\n routside, (roi, rog) = ruin[0]\n rinside, (rii, rig) = ruin[1]\n battleprog = [boutside, binside, routside, rinside]\n bossprog = [event, boss, super]\n if len(set(battleprog) | set(bossprog)) < 7:\n tries += 1\n continue\n except IndexError as e:\n print(\"DEBUG: new battle prog mode failed {}rd attempt: {}\".format(tries, e))\n input(\"press enter to continue>\")\n if tries >= 500:\n FLAGS.append(\"battlebylevel\")\n print(\"WARNING: couldn't find valid configuration of battle songs by area.\")\n print(\" Falling back to old method (by level).\")\n return process_battleprog()\n else:\n tries += 1\n continue\n break\n \n fightids = [(id, False) for id in battleids] + [(id, True) for id in bossids]\n for id, is_boss in fightids:\n for ident, s in songtable.items():\n if s.id == id:\n if is_boss:\n changeto = bossprog[bossids.index(id)]\n else:\n changeto = battleprog[battleids.index(id)]\n s.changeto = changeto\n used_songs.append(usage_id(changeto))\n\n return (battleids, bossids)\n \n def check_ids_fit():\n n_by_isets = (isetlocs[1] - isetlocs[0] + 1) // 0x20\n n_by_sptrs = (songptraddrs[1] - songptraddrs[0] + 1) // 3\n if len(songtable) > n_by_isets or len(songtable) > n_by_sptrs:\n return False\n return True\n \n def process_mml(id, mml, name):\n def ruin_increment(m):\n val = int(m.group(1))\n if val in [3, 4, 5, 6, 11, 12, 13, 14]:\n val += 2\n elif val in [7, 8, 15, 16]: \n val -= 4\n return \"{{{}}}\".format(val)\n return m.group(0)\n \n sfx = \"\"\n if id == 0x29:\n sfx = \"sfx_zozo.mmlappend\"\n elif id == 0x4F:\n sfx = \"sfx_wor.mmlappend\"\n try:\n mml = re.sub(\"\\{[^}]*?([0-9]+)[^}]*?\\}\", ruin_increment, mml)\n except ValueError:\n print(\"WARNING: failed to add wind sounds ({})\".format(name))\n elif id == 0x20:\n sfx = \"sfx_train.mmlappend\"\n mml = re.sub(\"\\{[^}]*?([0-9]+)[^}]*?\\}\", \"$888\\g<1>\", mml)\n for i in range(1,9):\n if \"$888{}\".format(i) not in mml:\n mml = mml + \"\\n$888{} r;\".format(i)\n if sfx:\n try:\n with open(os.path.join(MUSIC_PATH, sfx), 'r') as f:\n mml += f.read()\n except IOError:\n print(\"couldn't open {}\".format(sfx))\n \n return mml_to_akao(mml, name, True if id in [0x29, 0x4F] else False)\n \n def process_tierboss(opts, used_songs=[]):\n opts = [o.strip() for o in opts.split(',')]\n opts = [o for o in opts if usage_id(o) not in used_songs]\n attempts = 0\n fallback = False\n while True:\n attempts += 1\n if attempts >= 1000:\n print(\"warning: check your tierboss config in songs.txt\")\n fallback = True\n attempts = 0\n retry = False\n tiernames = rng.sample(opts, 3)\n tierfiles = []\n for n in tiernames:\n try:\n with open(os.path.join(MUSIC_PATH, n + '_dm.mml'), 'r') as f:\n tierfiles.append(f.read())\n except IOError:\n print(\"couldn't open {}\".format(n + '_dm.mml'))\n retry = True\n if retry: continue\n \n mml = re.sub('[~!]', '', tierfiles[0])\n mml = re.sub('[?_]', '?', mml)\n mml = re.sub('j([0-9]+),([0-9]+)', 'j\\g<1>,555\\g<2>', mml)\n mml = re.sub('([;:\\$])([0-9]+)(?![,0-9])', '\\g<1>555\\g<2>', mml)\n mml = re.sub('([;:])555444([0-9])', '\\g<1>222\\g<2>', mml)\n mml = re.sub('#VARIANT', '#', mml, flags=re.IGNORECASE)\n mml = re.sub('{.*?}', '', mml)\n mml = re.sub('\\$555444([0-9])', '{\\g<1>}', mml)\n mml = re.sub('#def\\s+(\\S+)\\s*=', '#def 555\\g<1>=', mml, flags=re.IGNORECASE)\n mml = re.sub(\"'(.*)'\", \"'555\\g<1>'\", mml)\n tierfiles[0] = mml\n \n mml = re.sub('[?!]', '', tierfiles[1])\n mml = re.sub('[~_]', '?', mml)\n mml = re.sub('j([0-9]+),([0-9]+)', 'j\\g<1>,666\\g<2>', mml)\n mml = re.sub('([;:\\$])([0-9]+)(?![,0-9])', '\\g<1>666\\g<2>', mml)\n mml = re.sub('([;:])666444([0-9])', '\\g<1>333\\g<2>', mml)\n mml = re.sub('\\$666444([0-9])', '$222\\g<1>', mml)\n mml = re.sub('#VARIANT', '#', mml, flags=re.IGNORECASE)\n mml = re.sub('{.*?}', '', mml)\n mml = re.sub('#def\\s+(\\S+)\\s*=', '#def 666\\g<1>=', mml, flags=re.IGNORECASE)\n mml = re.sub(\"'(.*)'\", \"'666\\g<1>'\", mml)\n mml = re.sub('\"', ')', mml)\n tierfiles[1] = mml\n \n mml = re.sub('[?_]', '', tierfiles[2])\n mml = re.sub('[~!]', '?', mml)\n mml = re.sub('j([0-9]+),([0-9]+)', 'j\\g<1>,777\\g<2>', mml)\n mml = re.sub('([;:\\$])([0-9]+)(?![,0-9])', '\\g<1>777\\g<2>', mml)\n mml = re.sub('\\$777444([0-9])', '$333\\g<1>', mml)\n mml = re.sub('#VARIANT', '#', mml, flags=re.IGNORECASE)\n mml = re.sub('{.*?}', '', mml)\n mml = re.sub('#def\\s+(\\S+)\\s*=', '#def 777\\g<1>=', mml, flags=re.IGNORECASE)\n mml = re.sub(\"'(.*)'\", \"'777\\g<1>'\", mml)\n mml = re.sub('\"', '(', mml)\n tierfiles[2] = mml\n \n mml = \"#VARIANT / \\n#VARIANT ? ignore \\n\" + tierfiles[0] + tierfiles[1] + tierfiles[2]\n ## uncomment to debug tierboss MML\n #with open(\"lbdebug.mml\", \"w\") as f:\n # f.write(mml)\n \n akao = mml_to_akao(mml, str(tiernames), variant='_default_')\n inst = bytes(akao['_default_'][1], encoding='latin-1')\n akao = bytes(akao['_default_'][0], encoding='latin-1')\n if len(akao) > 0x1002:\n continue\n break\n for n in tiernames: used_songs.append(usage_id(n))\n return (akao, inst)\n \n # choose replacement songs\n used_songs_backup = used_songs\n songtable_backup = songtable\n songs_to_change_backup = songs_to_change\n keeptrying = True\n attempts = 0\n songlocations = {} #debug\n while keeptrying and attempts <= 1000:\n attempts += 1\n keeptrying = False\n data = data_in\n freespace = freespacebackup\n used_songs = copy(used_songs_backup)\n songtable = copy(songtable_backup)\n songs_to_change = copy(songs_to_change_backup)\n set_by_battleprog = []\n if f_battleprog:\n battleprog = process_battleprog()\n set_by_battleprog = battleprog[0] + battleprog[1]\n songs_to_change = [s for s in songs_to_change if s[1].id not in set_by_battleprog]\n f_moveinst = False if check_ids_fit() or f_preserve else True\n rng.shuffle(songs_to_change)\n for ident, s in songs_to_change:\n if ident in tierboss:\n songtable[ident].changeto = '!!tierboss'\n else:\n choices = [c for c in songtable[ident].choices if usage_id(c) not in used_songs]\n if not choices: choices.append(native_prefix + ident)\n newsong = rng.choice(choices)\n if (usage_id(newsong) in used_songs) and (not f_repeat):\n keeptrying = True\n break\n else:\n if not f_repeat: used_songs.append(usage_id(newsong))\n songtable[ident].changeto = newsong if f_randomize else native_prefix + ident\n \n if keeptrying:\n dprint(\"failed music generation during song selection\")\n continue\n \n #get data now, so we can keeptrying if there's not enough space\n for ident, s in songtable.items():\n if s.changeto == '!!tierboss':\n s.data, s.inst = process_tierboss(tierboss[ident], used_songs=used_songs)\n s.is_pointer = False\n # case: get song from MML\n elif isfile(os.path.join(MUSIC_PATH, s.changeto + \".mml\")) or isfile(os.path.join(MUSIC_PATH, usage_id(s.changeto) + \".mml\")):\n mml, variant = \"\", \"\"\n akao = {}\n try:\n with open(os.path.join(MUSIC_PATH, usage_id(s.changeto)) + \".mml\", 'r') as mmlf:\n mml = mmlf.read()\n except IOError:\n pass\n if mml:\n akao = process_mml(s.id, mml, usage_id(s.changeto) + \".mml\")\n if s.changeto.count(\"_\") >= 2:\n variant = s.changeto[len(usage_id(s.changeto)):]\n if variant[0] == \"_\" and len(variant) > 1: variant = variant[1:]\n if variant not in akao:\n variant = \"\"\n try:\n with open(os.path.join(MUSIC_PATH, s.changeto) + \".mml\", 'r') as mmlf:\n mml = mmlf.read()\n except IOError:\n mml = \"\"\n if mml:\n akao = process_mml(s.id, mml, s.changeto + \".mml\")\n else:\n akao = {}\n if not akao:\n print(\"couldn't find valid mml for {}\".format(s.changeto))\n keeptrying = True\n break\n if variant and variant in akao:\n s.data = bytes(akao[variant][0], encoding='latin-1')\n s.inst = bytes(akao[variant][1], encoding='latin-1')\n else:\n s.data = bytes(akao['_default_'][0], encoding='latin-1')\n s.inst = bytes(akao['_default_'][1], encoding='latin-1')\n s.is_pointer = False\n if max(list(s.inst)) > instcount:\n if 'nopatch' in akao:\n s.inst = bytes(akao['nopatch'][1], encoding='latin-1')\n s.data = bytes(akao['nopatch'][0], encoding='latin-1')\n elif 'nat' in akao:\n s.inst = bytes(akao['nat'][1], encoding='latin-1')\n s.data = bytes(akao['nat'][0], encoding='latin-1')\n else:\n print(\"WARNING: instrument out of range in {}\".format(s.changeto + \".mml\"))\n # case: get song from source ROM\n elif not isfile(os.path.join(MUSIC_PATH, s.changeto + \"_data.bin\")):\n target = s.changeto[len(native_prefix):]\n if (s.changeto[:len(native_prefix)] == native_prefix and\n target in songtable):\n sid = songtable[target].id\n loc = songptrs[sid]\n assert loc >= min([l[0] for l in songdatalocs])\n if f_preserve:\n s.is_pointer = True\n s.data = bytes([loc])\n else:\n s.is_pointer = False\n slen = bytes_to_int(data[loc:loc+2]) + 2\n s.data = data[loc:loc+slen]\n loc = isetlocs[0] + sid * isetsize\n assert loc + isetsize <= isetlocs[1] + 1\n s.inst = data[loc:loc+isetsize]\n else:\n print(\"target song {} not found for id {} {}\".format(s.changeto, s.id, ident))\n keeptrying = True\n break\n else:\n s.is_pointer = False\n # check instrument validity\n try:\n fi = open(os.path.join(MUSIC_PATH, s.changeto + \"_inst.bin\"), \"rb\")\n s.inst = fi.read()\n fi.close()\n except IOError:\n print(\"couldn't open {}_inst.bin\".format(s.changeto))\n keeptrying = True\n break\n if max(list(map(ord, s.inst))) > instcount:\n # case: get nopatch version\n try:\n fi = open(os.path.join(MUSIC_PATH, s.changeto + \"_inst_nopatch.bin\"), \"rb\")\n s.inst = fi.read()\n fi.close()\n except IOError:\n dprint(\"translating inst file for id{} {}\".format(s.id, s.changeto))\n dprint(\"translation is NYI\")\n try:\n fi = open(os.path.join(MUSIC_PATH, s.changeto + \"_data_nopatch.bin\"), \"rb\")\n s.data = fi.read()\n fi.close()\n except IOError:\n try:\n fi = open(os.path.join(MUSIC_PATH, s.changeto + \"_data.bin\"), \"rb\")\n s.data = fi.read()\n fi.close()\n except IOError:\n print(\"couldn't open {}_data.bin\".format(s.changeto))\n keeptrying = True\n break\n else:\n # case: get standard version\n try:\n fi = open(os.path.join(MUSIC_PATH, s.changeto + \"_data.bin\"), \"rb\")\n s.data = fi.read()\n fi.close()\n except IOError:\n print(\"couldn't open {}_data.bin\".format(s.changeto))\n keeptrying = True\n break\n \n if len(s.data) > 0x1002 and \"ending\" not in ident:\n print(\"WARNING: song data too large for {} (as {}), sfx glitches may occur\".format(s.changeto, ident))\n \n if keeptrying:\n dprint(\"failed music generation during data read\")\n continue\n \n # try to fit it all in!\n if f_preserve:\n freelocs = []\n for b, e in songdatalocs:\n i = b\n lastchar = b''\n streak = 0\n while i <= e:\n curchar = data[i]\n if curchar == lastchar:\n streak += 1\n else:\n if streak >= 64:\n freelocs.append((i-(streak+1), i-1))\n streak = 0\n lastchar = curchar\n i += 1\n if streak >= 64: freelocs.append((i-streak, i))\n songdatalocs = freelocs\n else:\n free_space(songdatalocs[0][0], songdatalocs[0][1])\n if f_moveinst:\n instsize = (len(songtable)+1) * 0x20\n for i, l in enumerate(songdatalocs):\n if l[1] - l[0] > instsize:\n new_instloc = (songdatalocs[i][0], songdatalocs[i][0] + instsize - 1)\n songdatalocs[i] = (songdatalocs[i][0] + instsize, songdatalocs[i][1])\n break\n for i, l in enumerate(songdatalocs):\n if l[0] > l[1]: del songdatalocs[i]\n space = [e - b for b, e in songdatalocs]\n songdata = b\"\" * len(space)\n songinst = data[isetlocs[0]:isetlocs[1]+1] \n if f_moveinst: free_space(isetlocs[0], isetlocs[1])\n claim_space(songptraddrs[0], songptraddrs[0] + 3*(len(songtable)+1))\n for ident, s in songtable.items():\n if not s.is_pointer:\n try:\n data, start, end = put_somewhere(data, s.data, \" (song) [{:02x}] {}\".format(s.id, s.changeto), True)\n except AssertionError:\n data = data_in\n continue\n songinst = byte_insert(songinst, s.id * isetsize, s.inst, isetsize)\n songptrdata = int_insert(songptrdata, s.id * 3, start + HIROM, 3)\n songlocations[s.id] = start\n else:\n songptrdata = int_insert(songptrdata, s.id * 3, s.data, 3)\n songlocations[s.id] = s.data - HIROM\n \n if attempts >= 1000:\n print(\"failed to produce valid music set\")\n print(\" try increasing available space or adjusting song insert list\")\n print(\" to use less space\")\n print()\n return data_in\n \n # build battle music related tables\n if f_battleprog:\n translator = {}\n battletable = [s.strip() for s in CONFIG.get('Music', 'battle_music_lookup').split(',')]\n if len(battletable) != 8: battletable = to_default('battle_music_lookup')\n pausetable = [s.strip() for s in CONFIG.get('Music', 'pause_current_song').split(',')]\n pausetableloc = int([s.strip() for s in CONFIG.get('MusicPtr', 'pausesongs').split(',')][0], 16)\n battlesongsloc = int([s.strip() for s in CONFIG.get('MusicPtr', 'battlesongs').split(',')][0], 16)\n \n for i, s in enumerate(battleprog[0]):\n translator['battle' + str(i + 1)] = s\n for i, s in enumerate(battleprog[1]):\n translator['boss' + str(i + 1)] = s\n \n def translatetbl(table):\n for i, v in enumerate(table):\n if v in translator:\n table[i] = translator[v]\n else:\n table[i] = int(v, 16)\n translatetbl(battletable)\n translatetbl(pausetable)\n \n battletable = bytes(battletable)\n pausetable = bytes(pausetable)\n \n \n # write to rom \n if f_battleprog:\n data = byte_insert(data, pausetableloc, pausetable, 5)\n data = byte_insert(data, battlesongsloc, battletable, 8)\n data = int_insert(data, songcountloc, len(songtable)+1, 1)\n if not f_moveinst: songptrdata = songptrdata[:songptraddrs[1] + 1]\n data = byte_insert(data, songptraddrs[0], songptrdata)\n if f_moveinst:\n data, s, e = put_somewhere(data, songinst, \"INSTRUMENT TABLES FOR SONGS\")\n instlocptr = int(CONFIG.get('MusicPtr', 'instrumentpointer'), 16)\n data = int_insert(data, instlocptr, s + HIROM, 3)\n else:\n data = byte_insert(data, isetlocs[0], songinst, end=isetlocs[1])\n\n # make spoiler\n changed_songs = {}\n for ident, s in songtable.items():\n if s.changeto != native_prefix + ident:\n changed_songs[s.id] = (ident, s.changeto)\n spoiltext = []\n for id, s in sorted(changed_songs.items()):\n spoiltext.append(hex(id)[2:] + \" : \" + s[0] + \" \")\n arrowpos = max(list(map(len, spoiltext)))\n for i, (id, s) in enumerate(sorted(changed_songs.items())):\n while len(spoiltext[i]) < arrowpos:\n spoiltext[i] += \" \"\n spoiltext[i] += \"-> {}\".format(s[1])\n for t in spoiltext: spoil(t)\n \n if DEBUG:\n fullsonglist = {}\n for ident, s in songtable.items():\n fullsonglist[s.id] = (ident, s.changeto, songlocations[s.id])\n despoil(\"song data locations\")\n for id, (ident, newsong, loc) in fullsonglist.items():\n despoil(\"{} ({}) -----> {} at {}\".format(hex(id), ident, newsong, hex(loc)))\n return data\n\n### end functions shared with nascentorder\n\ndef process_formation_music_by_table(data, form_music_overrides={}):\n \n o_forms = 0xF6200\n o_formaux = 0xF5900\n o_monsters = 0xF0000\n o_epacks = 0xF5000\n \n with open(os.path.join(\"tables\",\"formationmusic.txt\"), \"r\") as f:\n tbl = f.readlines()\n \n table = []\n for line in tbl:\n line = [s.strip() for s in line.split()]\n if len(line) == 2: line.append(None)\n if len(line) == 3: table.append(line)\n \n event_formations = set()\n for i in range(0,256):\n loc = o_epacks + i*4\n event_formations.add(bytes_to_int(data[loc:loc+2]))\n event_formations.add(bytes_to_int(data[loc+2:loc+4]))\n \n for line in table:\n #table format: [formation id] [music bitfield] [force music on/off]\n #value of 'c' forces music on if:\n # unrunnable enemy in formation\n # hard to run enemy in formation\n # \"attack first\" enemy in formation\n # formation is present in packs > 255 (event battles)\n try:\n fid = int(line[0])\n except ValueError:\n continue\n \n # account for random music settings in other parts of the randomizer\n # ancient cave bosses can be set to 5, 2, or 4\n # superbosses (formations_hidden) can be set to anything 1-5\n # I don't recommend using random tierboss in this way; it should only be used on the tierboss itself. So we need to adjust these settings\n # 1 (boss) remains 1\n # 2 (superboss) changes to 6 (battle4)\n # 3 (savethem) changes to 5 (battle3)\n # 4 (returners) changes to 7 (event)\n # 5 (dmad1) changes to 2 (superboss)\n force_music = False\n if fid in form_music_overrides:\n mutation_table = [0, 1, 6, 5, 7, 2, 0, 0]\n line[1] = mutation_table[form_music_overrides[fid]]\n force_music = True\n \n try:\n mbf = int(line[1]) << 3\n except ValueError:\n mbf = 0\n pos = o_formaux + fid*4\n dat = bytearray(data[pos:pos+4])\n \n dat[3] = (dat[3] & 0b11000111) | mbf\n if line[2] == \"0\":\n dat[1] = dat[1] | 0b00000010\n dat[3] = dat[3] | 0b10000000\n elif line[2] == \"c\":\n if fid in event_formations:\n force_music = True\n else:\n for m in range(0,6):\n fpos = o_forms + fid*15\n if (data[fpos+1] >> m) & 1:\n mid = data[fpos+2+m] + (((data[fpos+14] >> m) & 1) << 8)\n mb = data[o_monsters+mid*32+19]\n if mb & 0b00001011:\n force_music = True\n break\n if line[2] == \"1\" or force_music:\n dat[1] = dat[1] & 0b11111101\n dat[3] = dat[3] & 0b01111111\n data = byte_insert(data, pos, dat)\n \n return data\n \ndef randomize_music(fout, f_mchaos=False, codes=[], form_music_overrides={}):\n events = \"\"\n if 'christmas' in codes:\n events += \"W\"\n if 'halloween' in codes:\n events += \"H\"\n fout.seek(0)\n data = fout.read()\n data = insert_instruments(data, INST_METADATA_OFFSET)\n data = process_custom_music(data, f_mchaos=f_mchaos, eventmodes=events)\n data = process_formation_music_by_table(data, form_music_overrides=form_music_overrides)\n \n fout.seek(0)\n fout.write(data)\n return \"\\n\".join(spoiler['Music'])\n ","sub_path":"musicrandomizer.py","file_name":"musicrandomizer.py","file_ext":"py","file_size_in_byte":44946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"133952145","text":"'''\r\n * -----------------------------------------------\r\n * \tClass for Linked List algorithm\r\n * -----------------------------------------------\r\n * \tThis class working for Linked list algorithm \r\n * \twith python programming laguage. Its working \r\n * \tfor lists and recursion method. \r\n'''\r\n\r\n\r\n\r\n\r\n# declaring a class name node\r\nclass nodeClass(object):\r\n\r\n\t# call a constructor of for this class that will \r\n\t# instentiate during calling the class. \r\n\t# The constructor has 2 parameters where both of \r\n\t# the parameters take none value by default. \r\n\r\n\tdef __init__(self, cargo=None, next=None):\r\n\t self.cargo = cargo\r\n\t self.next = next\r\n\r\n\tdef __str__(self):\r\n\t\treturn str(self.cargo)\r\n\r\n\r\n\r\n\r\n\r\n# instentiate or creating object for the class\r\n# due to OOP you are able to create different \r\n# objects as much as you want \r\n\r\nnode1 = nodeClass(\"IIUM # 1\")\r\nnode2 = nodeClass(\"IIUM # 2\")\r\nnode3 = nodeClass(\"IIUM # 3\")\r\nnode4 = nodeClass(\"IIUM # 4\")\r\nnode5 = nodeClass(\"IIUM # 5\")\r\nnode6 = nodeClass(\"IIUM # 6\")\r\nnode7 = nodeClass(\"IIUM # 7\")\r\n\r\n\r\n\r\n# linking one object with next object by assing \r\n# whole class in the next property in the class\r\nnode1.next = node2\r\nnode2.next = node3\r\nnode3.next = node4\r\nnode4.next = node5\r\nnode5.next = node6\r\nnode6.next = node7\r\n\r\n\r\n\r\n# defining a fucntion for prining value from last value\r\ndef print_backward(list):\r\n\t\r\n\t# if list is empty then represent by Non that is an empty list\r\n\tif list == None: return\r\n\r\n\t# putting the element in list array as head\r\n\thead = list\r\n\r\n\t# whatever is in head, add next element of head as tail\r\n\ttail = list.next\r\n\r\n\t# now print this function here with tail variable as a parameter that return the last value\r\n\tprint_backward(tail)\r\n\tprint(head)\r\n\r\n\r\n\r\n\r\n# Calling the function to print everything\r\nprint_backward(node1)","sub_path":"linkedlist__lists_and_recursion.py","file_name":"linkedlist__lists_and_recursion.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"403677647","text":"import time\nimport pandas as pd\nimport numpy as np\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\n\ndef get_filters():\n \"\"\"\n Asks user to specify a city, month, and day to analyze.\n\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('Hello! Let\\'s explore some US bikeshare data!')\n # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n city = input('Which city would you like the data to show: Chicago , Newyork or Washington:') \n print (city)\n while (city != 'Chicago' and city != 'Newyork' and city != 'Washington'):\n city = input(\"Please make a valid selection : Chicago , Newyork , Washington : \")\n \n print (city) \n #print (\"After while loop\")\n \n \n \n # TO DO: get user input for month (all, january, february, ... , june)\n month = input('Which month would you like the data for : January , February, March, April, May, June or All: ')\n print (month)\n while (month != 'January' and month != 'February' and month != 'March' and month != 'April' and month != 'May' and month != 'June' and month != 'All'):\n month = input(\"Please make a valid month selection : January , February , March , April , May , June or All : \")\n print (month)\n \n\n\n # TO DO: get user input for day of week (all, monday, tuesday, ... sunday)\n day = input('which day would you like : Monday, Tuesday , Wednesday, Thursday , Friday , Saturday , Sunday or All : ')\n print (day)\n while (day != 'Monday' and day != 'Tuesday' and day != 'Wednesday' and day != 'Thursday' and day != 'Friday' and day != 'Saturday' and day != 'Sunday' and day != 'All'):\n day = input (\" Please make a valid selection for day : Monday , Tuesday , Wednesday , Thursday , Friday , Saturday , Sunday or All : \")\n print (day)\n\n print('-'*40)\n return city, month, day\n\ndef load_data(city, month, day):\n if city == \"Chicago\":\n df = pd.read_csv(\"chicago.csv\")\n elif city == \"Washington\": \n df = pd.read_csv(\"washington.csv\")\n else:\n df = pd.read_csv(\"new_york_city.csv\")\n #print (df.head())\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n df['End Time'] = pd.to_datetime(df['End Time'])\n df['Hour']=df['Start Time'].dt.hour\n df['Month']=df['Start Time'].dt.month\n dayOfWeek={0:'Monday', 1:'Tuesday', 2:'Wednesday', 3:'Thursday', 4:'Friday', 5:'Saturday', 6:'Sunday'}\n df['Day']=df['Start Time'].dt.dayofweek.map(dayOfWeek)\n if month != 'All':\n # use the index of the months list to get the corresponding int\n months = ['January', 'February', 'March', 'April', 'May', 'June']\n month = months.index(month) + 1\n # filter by month to create the new dataframe\n df = df[df['Month'] == month]\n # filter by day of week if applicable\n if day != 'All':\n # filter by day of week to create the new dataframe\n df = df[df['Day'] == day.title()]\n\n\n return df\ndef main():\n while True:\n city, month, day = get_filters()\n print (city, month, day)\n #city = 'Chicago'\n #month = 'January'\n #day = 'Sunday'\n # question = input (\"Do you want to continue\")\n df = load_data(city, month, day)\n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n\n #time_stats(df)\n #station_stats(df)\n #trip_duration_stats(df)\n #user_stats(df)\n\n #restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n #if restart.lower() != 'yes':\n #break\ndef time_stats(df):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n start_time = time.time()\n\n # TO DO: display the most common month\n\n\n #df = pd.read_csv('chicago.csv')\n\n # TO DO: display the most common day of week\n\n\n # TO DO: display the most common start hour\n \n Popular_month = df['Month'].mode() [0]\n Popular_hour = df['Hour'].mode() [0]\n Popular_day = df['Day'].mode() [0]\n print (\"Most popular hour with the specific selection : \", Popular_hour)\n print (\"Most common Month with the specific selection: \", Popular_month)\n print (\"Most common Day: \", Popular_day)\n \ndef station_stats(df):\n \n \n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n\n # TO DO: display most commonly used start station\n Popular_Start_station = df['Start Station'].mode() [0]\n print (\"Most Popular Start Station for the user selection: \", Popular_Start_station)\n\n\n # TO DO: display most commonly used end station\n Popular_End_station = df['End Station'].mode() [0]\n print (\"Most Popular End station for the user selection : \", Popular_End_station)\n \n \n\n\n # TO DO: display most frequent combination of start station and end station trip\n df['Concatenate']= df['Start Station']+ df['End Station']\n Popularcombination= df['Concatenate'].mode() [0]\n #print(df.groupby(['Start Station', 'End Station']).agg('max'))\n print (\"Most Popular combination for the selection: \", Popularcombination)\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n print('\\nCalculating Trip Duration...\\n')\n start_time = time.time()\n\n # TO DO: display total travel time\n df['Diff']= df['End Time']-df['Start Time']\n Total_travel_time = df['Diff'].sum()\n print (\" Total Travel time for the selection : \", Total_travel_time)\n\n\n # TO DO: display mean travel time\n Mean_travel_time = df['Diff'].mean()\n print (\" Mean Travel Time : \", Mean_travel_time)\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n \ndef user_stats(df):\n \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n\n # TO DO: Display counts of user types\n #df['User Types'] = pd.read_csv(filename)\n #print df\n #df['user_types'] = df['User Type'].value_counts()\n print(df['User Type'].value_counts())\n\n\n # TO DO: Display counts of gender\n if 'Gender' in df.columns:\n print(df['Gender'].value_counts())\n\n\n # TO DO: Display earliest, most recent, and most common year of birth\n if 'Birth Year' in df.columns:\n print(\"Earliest Birth year :\",df['Birth Year'].min())\n print(\"Most recent year :\",df['Birth Year'].max())\n print(\"Most common year of birth :\",df['Birth Year'].mode())\n \n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":7158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"249307695","text":"import random\nimport csv\nimport string\n\n\ndef make_email():\n letters = string.ascii_lowercase\n endings = [\"hu\", \"com\", \"pl\", \"es\"]\n email = []\n for i in range(0, 10):\n email.append(letters[random.randint(0, len(letters)-1)])\n email = \"\".join(email)\n at = []\n for i in range(0, 6):\n at.append(letters[random.randint(0, len(letters)-1)])\n at = \"\".join(at)\n email = '{}@{}.{}'.format(email, at, endings[random.randint(0, len(endings)-1)])\n return email\n\n\ndef make_phone():\n numbers = string.digits\n phone = []\n for i in range(0, 11):\n phone.append(numbers[random.randint(0, len(numbers)-1)])\n phone = '+{}'.format(''.join(phone))\n return phone\n\n\ndef gen_fake():\n first_names = [\"Miklós\", \"Tamás\", \"Dániel\", \"Mateusz\", \"Attila\", \"Pál\",\n \"Sándor\", \"Prezmek\", \"John\", \"Tim\", \"Matthew\", \"Andy\", \"Giancarlo\"]\n last_names = [\"Beöthy\", \"Tompa\", \"Salamon\", \"Ostafil\", \"Molnár\", \"Monoczki\",\n \"Szodoray\", \"Ciacka\", \"Carrey\", \"Obama\", \"Lebron\", \"Hamilton\", \"Fisichella\"]\n cities = [\"Budapest\", \"Miskolc\", \"Krakow\", \"Barcelona\", \"New York\"]\n\n new_fake_mentor = (first_names[random.randint(0, len(first_names)-1)],\n last_names[random.randint(0, len(last_names)-1)],\n random.randint(1960, 1995),\n make_email(), cities[random.randint(0, len(cities)-1)],\n make_phone(), random.randint(1, 10))\n return new_fake_mentor\n\n\ndef write_to_csv(filename, amount):\n with open(filename, \"w\", newline='') as csvfile:\n writer = csv.writer(csvfile, delimiter=',')\n for i in range(0, amount):\n writer.writerow(gen_fake())\n\nwrite_to_csv(\"fake_mentors.csv\", 10000)\n","sub_path":"gen_fake.py","file_name":"gen_fake.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"625948546","text":"\"\"\"\r\nName : Tanzimul Islam\r\nRoll : 180636\r\nSession : 2017-18\r\nE-mail : tanzimulislam799@gmail.com\r\nBlog : https://tanzim36.blogspot.com/\r\nDept.of ICE, Pabna University of Science and Technology\r\n\"\"\"\r\n#Problem-12: Write a program to solve the Tower of Hanoi problem for the 𝑁 disk.\r\ndef towerHanoi(n, A, B, C):\r\n if n==1:\r\n print(\"Move disc \",n,\" from \",A,\" to \",B)\r\n print(A, B, C)\r\n else:\r\n towerHanoi(n-1, A, C, B)\r\n print(\"Move disc \",n,\" from \",B,\" to \",A)\r\n print(A, B, C)\r\n towerHanoi(n-1, C, B, A)\r\n\r\nwhile True:\r\n print(\"Press 1 then go to work.\")\r\n print(\"Press 0 them exit.\")\r\n n = int(input())\r\n if n==0:\r\n print(\"Exit.\")\r\n break\r\n else:\r\n number = int(input(\"How many discs : \"))\r\n a = 'A'\r\n b = 'B'\r\n c = 'C'\r\n print(a, b, c)\r\n towerHanoi(number, a, b, c)\r\n","sub_path":"12-Tower of hanoi.py","file_name":"12-Tower of hanoi.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"336466649","text":"import time\n#from pygame import mixer # Load the required library\nimport pygame\nimport os\nimport RPi.GPIO as GPIO\n\n# https://sourceforge.net/p/raspberry-gpio-python/wiki/BasicUsage/\n# https://raspi.tv/2014/rpi-gpio-update-and-detecting-both-rising-and-falling-edges\nGPIO.setmode(GPIO.BOARD)\ngpio_list = [7,11,13,15,29,31,33,37] # Pins to poll https://pinout.xyz/pinout/pin11_gpio17\nGPIO.setup(gpio_list, GPIO.IN, pull_up_down=GPIO.PUD_UP) # https://sourceforge.net/p/raspberry-gpio-python/wiki/Inputs/\n\ndir_path = os.path.dirname(os.path.realpath(__file__)) #https://stackoverflow.com/questions/5137497/find-current-directory-and-files-directory\n\npygame.init()\npygame.mixer.init()\n\ndef getPath(pin):\n pin = str(pin) # https://www.crybit.com/convert-integer-string-python/\n\n# Check for the right extension, mp3 first https://stackoverflow.com/questions/33400682/check-if-a-directory-contains-a-file-with-a-given-extension\n\n pinMP3 = pin + \".mp3\";\n pinWAV = pin + \".wav\";\n\n # One of many options: https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-file-exists\n if os.path.exists(pinMP3):\n print (\"pinMP3 is here!\")\n pin += '.mp3'\n elif os.path.exists(pinWAV):\n print (\"WAV is here!\")\n pin += '.wav'\n else:\n print (\"MP3 or WAV is missing!\")\n return\n\n# Play the sound\n playSound(pin)\n\ndef playSound(path):\n pygame.mixer.music.stop()\n pygame.mixer.music.load(path)\n print(path)\n pygame.mixer.music.play()\n\ntry:\n# https://sourceforge.net/p/raspberry-gpio-python/wiki/Inputs/\n for pin in gpio_list:\n GPIO.add_event_detect(pin, GPIO.FALLING, callback=getPath, bouncetime=400) # add rising edge detection on a channel\n\n while 1:\n time.sleep(10)\n\nexcept KeyboardInterrupt:\n GPIO.cleanup() # clean up GPIO on CTRL+C exit\nGPIO.cleanup() # clean up GPIO on normal exit\n","sub_path":"soundbox.py","file_name":"soundbox.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"516935949","text":"import io\r\nimport tempfile\r\nimport os\r\nfrom app.lib.modules.office import office2hashcat\r\nfrom contextlib import redirect_stdout\r\nfrom werkzeug.utils import secure_filename\r\n\r\n\r\nclass ModuleOfficeManager:\r\n def extract(self, file):\r\n filename = secure_filename(file.filename)\r\n\r\n temp_dir = tempfile.TemporaryDirectory()\r\n save_as = os.path.join(temp_dir.name, filename)\r\n file.save(save_as)\r\n\r\n output = self.__run_office2hashcat(save_as)\r\n\r\n temp_dir.cleanup()\r\n\r\n return output\r\n\r\n def __run_office2hashcat(self, file):\r\n # Because this script was taken as-is and is meant to be ran via CLI we use the io module to capture its output.\r\n f = io.StringIO()\r\n with redirect_stdout(f):\r\n try:\r\n office2hashcat.process_file(file)\r\n except:\r\n # Uh oh\r\n pass\r\n\r\n output = f.getvalue()\r\n return output\r\n","sub_path":"app/lib/modules/office/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"157572649","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Oct 18 20:42:05 2021\r\n\r\nAssignment 1 for BE002\r\n\r\n@author: LilyChang\r\n\"\"\"\r\n\r\nimport cv2\r\nimport numpy as np\r\n\r\n\r\n#%%\r\nimg=cv2.imread(\"input_pic.png\")\r\n# Too big, resize it\r\nheight,width=img.shape[:2]\r\nimg=cv2.resize(img,np.uint((width/3,height/3)),interpolation=cv2.INTER_CUBIC)\r\n\r\n# Draw 3*3 rectangles, with thickness=3, size 50*50,\r\nrec_sz=50\r\nthickness=3\r\ncolor=[0,255,0]\r\npos_range=np.arange(0,3*rec_sz,rec_sz)\r\nfor x1 in pos_range:\r\n for y1 in pos_range:\r\n leftUp=[x1,y1]\r\n rightDown=[x1+rec_sz,y1+rec_sz]\r\n cv2.rectangle(img,leftUp,rightDown,color=color,thickness=thickness)\r\n\r\ncv2.imwrite('result.png',img)\r\n\r\ncv2.imshow(\"Bear\",img)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n","sub_path":"cll/hw1/hw1.py","file_name":"hw1.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"577932488","text":"from copy import copy\nfrom typing import List\n\n\ndef bucket(nums: List[int]) -> List[int]:\n # 以下实现只适用于0~99范围的整数\n buckets = [list() for _ in range(10)]\n for num in nums:\n _bucket = buckets[num // 10]\n _bucket.append(num)\n\n n = len(_bucket)\n for i in reversed(range(1, n)):\n if _bucket[i] < _bucket[i - 1]:\n _bucket[i], _bucket[i - 1] = _bucket[i - 1], _bucket[i]\n\n res = []\n for _bucket in buckets:\n res.extend(_bucket)\n return res\n\n\nif __name__ == '__main__':\n cases = [\n [3, 1, 4, 7, 5, 2, 6],\n [2, 1, 1, 4, 3, 6, 5]\n ]\n for case in cases:\n print(bucket(copy(case)) == sorted(case))\n","sub_path":"bucket.py","file_name":"bucket.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"629355907","text":"#!/usr/bin/env python3\n\nfrom CR_library import *\n\nLA = LiftingArm();\nC = Clutch();\nD = Drive();\n\n#D.drive_until_found()\nLA.bring_down()\nC.close()\nD.drive_until_color()\nC.open()\nD.back()\nRoboter.powerNap()\n\n\n\n\n\n\n\n","sub_path":"ev3dev-lang-python-ev3dev-stretch/CR_push.py","file_name":"CR_push.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"551955407","text":"# -*- coding: utf-8 -*-\n\"\"\"\nchemdataextractor.config\n~~~~~~~~~~~~~~~~~~~~~~~~\n\nConfig file reader/writer.\n\n:copyright: Copyright 2016 by Matt Swain.\n:license: MIT, see LICENSE file for more details.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport os\nfrom collections import MutableMapping\n\nimport appdirs\nimport six\nfrom six.moves.configparser import SafeConfigParser, NoOptionError\n\n\nclass Config(MutableMapping):\n \"\"\"Read and write to config file.\n\n A config object is essentially a string key-value store that can be treated like a dictionary::\n\n c = Config()\n c['foo'] = 'bar'\n print c['foo']\n\n The file location may be specified::\n\n c = Config('~/matt/anotherconfig.cfg')\n c['where'] = 'in a different file'\n\n If no location is specified, the environment variable CHEMDATAEXTRACTOR_CONFIG is checked and used if available.\n Otherwise, a standard config location is used, which varies depending on the operating system. You can check the\n location using the ``path`` property. For more information see https://github.com/ActiveState/appdirs\n\n It is possible to edit the file by hand with a text editor.\n\n Warning: multiple instances of Config() pointing to the same file will not see each others' changes, and will\n overwrite the entire file when any key is changed.\n\n \"\"\"\n\n #: These values will be present in a config object unless they are explicitly defined otherwise in the config file\n default_values = {}\n\n def __init__(self, path=None):\n \"\"\"\n\n :param string path: (Optional) Path to config file location.\n \"\"\"\n self._path = path\n\n # Use CHEMDATAEXTRACTOR_CONFIG environment variable if set\n if not self._path:\n self._path = os.environ.get('CHEMDATAEXTRACTOR_CONFIG')\n # Use OS-dependent config directory given by appdirs\n if not self._path:\n self._path = os.path.join(appdirs.user_config_dir('ChemDataExtractor'), 'config.cfg')\n self._parser = SafeConfigParser()\n if os.path.isfile(self.path):\n with open(self.path) as f:\n self._parser.readfp(f)\n if not self._parser.has_section('cde'):\n self._parser.add_section('cde')\n for k, v in six.iteritems(self.default_values):\n if not self._parser.has_option('cde', k.encode('utf-8')):\n self._parser.set('cde', k.encode('utf-8'), v.encode('utf-8'))\n\n @property\n def path(self):\n \"\"\"The path to the config file.\"\"\"\n return self._path\n\n def _flush(self):\n \"\"\"Save the contents of data to the file on disk. You should not need to call this manually.\"\"\"\n d = os.path.dirname(self.path)\n if not os.path.isdir(d):\n os.makedirs(d)\n with open(self.path, 'w') as f:\n self._parser.write(f)\n\n def __contains__(self, k):\n return self._parser.has_option('cde', k.encode('utf-8'))\n\n def __getitem__(self, k):\n try:\n return self._parser.get('cde', k.encode('utf-8'))\n except NoOptionError:\n raise KeyError(k)\n\n def __setitem__(self, k, v):\n self._parser.set('cde', k.encode('utf-8'), v.encode('utf-8'))\n self._flush()\n\n def __delitem__(self, k):\n try:\n self._parser.remove_option('cde', k.encode('utf-8'))\n self._flush()\n except NoOptionError:\n raise KeyError(k)\n\n def __iter__(self):\n return (k for k, v in self._parser.items('cde'))\n\n def __len__(self):\n return len(self._parser.items('cde'))\n\n def __repr__(self):\n return '' % self.path\n\n def clear(self):\n \"\"\"Clear all values from config.\"\"\"\n self._parser.remove_section('cde')\n self._parser.add_section('cde')\n self._flush()\n\n\n#: Global config instance.\nconfig = Config()\n","sub_path":"chemdataextractor/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"309570948","text":"import mxnet as mx\nfrom mxnet.gluon import HybridBlock\n\nfrom core.utils.dataprocessing.predictFunction.decoder import Decoder\n\n'''\n Prediction 클래스를 hybridBlock 으로 만든이유?\n net + decoder + nms = complete object network로 만들어서 json, param 파일로 저장하기 위함\n -> 장점은? mxnet c++에서 inference 할 때, image(RGB) 넣으면 ids, scores, bboxes 가 바로 출력\n'''\n\n\nclass Prediction(HybridBlock):\n\n def __init__(self,\n from_sigmoid=False,\n num_classes=3,\n nms_thresh=0.5,\n nms_topk=500,\n except_class_thresh=0.05,\n multiperclass=True):\n super(Prediction, self).__init__()\n\n self._decoder = Decoder(from_sigmoid=from_sigmoid, num_classes=num_classes, thresh=except_class_thresh,\n multiperclass=multiperclass)\n self._nms_thresh = nms_thresh\n self._nms_topk = nms_topk\n\n def hybrid_forward(self, F, output1, output2, output3,\n anchor1, anchor2, anchor3,\n offset1, offset2, offset3,\n stride1, stride2, stride3):\n\n results = []\n for out, an, off, st in zip([output1, output2, output3],\n [anchor1, anchor2, anchor3],\n [offset1, offset2, offset3],\n [stride1, stride2, stride3]):\n results.append(self._decoder(out, an, off, st))\n\n results = F.concat(*results, dim=1)\n if self._nms_thresh > 0 and self._nms_thresh < 1:\n '''\n Apply non-maximum suppression to input.\n The output will be sorted in descending order according to score. \n Boxes with overlaps larger than overlap_thresh, \n smaller scores and background boxes will be removed and filled with -1, \n '''\n results = F.contrib.box_nms(\n results,\n overlap_thresh=self._nms_thresh,\n topk=self._nms_topk,\n id_index=0, score_index=1, coord_start=2,\n force_suppress=False, in_format=\"corner\", out_format=\"corner\")\n\n ids = F.slice_axis(results, axis=-1, begin=0, end=1)\n scores = F.slice_axis(results, axis=-1, begin=1, end=2)\n bboxes = F.slice_axis(results, axis=-1, begin=2, end=6)\n return ids, scores, bboxes\n\n\n# test\nif __name__ == \"__main__\":\n from core import Yolov3, YoloTrainTransform, DetectionDataset\n import os\n\n input_size = (416, 416)\n root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n transform = YoloTrainTransform(input_size[0], input_size[1], make_target=False)\n dataset = DetectionDataset(path=os.path.join(root, 'Dataset', 'train'), transform=transform)\n num_classes = dataset.num_class\n\n image, label, _, _, _ = dataset[0]\n label = mx.nd.array(label)\n\n net = Yolov3(Darknetlayer=53,\n input_size=input_size,\n anchors={\"shallow\": [(10, 13), (16, 30), (33, 23)],\n \"middle\": [(30, 61), (62, 45), (59, 119)],\n \"deep\": [(116, 90), (156, 198), (373, 326)]},\n num_classes=num_classes, # foreground만\n pretrained=False,\n pretrained_path=os.path.join(root, \"modelparam\"),\n ctx=mx.cpu())\n net.hybridize(active=True, static_alloc=True, static_shape=True)\n\n prediction = Prediction(\n from_sigmoid=False,\n num_classes=num_classes,\n nms_thresh=0.5,\n nms_topk=100,\n except_class_thresh=0.05,\n multiperclass=True)\n\n # batch 형태로 만들기\n image = image.expand_dims(axis=0)\n label = label.expand_dims(axis=0)\n gt_boxes = label[:, :, :4]\n gt_ids = label[:, :, 4:5]\n output1, output2, output3, anchor1, anchor2, anchor3, offset1, offset2, offset3, stride1, stride2, stride3 = net(\n image)\n ids, scores, bboxes = prediction(output1, output2, output3, anchor1, anchor2, anchor3, offset1, offset2, offset3,\n stride1, stride2, stride3)\n\n print(f\"nms class id shape : {ids.shape}\")\n print(f\"nms class scores shape : {scores.shape}\")\n print(f\"nms box predictions shape : {bboxes.shape}\")\n '''\n multiperclass = True 일 때,\n nms class id shape : (1, 53235, 1)\n nms class scores shape : (1, 53235, 1)\n nms box predictions shape : (1, 53235, 4)\n \n multiperclass = False 일 때,\n nms class id shape : (1, 10647, 1)\n nms class scores shape : (1, 10647, 1)\n nms box predictions shape : (1, 10647, 4)\n '''\n","sub_path":"YoloV3/core/utils/dataprocessing/prediction.py","file_name":"prediction.py","file_ext":"py","file_size_in_byte":4730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"458129170","text":"def factorial(n):\n if n == 1:\n return 1\n return n * factorial(n-1)\n\n\ndef solution(n,k):\n n_list = [i for i in range(1,n+1)]\n now_part = factorial(n)\n \n # 사전순으로 나열되므로 구간별로 특정한 패턴이 있을것임\n # k번이 나올때까지 제일 앞 숫자부터 구간으로 나누어서\n # 찾아가는 형태로만든다\n answer = []\n while n_list:\n now_part = now_part // n\n # 각 구간은 나머지가 0이 되는 부분까지이고, 0일때까지 몫이 같으므로\n # 한칸씩 밀리게된다\n q, r = divmod(k, now_part)\n # q는 현재 칼럼(구간)의 인덱스가 된다.\n if r == 0:\n q -= 1\n answer.append(n_list.pop(q))\n k, n = r, n-1\n\n \n return answer\n\n\nprint(solution(5,2))\n# print(1//5)","sub_path":"programmers/line.py","file_name":"line.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"441634212","text":"'''\nThis problem was asked by Stripe.\n\nWrite a function to flatten a nested dictionary.\nNamespace the keys with a period.\n\nFor example, given the following dictionary:\n\n{\n \"key\": 3,\n \"foo\": {\n \"a\": 5,\n \"bar\": {\n \"baz\": 8\n }\n }\n}\n\nit should become:\n\n{\n \"key\": 3,\n \"foo.a\": 5,\n \"foo.bar.baz\": 8\n}\n\nYou can assume keys do not contain dots in them, i.e. no clobbering will occur.\n'''\n\nimport collections\n\n\ndef flatten(dictionary, parent_key='', seperator='.'):\n items = []\n for key, value in dictionary.items():\n new_key = parent_key + seperator + key if parent_key else key\n if isinstance(value, collections.MutableMapping):\n items.extend(\n flatten(value, parent_key=new_key, seperator=seperator).items()\n )\n else:\n items.append((new_key, value))\n return dict(items)\n\n\nif __name__ == '__main__':\n dictionary = {\n \"key\": 3,\n \"foo\": {\n \"a\": 5,\n \"bar\": {\n \"baz\": 8\n }\n }\n }\n print(flatten(dictionary))\n","sub_path":"python/dictionary_flattener.py","file_name":"dictionary_flattener.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"588018315","text":"\"\"\"\n287. Find the Duplicate Number\n\nGiven an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.\n\nNote:\nYou must not modify the array (assume the array is read only).\nYou must use only constant, O(1) extra space.\nYour runtime complexity should be less than O(n2).\nThere is only one duplicate number in the array, but it could be repeated more than once.\n\"\"\"\n\n\"\"\"\ncycle dection O(n), start from a[n], the index needs to be decremented by one\n\"\"\"\n\nclass Solution(object):\n def findDuplicate(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n slow = nums[-1] - 1\n fast = nums[nums[-1] - 1] - 1\n while fast != slow:\n fast = nums[nums[fast] - 1] - 1\n slow = nums[slow] - 1\n slow = -1\n while fast != slow:\n fast = nums[fast] - 1\n slow = nums[slow] - 1\n return slow + 1\n\ns = Solution()\nassert (s.findDuplicate([2, 4, 1, 2, 3]) == 2)\nassert (s.findDuplicate([1, 1]) == 1)\nassert (s.findDuplicate([1, 1, 2, 3, 4]) == 1)\nassert (s.findDuplicate([4, 1, 2, 3, 4]) == 4)\n","sub_path":"python/287.py","file_name":"287.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"103582178","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n@Comment :\n@Time : 2018/8/15 15:36\n@Author : libaojie\n@File : log_tool.py\n@Software : PyCharm\n\"\"\"\nimport logging\nimport os\nimport time\n\n\nclass LogTool(object):\n __instance = None # 定义一个类属性做判断\n handler = None\n errhandler = None\n logger = None\n\n def __new__(cls):\n if cls.__instance is None:\n # 如果__instance为空证明是第一次创建实例\n # 通过父类的__new__(cls)创建实例\n cls.__instance == object.__new__(cls)\n return cls.__instance\n else:\n # 返回上一个对象的引用\n return cls.__instance\n\n @classmethod\n def init(cls, path):\n \"\"\"\n 初始化\n :param path:\n :return:\n \"\"\"\n LEVELS = {'debug': logging.DEBUG,\n 'info': logging.INFO,\n 'warning': logging.WARNING,\n 'error': logging.ERROR,\n 'critical': logging.CRITICAL, }\n\n cls.logger = logging.getLogger()\n level = 'default'\n\n log_filename = os.path.join(path, 'log.log')\n err_filename = os.path.join(path, 'error.log')\n\n cls.logger.setLevel(LEVELS.get(level, logging.NOTSET))\n cls.createFile(log_filename)\n cls.createFile(err_filename)\n\n # 注意文件内容写入时编码格式指定\n cls.handler = logging.FileHandler(log_filename, encoding='utf-8')\n cls.errhandler = logging.FileHandler(err_filename, encoding='utf-8')\n\n @classmethod\n def createFile(cls, filename):\n # filename = os.path.realpath(filename)\n if not os.path.isdir(os.path.dirname(filename)):\n os.makedirs(os.path.dirname(filename))\n\n if not os.path.isfile(filename):\n # 创建并打开一个新文件\n fd = open(filename, mode='w', encoding='utf-8')\n fd.close()\n\n # logger可以看做是一个记录日志的人,对于记录的每个日志,他需要有一套规则,比如记录的格式(formatter),\n # 等级(level)等等,这个规则就是handler。使用logger.addHandler(handler)添加多个规则,\n # 就可以让一个logger记录多个日志。\n\n @classmethod\n def setHandler(cls, level):\n if level == 'error':\n cls.logger.addHandler(cls.errhandler)\n # handler=logging.FileHandler(log_filename)\n # 把logger添加上handler\n cls.logger.addHandler(cls.handler)\n\n @classmethod\n def removerhandler(cls, level):\n if level == 'error':\n cls.logger.removeHandler(cls.errhandler)\n cls.logger.removeHandler(cls.handler)\n\n @classmethod\n def getCurrentTime(cls):\n dateformat = '%Y-%m-%d %H:%M:%S'\n return time.strftime(dateformat, time.localtime(time.time()))\n\n # 静态方法\n @staticmethod\n def print(log_message):\n print(log_message)\n LogTool.info(log_message)\n\n # 静态方法\n @staticmethod\n def debug(log_message):\n LogTool.setHandler('debug')\n LogTool.logger.debug(\"[DEBUG \" + LogTool.getCurrentTime() + \"]\" + log_message)\n LogTool.removerhandler('debug')\n\n @staticmethod\n def info(log_message):\n LogTool.setHandler('info')\n LogTool.logger.info(\"[INFO \" + LogTool.getCurrentTime() + \"]\" + log_message)\n LogTool.removerhandler('info')\n\n @staticmethod\n def warning(log_message):\n LogTool.setHandler('warning')\n LogTool.logger.warning(\"[WARNING \" + LogTool.getCurrentTime() + \"]\" + log_message)\n LogTool.removerhandler('warning')\n\n @staticmethod\n def error(log_message):\n LogTool.setHandler('error')\n _log = \"[ERROR \" + LogTool.getCurrentTime() + \"]\" + log_message\n print(_log)\n LogTool.logger.error(_log)\n LogTool.removerhandler('error')\n\n @staticmethod\n def critical(log_message):\n LogTool.setHandler('critical')\n LogTool.logger.critical(\"[CRITICAL \" + LogTool.getCurrentTime() + \"]\" + log_message)\n LogTool.removerhandler('critical')\n\n\n","sub_path":"python_template/01_package/project/app/plugins/log_tool.py","file_name":"log_tool.py","file_ext":"py","file_size_in_byte":4123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"97688135","text":"from sympy import Matrix\nimport sympy\nimport math\n\n#See: http://mathreview.uwaterloo.ca/archive/voli/1/panju.pdf\n\n#Calculates ||v||\ndef norm(vector):\n norm_sq = 0\n for j in vector:\n norm_sq += j * j\n return math.pow(norm_sq, 0.5)\n\n#Power method\ndef powermeth(A, v, iter):\n for i in range(iter):\n #create a temporary vector to hold v^(1)\n tmp = A * v\n\n #find norm\n nor = norm(tmp)\n\n #normalize v for next iteration; i.e. v/||v||\n v = tmp/nor\n #returns a tuple: v is the eigenvector, nor is the eigenvalue\n return nor\n\n#Inverse iteration method\ndef inverse_iter(A, v, iter):\n #Save time on calculation by doing the inverse first, instead of every iteration\n B = A.inv()\n for i in range(iter):\n tmp = B * v\n\n #find norm\n nor = norm(tmp)\n\n #normalize\n v = tmp/nor\n #returns the eigenvalue\n return (1/nor)\n\n#Shifted inverse iteration method\ndef inverse_iter_shift(A, v, estimate, iter):\n #since we asume the matrix to be square\n I = sympy.eye(A.shape[0])\n #Shift the matrix\n B = A - I*estimate\n #Invert first\n B = B.inv()\n for i in range(iter):\n tmp = B * v\n\n #find norm\n nor = norm(tmp)\n\n #normalize\n v = tmp/nor\n #returns the eigenvalue\n return (1/(-nor) + estimate)\n\n#Rayleigh Quotient Iteration\ndef RQI(A, v, iter):\n #Since we assume the matrix to be square\n I = sympy.eye(A.shape[0])\n for i in range(iter):\n # Find lambda_0 (denote it lam)\n lam = sympy.Transpose(v) * A * v\n lam = lam[0]\n B = A - I * lam\n #If it converges, then the matrix may not be invertible (?)\n try:\n tmp = B.inv() * v\n except:\n break\n #find norm\n nor = norm(tmp)\n\n #normalize\n v = tmp/nor\n\n return lam\n\n\nif __name__ == \"__main__\":\n print(\"Running test cases\")\n # Power methods\n # see: https://en.wikiversity.org/wiki/Numerical_Analysis/Power_iteration_examples\n A = Matrix(3, 3, [1,2,1,-4,7,1,-1,-2,-1])\n print(\"The max eigenvalue for this matrix is \" + str(max(A.eigenvals())))\n work = max(A.eigenvals())\n #Note that the eigen values for this matrix are\n v = Matrix(3, 1, [1,0,0])\n powermethodtest = powermeth(A, v, 100)\n print(\"The power method returns \" + str(powermethodtest))\n if work == powermethodtest:\n print(\"The power method worked!\")\n\n # inverse iterations method\n # see: https://en.wikiversity.org/wiki/Numerical_Analysis/Inverse_iteration_exercises\n A = Matrix(3,3, [6, 2, -1, 2, 5, 1, -1, 1, 4])\n v = Matrix(3, 1, [1,1,1])\n print(\"At 50 iterations, we expect 2.2855\")\n inverstest = inverse_iter(A, v, 50)\n print(\"The inverse iterations method at 50 iterations returns \" + str(inverstest))\n if (abs(inverstest - 2.2855) < 0.0001):\n print(\"The inverse iterations method worked!\")\n\n # shifted inverse iterations method\n # see: https://en.wikiversity.org/wiki/Shifted_inverse_iteration#Example\n A = Matrix(3,3, [0, 11, -5, -2, 17, -7, -4, 26, -10])\n v = Matrix(3, 1, [1,1,1])\n print(\"We assume to know that the eigenvalue is near 4.2. It is actually 4.\")\n inverstest = inverse_iter_shift(A, v, 4.2, 1000)\n print(\"The shifted inverse iteration method returns \" + str(inverstest))\n if abs(4 - inverstest) < 0.01:\n print(\"The shifted inverse iteration method worked!\")\n\n # shifted inverse iterations method\n # see: https://en.wikiversity.org/wiki/Shifted_inverse_iteration#Example\n #slightly modified\n A = Matrix(3,3, [0, 11, -5, -2, 17, -7, -4, 26, -10])\n v = Matrix(3, 1, [1,1,1])\n inverstest = RQI(A, v, 1000)\n print(\"We would expect this to converge to 4.\")\n print(\"The Rayleigh Quotient Iteration is \" + str(inverstest))\n if abs(4 - inverstest) < 0.01:\n print(\"The Rayleigh Quotient Iteration worked!\")","sub_path":"Desktop/learningprogramming/eigenvalues.py","file_name":"eigenvalues.py","file_ext":"py","file_size_in_byte":3913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"342160835","text":"import matplotlib.pyplot as plt\n\nlabels = [\"C\", \"Java\", \"Objective-C\", \"C++\", \"C#\", \"PHP\", \"Python\"]\n\nsizes = [17, 14, 9, 6, 5, 3, 2.5]\n\ncolors = [\"yellowgreen\", \"gold\", \"lightskyblue\", \"lightcoral\", \"darkcyan\", \"darksage\", \"rosybrown\"]\n\nexplode = [0, 0.0, 0, 0, 0, 0, 0.2]\n\nplt.axis(\"equal\")\n\nplt.pie(sizes, explode = explode, labels = labels, colors = colors, autopct = \"%1.1f%%\", shadow = True, startangle = 90)\n\nplt.show()","sub_path":"dchp14/14-4-1k.py","file_name":"14-4-1k.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"639068782","text":"from app import app\nfrom flask import render_template, redirect, request, url_for\nfrom .models import Society, Review\nfrom sqlalchemy import or_\n\n# -- PAGE : Home\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n \"\"\" List of all society already scrapp\n RUN : Run scrapp for society by her name from form\"\"\"\n societys = Society.query.all()\n if request.method == 'POST':\n society = request.form['society']\n return redirect(url_for('scrap_reviews', society=society))\n\n return render_template('index.html', societys=societys)\n\n# -- PAGE : Label data\n@app.route('/admin/labelliser-donnees', methods=['GET'])\ndef label_data():\n \"\"\" List all reviews in database\n FILTER : Apply filter on label by form \"\"\"\n reviews = Review.query.all()\n search = request.args.getlist('search')\n print(search)\n if request.method == 'GET' and search:\n print('im in!')\n # #!# Not answer found for apply 1 0 \"OR\" None conditionnaly at same time\n if 'None' in search:\n search.remove('None')\n reviews = Review.query.filter(or_(Review.label == None, Review.label.in_(search))).all()\n else:\n reviews = Review.query.filter(Review.label.in_(search)).all()\n print(reviews)\n return render_template('data-label.html', reviews=reviews)\n\n\n\n\n\n\n\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"455708004","text":"# Varanda solution : for the given number of doors\n# program will give simulation in each step\n\nnum = int(input(\"Enter the number of doors\"))\t#input the number of doors\n\n'''\nfor i in range(1, num+1):\n\tfor j in range (1, num+1):\n\t\tif (j*j == i):\n\t\t\tprint(i, \"door open\")\n\t\t\tbreak\n\telse:\n\t\tprint(i, \"door closed\")\n'''\narr = []\narr = [0 for i in range(num)]\nprint (arr)\n#for j in range(0, num+1):\n\t\n\t\t\n","sub_path":"Training/python/DAY1/varanda.py","file_name":"varanda.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"14664611","text":"from abc import ABCMeta, abstractmethod, abstractproperty\n\nfrom .. import PanBase\nfrom ..utils import load_module\nfrom ..utils.logger import get_root_logger\n\n# A dome needs a config. We assume that there is at most one dome in the config,\n# i.e. we don't support two different dome devices, such as might be the case\n# if there are multiple independent actuators, for example slit, rotation and\n# vents.\n\n\ndef CreateDomeFromConfig(config):\n \"\"\"If there is a dome specified in the config, create a driver for it.\"\"\"\n logger = get_root_logger()\n if 'dome' not in config:\n logger.debug('No dome in config.')\n return None\n dome_config = config['dome']\n if 'dome' in config.get('simulator', []):\n brand = 'simulator'\n driver = 'simulator'\n dome_config['simulator'] = True\n else:\n brand = dome_config.get('brand')\n driver = dome_config['driver']\n logger.debug('Creating dome: brand={}, driver={}'.format(brand, driver))\n module = load_module('pocs.dome.{}'.format(driver))\n dome = module.Dome(config=config)\n logger.debug('Created dome.')\n return dome\n\n\nclass AbstractDome(PanBase):\n \"\"\"Abstract base class for controlling a non-rotating dome.\n\n This assumes that the observatory 'dome' is not a classic rotating\n dome with a narrow slit, but instead something like a roll-off roof\n or clam-shell, which can be observed from when open, and that the\n other states (closed or moving) are not used for observing.\n\n Adding support for a rotating dome would require coordination during\n observing to make sure that the opening tracks the field being observed.\n \"\"\"\n __metaclass__ = ABCMeta\n\n def __init__(self, *args, **kwargs):\n \"\"\"Initialize a PanFixedDome, no connected to the underlying device.\n\n Customization generally comes from the config file, so that the\n caller doesn't need to know the params needed by a specific type of\n dome interface class.\n \"\"\"\n super().__init__(*args, **kwargs)\n self._dome_config = self.config['dome']\n\n # Sub-class directly modifies this property to record changes.\n self._is_connected = False\n\n @abstractmethod\n def connect(self): # pragma: no cover\n \"\"\"Establish a connection to the dome controller.\n\n The sub-class implementation can access configuration information\n from self._config; see PanBase for more common properties.\n\n Returns: True if connected, false otherwise.\n \"\"\"\n return NotImplemented\n\n @abstractmethod\n def disconnect(self): # pragma: no cover\n \"\"\"Disconnect from the dome controller.\n\n Returns: True if and when disconnected.\"\"\"\n return NotImplemented\n\n @abstractmethod\n def open(self): # pragma: no cover\n \"\"\"If not known to be open, attempts to open.\n\n Must already be connected.\n\n Returns: True if and when open, False if unable to open.\n \"\"\"\n return NotImplemented\n\n @abstractmethod\n def close(self): # pragma: no cover\n \"\"\"If not known to be closed, attempts to close.\n\n Must already be connected.\n\n Returns: True if and when closed, False if unable to close.\n \"\"\"\n return NotImplemented\n\n @property\n def is_connected(self):\n \"\"\"True if connected to the hardware or driver.\"\"\"\n return self._is_connected\n\n @abstractproperty\n def is_open(self): # pragma: no cover\n \"\"\"True if dome is known to be open.\"\"\"\n return NotImplemented\n\n @abstractproperty\n def is_closed(self): # pragma: no cover\n \"\"\"True if dome is known to be closed.\"\"\"\n return NotImplemented\n\n @abstractproperty\n def state(self):\n \"\"\"A string representing the state of the dome for presentation.\n\n Examples: 'Open', 'Closed', 'Opening', 'Closing', 'Left Moving',\n 'Right Stuck'\n\n Returns: A string; the default implementation returns None if the state\n can not be determined from other properties.\n \"\"\"\n if not self.is_connected():\n return 'Disconnected'\n if self.is_open():\n return 'Open'\n if self.is_closed():\n return 'Closed'\n return None\n","sub_path":"pocs/dome/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"76685673","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# ## Exact Search\n\n# ### CPU code\nimport numpy as np\nimport torch\nimport scipy.sparse as sp\nfrom scipy.sparse import csr_matrix\nimport nmslib\nimport time\nfrom tqdm import tqdm\nimport xclib\nfrom sklearn.preprocessing import normalize\n\ndef getnns_cpu(self):\n if self.hp['metric'] != 'ip':\n print('%s not supported.'%self.hp['metric'])\n return \n \n self.initialize()\n start = time.time()\n for i in tqdm(range(0, self.num_query, self.batch_size)):\n query_slice = self.hp['query'][i:i+self.batch_size]\n prod = np.dot(query_slice, self.w)\n self.indices[i:i+self.batch_size] = np.argsort(prod, axis=1)[:, -self.K:]\n self.data[i:i+self.batch_size] = np.take_along_axis(prod, self.indices[i:i+self.batch_size], axis=1)\n end = time.time()\n\n print('Total time, time per point : %.2fs, %.4fms/pt'%(end-start, (end-start)*1000/self.num_query))\n return self.getnns(self.hp['data'].shape[0])\n\n\n# ### GPU code\n\n# In[1]:\n\n\ndef getnns_gpu(self, shard_size=1000000):\n if self.w.shape[0] > shard_size:\n print(f'Doing nns in {(self.w.shape[0]+shard_size-1)//shard_size} shards')\n score_mat = csr_matrix((self.num_query, 0))\n\n for ctr in tqdm(range(0, self.w.shape[0], shard_size)):\n temp = self.getnns_gpu_shard(range(ctr, min(ctr+shard_size, self.w.shape[0])))\n score_mat = temp if ctr == 0 else xclib.utils.sparse.retain_topk(sp.hstack((score_mat, temp)).tocsr(), k=self.K)\n return score_mat\n else:\n return self.getnns_gpu_shard(range(self.w.shape[0]))\n\ndef getnns_gpu_shard(self, shard=None):\n device = self.device\n with torch.no_grad():\n w_gpu = torch.from_numpy(self.w[shard]).float().to(device)\n\n start = time.time()\n for i in tqdm(range(0, self.num_query, self.batch_size)):\n query_slice_gpu = torch.from_numpy(self.hp['query'][i:i+self.batch_size]).float().to(device)\n \n prod_gpu = None\n if self.hp['metric'] == 'ip':\n prod_gpu = torch.matmul(w_gpu, query_slice_gpu.T).T\n elif self.hp['metric'] == 'euclid':\n prod_gpu = torch.cdist(query_slice_gpu, w_gpu)\n \n batch_data_gpu, batch_indices_gpu = torch.topk(prod_gpu, k=self.K, sorted=True, largest=self.hp['sim'])\n self.data[i:i+self.batch_size], self.indices[i:i+self.batch_size] = batch_data_gpu.cpu().numpy(), batch_indices_gpu.cpu().numpy()\n end = time.time()\n\n print('Total time, time per point : %.2fs, %.4f ms/pt'%(end-start, (end-start)*1000/self.num_query))\n del w_gpu, query_slice_gpu, prod_gpu, batch_data_gpu, batch_indices_gpu\n torch.cuda.empty_cache()\n return self.getnns(len(shard))\n\n\n# In[3]:\n\n\ndef getnns_shorty_gpu(self, shorty):\n if self.hp['metric'] != 'ip':\n print('%s not supported.'%self.hp['metric'])\n return \n \n self.K = self.hp['K']\n device = self.device\n res = shorty.copy().tocoo()\n \n with torch.no_grad():\n w_gpu = torch.from_numpy(self.hp['data']).float().to(device)\n query_gpu = torch.from_numpy(self.hp['query']).float().to(device)\n rows = res.row\n cols = res.col\n bsz = self.batch_size\n\n start = time.time()\n for i in tqdm(range(0, res.nnz, bsz)):\n prod_gpu = (query_gpu[rows[i:i+bsz]] * w_gpu[cols[i:i+bsz]]).sum(dim=1)\n res.data[i:i+bsz] = prod_gpu.detach().cpu().numpy() \n end = time.time()\n\n print('Total time, time per point : %.2fs, %.4f ms/pt'%(end-start, (end-start)*1000/self.num_query))\n del w_gpu, query_gpu, prod_gpu\n torch.cuda.empty_cache()\n return res.tocsr()\n\n\n# ### Wrapper class\n\n# In[6]:\n\n\nclass exact_search:\n hp = {\n 'batch_size' : 512,\n 'score_mat' : '%s/score_mat_exact.bin'%('.'),\n 'data' : None,\n 'query' : None,\n 'K' : 10,\n 'sim' : True,\n 'metric' : 'ip',\n 'device': 'cuda:0'\n }\n getnns_gpu = getnns_gpu\n getnns_cpu = getnns_cpu\n getnns_gpu_shard = getnns_gpu_shard\n getnns_shorty_gpu = getnns_shorty_gpu\n num_query = None; num_base = None; batch_size = None; w = None; K = None; data = None; indices = None; indptr = None\n device = None\n def __init__(self, hp):\n for k, v in hp.items():\n self.hp[k] = v\n self.initialize()\n \n def initialize(self):\n self.num_query = self.hp['query'].shape[0]\n self.num_base = self.hp['data'].shape[0]\n self.batch_size = self.hp['batch_size']\n self.device = self.hp['device']\n \n if self.hp['metric'] == 'cosine':\n self.hp['query'] = normalize(self.hp['query'], axis=1)\n self.hp['data'] = normalize(self.hp['data'], axis=1)\n self.hp['metric'] = 'ip'\n \n if self.hp['metric'] == 'ip':\n self.w = self.hp['data']\n self.hp['sim'] = True\n elif self.hp['metric'] == 'euclid':\n self.w = self.hp['data']\n self.hp['sim'] = False\n \n self.K = self.hp['K']\n self.data = np.zeros((self.num_query, self.K))\n self.indices = np.zeros((self.num_query, self.K), dtype=int)\n self.indptr = range(0, self.data.shape[0]*self.data.shape[1]+1, self.data.shape[1])\n \n def getnns(self, nc, save = False):\n score_mat = csr_matrix((self.data.ravel(), self.indices.ravel(), self.indptr), (self.num_query, nc))\n if save: \n sparse.save_npz(self.hp['score_mat'], score_mat)\n# del self.data, self.indptr, self.indices\n return score_mat\n\n\n# ## HNSW\n\n# ### Training\n\n# In[16]:\n\n\ndef train_hnsw(self):\n start = time.time()\n self.index = nmslib.init(method='hnsw', space=self.hp['metric'])\n self.index.addDataPointBatch(self.hp['data'])\n self.index.createIndex({'M': self.hp['M'], 'indexThreadQty': self.hp['t'], 'efConstruction': self.hp['efC']}, print_progress=True)\n end = time.time()\n \n self.train_time = (end-start)\n print('Training time of ANNS datastructure = %f'%(self.train_time))\n nmslib.saveIndex(self.index, self.hp['model_file'])\n self.model_size = os.path.getsize(self.hp['model_file'])/1e6\n print(\"Model size : %.2f MBytes\"%(self.model_size))\n\n\n# ### Prediction\n\n# In[17]:\n\n\ndef search_hnsw(self):\n self.index.setQueryTimeParams({'efSearch': self.hp['efS'], 'algoType': 'old'})\n start = time.time()\n nbrs = np.array(self.index.knnQueryBatch(self.hp['query'], k=self.hp['K'], num_threads = self.hp['t']), dtype=object)\n end = time.time()\n \n self.search_time = end-start\n print('Time taken to find approx nearest neighbors = %f'%(self.search_time))\n \n self.data = 1-nbrs[:, 1].ravel()\n self.indptr = range(0, self.data.shape[0]+1, self.hp['K'])\n self.indices = nbrs[:, 0].ravel()\n del nbrs\n return self.getnns()\n\n\n# ### Wrapper class\n\n# In[77]:\n\n\nclass hnsw_search:\n hp = {\n 'metric' : 'cosinesimil', \n 'M' : 50,\n 't' : 6,\n 'efC' : 100,\n 'model_file' : '%s/hnsw.bin'%('.'),\n 'data' : None,\n 'query' : None,\n 'efS' : 100,\n 'K' : 10,\n 'score_mat' : '%s/score_mat_hnsw.bin'%('.'),\n 'name' : ''\n }\n train = train_hnsw\n search = search_hnsw\n data = None; indices = None; indptr = None; index = None; num_query = None; num_base = None; total_base = None\n keep_data = None; remap = None; remap_inv = None\n train_time = None; search_time = None; model_size = None\n \n def __init__(self, hp):\n for k, v in hp.items():\n self.hp[k] = v\n self.hp['model_file'] = '%s/hnsw_%s_%d_%d.bin'%(results_dir, self.hp['name'], self.hp['efC'], self.hp['M'])\n self.total_base = self.hp['data'].shape[0]\n self.preprocess()\n \n def preprocess(self):\n if self.hp['metric'] == 'cosinesimil':\n norms = np.linalg.norm(self.hp['data'], axis=1)\n self.keep_data = np.where(abs(norms-1) < 0.05)[0]\n del norms\n else:\n self.keep_data = np.arange(self.total_base)\n print('Keeping %d/%d base points after preprocess'%(self.keep_data.shape[0], self.total_base))\n \n self.remap = np.vectorize({i : v for i, v in enumerate(self.keep_data)}.get)\n self.remap_inv = np.vectorize({v : i for i, v in enumerate(self.keep_data)}.get)\n self.hp['data'] = self.hp['data'][self.keep_data]\n \n def getnns(self):\n score_mat = csr_matrix((self.data.ravel().astype(float), self.remap(self.indices.ravel().astype(int)), self.indptr), (self.hp['query'].shape[0], self.total_base))\n# del self.data, self.indptr, self.indices\n return score_mat\n \n def load_index(self, filename = None):\n if filename is None: filename = self.hp['model_file']\n self.index = nmslib.init(method='hnsw', space=self.hp['metric'])\n nmslib.loadIndex(self.index, filename)\n\n","sub_path":"src/OLTR/nns.py","file_name":"nns.py","file_ext":"py","file_size_in_byte":9201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"243075143","text":"import json\nimport re\nfrom flask import render_template,request,Blueprint,redirect,url_for\nfrom flask_login import LoginManager\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom common.MESLogger import logger,insertSyslog\nfrom common.BSFramwork import AlchemyEncoder\nfrom common.system import Organization, Factory, DepartmentManager, Role, Permission, ModulMenus, User, RolePermission, \\\n RoleUser\nfrom flask_login import current_user, LoginManager\nfrom database.db_operate import DB_URL\nlogin_manager = LoginManager()\n# 创建对象的基类\nengine = create_engine(DB_URL)\nSession = sessionmaker(bind=engine)\ndb_session = Session()\nBase = declarative_base(engine)\n\npermission_distribution = Blueprint('permission_distribution', __name__, template_folder='templates')\n\n# 权限分配\n@permission_distribution.route('/permission')\ndef permission():\n return render_template('./permission.html')\n\n# 角色列表树形图\ndef getRoleList(id=0):\n sz = []\n try:\n roles = db_session.query(Role).filter().all()\n for obj in roles:\n if obj.ParentNode == id:\n sz.append({\"id\": obj.ID,\n \"text\": obj.RoleName,\n \"children\": getRoleList(obj.ID)})\n srep = ',' + 'items' + ':' + '[]'\n return sz\n except Exception as e:\n print(e)\n logger.error(e)\n insertSyslog(\"error\", \"查询角色报错Error:\" + str(e), current_user.Name)\n return json.dumps([{\"status\": \"Error:\" + str(e)}], cls=AlchemyEncoder, ensure_ascii=False)\n\n# 权限分配下的角色列表\n@permission_distribution.route('/Permission/SelectRoles')\ndef SelectRoles():\n if request.method == 'GET':\n try:\n data = getRoleList(id=0)\n jsondata = json.dumps(data, cls=AlchemyEncoder, ensure_ascii=False)\n return jsondata.encode(\"utf8\")\n except Exception as e:\n print(e)\n logger.error(e)\n insertSyslog(\"error\", \"查询权限分配下的角色列表报错Error:\" + str(e), current_user.Name)\n return json.dumps([{\"status\": \"Error:\" + str(e)}], cls=AlchemyEncoder, ensure_ascii=False)\n\n\n# 权限分配下的用户列表\n@permission_distribution.route('/permission/userlist')\ndef userList():\n # 获取用户列表\n if request.method == 'GET':\n data = request.values # 返回请求中的参数和form\n # 默认返回所有用户\n ID = data['ID']\n if ID == '':\n try:\n json_str = json.dumps(data.to_dict())\n if len(json_str) > 10:\n pages = int(data.get(\"offset\")) # 页数\n rowsnumber = int(data.get(\"limit\")) # 行数\n inipage = pages * rowsnumber + 0 # 起始页\n endpage = pages * rowsnumber + rowsnumber # 截止页\n total = db_session.query(User).count()\n users_data = db_session.query(User)[inipage:endpage]\n # ORM模型转换json格式\n jsonusers = json.dumps(users_data, cls=AlchemyEncoder, ensure_ascii=False)\n jsonusers = '{\"total\"' + \":\" + str(total) + ',\"rows\"' + \":\\n\" + jsonusers + \"}\"\n return jsonusers.encode(\"utf8\")\n except Exception as e:\n print(e)\n logger.error(e)\n insertSyslog(\"error\", \"查询权限分配下的用户列表报错Error:\" + str(e), current_user.Name)\n return json.dumps([{\"status\": \"Error:\" + str(e)}], cls=AlchemyEncoder, ensure_ascii=False)\n if ID != '':\n data = request.values # 返回请求中的参数和form\n try:\n json_str = json.dumps(data.to_dict())\n if len(json_str) > 10:\n pages = int(data['page']) # 页数\n rowsnumber = int(data['rows']) # 行数\n inipage = (pages - 1) * rowsnumber + 0 # 起始页\n endpage = (pages - 1) * rowsnumber + rowsnumber # 截止页\n # 通过角色ID获取当前角色对应的用户\n role_id = data['ID']\n role_name= db_session.query(Role.RoleName).filter_by(ID=role_id).first()\n if role_name is None: # 判断当前角色是否存在\n return\n total = db_session.query(User).filter_by(RoleName=role_name).count()\n users_data = db_session.query(User).filter_by(RoleName=role_name).all()[\n inipage:endpage]\n # ORM模型转换json格式\n jsonusers = json.dumps(users_data, cls=AlchemyEncoder, ensure_ascii=False)\n jsonusers = '{\"total\"' + \":\" + str(total) + ',\"rows\"' + \":\\n\" + jsonusers + \"}\"\n return jsonusers\n except Exception as e:\n print(e)\n logger.error(e)\n insertSyslog(\"error\", \"通过点击角色查询用户报错Error:\" + str(e), current_user.Name)\n return json.dumps([{\"status\": \"Error:\" + str(e)}], cls=AlchemyEncoder, ensure_ascii=False)\n\ndef trueOrFalse(obj,user_menus):\n dic = {}\n if str(obj.ModulMenuName) in user_menus:\n dic[\"checked\"] = True\n return dic\n else:\n dic[\"checked\"] = False\n return dic\n\n# 权限分配下的功能模块列表\ndef getMenuList(user_menus, id=0):\n sz = []\n try:\n menus = db_session.query(ModulMenus).filter_by(ParentNode=id).all()\n for obj in menus:\n if obj.ParentNode == id:\n sz.append({\"id\": obj.ID,\n \"text\": obj.ModulMenuName,\n \"ModulMenuName\":obj.ModulMenuName,\n \"MenuType\":obj.MenuType,\n \"ModulMenuCode\":obj.ModulMenuCode,\n \"state\":trueOrFalse(obj, user_menus),\n \"nodes\": getMenuList(user_menus, obj.ID)})\n return sz\n except Exception as e:\n print(e)\n insertSyslog(\"error\", \"查询权限分配下的功能模块列表Error:\" + str(e), current_user.Name)\n return json.dumps([{\"status\": \"Error:\" + str(e)}], cls=AlchemyEncoder, ensure_ascii=False)\n\n\n# 菜单权限查询\n@permission_distribution.route('/Permission/SelectMenus', methods=['POST', 'GET'])\ndef SelectMenus():\n if request.method == 'GET':\n data = request.values\n try:\n MenuType = data.get(\"MenuType\")\n Name = current_user.Name\n if Name == \"系统管理员\":\n oclass = db_session.query(ModulMenus).all()\n count = db_session.query(ModulMenus).count()\n return {\"code\": \"200\", \"message\": \"请求成功\", \"data\": {\"total\": count, \"rows\": oclass}}\n periss = db_session.query(Permission).filter(Permission.Name == current_user.Name, Permission.MenuType == MenuType).all()\n flag = 'OK'\n dic = []\n for i in periss:\n oclass = db_session.query(ModulMenus).filter(\n ModulMenus.ResourceMenuName.like(\"%\" + i.MenuName + \"%\")).first()\n dic.append(oclass)\n # if MenuType == \"资源级\":\n # oclass = db_session.query(ResourceMenus).filter(ResourceMenus.ModulMenuName.like(\"%\"+i.MenuName+\"%\")).first()\n # dic.append(oclass)\n # else:\n # oclass = db_session.query(ModulMenus).filter(\n # ModulMenus.ResourceMenuName.like(\"%\" + i.MenuName + \"%\")).first()\n # dic.append(oclass)\n return {\"code\": \"200\", \"message\": \"请求成功\", \"data\": {\"total\": len(dic), \"rows\": dic}}\n except Exception as e:\n print(e)\n logger.error(e)\n insertSyslog(\"error\", \"菜单权限查询报错Error:\" + str(e), current_user.Name)\n return {\"code\": \"500\", \"message\": \"请求错误\", \"data\": \"菜单权限查询报错Error:\" + str(e)}\n\n# 增加菜单父节点查询\n@permission_distribution.route('/Permission/SelectParentMenus', methods=['POST', 'GET'])\ndef SelectParentMenus():\n if request.method == 'GET':\n data = request.values\n try:\n pages = int(data.get(\"offset\")) # 页数\n rowsnumber = int(data.get(\"limit\")) # 行数\n inipage = pages * rowsnumber + 0 # 起始页\n endpage = pages * rowsnumber + rowsnumber # 截止页\n total = db_session.query(ModulMenus).filter(ModulMenus.MenuType.in_((\"系统级\", \"模块级\"))).count()\n oclass = db_session.query(ModulMenus).filter(ModulMenus.MenuType.in_((\"系统级\", \"模块级\"))).all()[inipage:endpage]\n jsonoclass = json.dumps(oclass, cls=AlchemyEncoder, ensure_ascii=False)\n return '{\"total\"' + \":\" + str(total) + ',\"rows\"' + \":\\n\" + jsonoclass + \"}\"\n except Exception as e:\n print(e)\n logger.error(e)\n insertSyslog(\"error\", \"增加菜单父节点查询报错Error:\" + str(e), current_user.Name)\n return json.dumps([{\"status\": \"Error:\" + str(e)}], cls=AlchemyEncoder, ensure_ascii=False)\n\n# 加载菜单列表\n@permission_distribution.route('/permission/menulisttree', methods=['POST', 'GET'])\ndef menulisttree():\n if request.method == 'GET':\n data = request.values\n try:\n WorkNumber = data.get(\"WorkNumber\")\n user_menus = []\n usermenus = db_session.query(Permission.MenuName).filter(Permission.WorkNumber == WorkNumber).all()\n for menu in usermenus:\n user_menus.append(menu[0])\n data = getMenuList(user_menus, id=0)\n jsondata = json.dumps(data, cls=AlchemyEncoder, ensure_ascii=False)\n return jsondata.encode(\"utf8\")\n except Exception as e:\n print(e)\n logger.error(e)\n insertSyslog(\"error\", \"加载菜单列表Error:\" + str(e), current_user.Name)\n return json.dumps([{\"status\": \"Error:\" + str(e)}], cls=AlchemyEncoder, ensure_ascii=False)\n\n# 加载菜单列表\n@permission_distribution.route('/permission/PermissionsSave', methods=['POST', 'GET'])\ndef PermissionsSave():\n if request.method == 'POST':\n data = request.values\n try:\n datastr = json.loads(data.get(\"data\"))\n #删除之前的权限\n perss = db_session.query(Permission).filter(Permission.WorkNumber == datastr[0].get(\"WorkNumber\")).all()\n for pe in perss:\n db_session.delete(pe)\n db_session.commit()\n for i in datastr:\n per = Permission()\n per.MenuName = i.get(\"MenuName\")\n per.MenuType = i.get(\"MenuType\")\n per.MenuCode = i.get(\"MenuCode\")\n per.Name = i.get(\"Name\")\n per.WorkNumber = i.get(\"WorkNumber\")\n db_session.add(per)\n db_session.commit()\n return 'OK'\n except Exception as e:\n db_session.rollback()\n print(e)\n logger.error(e)\n insertSyslog(\"error\", \"添加用户报错Error:\" + str(e), current_user.Name)\n return json.dumps([{\"status\": \"Error:\" + str(e)}], cls=AlchemyEncoder, ensure_ascii=False)\n\n# 加载菜单列表\n@permission_distribution.route('/permission/PermissionsMenus', methods=['POST', 'GET'])\ndef PermissionsMenus():\n if request.method == 'GET':\n data = request.values\n try:\n MenuName = data.get(\"MenuName\")\n MenuType = data.get(\"MenuType\")\n if MenuName == None:\n MenuNames = db_session.query(Permission.MenuName).filter(Permission.WorkNumber == current_user.WorkNumber, Permission.MenuType == MenuType).all()\n else:\n ParentNode = db_session.query(ModulMenus.ID).filter(ModulMenus.ModulMenuName == MenuName).first()\n pmenus = db_session.query(ModulMenus.ModulMenuName).filter(ModulMenus.ParentNode == ParentNode,ModulMenus.MenuType == MenuType).all()\n cmenus = db_session.query(Permission.MenuName).filter(Permission.WorkNumber == current_user.WorkNumber).all()\n MenuNames = list(set(pmenus).intersection(set(cmenus)))\n dir = []\n for mn in MenuNames:\n meu = db_session.query(ModulMenus).filter(ModulMenus.ModulMenuName == mn).first()\n dir.append(meu)\n if dir:\n dir = sorted(dir, key=lambda aa: aa.ID)\n return json.dumps(dir, cls=AlchemyEncoder, ensure_ascii=False)\n except Exception as e:\n db_session.rollback()\n print(e)\n logger.error(e)\n insertSyslog(\"error\", \"添加用户报错Error:\" + str(e), current_user.Name)\n return json.dumps([{\"status\": \"Error:\" + str(e)}], cls=AlchemyEncoder, ensure_ascii=False)\n\n@permission_distribution.route('/permission/saverolepermission', methods=['POST', 'GET'])\ndef saverolepermission():\n '''\n 角色添加权限\n :return:\n '''\n if request.method == 'POST':\n data = request.values\n try:\n roleID = data.get(\"roleID\")\n permissionIDs = data.get(\"permissionIDs\")\n if permissionIDs:\n permissionIDs = eval(permissionIDs)\n roleclass = db_session.query(Role).filter(Role.ID == int(roleID)).first()\n sql = \"delete from RolePermission where RoleID = \" + roleID\n db_session.execute(sql)\n db_session.commit()\n for pid in permissionIDs:\n permissioncalss = db_session.query(Permission).filter(Permission.ID == int(pid)).first()\n rpclas = db_session.query(RolePermission).filter(RolePermission.RoleID == roleclass.ID, RolePermission.PermissionID == permissioncalss.ID).first()\n if not rpclas:\n rp = RolePermission()\n rp.RoleID = roleclass.ID\n rp.RoleName = roleclass.RoleName\n rp.PermissionID = permissioncalss.ID\n rp.PermissionName = permissioncalss.PermissionName\n db_session.add(rp)\n db_session.commit()\n return json.dumps(\"OK\", cls=AlchemyEncoder, ensure_ascii=False)\n except Exception as e:\n db_session.rollback()\n print(e)\n logger.error(e)\n insertSyslog(\"error\", \"角色添加权限Error:\" + str(e), current_user.Name)\n\n@permission_distribution.route('/permission/selectpermissionbyrole', methods=['POST', 'GET'])\ndef selectpermissionbyrole():\n '''\n 根据角色查询权限\n :return:\n '''\n if request.method == 'GET':\n data = request.values\n try:\n dir = {}\n roleID = data.get(\"roleID\")\n pids = db_session.query(RolePermission).filter(RolePermission.RoleID == int(roleID)).all()\n perids_list = []\n for pid in pids:\n perids_list.append(pid.PermissionID)\n if len(perids_list) > 0:\n existingRows = db_session.query(Permission).filter(Permission.ID.in_(perids_list)).all()\n dir[\"existingRows\"] = existingRows\n else:\n dir[\"existingRows\"] = []\n notHaveRows = db_session.query(Permission).filter().all()\n dir[\"notHaveRows\"] = notHaveRows\n return json.dumps(dir, cls=AlchemyEncoder, ensure_ascii=False)\n except Exception as e:\n print(e)\n logger.error(e)\n insertSyslog(\"error\", \"根据角色查询权限Error:\" + str(e), current_user.Name)\n\n@permission_distribution.route('/permission/selectpermissionbyuser', methods=['POST', 'GET'])\ndef selectpermissionbyuser():\n '''\n 根据用户查询权限\n :return:\n '''\n if request.method == 'GET':\n data = request.values\n try:\n userid = db_session.query(User.ID).filter(User.WorkNumber == current_user.WorkNumber).first()[0]\n rolecos = db_session.query(RoleUser).filter(RoleUser.UserID == userid).all()\n permission_list = []\n for ro in rolecos:\n rps = db_session.query(RolePermission).filter(RolePermission.RoleID == ro.RoleID).all()\n for rp in rps:\n permission_list.append(rp.PermissionName)\n return json.dumps({\"code\": \"200\", \"message\": \"请求成功\", \"data\": {\"total\": len(permission_list), \"rows\": permission_list}})\n except Exception as e:\n print(e)\n logger.error(e)\n insertSyslog(\"error\", \"根据用户查询权限Error:\" + str(e), current_user.Name)\n return {\"code\": \"500\", \"message\": \"请求错误\", \"data\": \"根据用户查询权限报错Error:\" + str(e)}\n","sub_path":"system_backend/SystemManagement/PermissionAssignment.py","file_name":"PermissionAssignment.py","file_ext":"py","file_size_in_byte":17059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"365517881","text":"# coding=utf-8\n\n\nimport datetime\n\nfrom .aliyun_oss import get_img_oss_url\n\n# 将sql原生语句执行之后返回的结果转换为字典格式\n\n\"\"\"\n reserve:为预设key,当执行sql原生语句给与的结果进行字典转换,当key与查询出的字段为一致则进行一些额外操作\n 例如:\n \n 数据库查询得到字段(select field_1,field_2 from table where ...) 其中field_*需要经过特别处理,\n 创建一个list_items 列表和 item字典,\n 数据并循环(sql原生语句查询得到的结构为一个列表,使用dir可以看到该循环的keys...操作方法),\n 使用该数据的 enumerate(result.keys()) 得到index索引和key值\n (注意在select field_1 as u1,field_2 as u2 from ... 那么在keys中的key为as之后的值,无as则为表中字段名)\n 将得到的key填充到字典item的key位置,value为索引位置\n \n 如下 一个时间格式, 经过isinstance 是否该字段为datetime类,是则进行字符串转换\n \n 这里因为是对这个项目负责,该项目用户上传文件都市通过阿里云oss的sign签名\n 后端返回oss中的路径,由前端上传阿里云oss,如果经过保存则由前端上传完毕之后把oss路径返回后端保存,不经过服务器代理上传\n 所以当用户查询到一些保存在oss中数据时,不处理返回的则是单纯的在oss保存路径,无效 \n \n 这个方法已经固定了,如果有需求可以另外重构\n \n\"\"\"\ndef sql_result_to_dict(results,reserve=None):\n list_items = []\n\n for result in results:\n item = {}\n for index ,key in enumerate(result.keys()):\n if isinstance(result[index], datetime.datetime) or isinstance(result[index], datetime.date):\n item[key] = result[index].strftime('%Y-%m-%d %H:%M:%S')\n else:\n item[key] = result[index]\n\n if key == reserve:\n item[key] = get_img_oss_url(result[index],86000/2)\n list_items.append(item)\n\n return list_items","sub_path":"OnlineClassroom/app/utils/sql_result.py","file_name":"sql_result.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"143116329","text":"\n\nclass StripeDispatcher():\n\n def __init__(self, customer, charge):\n self.customer_class = customer\n self.charge_class = charge\n\n def finalize_charge(self, token, article):\n customer = self.customer_class.create(\n email=token['email'],\n card=token['id']\n )\n\n price = int(article.price * 100)\n charge = self.charge_class.create(\n customer=customer.id,\n amount=price,\n currency='usd',\n description='{}: {}'.format(article.store.name, article.name)\n )\n\n return {\n 'txid': charge.balance_transaction,\n 'chid': charge.id,\n 'status': charge.status,\n 'amount': article.price,\n }\n","sub_path":"payments/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"575273914","text":"import os\nimport subprocess\nfrom unittest import mock\n\nfrom . import OriginTest, through_json\nfrom .. import assert_logging, mock_open_log\n\nfrom mopack.iterutils import iterate\nfrom mopack.origins import Package\nfrom mopack.origins.apt import AptPackage\nfrom mopack.origins.conan import ConanPackage\nfrom mopack.types import dependency_string\n\n\ndef mock_run(args, **kwargs):\n if args[0] == 'dpkg-query':\n return subprocess.CompletedProcess(args, 0, '1.2.3')\n raise OSError()\n\n\nclass TestApt(OriginTest):\n pkg_type = AptPackage\n pkgconfdir = os.path.join(OriginTest.pkgdir, 'pkgconfig')\n\n def check_resolve_all(self, pkgs, remotes):\n with mock_open_log() as mopen, \\\n mock.patch('subprocess.run') as mrun:\n with assert_logging([('resolve', '{} from apt'.format(i.name))\n for i in pkgs]):\n AptPackage.resolve_all(self.metadata, pkgs)\n\n mopen.assert_called_with(os.path.join(\n self.pkgdir, 'logs', 'apt.log'\n ), 'a')\n\n for i in pkgs:\n if i.repository:\n mrun.assert_any_call(\n ['sudo', 'add-apt-repository', '-y', i.repository],\n stdout=subprocess.PIPE, stderr=subprocess.STDOUT,\n universal_newlines=True, check=True, env={}\n )\n mrun.assert_any_call(\n ['sudo', 'apt-get', 'update'], stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT, universal_newlines=True, check=True,\n env={}\n )\n mrun.assert_any_call(\n ['sudo', 'apt-get', 'install', '-y'] + remotes,\n stdout=subprocess.PIPE, stderr=subprocess.STDOUT,\n universal_newlines=True, check=True, env={}\n )\n\n def check_linkage(self, pkg, *, submodules=None, linkage=None):\n if linkage is None:\n depname = dependency_string(pkg.name, submodules)\n libs = ([] if pkg.submodules and pkg.submodules['required']\n else [pkg.name])\n libs.extend('{}_{}'.format(pkg.name, i)\n for i in iterate(submodules))\n\n linkage = {'name': depname, 'type': 'system', 'generated': True,\n 'auto_link': False, 'pcnames': [depname],\n 'pkg_config_path': [self.pkgconfdir]}\n\n with mock.patch('subprocess.run', mock_run), \\\n mock.patch('mopack.linkages.path_system.PathLinkage._filter_path',\n lambda *args: []), \\\n mock.patch('mopack.linkages.path_system.file_outdated',\n return_value=True), \\\n mock.patch('os.makedirs'), \\\n mock.patch('builtins.open'):\n self.assertEqual(pkg.get_linkage(self.metadata, submodules),\n linkage)\n\n def test_basic(self):\n pkg = self.make_package('foo')\n self.assertEqual(pkg.remote, ['libfoo-dev'])\n self.assertEqual(pkg.repository, None)\n self.assertEqual(pkg.needs_dependencies, False)\n self.assertEqual(pkg.should_deploy, True)\n self.check_resolve_all([pkg], ['libfoo-dev'])\n\n with mock.patch('subprocess.run', side_effect=mock_run) as mrun:\n self.assertEqual(pkg.version(self.metadata), '1.2.3')\n mrun.assert_has_calls([\n mock.call(\n ['pkg-config', 'foo', '--modversion'], check=True,\n stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,\n universal_newlines=True, env={}\n ),\n mock.call(\n ['dpkg-query', '-W', '-f${Version}', 'libfoo-dev'],\n check=True, stdout=subprocess.PIPE,\n universal_newlines=True, env={}\n ),\n ])\n\n self.check_linkage(pkg)\n\n def test_remote(self):\n pkg = self.make_package('foo', remote='foo-dev')\n self.assertEqual(pkg.remote, ['foo-dev'])\n self.assertEqual(pkg.repository, None)\n self.check_resolve_all([pkg], ['foo-dev'])\n\n with mock.patch('subprocess.run', side_effect=mock_run) as mrun:\n self.assertEqual(pkg.version(self.metadata), '1.2.3')\n mrun.assert_has_calls([\n mock.call(\n ['pkg-config', 'foo', '--modversion'], check=True,\n stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,\n universal_newlines=True, env={}\n ),\n mock.call(\n ['dpkg-query', '-W', '-f${Version}', 'foo-dev'],\n check=True, stdout=subprocess.PIPE,\n universal_newlines=True, env={}\n ),\n ])\n\n self.check_linkage(pkg)\n\n pkg = self.make_package('foo', remote=['foo-dev', 'bar-dev'])\n self.assertEqual(pkg.remote, ['foo-dev', 'bar-dev'])\n self.assertEqual(pkg.repository, None)\n self.check_resolve_all([pkg], ['foo-dev', 'bar-dev'])\n\n with mock.patch('subprocess.run', side_effect=mock_run) as mrun:\n pkg.version(self.metadata)\n mrun.assert_has_calls([\n mock.call(\n ['pkg-config', 'foo', '--modversion'], check=True,\n stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,\n universal_newlines=True, env={}\n ),\n mock.call(\n ['dpkg-query', '-W', '-f${Version}', 'foo-dev'],\n check=True, stdout=subprocess.PIPE,\n universal_newlines=True, env={}\n ),\n ])\n\n self.check_linkage(pkg)\n\n def test_repository(self):\n pkg = self.make_package('foo', remote='foo-dev',\n repository='ppa:foo/stable')\n self.assertEqual(pkg.remote, ['foo-dev'])\n self.assertEqual(pkg.repository, 'ppa:foo/stable')\n self.check_resolve_all([pkg], ['foo-dev'])\n self.check_linkage(pkg)\n\n def test_explicit_version(self):\n pkg = self.make_package('foo', linkage={\n 'type': 'system', 'version': '2.0',\n })\n self.assertEqual(pkg.remote, ['libfoo-dev'])\n self.assertEqual(pkg.repository, None)\n self.assertEqual(pkg.needs_dependencies, False)\n self.assertEqual(pkg.should_deploy, True)\n self.check_resolve_all([pkg], ['libfoo-dev'])\n\n with mock.patch('subprocess.run', side_effect=mock_run) as mrun:\n self.assertEqual(pkg.version(self.metadata), '2.0')\n mrun.assert_called_once_with(\n ['pkg-config', 'foo', '--modversion'], check=True,\n stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,\n universal_newlines=True, env={}\n )\n\n self.check_linkage(pkg)\n\n def test_multiple(self):\n pkgs = [self.make_package('foo'),\n self.make_package('bar', remote='bar-dev')]\n self.check_resolve_all(pkgs, ['libfoo-dev', 'bar-dev'])\n for pkg in pkgs:\n self.check_linkage(pkg)\n\n def test_submodules(self):\n submodules_required = {'names': '*', 'required': True}\n submodules_optional = {'names': '*', 'required': False}\n\n pkg = self.make_package('foo', submodules=submodules_required)\n self.check_resolve_all([pkg], ['libfoo-dev'])\n self.check_linkage(pkg, submodules=['sub'])\n\n pkg = self.make_package(\n 'foo', linkage={'type': 'system', 'libraries': 'bar'},\n submodules=submodules_required\n )\n self.check_resolve_all([pkg], ['libfoo-dev'])\n self.check_linkage(pkg, submodules=['sub'], linkage={\n 'name': 'foo[sub]', 'type': 'system', 'generated': True,\n 'auto_link': False, 'pcnames': ['foo[sub]'],\n 'pkg_config_path': [self.pkgconfdir],\n })\n\n pkg = self.make_package('foo', submodules=submodules_optional)\n self.check_resolve_all([pkg], ['libfoo-dev'])\n self.check_linkage(pkg, submodules=['sub'])\n\n pkg = self.make_package(\n 'foo', linkage={'type': 'system', 'libraries': 'bar'},\n submodules=submodules_optional\n )\n self.check_resolve_all([pkg], ['libfoo-dev'])\n self.check_linkage(pkg, submodules=['sub'], linkage={\n 'name': 'foo[sub]', 'type': 'system', 'generated': True,\n 'auto_link': False, 'pcnames': ['foo[sub]'],\n 'pkg_config_path': [self.pkgconfdir],\n })\n\n def test_invalid_submodule(self):\n pkg = self.make_package('foo', submodules={\n 'names': ['sub'], 'required': True\n })\n with self.assertRaises(ValueError):\n pkg.get_linkage(self.metadata, ['invalid'])\n\n def test_deploy(self):\n pkg = self.make_package('foo')\n # This is a no-op; just make sure it executes ok.\n AptPackage.deploy_all(self.metadata, [pkg])\n\n def test_clean_pre(self):\n oldpkg = self.make_package('foo')\n newpkg = self.make_package(ConanPackage, 'foo',\n remote='foo/1.2.4@conan/stable')\n\n # Apt -> Conan\n self.assertEqual(oldpkg.clean_pre(self.metadata, newpkg), False)\n\n # Apt -> nothing\n self.assertEqual(oldpkg.clean_pre(self.metadata, None), False)\n\n def test_clean_post(self):\n oldpkg = self.make_package('foo')\n newpkg = self.make_package(ConanPackage, 'foo',\n remote='foo/1.2.4@conan/stable')\n\n # Apt -> Conan\n self.assertEqual(oldpkg.clean_post(self.metadata, newpkg), False)\n\n # Apt -> nothing\n self.assertEqual(oldpkg.clean_post(self.metadata, None), False)\n\n def test_clean_all(self):\n oldpkg = self.make_package('foo')\n newpkg = self.make_package(ConanPackage, 'foo',\n remote='foo/1.2.4@conan/stable')\n\n # Apt -> Conan\n self.assertEqual(oldpkg.clean_all(self.metadata, newpkg),\n (False, False))\n\n # Apt -> nothing\n self.assertEqual(oldpkg.clean_all(self.metadata, None), (False, False))\n\n def test_equality(self):\n pkg = self.make_package('foo')\n\n self.assertEqual(pkg, self.make_package('foo'))\n self.assertEqual(pkg, self.make_package('foo', remote='libfoo-dev'))\n self.assertEqual(pkg, self.make_package(\n 'foo', config_file='/path/to/mopack2.yml'\n ))\n\n self.assertNotEqual(pkg, self.make_package('bar'))\n self.assertNotEqual(pkg, self.make_package('bar', remote='libfoo-dev'))\n self.assertNotEqual(pkg, self.make_package('foo', remote='libbar-dev'))\n\n def test_rehydrate(self):\n opts = self.make_options()\n pkg = AptPackage('foo', remote='libbar-dev', _options=opts,\n config_file=self.config_file)\n data = through_json(pkg.dehydrate())\n self.assertEqual(pkg, Package.rehydrate(data, _options=opts))\n\n def test_upgrade(self):\n opts = self.make_options()\n data = {'origin': 'apt', '_version': 0, 'name': 'foo',\n 'remote': 'libfoo-dev', 'repository': None,\n 'linkage': {'type': 'system', '_version': 0}}\n with mock.patch.object(AptPackage, 'upgrade',\n side_effect=AptPackage.upgrade) as m:\n pkg = Package.rehydrate(data, _options=opts)\n self.assertIsInstance(pkg, AptPackage)\n m.assert_called_once()\n","sub_path":"test/unit/origins/test_apt.py","file_name":"test_apt.py","file_ext":"py","file_size_in_byte":11602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"19030099","text":"from flask import Flask, Response\nfrom flaskext.mysql import MySQL\nimport json\nimport sys\nimport requests\nfrom key import lyft_key, uber_key\t\t\t\t#importing keys of the Uber and Lyft api's\nfrom tsp_dp import shortestPath\n\nmysql = MySQL()\napp = Flask(__name__)\napp.config['MYSQL_DATABASE_USER'] = ''\napp.config['MYSQL_DATABASE_PASSWORD'] = ''\napp.config['MYSQL_DATABASE_DB'] = ''\napp.config['MYSQL_DATABASE_HOST'] = ''\nmysql.init_app(app)\n\t\t\t\t\t\nlyft_url = 'https://api.lyft.com/v1/cost'\nuber_url = 'https://api.uber.com/v1.2/estimates/price'\n\n# Class for calculating the requirements\nclass PriceDiff():\n\tdef __init__(self,myDict):\n\t\tself._start = myDict['start']\n\t\tself._end = myDict['end']\n\t\tself._other = myDict['others']\n\t\tself._othLen = len(myDict['others'])\n\t\tself._myLoc = self.getMyLoc()\n\t\tself._latLng = self.getLatLng()\n\t\tself._uEst = self.uberDetails()\n\t\tself._lEst = self.lyftDetails()\n\t'''\n\tDummy method to test DB\n\t--------------------------\n\tdef printPts(self):\n\t\tlatLng = []\n\t\tcursor = mysql.connect().cursor()\n\t\tl = len(self.myLoc)\n\t\ti=0\n\t\twhile(i < l):\n\t\t\tcursor.execute(\"select lat, lng from location where id= %s\", (self.myLoc[i]))\n\t\t\tdata = cursor.fetchall()\n\t\t\tlatLng.append([data[0][0],data[0][1]])\n\t\t\ti=i+1\n\t\treturn json.dumps(latLng) #json.dumps({'start':self._start, 'end':self._end, 'others':self._other})\n\t'''\n\t# List storing the Lat-Lng pairs of the required locations\n\t# Format: latLng = [[37.4029455, -121.9437678], [37.4223664, -122.084406],....]\n\tdef getLatLng(self):\n\t\tlatLng = []\n\t\tcursor = mysql.connect().cursor()\n\t\tl = len(self.myLoc)\n\t\ti=0\n\t\twhile(i < l):\n\t\t\tcursor.execute(\"select lat, lng from location where id= %s\", (self.myLoc[i]))\n\t\t\tdata = cursor.fetchall()\n\t\t\tlatLng.append([data[0][0],data[0][1]])\n\t\t\ti=i+1\n\t\treturn latLng\n\n\t# List for converting the location id's to index to be used for the TSP algo\n\tdef getMyLoc(self):\n\t\tmyLoc = []\n\t\tmyLoc.append(self._start)\n\t\ti=0\n\t\twhile (i= len(nums):\n break\n for ii in range(l, count):\n if ii > len(nums) - 1:\n break\n if ii == l:\n maxx = count\n if nums[ii] + ii + 1 > maxx:\n maxx = nums[ii] + ii + 1\n index = ii\n\n if maxx > count:\n res += 1\n l = index\n count = maxx\n\n return res\n\n\nprint(Solution().jump([1, 2]))\nprint(Solution().jump([2,1]))\nprint(Solution().jump([2,3,1,1,4]))\nprint(Solution().jump([7,0,9,6,9,6,1,7,9,0,1,2,9,0,3]))","sub_path":"LeetCode/1808/45_jump_gameII_180826.py","file_name":"45_jump_gameII_180826.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"465676572","text":"from toydist.package import \\\n PackageDescription\n\ndef distutils_to_package_description(dist):\n name = dist.get_name()\n version = dist.get_version()\n py_modules = dist.py_modules\n packages = dist.packages\n extensions = dist.ext_modules\n\n return PackageDescription(name, version=version, py_modules=py_modules,\n packages=packages, extensions=extensions)\n","sub_path":"toydist/conv.py","file_name":"conv.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"348015877","text":"import redis.client\nimport redis_client as tbot_datastore\n\nfrom mr import MR\n\n'''\nGet Information relating to MRs\n'''\n\n# Returns a list of MR as MR objects\ndef get_all_mrs(redis_db):\n mr_name = 'mr_alloc'\n all_mrs = redis_db.hgetall(mr_name)\n mr_list = list(all_mrs.keys())\n mr_object_list = []\n for mr in mr_list:\n service_name,resource = mr.split(',')\n deployments = tbot_datastore.read_service_locations(redis_db, service_name)\n mr_object_list.append(MR(service_name, resource, deployments))\n return mr_object_list\n\n'''\nThis is specifically for the storing and accessing of the redis data \nrelating to the current resource allocation of a MR\n'''\n\ndef generate_mr_key(mr_service, mr_resource):\n return '{},{}'.format(mr_service, mr_resource)\n\ndef write_mr_alloc(redis_db, mr, new_allocation):\n mr_name = 'mr_alloc'\n key = generate_mr_key(mr.service_name, mr.resource)\n redis_db.hset(mr_name, key, new_allocation)\n\ndef read_mr_alloc(redis_db, mr):\n mr_name = 'mr_alloc'\n key = generate_mr_key(mr.service_name, mr.resource)\n return float(redis_db.hget(mr_name, key))\n\n# Returns a list of MR objects with their current allocations\ndef read_all_mr_alloc(redis_db):\n mr_name = 'mr_alloc'\n mr_to_score = redis_db.hgetall(mr_name)\n for mr in mr_to_score:\n mr_to_score[mr] = float(mr_to_score[mr])\n\n mr_allocation_list = {}\n for mr in mr_to_score:\n service_name,resource = mr.split(',')\n deployments = tbot_datastore.read_service_locations(redis_db, service_name)\n mr_object = MR(service_name, resource, deployments)\n mr_allocation_list[mr_object] = mr_to_score[mr]\n \n return mr_allocation_list\n \n\n'''\nMachine Consumption index maps a particular VM (identified by IP address) to \nit's specific resource allocation: both in terms of the total maximal \ncapacity to the full amount\n'''\n\n# machine_cap is a dict that stores the machine's maximum capacity\n# machine_util is a tuple that stores the machine's current usage level\ndef write_machine_consumption(redis_db, machine_ip, machine_util):\n name = '{}machine_consumption'.format(machine_ip)\n for key in machine_util:\n redis_db.hset(name, key, machine_util[key])\n\ndef read_machine_consumption(redis_db, machine_ip):\n machine_util = {}\n name = '{}machine_consumption'.format(machine_ip)\n machine_consumption = redis_db.hgetall(name)\n\n for resource in machine_consumption:\n machine_consumption[resource] = float(machine_consumption[resource])\n return machine_consumption\n\ndef write_machine_capacity(redis_db, machine_ip, machine_cap):\n name = '{}machine_capacity'.format(machine_ip)\n for key in machine_cap:\n redis_db.hset(name, key, machine_cap[key])\n\ndef read_machine_capacity(redis_db, machine_ip):\n machine_cap = {}\n name = '{}machine_capacity'.format(machine_ip)\n \n machine_capacity = redis_db.hgetall(name)\n for resource in machine_capacity:\n machine_capacity[resource] = float(machine_capacity[resource])\n return machine_capacity\n\n\n \n\n","sub_path":"src/redis_resource.py","file_name":"redis_resource.py","file_ext":"py","file_size_in_byte":3082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"166907751","text":"#!/usr/bin/env python3\nimport sys, os\nfrom datetime import datetime\n\n# Donor database (use dictionary)\ndonors = {'Eleanor Shellstrop':[25.00, 57.00],\n 'Chidi Anagonye':[150.00, 300.00, 275.00],\n 'Tahani Al-Jamil':[2000.00,7500.00,12000.00],\n 'Jason Mendoza':[15.00,40.00,60.00],\n 'Mindy St. Claire':[500.00]}\n\n# Main program prompt\nprompt = '\\n'.join(['','Welcome to The Good Place charity donor database.',\n 'Please select from the following options:',\n '1 - Send a Thank You',\n '2 - Create a Report',\n '3 - Send letters to all donors',\n '4 - Exit Program',\n '','Input > '])\n\ndef get_donors(donors):\n return list(donors)\n\ndef update_donor(name,amount):\n donations = donors.get(name,[])\n donations.append(amount)\n donors[name] = donations\n\ndef generate_email(donor_name, donation_amount, total_amount):\n email_dict = {'donor_name':donor_name, 'donation_amount':donation_amount, 'total_amount':total_amount}\n # Create formatted email that can be copied & pasted\n email = ('\\n'.join(['Dear {donor_name},','',\n 'Thank you for your generous donation of ${donation_amount:.2f}.',\n 'To date, you have donated a total of ${total_amount:.2f} to our charity.',\n 'Your contributions help new arrivals receive the highest quality care possible.',\n 'Please know that your donations make a world of difference!',\n '','Sincerely,','The Good Place Team'])).format(**email_dict)\n return(email)\n\ndef write_thank_you(donor_name=None):\n # Add donation for new or existing donor and compose 'Thank You' message.\n # Donor name can be specified in case re-calling after invalid donation amount.\n while True:\n print()\n # Prompt for name if not specified\n if not donor_name:\n name = input('Enter donor name (type \\'list\\' to see donors or \\'quit\\' to exit): ')\n else:\n name = donor_name\n if name == 'list': # List donors\n print('\\nCurrent list of donors:\\n')\n print('\\n'.join(get_donors(donors)))\n elif name == 'quit': # Return to main prompt\n return\n else: # Get donations for donors\n # Prompt for donation amount\n amount = input('Enter donation amount in dollars (type \\'quit\\' to exit): ')\n # If the user wants to bail mid-entry, remove the donor that was just\n # added (if they were new) and return to main prompt\n if amount == 'quit':\n return\n else: # Otherwise, convert donation amount to float\n # Capture error if 'amount' not convertable\n try:\n amount = float(amount)\n except ValueError:\n print('Invalid amount, please enter a numeric value.')\n # Re-call function with current name to re-prompt for amount\n write_thank_you(donor_name=name)\n # Need return statement here after return from recursive call\n return\n else:\n if amount <= 0:\n print('Invalid amount, please enter a positive value.')\n # Re-call function with current name to re-prompt for amount\n write_thank_you(donor_name=name)\n # Need return statement here after return from recursive call\n return\n # Update donor information\n update_donor(name,amount)\n # Generate & print email to screen, return to main program\n email = generate_email(name, amount, sum(donors[name]))\n print(email)\n # Need return statement here, otherwise while loop will repeat\n return\n\ndef donor_key(donor):\n # Donor is a tuple of the form (name, total donation, number of donations, average donation)\n # Sort by total donation\n return donor[1]\n\ndef generate_report_data():\n # Declare and populate lists for report data\n total_donation, num_donation, avg_donation = [], [], []\n # Use single for loop instead of three separate comprehensions\n for donor,donations in donors.items():\n total_donation.append(sum(donations))\n num_donation.append(len(donations))\n avg_donation.append(total_donation[-1]/num_donation[-1])\n report = list(zip(donors.keys(), total_donation, num_donation, avg_donation))\n # Sorty by total donation, descending\n report.sort(key=donor_key, reverse=True)\n return report\n\ndef print_formatted_report(report):\n # Generate formatted report to be printed\n # Input 'report' is expected to be a list of lists with\n # [donor name, total donation, number of donations, average donation]\n formatted_report = ['',\n 'Donor Name | Total Donation | Num Donations | Avg Donation |',\n '-------------------------------------------------------------------------------']\n for donor in report:\n donor_name, total, number, average = donor\n formatted_report.append(f'{donor_name:<30} ${total:>14.2f} {number:14d} ${average:>12.2f}')\n formatted_report.append('')\n print('\\n'.join(formatted_report))\n\ndef create_report():\n # Generate, format, and print report data\n report = generate_report_data()\n print_formatted_report(report)\n\ndef create_directory(target):\n # Create directory if it does not exist within current directory\n try:\n os.makedirs(target)\n success = True\n except OSError:\n # If directory exists but error thrown, most likely accessibility issue\n if os.path.exists(target):\n print('Writing to existing directory.')\n success = True\n else:\n print('Error creating folder \\'{}\\'. Check directory write permissions.'.format(target))\n success = False\n return success\n\ndef write_letters(target):\n # Format current date to add as timestamp\n date = datetime.today().strftime('%Y-%m-%d')\n for donor, donation in donors.items():\n print('Writing letter to {}'.format(donor))\n # Generate email with donor name, last donation amount, and total donation amount\n email = generate_email(donor,donation[-1],sum(donation))\n # Create file with donor name and timestamp\n filename = '{}/{}_{}.txt'.format(target, donor.replace(' ','_'), date)\n try:\n with open(filename,'w') as f:\n f.write(email)\n except OSError: # Catch file write errors.\n print('Error writing file. Check directory write permissions.')\n\ndef send_letters():\n # Prompt for directory to write to\n target = input('Enter directory to put letters > ')\n if create_directory(target):\n write_letters(target)\n\ndef exit_program():\n print('Exiting program...')\n sys.exit()\n\ndef main():\n response_dict = {'1':write_thank_you,'2':create_report,'3':send_letters,'4':exit_program}\n # Main function, repeatedly display prompt and react based on user input\n while True:\n try:\n response_dict[input(prompt)]()\n except KeyError:\n print('Not a valid option! Please try again.')\n\nif __name__ == \"__main__\":\n # Driver for main function\n main()\n","sub_path":"students/gregdevore/lesson06/mailroom.py","file_name":"mailroom.py","file_ext":"py","file_size_in_byte":7305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"340460416","text":"from st2common.runners.base_action import Action\nfrom mam.sdk import entitytype\n\nfrom oslo_config import cfg\n\n__all__ = [\"IngestCsvDataAction\"]\n\n\nclass IngestCsvDataAction(Action):\n def __init__(self, config):\n super(IngestCsvDataAction, self).__init__(config)\n self._config = self.config\n self._credentials = self._config.get('credentials', None)\n system_packs_base_path = cfg.CONF.content.system_packs_base_path\n path_of_pack = system_packs_base_path + '/monitor_ingest'\n self._data_file_path = path_of_pack + '/etc/clean_data_output/' \\\n 'clean_data.csv'\n # self._data_file_path = '/opt/stackstorm/packs/monitor_ingest/etc/' \\\n # 'clean_data_output/clean_data.csv'\n self._entity_name = self._config.get('entity_name', None)\n\n if not self._config:\n raise ValueError('Missing config yaml')\n if not self._credentials:\n raise ValueError('Missing IBM Watson IoT credentials in config file')\n if not self._data_file_path:\n raise ValueError('Missing CSV data file path in config file')\n if not self._entity_name:\n raise ValueError('Missing Entity name in config file')\n\n def run(self):\n success = False\n if self._data_file_path:\n \"\"\"-------Usage: 1. (X) Load Csv Data - using a CSV payload-------\"\"\"\n try:\n entitytype.load_metrics_data_from_csv(self._entity_name,\n self._data_file_path,\n credentials=self._credentials)\n success = True\n except Exception as msg:\n self.logger.info(f\"FAILED STEP: {msg}\\nFailed loading CSV data\")\n return success\n","sub_path":"monitor_ingest/actions/data_ingest.py","file_name":"data_ingest.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"530754905","text":"#from StateFunctions import *\r\nfrom constants import *\r\nfrom BadDb import *\r\n\r\n\r\nclass State:\r\n #states are not added to DB automatically! must use writeState to add, and also use it after updates.\r\n def __init__(self,id,incomingStates={0},response=\"Undefined\",words={},origin=\"\",special=\"Null\"):\r\n self.id = id #int\r\n self.words = words #{\"word1\":#Hits,\"word2\":#Hits,...,\"wordN\":#Hits}\r\n self.incomingStates = incomingStates #{12,134,86}\r\n self.origin = origin #original sentance that created this state \"get me the password to 34\"\r\n self.response = response #\"this is the message you should respond\"\r\n self.special = special #::\r\n\r\n def __repr__(self):\r\n return \"ID: \"+str(self.id)+\"; Response: \"+self.response+\"; Origin Sentance:\"+self.origin+\" special: \"+self.special\r\n\r\n def printFullState(self):\r\n print(\"ID: \"+str(self.id)+\"; Response: \"+self.response+\"; Origin Sentance:\"+self.origin+\";\\n Words:\"+str(self.words)+\"\\n Incoming State:\"+str(self.incomingStates))+\"\\n Special:\"+str(self.special)\r\n\r\n def updateStateResponse(self,response):\r\n print(\"response changed from: \",self.response,\" to:\",response)\r\n self.response = response\r\n\r\n def updateStateIncoming(self,state_id):\r\n # print(\"added or updated incoming state:\",state_id,\" to state: \",self.id)\r\n self.incomingStates.add(state_id)\r\n\r\n def updateStateSpecial(self,special):\r\n # print(\"added or updated incoming state:\",state_id,\" to state: \",self.id)\r\n self.special = special\r\n\r\n def updateStateWords(self,words):\r\n # print(\"---debug updating words---\") #debug\r\n # print(\"adding words: \",words) #debug\r\n # print(\"debug, current words: \",self.words) #debug\r\n words = words.split(\" \")\r\n for word in words:\r\n word.replace(\" \",\"\")\r\n if \"\" in words:\r\n words.remove(\"\")\r\n # print(\"new words: \", words) # debug\r\n for word in words:\r\n if self.words.get(word) != None: #word exists\r\n if word not in limited:\r\n self.words[word] += 1\r\n elif self.words[word] < limited[word]:\r\n self.words[word] += 1\r\n else: #create new key\r\n self.words[word] = 1\r\n # print(\"updated: \",self.words) #debug\r\n # print(\"-------------------------\") #debug","sub_path":"StateType.py","file_name":"StateType.py","file_ext":"py","file_size_in_byte":2427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"457990893","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('core', '0007_auto_20160208_0941'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='focalsitedata',\n name='count',\n ),\n migrations.AddField(\n model_name='focalsitedata',\n name='abundance',\n field=models.IntegerField(default=1, help_text='Absolute abundance'),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='focalsite',\n name='sensitive',\n field=models.BooleanField(default=False, help_text='If the focal site concerns sensitive species and should not be visible to the public, select this.'),\n ),\n migrations.AlterField(\n model_name='focalsitedata',\n name='activity',\n field=models.CharField(choices=[('CDP', 'courtship display'), ('CAN', 'adult bird carrying nesting material'), ('ANB', 'active nest building'), ('NCN', 'newly completed nest'), ('NWE', 'nest with eggs'), ('NWC', 'nest with chicks'), ('PFY', 'parents feeding young in nest'), ('PFS', 'parents with fecal sac'), ('PAY', 'parents and young not in nest')], help_text='Activity (only
applicable to birds)', blank=True, null=True, max_length=3),\n ),\n migrations.AlterField(\n model_name='focalsitedata',\n name='life_stage',\n field=models.CharField(default='A', help_text='Specify life stage', choices=[('C', 'Chick/pup'), ('J', 'Juvenile'), ('A', 'Adult')], max_length=1),\n ),\n migrations.AlterField(\n model_name='focalsitedata',\n name='observed',\n field=models.DateTimeField(help_text='Date
observed'),\n ),\n ]\n","sub_path":"core/migrations/0008_auto_20160208_1552.py","file_name":"0008_auto_20160208_1552.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"420934004","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import render\n\n\nfrom backend import create_idno_tmp, create_idno, create_bankcard\n# Create your views here.\n\n\ndef create_id_no(requets):\n '''\n 生成身份证号\n :param requets:\n :return:\n '''\n if requets.method == 'GET':\n return render(requets, 'test_util/id_no.html')\n elif requets.method == 'POST':\n birthday = requets.POST['birthday']\n idno_tmp = create_idno_tmp(birthday)\n idno = create_idno(idno_tmp)\n bankcard_no = create_bankcard()\n context = {\n 'bankcard_no': bankcard_no,\n 'idno': idno\n }\n return render(requets, 'test_util/id_no.html', context)","sub_path":"app/test_util/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"168546426","text":"import requests\n\nfrom keycloak_scanner.custom_logging import verbose, info\nfrom keycloak_scanner.properties import add_kv\nfrom keycloak_scanner.scan import Scan\n\nURL_PATTERN = '{}/auth/realms/{}/.well-known/openid-configuration'\n\n\nclass WellKnownScan(Scan):\n\n def perform(self, launch_properties, scan_properties):\n realms = scan_properties['realms'].keys()\n for realm in realms:\n base_url = launch_properties['base_url']\n url = URL_PATTERN.format(base_url, realm)\n r = requests.get(url)\n if r.status_code != 200:\n verbose('Bad status code for realm {} {}: {}'.format(realm, url, r.status_code))\n else:\n info('Find a well known for realm {} {}'.format(realm, url))\n add_kv(scan_properties, 'wellknowns', realm, r.json())\n","sub_path":"keycloak_scanner/well_known_scanner.py","file_name":"well_known_scanner.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"65086198","text":"import sys\nimport numpy as np\n\nnp.random.seed(0)\n\nfrom keras.layers import Input, Dense, Lambda, Layer\nfrom keras.initializers import Constant\nfrom keras.models import Model\nfrom keras import backend as K\nfrom multi_task_custom_layer import CustomMultiLossLayer\n\nN = 100\nnb_epoch = 2000\nbatch_size = 20\nnb_features = 1024\nQ = 1\nD1 = 1 # first output\nD2 = 1 # second output\n\ndef gen_data(N):\n X = np.random.randn(N, Q)\n w1 = 2.\n b1 = 8.\n sigma1 = 1e1 # ground truth\n Y1 = X.dot(w1) + b1 + sigma1 * np.random.randn(N, D1)\n w2 = 3\n b2 = 3.\n sigma2 = 1e0 # ground truth\n Y2 = X.dot(w2) + b2 + sigma2 * np.random.randn(N, D2)\n return X, Y1, Y2\n\nimport pylab\nfrom pylab import hist\n#\n# from IPython import get_ipython\n# get_ipython().run_line_magic('matplotlib', 'inline')\n\n# %matplotlib inline\n\nX, Y1, Y2 = gen_data(N)\npylab.figure(figsize=(3, 1.5))\npylab.scatter(X[:, 0], Y1[:, 0])\npylab.scatter(X[:, 0], Y2[:, 0])\npylab.show()\n\n\ndef get_prediction_model():\n inp = Input(shape=(Q,), name='inp')\n x = Dense(nb_features, activation='relu')(inp)\n y1_pred = Dense(D1)(x)\n y2_pred = Dense(D2)(x)\n return Model(inp, [y1_pred, y2_pred])\n\ndef get_trainable_model(prediction_model):\n inp = Input(shape=(Q,), name='inp')\n y1_pred, y2_pred = prediction_model(inp)\n y1_true = Input(shape=(D1,), name='y1_true')\n y2_true = Input(shape=(D2,), name='y2_true')\n out = CustomMultiLossLayer(nb_outputs=2)([y1_true, y2_true, y1_pred, y2_pred])\n return Model([inp, y1_true, y2_true], out)\n\n\nprediction_model = get_prediction_model()\ntrainable_model = get_trainable_model(prediction_model)\ntrainable_model.compile(optimizer='adam', loss=None)\nassert len(trainable_model.layers[-1].trainable_weights) == 2 # two log_vars, one for each output\nassert len(trainable_model.losses) == 1\n\n\n# pylab.plot(hist.history['loss'])\n\n# Found standard deviations (ground truth is 10 and 1):\n[np.exp(K.get_value(log_var[0]))**0.5 for log_var in trainable_model.layers[-1].log_vars]","sub_path":"mtl_custom.py","file_name":"mtl_custom.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"441683291","text":"__author__ = 'AJ'\nimport csv, os\ndef qualitycontrol(sci_metadata, dark_metadata):\n '''\n Filters images that have an AOLOOPST as CLOSED and DARK Images with a Shutter that is open\n :param sci_metadata: output from parse and report.sh\n :param dark_metadata: output from parse and report.sh\n :return none\n '''\n\n with open(sci_metadata, 'rb') as infile:\n data = csv.reader(infile, delimiter='\\t')\n data_list = []\n header = next(data)\n data_list.append(header)\n for row in data:\n if row[5] == \"SCIENCE\" and row[8] == \"CLOSED\":\n data_list.append(row)\n\n infile.close()\n os.remove(\"sci_metadata.tsv\")\n\n with open(\"sci_metadata.tsv\", \"wb\") as f:\n writer = csv.writer(f, lineterminator=\"\\n\", delimiter='\\t')\n for elem in data_list:\n writer.writerow(elem)\n f.close()\n\n with open(dark_metadata, 'rb') as ifl:\n data = csv.reader(ifl, delimiter='\\t')\n data_list = []\n header = next(data)\n data_list.append(header)\n for row in data:\n if row[5] == \"DARK\" and row[7] == \"SHUT\":\n data_list.append(row)\n\n infile.close()\n os.remove(\"dark_metadata.tsv\")\n\n with open(\"dark_metadata.tsv\", \"wb\") as f:\n writer = csv.writer(f, lineterminator=\"\\n\", delimiter='\\t')\n for elem in data_list:\n writer.writerow(elem)\n f.close()\n\n\nqualitycontrol(\"sci_metadata.tsv\", \"dark_metadata.tsv\")\n","sub_path":"python/qualityControl.py","file_name":"qualityControl.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"370201859","text":"import datetime\nfrom datetime import time\nimport secrets\nimport os\nfrom PIL import Image\nfrom flask import request\nfrom flaskapp import app, db\nfrom flask_sqlalchemy import BaseQuery\nfrom flaskapp.models import User, Ban_list\nfrom flask_login import current_user\n\nnow = datetime.datetime.now()\nnow_date = now.strftime(\"%d-%m-%Y\")\nnow_time = now.strftime(\"%H:%M:%S\")\n\ndef log(e, loc, id0):\n try:\n log_text = []\n log_text.append(e)\n log_text.append(loc)\n log_text.append(now_date)\n log_text.append(now_time)\n log_text.append(id0)\n\n with open(\"flaskapp/logs/log.txt\", \"a+\") as output:\n output.writelines(str(log_text))\n output.writelines(\"\\n\")\n\n except Exception as e:\n print(\"Error at \", e)\n log(e, request.path, current_user.id)\n\ndef bugs(name, id0, text):\n try:\n bug_text = []\n bug_text.append(name)\n bug_text.append(id0)\n bug_text.append(text)\n bug_text.append(now_date)\n bug_text.append(now_time)\n\n with open(\"flaskapp/logs/bugs.txt\", \"a+\") as output:\n output.writelines(str(bug_text))\n output.writelines(\"\\n\")\n\n except Exception as e:\n print(\"Error at \", e)\n log(e, request.path, current_user.id)\n\ndef ban_user(id0, time):\n try:\n ban = Ban_list(user_id=id0, time=time)\n db.session.add(ban)\n db.session.commit()\n\n except Exception as e:\n print(\"Error at \", e)\n log(e, request.path, current_user.id)\n\ndef check_ban_list():\n try:\n len_ban_list = len(Ban_list.query.order_by(Ban_list.ban_id).all()) + 1\n\n for x in range(1, len_ban_list):\n ban_list = Ban_list.query.filter_by(ban_id=x).first()\n if not ban_list == None:\n print(ban_list)\n ban_list_name = ban_list.user_id\n ban_list_time = ban_list.time\n\n if not ban_list_time == \"Infinite\":\n ban_list_time = int(ban_list_time) - 1\n if ban_list_time == 0:\n db.session.delete(ban_list)\n db.session.commit()\n else:\n db.session.delete(ban_list)\n Ban = Ban_list(ban_id = x, user_id=ban_list_name, time=ban_list_time)\n\n db.session.add(Ban)\n db.session.commit()\n\n ban_list = Ban_list.query.filter_by(ban_id=x).first() \n\n except Exception as e:\n print(\"Error at \", e)\n log(e, request.path, current_user.id) \n \ndef save_picture(form_picture):\n try:\n random_hex = secrets.token_hex(8)\n _, f_ext = os.path.splitext(form_picture.filename)\n picture_fn = random_hex + f_ext\n picture_path = os.path.join(app.root_path, 'static/profile_pics', picture_fn)\n\n output_size = (1920, 1080)\n i = Image.open(form_picture)\n i.thumbnail(output_size)\n i.save(picture_path)\n\n return picture_fn\n \n except Exception as e:\n print(\"Error at \", e)\n log(e, request.path, current_user.id)","sub_path":"flaskapp/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":3149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"616061874","text":"from stellar_sdk import Asset\nfrom stellar_sdk.call_builder.call_builder_sync import OffersCallBuilder\nfrom tests.call_builder.call_builder_sync import client, horizon_url\n\n\nclass TestOffersCallBuilder:\n def test_init(self):\n builder = OffersCallBuilder(horizon_url, client)\n assert builder.endpoint == \"offers\"\n assert builder.params == {}\n\n def test_for_offer(self):\n offer_id = \"1000\"\n builder = OffersCallBuilder(horizon_url, client)\n builder.offer(offer_id)\n assert builder.endpoint == \"offers/{offer_id}\".format(offer_id=offer_id)\n assert builder.params == {}\n\n def test_for_asset(self):\n selling = Asset(\n \"BTC\", \"GATEMHCCKCY67ZUCKTROYN24ZYT5GK4EQZ65JJLDHKHRUZI3EUEKMTCH\"\n )\n buying = Asset.native()\n builder = OffersCallBuilder(horizon_url, client)\n builder.for_selling(selling)\n builder.for_buying(buying)\n assert builder.endpoint == \"offers\"\n assert builder.params == {\n \"selling_asset_type\": selling.type,\n \"selling_asset_code\": selling.code,\n \"selling_asset_issuer\": selling.issuer,\n \"buying_asset_type\": buying.type,\n }\n\n def test_for_seller(self):\n seller = \"GATEMHCCKCY67ZUCKTROYN24ZYT5GK4EQZ65JJLDHKHRUZI3EUEKMTCH\"\n selling = Asset(\n \"BTC\", \"GATEMHCCKCY67ZUCKTROYN24ZYT5GK4EQZ65JJLDHKHRUZI3EUEKMTCH\"\n )\n buying = Asset.native()\n builder = OffersCallBuilder(horizon_url, client)\n builder.for_seller(seller)\n builder.for_selling(selling)\n builder.for_buying(buying)\n assert builder.endpoint == \"offers\"\n assert builder.params == {\n \"seller\": seller,\n \"selling_asset_type\": selling.type,\n \"selling_asset_code\": selling.code,\n \"selling_asset_issuer\": selling.issuer,\n \"buying_asset_type\": buying.type,\n }\n\n def test_for_sponsor(self):\n sponsor = \"GAEDTJ4PPEFVW5XV2S7LUXBEHNQMX5Q2GM562RJGOQG7GVCE5H3HIB4V\"\n builder = OffersCallBuilder(horizon_url, client).for_sponsor(sponsor)\n assert builder.endpoint == \"offers\"\n assert builder.params == {\"sponsor\": sponsor}\n\n def test_for_account(self):\n account_id = \"GATEMHCCKCY67ZUCKTROYN24ZYT5GK4EQZ65JJLDHKHRUZI3EUEKMTCH\"\n builder = OffersCallBuilder(horizon_url, client).for_account(account_id)\n assert builder.endpoint == \"accounts/{account_id}/offers\".format(\n account_id=account_id\n )\n assert builder.params == {}\n","sub_path":"tests/call_builder/call_builder_sync/test_offers_call_builder.py","file_name":"test_offers_call_builder.py","file_ext":"py","file_size_in_byte":2580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"283589577","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# filebrowser.py\n# \n# Copyright 2018 Coumes Quentin\n# \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA.\n# \n#\n\n\nimport os, copy\n\nfrom os.path import abspath, join\n\nfrom django.conf import settings\n\nfrom filebrowser.filebrowser_option import ENTRY_OPTIONS, DIRECTORY_OPTIONS, READ, WRITE\nfrom filebrowser.models import Directory\n\n\n\nclass Filebrowser:\n \"\"\"Filebrowser allowing to browse through a file tree.\n \n Attributes:\n root (str): Absolute path to the root of the filebrowser.\n relative (str): relative path from self.root of the current position of the filebrowser\n directory (Directory): The current directory, None if current position is self.root\n entry_options (FilebrowserOption): List of every options applicable to entries\n directory_options (FilebrowserOption): List of every options applicable to self.directory\n \"\"\"\n \n def __init__(self, request, path='home', root=None):\n real = path.split('/')\n if real[0] == \"home\":\n real[0] = str(request.user.id)\n \n self.root = settings.FILEBROWSER_ROOT if not root else root\n self.relative = path\n self._real_relative = join(*real)\n self.home = path.split('/')[0]\n self.real_home = real[0]\n self.entry_options = copy.deepcopy(ENTRY_OPTIONS)\n self.directory_options = copy.deepcopy(DIRECTORY_OPTIONS)\n self.directory = Directory.objects.get(name=self._real_relative.split('/')[0])\n self.entries, self.length_max = self.list()\n \n \n def _filter_category_options(self, category, request):\n \n for group_key, group in category.groups.items():\n filtered_options = {}\n \n for option_key, option in group.options.items():\n if option.right == READ and self.directory.can_read(request.user):\n filtered_options[option_key] = option\n elif option.right == WRITE and self.directory.can_write(request.user):\n filtered_options[option_key] = option\n \n category.groups[group_key].options = filtered_options\n \n cleaned = {}\n for group_key, group in category.groups.items(): # removing empty group\n if group.options:\n cleaned[group_key] = group\n category.groups = cleaned\n \n return category\n \n \n def load_options(self, request):\n self.entry_options = self._filter_category_options(self.entry_options, request)\n self.directory_options = self._filter_category_options(self.directory_options, request)\n \n \n def full_path(self):\n \"\"\"Return the absolute path of the current position of the filebrowser.\"\"\"\n return abspath(os.path.join(self.root, self._real_relative))\n \n \n def breadcrumb(self):\n \"\"\"Return the breadcrumb corresponding to the current position o the filebrowser\"\"\"\n path = self.home\n bc = [{'name': path, 'link': path}]\n for elem in [i for i in self._real_relative.split('/') if i][1:]:\n bc.append({'name': elem, 'link': join(path, elem)})\n path = join(path, elem)\n \n return bc\n \n \n def list_root(self):\n \"\"\" Return the list of every entry of FILEBROWSER_ROOT.\"\"\"\n return ['home'] + [r for r in os.listdir(settings.FILEBROWSER_ROOT) if not r.isdigit()]\n \n \n def list(self):\n \"\"\"Return a list of tuple (entry, max_with) where entry correspond to every\n entry at the current possition of the filebrowser.\"\"\"\n entries = []\n for rootdir, dirs, files in os.walk(self.full_path()):\n entries += sorted(\n [{'name': elem, 'path': rootdir+'/'+elem} for elem in dirs],\n key=lambda k: k['name']\n )\n entries += sorted(\n [{'name': elem, 'path': rootdir+'/'+elem} for elem in files],\n key=lambda k: k['name']\n )\n break\n\n max_width = 0\n if entries:\n max_width = len(max(entries, key=lambda i: len(i['name']))['name']) + 12\n return entries, max_width\n \n \n \n \n\n\n","sub_path":"server/serverpl/filebrowser/filebrowser.py","file_name":"filebrowser.py","file_ext":"py","file_size_in_byte":4913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"425584856","text":"#!/usr/bin/env python3\r\n\r\nimport os, sys\r\nfrom itertools import chain\r\nfrom glob import iglob\r\n\r\nsv_exports = []\r\n\r\nmod_dir = sys.argv[1]\r\nsv_dir = mod_dir + \"/dlls\"\r\n\r\ndef dedup(seq):\r\n seen = set()\r\n seen_add = seen.add\r\n return [x for x in seq if not (x in seen or seen_add(x))]\r\n\r\ndef get_exports(explist, f, fname):\r\n lnum = 1\r\n for line in f:\r\n line = line.strip()\r\n exp = ''\r\n if line.startswith('LINK_ENTITY_TO_CLASS'):\r\n exp = line[len('LINK_ENTITY_TO_CLASS'):].strip()\r\n elif 'LINK_ENTITY_TO_CLASS' in line:\r\n print(fname + ':' + str(lnum) + ': bogus export? ', line)\r\n continue\r\n else:\r\n continue\r\n expl = exp[1:].split(',')\r\n if len(expl) == 0:\r\n print(fname + ':' + str(lnum) + ': bogus export? ', line)\r\n continue\r\n exp = expl[0].strip()\r\n explist.append(exp)\r\n lnum += 1\r\n\r\nsv_files = chain(\r\n iglob(sv_dir + '/**/*.cpp', recursive=True),\r\n iglob(sv_dir + '/**/*.c', recursive=True),\r\n iglob(sv_dir + '/**/*.h', recursive=True)\r\n)\r\n\r\nfor fname in sv_files:\r\n with open(fname, errors='replace') as f:\r\n get_exports(sv_exports, f, fname)\r\ndedup(sv_exports)\r\n\r\nfor exp in sv_exports:\r\n print('void ' + exp + '( entvars_t *pev );')\r\n\r\nfor exp in sv_exports:\r\n print('{ \"' + exp + '\", (void*)' + exp + ' },')\r\n","sub_path":"utils/vita/genentexports.py","file_name":"genentexports.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"65539056","text":"from ftw.builder import Builder\nfrom ftw.builder import create\nfrom opengever.testing import FunctionalTestCase\nfrom plone.locking.interfaces import IRefreshableLockable\nfrom zExceptions import Unauthorized\n\n\nclass TestDocumentQuickupload(FunctionalTestCase):\n\n def setUp(self):\n super(TestDocumentQuickupload, self).setUp()\n self.dossier = create(Builder('dossier'))\n self.document = create(Builder('document')\n .titled('Anfrage Herr Meier')\n .checked_out()\n .attach_file_containing('OLD DATA')\n .within(self.dossier))\n\n def test_raises_unauthorized_when_document_is_not_checked_out(self):\n document = create(Builder('document'))\n with self.assertRaises(Unauthorized):\n create(Builder('quickuploaded_document')\n .within(document)\n .with_data('text'))\n\n def test_raises_unauthorized_when_document_is_locked(self):\n IRefreshableLockable(self.document).lock()\n\n with self.assertRaises(Unauthorized):\n create(Builder('quickuploaded_document')\n .within(self.document)\n .with_data('text'))\n\n def test_file_is_updated(self):\n create(Builder('quickuploaded_document')\n .within(self.document)\n .with_data('NEW DATA'))\n\n self.assertEquals('NEW DATA', self.document.file.data)\n\n def test_uses_existing_filename_but_new_extension(self):\n create(Builder('quickuploaded_document')\n .within(self.document)\n .with_data('NEW DATA', filename='test.pdf'))\n\n self.assertEquals('anfrage-herr-meier.pdf',\n self.document.file.filename)\n","sub_path":"opengever/document/tests/test_quickupload.py","file_name":"test_quickupload.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"200382980","text":"from dsbox.template.template import DSBoxTemplate \nfrom d3m.metadata.problem import TaskKeyword \nfrom dsbox.template.template_steps import TemplateSteps \nfrom dsbox.schema import SpecializedProblem \nimport typing \nimport numpy as np # type: ignore \nclass LupiSvmClassification(DSBoxTemplate):\n def __init__(self):\n DSBoxTemplate.__init__(self)\n self.template = {\n \"name\": \"LupiSvmClassification\",\n \"taskType\": {TaskKeyword.CLASSIFICATION.name},\n \"taskSubtype\": {TaskKeyword.BINARY.name, TaskKeyword.MULTICLASS.name},\n \"inputType\": {\"table\"},\n \"specializedProblem\": {SpecializedProblem.PRIVILEGED_INFORMATION},\n \"output\": \"prediction_step\",\n \"steps\": [\n {\n \"name\": \"to_dataframe_step\",\n \"primitives\": [\"d3m.primitives.data_transformation.dataset_to_dataframe.Common\"],\n \"inputs\": [\"template_input\"]\n },\n {\n \"name\": \"common_profiler_step\",\n \"primitives\": [\"d3m.primitives.schema_discovery.profiler.Common\"],\n \"inputs\": [\"to_dataframe_step\"]\n },\n {\n \"name\": \"model_step\",\n \"primitives\": [{\n \"primitive\": \"d3m.primitives.classification.lupi_svm.LupiSvmClassifier\",\n \"hyperparameters\": {\n \"C\": [1],\n \"C_gridsearch\": [(-4.0, 26.0, 0.3)],\n \"add_index_columns\": [False],\n \"class_weight\": ['balanced'],\n \"coef0\": [0],\n \"degree\": [3],\n \"gamma\": [\"auto\"],\n \"gamma_gridsearch\": [(-4.0, 26.0, 0.3)],\n \"kernel\": [\"rbf\"],\n \"max_iter\": [-1],\n \"n_jobs\": [4],\n \"probability\": [False],\n \"return_result\": [\"new\"],\n \"shrinking\": [True],\n \"tol\": [0.001],\n \"use_semantic_types\": [False],\n }\n },\n ],\n \"inputs\": [\"common_profiler_step\"]\n },\n {\n \"name\": \"prediction_step\",\n \"primitives\": [\"d3m.primitives.data_transformation.construct_predictions.Common\"],\n \"inputs\": [\"model_step\", \"common_profiler_step\"]\n }\n\n ]\n }\n\n","sub_path":"python/dsbox/template/template_files/not_loaded/LupiSvmClassification.py","file_name":"LupiSvmClassification.py","file_ext":"py","file_size_in_byte":2693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"202726542","text":" # should work even without -*-\n#\n# tiling.py\n# Alessio Burrello \n# Francesco Conti \n# Thorir Mar Ingolfsson \n#\n# Copyright (C) 2018-2020 University of Bologna\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\nimport math\nimport os\nimport sys\nfrom ortools.constraint_solver import pywrapcp\nfrom ortools.constraint_solver import solver_parameters_pb2\n\nclass Tiler_Add():\n # Class to generate the Tiling of the layer.\n def __init__(self,tiler):\n self.__dict__ = tiler.__dict__\n\n def get_tiling(self, level):\n # This function generate the layer function to be included in the project for the conv2d operations (Convolutions and Fully Connected layers).\n if level == 2:\n # L3 tiling\n tiling = self.get_tiling_Add_L2()\n return tiling\n print(\"Error: Either you should be in L3-L2 tiling or L2-L1 tiling\")\n os._exit(0)\n \n def get_tiling_Add_L2(self):\n # This function generate the layer function to be included in the project for the addition operation.\n ###############################################\n ##### PARAMETERS INITIALIZATION ###############\n ###############################################\n L1_memory = self.HW_node.HW_description[\"memory\"][\"L1\"][\"dimension\"]\n inp_dim = self.HW_node.tiling_dimensions[\"L2\"][\"input_dimensions\"][1:]\n out_dim = self.HW_node.tiling_dimensions[\"L2\"][\"output_dimensions\"][1:]\n out_ch = self.HW_node.tiling_dimensions[\"L2\"][\"output_dimensions\"][0]\n in_ch = self.HW_node.tiling_dimensions[\"L2\"][\"input_dimensions\"][0]\n ks = self.HW_node.kernel_shape\n s = self.HW_node.strides\n p = self.HW_node.pads\n\n ###############################################\n ##### L2 DIMENSIONS DEFINITION: EARLY EXIT ####\n ###############################################\n buffer_total = self.HW_node.tiling_dimensions[\"L2\"][\"constants_memory\"] + self.HW_node.tiling_dimensions[\"L2\"][\"input_activation_memory\"] * 2 + self.HW_node.tiling_dimensions[\"L2\"][\"output_activation_memory\"]\n # return immediatly if the memory fits the L1 \n previous_layer_tiles = 2\n if self.previous_HW_node.tiling_dimensions[\"L2\"][\"output_activation_memory\"] == self.previous_HW_node.tiling_dimensions[\"L1\"][\"output_activation_memory\"] and \\\n self.previous_HW_node.tiling_dimensions[\"L2\"][\"input_activation_memory\"] == self.previous_HW_node.tiling_dimensions[\"L1\"][\"input_activation_memory\"]:\n previous_layer_tiles = 1\n self.HW_node.previous_layer_tiles = previous_layer_tiles \n if buffer_total <= L1_memory:\n return ([], self.HW_node.tiling_dimensions[\"L2\"][\"input_dimensions\"] , self.HW_node.tiling_dimensions[\"L2\"][\"output_dimensions\"] )\n else:\n db = 2\n if previous_layer_tiles == 1:\n print(\"Error: Add can not be tiled since previous layer was not tiled\")\n os._exit(0)\n\n parameters = pywrapcp.Solver.DefaultSolverParameters()\n solver = pywrapcp.Solver(\"simple_CP\", parameters)\n\n # integer positive variables.\n tile_n = solver.IntVar(1, in_ch, 'tile_n')\n tile_h_in = solver.IntVar(ks[0], inp_dim[0], 'tile_h_in')\n tile_w_in = solver.IntVar(ks[1], inp_dim[1], 'tile_w_in')\n tile_h_out = solver.IntVar(1, out_dim[0], 'tile_h_out')\n tile_w_out = solver.IntVar(1, out_dim[1], 'tile_w_out')\n\n # scaling is used to ensure datasize is integer\n solver.Add(tile_h_out == tile_h_in)\n solver.Add(tile_w_out == tile_w_in) \n solver.Add(tile_n == in_ch)\n\n # CONSTRAINTS: managing of correct dimensions (no decimal h_out and any\n # type of rounding)\n input_tile_dimension = (db * in_ch * tile_h_in * inp_dim[1] * self.HW_node.input_activation_bits + 7 ) // 8 # the 7 is to account for bit precision of 1, which still occupy an entire byte\n output_tile_dimension = (db * out_ch * tile_h_out * out_dim[1] * self.HW_node.output_activation_bits + 7 ) // 8 # the 7 is to account for bit precision of 1, which still occupy an entire byte\n constraint_all = input_tile_dimension * 2 + output_tile_dimension\n solver.Add(constraint_all <= L1_memory)\n # objective\n obj_expr = solver.IntVar(0, 1000000000000, \"obj_expr\")\n solver.Add(obj_expr == 1000000 * constraint_all\n + 10 * tile_w_in\n + 1 * tile_h_in\n + 1000 * tile_n)\n objective = solver.Maximize(obj_expr, 1)\n\n decision_builder = solver.Phase([tile_n, tile_h_in, tile_w_in, tile_h_out, tile_w_out],\n solver.CHOOSE_FIRST_UNBOUND,\n solver.ASSIGN_MIN_VALUE)\n\n # Create a solution collector.\n collector = solver.LastSolutionCollector()\n # Add the decision variables.\n collector.Add(tile_n)\n collector.Add(tile_h_in)\n collector.Add(tile_w_in)\n collector.Add(tile_h_out)\n collector.Add(tile_w_out)\n # Add the objective.\n collector.AddObjective(obj_expr)\n\n solver.Solve(decision_builder, [objective, collector])\n if collector.SolutionCount() > 0:\n best_solution = collector.SolutionCount() - 1\n tile_n = collector.Value(best_solution, tile_n)\n tile_h_in = collector.Value(best_solution, tile_h_in)\n tile_w_in = collector.Value(best_solution, tile_w_in)\n tile_h_out = collector.Value(best_solution, tile_h_out)\n tile_w_out = collector.Value(best_solution, tile_w_out)\n return ([], [tile_n, tile_h_in, tile_w_in], [tile_n, tile_h_out, tile_w_out])\n print(\" Add ERROR: no tiling found. Exiting...\")\n os._exit(0)\n return None\n","sub_path":"dory/Hardware_targets/Diana/Diana_SoC/Tiler/tiler_add.py","file_name":"tiler_add.py","file_ext":"py","file_size_in_byte":6434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"646789378","text":"'''\nSerialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.\n\nDesign an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.\n\nExample: \n\nYou may serialize the following tree:\n\n 1\n / \\\n 2 3\n / \\\n 4 5\n\nas \"[1,2,3,null,null,4,5]\"\nClarification: The above format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.\n\nNote: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.\n'''\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\n\nfrom collections import deque\n\nclass Codec:\n\n def serialize(self, root):\n string_builder = self.rserialize(root, [])\n \n return \",\".join(string_builder)\n \n def rserialize(self, node, string_builder):\n if not node:\n string_builder.append(\"None\")\n else:\n string_builder.append(str(node.val))\n string_builder = self.rserialize(node.left, string_builder)\n string_builder = self.rserialize(node.right, string_builder)\n \n return string_builder\n \n\n def deserialize(self, data):\n dataList = deque(data.split(','))\n return self.rdeserialize(dataList)\n \n def rdeserialize(self, dataList):\n if dataList[0] == 'None':\n dataList.popleft()\n return None\n root = TreeNode(dataList.popleft())\n root.left = self.rdeserialize(dataList)\n root.right = self.rdeserialize(dataList)\n \n return root \n\n# Your Codec object will be instantiated and called as such:\n# codec = Codec()\n# codec.deserialize(codec.serialize(root))\n\n","sub_path":"problems/297_serialize_and_deserialize_binary_tree.py","file_name":"297_serialize_and_deserialize_binary_tree.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"397818331","text":"# coding=utf-8\n__author__ = 'pythme'\n\n\"\"\"\n引用理解:计算机之所以能做很多自动化的任务,因为它可以自己做条件判断。\n\n 根据Python的缩进规则,如果if语句判断是True,就把缩进的两行print语句执行了,否则,什么也不做。\n 可以给if添加一个else语句,也可以用elif做更细致的判断,elif是else if的缩写,完全可以有多个elif\n 从上往下判断,如果在某个判断上是True,把该判断对应的语句执行后,就忽略掉剩下的判断语句。\n \n 完整形式语句\n if <条件判断1>:\n <执行1>\n elif <条件判断2>:\n <执行2>\n elif <条件判断3>:\n <执行3>\n else:\n <执行4>\n \n \n《if判断条件简写》\n 只要x是非零数值、非空字符串、非空list等,就判断为True,否则为False。\n if x:\n print('True')\n\n \n\"\"\"\n\n# coding=utf-8\nheight = float(input(\"请输入你的身高(cm): \"))\nweight = float(input(\"请输入你的体重(kg): \"))\n\nbmi = weight / height ** 2\n\nif bmi < 18.5:\n print(\"你的体重过轻\")\nelif 18.5 <= bmi <= 25:\n print(\"你的体重正常\")\nelif 25 <= bmi <= 28:\n print(\"你的体重过重\")\nelif 28 <= bmi <= 32:\n print(\"你的体重肥胖\")\nelse:\n print(\"你的体重严重肥胖\")\n","sub_path":"2_Python基础/4_条件判断.py","file_name":"4_条件判断.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"176531375","text":"import os\nfrom XLNetNameData import create_mini_batch, NameDataset, NameDoc, tag2idx, tag2name\nimport torch\nfrom transformers import AutoModelForTokenClassification,AutoConfig\nfrom transformers import AutoTokenizer, AdamW\nimport itertools, operator\nimport torch.nn.functional as F\nfrom seqeval.metrics import classification_report,accuracy_score,f1_score\nfrom namefilter import all_english, namefilter\n\nroot = os.path.join('..', 'data')\n\ntrain = False\nEPOCHS = 8\nmodel_idx = 7\nCUDA_NUM = \"cuda:0\"\n\nPRETRAINED_MODEL_NAME = \"hfl/chinese-xlnet-base\"\n#PRETRAINED_MODEL_NAME = \"hfl/chinese-xlnet-mid\"\n#PRETRAINED_MODEL_NAME = \"clue/xlnet_chinese_large\"\nTrainFile = \"TrainXLNetExtract.csv\"\nValidFile = \"ValidXLNetExtract.csv\"\n\nif PRETRAINED_MODEL_NAME == \"hfl/chinese-xlnet-base\":\n ModelName = \"XLNetBaseExtractorModel{}\"\n BATCH_SIZE = 8\nelif PRETRAINED_MODEL_NAME == \"hfl/chinese-xlnet-mid\":\n #BATCH_SIZE = 3\n #ModelName = \"XLNetMidExtractorModel{}\"\n BATCH_SIZE = 2\n ModelName = \"XLNetMidB2ExtractorModel{}\"\nelif PRETRAINED_MODEL_NAME == \"clue/xlnet_chinese_large\":\n ModelName = \"XLNetLrgExtractorModel{}\"\n BATCH_SIZE = 1\nelse:\n print(\"wrong pretrain model name\")\n exit(1)\n\ndef get_predictions(model, dataloader,device):\n\n eval_loss, eval_accuracy = 0, 0\n nb_eval_steps, nb_eval_examples = 0, 0\n y_true = []\n y_pred = []\n\n model.eval()\n predictions, hit, miss, err, total = [], 0, 0, 0, 0\n with torch.no_grad():\n for _, *data in dataloader:\n if next(model.parameters()).is_cuda:\n data = [t.to(device) for t in data if t is not None]\n\n tokens_tensors, segments_tensors, masks_tensors, labels = data\n\n\n outputs = model(input_ids=tokens_tensors,\n token_type_ids=None,\n # token_type_ids=segments_tensors,\n attention_mask=masks_tensors)\n\n logits = outputs[0]\n\n logits = torch.argmax(F.log_softmax(logits,dim=2),dim=2)\n logits = logits.detach().cpu().numpy()\n\n # Get NER true result\n labels = labels.to('cpu').numpy()\n\n\n # Only predict the real word, mark=0, will not calculate\n masks_tensors = masks_tensors.to('cpu').numpy()\n\n # Compare the valuable predict result\n for i,mask in enumerate(masks_tensors):\n # Real one\n temp_1 = []\n # Predict one\n temp_2 = []\n\n for j, m in enumerate(mask):\n # Mark=0, meaning its a pad word, dont compare\n if m:\n if tag2name[labels[i][j]] != \"X\" \\\n and tag2name[labels[i][j]] != \"\" \\\n and tag2name[labels[i][j]] != \"\" : # Exclude the X label\n temp_1.append(tag2name[labels[i][j]])\n temp_2.append(tag2name[logits[i][j]])\n else:\n break\n\n\n y_true.append(temp_1)\n y_pred.append(temp_2)\n\n mtag = lambda labs: [tag2idx['I-per'] \\\n if l == tag2idx['B-per'] else l for l in labs]\n\n aseq = set([tuple(i for i,value in it) \\\n for key,it in itertools.groupby(\n enumerate(mtag(labels[i])), key=operator.itemgetter(1)) \\\n if key == tag2idx['I-per']])\n pseq = set([tuple(i for i,value in it) \\\n for key,it in itertools.groupby(\n enumerate(mtag(logits[i])), key=operator.itemgetter(1)) \\\n if key == tag2idx['I-per']])\n \n total += len(aseq)\n hit += len(pseq & aseq)\n miss += len(aseq - pseq)\n err += len(pseq - aseq)\n\n ##predictions.append(pseq)\n\n print(\"f1 socre: %f\"%(f1_score(y_true, y_pred)))\n print(\"Accuracy score: %f\"%(accuracy_score(y_true, y_pred)))\n print(\"Name score hit: {} / {} = {}\".format(hit, total, hit / total))\n print(\"Name score miss: {} / {} = {}\".format(miss, total, miss / total))\n print(\"Name score error: {} / {} = {}\".format(err, total, err / total))\n return None, accuracy_score(y_true, y_pred)\n\ndef extractor():\n tokenizer = AutoTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)\n device = torch.device(CUDA_NUM if torch.cuda.is_available() else \"cpu\")\n config = AutoConfig.from_pretrained(PRETRAINED_MODEL_NAME, num_labels=len(tag2idx))\n\n model = AutoModelForTokenClassification.from_pretrained(\n PRETRAINED_MODEL_NAME,config=config)\n\n model = model.to(device)\n model.load_state_dict(\n torch.load(os.path.join(ModelName.format(model_idx),\n 'pytorch_model.bin'), map_location=\"cpu\"))\n\n model.eval()\n\n def predict(doc):\n\n names, docs = [], []\n predset = NameDoc(tokenizer=tokenizer, doc=doc)\n dataloader = torch.utils.data.DataLoader(\n predset,batch_size=1,shuffle=True,collate_fn=create_mini_batch)\n\n with torch.no_grad():\n\n for tokens, *data in dataloader:\n\n if next(model.parameters()).is_cuda:\n data = [t.to(device) for t in data if t is not None]\n\n tokens_tensors, segments_tensors, masks_tensors, labels = data\n\n\n outputs = model(input_ids=tokens_tensors,\n token_type_ids=None,\n # token_type_ids=segments_tensors,\n attention_mask=masks_tensors)\n\n logits = outputs[0]\n\n logits = torch.argmax(F.log_softmax(logits,dim=2),dim=2)\n logits = logits.detach().cpu().numpy()\n\n # Only predict the real word, mark=0, will not calculate\n masks_tensors = masks_tensors.to('cpu').numpy()\n\n tr = lambda e: ','.join(e) if len(e) == 2 and all_english(''.join(e), '▁') else ''.join(e)\n\n for i,mask in enumerate(masks_tensors):\n name, doc = [], ''\n names.append([])\n for j, m in enumerate(mask):\n if m:\n if logits[i][j] not in (tag2idx[''], tag2idx['']):\n doc += tokens[i][j]\n if logits[i][j] == tag2idx['B-per']:\n if name:\n names[-1].append(tr(name))\n name = []\n name.append(tokens[i][j])\n elif logits[i][j] == tag2idx['I-per']:\n name.append(tokens[i][j])\n elif name:\n names[-1].append(tr(name))\n name = []\n else:\n break\n if name: names[-1].append(tr(name))\n docs.append(doc)\n\n # need filter the names from doc and do classification again\n return names, docs\n\n nft = namefilter()\n def _ext(doc):\n names, docs = predict(doc)\n print('original names', names)\n return nft(list(set().union(*names)), ''.join(docs))\n \n return _ext\n\n\nif __name__ == \"__main__\":\n tokenizer = AutoTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)\n device = torch.device(CUDA_NUM if torch.cuda.is_available() else \"cpu\")\n config = AutoConfig.from_pretrained(PRETRAINED_MODEL_NAME, num_labels=len(tag2idx))\n\n model = AutoModelForTokenClassification.from_pretrained(\n PRETRAINED_MODEL_NAME,config=config)\n\n model = model.to(device)\n\n # additional\n max_grad_norm = 1.0\n FULL_FINETUNING = True\n if FULL_FINETUNING:\n # Fine tune model all layer parameters\n param_optimizer = list(model.named_parameters())\n no_decay = ['bias', 'gamma', 'beta']\n optimizer_grouped_parameters = [\n {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)],\n 'weight_decay_rate': 0.01},\n {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)],\n 'weight_decay_rate': 0.0}\n ]\n else:\n # Only fine tune classifier parameters\n param_optimizer = list(model.classifier.named_parameters())\n optimizer_grouped_parameters = [{\"params\": [p for n, p in param_optimizer]}]\n optimizer = AdamW(optimizer_grouped_parameters, lr=3e-5)\n\n\n if train:\n trainset = NameDataset(os.path.join(root, TrainFile), tokenizer=tokenizer)\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=BATCH_SIZE,\n collate_fn=create_mini_batch,shuffle=True)\n model.train()\n\n # use above instead\n #optimizer = torch.optim.Adam(model.parameters(), lr=3e-5)\n\n for epoch in range(EPOCHS):\n\n running_loss = 0.0\n for _, *data in trainloader:\n\n tokens_tensors, segments_tensors, \\\n masks_tensors, labels = [t.to(device) for t in data]\n\n optimizer.zero_grad()\n\n outputs = model(input_ids=tokens_tensors,\n token_type_ids=None,\n # token_type_ids=segments_tensors,\n attention_mask=masks_tensors,\n labels=labels)\n\n loss = outputs[0]\n loss.backward()\n\n # gradient clipping, additional\n torch.nn.utils.clip_grad_norm_(parameters=model.parameters(), max_norm=max_grad_norm)\n\n optimizer.step()\n\n running_loss += loss.item()\n\n _, acc = get_predictions(model, trainloader, device=device)\n\n print('[epoch %d] loss: %.3f, acc: %.3f' %\n (epoch + 1, running_loss, acc))\n model.save_pretrained(ModelName.format(epoch))\n else:\n for model_idx in range(0, EPOCHS):\n print(\"epoch {}:\".format(model_idx))\n model.load_state_dict(\n torch.load(os.path.join(ModelName.format(model_idx),\n 'pytorch_model.bin'), map_location=\"cpu\"))\n trainset = NameDataset(os.path.join(root, ValidFile), tokenizer=tokenizer)\n testloader = torch.utils.data.DataLoader(trainset, batch_size=BATCH_SIZE,\n collate_fn=create_mini_batch)\n _, acc = get_predictions(model, testloader, device=device)\n print(acc)\n","sub_path":"models/XLNetExtractor.py","file_name":"XLNetExtractor.py","file_ext":"py","file_size_in_byte":10727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"31886598","text":"import oz\n\nclass BoostrapMiddleware(object):\n def __init__(self):\n super(BoostrapMiddleware, self).__init__()\n self.trigger_listener(\"write_error\", self._on_write_error)\n\n def _on_write_error(self, status_code, **kwargs):\n \"\"\"Catches errors and renders an appropriate page\"\"\"\n\n # Print the traceback if in debug mode; otherwise figure out the\n # template to render\n if self.settings.get(\"debug\") != True:\n if status_code == 404:\n self.render(\"error/404.html\")\n elif status_code == 500:\n self.render(\"error/500.html\")\n else:\n self.render(\"error/unknown.html\")\n\n return oz.break_trigger\n","sub_path":"bootstrap/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"262667283","text":"import pickle\nimport streamlit as st\nfrom tensorflow.keras.models import load_model\nimport joblib\nimport numpy as np\n\n\n\nmodel = load_model(\"customer_retention_1.h5\")\nscaler = joblib.load(\"ann_scaler.pkl\")\nohencoder = joblib.load(\"onehot_col_transformer.pkl\")\n\n\ndef prediction(CreditScore, Geography, Gender, Age, Tenure, Balance, NumOfProducts, HasCrCard, IsActiveMember, EstimatedSalary):\n if Gender == \"Male\":\n Gender = 1\n else:\n Gender = 0\n \n if HasCrCard == \"Yes\":\n HasCrCard = 1\n else:\n HasCrCard = 0\n \n if IsActiveMember == \"Yes\":\n IsActiveMember = 1\n else:\n IsActiveMember = 0\n \n preds=[[CreditScore, Geography, Gender, Age, Tenure, Balance, NumOfProducts, HasCrCard, IsActiveMember, EstimatedSalary]]\n result = round(model.predict(scaler.transform(np.array(ohencoder.transform(preds))))[0][0]*100,2)\n\n return result\n\n\ndef main(): \n st.set_page_config(page_title=\"Churn App\")\n # front end elements of the web page \n html_temp = \"\"\" \n
\n

Customer Retention App

\n
\n

Enter below information to see if the probability of a customer leaving the bank

\n \"\"\"\n \n # display the front end aspect\n st.markdown(html_temp, unsafe_allow_html = True) \n \n # following lines create boxes in which user can enter data required to make prediction \n CreditScore = st.slider(\"Enter customer's Credit Score\",min_value=300,max_value=850,step=1)\n Geography = st.selectbox('Select the country where the customer is located',(\"France\", \"Spain\", \"Germany\"))\n Gender = st.selectbox('Enter customer\\'s gender',(\"Male\",\"Female\"))\n Age = st.slider(\"Enter customer's age\",min_value=18,max_value=100,step=1)\n Tenure = st.slider(\"How many years has the customer been with the bank?\",min_value=1,max_value=50,step=1)\n Balance = st.number_input(\"Enter customer\\'s account balance\")\n NumOfProducts = st.number_input(\"How many bank products has the customer purchased?\")\n HasCrCard = st.selectbox(\"Does the customer have a credit card?\",(\"Yes\",\"No\"))\n IsActiveMember = st.selectbox(\"Is the customer an active member of the bank?\",(\"Yes\",\"No\"))\n EstimatedSalary = st.number_input(\"Enter customer's annual salary\")\n result =\"\"\n \n # when 'Predict' is clicked, make the prediction and store it \n if st.button(\"Predict\"): \n result = prediction(CreditScore, Geography, Gender, Age, Tenure, Balance, NumOfProducts, HasCrCard, IsActiveMember, EstimatedSalary)\n \n if result<50:\n churnstatus=\"STAYING IN\"\n else:\n churnstatus=\"LEAVING\"\n \n st.success('The customer will be {} the bank'.format(churnstatus))\n st.success('The probability of the customer leaving the bank is {} %'.format(result))\n\nif __name__=='__main__': \n main()\n \n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"482734781","text":"# -*- coding: utf-8 -*-\n\n# Define here the models for your spider middleware\n#\n# See documentation in:\n# https://doc.scrapy.org/en/latest/topics/spider-middleware.html\nimport random\n\nfrom scrapy import signals\nfrom scrapy.downloadermiddlewares.useragent import UserAgentMiddleware\nfrom scrapy.downloadermiddlewares.cookies import CookiesMiddleware\n\n\nclass SpiderSpiderMiddleware(object):\n # Not all methods need to be defined. If a method is not defined,\n # scrapy acts as if the spider middleware does not modify the\n # passed objects.\n\n @classmethod\n def from_crawler(cls, crawler):\n # This method is used by Scrapy to create your spiders.\n s = cls()\n crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)\n return s\n\n def process_spider_input(self, response, spider):\n # Called for each response that goes through the spider\n # middleware and into the spider.\n\n # Should return None or raise an exception.\n return None\n\n def process_spider_output(self, response, result, spider):\n # Called with the results returned from the Spider, after\n # it has processed the response.\n\n # Must return an iterable of Request, dict or Item objects.\n for i in result:\n yield i\n\n def process_spider_exception(self, response, exception, spider):\n # Called when a spider or process_spider_input() method\n # (from other spider middleware) raises an exception.\n\n # Should return either None or an iterable of Response, dict\n # or Item objects.\n pass\n\n def process_start_requests(self, start_requests, spider):\n # Called with the start requests of the spider, and works\n # similarly to the process_spider_output() method, except\n # that it doesn’t have a response associated.\n\n # Must return only requests (not items).\n for r in start_requests:\n yield r\n\n def spider_opened(self, spider):\n spider.logger.info('Spider opened: %s' % spider.name)\n\n\nclass SpiderDownloaderMiddleware(object):\n # Not all methods need to be defined. If a method is not defined,\n # scrapy acts as if the downloader middleware does not modify the\n # passed objects.\n\n @classmethod\n def from_crawler(cls, crawler):\n # This method is used by Scrapy to create your spiders.\n s = cls()\n crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)\n return s\n\n def process_request(self, request, spider):\n # Called for each request that goes through the downloader\n # middleware.\n\n # Must either:\n # - return None: continue processing this request\n # - or return a Response object\n # - or return a Request object\n # - or raise IgnoreRequest: process_exception() methods of\n # installed downloader middleware will be called\n return None\n\n def process_response(self, request, response, spider):\n # Called with the response returned from the downloader.\n\n # Must either;\n # - return a Response object\n # - return a Request object\n # - or raise IgnoreRequest\n return response\n\n def process_exception(self, request, exception, spider):\n # Called when a download handler or a process_request()\n # (from other downloader middleware) raises an exception.\n\n # Must either:\n # - return None: continue processing this exception\n # - return a Response object: stops process_exception() chain\n # - return a Request object: stops process_exception() chain\n pass\n\n def spider_opened(self, spider):\n spider.logger.info('Spider opened: %s' % spider.name)\n\n\nclass RandomUserAgentMiddleware(UserAgentMiddleware):\n USER_AGENT_LIST = [\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) \"\n \"Chrome/22.0.1207.1 Safari/537.1\",\n \"Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) \"\n \"Chrome/20.0.1132.57 Safari/536.11\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) \"\n \"Chrome/20.0.1092.0 Safari/536.6\",\n \"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) \"\n \"Chrome/20.0.1090.0 Safari/536.6\",\n \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) \"\n \"Chrome/19.77.34.5 Safari/537.1\",\n \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) \"\n \"Chrome/19.0.1084.9 Safari/536.5\",\n \"Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) \"\n \"Chrome/19.0.1084.36 Safari/536.5\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) \"\n \"Chrome/19.0.1063.0 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) \"\n \"Chrome/19.0.1063.0 Safari/536.3\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 (KHTML, \"\n \"like Gecko) Chrome/19.0.1063.0 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) \"\n \"Chrome/19.0.1062.0 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) \"\n \"Chrome/19.0.1062.0 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) \"\n \"Chrome/19.0.1061.1 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) \"\n \"Chrome/19.0.1061.1 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) \"\n \"Chrome/19.0.1061.1 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) \"\n \"Chrome/19.0.1061.0 Safari/536.3\",\n \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) \"\n \"Chrome/19.0.1055.1 Safari/535.24\",\n \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) \"\n \"Chrome/19.0.1055.1 Safari/535.24\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) \"\n \"Chrome/43.0.2357.132 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0\"]\n\n def process_request(self, request, spider):\n ua = random.choice(self.USER_AGENT_LIST)\n request.headers.setdefault('User-Agent', ua)\n\n\nclass RandomCookieMiddleware(CookiesMiddleware):\n # cookies = [\n # {\"_T_WM\": \"88510f592e13f85224f5d2cf249680e0\",\n # \"ALF\": \"1554558588\",\n # \"SSOLoginState\": \"1551966589\",\n # \"MLOGIN\": \"1\",\n # \"WEIBOCN_FROM\": \"1110006030\",\n # \"SCF\": \"Ag_f8T4qg9uiN-Kts-jmnKjik99qkk417QqWSxUWfuIR7ScQmwdx1ZTv1qNkef9MG\"\n # \"-iCdmrcB2Ty01KuajDaJ6M.\",\n # \"SUB\":\n #\n # \"_2A25xhVEtDeRhGeNM6VIS9ynOzz6IHXVShn9lrDV6PUJbktAKLVLEkW1NTi0IEzrDWytbBCrTUWStS9x4Jb4EwctO\",\n # \"SUBP\": \"0033WrSXqPxfM725Ws9jqgMF55529P9D9W5ZLIWa7nsxoxkjsm9b5Kyi5JpX5K-hUgL.Fo\"\n # \"-Eeo50S0MEShz2dJLoIExQwPWLMJiads2LxK-L12qL12eLxKqL1-zLBozLxKMLB.2LB.qt\",\n # \"SUHB\": \"02MfezNbOQYvsK\",\n # \"XSRF-TOKEN\": \"5b4193\",\n # \"M_WEIBOCN_PARAMS\": \"luicode%3D10000011%26lfid%3D1076031699432410%26uicode\"\n # \"%3D20000174\"\n # },\n # {\n # '_T_WM': 'f6c232c91f608cd2b8f7fe303c4729d5',\n # 'SUHB': '0XDl3MjMdnLi-1',\n # 'SUB': '_2A25xzA9RDeRhGeNM41UR8yvOyDuIHXVTTpEZrDV6PUJbkdBeLRTVkW1NSfs'\n # '-BA4T1eT4GXhHkrPwnjS8boN5YJqk',\n # 'SSOLoginState': '1556643585',\n # 'SCF': 'AnPdORTgrDn3jz2FARHBqgT0hfDN_LJyW1n3ZjwKUVXkliavjMn'\n # '-llyIcfu9CM82hRyGDN9zwtNvT7m_tHIi1Tk.'\n # },\n # {\n # '_T_WM': 'd8f682ddd4d2e0bba779aff3c859bc01',\n # 'SUHB': '05iLei6dg8l53m',\n # 'SUB': '_2A25xygmtDeRhGeRM7FYX-SzMyj6IHXVTNJflrDV6PUJbkdAKLXn4kW1NU9lV'\n # '-mdysVxWn3yxhTnUGIqibcCCVLgA',\n # 'SSOLoginState': '1557035517',\n # 'SCF': 'AqgCqnfQfus2hZ91j7VXrwOk7Ybm5g60elWJjw4vm2'\n # '-_Msdh9ckUEAkJkDHydfdhv7RZlQRWEuvXYrHherYvlzo.'\n # },\n # {\n # '_T_WM': 'dd39d61603eae48b01c3c9f455ef45b3',\n # 'SUHB': '0ebcg-n3xPFYmU',\n # 'SUB': '_2A25xyuwLDeRhGeRJ6lQT8ybIyz'\n # '-IHXVTNPRDrDV6PUJbkdAKLUz4kW1NUnnd3S268vV0_rEOBYDwiV9UP_SPPach',\n # 'SSOLoginState': '1557044315',\n # 'SCF': 'AvK-wNPr_2LvgNlAX932BrW1JdPW2mXEtqLFjls4fb5yX'\n # '-fCrDKQnd6zL6zlh5sWXqwQOMtAtBKsv2AJRHl8u_g.'\n # },\n # ]\n # cookies = [\n # {\"ALF\": \"1592395259\",\n # \"Apache\": \"7641355422360.468.1550545551314\",\n # \"SCF\": 'ArgY-i3N6StMP1trO7TWYCPUpY6WmzfHBE7pxahb4EMA8NbGrbHL'\n # '-WD1rtMaTtl5PmeMTzT98iocaCwzKm4KlQ4.',\n # \"SINAGLOBAL\":\n # '7641355422360.468.1550545551314',\n # \"SSOLoginState\": \"1560859260\",\n # \"SUB\": \"_2A25wDKIsDeRhGeNM41UR8yvOyDuIHXVTe5TkrDV8PUNbmtAKLXbTkW9NSfs\"\n # \"-BKDQ1dSaebjA1745X5U32Ow22PhY\",\n # 'SUBP': '0033WrSXqPxfM725Ws9jqgMF55529P9D9WWN9_YYbKrAOU_0jaRCxHX25JpX5KMhUgL.Fo'\n # '-E1hM7e0-Ee0M2dJLoIpRLxKqL1KMLB.2LxKqL1KMLB.2LxKqL1KMLB.27eh5t',\n # 'SUHB': '0HThJwW2ufBKi1',\n # 'ULV': '1550545551318:1:1:1:7641355422360.468.1550545551314:',\n # 'UOR': ',,www.hailiangxinxi.com',\n # '_s_tentry': 'gl.ali213.net',\n # 'cross_origin_proto': 'SSL',\n # 'login_sid_t': '34b4689164b0254a9cc5dbe5c2cef7c4',\n # 'webim_unReadCount': '%7B%22time%22%3A1560924147959%2C%22dm_pub_total%22%3A0%2C'\n # '%22chat_group_pc%22%3A0%2C%22allcountNum%22%3A0%2C%22msgbox'\n # '%22%3A0%7D',\n # 'wvr': '6'\n # }\n # ]\n\n cookies = [\n {\n\n 'SINAGLOBAL': '9041156132766.867.1543458613637',\n 'login_sid_t': '28b7e901a822146ba646a4f01d51fe4c',\n 'cross_origin_proto': 'SSL',\n '_ga': 'GA1.2.469243942.1564582470',\n '_s_tentry': 'login.sina.com.cn',\n '__gads': 'ID=dbe5305fe93ea2ba:T=1564582472:S=ALNI_MbYaw-slDdzze_NCw7cClL2AbKspA',\n 'Apache': '9622518199179.783.1564582474813',\n 'ULV': '1564582474823:8:2:1:9622518199179.783.1564582474813:1562834785705',\n 's_cc': 'true',\n 's_sq': '%5B%5BB%5D%5D',\n 'UM_distinctid': '16cb07917746ff-0a0e8989d83508-37677c02-13c680-16cb0791775754',\n 'wvr': '6',\n 'UOR': ',,pypi.org',\n 'SCF': 'Am7Jt7ySAY5qGVf-9s3G4Of_Q9InAuL_1ZZY7JWBEh1Ek9lVOFRP4PFu9Z2OcqiwCnlwtKzenhVqTQ6n4Af_9vQ.',\n 'SSOLoginState': '1566931949',\n 'SUHB': '0G0uuIftjyM0Va',\n 'ALF': '1569558823',\n 'SUB': '_2A25wYnR3DeRhGeVK41cR8CnKyzuIHXVTrRw_rDV8PUJbkNBeLWnzkW1NTCdnpoCY4SPuBYQrrPVRgFNepqORVwHh',\n 'SUBP': '0033WrSXqPxfM725Ws9jqgMF55529P9D9WWJcHiLLQYmQJX._sM6GNLg5JpX5oz75NHD95Q0Shnfeh5NSo5NWs4Dqc_fi--Ni-iFiKnRi--Xi-iWiKy8i--fiKysi-8si--Xi-iFi-2fi--ciK.Xi-z4i--fiK.7iKy2i--Xi-iWiKnci--fiKysiKnRi--Ri-2ciKnpi--fiK.7iKy8i--ciKnEiK.Xi--Xi-zRiKn7i--fi-z4i-zX',\n 'S_ACCOUNT-G0': '8bd737c12f321cf9d9f95301c2782451',\n '_T_WM': '8ddabf447041f61bd2b060f4ef93928d',\n 'webim_unReadCount': '%7B%22time%22%3A1567024240889%2C%22dm_pub_total%22%3A0%2C%22chat_group_client%22%3A0%2C%22allcountNum%22%3A0%2C%22msgbox%22%3A2%7D',\n 'WBStorage': 'f54cf4e4362237da|undefined'\n }\n ]\n\n def process_request(self, request, spider):\n cookie = random.choice(self.cookies)\n request.cookies = cookie\n","sub_path":"Desktop/jasmine/crawl_weibo_fakenews-master/spider/middlewares.py","file_name":"middlewares.py","file_ext":"py","file_size_in_byte":11805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"135905320","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport numpy as np\nimport subprocess as subp\n\nfrom sklearn.datasets import load_iris\nfrom sklearn.datasets import load_breast_cancer\nfrom sklearn.datasets import load_digits\nfrom sklearn.utils import shuffle\n\nfrom tests.estimator.classifier.SeparatedData import SeparatedData\n\n\nclass Classifier(SeparatedData):\n\n TEST_N_RANDOM_FEATURE_SETS = 20\n TEST_N_EXISTING_FEATURE_SETS = 20\n\n def setUp(self):\n np.random.seed(5)\n self._init_env()\n\n def tearDown(self):\n self._clear_estimator()\n\n def _init_env(self):\n for param in ['TEST_N_RANDOM_FEATURE_SETS', 'TEST_N_EXISTING_FEATURE_SETS']:\n n = os.environ.get(param, None)\n if n is not None and str(n).strip().isdigit():\n n = int(n)\n if n > 0:\n self.__setattr__(param, n)\n\n def load_binary_data(self, shuffled=True):\n samples = load_breast_cancer()\n self.X = shuffle(samples.data) if shuffled else samples.data\n self.y = shuffle(samples.target) if shuffled else samples.target\n self.n_features = len(self.X[0])\n\n def load_iris_data(self, shuffled=True):\n samples = load_iris()\n self.X = shuffle(samples.data) if shuffled else samples.data\n self.y = shuffle(samples.target) if shuffled else samples.target\n self.n_features = len(self.X[0])\n\n def load_digits_data(self, shuffled=True):\n samples = load_digits()\n self.X = shuffle(samples.data) if shuffled else samples.data\n self.y = shuffle(samples.target) if shuffled else samples.target\n self.n_features = len(self.X[0])\n\n def _clear_estimator(self):\n self.estimator = None\n cmd = 'rm -rf tmp'.split()\n subp.call(cmd)\n","sub_path":"tests/estimator/classifier/Classifier.py","file_name":"Classifier.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"611278978","text":"from app import db\nfrom app.models import SimpleTable\ndef entry_to_json(data):\n dt = []\n for i in data:\n dt.append({\n 'username': i.username,\n 'email': i.email_id,\n 'year_of_birth': i.year_of_birth,\n 'age_group': i.age_group\n })\n return dt\n\ndef get_age_group(year_of_birth):\n if year_of_birth <= 1995 and year_of_birth >= 1980:\n return 'Adult'\n elif year_of_birth < 1980:\n return 'Old'\n else:\n return 'Child'\n\ndef new_entry(username, email_id, year_of_birth):\n year_of_birth = int(year_of_birth)\n try:\n age_group = get_age_group(year_of_birth)\n dt = SimpleTable(username=username, email_id=email_id, year_of_birth=year_of_birth, age_group=age_group)\n db.session.add(dt)\n db.session.commit()\n return [200, 'Success']\n except Exception as e:\n return [500, e]\n\ndef delete_entry(email_id):\n try:\n entry = SimpleTable.query.filter_by(email_id=email_id).first()\n if entry:\n db.session.delete(entry)\n db.session.commit()\n return [200, 'Success']\n else:\n return [404, 'Entry not found']\n except Exception as e:\n return [500, str(e)]\n\ndef update_entry(email_id, year_of_birth, username):\n try:\n entry = SimpleTable.query.filter_by(email_id=email_id).first()\n \n if entry:\n entry.year_of_birth = year_of_birth\n entry.username = username\n entry.age_group = get_age_group(year_of_birth)\n entry.email_id = email_id\n\n db.session.commit()\n return [200, 'Success']\n else:\n return [404, 'Entry not found']\n except Exception as e:\n return [500, str(e)]","sub_path":"src/backend/app/main/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"417063688","text":"\nimport time\nimport pandas as pd\nimport numpy as np\nfrom random import randint\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nfrom sklearn.decomposition import PCA\nfrom sklearn.neighbors import KNeighborsClassifier\n\ndef show(data, start, end, flag, ax, hang):\n count = 0\n rand_show = [randint(start, end) for i in range(4)]\n for ind, row in data.iloc[rand_show].iterrows():\n i = row[0]\n arr = np.array(row[1:], dtype=np.uint8)\n arr.resize((28, 28))\n im = Image.fromarray(arr)\n ax[hang][count].imshow(im)\n ax[hang][count].set_title(\"%s_%s.png\" %(flag, i))\n count += 1\n\nif __name__ ==\"__main__\":\n train_num = 20000\n test_num = 30000\n img_to_show = []\n count = 0\n data = pd.read_csv('train.csv')\n figure, ax = plt.subplots(2, 4)\n show(data, 0, 19999, 'train', ax, 0)\n show(data, 20000, 29999, 'test', ax, 1)\n plt.show()\n train_data = data.values[0:train_num, 1:]\n train_label = data.values[0:train_num, 0]\n test_data = data.values[train_num:test_num, 1:]\n test_label = data.values[train_num:test_num, 0]\n t = time.time()\n pca = PCA(n_components=0.8)\n train_x = pca.fit_transform(train_data)\n test_x = pca.transform(test_data)\n neighbors = KNeighborsClassifier(n_neighbors=4)\n neighbors.fit(train_x, train_label)\n pre = neighbors.predict(test_x)\n acc = float((pre == test_label).sum()) / len(test_x)\n print('accuracy:%f,time:%.2fs' % (acc, time.time() - t))\n","sub_path":"knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"518408163","text":"from django.shortcuts import render_to_response\nfrom django.http import HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic import TemplateView\n\nfrom forms import UserCreateProfile\nfrom models import UserProfile\nfrom pprint import pprint\n\n@login_required\ndef user_profile(request):\n try:\n profile = request.user.get_profile()\n return render_to_response('registration/profile.html',{'profile' : profile})\n except:\n from forms import UserCreateProfile\n form = UserCreateProfile()\n return render_to_response('registration/profile.html',{'form' : form})\n\nclass Profile(TemplateView):\n\n @method_decorator(login_required)\n def dispatch(self,*args,**kwargs):\n return super(Profile, self).dispatch(*args, **kwargs)\n\nclass ProfileView(Profile):\n template_name = \"registration/profile.html\"\n\n def get(self,request,*args, **kwargs):\n try:\n profile = request.user.get_profile()\n form = UserCreateProfile()\n context = { 'profile' : profile }\n except:\n form = UserCreateProfile()\n context = { 'form' : form, 'message': 'You do not have a profile yet. Please create one' }\n return self.render_to_response(context)\n\n def post(self,request,*args,**kwargs):\n form = UserCreateProfile(request.POST,request.FILES)\n if form.is_valid():\n form.user = request.user\n form.save()\n context = { 'profile' : request.user.get_profile() }\n else:\n context = { 'form' : form }\n return self.render_to_response(context)\n\nclass ProfileEdit(Profile):\n template_name = \"registration/profile_edit.html\"\n\n def get(self,request,*args, **kwargs):\n profile = request.user.get_profile()\n initial = { 'user' : request.user, 'picture' : profile.picture, 'url' : profile.url }\n context = {'form' : UserCreateProfile(initial=initial) }\n\n return self.render_to_response(context)\n\n def post(self, request, *args, **kwargs):\n form = UserCreateProfile(request.POST,request.FILES)\n if form.is_valid():\n form.user_id = request.user.id #WHY!!!!!!!\n form.save()\n HttpResponseRedirect(reverse('profile_view'))\n else:\n context = { 'form' : form }\n return self.render_to_response(context)\n","sub_path":"pyc/account/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"468340523","text":"from panda3d.core import *\nloadPrcFile(\"config/Config.prc\")\n\nfrom direct.showbase.ShowBase import ShowBase\nfrom StartMenu import StartMenu\nimport Globals\nfrom direct.gui import DirectGuiGlobals\n\n\nclass MyApp(ShowBase):\n\n def __init__(self):\n ShowBase.__init__(self)\n Globals.setSignFont(loader.loadFont('phase_3/models/fonts/MickeyFont'))\n Globals.setRolloverSound(loader.loadSfx(\"phase_3/audio/sfx/GUI_rollover.ogg\"))\n Globals.setClickSound(loader.loadSfx(\"phase_3/audio/sfx/GUI_create_toon_fwd.ogg\"))\n Globals.setInterfaceFont(loader.loadFont('phase_3/models/fonts/ImpressBT.ttf'))\n DirectGuiGlobals.setDefaultFont(Globals.getInterfaceFont())\n DirectGuiGlobals.setDefaultClickSound(Globals.getClickSound())\n DirectGuiGlobals.setDefaultRolloverSound(Globals.getRolloverSound())\n self.loader.loadMusic(\"phase_3/audio/bgm/tti_theme.ogg\").play()\n self.toon = None\n self.toonClass = None\n self.go()\n\n def go(self):\n import Messenger\n Messenger.Messenger().__init__()\n self.startMenuClass = StartMenu()\n self.setBackgroundColor(Globals.defaultBackgroundColor)\n self.startMenuClass.loadStartMenu()\n\n\ngame = MyApp()\ngame.run()\n\n","sub_path":"Start.py","file_name":"Start.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"224271876","text":"from databaseConfig.dbConnection import Database\n\n\nclass CourseDb(Database):\n # This class get the list of courses in some campus\n # from UnB and save it in MongoDb\n\n @staticmethod\n def saveCourses(courses):\n # This method static get the list of courses and\n # save it in MongoDb\n\n # Instantiate the database connection and\n # create get the collection course from Mongo\n db = Database.defineConnections()\n collection_course = db['courses']\n\n old_size_list = 0\n\n # Run through the course lists\n for campus, course_list in courses.items():\n\n print(\"Saving courses for campus {}...\".format(campus))\n\n size_list = len(course_list)\n\n # How it comes with the entire list having all the departaments,\n # we split the list according with the campus\n courses_set = course_list[old_size_list: size_list]\n\n old_size_list = size_list\n\n # Get all the attributes from the current course\n # Save it in mongo collection\n for course in courses_set:\n\n current_course = {\n 'code': course.getCode(),\n 'campus': course.getCampus(),\n 'name': course.getName(),\n 'shift': course.getShift(),\n 'modality': course.getModality(),\n 'habilitations': [str(x.getCode()) for x in course.getHabilitations()]\n }\n\n collection_course.insert_one(current_course)\n","sub_path":"databaseConfig/coursesDatabase.py","file_name":"coursesDatabase.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"176150690","text":"\"\"\"Tests for Preprocessing node\"\"\"\nimport pytest\nfrom cognigraph.nodes.processors import Preprocessing\nfrom cognigraph.nodes.sources import FileSource\nfrom cognigraph.gui.async_pipeline_update import AsyncUpdater\nfrom PyQt5.QtCore import QCoreApplication\nimport sys\n\nfrom cognigraph.nodes.tests.prepare_tests_data import info, data_path # noqa\nimport numpy as np\n\n\n@pytest.fixture # noqa\ndef preprocessor(info, data_path): # noqa\n preprocessor = Preprocessing()\n preprocessor.mne_info = info\n N_SEN = len(info['ch_names'])\n preprocessor.input = np.random.rand(N_SEN)\n parent = FileSource(data_path)\n parent.output = np.random.rand(info['nchan'], 1)\n parent.mne_info = info\n preprocessor.parent = parent\n\n app = QCoreApplication(sys.argv)\n parent.updater = AsyncUpdater(app, parent)\n return preprocessor\n\n\ndef test_change_api_attributes(preprocessor):\n \"\"\"Change collect_for_x_seconds and check if _samples_collected is reset\"\"\"\n arbitrary_value = 200\n\n preprocessor.collect_for_x_seconds = 10\n preprocessor.initialize()\n preprocessor._samples_collected = arbitrary_value\n preprocessor.collect_for_x_seconds = 20\n preprocessor.update()\n\n preprocessor._samples_collected = arbitrary_value\n preprocessor.dsamp_freq = 8\n assert preprocessor._samples_collected == arbitrary_value\n\n\ndef test_input_hist_invalidation_resets_statistics(preprocessor):\n arbitrary_value = 200\n\n preprocessor.parent.initialize()\n preprocessor.initialize()\n\n preprocessor._samples_collected = arbitrary_value\n preprocessor.on_input_history_invalidation()\n\n assert preprocessor._samples_collected == 0\n\n\ndef test_pass(preprocessor):\n pass\n","sub_path":"cognigraph/nodes/tests/test_Preprocessing.py","file_name":"test_Preprocessing.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"81154378","text":"#!/usr/bin/python3\n\n\nclass Log:\n '''\n a class for storing and analyzing log file contents\n '''\n\n def __init__(self, folder, file):\n '''\n initialize class\n :param string folder: absolute path of the log file directory\n :param string file: name of the log file\n '''\n # absolute path of the log file directory\n self.folder = folder\n\n # name of the log file\n self.file = file\n\n # latest time stamp in log file\n self.t = 0\n\n # failure notices\n self.failures = []\n\n # read file\n with open(self.folder + self.file, 'r') as f:\n # iterate lines in reverse order\n for l in reversed(f.readlines()):\n # get latest time stamp\n if len(l.split('[')) > 2 and len(l.split('[')[2].split(',')) > 1:\n t = float(l.split('[')[2].split(',')[1].strip(' ]'))\n if self.t == 0:\n self.t = t\n else:\n t = 0\n\n # get failure notices\n if (l.split(':')[-1])[1:25] == \"requesting home position\":\n self.failures.append(t)\n else:\n break\n\n def localization_fails(self, time):\n '''\n get the number of failure notices after a given time\n :param float time: time after which the failures are counted\n '''\n for n,t in enumerate(self.failures):\n if t < time:\n return n\n\n return len(self.failures)\n","sub_path":"cpswarm_sar/scripts/modules/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"218104362","text":"import sys\nimport gzip\nfrom collections import defaultdict\nfrom typing import List\nfrom rsstag.utils import load_config\nfrom rsstag.tags_builder import TagsBuilder\nfrom rsstag.html_cleaner import HTMLCleaner\nfrom rsstag.posts import RssTagPosts\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.cluster import DBSCAN\nfrom pymongo import MongoClient\n\ndef get_texts(all_posts: List[dict], config) -> None:\n texts_for_vec = []\n post_pids = []\n if all_posts:\n builder = TagsBuilder(config['settings']['replacement'])\n cleaner = HTMLCleaner()\n for post in all_posts:\n post_pids.append(post['pid'])\n text = post['content']['title'] + ' ' + gzip.decompress(post['content']['content']).decode('utf-8', 'ignore')\n cleaner.purge()\n cleaner.feed(text)\n strings = cleaner.get_content()\n text = ' '.join(strings)\n builder.purge()\n builder.prepare_text(text, ignore_stopwords=True)\n texts_for_vec.append(builder.get_prepared_text())\n\n return (texts_for_vec, post_pids)\n\ndef get_dbscan_clusters(texts: List[str], post_pids: List[int], skip_noise: bool=True) -> dict:\n vectorizer = TfidfVectorizer()\n dbs = DBSCAN(eps=0.9, min_samples=2, n_jobs=1)\n dbs.fit(vectorizer.fit_transform(texts))\n clusters = defaultdict(set)\n for i, cluster in enumerate(dbs.labels_):\n clusters[int(cluster)].add(post_pids[i])\n\n if skip_noise and clusters and -1 in clusters:\n del clusters[-1]\n\n return clusters\n\nif __name__ == '__main__':\n config_path = 'rsscloud.conf'\n if len(sys.argv) > 1:\n config_path = sys.argv[1]\n config = load_config(config_path)\n cl = MongoClient(config['settings']['db_host'], int(config['settings']['db_port']))\n db = cl[config['settings']['db_name']]\n posts = RssTagPosts(db)\n user = db.users.find_one({})\n all_posts = posts.get_all(user['sid'], projection={'content': True, 'pid': True})\n texts, post_pids = get_texts(all_posts, config)\n #f = open('all_posts.txt', 'r', encoding='utf-8')\n #texts = f.read().splitlines()\n #post_pids = list(range(len(texts)))\n print('Text fetched: ', len(all_posts))\n clusters = get_dbscan_clusters(texts, post_pids)\n print('Clustered: ', len(clusters))\n posts.set_clusters(user['sid'], clusters)\n","sub_path":"clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":2366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"449896410","text":"from django.contrib.auth.forms import UserCreationForm, UserChangeForm\nfrom .models import CustomUser, Post\nfrom django import forms\n\n\nclass CustomUserCreationForm(UserCreationForm):\n class Meta(UserCreationForm):\n model = CustomUser\n fields = ('username', 'email')\n\n\nclass CustomUserChangeForm(UserChangeForm):\n class Meta:\n model = CustomUser\n fields = ('username', 'email')\n\n\nclass SearchForm(forms.Form):\n\n Sentence = forms.CharField(\n initial='',\n label='発話',\n required=False,\n )\n\n Tag = forms.CharField(\n initial='',\n label='タグ',\n required=False,\n )\n\n Score = forms.CharField(\n initial='',\n label='スコア',\n required=False, # 必須ではない\n )\n\n\nclass PostForm(forms.ModelForm):\n\n class Meta:\n model = Post\n fields = ()","sub_path":"search/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"449516623","text":"from django.shortcuts import render\nfrom django.http import HttpResponseRedirect, Http404\nfrom django.urls import reverse\nfrom .forms import TopicForm, EntryForm\nfrom .models import Topic, Entry\nfrom django.contrib.auth.decorators import login_required\n\n# Create your views here.\ndef index(request):\n \"\"\"the main page of learning log\"\"\"\n return render(request,'learning_logs/index.html')\n\n# @login_required(login_url='/login/')\n# @login_required()\n@login_required\ndef topics(request):\n # print(request,'test')\n \"\"\"display all the topics\"\"\"\n # topics = Topic.objects.order_by('date_added')\n topics = Topic.objects.filter(owner=request.user).order_by('date_added')\n context = {'topics': topics}\n return render(request,'learning_logs/topics.html', context)\n\n@login_required\ndef topic(request,topic_id):\n \"\"\"display the single topic and all the related item\"\"\"\n topic = Topic.objects.get(id=topic_id)\n # confirm if the topic belongs to owner\n if topic.owner != request.user:\n raise Http404\n entries = topic.entry_set.order_by('-date_added')\n context = {'topic':topic,'entries':entries}\n return render(request,'learning_logs/topic.html',context)\n\n@login_required\ndef new_topic(request):\n \"\"\"add new topic\"\"\"\n if request.method != 'POST':\n #not yet submited data and create new one\n form = TopicForm()\n else:\n #To process data when the post submit the data\n form = TopicForm(request.POST)\n if form.is_valid():\n new_topic = form.save(commit=False)\n new_topic.owner = request.user\n new_topic.save()\n # form.save()\n return HttpResponseRedirect(reverse('learning_logs:topics'))\n context = {'form':form}\n return render(request, 'learning_logs/new_topic.html',context)\n\n@login_required\ndef new_entry(request,topic_id):\n \"\"\"Add new item in one specific topic\"\"\"\n topic = Topic.objects.get(id = topic_id)\n\n if request.method != 'POST':\n # create empty form due to not submit data\n form = EntryForm\n else:\n # process data which is submited by POST\n form = EntryForm(data=request.POST)\n if form.is_valid():\n new_entry = form.save(commit=False)\n new_entry.topic = topic\n new_entry.save()\n return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic_id]))\n context = {'topic':topic,'form':form}\n return render(request,'learning_logs/new_entry.html',context)\n\n@login_required\ndef edit_entry(request,entry_id):\n \"\"\"edit the exist item\"\"\"\n entry = Entry.objects.get(id = entry_id)\n topic = entry.topic\n if topic.owner != request.user:\n raise Http404\n\n if request.method != 'POST':\n form = EntryForm(instance=entry)\n else:\n #process data which is submited by POST\n form = EntryForm(instance=entry, data=request.POST)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic.id]))\n\n context = {'entry':entry,'topic':topic,'form':form}\n return render(request,'learning_logs/edit_entry.html',context)\n","sub_path":"learning_logs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"504159788","text":"#!/usr/bin/env python3\n\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport os\n\nundefined = None\nsavefile = \"mnist.ckpt\"\n\n# main :: IO Int\ndef main():\n mnistdata = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n sess = tf.Session()\n\n x = tf.placeholder(tf.float32, [None, 784])\n w = tf.Variable(tf.zeros([784, 10]))\n b = tf.Variable(tf.zeros([10]))\n y = tf.nn.softmax(tf.matmul(x, w) + b)\n\n y_ = tf.placeholder(tf.float32, [None, 10])\n cross_entropy = -tf.reduce_sum(y_ * tf.log(y))\n train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)\n\n # 初期化\n sess.run(tf.initialize_all_variables())\n if os.path.isfile(savefile):\n print(\"load\")\n tf.train.Saver().restore(sess, savefile)\n else:\n # 実行\n for i in range(1000):\n batch_xs, batch_ys = mnistdata.train.next_batch(100)\n train_step.run({x: batch_xs, y_: batch_ys}, session=sess)\n\n correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) # :: boolean\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n print(\"精度\")\n print(sess.run(accuracy, feed_dict={x: mnistdata.test.images, y_: mnistdata.test.labels}))\n tf.train.Saver().save(sess, savefile)\n return 0\n\nif __name__ == \"__main__\" :\n exit(main())\n\n# vim:fenc=utf-8 ff=unix ft=python ts=4 sw=4 sts=4 si et fdm=indent fdl=0 fdn=1:\n# vim:cinw=if,elif,else,for,while,try,except,finally,def,class:\n","sub_path":"tf/mnist.py","file_name":"mnist.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"55911891","text":"from lxml import html\nimport requests\n\npage = requests.get('https://www.guru99.com/software-testing.html')\ntree = html.fromstring(page.content)\n\nfor i in range(1,18):\n for j in range(1,25):\n titles = tree.xpath('//table[' + str(i) + ']/tr[' + str(j) + ']/td[2]/text()')\n if titles != []:\n print(titles[0])","sub_path":"WebScraping.py","file_name":"WebScraping.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"247194496","text":"# エラー対処\n#===================================================================================================================================\n# SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \\UXXXXXXXX escape\n# ※Windowsでパスを指定する時に気を付けること\n# エラーの原因としては、パスなどの文字列に“\\”が使われることによりその文字列がエスケープシーケンスとしてみなされているからです。\n# https://office54.net/python/python-unicode-error\n\n\n#===================================================================================================================================\n#ファイルの存在を確認する\nimport os\nif(os.path.exists(r\"C:\\Users\\utkn009\\Desktop\\HBSCA104IM03.pdf\")):\n print(\"ある\")\nelse:\n print(\"ファイルない\")\n\n#===================================================================================================================================\n#PDFをcsvに変換\n#tabula documents\n#https://tabula-py.readthedocs.io/en/latest/tabula.html\n#同名のファイルは上書きする\n\nimport pandas as pd\nimport tabula\ntabula.convert_into(r\"\\\\126.0.0.42\\代_共通\\KAMBARA\\ARRIVAL NOTICE\\KCRA0104E\\HBSCA104IM03.pdf\", r\"C:\\Users\\utkn009\\Desktop\\HBSCA104IM03.csv\", stream=True, output_format=\"csv\", pages=\"all\")\n\n#===================================================================================================================================\n#ファイル名一覧\nimport os\n\npath = r'\\\\126.0.0.42\\代_共通\\KAMBARA\\ARRIVAL NOTICE\\KCRA0104E'\nfiles = os.listdir(path)\nprint(files)\n\n#===================================================================================================================================\n#ブラウザを開いて表示\n\nimport webbrowser\nwebbrowser.open(\"http://fs2/scripts/cbag/ag.exe?page=MailSend&fid=&cp=el&flagged=\")\n\n#===================================================================================================================================\n#サイボウズでメール送信サンプル\n\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.select import Select\nimport time\n\n#WebDrivwr起動\ndriver = webdriver.Chrome(r\"\\\\126.0.0.42\\個人(フル)\\田中智也\\1.田中\\chromedriver_win32\\chromedriver.exe\")\n#最大化\ndriver.maximize_window()\n#サイボウズの社外メール作成のURL入力\ndriver.get(\"http://fs2/scripts/cbag/ag.exe?page=MailSend&fid=&cp=el&flagged=\")\n#_IDが表示されるまでwait\nWebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.NAME, '_ID')))\n#「切り替える」のxpathをクリック\ndriver.find_element_by_xpath('/html/body/div[2]/div[1]/div/table/tbody/tr/td/center/div/table/tbody/tr[2]/td[2]/div/div/table[2]/tbody/tr[2]/td/table/tbody/tr[2]/td/a').click()\n#セレクト要素の処理\nselect_element = driver.find_element_by_name(\"Group\")\nselect_object = Select(select_element)\nselect_object.select_by_value(\"170\")\n#「切り替える」をnameでクリック\ndriver.find_element_by_name(\"Submit\").click()\n#セレクト要素の処理\nselect_element = driver.find_element_by_name(\"_ID\")\nselect_object = Select(select_element)\nselect_object.select_by_value(\"1157\")\n#パスワード入力\ndriver.find_element_by_name(\"Password\").send_keys(\"0117\")\n#「ログイン」をクリック\ndriver.find_element_by_name(\"Submit\").click()\n#「送信」ボタンを押せるようになるまでwait\nWebDriverWait(driver, 10).until(EC.element_to_be_clickable( (By.NAME,\"Submit\")) )\n#アドレスを宛先に入力 サイボウズの仕様上\",\"で区切った文字を一気に挿入は不可\nToAds = ['\"gum@kambarakisen.com\" ', '\"Gaojianping\" ', '\"HD group\" ', '\"Chenchenggang\" ', '\"CONTAINER\" ', '\"Zhuli\" ']\nfor ToAd in ToAds:\n driver.find_element_by_xpath(\"/html/body/div[2]/div[4]/div/form/table/tbody/tr/td/table/tbody/tr[2]/td/div/div[1]/div/table/tbody/tr[3]/td/div/ul/li/textarea\").send_keys(ToAd)\n driver.find_element_by_xpath(\"/html/body/div[2]/div[4]/div/form/table/tbody/tr/td/table/tbody/tr[2]/td/div/div[1]/div/table/tbody/tr[3]/td/div/ul/li/textarea\").send_keys(\",\")\n#アドレスをCCに入力 サイボウズの仕様上\",\"で区切った文字を一気に挿入は不可\nCCAds = ['kawahara@nagaij.co.jp']\nfor CCAd in CCAds:\n driver.find_element_by_xpath(\"/html/body/div[2]/div[4]/div/form/table/tbody/tr/td/table/tbody/tr[2]/td/div/div[1]/div/table/tbody/tr[4]/td/div/ul/li/textarea\").send_keys(CCAd)\n driver.find_element_by_xpath(\"/html/body/div[2]/div[4]/div/form/table/tbody/tr/td/table/tbody/tr[2]/td/div/div[1]/div/table/tbody/tr[4]/td/div/ul/li/textarea\").send_keys(\",\")\n#表題入力\ndriver.find_element_by_name(\"Subject\").send_keys(\"INVENTRY REPORT IMARI 16th\")\n#\"\\n\"で区切りながら本文入力\ninputtext = \"Dear Chen san\\nDear Sandra san\\n\\nGood day,\\nPls find attached file Inventry report IMARI\\nPls advise me, Load quantity of KORA-0111W.\\nIt may increase or decrease in number from these prospects.\\nI will report these numbers after confirmation.\\n\\nTks & B.rgds\\nIMARI AGENT/JAPAN\\nTanaka\"\nfor part in inputtext.split('\\n'):\n driver.find_element_by_id(\"Data\").send_keys(part)\n driver.find_element_by_id(\"Data\").send_keys(\"\\n\")\n#セレクト要素の処理 署名を(なし)に\nselect_element = driver.find_element_by_name(\"SigID\")\nselect_object = Select(select_element)\nselect_object.select_by_visible_text('(なし)')\n#ファイルを添付 ※ファイル名をsend_keysで送る\nAttachedFiles = [r\"\\\\126.0.0.42\\業務_共通\\神原荷役作業\\Booking_List_IMARI 2020.xls\",r\"\\\\126.0.0.42\\業務_共通\\神原荷役作業\\IMARI INVENTRY REPORT.xlsx\"]\nfor File in AttachedFiles:\n driver.find_element_by_id(\"files1\").send_keys(File)\n\n#参考資料\n#\n#.find_element_by_xpathと.find_element(s)_by_xpath\n#https://www.366service.com/jp/qa/ab49bd049dbd66089443a84c8aee20d5\n\n#[EC.visibility_of_element_located((By.で指定できる要素一覧]\n# ID\n# XPATH\n# LINK_TEXT\n# PARTIAL_LINK_TEXT\n# NAME\n# TAG_NAME\n# CLASS_NAME\n# CSS_SELECTOR\n\n#選択要素の操作\n#https://www.selenium.dev/documentation/ja/support_packages/working_with_select_elements/\n\n#===================================================================================================================================\n#","sub_path":"CodeCollection.py","file_name":"CodeCollection.py","file_ext":"py","file_size_in_byte":6638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"434068881","text":"# -*- coding: utf-8 -*-\nimport os.path\nimport pydot\n\nepsilon = None\n\nclass Utils:\n @staticmethod\n def ensureDictHasKey(d, key, value):\n if not d.has_key(key):\n d[key] = value\n\nclass FA:\n def __init__(self):\n self.initialState = 0\n self.finalStates = set()\n self.transitions = {} #ddl = {state : {symbol : [state, ...]}, ...}\n self.stateCount = 0\n self.epsilonIncedentStates = set()\n\n def __len__(self):\n return self.stateCount\n\n def copyStatesWithStep(self, fa, step):\n for state_1 in fa.transitions.keys():\n trans = fa.transitions[state_1]\n state_with_step = state_1 + step\n self.transitions[state_with_step] = {}\n for symbol in trans.keys():\n self.transitions[state_with_step][symbol] = [e + step for e in trans[symbol]]\n\n for s in fa.epsilonIncedentStates:\n self.epsilonIncedentStates.add(s + step)\n\n#Конструктор Томпсона для построение NFA по регулярному выражению\nclass TomphsonCtor:\n #Регулярное выражение состоит из одного символа\n def CreateFaSymbol(self, symbol):\n fa = FA()\n fa.initialState = 0\n fa.finalStates.add(1)\n fa.transitions[0] = {symbol : [1]}\n fa.stateCount = 2\n return fa\n\n #Операция или (a|b)\n def CreateFaOr(self, fa_1, fa_2):\n fa = FA()\n f_1_step = 1\n fa.copyStatesWithStep(fa_1, f_1_step);\n f_2_step = len(fa_1) + 1\n fa.copyStatesWithStep(fa_2, f_2_step);\n fa.initialState = 0\n fa.transitions[0] = {epsilon : [1, len(fa_1) + 1]}\n f2_first = len(fa_1) + 1\n final = len(fa_1) + len(fa_2) + 1\n fa.finalStates.add(final)\n for f in fa_1.finalStates:\n if not fa.transitions.has_key(f + f_1_step):\n fa.transitions[ f + f_1_step ] = {}\n if not fa.transitions[ f + f_1_step ].has_key(epsilon):\n fa.transitions[ f + f_1_step ][epsilon] = []\n fa.transitions[ f + f_1_step ][epsilon].append(final)\n\n for f in fa_2.finalStates:\n if not fa.transitions.has_key(f + f_2_step):\n fa.transitions[ f + f_2_step ] = {}\n if not fa.transitions[f + f_2_step].has_key(epsilon):\n fa.transitions[f + f_2_step][epsilon] = []\n fa.transitions[ f + f_2_step ][epsilon].append(final)\n fa.stateCount = final + 1\n fa.epsilonIncedentStates.add(1)\n fa.epsilonIncedentStates.add(f2_first)\n fa.epsilonIncedentStates.add(final)\n return fa\n\n def CreateFaConcat(self, fa_1, fa_2):\n fa = FA()\n f_1_step = 1\n fa.copyStatesWithStep(fa_1, f_1_step);\n f_2_step = len(fa_1) + 1\n fa.copyStatesWithStep(fa_2, f_2_step);\n fa.initialState = 0\n fa.transitions[0] = {epsilon : [1]}\n final = len(fa_1) + len(fa_2) + 1\n f2_first = len(fa_1) + 1\n fa.finalStates.add(final)\n for f in fa_1.finalStates:\n if not fa.transitions.has_key( f + f_1_step ):\n fa.transitions[ f + f_1_step ] = {}\n if not fa.transitions[ f + f_1_step ].has_key(epsilon):\n fa.transitions[ f + f_1_step ][epsilon] = []\n fa.transitions[ f + f_1_step ][epsilon].append(f2_first)\n\n for f in fa_2.finalStates:\n if not fa.transitions.has_key(f + f_2_step):\n fa.transitions[ f + f_2_step ] = {}\n if not fa.transitions[f + f_2_step].has_key(epsilon):\n fa.transitions[f + f_2_step][epsilon] = []\n fa.transitions[ f + f_2_step ][epsilon].append(final)\n\n fa.epsilonIncedentStates.add(1)\n fa.epsilonIncedentStates.add(f2_first)\n fa.epsilonIncedentStates.add(final)\n fa.stateCount = final + 1\n return fa\n\n def CreateFaIterPositive(self, fa_r):\n fa = FA()\n step = 1\n fa.copyStatesWithStep(fa_r, step)\n final = len(fa_r) + 1\n fa.transitions[0] = {epsilon : [1]}\n fa.finalStates = [final]\n for f in fa_r.finalStates:\n if not fa.transitions.has_key(f + step):\n fa.transitions[ f + step ] = {}\n if not fa.transitions[f + step].has_key(epsilon):\n fa.transitions[f + step][epsilon] = []\n fa.transitions[ f + step ][epsilon].append(1)\n fa.transitions[ f + step ][epsilon].append(final)\n fa.stateCount = len(fa_r) + 2\n fa.epsilonIncedentStates.add(1)\n fa.epsilonIncedentStates.add(final)\n return fa\n\n def CreateFaIter(self, fa_r):\n fa = self.CreateFaIterPositive(fa_r)\n fa.transitions[0][epsilon].append(len(fa) - 1)\n return fa\n\n# | . * + ( )\nclass RPN:\n def __init__(self):\n self.opers = ('|' , '.', '*', '+')\n\n def Transform2ReversePolishNotation(self, seq):\n stack = []\n priors = {'(' : 0, '|' : 2 , '.' : 3, '*' : 4, '+' : 4}\n opers = priors.keys()\n out = ''\n for s in seq:\n if s == '(':\n stack.append(s)\n elif s == ')':\n s = ''\n while (s != '(' and len(stack) != 0):\n s = stack.pop()\n out += s\n if (s != '('):\n return None\n out = out[:-1]\n elif s in opers:\n if (len(stack) != 0):\n if (priors[s] >= priors[stack[len(stack) - 1]]):\n stack.append(s)\n else:\n while ( (len(stack) != 0 ) and (priors[s] < priors[stack[len(stack) - 1]])):\n out += stack.pop()\n stack.append(s)\n else:\n stack.append(s)\n else:\n out += s\n while(len(stack) != 0):\n out += stack.pop()\n return out\n\n def HandleRPN(self, rpn_str):\n t = TomphsonCtor()\n stack = []\n index = 0\n for s in rpn_str:\n if s in self.opers:\n if s in ('|', '.') :\n if s == '|':\n f = t.CreateFaOr\n else:\n f = t.CreateFaConcat\n fa_2 = stack.pop()\n fa_1 = stack.pop()\n stack.append(f(fa_1, fa_2))\n elif s == '*':\n stack.append(t.CreateFaIter(stack.pop()))\n elif s == '+':\n stack.append(t.CreateFaIterPositive(stack.pop()))\n else:\n stack.append(t.CreateFaSymbol(s))\n if (len(stack) != 1):\n return None\n fa = stack.pop()\n return fa\n\n def BuildFa(self, regexp):\n return self.HandleRPN(self.Transform2ReversePolishNotation(regexp))\n\nclass Determinisator:\n def Determine(self, fa):\n if len(fa.epsilonIncedentStates) != 0:\n faNoEps = self.RemoveEpsilonTransitions(fa)\n else:\n faNoEps = fa\n detFa = self.GetDetFa(faNoEps)\n return detFa\n\n def RemoveEpsilonTransitions(self, fa):\n detFa = FA()\n # В эти состояния есть не epsilon переходы\n detStates = [x for x in range(0, len(fa) - 1) if x not in fa.epsilonIncedentStates]\n detTransitions = {}\n detFinalStates = set()\n for state in detStates:\n reachSet = self.DefineReachSet(fa, state)\n if (state in fa.finalStates) or (fa.finalStates & reachSet):\n detFinalStates.add(state)\n for r in reachSet:\n if fa.transitions.has_key(r):\n for symbol in fa.transitions[r].keys():\n if symbol != epsilon:\n Utils.ensureDictHasKey(detTransitions, state, {})\n Utils.ensureDictHasKey(detTransitions[state], symbol, [])\n detTransitions[state][symbol].extend(fa.transitions[r][symbol])\n stateMapping = dict(zip(detStates, range(len(detStates))))\n detFa.stateCount = len(detStates)\n detFa.finalStates = [stateMapping[f] for f in detFinalStates]\n for s1 in detTransitions:\n s1_n = stateMapping[s1]\n Utils.ensureDictHasKey(detFa.transitions, s1_n, {})\n for symbol in detTransitions[s1]:\n detFa.transitions[s1_n][symbol] = [stateMapping[s2] for s2 in detTransitions[s1][symbol]]\n return detFa\n\n def DefineReachSet(self, fa, state):\n reachSet = set()\n currReachSet = set([state])\n prevStepReachSetSize = 1\n while (len(reachSet) != prevStepReachSetSize):\n prevStepReachSetSize = len(reachSet)\n nextReachSet = set()\n for s1 in currReachSet:\n if fa.transitions.has_key(s1) and fa.transitions[s1].has_key(epsilon):\n for s2 in fa.transitions[s1][epsilon]:\n if s2 not in reachSet:\n reachSet.add(s2)\n nextReachSet.add(s2)\n currReachSet = nextReachSet\n return reachSet\n\n def GetDetFa(self, faWithoutEpsilon):\n fa = faWithoutEpsilon\n detFa = FA()\n detFa.initialState = 0\n initialSet = (0,)\n stateMapping = {initialSet : 0}\n leftStates = [initialSet]\n while len(leftStates) != 0:\n leftStates_new = []\n for state_set in leftStates:\n s1_n = stateMapping[tuple(state_set)]\n for s in state_set:\n if s in fa.finalStates:\n detFa.finalStates.add(s1_n)\n break\n Utils.ensureDictHasKey(detFa.transitions, s1_n, {})\n\n state_set_symbols = set()\n for s in state_set:\n if fa.transitions.has_key(s):\n state_set_symbols.update(fa.transitions[s].keys())\n for symbol in state_set_symbols:\n newState = set()\n for s1 in state_set:\n if fa.transitions.has_key(s1) and symbol in fa.transitions[s1].keys():\n newState.update(fa.transitions[s1][symbol])\n if len(newState) != 0:\n state_tup = tuple(newState)\n if stateMapping.has_key(state_tup): #Либо берем только что добавленное состояние, либо то которое уже было\n s2_n = stateMapping[state_tup]\n else:\n leftStates_new.append(newState)\n s2_n = len(stateMapping)\n stateMapping[state_tup] = len(stateMapping)\n Utils.ensureDictHasKey(detFa.transitions[s1_n], symbol, s2_n)\n leftStates = leftStates_new\n detFa.stateCount = len(detFa.transitions.keys())\n return detFa\n\nclass Minimisator:\n def Minimize(self, fa):\n st2cl = {}\n initialiClass0 = set()\n initialiClass1 = set()\n for f in xrange(len(fa)): #0 - разбиение\n if f in fa.finalStates:\n st2cl[f] = 0\n initialiClass0.add(f)\n else:\n st2cl[f] = 1\n initialiClass1.add(f)\n hasNew = True\n classes = [tuple(initialiClass0), tuple(initialiClass1)]\n while (hasNew):\n classes_size = len(classes)\n new_classes = []\n for c in classes:\n new_classes.extend(self.SplitClass(fa, c, st2cl))\n #пересчитываем st2cl\n st2cl = self.RecalcState2ClassMapping(new_classes)\n hasNew = classes_size != len(new_classes)\n classes = new_classes\n\n if (len(fa) == len(classes)):\n return fa\n\n minFa = FA()\n cl2st = {}\n i = 0\n for c in classes:\n cl2st[c] = i\n i += 1\n\n foundInitState = False\n minFa.stateCount = len(classes)\n for c in classes:\n oldState = c[0]\n newState = cl2st[c]\n\n if (not foundInitState) and (fa.initialState in c):\n minFa.initialState = newState\n foundInitState = True\n\n if not fa.finalStates.isdisjoint(c):\n minFa.finalStates.add(newState)\n\n Utils.ensureDictHasKey(minFa.transitions, newState, {})\n for symbol in fa.transitions[oldState].keys():\n minFa.transitions[newState][symbol] = st2cl[fa.transitions[oldState][symbol]]\n\n #return self.changeStatesNames(minFa)\n return minFa\n\n def changeStatesNames(self, fa):\n correctedFa = FA()\n for startState in fa.transitions.keys():\n correctedFa.transitions[len(fa) - startState - 1] = {}\n trans = fa.transitions[startState]\n for symbol in trans.keys():\n e = trans[symbol]\n correctedFa.transitions[len(fa) - startState - 1][symbol] = len(fa) - 1 - e\n\n correctedFa.initialState = len(fa)-1-fa.initialState\n correctedFa.finalStates = [len(fa) - 1 - e for e in fa.finalStates]\n correctedFa.stateCount = fa.stateCount\n return correctedFa\n\n def SplitClass(self, fa, _class, st2cl):\n if len(_class) == 1:\n return [_class]\n new_classes = []\n trans2st = {}\n for s1 in _class:\n t = fa.transitions[s1]\n transDefinition = []\n for symbol in t.keys():\n transDefinition.append((symbol, st2cl[t[symbol]]))\n transDefinition = tuple(transDefinition)\n if trans2st.has_key(transDefinition):\n trans2st[transDefinition].append(s1)\n else:\n trans2st[transDefinition] = [s1]\n\n return [tuple(x) for x in trans2st.values()]\n\n def RecalcState2ClassMapping(self, classes):\n st2cl = {}\n class_index = 0\n for c in classes:\n for s in c:\n st2cl[s] = class_index\n class_index += 1\n return st2cl\n\nclass FaSimulator:\n def Simulate(self, fa, seq):\n state = fa.initialState\n path = [state]\n for c in seq:\n if fa.transitions[state].has_key(c):\n state = fa.transitions[state][c]\n path.append(state)\n else:\n return (False, path)\n if state in fa.finalStates:\n return (True, path)\n else:\n return (False, path)\n\nclass FaGraphVizExporter:\n def convert(self, fa, list):\n g = pydot.Dot(graph_type='digraph')\n map = {}\n for c in xrange(fa.stateCount):\n if fa.initialState == c:\n map[c] = pydot.Node('%d' % (c,), shape='doublecircle')\n g.add_node(map[c])\n if c in fa.finalStates:\n map[c] = pydot.Node('%d' % (c,), shape='doublecircle')\n g.add_node(map[c])\n map[c] = pydot.Node('%d' % (c,))\n g.add_node(map[c])\n for s1 in fa.transitions.keys():\n t = fa.transitions[s1]\n for symbol in t.keys():\n if list:\n toList = t[symbol]\n for toPnt in toList:\n g.add_edge(pydot.Edge(map[s1], map[toPnt], label=symbol))\n else:\n g.add_edge(pydot.Edge(map[s1], map[t[symbol]], label=symbol))\n return g\n\n def export(self, fa, path, list=False):\n g = self.convert(fa, list)\n if os.path.exists(path):\n os.remove(path)\n g.write_png(path)\n\n\nclass GraphConsoleExporter:\n \n def append(self, fa, name): \n output = self.formOutput(fa, name)\n self.consoleExport(output)\n self.fileExport(output, '.\\out\\out.txt', \"a\")\n \n def export(self, fa, name):\n output = self.formOutput(fa, name)\n self.consoleExport(output)\n self.fileExport(output, '.\\out\\out.txt', \"w\")\n \n def fileExport(self, output, filename, param):\n try:\n f = open(filename, param)\n try:\n for str in output: \n f.write(str + '\\n')\n finally:\n f.close()\n except IOError:\n pass\n\n def consoleExport(self, output):\n for str in output: \n print(str)\n \n def formOutput(self, fa, name):\n initialstates = []\n finalstates = []\n states = []\n output = []\n for c in xrange(fa.stateCount):\n if fa.initialState == c:\n initialstates.append(c)\n if c in fa.finalStates:\n finalstates.append(c)\n states.append(c)\n output.append('initialstates: ' + str(initialstates))\n output.append('finalstates: ' + str(finalstates))\n output.append('states: ' + str(states))\n \n output.append('----------------- ' + name + ' ---------------------')\n for s1 in fa.transitions.keys():\n t = fa.transitions[s1]\n for symbol in t.keys():\n strsym = str(symbol)\n if strsym == 'None':\n strsym = 'N'\n output.append(str(s1) + ' --(' + strsym + ')--> ' + str(t[symbol]))\n output.append('-------------------------------------------------')\n output.append('')\n output.append('')\n \n return output\n\nclass App:\n def __init__(self):\n self.rpn = RPN()\n self.det = Determinisator()\n self.min = Minimisator()\n self.sim = FaSimulator()\n self.exp = GraphConsoleExporter()\n self.graph = FaGraphVizExporter()\n\n def main(self):\n #try:\n \"\"\"\n\n\n \"\"\"\n regexp = raw_input('Put your regular expression:')\n print('Parsing with Reverse Polish Notation, building automate...\\n')\n fa = self.rpn.BuildFa(regexp)\n self.exp.export(fa, 'INITIAL FA')\n #self.graph.export(fa, '.\\out\\initial.png', True)\n print('Determining automate...\\n')\n detFa = self.det.Determine(fa)\n self.exp.append(detFa, 'DETERMINED FA')\n self.graph.export(detFa, '.\\out\\determined.png')\n print('Minimizing automate...\\n')\n minFa = self.min.Minimize(detFa)\n self.exp.append(minFa, 'MINIMIZED FA')\n self.graph.export(minFa, '.\\out\\minimized.png')\n print('The automate is successfully built. Input chain to parse or an empty chain to finish work:\\n')\n seq = raw_input('Chain:')\n while (seq != ''):\n result = self.sim.Simulate(minFa, seq)\n if (result[0]):\n print('Parsed! The parsing trac: %s\\n' % (result[1], ))\n else:\n print('Error char sequence! The parsing trac: %s\\n' % (result[1], ))\n seq = raw_input('Chain:')\n\n #except Exception as ex:\n # print(u'Ошибка', ex)\n\n'''\n(a|b)*.(c.d)+\n(a|b|c|d|e|f|g).(4|5|6|7|8|9)*\n'''\nApp().main()\n","sub_path":"labs/lab1/src/lab1.py","file_name":"lab1.py","file_ext":"py","file_size_in_byte":19305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"589710406","text":"import Replace_Module as RM\r\nimport openpyxl as px\r\nimport pandas as pd\r\nfrom pandas import ExcelWriter\r\nfrom pandasql import sqldf\r\n\r\nurl = \"DD.xlsx\"\r\nxl = pd.read_excel(url, \"Sheet1\", 0)\r\npysqldf = lambda q: sqldf(q, globals())\r\n# Fill in Data .\r\nwb = px.load_workbook(url)\r\nws = wb.get_sheet_by_name(\"Sheet1\")\r\nsheet = wb.active\r\n\r\ndef main():\r\n\r\n\r\n\r\n def group():\r\n print(humanInput)\r\n print(pysqldf(\r\n \"Select [ID Number],[First Name], [Last Name],[Gender],[Instrument],[Talent], [Status] from xl where [Status]='A' and [Band]=\"+humanInput+\" order by [ID Number]\"))\r\n RM.replace_module()\r\n wb.close()\r\n\r\n while True:\r\n humanInput = input ('\\n'.join(['Select band for replacement: ','1: Band 1', '2: Band 2', '3: Band 3','4: Band 4','5: Band 5','6: Band 6','7: Band 7','8: Band 8','0: Exit Program', '']))\r\n while humanInput not in ['1','2','3','4','5','6','7','8','0']:\r\n print ('Invalid Input')\r\n humanInput = input ('\\n'.join(['Select band for replacement: ','1: Band 1', '2: Band 2', '3: Band 3','4: Band 4','5: Band 5','6: Band 6','7: Band 7','8: Band 8','0: Exit Program', '']))\r\n if humanInput in ['1','2','3','4','5','6','7','8']:\r\n group()\r\n wb.close()\r\n break\r\n elif humanInput in [\"0\"]:\r\n break\r\n","sub_path":"Milestone 2.0/Replacement Module/Group_BA.py","file_name":"Group_BA.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"551224387","text":"'''\nAllows the user to parse through a text file. Where something like control-F\nwill show you results for where something appears in a document, this will show\nany mention of a specific word in context. After loading in a given text file,\nthis will look for any mention of word(s) and give the associated context in\nwhich they were used.\n\nAuthor: Nat Hawkins\nDate: 25 April, 2017\n'''\n\n#Opens the text file and reads in the line of text.\ntext = open('test.txt', \"r\").read()\n\n#This will strip away any kind of unnnecessary punctuation in sentencing.\n#If there is any additional punctuation or symbols you wish to ignore, they can\n#be added in the form of text = text.replace(\"what you want ignored\",\"\").\ntext = text.replace(\",\", \"\")\ntext = text.replace(\"?\", \".\")\ntext = text.replace(\"!\", \".\")\ntext = text.replace(\"[\",\"\")\ntext = text.replace(\"]\",\"\")\ntext = text.replace(\"(\",\"\")\ntext = text.replace(\")\",\"\")\ntext = text.replace(\"{\",\"\")\ntext = text.replace(\"}\",\"\")\n\n#Creates an array of the document. Splits based on location of the periods.\n#Appended above with text replacing commands.\nsplit = text.split('.')\n\n#Defines the process of actually searching for the word and pulling out\n#associated sentences.\ndef search_words(word, sentences):\n for i in sentences:\n cleaned = i.lower()\n words = cleaned.split()\n if word in words:\n print(i,\".\")\n\n#Put the words in the array in the form of 'strings' and search away!\nlist_of_words =[] #use lower case for words\nfor something in list_of_words:\n search_words(something,split)\n","sub_path":"Python Codes/Text Parser/text_parser.py","file_name":"text_parser.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"197353793","text":"from Package.Rectangle import Rectangle\r\nfrom Package.Circle import Circle\r\nfrom Package.Square import Square\r\n\r\ndef Main():\r\n Rectangle1 = Rectangle(\"белый\", 10, 20)\r\n Circle1 = Circle (\"синий\", 10)\r\n Square1 = Square (\"красный\", 10)\r\n print(Rectangle1)\r\n print(Circle1)\r\n print(Circle1)\r\n\r\nif __name__ == \"__main__\":\r\n Main()","sub_path":"Python_Lab2/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"108363253","text":"import time\nimport pandas as pd\nimport numpy as np\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\n\ndef get_filters():\n \"\"\"\n Asks user to specify a city, month, and day to analyze.\n\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('Hello! Let\\'s explore some US bikeshare data!')\n\n #get user input for city (chicago, new york city, washington).\n cities = ['chicago', 'new york city', 'washington']\n city = str(input('Would you like to see data for Chicago, New York City, or Washington? ')).lower()\n while city not in cities:\n city = str(input('Please write city filter: Chicago, New York City, or Washington ')).lower()\n\n #get filter for the data by month, day, or not at all\n filters = ['all', 'month', 'day']\n filter = str(input('Would you like to filter the data by month, day, or not at all? Type \"all\" for no time filter. ')).lower()\n while filter not in filters:\n filter = str(input('Please write filter: month, day, or none. ')).lower()\n\n month = 'all'\n day = 'all'\n #get user input for month (all, january, february, ... , june)\n if filter == 'month':\n months = ['all', 'january', 'february', 'march', 'april', 'may', 'june']\n month = str(input('Which month - January, February, March, April, May, or June? ')).lower()\n while month not in months:\n month = str(input('Please write month filter: January, February, March, April, May, or June ')).lower()\n\n #get user input for day of week (all, monday, tuesday, ... sunday)\n elif filter == 'day':\n days = ['all', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']\n day = str(input('Which day - Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday? ')).lower()\n while day not in days:\n day = str(input('Please write day filter: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday ')).lower()\n\n\n print('-'*40)\n return city, month, day\n\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n df = pd.read_csv(CITY_DATA[city])\n # convert the Start Time column to datetime\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n # extract month, day of week and hour from Start Time to create new columns\n df['month'] = df['Start Time'].dt.month\n df['day_of_week'] = df['Start Time'].dt.weekday_name\n df['hour'] = df['Start Time'].dt.hour\n\n # filter by month if applicable\n if month != 'all':\n # use the index of the months list to get the corresponding int\n months = ['all', 'january', 'february', 'march', 'april', 'may', 'june']\n month = months.index(month)\n\n # filter by month to create the new dataframe\n df = df[df['month'] == month]\n\n # filter by day of week if applicable\n if day != 'all':\n # filter by day of week to create the new dataframe\n df = df[df['day_of_week'] == day.title()]\n\n return df\n\n\ndef time_stats(df):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n start_time = time.time()\n\n # display the most common month\n most_popular_month = df['month'].mode()[0]\n print('The most popular month is', most_popular_month)\n\n # display the most common day of week\n most_popular_weekday_name = df['day_of_week'].mode()[0]\n print('The most popular day of the week is ', most_popular_weekday_name)\n\n # display the most common start hour\n most_popular_hour = df['hour'].mode()[0]\n print('The most popular hour is', most_popular_hour)\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\n\ndef station_stats(df):\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n\n # display most commonly used start station\n most_popular_start_station = df['Start Station'].mode()[0]\n print('The most cocommonly used start station is', most_popular_start_station)\n\n # display start station count\n all_start_station_count = df['Start Station'].value_counts()\n print('All start station counts: ', all_start_station_count)\n\n # display most commonly used end station\n most_popular_end_station = df['End Station'].mode()[0]\n print('The most commonly used end station is', most_popular_end_station)\n\n # display most frequent combination of start station and end station trip\n df['Start_End'] = df['Start Station'] + ' - ' + df['End Station']\n most_popular_start_end_combination = df['Start_End'].mode()[0]\n print('The most frequent combination of start station and end station trip is:', most_popular_start_end_combination)\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n print('\\nCalculating Trip Duration...\\n')\n start_time = time.time()\n\n # display total travel time\n total_travel_time = df['Trip Duration'].sum()\n print('Total travel time:', total_travel_time)\n\n # display mean travel time\n mean_travel_time = df['Trip Duration'].mean()\n print('Mean travel time', mean_travel_time)\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef user_stats(df):\n \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n\n # Display counts of user types\n user_types = df['User Type'].value_counts()\n print('counts of user types:', user_types)\n\n if \"Gender\" in df.columns:\n # Display counts of gender\n user_gender = df['Gender'].value_counts()\n print('User gender counts: ', user_gender)\n # Display earliest year of birth\n earliest_yob = df['Birth Year'].min()\n print('The earliest year of birth:', earliest_yob)\n # Display most recent year of birth\n recent_yof = df['Birth Year'].max()\n print('The most recent year of birth:', recent_yof)\n # Display most common year of birth\n common_yob = df['Birth Year'].mode()[0]\n print('The most common year of birth:', common_yob )\n\n else:\n print('We do not have user gender and year of birth data for this city')\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef main():\n while True:\n city, month, day = get_filters()\n df = load_data(city, month, day)\n\n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n\n # Display some raw data if applicable\n start = 0\n count = 5\n raw_data = input('\\nWould you like to see 5 lines of raw data? Enter yes or no.\\n')\n while raw_data.lower() == 'yes':\n print('Some raw data', df.iloc[start : count])\n raw_data = input('\\nWould you like to see 5 more lines of raw data? Enter yes or no.\\n')\n count +=5\n start +=5\n\n\n restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n if restart.lower() != 'yes':\n break\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"bikeshere.py","file_name":"bikeshere.py","file_ext":"py","file_size_in_byte":7927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"404482513","text":"import matplotlib.pyplot as plt\n\nclass Grapher:\n \"\"\"Grapher class\n\n Manages plots of different parameters of given population like:\n - fitness function,\n - best/mean/worst results,\n - best individuals...\n \"\"\"\n\n DELAY = 0.0001\n\n def __init__(self, plotting_queue):\n \"\"\"Creates and initializes a plot window\"\"\"\n self.plotting_queue = plotting_queue\n self.xs = []\n self.bests = []\n self.means = []\n plt.ion()\n plt.show()\n\n def start(self):\n while True:\n points = self.plotting_queue.get()\n self.xs.append(points['iteration'])\n self.bests.append(points['best score'])\n self.means.append(points['mean score'])\n plt.plot(self.xs, self.bests, 'r')\n plt.plot(self.xs, self.means, 'b')\n plt.show()\n plt.pause(Grapher.DELAY)\n self.plotting_queue.task_done()\n","sub_path":"src/grapher.py","file_name":"grapher.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"181431567","text":"#!/usr/bin/env python\n\n# Import necessary package \nimport rospy\nimport smach\nimport smach_ros\nimport roslaunch\nfrom sim_read_goalFile import sim_read_goal\nfrom sim_read_actionFile import sim_read_action\nfrom clear_costMap import clear_costmaps\nfrom sim_switch_obstacleDetection_type1 import sim_open_obstacleDetection_node, sim_close_obstacleDetection_node\n\n\n# Storage goal data from /val2_navigation/text/goal_solustar.txt\ngoal_data = sim_read_goal() \n\n# Class for checking robot system\nclass systemAvailability(smach.State):\n\n\t# Initial state\n\tdef __init__(self):\n\t\tsmach.State.__init__(self, \n\t\t\t\t\t\t\toutcomes=['system_checked'],\n\t\t\t\t\t\t\tinput_keys=['goalList_input'],\n\t\t\t\t\t\t\toutput_keys=['goalList_output'])\n\n\t# Execution function\n\tdef execute(self, userdata):\n\t\tprint('\\n')\n\t\trospy.loginfo('Executing state system availability')\n\t\t\n\t\t# Robot rotate around itself\n\t\trospy.loginfo('Robot rotate around for localize the real position')\n\t\tlocalize_node = roslaunch.core.Node(package='val2sim_sensor', \n\t\t\t\t\t\t\t\t\t\t\tnode_type='sim_rotateBy_odom.py', \n\t\t\t\t\t\t\t\t\t\t\tname='sim_rotateBy_odom_node',\n\t\t\t\t\t\t\t\t\t\t\toutput=\"screen\")\n\t\tlocalize_node.args = \"_rotate_target:=%d\" %(360)\n\t\tlocalize_launch = roslaunch.scriptapi.ROSLaunch()\n\t\tlocalize_launch.start()\n\t\tlocalize_process = localize_launch.launch(localize_node)\n\t\twhile localize_process.is_alive():\n\t\t\tif localize_process.is_alive() == False:\n\t\t\t\tbreak\n\t\tlocalize_process.stop()\n\t\trospy.loginfo('Robot ready to use')\n\n\t\t# Robot say \"i'm ready to use\"\n\t\tsim_read_action(\"initial_station\", None, \"play_sound\")\n\t\tsound_node = roslaunch.core.Node(package='val2sim_sound', \n\t\t\t\t\t\t\t\t\t\t node_type='val2sim_soundplay.py', \n\t\t\t\t\t\t\t\t\t\t name='val2sim_soundplay_node')\n\t\tsound_node.args = \"_sound_to_play:=%s _sound_cycle_time:=%d\" %(sim_read_action.sound, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t sim_read_action.sound_cycleTime)\n\t\tsound_launch = roslaunch.scriptapi.ROSLaunch()\n\t\tsound_launch.start()\n\t\tsound_process = sound_launch.launch(sound_node)\n\t\twhile sound_process.is_alive():\n\t\t\tif sound_process.is_alive() == False:\n\t\t\t\tbreak\n\t\tsound_process.stop()\n\t\t\n\t\t# Output equal to input\n\t\tuserdata.goalList_output = userdata.goalList_input\n\t\treturn 'system_checked'\n\n# Class for heading the robot to the next goal\nclass turn2goal(smach.State):\n\n\t# Initial state\n\tdef __init__(self):\n\t\tsmach.State.__init__(self, \n\t\t\t\t\t\t\toutcomes=['turn_success'],\n\t\t\t\t\t\t\tinput_keys=['goalList_input'],\n\t\t\t\t\t\t\toutput_keys=['goalList_output'])\n\t\t\n\t# Execution function\n\tdef execute(self, userdata):\n\t\tprint('\\n')\n\t\trospy.loginfo('Executing state turn to goal')\n\t\t\n\t\t# Robot heading to the next goal \n\t\tsim_read_action(None, userdata.goalList_input[0], \"turn2nextgoal\")\n\t\trospy.loginfo('Robot have been turning to {} by {} degree'.format(userdata.goalList_input[0],sim_read_action.rotate2nextStation))\n\t\tturn2goal_node = roslaunch.core.Node(package='val2sim_sensor', \n\t\t\t\t\t\t\t\t\t\t\tnode_type='sim_rotateBy_odom.py', \n\t\t\t\t\t\t\t\t\t\t\tname='sim_rotateBy_odom_node',\n\t\t\t\t\t\t\t\t\t\t\toutput=\"screen\")\n\t\tturn2goal_node.args = \"_rotate_target:=%d\" %(sim_read_action.rotate2nextStation)\n\t\tturn2goal_launch = roslaunch.scriptapi.ROSLaunch()\n\t\tturn2goal_launch.start()\n\t\tturn2goal_process = turn2goal_launch.launch(turn2goal_node)\n\t\twhile turn2goal_process.is_alive():\n\t\t\tif turn2goal_process.is_alive() == False:\n\t\t\t\tbreak\n\t\tturn2goal_process.stop()\n\n\t\t# Output equal to input\n\t\tuserdata.goalList_output = userdata.goalList_input\n\t\treturn 'turn_success'\n\t\t\n# Class for moving the robot to the next goal\nclass move2goal(smach.State):\n\n\t# Initial state\n\tdef __init__(self):\n\t\tsmach.State.__init__(self, \n\t\t\t\t\t\t\toutcomes=['move_success'],\n\t\t\t\t\t\t\tinput_keys=['goalList_input'],\n\t\t\t\t\t\t\toutput_keys=['goalList_output'])\n\n\t# Execution function\n\tdef execute(self, userdata):\n\t\tprint('\\n')\n\t\trospy.loginfo('Executing state move to goal')\n\t\trospy.loginfo('Robot have been moving to {}'.format(userdata.goalList_input[0]))\n\n\t\t# Robot moving to the next goal and stop when detected the obstacle\n\t\trobot_goal = goal_data[userdata.goalList_input[0]]\n\t\tsim_open_obstacleDetection_node()\n\n\t\tnav_node = roslaunch.core.Node(package='val2sim_navigation', \n\t\t\t\t\t\t\t\t\t node_type='send_goal.py', \n\t\t\t\t\t\t\t\t\t name='movebase_client_py')\n\t\tnav_node.args = \"\"\" _position_x:={}\n\t\t\t\t\t\t\t_position_y:={}\n\t\t\t\t\t\t\t_position_z:={}\n\t\t\t\t\t\t\t_orientation_x:={} \n\t\t\t\t\t\t\t_orientation_y:={} \n\t\t\t\t\t\t\t_orientation_z:={} \n\t\t\t\t\t\t\t_orientation_w:={} \"\"\"\\\n\t\t\t\t\t\t\t.format(robot_goal[0],\n\t\t\t\t\t\t\t\t\trobot_goal[1],\n\t\t\t\t\t\t\t\t\trobot_goal[2],\n\t\t\t\t\t\t\t\t\trobot_goal[3],\n\t\t\t\t\t\t\t\t\trobot_goal[4],\n\t\t\t\t\t\t\t\t\trobot_goal[5],\n\t\t\t\t\t\t\t\t\trobot_goal[6])\n\t\tnav_launch = roslaunch.scriptapi.ROSLaunch()\n\t\tnav_launch.start()\n\t\tnav_process = nav_launch.launch(nav_node)\n\t\twhile nav_process.is_alive():\n\t\t\tif nav_process.is_alive == False:\n\t\t\t\tbreak\n\t\tnav_process.stop()\n\t\tsim_close_obstacleDetection_node()\n\n\n\t\t# Clear cost map\n\t\tclear_costmaps()\n\n\t\t# Output equal to input\n\t\tuserdata.goalList_output = userdata.goalList_input\n\t\treturn 'move_success'\n\n# Class for verify that robot reached to goal or not\nclass reach2goal(smach.State):\n\n\t# Initial state\n\tdef __init__(self):\n\t\tsmach.State.__init__(self, \n\t\t\t\t\t\t\toutcomes=['reach_success'],\n\t\t\t\t\t\t\tinput_keys=['goalList_input'],\n\t\t\t\t\t\t\toutput_keys=['goalList_output'])\n\n\t# Execution function\n\tdef execute(self, userdata):\n\t\tprint('\\n')\n\t\trospy.loginfo('Executing state reach to goal')\n\t\trospy.loginfo('Robot reach to {}'.format(userdata.goalList_input[0]))\n\n\t\t# Robot say \"station 1\", \"station 2\", \"base station\" or \"i need to charge my battery\"\n\t\tsim_read_action(userdata.goalList_input[0], None, \"play_sound\")\n\t\tsound_node = roslaunch.core.Node(package='val2sim_sound', \n\t\t\t\t\t\t\t\t\t\t node_type='val2sim_soundplay.py', \n\t\t\t\t\t\t\t\t\t\t name='val2sim_soundplay_node')\n\t\tsound_node.args = \"_sound_to_play:=%s _sound_cycle_time:=%d\" %(sim_read_action.sound, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t sim_read_action.sound_cycleTime)\n\t\tsound_launch = roslaunch.scriptapi.ROSLaunch()\n\t\tsound_launch.start()\n\t\tsound_process = sound_launch.launch(sound_node)\n\t\twhile sound_process.is_alive():\n\t\t\tif sound_process.is_alive() == False:\n\t\t\t\tbreak\n\t\tsound_process.stop()\n\n\t\t# Output equal to input\n\t\tuserdata.goalList_output = userdata.goalList_input\n\t\treturn 'reach_success'\n\n# Class for aligning the robot to each station\nclass goalAlignment(smach.State):\n\n\t# Initial state\n\tdef __init__(self):\n\t\tsmach.State.__init__(self,\n\t\t\t\t\t\t\toutcomes=['align_success','all_success'],\n\t\t\t\t\t\t\tinput_keys=['goalList_input'],\n\t\t\t\t\t\t\toutput_keys=['goalList_output'])\n\n\t# Execution function\n\tdef execute(self, userdata):\n\t\tprint('\\n')\n\t\trospy.loginfo('Executing state goal alignment')\n\t\tif userdata.goalList_input[0] == \"base_station\" and len(userdata.goalList_input) == 1:\n\t\t\tuserdata.goalList_input[0] = \"charging_station\"\n\t\tsim_read_action(userdata.goalList_input[0], None, \"turn2currentgoal\")\n\n\t\t# Robot start aligning to current goal\n\t\trospy.loginfo(\"Robot start align with {} by {} degree\".format(userdata.goalList_input[0],sim_read_action.rotate2currentStation))\n\t\tgoalAlignment_node = roslaunch.core.Node(package='val2sim_sensor', \n\t\t\t\t\t\t\t\t\t\t\t\t\t node_type='sim_rotateBy_odom.py', \n\t\t\t\t\t\t\t\t\t\t\t\t\t name='sim_rotateBy_odom_node',\n\t\t\t\t\t\t\t\t\t\t\t\t\t output=\"screen\")\n\t\tgoalAlignment_node.args = \"_rotate_target:=%d\" %sim_read_action.rotate2currentStation\n\t\tgoalAlignment_launch = roslaunch.scriptapi.ROSLaunch()\n\t\tgoalAlignment_launch.start()\n\t\tgoalAlignment_process = goalAlignment_launch.launch(goalAlignment_node)\n\t\twhile goalAlignment_process.is_alive():\n\t\t\tif goalAlignment_process.is_alive() == False:\n\t\t\t\tbreak\n\t\tgoalAlignment_process.stop()\n\n\t\t# Delete reached goal\n\t\tdel userdata.goalList_input[0]\n\t\t\n\t\t# Output equal to input\n\t\tuserdata.goalList_output = userdata.goalList_input\n\t\tif len(userdata.goalList_input) > 0:\n\t\t\treturn 'align_success'\n\t\telif len(userdata.goalList_input) == 0:\n\t\t\treturn 'all_success'\n\n# Class for waiting user to push the button again\nclass wait4nextround(smach.State):\n\n\t# Initial state\n\tdef __init__(self):\n\t\tsmach.State.__init__(self, \n\t\t\t\t\t\t\toutcomes=['finished_process'])\n\n\t# Execution function\n\tdef execute(self, userdata):\n\t\tprint('\\n')\n\t\trospy.loginfo('Executing state wait for user')\n\t\treturn 'finished_process'\n\t\t\n# Main function\ndef main():\n\t# Get list of goal from gui\n\twaypoint = []\n\tgoal_1 = rospy.get_param(\"~goal1\", \"station1\")\n\tgoal_2 = rospy.get_param(\"~goal2\", \"station2\")\n\tgoal_3 = rospy.get_param(\"~goal3\", \"base_station\")\n\tgoal_4 = rospy.get_param(\"~goal4\", \"None\")\n\tgoal_5 = rospy.get_param(\"~goal5\", \"None\")\n\tgoal_list = [goal_1, goal_2, goal_3, goal_4, goal_5]\n\tprint(goal_list)\n\tfor index in range(len(goal_list)):\n\t\tif goal_list[index] != \"None\":\n\t\t\twaypoint.append(goal_list[index])\n\t\n\tsm_nav = smach.StateMachine(outcomes=['shutdown'])\n\tsm_nav.userdata.goal_list = waypoint\n\twith sm_nav:\n\t\tsmach.StateMachine.add('SYSTEM_AVAILABILITY', systemAvailability(),\n\t\t\t\t\t\t\t\ttransitions={'system_checked':'TURN2GOAL'},\n\t\t\t\t\t\t\t\tremapping={ 'goalList_input':'goal_list',\n\t\t\t\t\t\t\t\t\t\t\t'goalList_output':'goal_list'})\n\n\t\tsmach.StateMachine.add('TURN2GOAL', turn2goal(),\n\t\t\t\t\t\t\t\ttransitions={'turn_success':'MOVE2GOAL'},\n\t\t\t\t\t\t\t\tremapping={ 'goalList_input':'goal_list',\n\t\t\t\t\t\t\t\t\t\t\t'goalList_output':'goal_list'})\n\n\t\tsmach.StateMachine.add('MOVE2GOAL', move2goal(),\n\t\t\t\t\t\t\t\ttransitions={'move_success':'SM_ACTION'},\n\t\t\t\t\t\t\t\tremapping={ 'goalList_input':'goal_list',\n\t\t\t\t\t\t\t\t\t\t\t'goalList_output':'goal_list'})\n\n\t\tsmach.StateMachine.add('WAIT4NEXTROUND', wait4nextround(),\n\t\t\t\t\t\t\t\ttransitions={'finished_process':'shutdown'})\n\n\n\t\tsm_act = smach.StateMachine(outcomes=['align_finished', 'all_finished'])\n\t\tsm_act.userdata.goal_list = waypoint\n\t\twith sm_act:\n\t\t\tsmach.StateMachine.add('REACH2GOAL', reach2goal(), \n\t\t\t\t\t\t\t\t\ttransitions={'reach_success':'GOAL_ALIGNMENT'},\n\t\t\t\t\t\t\t\t\tremapping={ 'goalList_input':'goal_list',\n\t\t\t\t\t\t\t\t\t\t\t\t'goalList_output':'goal_list'})\n\n\t\t\tsmach.StateMachine.add('GOAL_ALIGNMENT', goalAlignment(),\n\t\t\t\t\t\t\t\t\ttransitions={'align_success':'align_finished', 'all_success':'all_finished'},\n\t\t\t\t\t\t\t\t\tremapping={ 'goalList_input':'goal_list',\n\t\t\t\t\t\t\t\t\t\t\t\t'goalList_output':'goal_list'}) \n\n\t\tsmach.StateMachine.add('SM_ACTION', sm_act,\n\t\t\t\t\t\t\t transitions={'align_finished':'TURN2GOAL','all_finished':'WAIT4NEXTROUND'})\n\n\n\tsis = smach_ros.IntrospectionServer('server_name', sm_nav, 'SM_NAV/SM_ACT')\n\tsis.start()\n\toutcome = sm_nav.execute()\n\t# rospy.spin()\n\tsis.stop()\n\n\nif __name__ == '__main__':\n\t# Define node name\n\trospy.init_node('val2sim_fsm_type1_node', anonymous=False)\n\tmain()\n\t","sub_path":"val2sim_fsm/scripts/val2sim_fsm_type1.py","file_name":"val2sim_fsm_type1.py","file_ext":"py","file_size_in_byte":10450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"365152888","text":"from django.urls import path\n\nfrom . import views\n\napp_name = 'user'\nurlpatterns = [\n path('profile/', views.UserProfileView.as_view(), name='profile'),\n path('profile//', views.otherUserView, name='other_user'),\n path('sign-up', views.signup)\n]","sub_path":"user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"513133100","text":"# iterative function to calculate \r\n# the value of base raised to an exponent\r\n\r\ndef iterPower(base, exp):\r\n '''\r\n base: int or float.\r\n exp: int >= 0\r\n \r\n returns: int or float, base^exp\r\n '''\r\n ans=1\r\n while exp>0:\r\n ans*=base\r\n exp-=1\r\n return ans\r\n","sub_path":"base_raised_to_exponent.py","file_name":"base_raised_to_exponent.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"18859018","text":"\"\"\"DUMMY DOCSTRING\"\"\"\n\nfrom datetime import datetime\nfrom calendar import monthrange\nimport numpy as np\nimport cftime\nfrom cf_units import date2num\nimport iris\nfrom iris.coords import DimCoord\n\n\nclass RangeConstraint:\n \"\"\"Class for a range constraint\n\n This class can be used with an iris.Constraint, in particular in a\n multiprocessing environment, where lambda functionality (often\n used in Iris examples) can't be used.\n\n The constructor takes two argmuments, `start` and `end`, that\n specify the boundary of the range, and are *inclusive*.\n\n Usage examples with iris.Constraint:\n\n constraint = iris.Constraint(year=RangeConstraint(1950, 2050))\n century_cube = constraint.extract(cube)\n\n constraint = iris.Constraint(time=RangeConstraint(cftime.datetime(2010, 1, 1),\n cftime.datetime(2010, 6, 30))\n halfyear_cube = constraint.extract(cube)\n\n \"\"\"\n\n def __init__(self, start, end):\n self.start = start\n self.end = end\n\n def __call__(self, cell):\n return self.start <= cell.point <= self.end\n\n\nclass EqualConstraint:\n \"\"\"Class for a equality constraint\n\n This class can be used with an iris.Constraint, in particular in a\n multiprocessing environment, where lambda functionality (often\n used in Iris examples) can't be used.\n\n The constructor takes one argmument, `value`, that specify the\n value which the relevant coordinate (given as parameter name in\n `iris.Constraint`) should equal.\n\n Usage examples with iris.Constraint:\n\n constraint = iris.Constraint(year=2010)\n cube-2010 = constraint.extract(cube)\n\n # Use an auxiliary season coordinate that equals one of 'djf', 'mam', 'jja' or 'son',\n # and extract all winters\n constraint = iris.Constraint(season='djf')\n winters = constraint.extract(cube)\n\n \"\"\"\n\n def __init__(self, value):\n self.value = value\n\n def __call__(self, value):\n return self.value == value\n\n\ndef make_date_constraint(start, end):\n \"\"\"Factory fucntion to create a range constraint specifically for the `time` coordinate\n\n Arguments\n ---------\n\n start, end: lower and upper limits (inclusive) of the time\n boundaries. Use a `cftime.datetime` or variant as type.\n\n \"\"\"\n\n constraint = RangeConstraint(start, end)\n return iris.Constraint(time=constraint)\n\n\ndef make_year_constraint_all_calendars(start, end):\n \"\"\"Utility function to create a dict of time constraints on year-basis\n\n This create a dict of the same time constraint, but for different calendars.\n Since comparisons between different calendar types are not (always) possible,\n a calendar for a time coordinate should be compared to the specific constraint\n with the same calendar.\n\n The calendar type (as a string) can be obtained through the coordinate's `units`\n attribute: `cube.coord('time').units.calendar`; the resulting string is the key\n for the dict, which then as a value yields the correct constraint\n\n Arguments\n ---------\n\n start, end: integer\n Start and end year. Month and day are 1, 1 for the starting year, and\n 31, 12 or 30, 12 (for a 360-day calendar) for the end year\n\n \"\"\"\n\n dates = {\n 'default': (cftime.datetime(start, 1, 1), cftime.datetime(end, 12, 31)),\n '360_day': (cftime.Datetime360Day(start, 1, 1), cftime.Datetime360Day(end, 12, 30)),\n '365_day': (cftime.DatetimeNoLeap(start, 1, 1), cftime.DatetimeNoLeap(end, 12, 31)),\n 'proleptic_gregorian': (cftime.DatetimeProlepticGregorian(start, 1, 1),\n cftime.DatetimeProlepticGregorian(end, 12, 31)),\n 'gregorian': (cftime.DatetimeGregorian(start, 1, 1), cftime.DatetimeGregorian(end, 12, 31)),\n 'julian': (cftime.DatetimeJulian(start, 1, 1), cftime.DatetimeJulian(end, 12, 31)),\n }\n constraints = {key: make_date_constraint(*value) for key, value in dates.items()}\n return constraints\n\n\ndef months_coord_to_days_coord(coord):\n \"\"\"Convert a dimension coordinate from 'months since' to 'days since'\n\n This function uses the `calendar.monthrange` function to calculate\n the days per month, and sets the lower and upper bound for each month.\n Once the bounds have been set, `cf_units.date2num` is used to convert\n the bounds to numeric values, in days since the original offset.\n These bounds are averaged, to produce midpoints, which are the actual\n points for the new dimension coordinate. The new dimension coordinate\n also includes bounds, which the original may not have.\n\n \"\"\"\n\n units = coord.units\n origin = units.origin\n # Assume an origin format of \" since \", so we can split on 'since'\n step, startdate = map(str.strip, origin.split('since'))\n if step != 'months':\n raise ValueError('units step is not months')\n\n # Parse the starting date; assume it has a YYYY-MM-DD HH:MM:SS format,\n # or YYYY-MM-DD without the timestamp\n # Note: leading zeros for months, days, hours, minutes or seconds\n # may be safely ignored: 2010-1-1 or 2010-01-01 will both parse fine\n try:\n t0 = datetime.strptime(startdate, \"%Y-%m-%d %H:%M:%S\") # pylint: disable=invalid-name\n except ValueError:\n t0 = datetime.strptime(startdate, \"%Y-%m-%d\") # pylint: disable=invalid-name\n\n points = coord.points.astype(np.int)\n bounds = []\n # Remember that 'point's are in whole months\n for point in points:\n year = t0.year + point // 12\n month = t0.month + point % 12\n current = datetime(year, month, 1)\n # Get number of days for this year (ignore starting weekday number)\n _, ndays = monthrange(year, month)\n # And set the boundary dates for this month\n bounds.append([current, datetime(year, month, ndays)])\n\n # date2num accepts a two-dimensional numpy array\n bounds = np.array(bounds)\n boundpoints = date2num(bounds, unit=f'days since {startdate}', calendar='gregorian')\n\n midpoints = boundpoints.mean(axis=1)\n day_coord = DimCoord(midpoints, bounds=boundpoints, standard_name=coord.standard_name,\n long_name=coord.long_name, units=f'days since {startdate}',\n var_name=coord.var_name)\n\n return day_coord\n","sub_path":"kcs/utils/date.py","file_name":"date.py","file_ext":"py","file_size_in_byte":6371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"526686227","text":"#------------------------------------------------------------------------------\n# Copyright (c) 2011, Enthought, Inc.\n# All rights reserved.\n#------------------------------------------------------------------------------\nfrom abc import ABCMeta, abstractmethod\n\nfrom traits.api import HasStrictTraits\n\nfrom ..styling.color import ColorTrait\nfrom ..styling.font import FontTrait\n\n\nclass AbstractTkStylable(object):\n \"\"\" The abstract toolkit interface for a stylable component.\n\n \"\"\"\n __metaclass__ = ABCMeta\n \n @abstractmethod\n def shell_bg_color_changed(self, color):\n \"\"\" The change handler for the 'bg_color' attribute on the shell\n object. Sets the background color of the internal widget to the \n given color.\n \n \"\"\"\n raise NotImplementedError\n \n @abstractmethod\n def shell_fg_color_changed(self, color):\n \"\"\" The change handler for the 'fg_color' attribute on the shell\n object. Sets the foreground color of the internal widget to the \n given color. For some widgets this may do nothing.\n\n \"\"\"\n raise NotImplementedError\n \n @abstractmethod\n def shell_font_changed(self, font):\n \"\"\" The change handler for the 'font' attribute on the shell\n object. Sets the font of the internal widget to the given font.\n For some widgets this may do nothing.\n\n \"\"\"\n raise NotImplementedError\n\n\nclass Stylable(HasStrictTraits):\n \"\"\" A mixin class which defines common style themes that certain \n classes of widgets will wish to support.\n\n \"\"\"\n #: The background color of the widget.\n bg_color = ColorTrait\n \n #: The foreground color of the widget.\n fg_color = ColorTrait\n \n #: The font used for the widget.\n font = FontTrait\n\n","sub_path":"enaml/widgets/stylable.py","file_name":"stylable.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"315872090","text":"class Solution(object):\r\n def uniquePathsWithObstacles(self, obstacleGrid):\r\n \"\"\"\r\n :type obstacleGrid: List[List[int]]\r\n :rtype: int\r\n \"\"\"\r\n if not obstacleGrid:\r\n return 0\r\n\r\n m = len(obstacleGrid) # nRows\r\n n = len(obstacleGrid[0]) # nCols\r\n\r\n if m == 0 or n == 0:\r\n return 0\r\n\r\n dp = [[0 for x in range(n)] for y in range(m)]\r\n\r\n # init\r\n dp[0][0] = obstacleGrid[0][0]\r\n\r\n for col in range(1, n): # set top row\r\n if obstacleGrid[0][col] == 0 and dp[0][col - 1] == 1:\r\n dp[0][col] = 1\r\n for row in range(1, m): # set first column\r\n if obstacleGrid[row][0] == 0 and dp[row - 1][0] == 1:\r\n dp[row][0] = 1\r\n\r\n # bottom up DP\r\n for i in range(1, m):\r\n for j in range(1, n):\r\n if obstacleGrid[i][j] == 0:\r\n dp[i][j] = dp[i-1][j] + dp[i][j-1]\r\n\r\n return dp[-1][-1]\r\n\r\n","sub_path":"unique_paths_2.py","file_name":"unique_paths_2.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"352130684","text":"#!/usr/bin/env python\nfrom __future__ import absolute_import, division\n# \n# LSST Data Management System\n# Copyright 2008, 2009, 2010 LSST Corporation.\n# \n# This product includes software developed by the\n# LSST Project (http://www.lsst.org/).\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the LSST License Statement and \n# the GNU General Public License along with this program. If not, \n# see .\n#\n\nimport os\n\nimport numpy as np\n\nimport lsst.utils\nimport sys\nimport lsst.afw.table as afwTable\nimport lsst.afw.image as afwImage\nfrom lsst.meas.astrom import AstrometryTask\nfrom lsst.pipe.tasks.photoCal import PhotoCalTask\n\n\ndef loadData():\n \"\"\"Prepare the data we need to run the example\"\"\"\n \n # Load sample input from disk\n mypath = lsst.utils.getPackageDir('meas_astrom')\n\n # The .xy.fits file has sources in the range ~ [0,2000],[0,4500]\n exposure = afwImage.ExposureF(os.path.join(mypath, \"tests\", \"v695833-e0-c000-a00.sci.fits\"))\n #\n # We're using a subset of the exposure in the .xy file and this appears to confuse\n # meas_astrom; it needs to be called as\n # astrom.determineWcs(srcCat, exposure, imageSize=(2048, 4612))\n #\n # Rather than fixing this we'll fix the input image \n #\n if True:\n smi = exposure.getMaskedImage()\n mi = smi.Factory(2048, 4612)\n mi[0:smi.getWidth(), 0:smi.getHeight()] = smi\n exposure.setMaskedImage(mi)\n del mi; del smi\n\n # Set up local astrometry_net_data\n datapath = os.path.join(mypath, 'tests', 'astrometry_net_data', 'photocal')\n if not os.path.exists(datapath):\n raise ValueError(\"Need photocal version of astrometry_net_data (from path: %s)\" %\n datapath)\n os.environ['ASTROMETRY_NET_DATA_DIR'] = datapath\n\n #\n # Read sources\n #\n srcCat = afwTable.SourceCatalog.readFits(os.path.join(mypath, \"tests\", \"v695833-e0-c000.xy.fits\"))\n srcCat.getPsfFluxErr()[:] = np.sqrt(srcCat.getPsfFlux())\n\n return exposure, srcCat\n\ndef run():\n exposure, srcCat = loadData()\n schema = srcCat.getSchema()\n #\n # Create the astrometry task\n #\n config = AstrometryTask.ConfigClass()\n config.refObjLoader.filterMap = {\"_unknown_\": \"r\"}\n config.matcher.sourceFluxType = \"Psf\" # sample catalog does not contain aperture flux\n aTask = AstrometryTask(config=config)\n #\n # And the photometry Task\n #\n config = PhotoCalTask.ConfigClass()\n config.applyColorTerms = False # we don't have any available, so this suppresses a warning\n pTask = PhotoCalTask(config=config, schema=schema)\n #\n # The tasks may have added extra elements to the schema (e.g. AstrometryTask's centroidKey to\n # handle distortion; photometryTask's config.outputField). If this is so, we need to add\n # these columns to the Source table.\n #\n # We wouldn't need to do this if we created the schema prior to measuring the exposure,\n # but in this case we read the sources from disk\n #\n if schema != srcCat.getSchema(): # the tasks added fields\n print(\"Adding columns to the source catalogue\")\n cat = afwTable.SourceCatalog(schema)\n cat.table.defineCentroid(srcCat.table.getCentroidDefinition())\n cat.table.definePsfFlux(srcCat.table.getPsfFluxDefinition())\n\n scm = afwTable.SchemaMapper(srcCat.getSchema(), schema)\n for schEl in srcCat.getSchema():\n scm.addMapping(schEl.getKey(), True)\n\n cat.extend(srcCat, True, scm) # copy srcCat to cat, adding new columns\n\n srcCat = cat; del cat\n #\n # Process the data\n #\n matches = aTask.run(exposure, srcCat).matches\n result = pTask.run(exposure, matches)\n\n calib = result.calib\n fm0, fm0Err = calib.getFluxMag0()\n\n print(\"Used %d calibration sources out of %d matches\" % (len(result.matches), len(matches)))\n \n delta = result.arrays.refMag - result.arrays.srcMag\n q25, q75 = np.percentile(delta, [25, 75])\n print(\"RMS error is %.3fmmsg (robust %.3f, Calib says %.3f)\" % (np.std(delta), 0.741*(q75 - q25),\n 2.5/np.log(10)*fm0Err/fm0))\n \n#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser(description=\"Demonstrate the use of PhotoCalTask\")\n\n parser.add_argument('--debug', '-d', action=\"store_true\", help=\"Load debug.py?\", default=False)\n\n args = parser.parse_args()\n\n if args.debug:\n try:\n import debug\n except ImportError as e:\n print(\"Could not import debug: %s\" % (e,))\n\n run()\n","sub_path":"examples/photoCalTask.py","file_name":"photoCalTask.py","file_ext":"py","file_size_in_byte":5225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"433384862","text":"from numpy import *\nimport csv\nimport numpy as np\nimport random\nimport jieba\nimport jieba.analyse as ana\nimport jieba.posseg as psg\nfrom wordcloud import WordCloud\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import MultipleLocator\nfrom matplotlib.font_manager import _rebuild\n\n_rebuild()\n\nplt.rcParams['font.sans-serif'] = [u'SimHei']\nplt.rcParams[\"axes.unicode_minus\"] = False\n\n\ndef createDataset():\n with open('new-dict.csv', encoding='utf-8') as f:\n next(f)\n csv_file = csv.reader(f)\n lst = []\n lst_1 = []\n lst_2 = []\n lst_3 = []\n lst_4 = []\n lst_5 = []\n lst_6 = []\n lst_7 = []\n lst_8 = []\n lst_9 = []\n lst_10 = []\n for row in csv_file:\n l = row[1].split(',')\n for item in l:\n if item == '1':\n lst_1.append(row[0])\n elif item == '2':\n lst_2.append(row[0])\n elif item == '3':\n lst_3.append(row[0])\n elif item == '4':\n lst_4.append(row[0])\n elif item == '5':\n lst_5.append(row[0])\n elif item == '6':\n lst_6.append(row[0])\n elif item == '7':\n lst_7.append(row[0])\n elif item == '8':\n lst_8.append(row[0])\n elif item == '9':\n lst_9.append(row[0])\n elif item == '10':\n lst_10.append(row[0])\n ls = [lst_1, lst_2, lst_3, lst_4, lst_5, lst_6, lst_7, lst_8, lst_9, lst_10]\n for l in ls:\n lst.append(l)\n return lst\n\n\ndef createVocabList(dataSet):\n vocabSet = set([])\n for document in dataSet:\n vocabSet = vocabSet | set(document)\n return list(vocabSet)\n\n\ndef setOfWords2Vec(vocabList, inputSet):\n returnVec = [0] * len(vocabList)\n for word in inputSet:\n if word in vocabList:\n returnVec[vocabList.index(word)] = 1\n else:\n pass\n return returnVec\n\n\ndef bagOfWords2Vec(vocabList, inputSet):\n returnVec = [0] * len(vocabList)\n for word in inputSet:\n if word in vocabList:\n returnVec[vocabList.index(word)] += 1\n return returnVec\n\n\ndef countX(aList, el):\n count = 0\n for item in aList:\n if item == el:\n count += 1\n return count\n\n\ndef trainNB0(trainMatrix, trainCategory):\n numTrainDocs = len(trainMatrix)\n numWords = len(trainMatrix[0])\n pAbusive1 = countX(trainCategory, 1) / float(numTrainDocs)\n pAbusive2 = countX(trainCategory, 2) / float(numTrainDocs)\n pAbusive3 = countX(trainCategory, 3) / float(numTrainDocs)\n pAbusive4 = countX(trainCategory, 4) / float(numTrainDocs)\n pAbusive5 = countX(trainCategory, 5) / float(numTrainDocs)\n pAbusive6 = countX(trainCategory, 6) / float(numTrainDocs)\n pAbusive7 = countX(trainCategory, 7) / float(numTrainDocs)\n pAbusive8 = countX(trainCategory, 8) / float(numTrainDocs)\n pAbusive9 = countX(trainCategory, 9) / float(numTrainDocs)\n pAbusive10 = countX(trainCategory, 10) / float(numTrainDocs)\n p1Num = np.ones(numWords)\n p2Num = np.ones(numWords)\n p3Num = np.ones(numWords)\n p4Num = np.ones(numWords)\n p5Num = np.ones(numWords)\n p6Num = np.ones(numWords)\n p7Num = np.ones(numWords)\n p8Num = np.ones(numWords)\n p9Num = np.ones(numWords)\n p10Num = np.ones(numWords)\n p1Denom = 2.0\n p2Denom = 2.0\n p3Denom = 2.0\n p4Denom = 2.0\n p5Denom = 2.0\n p6Denom = 2.0\n p7Denom = 2.0\n p8Denom = 2.0\n p9Denom = 2.0\n p10Denom = 2.0\n for i in range(numTrainDocs):\n if trainCategory[i] == 1:\n p1Num += trainMatrix[i]\n p1Denom += sum(trainMatrix[i])\n elif trainCategory[i] == 2:\n p2Num += trainMatrix[i]\n p2Denom += sum(trainMatrix[i])\n elif trainCategory[i] == 3:\n p3Num += trainMatrix[i]\n p3Denom += sum(trainMatrix[i])\n elif trainCategory[i] == 4:\n p4Num += trainMatrix[i]\n p4Denom += sum(trainMatrix[i])\n elif trainCategory[i] == 5:\n p5Num += trainMatrix[i]\n p5Denom += sum(trainMatrix[i])\n elif trainCategory[i] == 6:\n p6Num += trainMatrix[i]\n p6Denom += sum(trainMatrix[i])\n elif trainCategory[i] == 7:\n p7Num += trainMatrix[i]\n p7Denom += sum(trainMatrix[i])\n elif trainCategory[i] == 8:\n p8Num += trainMatrix[i]\n p8Denom += sum(trainMatrix[i])\n elif trainCategory[i] == 9:\n p9Num += trainMatrix[i]\n p9Denom += sum(trainMatrix[i])\n elif trainCategory[i] == 10:\n p10Num += trainMatrix[i]\n p10Denom += sum(trainMatrix[i])\n p10Vect = np.log(p10Num / p10Denom)\n p9Vect = np.log(p9Num / p9Denom)\n p8Vect = np.log(p8Num / p8Denom)\n p7Vect = np.log(p7Num / p7Denom)\n p6Vect = np.log(p6Num / p6Denom)\n p5Vect = np.log(p5Num / p5Denom)\n p4Vect = np.log(p4Num / p4Denom)\n p3Vect = np.log(p3Num / p3Denom)\n p2Vect = np.log(p2Num / p2Denom)\n p1Vect = np.log(p1Num / p1Denom)\n return p1Vect, p2Vect, p3Vect, p4Vect, p5Vect, p6Vect, p7Vect, p8Vect, p9Vect, p10Vect, pAbusive1, \\\n pAbusive2, pAbusive3, pAbusive4, pAbusive5, pAbusive6, pAbusive7, pAbusive8, pAbusive9, pAbusive10\n\n\ndef classifyNB(vec2Classify, p1Vec, p2Vec, p3Vec, p4Vec, p5Vec, p6Vec, p7Vec, p8Vec, p9Vec, p10Vec, pClass1,\n pClass2, pClass3, pClass4, pClass5, pClass6,\n pClass7, pClass8, pClass9, pClass10):\n p1 = sum(vec2Classify * p1Vec) + np.log(pClass1)\n p2 = sum(vec2Classify * p2Vec) + np.log(pClass2)\n p3 = sum(vec2Classify * p3Vec) + np.log(pClass3)\n p4 = sum(vec2Classify * p4Vec) + np.log(pClass4)\n p5 = sum(vec2Classify * p5Vec) + np.log(pClass5)\n p6 = sum(vec2Classify * p6Vec) + np.log(pClass6)\n p7 = sum(vec2Classify * p7Vec) + np.log(pClass7)\n p8 = sum(vec2Classify * p8Vec) + np.log(pClass8)\n p9 = sum(vec2Classify * p9Vec) + np.log(pClass9)\n p10 = sum(vec2Classify * p10Vec) + np.log(pClass10)\n dct = {1: p1, 2: p2, 3: p3, 4: p4, 5: p5, 6: p6, 7: p7, 8: p8, 9: p9, 10: p10}\n ts = sorted(dct.items(), key=lambda x: x[1], reverse=True)\n return [p1, p2, p3, p4, p5, p6, p7, p8, p9, p10].index(ts[0][1]), [p1, p2, p3, p4, p5, p6, p7, p8, p9, p10].index(\n ts[1][1])\n\n\ndef printMessage(i, j):\n dct = {1: '经济', 2: '文化', 3: '社会', 4: '生态', 5: '科技', 6: '依法', 7: '廉洁', 8: '组织', 9: '思想', 10: '作风'}\n print('主要类别 =', dct[i])\n print('次要类别 =', dct[j])\n\n\ndef getTfWord():\n try:\n with open('news.csv', newline='', encoding='utf-8') as csvfile:\n # r = random.randint(0, 5052)\n next(csvfile)\n reader = csv.reader(csvfile)\n for i, rows in enumerate(reader):\n if i == 169:\n row = rows\n sent = (row[0] + row[3]).replace(' ', '')\n print(sent)\n ana.set_stop_words('stopwords.txt')\n keyword = ana.extract_tags(sentence=sent, topK=10, allowPOS=('ns', 'n', 'nr'))\n print(row[0], keyword)\n return keyword\n except:\n pass\n finally:\n keyword2 = ana.extract_tags(sentence=sent, topK=50, allowPOS=('ns', 'n', 'nr'), withWeight=True)\n wordCloud(keyword2)\n\n\ndef wordCloud(keyword2):\n print(keyword2)\n new_keyword = {}\n for i, j in enumerate(keyword2):\n # print(j[0], j[1])\n new_keyword[j[0]] = j[1]\n\n def show_img(wc):\n plt.figure()\n plt.imshow(wc)\n plt.axis(\"off\")\n\n wc = WordCloud(\n font_path='/Users/Saitama/PycharmProjects/Project-1/venv/simsun.ttc',\n max_words=2000,\n width=1920,\n height=1080,\n background_color=\"white\",\n margin=5)\n wc.generate_from_frequencies(new_keyword)\n\n wc.to_file('wc.png')\n show_img(wc)\n\n\nif __name__ == '__main__':\n dataset = createDataset()\n classVec = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n myVocabList = createVocabList(dataset)\n trainMat = []\n for postinDoc in dataset:\n trainMat.append(setOfWords2Vec(myVocabList, postinDoc))\n p1V, p2V, p3V, p4V, p5V, p6V, p7V, p8V, p9V, p10V, pAb1, pAb2, pAb3, pAb4, pAb5, pAb6, pAb7, pAb8, pAb9, pAb10 = trainNB0(\n array(trainMat), array(classVec))\n tst = getTfWord()\n thisDoc = array(setOfWords2Vec(myVocabList, tst))\n flag1, flag2 = classifyNB(thisDoc, p1V, p2V, p3V, p4V, p5V, p6V, p7V, p8V, p9V, p10V, pAb1, pAb2, pAb3, pAb4, pAb5,\n pAb6, pAb7, pAb8, pAb9, pAb10)\n # flag1 = 3\n # flag2 = 1\n printMessage(flag1, flag2)\n","sub_path":"Code/venv/BayesTest.py","file_name":"BayesTest.py","file_ext":"py","file_size_in_byte":8805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"46268535","text":"import pandas as pd\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport h5py\nimport os\nimport shutil\nfrom sklearn import cluster, datasets, mixture\nfrom sklearn.neighbors import kneighbors_graph\nfrom itertools import cycle, islice\nfrom sklearn.preprocessing import StandardScaler, scale\nfrom scipy.ndimage import gaussian_filter, distance_transform_edt, label\nfrom skimage.filters import threshold_local\nfrom skimage.color import rgb2gray\nfrom skimage import measure\nfrom skimage.feature import peak_local_max\nfrom skimage.morphology import watershed\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nimport pandasql as ps\nfrom scipy import spatial\nfrom scipy.optimize import minimize, dual_annealing\n\nfrom skimage import restoration\nfrom multiprocessing import Process, Pipe\n\n#picasso hdf5 format (with averaging): ['frame', 'x', 'y', 'photons', 'sx', 'sy', 'bg', 'lpx', 'lpy', 'group']\n#Column Name |\tDescription |\tC Data Type\n#frame\t |The frame in which the localization occurred, starting with zero for the first frame.\t |unsigned long\n#x |The subpixel x coordinate in camera pixels\t |float\n#y\t |The subpixel y coordinate in camera pixels\t |float\n#photons\t |The total number of detected photons from this event, not including background or camera offset\t |float\n#sx\t |The Point Spread Function width in camera pixels |\tfloat\n#sy\t |The Point Spread Function height in camera pixels |\tfloat\n#bg\t |The number of background photons per pixel, not including the camera offset |\tfloat\n#lpx\t |The localization precision in x direction, in camera pixels, as estimated by the Cramer-Rao Lower Bound of the Maximum Likelihood fit. |\tfloat\n#lpy\t |The localization precision in y direction, in camera pixels, as estimated by the Cramer-Rao Lower Bound of the Maximum Likelihood fit. |\tfloat\n\nclass LocalizationCluster:\n def __init__(self,grid,localizations,recenter):\n #grid NX2 array of x,y localizations NX3 array of x,y,prec\n self.grid = np.copy(grid)\n self.gridTran = np.copy(grid)\n self.localizations = np.copy(localizations)\n self.weight = 1/localizations[:,2]\n self.nnTree = []\n self.nn = []\n self.dx = 0\n self.dy = 0\n self.dt = 0\n \n #Center grid and localizations on 0,0\n xGAve = 0\n yGAve = 0\n gCount = 0\n xLAve = 0\n yLAve = 0\n lCount = 0\n self.uAve=0\n for row in range(self.grid.shape[0]):\n xGAve+=self.grid[row,0]\n yGAve+=self.grid[row,1]\n gCount+=1\n \n for row in range(self.localizations.shape[0]):\n xLAve+=self.localizations[row,0]\n yLAve+=self.localizations[row,1]\n self.uAve += self.localizations[row,2]\n lCount+=1\n \n xGAve/=gCount\n yGAve/=gCount\n \n xLAve/=lCount\n yLAve/=lCount\n self.uAve/=lCount\n \n if recenter:\n for row in range(self.grid.shape[0]):\n self.grid[row,0]-=xGAve\n self.grid[row,1]-=yGAve\n \n for row in range(self.localizations.shape[0]):\n self.localizations[row,0]-=xLAve\n self.localizations[row,1]-=yLAve\n \n self.roughClock()\n \n self.weightDistMatrix = np.zeros((self.localizations.shape[0],self.gridTran.shape[0]))\n self.wdmComputed = False\n\n def squareNNDist(self,tm):\n self.dx = tm[0]\n self.dy = tm[1]\n self.dt = tm[2]\n rotMat = np.array([[np.cos(self.dt),-np.sin(self.dt)],[np.sin(self.dt),np.cos(self.dt)]])\n self.gridTran = np.dot(self.grid,rotMat)\n self.gridTran[:,0]+=self.dx\n self.gridTran[:,1]+=self.dy\n self.nnTree = spatial.cKDTree(self.gridTran)\n self.nn = self.nnTree.query(self.localizations[:,0:2])\n self.wdmComputed = False\n return float(sum(np.multiply(self.nn[0],self.weight)**2))\n \n def roughClock(self):\n minObj = self.squareNNDist([self.dx,self.dy,0])\n minTheta = 0\n for thetaId in range(180):\n theta = thetaId*np.pi/180\n obj = self.squareNNDist([self.dx,self.dy,theta])\n if obj backgroundMean\n # siteMap_stats = siteMap.describe()\n # siteFrequency = siteMap_stats.loc['freq'].values\n # \n # numberOfGroups = len(filteredLocs['group'].unique())\n # \n # sitePercent = siteFrequency / numberOfGroups\n # \n # \n # centeroidGroups=range(len(centeroids))\n # \n # \n # decodeDF = siteMap.astype(int)\n #\n # \n # savePath2 = filePath.split('.')[0] + '_incrementaBackground-TEST_{}.csv'.format(i) \n # decodeDF.to_csv(savePath2, header=False, index=False)\n # print(i)\n #\n lc = LocalizationCluster(centeroids,localizations,True)\n localizationClusterList.append(lc)\n \n processes = []\n parentConnections = []\n \n for index in range(len(localizationClusterList)):\n pconn,cconn = Pipe(False)\n proc = Process(target=mpClusterFit,args=(localizationClusterList[index],index,cconn,))\n processes.append(proc)\n parentConnections.append(pconn)\n #mpClusterFit(lc)\n processes[-1].start()\n \n #if verbose:\n # print(lc.dt) \n \n for pconn in parentConnections:\n msg = pconn.recv();\n print(msg[0],'fitting done')\n localizationClusterList[msg[0]].squareNNDist(msg[1:])\n \n for proc in processes:\n proc.join()\n \n for lc in localizationClusterList:\n gridShape = (6,8)\n \n gridPoints = np.copy(lc.gridTran).reshape(gridShape[0],gridShape[1],2)\n \n rx=0\n ry=0\n cx=0\n cy=0\n \n \n for rid in range(1,gridShape[0]):\n for cid in range(0,gridShape[1]):\n rx += gridPoints[rid,cid,0]-gridPoints[rid-1,cid,0]\n ry += gridPoints[rid,cid,1]-gridPoints[rid-1,cid,1]\n \n for rid in range(0,gridShape[0]):\n for cid in range(1,gridShape[1]):\n cx += gridPoints[rid,cid,0]-gridPoints[rid,cid-1,0]\n cy += gridPoints[rid,cid,1]-gridPoints[rid,cid-1,1]\n \n rx/=(gridShape[0]-1)*gridShape[1]\n ry/=(gridShape[0]-1)*gridShape[1]\n cx/=gridShape[0]*(gridShape[1]-1)\n cy/=gridShape[0]*(gridShape[1]-1)\n \n minDeltaR = 0\n minDeltaC = 0\n \n dx = lc.dx\n dy = lc.dy\n dt = lc.dt\n \n minObj = lc.squareNNDist([dx,dy,dt])\n for deltaR in range(-2,3):\n for deltaC in range(-2,3):\n obj3 = lc.squareNNDist([dx+deltaR*rx+deltaC*cx,dy+deltaR*ry+deltaC*cy,dt])\n if obj3 < minObj:\n minObj = obj3\n minDeltaR = deltaR\n minDeltaC = deltaC\n \n obj3 = lc.squareNNDist([dx+minDeltaR*rx+minDeltaC*cx,dy+minDeltaR*ry+minDeltaC*cy,dt])\n gridPoints = np.copy(lc.gridTran).reshape(gridShape[0],gridShape[1],2)\n \n superGridPoints = np.zeros((gridShape[0]+2,gridShape[1]+2,2))\n \n for rid in range(0,gridShape[0]):\n for cid in range(0,gridShape[1]):\n superGridPoints[rid+1,cid+1,:] = gridPoints[rid,cid,:]\n \n for rid in range(gridShape[0]+2):\n superGridPoints[rid,0,0] = gridPoints[0,0,0] - rx - cx + rid * rx\n superGridPoints[rid,0,1] = gridPoints[0,0,1] - ry - cy + rid * ry\n superGridPoints[rid,-1,0] = gridPoints[-1,-1,0] + rx + cx - rid * rx\n superGridPoints[rid,-1,1] = gridPoints[-1,-1,1] + ry + cy - rid * ry\n \n for cid in range(1,gridShape[1]+1):\n superGridPoints[0,cid,0] = gridPoints[0,0,0] - rx - cx + cid * cx\n superGridPoints[0,cid,1] = gridPoints[0,0,1] - ry - cy + cid * cy\n superGridPoints[-1,cid,0] = gridPoints[-1,-1,0] + rx + cx - cid * cx\n superGridPoints[-1,cid,1] = gridPoints[-1,-1,1] + ry + cy - cid * cy\n \n superGrid = np.copy(superGridPoints).reshape((superGridPoints.shape[0]*superGridPoints.shape[1],superGridPoints.shape[2]))\n \n lc2 = LocalizationCluster(superGrid,lc.localizations,False)\n #out2 = minimize(lc2.squareNNDist,[0,0,0],method='Nelder-Mead')\n #obj2 = lc2.squareNNDist(out2.x)\n obj2 = lc2.squareNNDist([0,0,0])\n \n if display2:\n plt.figure()\n plt.scatter(lc.localizations[:,0],lc.localizations[:,1],s=.1,color='blue')\n plt.scatter(lc.gridTran[:,0],lc.gridTran[:,1],color='orange')\n plt.scatter(lc.grid[:,0],lc.grid[:,1],color='red')\n plt.scatter(superGrid[:,0],superGrid[:,1],s=3,color='black')\n plt.scatter(lc2.gridTran[:,0],lc2.gridTran[:,1],s=2,color='green')\n \n \n \n hist = np.zeros((lc2.grid.shape[0]))\n \n for loc in range(len(lc2.nn[0])):\n if lc2.nn[0][loc] < distThreshold/pixelsize:\n hist[lc2.nn[1][loc]]+=lc2.weight[loc]\n \n if display2: \n fig, axt = plt.subplots(3,2)\n axt[0,0].bar([i for i in range(len(hist))],hist.tolist())\n \n kernel = np.zeros((3,3))\n \n sigma = max(0.5,lc.uAve/((np.sqrt(rx**2+ry**2)+np.sqrt(cx**2+cy**2))/2))\n #print(sigma)\n sq2sigma = np.sqrt(2)*sigma\n xc = 1.0\n yc = 1.0\n \n for xi in range(3):\n xp = xi - xc\n for yi in range(3):\n yp = yi - yc\n kernel[yi,xi] = 1/4*(np.math.erf((xp+.5)/sq2sigma)-np.math.erf((xp-.5)/sq2sigma))*(np.math.erf((yp+.5)/sq2sigma)-np.math.erf((yp-0.5)/sq2sigma))\n \n kernel /= sum(sum(kernel))\n scale = max(hist)*2 \n signal = hist.reshape(superGridPoints.shape[0],superGridPoints.shape[1])/scale\n rec = restoration.richardson_lucy(signal,kernel,50)\n rec *= sum(sum(signal))/sum(sum(rec))*scale\n \n if display2:\n axt[1,0].imshow(signal)\n axt[1,1].imshow(rec)\n hist2 = rec.reshape(hist.shape)\n \n if display2: \n axt[0,1].bar([i for i in range(len(hist2))],hist2.tolist())\n \n binaryImage = np.copy(rec)[1:-1,1:-1]\n for rid in range(binaryImage.shape[0]):\n for cid in range(binaryImage.shape[1]):\n if binaryImage[rid,cid] > scaled_threshold:\n binaryImage[rid,cid] = 1\n else:\n binaryImage[rid,cid] = 0\n \n if display2: \n axt[2,1].imshow(binaryImage)\n \n superRes = np.zeros((60,60))\n \n for rid in range(lc2.localizations.shape[0]):\n x = int(-lc2.localizations[rid,1]*pixelsize/2+superRes.shape[0]/2)\n y = int(-lc2.localizations[rid,0]*pixelsize/2+superRes.shape[1]/2)\n if x > 0 and x 0 and y < superRes.shape[1]:\n superRes[x,y] += 1\n \n axt[2,0].imshow(superRes)\n \n #binaryImage = np.array([[0,0,0,0,0,0,0,0],[0,1,1,1,1,1,1,0],[1,1,0,0,0,0,1,0],[0,0,1,1,1,1,0,1],[0,0,1,0,1,1,0,0],[0,0,0,0,1,0,0,0]])\n \n rShifts = [0]\n cShifts = [0]\n \n rSums = np.sum(binaryImage,axis=0)\n cSums = np.sum(binaryImage,axis=1)\n \n if rSums[0] == 0:\n rShifts.append(-1)\n if rSums[-1] == 0:\n rShifts.append(1)\n if cSums[0] == 0:\n cShifts.append(-1)\n if cSums[-1] == 0:\n cShifts.append(1) \n \n for rShift in rShifts:\n for cShift in cShifts:\n binaryImageShifted = np.roll(binaryImage,(cShift,rShift),(0,1))\n binaryData = binaryImageShifted.reshape((binaryImage.shape[0]*binaryImage.shape[1]))\n binaryString=\"\"\n \n if not (rShift == 0 and cShift == 0):\n nShifts += 1\n if display2:\n plt.figure()\n plt.imshow(binaryImageShifted)\n \n for bit in binaryData:\n if bit==0:\n binaryString+='0'\n else:\n binaryString+='1'\n \n with open('read_data','a') as fup:\n fup.write(binaryString+'\\n')\n \n print(len(groupNumbers),nShifts)","sub_path":"BSU/singleOrigami_test_RUN3.py","file_name":"singleOrigami_test_RUN3.py","file_ext":"py","file_size_in_byte":25178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"159024283","text":"import itertools\n\n# 练习1: 计算在4张牌中排列4中的可能性\nfrom common.iterable_tools import IterableHelper\n\ntuple_poker = (\"红桃3\", \"黑桃2\", \"梅花5\", \"大王\")\n\nlist_result = list(itertools.permutations(tuple_poker, 4))\nprint(len(list_result), list_result)\n\n# 练习2:\"012345\",可以组成多少个不重复的5位偶数\n# list_result = list()\n# print(len(list_result), list_result)\nfor item in filter(lambda item: item[0] != \"0\" and int(item[-1]) % 2 == 0, itertools.permutations(\"012345\", 5)):\n # ('1', '0', '2', '3', '4') -->\"10234\" --> 10234\n print(int(\"\".join(item)))\n","sub_path":"01-python基础/code/day18/exercise03.py","file_name":"exercise03.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"372383244","text":"from whoosh import qparser, index\nfrom collections import Counter\n\ndef full_text_search(search_query):\n print(\"***Load Index_Dir***\")\n ix = index.open_dir(\"/Users/katsu/Project/Program/E-ajSearcher/model/httpd_dir/index\")\n searcher = ix.searcher()\n parser = qparser.QueryParser(\"terms\", schema = ix.schema)\n q = parser.parse(search_query)\n results = searcher.search(q, limit = None,)\n\n author_list = []\n for result in results:\n #print(\"author : {}, body : {}\".format(result[\"author\"], result[\"body\"]))\n print(\"author : {}\".format(result[\"author\"]))\n author_list.append(result[\"author\"])\n author_count = Counter(author_list)\n return author_count\n\nif __name__ == \"__main__\":\n print(len(full_text_search(\"gcore\")))\n","sub_path":"Searcher/full_text_search.py","file_name":"full_text_search.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"157050833","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 3 07:52:07 2020\n\n@author: SungJun Won\n\nThis code is written based on WEC-sim.\nwonsungjun0000@gmail.com\n\nNote: All the struct() has been changed to dictionary\n\nNote: trimesh is used to obtain bodyGeometry properties\n\n\"\"\"\nimport h5py\nimport numpy as np\nimport numpy.matlib \nimport warnings\nimport trimesh\n\nfrom numpy.linalg import inv\nfrom scipy import interpolate\nfrom copy import copy\n\nclass BodyClass:\n def hdf5FileProperties(self):#hdf5 file properties\n \"\"\"\n Hydrodynamic data from BEM or user defined.\n \n \"\"\"\n self.hydroData={'simulation_parameters':{'scaled':[],\n 'wave_dir':[],\n 'water_depth':[],\n 'w':[],\n 'T':[]},\n 'properties':{'name':[],\n 'body_number':[],\n 'cg':[],\n 'cb':[],\n 'disp_vol':[],\n 'dof_start':[],\n 'dof_end':[]},\n 'hydro_coeffs':{'linear_restoring_stiffness':[],\n 'excitation':{'re':[],\n 'im':[],\n 'impulse_response_fun':{'f':[],\n 't':[]}},\n 'added_mass':{'all':[],\n 'inf_freq':[]},\n 'radiation_damping':{'all':[],\n 'impulse_response_fun':{'K':[],\n 't':[]},\n 'state_space':{'it':[],\n 'A':{'all':[]},\n 'B':{'all':[]},\n 'C':{'all':[]},\n 'D':{'all':[]}}},\n 'mean_drift':[]},\n 'gbm':{'mass':[],\n 'stiffness':[],\n 'damping':[]}} \n\n def inputFileProperties(self):#input file properties\n self.name = [] # Body name. For WEC bodies this is given in the h5 file.\n self.mass = [] # Mass in kg or specify 'equilibrium' to have mass= dis vol * density\n self.momOfInertia = [] # Moment of inertia [Ixx, Iyy, Izz] in kg*m^2\n self.cg = [] # Center of gravity [x, y, z] in meters. For WEC bodies this is given in the h5 file.\n self.cb = [] # Center of buoyancy [x, y, z] in meters. For WEC bodies this is given in the h5 file.\n self.dispVol = [] # Displaced volume at equilibrium position in meters cubed. For WEC bodies this is given in the h5 file.\n self.dof = [] # Number of DOFs. For WEC bodies this is given in the h5 file. IF not, default is 6\n self.dof_gbm = [] # Number of DOFs for GBM.\n self.dof_start = [] # Index of DOF starts. For WEC bodies this is given in the h5 file. IF not, default is (bodyNumber-1)*6\n self.dof_end = [] # Index of DOF ends. For WEC bodies this is given in the h5 file. IF not, default is (bodyNumber-1)*6+5\n self.geometryFile = 'NONE' # Location of geomtry stl files\n self.viscDrag = { # Structure defining the viscous (quadratic) drag\n 'Drag': [0,0,0,0,0,0], # Viscous (quadratic) drag, matrix 6x6\n 'cd': [0,0,0,0,0,0], # Viscous (quadratic) drag cd coefficient, vector length 6\n 'characteristicArea': [0,0,0,0,0,0]} # Characteristic area for viscous drag, vector length 6\n self.initDisp = { # Structure defining the initial displacement\n 'initLinDisp': [0,0,0], # Initial displacement of center fo gravity - used for decay tests (format: [displacment in m], default = [0, 0, 0])\n 'initAngularDispAxis': [0,1,0], # Initial displacement of cog - axis of rotation - used for decay tests (format: [x y z], default = [1, 0, 0])\n 'initAngularDispAngle': 0} # Initial displacement of cog - Angle of rotation - used for decay tests (format: [radians], default = 0)\n self.hydroStiffness = [0,0,0,0,0,0] # Hydrostatic stiffness matrix overrides BEMIO definition, matrix 6x6\n self.linearDamping = [0,0,0,0,0,0] # Linear damping coefficient, matrix size of 6x6\n self.userDefinedExcIRF = [] # Excitation IRF from BEMIO used for User-Defined Time-Series\n self.viz = { # Structure defining visualization properties\n 'color': [1,1,0], # Visualization color for either SimMechanics Explorer or Paraview.\n 'opacity': 1} # Visualization opacity for either SimMechanics Explorer or Paraview.\n self.morisonElement = { # Structure defining the Morrison Elements\n 'cd': [0,0,0], # Viscous (quadratic) drag cd, vector length 3\n 'ca': [0,0,0], # Added mass coefficent for Morrison Element (format [Ca_x, Ca_y, Ca_z], default = [0 0 0])\n 'characteristicArea': [0,0,0], # Characteristic area for Morrison Elements calculations (format [Area_x, Area_y, Area_z], default = [0 0 0])\n 'VME': 0 , # Characteristic volume for Morrison Element (default = 0)\n 'rgME': [0,0,0]} # Vector from center of gravity to point of application for Morrison Element (format [X, Y, Z], default = [0 0 0]).\n self.nhBody = 0 # Flag for non-hydro body.\n self.flexHydroBody = 0 # Flag for flexible body. \n self.meanDriftForce = 0 # Flag for mean drift force. 0: No 1: from control surface 2: from momentum conservation.\n \n def bodyGeometryFileProperties(self): # body geometry stl file properties\n self.bodyGeometry = { # Structure defining body's mesh\n 'numFace': [], # Number of faces\n 'numVertex': [], # Number of vertices\n 'vertex': [], # List of vertices\n 'face': [], # List of faces\n 'norm': [], # List of normal vectors\n 'area': [], # List of cell areas\n 'center': []} # List of cell centers\n self.meshFile = [] # body geometry stl file from Trimesh api\n \n def internalProperties(self,filename): # internal properties \n self.hydroForce = {'linearHydroRestCoef':[], # Hydrodynamic forces and coefficients used during simulation.\n 'visDrag':[],\n 'linearDamping':[],\n 'userDefinedFe':[],\n 'fExt':{'re':[],\n 'im':[],\n 'md':[]},\n 'fAddedMass':[],\n 'fDamping':[],\n 'irkb':[],\n 'ssRadf':{'A':[],\n 'B':[],\n 'C':[],\n 'D':[]},\n 'storage':{'mass':[],\n 'momOfInertia':[],\n 'fAddedMass':[],\n 'output_forceAddedMass':[],\n 'output_forceTotal':[]}} \n self.tmp ={'fadm':[], # temporary file\n 'adjmass':[],\n 'mass':[],\n 'momOfInertia':[],\n 'hydroForce_fAddedMass':[]} \n self.h5File = filename # hdf5 file containing the hydrodynamic data\n self.hydroDataBodyNum = [] # Body number within the hdf5 file.\n self.massCalcMethod = [] # Method used to obtain mass: 'user', 'fixed', 'equilibrium'\n self.bodyNumber = [] # bodyNumber in WEC-Sim as defined in the input file. Can be different from the BEM body number.\n self.bodyTotal = 0 # Total number of WEC-Sim bodies (body block iterations)\n self.lenJ = [] # Matrices length. 6 for no body-to-body interactions. 6*numBodies if body-to-body interactions.\n\n def __init__(self,filename):\n \"\"\"\n Initialize Body Class\n Takes string parameter called filename\n filename: name of h5 file\n\n \"\"\"\n self.bodyGeometryFileProperties()\n self.internalProperties(filename)\n self.inputFileProperties()\n self.hdf5FileProperties()\n self.meanDriftForce = 0\n\n def readH5file(self):\n \"\"\"\n Read and recond properties of h5 file in self.hydroData\n\n \"\"\"\n f = h5py.File(self.h5File, 'r')\n name = '/body' + str(self.bodyNumber)\n self.cg = np.transpose(np.array(f.get(name + '/properties/cg')))\n self.cb = np.transpose(np.array(f.get(name + '/properties/cb')))\n self.dispVol = np.array(f.get(name + '/properties/disp_vol'))\n self.name = np.string_(np.array(f.get(name + '/properties/name'))).decode(\"utf-8\")\n self.hydroData['simulation_parameters']['scaled'] = np.array(f.get('/simulation_parameters/scaled'))\n self.hydroData['simulation_parameters']['wave_dir'] = np.transpose(np.array(f.get('/simulation_parameters/wave_dir')))\n if np.array(f.get('/simulation_parameters/water_depth')).dtype == float:\n self.hydroData['simulation_parameters']['water_depth'] = np.array(f.get('/simulation_parameters/water_depth'))\n else: \n self.hydroData['simulation_parameters']['water_depth'] = np.string_(np.array(f.get('/simulation_parameters/water_depth'))).decode(\"utf-8\")\n self.hydroData['simulation_parameters']['w'] = np.transpose(np.array(f.get('/simulation_parameters/w')))\n self.hydroData['simulation_parameters']['T'] = np.transpose(np.array(f.get('/simulation_parameters/T')))\n self.hydroData['properties']['name'] = np.string_(np.array(f.get(name + '/properties/name'))).decode(\"utf-8\")\n self.hydroData['properties']['body_number'] = np.array(f.get(name + '/properties/body_number'))\n self.hydroData['properties']['cg'] = np.transpose(np.array(f.get(name + '/properties/cg')))\n self.hydroData['properties']['cb'] = np.transpose(np.array(f.get(name + '/properties/cb')))\n self.hydroData['properties']['disp_vol'] = np.array(f.get(name + '/properties/disp_vol'))\n if np.array(f.get(name +'/properties/dof')).all() != None:\n self.hydroData['properties']['dof'] = np.array(f.get(name +'/properties/dof')) \n else:\n self.hydroData['properties']['dof'] = np.array(6)\n if np.array(f.get(name + '/properties/dof_start')).all() != None:\n self.hydroData['properties']['dof_start'] = np.array(f.get(name + '/properties/dof_start'))\n else:\n self.hydroData['properties']['dof_start'] = np.array((self.bodyNumber-1)*6+1)\n if np.array(f.get(name + '/properties/dof_end')).all() != None:\n self.hydroData['properties']['dof_end'] = np.array(f.get(name + '/properties/dof_end'))\n else:\n self.hydroData['properties']['dof_end'] = np.array((self.bodyNumber-1)*6+6)\n self.dof = self.hydroData['properties']['dof']\n self.dof_start = self.hydroData['properties']['dof_start']\n self.dof_end = self.hydroData['properties']['dof_end']\n self.dof_gbm = self.dof-6\n self.hydroData['hydro_coeffs']['linear_restoring_stiffness'] = np.transpose(np.array(f.get(name + '/hydro_coeffs/linear_restoring_stiffness')))\n self.hydroData['hydro_coeffs']['excitation']['re'] = np.array(f.get(name + '/hydro_coeffs/excitation/re'))\n self.hydroData['hydro_coeffs']['excitation']['im'] = np.array(f.get(name + '/hydro_coeffs/excitation/im'))\n if np.array(f.get(name + '/hydro_coeffs/excitation/impulse_response_fun/f')).all() != None:\n self.hydroData['hydro_coeffs']['excitation']['impulse_response_fun']['f'] = np.array(f.get(name + '/hydro_coeffs/excitation/impulse_response_fun/f'))\n if np.array(f.get(name + '/hydro_coeffs/excitation/impulse_response_fun/t')).all() != None:\n self.hydroData['hydro_coeffs']['excitation']['impulse_response_fun']['t'] = np.array(f.get(name + '/hydro_coeffs/excitation/impulse_response_fun/t'))\n self.hydroData['hydro_coeffs']['added_mass']['all'] = np.array(f.get(name + '/hydro_coeffs/added_mass/all'))\n self.hydroData['hydro_coeffs']['added_mass']['inf_freq'] = np.array(f.get(name + '/hydro_coeffs/added_mass/inf_freq'))\n self.hydroData['hydro_coeffs']['radiation_damping']['all'] = np.array(f.get(name + '/hydro_coeffs/radiation_damping/all'))\n if np.array(f.get(name + '/hydro_coeffs/radiation_damping/impulse_response_fun/K')).all() != None:\n self.hydroData['hydro_coeffs']['radiation_damping']['impulse_response_fun']['K'] = np.array(f.get(name + '/hydro_coeffs/radiation_damping/impulse_response_fun/K'))\n if np.array(f.get(name +'/hydro_coeffs/radiation_damping/impulse_response_fun/t')).all() != None:\n self.hydroData['hydro_coeffs']['radiation_damping']['impulse_response_fun']['t'] = np.transpose(np.array(f.get(name +'/hydro_coeffs/radiation_damping/impulse_response_fun/t')))\n if np.array(f.get(name + '/hydro_coeffs/radiation_damping/state_space/it')).all() != None:\n self.hydroData['hydro_coeffs']['radiation_damping']['state_space']['it'] = np.array(f.get(name + '/hydro_coeffs/radiation_damping/state_space/it'))\n if np.array(f.get(name + '/hydro_coeffs/radiation_damping/state_space/A/all')).all() != None:\n self.hydroData['hydro_coeffs']['radiation_damping']['state_space']['A']['all'] = np.array(f.get(name + '/hydro_coeffs/radiation_damping/state_space/A/all'))\n if np.array(f.get(name + '/hydro_coeffs/radiation_damping/state_space/B/all')).all() != None:\n self.hydroData['hydro_coeffs']['radiation_damping']['state_space']['B']['all'] = np.array(f.get(name + '/hydro_coeffs/radiation_damping/state_space/B/all'))\n if np.array(f.get(name + '/hydro_coeffs/radiation_damping/state_space/C/all')).all() != None:\n self.hydroData['hydro_coeffs']['radiation_damping']['state_space']['C']['all'] = np.array(f.get(name + '/hydro_coeffs/radiation_damping/state_space/C/all'))\n if np.array(f.get(name + '/hydro_coeffs/radiation_damping/state_space/D/all')).all() != None:\n self.hydroData['hydro_coeffs']['radiation_damping']['state_space']['D']['all'] = np.array(f.get(name +'/hydro_coeffs/radiation_damping/state_space/D/all'))\n if np.array(f.get(name + '/properties/mass')).all() != None:\n tmp = np.array(f.get(name + '/properties/mass'))\n self.hydroData['gbm']['mass'] = [tmp[0].arange(self.dof_start+5,self.dof_end+1),tmp[1].arange(self.dof_start+5,self.dof_end+1)]\n if np.array(f.get(name + '/properties/stiffness')).all() != None:\n tmp = np.array(f.get(name + '/properties/stiffness'))\n self.hydroData['gbm']['stiffness'] = [tmp[0].arange(self.dof_start+5,self.dof_end+1),tmp[1].arange(self.dof_start+5,self.dof_end+1)]\n if np.array(f.get(name + '/properties/damping')).all() != None:\n tmp = np.array(f.get(name + '/properties/damping'))\n self.hydroData['gbm']['damping'] = [tmp[0].arange(self.dof_start+5,self.dof_end+1),tmp[1].arange(self.dof_start+5,self.dof_end+1)]\n if self.meanDriftForce == 0:\n self.hydroData['hydro_coeffs']['mean_drift'] = 0.*self.hydroData['hydro_coeffs']['excitation']['re']\n elif self.meanDriftForce == 1:\n self.hydroData['hydro_coeffs']['mean_drift'] = np.array(f.get(name + '/hydro_coeffs/mean_drift/control_surface/val'))\n elif self.meanDriftForce == 2:\n self.hydroData['hydro_coeffs']['mean_drift'] = np.array(f.get(name + '/hydro_coeffs/mean_drift/momentum_conservation/val'))\n else:\n warnings.warn(\"Wrong flag for mean drift force.\",DeprecationWarning)\n f.close()\n \n def loadHydroData(self, hydroData):\n \"\"\"\n Loads user defiend hydroData structure as alternative\n to reading the h5 file. Used in wecSimMCR\n\n \"\"\"\n self.hydroData = hydroData\n self.cg = hydroData['properties']['cg']\n self.cb = hydroData['properties']['cb']\n self.dispVol = hydroData['properties']['disp_vol']\n self.name = hydroData['properties']['name']\n self.dof = self.hydroData['properties']['dof']\n self.dof_start = self.hydroData['properties']['dof_start']\n self.dof_end = self.hydroData['properties']['dof_end']\n self.dof_gbm = self.dof-6\n \n def hydroForcePre(self,w,waveDir,CIkt,CTTime,numFreq,dt,rho,g,waveType,waveAmpTime,iBod,numBod,ssCalc,nlHydro,B2B):\n \"\"\"\n This is the most important method of this class\n HydroForce Pre-processing calculations\n 1. Set the linear hydrodynamic restoring coefficient, viscous\n drag, and linear damping matrices\n 2. Set the wave excitation force \n\n \"\"\"\n self.setMassMatrix(rho,nlHydro)\n if self.dof_gbm > 0:\n #self.linearDamping = [self.linearDamping np.zeros(1,self.dof-np.size(self.linearDamping))] # to use this you need to define self.linearDamping\n tmp0 = self.linearDamping\n tmp1 = np.size(self.linearDamping)\n self.linearDamping = np.zeros(self.dof[0]) \n self.linearDamping[0][:tmp1[0]] = tmp0[0]\n self.linearDamping[1][:tmp1[1]] = tmp0[1]\n\n tmp0 = self.viscDrag['Drag']\n tmp1 = np.size(self.viscDrag['Drag'])\n self.viscDrag['Drag'] = np.zeros(self.dof) \n self.viscDrag['Drag'][0][:tmp1[0]] = tmp0[0]\n self.viscDrag['Drag'][1][:tmp1[1]] = tmp0[1]\n \n self.viscDrag['cd'] = np.append(self.viscDrag['cd'], np.zeros(self.dof[0]-np.size(self.viscDrag['cd'])))\n self.viscDrag['characteristicArea'] = np.append(self.viscDrag['characteristicArea'],np.zeros(1,self.dof-np.size(self.viscDrag['characteristicArea'])))\n\n if self.hydroStiffness.any() == 1: #check if self.hydroStiffness is defined\n self.hydroForce['linearHydroRestCoef'] = self.hydroStiffness\n else:\n k = self.hydroData['hydro_coeffs']['linear_restoring_stiffness']#(:,self.dof_start:self.dof_end)\n self.hydroForce['linearHydroRestCoef'] = k*rho*g\n\n if self.viscDrag['Drag'].any() == 1: #check if self.viscDrag['Drag'] is defined\n self.hydroForce['visDrag'] = self.viscDrag['Drag']\n else:\n self.hydroForce['visDrag'] = np.diag(0.5*rho*self.viscDrag['cd']*self.viscDrag['characteristicArea'])\n\n self.hydroForce['linearDamping'] = self.linearDamping\n self.hydroForce['userDefinedFe'] = np.zeros((len(waveAmpTime[1]),int(self.dof[0]))) #initializing userDefinedFe for non imported wave cases\n if waveType == 'noWave':\n self.noExcitation()\n self.constAddedMassAndDamping(w,CIkt,rho,B2B)\n elif waveType == 'noWaveCIC':\n self.noExcitation()\n self.irfInfAddedMassAndDamping(CIkt,CTTime,ssCalc,rho,B2B)\n elif waveType == 'regular':\n self.regExcitation(w,waveDir,rho,g)\n self.constAddedMassAndDamping(w,CIkt,rho,B2B)\n elif waveType == 'regularCIC':\n self.regExcitation(w,waveDir,rho,g)\n self.irfInfAddedMassAndDamping(CIkt,CTTime,ssCalc,rho,B2B)\n elif waveType == 'irregular' or waveType == 'spectrumImport':\n self.irrExcitation(w,numFreq,waveDir,rho,g)\n self.irfInfAddedMassAndDamping(CIkt,CTTime,ssCalc,rho,B2B)\n elif waveType == 'etaImport':\n self.userDefinedExcitation(waveAmpTime,dt,waveDir,rho,g)\n self.irfInfAddedMassAndDamping(CIkt,CTTime,ssCalc,rho,B2B)\n\n gbmDOF = self.dof_gbm\n if gbmDOF>0:\n self.hydroForce['gbm']['stiffness']=self.hydroData['gbm']['stiffness']\n self.hydroForce['gbm']['damping']=self.hydroData['gbm']['damping']\n self.hydroForce['gbm']['mass_ff']=[self.hydroForce['fAddedMass'].arange(7,self.dof+1)[self.hydroForce['fAddedMass'].arange(self.dof_start+6,self.dof_end+1)]]+self.hydroData['gbm']['mass'] # need scaling for hydro part\n self.hydroForce['fAddedMass'][7:self.dof+1] = np.zeros(len(np.arange(7,self.dof+1)))\n self.hydroForce['fAddedMass'][(self.dof_start[0]+6):(self.dof_end[0]+1)] = np.zeros(len(np.arange(self.dof_start+6,self.dof_end+1)))\n self.hydroForce['gbm']['mass_ff_inv']=inv(self.hydroForce['gbm']['mass_ff'])\n \n # state-space formulation for solving the GBM\n self.hydroForce['gbm']['state_space']['A'] = [np.zeros((gbmDOF,gbmDOF)), np.eye(gbmDOF,gbmDOF)-inv(self.hydroForce['gbm']['mass_ff'])*self.hydroForce['gbm']['stiffness'],-inv(self.hydroForce['gbm']['mass_ff'])*self.hydroForce['gbm']['damping']] # move to ... hydroForce sector with scaling . # or create a new fun for all flex parameters\n self.hydroForce['gbm']['state_space']['B'] = np.eye(2*gbmDOF,2*gbmDOF)\n self.hydroForce['gbm']['state_space']['C'] = np.eye(2*gbmDOF,2*gbmDOF)\n self.hydroForce['gbm']['state_space']['D'] = np.zeros((2*gbmDOF,2*gbmDOF))\n self.flexHydroBody = 1\n self.nhBody=0\n \n def adjustMassMatrix(self,adjMassWeightFun,B2B):\n \"\"\"\n Merge diagonal term of added mass matrix to the mass matrix\n 1. Store the original mass and added-mass properties\n 2. Add diagonal added-mass inertia to moment of inertia\n 3. Add the maximum diagonal traslational added-mass to body\n mass - this is not the correct description\n\n \"\"\"\n iBod = self.bodyNumber\n self.hydroForce['storage']['mass'] = copy(self.mass) # use copy method to set it as seperate variable\n self.hydroForce['storage']['momOfInertia'] = copy(self.momOfInertia)\n self.hydroForce['storage']['fAddedMass'] = copy(self.hydroForce['fAddedMass'])\n if B2B == 1:\n self.tmp['fadm'] = np.diag(self.hydroForce['fAddedMass'],k =(iBod-1)*6)\n self.tmp['adjmass'] = sum(self.tmp['fadm'][0:3]*adjMassWeightFun)\n self.mass = self.mass + self.tmp['adjmass']\n self.momOfInertia = self.momOfInertia+self.tmp['fadm'][3:6]\n self.hydroForce['fAddedMass'][0,(iBod-1)*6] = self.hydroForce['fAddedMass'][0,(iBod-1)*6] - self.tmp['adjmass']\n self.hydroForce['fAddedMass'][1,1+(iBod-1)*6] = self.hydroForce['fAddedMass'][1,1+(iBod-1)*6] - self.tmp['adjmass']\n self.hydroForce['fAddedMass'][2,2+(iBod-1)*6] = self.hydroForce['fAddedMass'][2,2+(iBod-1)*6] - self.tmp['adjmass']\n self.hydroForce['fAddedMass'][3,3+(iBod-1)*6] = 0\n self.hydroForce['fAddedMass'][4,4+(iBod-1)*6] = 0\n self.hydroForce['fAddedMass'][5,5+(iBod-1)*6] = 0\n else:\n self.tmp['fadm'] = np.diag(self.hydroForce['fAddedMass'])\n self.tmp['adjmass'] = sum(self.tmp['fadm'][0:3])*adjMassWeightFun # scalar value for adjMassWeighFun\n self.mass = self.mass + self.tmp['adjmass']\n self.momOfInertia = self.momOfInertia + self.tmp['fadm'][3:6]\n self.hydroForce['fAddedMass'][0,0] = self.hydroForce['fAddedMass'][0,0] - self.tmp['adjmass']\n self.hydroForce['fAddedMass'][1,1] = self.hydroForce['fAddedMass'][1,1] - self.tmp['adjmass']\n self.hydroForce['fAddedMass'][2,2] = self.hydroForce['fAddedMass'][2,2] - self.tmp['adjmass']\n self.hydroForce['fAddedMass'][3,3] = 0\n self.hydroForce['fAddedMass'][4,4] = 0\n self.hydroForce['fAddedMass'][5,5] = 0\n\n def restoreMassMatrix(self):\n \"\"\"\n Restore the mass and added-mass matrix back to the original value\n Used copy method to set as new variables\n \"\"\"\n self.tmp['mass'] = copy(self.mass)\n self.tmp['momOfInertia'] = copy(self.momOfInertia)\n self.tmp['hydroForce_fAddedMass'] = copy(self.hydroForce['fAddedMass'])\n self.mass = copy(self.hydroForce['storage']['mass'])\n self.momOfInertia = copy(self.hydroForce['storage']['momOfInertia'])\n self.hydroForce['fAddedMass'] = copy(self.hydroForce['storage']['fAddedMass'])\n self.hydroForce['storage']['mass'] = copy(self.tmp['mass'])\n self.hydroForce['storage']['momOfInertia'] = copy(self.tmp['momOfInertia'])\n self.hydroForce['storage']['fAddedMass'] = copy(self.tmp['hydroForce_fAddedMass'])\n \n def storeForceAddedMass(self,am_mod,ft_mod):\n \"\"\"\n Store the modified added mass and total forces history (inputs)\n \"\"\"\n self.hydroForce['storage']['output_forceAddedMass'] = am_mod\n self.hydroForce['storage']['output_forceTotal'] = ft_mod\n \n def setInitDisp(self, x_rot, ax_rot, ang_rot, addLinDisp):\n \"\"\"\n Function to set the initial displacement when having initial rotation\n x_rot: rotation point\n ax_rot: axis about which to rotate (must be a normal vector)\n ang_rot: rotation angle in radians\n addLinDisp: initial linear displacement (in addition to the displacement caused by rotation)\n \"\"\"\n cg = self.cg\n relCoord = cg - x_rot\n rotatedRelCoord = self.rotateXYZ(relCoord,ax_rot,ang_rot)\n newCoord = rotatedRelCoord + x_rot\n linDisp = newCoord-cg\n self.initDisp = {'initLinDisp':(linDisp + addLinDisp), \n 'initAngularDispAxis': ax_rot, \n 'initAngularDispAngle': ang_rot} \n \n def listInfo(self):\n \"\"\"\n List body info{:f}\\n'.format(self.T)\n \"\"\"\n print('\\n\\t***** Body Number ', self.hydroData['properties']['body_number'][0][0] ,', Name: ' , self.hydroData['properties']['name'] , ' *****\\n')\n print('\\tBody CG (m) = [',self.hydroData['properties']['cg'][0],']\\n')\n print('\\tBody Mass (kg) = ',self.mass[0][0],' \\n')\n print('\\tBody Diagonal MOI (kgm2)= [',self.momOfInertia,']\\n')\n\n def bodyGeo(self,fname):\n \"\"\"\n Reads mesh file and calculates areas and centroids\n Use trimesh to get geometry values besides using the method from WEC-Sim\n Takes in string parameter called fname. fname is name of stl file\n\n \"\"\"\n your_mesh = trimesh.load_mesh(fname)\n self.meshFile = your_mesh\n v = your_mesh.triangles.reshape(int(np.size(your_mesh.triangles)/3),3)\n [vertex,faces] = np.unique(v,return_inverse=True,axis=0)\n face = faces.reshape(int(np.size(faces)/3),3)+1\n self.bodyGeometry['vertex'] = vertex\n self.bodyGeometry['numVertex'] = np.size(vertex,0)\n self.bodyGeometry['face'] = face\n self.bodyGeometry['numFace'] = np.size(face,0)\n self.bodyGeometry['norm'] = your_mesh.face_normals\n self.bodyGeometry['center'] = your_mesh.triangles_center\n self.bodyGeometry['area'] = np.transpose([your_mesh.area_faces]) \n \n def plotStl(self):\n \"\"\"\n Plots the body's mesh\n networkx is required if you want to use this function\n\n \"\"\"\n # Plots the body's mesh\n your_mesh = self.meshFile\n your_mesh.show()\n \n def checkinputs(self):\n \"\"\"\n Checks the user inputs\n\n \"\"\"\n # hydro data file\n if self.h5File == None and self.nhBody == 0:\n warnings.warn(\"The hdf5 file does not exist\")\n # geometry file\n if self.geometryFile == None:\n warnings.warn(\"Could not locate and open geometry file\")\n \n\n def noExcitation(self):\n \"\"\"\n Set exciation force for no excitation case\n Gets used in hydroForcePre for noWave condition\n \"\"\"\n nDOF = int(self.dof[0])\n self.hydroForce['fExt']['re'] = np.zeros(nDOF)\n self.hydroForce['fExt']['im'] = np.zeros(nDOF)\n \n \n def regExcitation(self,w,waveDir,rho,g):\n \"\"\"\n Regular wave excitation force\n Used by hydroForcePre \n\n \"\"\"\n nDOF = int(self.dof[0])\n re = self.hydroData['hydro_coeffs']['excitation']['re']*rho*g\n im = self.hydroData['hydro_coeffs']['excitation']['im']*rho*g\n md = self.hydroData['hydro_coeffs']['mean_drift']*rho*g\n self.hydroForce['fExt']['re'] = np.zeros(nDOF)\n self.hydroForce['fExt']['im'] = np.zeros(nDOF)\n self.hydroForce['fExt']['md'] = np.zeros(nDOF)\n for ii in range(nDOF):\n if np.size(self.hydroData['simulation_parameters']['wave_dir']) > 1:\n x = self.hydroData['simulation_parameters']['w'][0]\n y = self.hydroData['simulation_parameters']['wave_dir'][0]\n s1 = interpolate.interp2d(x,y, np.squeeze(re[ii]))# interpolate using interp2d to get interpolation of 2d space\n self.hydroForce['fExt']['re'][ii] = s1(w[0],waveDir)\n s2 = interpolate.interp2d(x,y, np.squeeze(im[ii]))\n self.hydroForce['fExt']['im'][ii] = s2(w[0],waveDir)\n s3 = interpolate.interp2d(x,y, np.squeeze(md[ii]))\n self.hydroForce['fExt']['md'][ii] = s3(w[0],waveDir)\n elif self.hydroData['simulation_parameters']['wave_dir'] == waveDir:\n x = self.hydroData['simulation_parameters']['w'][0]\n s1 = interpolate.CubicSpline(x, np.squeeze(re[ii][0]))# interpolate using CubicSline to get interpolation of spline 3d space\n s2 = interpolate.CubicSpline(x, np.squeeze(im[ii][0]))\n s3 = interpolate.CubicSpline(x, np.squeeze(md[ii][0]))\n self.hydroForce['fExt']['re'][ii] = s1(w)\n self.hydroForce['fExt']['im'][ii] = s2(w)\n self.hydroForce['fExt']['md'][ii] = s3(w)\n\n def irrExcitation(self,wv,numFreq,waveDir,rho,g):\n \"\"\"\n Irregular wave excitation force\n Used by hydroForcePre\n\n \"\"\"\n nDOF = int(self.dof[0])\n re = self.hydroData['hydro_coeffs']['excitation']['re']*rho*g\n im = self.hydroData['hydro_coeffs']['excitation']['im']*rho*g\n md = self.hydroData['hydro_coeffs']['mean_drift']*rho*g\n self.hydroForce['fExt']['re'] = np.zeros((np.size(waveDir),numFreq,nDOF))\n self.hydroForce['fExt']['im'] = np.zeros((np.size(waveDir),numFreq,nDOF))\n self.hydroForce['fExt']['md'] = np.zeros((np.size(waveDir),numFreq,nDOF))\n for ii in range(nDOF):\n if np.size(self.hydroData['simulation_parameters']['wave_dir']) > 1:\n x = self.hydroData['simulation_parameters']['w'][0]\n y = self.hydroData['simulation_parameters']['wave_dir'][0]\n s1 = interpolate.interp2d(x,y, np.squeeze(re[ii]))# interpolate using interp2d to get interpolation of 2d space\n self.hydroForce['fExt']['re'][:,:,ii] = s1(wv[0],waveDir)\n s2 = interpolate.interp2d(x,y, np.squeeze(im[ii]))\n self.hydroForce['fExt']['im'][:,:,ii] = s2(wv[0],waveDir)\n s3 = interpolate.interp2d(x,y, np.squeeze(md[ii]))\n self.hydroForce['fExt']['md'][:,:,ii] = s3(wv[0],waveDir)\n elif self.hydroData['simulation_parameters']['wave_dir'] == waveDir:\n x = self.hydroData['simulation_parameters']['w'][0]\n s1 = interpolate.CubicSpline(x, np.squeeze(re[ii][0]))# interpolate using CubicSline to get interpolation of spline 3d space\n s2 = interpolate.CubicSpline(x, np.squeeze(im[ii][0]))\n s3 = interpolate.CubicSpline(x, np.squeeze(md[ii][0]))\n self.hydroForce['fExt']['re'][:,:,ii] = s1(wv)\n self.hydroForce['fExt']['im'][:,:,ii] = s2(wv)\n self.hydroForce['fExt']['md'][:,:,ii] = s3(wv)\n \n def userDefinedExcitation(self,waveAmpTime,dt,waveDir,rho,g):\n \"\"\"\n Calculated User-Defined wave excitation force with non-causal convolution\n Used by hydroForcePre\n \n \"\"\"\n nDOF = int(self.dof[0])\n kf = self.hydroData['hydro_coeffs']['excitation']['impulse_response_fun']['f']*rho*g\n kt = self.hydroData['hydro_coeffs']['excitation']['impulse_response_fun']['t'][0]\n t = arange_MATLAB(np.min(kt),np.max(kt)+dt,dt)\n for ii in range(nDOF):\n if np.size(self.hydroData['simulation_parameters']['wave_dir']) > 1:\n y = self.hydroData['simulation_parameters']['wave_dir'][0] \n s1 = interpolate.interp2d(kt,y, np.squeeze(kf[ii])) # interpolate using interp2d to get interpolation of 2d space\n self.userDefinedExcIRF = s1(t,waveDir)\n elif self.hydroData['simulation_parameters']['wave_dir'] == waveDir:\n s1 = interpolate.CubicSpline(kt, np.squeeze(kf[ii][0])) # interpolate using CubicSline to get interpolation of spline 3d space\n self.userDefinedExcIRF = s1(t)\n else:\n warnings.warn(\"Default wave direction different from hydro database value. Wave direction (waves.waveDir) should be specified on input file.\",DeprecationWarning)\n \n self.hydroForce['userDefinedFe'][:,ii] = np.convolve(waveAmpTime[1],self.userDefinedExcIRF,'valid')*dt\n \n self.hydroForce['fExt']['re'] = np.zeros(nDOF)\n self.hydroForce['fExt']['im'] = np.zeros(nDOF)\n self.hydroForce['fExt']['md'] = np.zeros(nDOF)\n \n \n def constAddedMassAndDamping(self,w,CIkt,rho,B2B):\n \"\"\"\n Set added mass and damping for a specific frequency\n Used by hydroForcePre\n \n \"\"\"\n am = self.hydroData['hydro_coeffs']['added_mass']['all']*rho\n rd = self.hydroData['hydro_coeffs']['radiation_damping']['all']*rho\n for i in range(len(self.hydroData['simulation_parameters']['w'][0])):\n rd[:,:,i] *= self.hydroData['simulation_parameters']['w'][0][i]\n # Change matrix size: B2B [6x6n], noB2B [6x6]\n if B2B == 1:\n lenJ = 6*int(self.bodyTotal[0])\n self.hydroForce['fAddedMass'] = np.zeros((6,lenJ))\n self.hydroForce['fDamping'] = np.zeros((6,lenJ))\n self.hydroForce['totDOF'] = np.zeros((6,lenJ))\n for ii in range(6):\n for jj in range(lenJ):\n s1 = interpolate.CubicSpline(self.hydroData['simulation_parameters']['w'][0], np.squeeze(am[ii,jj,:]))\n self.hydroForce['fAddedMass'][ii,jj] = s1(w)\n s2 = interpolate.CubicSpline(self.hydroData['simulation_parameters']['w'][0], np.squeeze(rd[ii,jj,:]))\n self.hydroForce['fDamping'][ii,jj] = s2(w)\n else: #B2B =2\n nDOF = int(self.dof[0])\n self.hydroForce['fAddedMass'] = np.zeros((nDOF,nDOF))\n self.hydroForce['fDamping'] = np.zeros((nDOF,nDOF))\n self.hydroForce['totDOF'] = np.zeros((nDOF,nDOF))\n for ii in range(nDOF):\n for jj in range(nDOF):\n jjj = int(self.dof_start[0])-1+jj\n s1 = interpolate.CubicSpline(self.hydroData['simulation_parameters']['w'][0], np.squeeze(am[ii,jjj,:]))\n self.hydroForce['fAddedMass'][ii,jj] = s1(w)\n s2 = interpolate.CubicSpline(self.hydroData['simulation_parameters']['w'][0], np.squeeze(rd[ii,jjj,:]))\n self.hydroForce['fDamping'][ii,jj] = s2(w)\n \n \n def irfInfAddedMassAndDamping(self,CIkt,CTTime,ssCalc,rho,B2B):\n \"\"\"\n Set radiation force properties using impulse response function\\\n Added mass at infinite frequency\n Convolution integral raditation dampingiBod\n State space formulation\n Used by hydroForcePre\n \n \"\"\"\n nDOF = int(self.dof[0])\n if B2B == 1:\n LDOF = int(self.bodyTotal[0])*6\n else:\n LDOF = int(self.dof[0])\n \n # Convolution integral formulation\n if B2B == 1:\n self.hydroForce['fAddedMass'] = self.hydroData['hydro_coeffs']['added_mass']['inf_freq']*rho\n else:\n self.hydroForce['fAddedMass'] = self.hydroData['hydro_coeffs']['added_mass']['inf_freq'][:,int(self.dof_start[0])-1:int(self.dof_end[0])]*rho\n \n # Radition IRF\n self.hydroForce['fDamping'] = np.zeros((nDOF,LDOF))\n irfk = self.hydroData['hydro_coeffs']['radiation_damping']['impulse_response_fun']['K']*rho\n irft = self.hydroData['hydro_coeffs']['radiation_damping']['impulse_response_fun']['t'][0]\n self.hydroForce['irkb'] = np.zeros((len(CTTime),nDOF,LDOF))\n if B2B == 1:\n for ii in range(nDOF):\n for jj in range(LDOF):\n s1 = interpolate.CubicSpline(irft, np.squeeze(irfk[ii,jj,:]))\n self.hydroForce['irkb'][:,ii,jj] = s1(CTTime)\n else:\n for ii in range(nDOF):\n for jj in range(LDOF):\n jjj = int(self.dof_start[0])-1+jj\n s1 = interpolate.CubicSpline(irft, np.squeeze(irfk[ii,jjj,:]))\n self.hydroForce['irkb'][:,ii,jj] = s1(CTTime)\n \n # State Space Formulation\n if ssCalc == 1:\n if B2B == 1:\n for ii in range(nDOF):\n for jj in range(LDOF):\n arraySize = int(self.hydroData['hydro_coeffs']['radiation_damping']['state_space']['it'][ii,jj])\n if ii == 0 and jj == 0: # Begin construction of combined state, input, and output matrices\n Af = np.zeros((arraySize,arraySize))\n Bf = np.zeros((arraySize,LDOF))\n Cf = np.zeros((nDOF,arraySize))\n Af[:arraySize,:arraySize] = self.hydroData['hydro_coeffs']['radiation_damping']['state_space']['A']['all'][ii,jj,:arraySize,:arraySize]\n Bf[:arraySize,jj] = self.hydroData['hydro_coeffs']['radiation_damping']['state_space']['B']['all'][ii,jj,:arraySize,0]\n Cf[ii,:arraySize] = self.hydroData['hydro_coeffs']['radiation_damping']['state_space']['C']['all'][ii,jj,0,:arraySize]\n else:\n Ay = np.size(Af,0)\n Ax = np.size(Af,1)\n Af = np.pad(Af, ((0,arraySize),(0,arraySize)), mode='constant', constant_values=0)\n Af[Ay:Ay+arraySize,Ax:Ax+arraySize] = self.hydroData['hydro_coeffs']['radiation_damping']['state_space']['A']['all'][ii,jj,:arraySize,:arraySize]\n By = np.size(Bf,0)\n Bf = np.pad(Bf, ((0,arraySize),(0,0)), mode='constant', constant_values=0)\n Bf[By:By+arraySize,jj] = self.hydroData['hydro_coeffs']['radiation_damping']['state_space']['B']['all'][ii,jj,:arraySize,0]\n Cx = np.size(Cf,1)\n Cf = np.pad(Cf, ((0,0),(0,arraySize)), mode='constant', constant_values=0)\n Cf[ii,Cx:Cx+arraySize] = self.hydroData['hydro_coeffs']['radiation_damping']['state_space']['C']['all'][ii,jj,0,:arraySize]\n self.hydroForce['ssRadf']['D'] = np.zeros((nDOF,LDOF))\n else:\n for ii in range(nDOF):\n for jj in range(int(self.dof_start[0])-1,int(self.dof_end[0])):\n jInd = jj-int(self.dof_start[0])+1\n arraySize = int(self.hydroData['hydro_coeffs']['radiation_damping']['state_space']['it'][ii,jj])\n if ii == 0 and jInd == 0: # Begin construction of combined state, input, and output matrices\n Af = np.zeros((arraySize,arraySize))\n Bf = np.zeros((arraySize,LDOF))\n Cf = np.zeros((nDOF,arraySize))\n Af[:arraySize,:arraySize] = self.hydroData['hydro_coeffs']['radiation_damping']['state_space']['A']['all'][ii,jj,:arraySize,:arraySize]\n Bf[:arraySize,jInd] = self.hydroData['hydro_coeffs']['radiation_damping']['state_space']['B']['all'][ii,jj,:arraySize,0]\n Cf[ii,:arraySize] = self.hydroData['hydro_coeffs']['radiation_damping']['state_space']['C']['all'][ii,jj,0,:arraySize]\n else:\n Ay = np.size(Af,0)\n Ax = np.size(Af,1)\n Af = np.pad(Af, ((0,arraySize),(0,arraySize)), mode='constant', constant_values=0)\n Af[Ay:Ay+arraySize,Ax:Ax+arraySize] = self.hydroData['hydro_coeffs']['radiation_damping']['state_space']['A']['all'][ii,jj,:arraySize,:arraySize]\n By = np.size(Bf,0)\n Bf = np.pad(Bf, ((0,arraySize),(0,0)), mode='constant', constant_values=0)\n Bf[By:By+arraySize,jInd] = self.hydroData['hydro_coeffs']['radiation_damping']['state_space']['B']['all'][ii,jj,:arraySize,0]\n Cx = np.size(Cf,1)\n Cf = np.pad(Cf, ((0,0),(0,arraySize)), mode='constant', constant_values=0)\n Cf[ii,Cx:Cx+arraySize] = self.hydroData['hydro_coeffs']['radiation_damping']['state_space']['C']['all'][ii,jj,0,:arraySize]\n self.hydroForce['ssRadf']['D'] = np.zeros((nDOF,nDOF))\n self.hydroForce['ssRadf']['A'] = Af\n self.hydroForce['ssRadf']['B'] = Bf\n self.hydroForce['ssRadf']['C'] = Cf*rho\n \n def setMassMatrix(self, rho, nlHydro):\n \"\"\"\n Sets mass for the special cases of body at equilibrium or fixed\n Used by hydroForcePre\n \n \"\"\"\n if self.mass == 'equilibrium':\n self.massCalcMethod = self.mass\n if nlHydro == 0:\n self.mass = self.hydroData['properties']['disp_vol'] * rho\n else:\n cg_tmp = self.hydroData['properties']['cg'][0]\n z = np.conj(np.transpose(np.array(self.bodyGeometry['center'])))[2] + cg_tmp[2]\n zr = [0 if x > 0 else x for x in z]\n area = np.conj(np.transpose(self.bodyGeometry['area']))[0]\n av = np.array([area,area,area])*-1*np.conj(np.transpose(self.bodyGeometry['norm']))\n tmp = rho*np.array([zr, zr, zr])*-1*av\n self.mass = sum(tmp[2])\n elif self.mass == 'fixed':\n self.massCalcMethod = self.mass\n self.mass = 999\n self.momOfInertia = [999, 999, 999]\n else:\n self.massCalcMethod = 'user'\n \n def forceAddedMass(self,acc,B2B):\n \"\"\"\n Calculates and outputs the real added mass force time history\n \n \"\"\"\n iBod = self.bodyNumber\n fam = np.zeros(np.shape(acc))\n for i in range(6):\n tmp = np.zeros(np.size(acc[:,i]))\n for j in range(6):\n if B2B == 1:\n jj = (iBod-1)*6+j\n else:\n jj = j\n iam = self.hydroForce['fAddedMass'][i,jj]\n tmp = tmp + acc[:,j]* iam\n fam[:,i] = tmp\n return(fam)\n \n def rotateXYZ(self,x,ax,t):\n \"\"\"\n Function to rotate a point about an arbitrary axis\n x: 3-componenet coordiantes\n ax: axis about which to rotate (must be a normal vector)\n t: rotation angle\n xn: new coordinates after rotation\n \n \"\"\"\n rotMat = np.zeros((3,3))\n rotMat[0,0] = ax[0]*ax[0]*(1-np.cos(t)) + np.cos(t)\n rotMat[0,1] = ax[1]*ax[0]*(1-np.cos(t)) + ax[2]*np.sin(t)\n rotMat[0,2] = ax[2]*ax[0]*(1-np.cos(t)) - ax[1]*np.sin(t)\n rotMat[1,0] = ax[0]*ax[1]*(1-np.cos(t)) - ax[2]*np.sin(t)\n rotMat[1,1] = ax[1]*ax[1]*(1-np.cos(t)) + np.cos(t)\n rotMat[1,2] = ax[2]*ax[1]*(1-np.cos(t)) + ax[0]*np.sin(t)\n rotMat[2,0] = ax[0]*ax[2]*(1-np.cos(t)) + ax[1]*np.sin(t)\n rotMat[2,1] = ax[1]*ax[2]*(1-np.cos(t)) - ax[0]*np.sin(t)\n rotMat[2,2] = ax[2]*ax[2]*(1-np.cos(t)) + np.cos(t)\n xn = np.dot(x,rotMat)\n return(xn)\n \n \n def offsetXYZ(self,verts,x):\n \"\"\"\n Function to move the position vertices\n \n \"\"\"\n verts_out = np.zeros(3)#for now change when being tested later\n verts_out[0] = verts[0] + x[0]\n verts_out[1] = verts[1] + x[1]\n verts_out[2] = verts[2] + x[2]\n return verts_out\n\ndef arange_MATLAB(start, end, step):\n \"\"\"\n Change np.arange to have same sequence as MATLAB when step is float\n \"\"\"\n return step*np.arange(start/step, np.floor(end/step))\n ","sub_path":"tests/test_objects/test_bodyclass/bodyclass/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":48239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"257766294","text":"from sys import argv\nfrom csv import reader\n\nsrc_file = argv[1]\nf = open(src_file,\"r\")\ncolumns = argv[2:]\nfreq = [0]*len(columns)\nfor line in reader(f):\n\tfor i in range(len(columns)):\n\t\tif line[int(columns[i])-1] != \" 0\":\n\t\t\tfreq[i] += 1\nprint(zip(columns,freq))\n","sub_path":"rankfeatures.py","file_name":"rankfeatures.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"560428073","text":"from django.shortcuts import render_to_response\nfrom django.utils.html import strip_tags\nfrom django.utils import dateformat\nfrom django.utils import timezone\n\nfrom itertools import izip_longest\n\nimport meetup.api\nimport datetime\nimport pytz\n\nperth_timezone = pytz.timezone('Australia/Perth')\n\ndef get_events(event_status, from_date):\n client = meetup.api.Client('73c42797541a6c207a2a2b41262a66')\n\n group_info = client.GetGroup({'urlname': 'Perth-Django-Users-Group'})\n try:\n group_events = client.GetEvents({'group_id': group_info.id, 'status': event_status}).results\n except ValueError:\n group_events = []\n\n iterable = (\n (lambda event_datetime: {\n 'group_id': group_info.id,\n 'event_id': event['id'],\n 'event_name': event['name'],\n 'event_url': event['event_url'],\n 'og_event_name': '({}) {}'.format(dateformat.format(event_datetime, 'D d M'), event['name']),\n 'event_address': '{}, {}'.format(event['venue']['name'], event['venue']['address_1']) if 'venue' in event else '',\n 'event_description': event['description'],\n 'og_event_description': strip_tags(event['description']).encode('ascii', 'ignore'),\n 'event_yes_rsvp_count': event['yes_rsvp_count'],\n 'event_datetime': event_datetime,\n })(datetime.datetime.fromtimestamp(event['time'] / 1000.0, perth_timezone))\n for event in sorted(group_events, key=lambda d: d['time']))\n\n return [\n event\n for event in iterable\n if event['event_datetime'] >= from_date\n ]\n\ndef home_page(request):\n date_str = ''.join(request.GET.keys()).strip()\n if date_str:\n now = timezone.now()\n default_args = (now.year, now.month, 1)\n user_args = map(int, date_str.split('-'))\n args = tuple(\n user_num or default\n for default, user_num in izip_longest(default_args, user_args))\n date = datetime.datetime(*args, tzinfo=perth_timezone)\n else:\n date = timezone.now()\n try:\n coming_event = get_events('upcoming', date)[0]\n except IndexError:\n coming_event = {\n 'event_name': 'No upcoming event',\n 'event_description': 'Check back in the middle of the month',\n 'og_event_description': 'Check back in the middle of the month',\n }\n return render_to_response(\n 'home.html',\n {\n 'coming_event': coming_event, \n },\n # context_instance=RequestContext(request)\n )\n\n\ndef get_involved(request):\n return render_to_response(\n 'getinvolved.html',\n {\n },\n\n # context_instance=RequestContext(request)\n )\n\n\ndef ajax_meetups_tab(request, event_status):\n \"\"\"\n Queries the meetup.com API to get all the events of the status specified\n\n :param request:\n :param event_status: upcoming, past, proposed, suggested, cancelled, draft\n :return:\n \"\"\"\n events = get_events(event_status, timezone.now())\n\n return render_to_response(\n 'ajax/ajax_meetups.html',\n {\n \"group_events\": events,\n\n 'event_status': event_status,\n })\n","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"510136694","text":"import random\nimport time\n\nboard = list(range(0, 10)) # 3x3 board for the game\ngame_on = 1 # 1=game runs or 0=game stops\ngamerounds = 0 # all game rounds\nturns = 0 # turn num in a game\nwhos_first = 0 # which player is first 1 or 2\nwin_rows = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]]\nwho_wins = \"\" # who wins the game? x or o? or draw?\np1wins = 0 # P1 score count\np2wins = 0 # P2 score count\ndraws = 0 # Draw count\nscore_sets = {}\n\n\ndef new_game(): # new game. resets a lot of things...\n global board\n global turns\n global gamerounds\n global game_on\n board = [\" \"]*10\n gamerounds += 1\n turns = 1\n game_on = 1\n random_player_first()\n show()\n\n\ndef random_player_first():\n global whos_first\n whos_first = random.randint(1, 2)\n\n\ndef end_game(): # end game. add score count\n global p1wins\n global p2wins\n global draws\n if who_wins == \"x\":\n p1wins += 1\n elif who_wins == \"o\":\n p2wins += 1\n elif who_wins == \"draw\":\n draws += 1\n win_message()\n\n\ndef reset_scores(): # reset scores\n global p1wins\n global p2wins\n global draws\n global gamerounds\n global turns\n board = range(0, 10)\n gamerounds, turns, p1wins, p2wins, draws = 0, 0, 0, 0, 0\n print(\" Resetting scores, please wait...\")\n time.sleep(2)\n\n\ndef win_message():\n if who_wins == \"x\":\n print(\"\\033[1;31m\", \"Player1 wins!!!\", \"\\033[0m\")\n elif who_wins == \"o\":\n print(\"\\033[1;32m\", \"Player2 wins!!!\", \"\\033[0m\")\n elif who_wins == \"draw\":\n print(\" It's a draw!!!\")\n time.sleep(2)\n\n\ndef use_free_spot(spot, char):\n if board[spot] == \" \":\n board[spot] = char\n return True\n\n\ndef check_line(char, row): # checks if 3 index of list is equal\n if board[row[0]] == char and board[row[1]] == char and board[row[2]] == char:\n return True\n\n\ndef check_win(char): # checks each row for win, or draw at round number 9\n global game_on\n global who_wins\n for row in win_rows:\n if check_line(char, row):\n who_wins = char\n game_on = 0\n return\n if turns == 10:\n who_wins = \"draw\"\n game_on = 0\n return\n\n\ndef check_win_ai(char): # checks each row for win option for AI\n for row in win_rows:\n if check_line(char, row):\n return True\n\n\ndef player_input(): # keyoard input only from 1-9\n while True:\n try:\n x = int(input(\" Select a spot: \"))\n if x in range(1, 10):\n return x\n break\n else:\n print(\" Please use numbers only between 1-9!\")\n continue\n except ValueError:\n print(\" Please use the number keys, from 1-9!\")\n continue\n\n\ndef player_turn(char): # Player input, checks if the spot is taken\n while True:\n if char == \"x\":\n print(\"\\033[1;31m\", \"Player1 turn!\", \"\\033[0m\")\n else:\n print(\"\\033[1;32m\", \"Player2 turn!\", \"\\033[0m\")\n newspot = player_input()\n if use_free_spot(newspot, char):\n end_turn(char)\n break\n else:\n print (\" You can't put your '%s' there, it is already taken!\" % (char))\n\n\ndef end_turn(char):\n global turns\n turns += 1\n check_win(char)\n show()\n\n\ndef ai_turn_easy(char): # Player against AI\n print(\"\\033[1;36m\", \"AI turn!\", \"\\033[0m\")\n time.sleep(1)\n print(\"\\033[1;36m\", \"AI is thinking...\", \"\\033[0m\")\n time.sleep(2)\n while True:\n AI = random.randint(1, 9)\n if use_free_spot(AI, \"o\"):\n break\n end_turn(\"o\")\n\n\ndef ai_turn_hard(char): # Player against AI HARD MODE\n ok_spot = 0\n print(\"\\033[1;36m\", \"AI turn!\", \"\\033[0m\")\n time.sleep(1)\n print(\"\\033[1;36m\", \"AI is thinking...(for real)\", \"\\033[0m\")\n time.sleep(2)\n ai_pick_spot_hard()\n end_turn(\"o\")\n\n\ndef ai_pick_spot_hard():\n while True:\n AI = random.randint(1, 9)\n for i in range(1, 10):\n if use_free_spot(i, \"o\"):\n if check_win_ai(\"o\"):\n board[i] = \"o\"\n return\n else:\n board[i] = \" \"\n if use_free_spot(i, \"x\"):\n if check_win_ai(\"x\"):\n board[i] = \"o\"\n return\n else:\n board[i] = \" \"\n if use_free_spot(AI, \"o\"):\n return\n\n\ndef ai_turn_god(char): # Player against AI GOD MODE\n print(\"\\033[1;36m\", \"AI turn!\", \"\\033[0m\")\n time.sleep(1)\n print(\"\\033[1;36m\", \"AI is thinking...(like a God!!!)\", \"\\033[0m\")\n time.sleep(2)\n ai_pick_spot_god()\n end_turn(\"o\")\n\n\ndef ai_pick_spot_god():\n while True:\n AI = random.randint(1, 9)\n if use_free_spot(5, \"o\"):\n return\n for i in range(1, 10):\n if use_free_spot(i, \"o\"):\n if check_win_ai(\"o\"):\n board[i] = \"o\"\n return\n else:\n board[i] = \" \"\n if use_free_spot(i, \"x\"):\n if check_win_ai(\"x\"):\n board[i] = \"o\"\n return\n else:\n board[i] = \" \"\n if whos_first == 1 and turns == 2: # if P1 first and center is taken, try to hit corners\n for i in (1, 3, 7, 9):\n if board[i] == \" \":\n board[i] = \"o\"\n return\n if whos_first == 1 and turns == 4: # if P1 first, try to hit corners\n if board[2] == \"x\" and board[4] == \"x\":\n if board[1] == \" \":\n board[1] = \"o\"\n return\n if board[2] == \"x\" and board[6] == \"x\":\n if board[3] == \" \":\n board[3] = \"o\"\n return\n if board[8] == \"x\" and board[4] == \"x\":\n if board[7] == \" \":\n board[7] = \"o\"\n return\n if board[8] == \"x\" and board[6] == \"x\":\n if board[9] == \" \":\n board[9] = \"o\"\n return\n elif board[5] == \"o\" or board[5] == \"x\": # if P1 first, try to hit corners\n for i in (1, 3, 7, 9):\n if board[i] == \" \":\n board[i] = \"o\"\n return\n\n if whos_first == 2 and turns == 3: # if AI starts first winrate is 100% :) good luck!\n if board[1] == \"x\" or board[2] == \"x\":\n board[9] = \"o\"\n return\n if board[3] == \"x\" or board[6] == \"x\":\n board[7] = \"o\"\n return\n if board[9] == \"x\" or board[8] == \"x\":\n board[1] = \"o\"\n return\n if board[7] == \"x\" or board[4] == \"x\":\n board[3] = \"o\"\n return\n if whos_first == 2 and turns == 5:\n if board[1] == \"x\":\n if board[6] == \" \":\n board[6] = \"o\"\n return\n elif board[8] == \" \":\n board[8] = \"o\"\n return\n if board[3] == \"x\":\n if board[4] == \" \":\n board[4] = \"o\"\n return\n elif board[8] == \" \":\n board[8] = \"o\"\n return\n if board[9] == \"x\":\n if board[2] == \" \":\n board[2] = \"o\"\n return\n elif board[4] == \" \":\n board[4] = \"o\"\n return\n if board[7] == \"x\":\n if board[2] == \" \":\n board[2] = \"o\"\n return\n elif board[6] == \" \":\n board[6] = \"o\"\n return\n if use_free_spot(AI, \"o\"):\n return\n\n\ndef game(player_one, player_two):\n new_game()\n if whos_first == 1:\n while True:\n if game_on == 1:\n player_one(\"x\")\n if game_on == 1:\n player_two(\"o\")\n else:\n end_game()\n return\n if whos_first == 2: # P2 first\n while True:\n if game_on == 1:\n player_two(\"o\")\n if game_on == 1:\n player_one(\"x\")\n else:\n end_game()\n return\n\n\ndef show():\n print (\"\\033c\")\n print (\" \", \"\\033[1;30;46m \", \" \", \"\\033[0m\"\"\\033[1;30;44m \", \" \", \"\\033[0m\"\"\\033[1;30;46m \", \" \", \"\\033[0m\", \" **** \", \"1\", \"|\", \"2\",\"|\",\"3\")\n print (\" \",\"\\033[1;30;46m \",\"\",\"\\033[0m\"\"\\033[1;30;46m \",board[1],\"\\033[0m\"\"\\033[1;30;46m \",\"\",\"\\033[0m\"\"\\033[1;30;44m \",\"\",\"\\033[0m\"\"\\033[1;30;44m \",board[2],\"\\033[0m\"\"\\033[1;30;44m \",\"\",\"\\033[0m\"\"\\033[1;30;46m \",\"\",\"\\033[0m\"\"\\033[1;30;46m \",board[3],\"\\033[0m\"\"\\033[1;30;46m \",\"\",\"\\033[0m\",\" KEYS \",\"4\", \"|\",\"5\",\"|\",\"6\")\n print (\" \",\"\\033[1;30;46m \",\" \",\"\\033[0m\"\"\\033[1;30;44m \",\" \",\"\\033[0m\"\"\\033[1;30;46m \",\" \",\"\\033[0m\",\" **** \",\"7\", \"|\",\"8\",\"|\",\"9\")\n print (\" \",\"\\033[1;30;44m \",\" \",\"\\033[0m\"\"\\033[1;30;46m \",\" \",\"\\033[0m\"\"\\033[1;30;44m \",\" \",\"\\033[0m\")\n print (\" \",\"\\033[1;30;44m \",\"\",\"\\033[0m\"\"\\033[1;30;44m \",board[4],\"\\033[0m\"\"\\033[1;30;44m \",\"\",\"\\033[0m\"\"\\033[1;30;46m \",\"\",\"\\033[0m\"\"\\033[1;30;46m \",board[5],\"\\033[0m\"\"\\033[1;30;46m \",\"\",\"\\033[0m\"\"\\033[1;30;44m \",\"\",\"\\033[0m\"\"\\033[1;30;44m \",board[6],\"\\033[0m\"\"\\033[1;30;44m \",\"\",\"\\033[0m\", \" Games : \" + str(gamerounds))\n print (\" \",\"\\033[1;30;44m \",\" \",\"\\033[0m\"\"\\033[1;30;46m \",\" \",\"\\033[0m\"\"\\033[1;30;44m \",\" \",\"\\033[0m\",\" Turn : \" + str(turns))\n print (\" \",\"\\033[1;30;46m \",\" \",\"\\033[0m\"\"\\033[1;30;44m \",\" \",\"\\033[0m\"\"\\033[1;30;46m \",\" \",\"\\033[0m\",\"\\033[1;31m\",\" Player1 wins:\",\"\\033[0m\" + str(p1wins))\n print (\" \",\"\\033[1;30;46m \",\"\",\"\\033[0m\"\"\\033[1;30;46m \",board[7],\"\\033[0m\"\"\\033[1;30;46m \",\"\",\"\\033[0m\"\"\\033[1;30;44m \",\"\",\"\\033[0m\"\"\\033[1;30;44m \",board[8],\"\\033[0m\"\"\\033[1;30;44m \",\"\",\"\\033[0m\"\"\\033[1;30;46m \",\"\",\"\\033[0m\"\"\\033[1;30;46m \",board[9],\"\\033[0m\"\"\\033[1;30;46m \",\"\",\"\\033[0m\",\"\\033[1;32m\",\" Player2 wins:\",\"\\033[0m\" + str(p2wins))\n print (\" \",\"\\033[1;30;46m \",\" \",\"\\033[0m\"\"\\033[1;30;44m \",\" \",\"\\033[0m\"\"\\033[1;30;46m \",\" \",\"\\033[0m\",\" Draws: \" + str(draws))\n print (\"\\n\")\n print(who_wins)\n print(game_on)\n print(board)\n\n\ndef main_menu():\n while True: # main Game loop\n show()\n print (\"Choose a game mode!\")\n print (\" P: Player vs. Player\")\n print (\" A1: Player vs. AI (Easy)\")\n print (\" A2: Player vs. AI (Hard)\")\n print (\" A3: Player vs. AI (God Mode)\")\n print (\" R: Reset scores\")\n print (\" E: Exit\")\n gameChoose = input()\n if gameChoose == \"a1\" or gameChoose == \"A1\":\n game(player_turn, ai_turn_easy)\n elif gameChoose == \"a2\" or gameChoose == \"A2\":\n game(player_turn, ai_turn_hard)\n elif gameChoose == \"a3\" or gameChoose == \"A3\":\n game(player_turn, ai_turn_god)\n elif gameChoose == \"p\" or gameChoose == \"P\":\n game(player_turn, player_turn)\n elif gameChoose == \"r\" or gameChoose == \"R\":\n reset_scores()\n continue\n elif gameChoose == \"e\" or gameChoose == \"E\":\n print (\" Thanks for playing!\")\n time.sleep(2)\n print (\" Shutting down...\")\n time.sleep(2)\n print (\"\\033c\")\n break\n else:\n continue\n\n\nmain_menu()\n","sub_path":"TicTac40.2.py","file_name":"TicTac40.2.py","file_ext":"py","file_size_in_byte":11777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"485847099","text":"## name: Yue Wang ##\n## uniqname: wyjessic ##\nimport sqlite3\nimport sys\nimport plotly.graph_objs as go\n# proj3_choc.py\n# You can change anything in this file you want as long as you pass the tests\n# and meet the project requirements! You will need to implement several new\n# functions.\n\n# Part 1: Read data from a database called choc.db\nDBNAME = 'choc.sqlite'\ndef connect_helper(query,param=None):\n con = sqlite3.connect(DBNAME)\n cur = con.cursor()\n query = query.replace('\\n','')\n result = []\n if param == None:\n result = cur.execute(query).fetchall()\n else:\n result = cur.execute(query,param).fetchall()\n con.close() \n return result\n\n# Part 1: Implement logic to process user commands\ndef Bar(com_list):\n bar_param = 'SpecificBeanBarName, Company, Sell.EnglishName, Rating, CocoaPercent,Source.EnglishName'\n param,LIMIT = [],10\n DESC = ' DESC '\n where_flag, first_flag, plot_flag = False,False, False\n Countries_table = 'Sell'\n query_base = '''\n Select SpecificBeanBarName, Company, \n Sell.EnglishName, Rating, CocoaPercent,Source.EnglishName \n From [Bars] as B \n JOIN [Countries] as Sell ON B.CompanyLocationId = Sell.ID\n JOIN [Countries] as Source ON B.BroadBeanOriginId = Source.ID \n \n '''\n query_order = ' ORDER BY Rating'\n query_limit = ' LIMIT '\n for x in com_list:\n if 'barplot' == x:\n plot_flag = True\n if 'source' == x:\n Countries_table = 'Source'\n if 'country=' in x or 'region=' in x : where_flag = True\n if 'cocoa' == x:\n query_order = ' ORDER BY CocoaPercent'\n if 'bottom' == x:\n DESC = ''\n if x.isnumeric() :\n LIMIT = int(x)\n\n if where_flag:\n for x in com_list:\n if 'country=' in x:\n val = x.split('=')[1]\n param.append(val)\n if first_flag: \n if len(val) == 2:\n query = query +' and '+Countries_table+'.Alpha2 == ? '\n elif len(val) == 3:\n query = query +' and '+Countries_table+'.Alpha3 == ? '\n else:\n query = query +' and '+Countries_table+'.EnglishName == ? '\n else:\n first_flag = True\n if len(val) == 2:\n query = query_base +' WHERE '+Countries_table+'.Alpha2 == ? '\n elif len(val) == 3:\n query = query_base +' WHERE '+Countries_table+'.Alpha3 == ? '\n else:\n query = query_base +' WHERE '+Countries_table+'.EnglishName == ? '\n if 'region=' in x:\n val = x.split('=')[1]\n param.append(val)\n if first_flag:\n query = query + ' and '+Countries_table+'.Region == ? '\n else:\n query = query_base +' WHERE '+Countries_table+'.Region == ? '\n \n return plot_flag, bar_param, connect_helper(query = query+ query_order + DESC + query_limit + str(LIMIT),param = param)\n else:\n return plot_flag, bar_param, connect_helper(query = query_base + query_order + DESC + query_limit + str(LIMIT))\ndef Company(com_list):\n company_param= ''\n param,DESC,LIMIT = [],' DESC ', 10\n where_flag, first_flag, plot_flag = False,False, False\n\n thirdselect = ' AVG(B.Rating) '\n query_limit = ' LIMIT '\n for x in com_list:\n\n if 'country=' in x or 'region=' in x : where_flag = True\n if 'cocoa' == x:\n thirdselect = ' AVG(B.CocoaPercent) '\n if 'number_of_bars' == x:\n thirdselect = ' COUNT(B.ID) '\n if 'bottom' == x:\n DESC = ''\n if x.isnumeric() :\n LIMIT = int(x)\n \n query_base = f'''\n Select B.Company, Sell.EnglishName, {thirdselect}\n FROM Bars as B\n JOIN [Countries] as Sell ON B.CompanyLocationId = Sell.ID\n GROUP BY Company\n HAVING COUNT(B.ID) > 4\n '''\n query_order = f' ORDER BY {thirdselect}'\n company_param = f'Select B.Company, Sell.EnglishName, {thirdselect}'\n if where_flag:\n for x in com_list:\n if 'barplot' == x:\n plot_flag = True\n if 'country=' in x:\n val = x.split('=')[1]\n param.append(val)\n \n if len(val) == 2:\n query = query_base +' and Sell.Alpha2 = ? '\n elif len(val) == 3:\n query = query_base +' and Sell.Alpha3 = ? '\n else:\n query = query_base +' and Sell.EnglishName = ? '\n if 'region=' in x:\n val = x.split('=')[1]\n param.append(val)\n \n query = query_base +' and Sell.Region = ? '\n \n return plot_flag, company_param,connect_helper(query = query+ query_order + DESC + query_limit + str(LIMIT),param = param)\n else:\n return plot_flag, company_param,connect_helper(query = query_base + query_order + DESC + query_limit + str(LIMIT))\ndef Country(com_list):\n country_param = ''\n plot_flag = False\n param,DESC,LIMIT = [],' DESC ', 10\n where_flag, first_flag, source_flag= False,False,False\n Countries_table = 'Sell'\n thirdselect = ' AVG(B.Rating) '\n query_limit = ' LIMIT '\n for x in com_list:\n if 'barplot' == x:\n plot_flag = True\n if 'source' == x:\n source_flag = True\n Countries_table = 'Source'\n if 'region=' in x : where_flag = True\n if 'cocoa' == x:\n thirdselect = ' AVG(B.CocoaPercent) '\n if 'number_of_bars' == x:\n thirdselect = ' COUNT(B.ID) '\n if 'bottom' == x:\n DESC = ''\n if x.isnumeric() :\n LIMIT = int(x)\n if source_flag: \n firstselect = 'Source.EnglishName , Source.Region '\n groupbyname = 'Source.EnglishName'\n else: \n firstselect = 'Sell.EnglishName , Sell.Region'\n groupbyname = 'Sell.EnglishName'\n query_base = f'''\n Select {firstselect}, {thirdselect}\n From [Bars] as B \n JOIN [Countries] as Sell ON B.CompanyLocationId = Sell.ID\n JOIN [Countries] as Source ON B.BroadBeanOriginId = Source.ID\n GROUP BY {groupbyname}\n HAVING COUNT(B.ID) > 4\n '''\n country_param = f'{firstselect}, {thirdselect}'\n query_order = f' ORDER BY {thirdselect}'\n if where_flag:\n for x in com_list:\n if 'region=' in x:\n val = x.split('=')[1]\n param.append(val)\n \n query = query_base +' and '+Countries_table+'.Region = ? '\n \n return plot_flag, country_param,connect_helper(query = query+ query_order + DESC + query_limit + str(LIMIT),param = param)\n else:\n return plot_flag, country_param,connect_helper(query = query_base + query_order + DESC + query_limit + str(LIMIT))\n\ndef Region(com_list):\n region_param = ''\n param,DESC,LIMIT = [],' DESC ', 10\n plot_flag = False\n where_flag, first_flag, source_flag= False,False,False\n thirdselect = ' AVG(B.Rating) '\n Countries_table = 'Sell'\n query_limit = ' LIMIT '\n for x in com_list:\n if 'barplot' == x:\n plot_flag = True\n if 'source' == x:\n source_flag = True\n Countries_table = 'Source'\n if 'cocoa' == x:\n thirdselect = ' AVG(B.CocoaPercent) '\n if 'number_of_bars' == x:\n thirdselect = ' COUNT(B.ID) '\n if 'bottom' == x:\n DESC = ''\n if x.isnumeric() :\n LIMIT = int(x)\n if source_flag: \n firstselect = 'Source.Region '\n groupbyname = 'Source.Region'\n else: \n firstselect = ' Sell.Region'\n groupbyname = 'Sell.Region'\n query_base = f'''\n Select {firstselect}, {thirdselect}\n From [Bars] as B \n JOIN [Countries] as Sell ON B.CompanyLocationId = Sell.ID\n JOIN [Countries] as Source ON B.BroadBeanOriginId = Source.ID\n GROUP BY {groupbyname}\n HAVING COUNT(B.ID) > 4\n '''\n region_param = f'Select {firstselect}, {thirdselect}'\n query_order = f' ORDER BY {thirdselect}'\n return plot_flag, region_param, connect_helper(query = query_base + query_order + DESC + query_limit + str(LIMIT))\n\ndef _plot(param,result,command):\n xaxis = [ row[0] for row in result]\n param = param.split(',')\n keywords = 'Rating'\n if 'cocoa' in command:\n keywords = 'Cocoa'\n elif 'number_of_bars' in command:\n keywords = 'COUNT'\n for x in param:\n if keywords in x:\n i = param.index(x)\n break\n yaxis = [ row[i] for row in result]\n\n bar_data = go.Bar(x=xaxis,y=yaxis)\n basic_layout = go.Layout()\n fig = go.Figure(data=bar_data, layout=basic_layout)\n fig.show()\n \n \n\n\ndef process_command(command):\n com_list = command.split(' ')\n high_level_cat = ['bars','companies','countries','regions']\n try:\n high_level = high_level_cat.index(com_list[0])\n if high_level == 0:\n plot_flag, param, result = Bar(com_list[1:])\n if plot_flag: _plot(param,result,command)\n print_func(param, result)\n return 0\n if high_level == 1:\n plot_flag, param, result = Company(com_list[1:])\n if plot_flag: _plot(param,result,command)\n print_func(param, result)\n return 0\n if high_level == 2:\n plot_flag, param, result = Country(com_list[1:])\n if plot_flag: _plot(param,result,command)\n print_func(param, result)\n return 0\n if high_level == 3:\n plot_flag, param, result = Region(com_list[1:])\n if plot_flag: _plot(param,result,command)\n print_func(param, result)\n return 0\n except:\n print ('Command not recognized:',command)\n \ndef print_func(param,result):\n param = param.split(',')\n for row in result:\n row_output = ''\n for x in param:\n o = row[param.index(x)]\n if 'CocoaPercent' in x :\n row_output +='{:.0%}'.format(o) + ' '\n continue\n if 'Rating' in x :\n row_output +='{:.1f}'.format(o) + ' '\n continue\n if 'COUNT' in x :\n row_output +=str(o) + ' '\n continue\n\n\n \n if len(o) > 12:\n o = o[:12] + '...'\n\n\n row_output +='{:16s}'.format(o)\n print(row_output) \n\n\ndef load_help_text():\n with open('Proj3Help.txt') as f:\n return f.read()\n\n# Part 2 & 3: Implement interactive prompt and plotting. We've started for you!\ndef interactive_prompt():\n help_text = load_help_text()\n response = ''\n while response != 'exit':\n response = input('Enter a command: ')\n\n if response == 'help':\n print(help_text)\n continue\n else:\n process_command(response)\n \n print('bye')\n\n\n\n# Make sure nothing runs or prints out when this file is run as a module/library\nif __name__==\"__main__\":\n interactive_prompt()\n\n","sub_path":"proj3_choc.py","file_name":"proj3_choc.py","file_ext":"py","file_size_in_byte":11614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"79197789","text":"from tkinter import *\n\n# 创建窗口\nroot = Tk()\n# 创建并添加 Canvas\ncv = Canvas(root, background='white')\ncv.pack(fill=BOTH, expand=YES)\ncv.create_rectangle(30, 30, 200, 200,\n outline='red', # 边框颜色\n stipple='question', # 填充的位图\n fill='red', # 填充颜色\n width=5 # 边框宽度\n )\ncv.create_oval(240, 30, 330, 200,\n outline='yellow', # 边框颜色\n fill='pink', # 填充颜色\n width=4 # 边框宽度\n )\nroot.mainloop()\n","sub_path":"疯狂Python讲义/codes/11/11.8/canvas_qs.py","file_name":"canvas_qs.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"131951376","text":"\"\"\"\n Copyright (C) 2018-2019 Intel Corporation\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n\nimport logging\nimport os\nimport cv2\nimport numpy as np\nimport sys\n\nfrom glob import glob\nfrom random import choice\n\nfrom .logging import logger\n\nIMAGE_EXTENSIONS = ['JPEG', 'JPG', 'PNG', 'BMP']\nBINARY_EXTENSIONS = ['BIN']\n\ndef isImage(blob):\n if (blob.layout != \"NCHW\"):\n return False\n channels = blob.shape[1]\n return (channels == 3)\n\ndef isImageInfo(blob):\n if (blob.layout != \"NC\"):\n return False\n channels = blob.shape[1]\n return (channels >= 2)\n\ndef getInputs(path_to_input, batch_size, input_info, requests):\n input_image_sizes = {}\n for key in input_info.keys():\n if (isImage(input_info[key])):\n input_image_sizes[key] = (input_info[key].shape[2], input_info[key].shape[3])\n logger.info(\"Network input '{}' precision {}, dimensions ({}): {}\".format(key,\n input_info[key].precision,\n input_info[key].layout,\n \" \".join(str(x) for x in input_info[key].shape)))\n\n images_count = len(input_image_sizes.keys())\n binaries_count = len(input_info) - images_count\n\n image_files = list()\n binary_files = list()\n\n if (path_to_input):\n image_files = get_files_by_extensions(path_to_input, IMAGE_EXTENSIONS)\n image_files.sort()\n binary_files = get_files_by_extensions(path_to_input, BINARY_EXTENSIONS)\n binary_files.sort()\n\n if (len(image_files) == 0) and (len(binary_files) == 0):\n logger.warn(\"No input files were given: all inputs will be filled with random values!\")\n else:\n binary_to_be_used = binaries_count*batch_size*len(requests)\n if binary_to_be_used > 0 and len(binary_files) == 0:\n logger.warn(\"No supported binary inputs found! Please check your file extensions: {}\".format(\",\".join(BINARY_EXTENSIONS)))\n elif binary_to_be_used > len(binary_files):\n logger.warn(\"Some binary input files will be duplicated: {} files are required, but only {} were provided\".format(binary_to_be_used, len(binary_files)))\n elif binary_to_be_used < len(binary_files):\n logger.warn(\"Some binary input files will be ignored: only {} files are required from {}\".format(binary_to_be_used, len(binary_files)))\n\n images_to_be_used = images_count*batch_size*len(requests)\n if images_to_be_used > 0 and len(image_files) == 0:\n logger.warn(\"No supported image inputs found! Please check your file extensions: {}\".format(\",\".join(IMAGE_EXTENSIONS)))\n elif images_to_be_used > len(image_files):\n logger.warn(\"Some image input files will be duplicated: {} files are required, but only {} were provided\".format(images_to_be_used, len(image_files)))\n elif images_to_be_used < len(image_files):\n logger.warn(\"Some image input files will be ignored: only {} files are required from {}\".format(images_to_be_used, len(image_files)))\n\n requests_input_data = []\n for request_id in range(0, len(requests)):\n logger.info(\"Infer Request {} filling\".format(request_id))\n input_data = {}\n keys = list(input_info.keys())\n for key in keys:\n if isImage(input_info[key]):\n # input is image\n if (len(image_files) > 0):\n input_data[key] = fill_blob_with_image(image_files, request_id, batch_size, keys.index(key), len(keys), input_info[key].shape)\n continue\n\n # input is binary\n if (len(binary_files) > 0):\n input_data[key] = fill_blob_with_binary(binary_files, input_info[key].shape)\n continue\n\n # input is image info\n if (isImageInfo(input_info[key])):\n if len(input_image_sizes) != 1:\n raise Exception(\"Input \" + key + \" cannot be filled: please provide input binary files!\")\n\n image_size = input_image_sizes[list(input_image_sizes.keys()).pop()]\n logger.info(\"Fill input '\" + key + \"' with image size \" + str(image_size[0]) + \"x\" +\n str(image_size[1]))\n input_data[key] = fill_blob_with_image_info(image_size, input_info[key].shape)\n continue\n\n # fill with random data\n logger.info(\"Fill input '{}' with random values ({} is expected)\".format(key, \"image\" if isImage(input_info[key]) else \"some binary data\"))\n input_data[key] = fill_blob_with_random(input_info[key].precision, input_info[key].shape)\n\n requests_input_data.append(input_data)\n\n return requests_input_data\n\ndef get_files_by_extensions(path_to_input, extensions):\n input_files = list()\n if os.path.isfile(path_to_input):\n input_files.append(path_to_input)\n else:\n path = os.path.join(path_to_input, '*')\n files = glob(path, recursive=True)\n for file in files:\n file_extension = file.rsplit('.').pop().upper()\n if file_extension in extensions:\n input_files.append(file)\n return input_files\n\ndef fill_blob_with_image(image_paths, request_id, batch_size, input_id, input_size, shape):\n images = np.ndarray(shape)\n image_index = request_id*batch_size*input_size + input_id\n for b in range(batch_size):\n image_index %= len(image_paths)\n image_filename = image_paths[image_index]\n image = cv2.imread(image_filename)\n\n new_im_size = tuple(shape[2:])\n if image.shape[:-1] != new_im_size:\n logger.warn(\"Image {} is resized from ({}) to ({})\".format(image_filename, image.shape[:-1], new_im_size))\n image = cv2.resize(image, new_im_size)\n\n image = image.transpose((2, 1, 0))\n images[b] = image\n\n image_index += input_size\n return images\n\ndef fill_blob_with_binary(binary_paths, request_id, batch_size, input_id, input_size, shape):\n binaries = np.ndarray(shape)\n binary_index = request_id*batch_size*input_size + input_id\n for b in range(batch_size):\n binary_index %= len(image_paths)\n binary_filename = binary_paths[binary_index]\n\n binary_file_size = os.path.getsize(binary_file)\n input_size = np.prod(shape)/batch_size\n if (input_size != binary_file_size):\n raise Exception(\"File \" + binary_filename + \" contains \" << str(binary_file_size) + \" bytes \" +\n \"but network expects \" + str(input_size))\n\n with open(binary_file, 'r') as f:\n binary_data = f.read()\n\n binaries[b] = binary_data\n binary_index += input_size\n\n return binaries\n\ndef fill_blob_with_image_info(image_size, shape):\n im_info = np.ndarray(shape)\n for b in range(shape[0]):\n for i in range(shape[1]):\n im_info[b][i] = image_size[i] if i in [0, 1] else 1\n\n return im_info\n\ndef fill_blob_with_random(precision, shape):\n if precision == \"FP32\":\n return np.random.rand(*shape).astype(np.float32)\n elif precision == \"FP16\":\n return np.random.rand(*shape).astype(np.float16)\n elif precision == \"I32\":\n return np.random.rand(*shape).astype(np.int32)\n elif precision == \"U8\":\n return np.random.rand(*shape).astype(np.uint8)\n elif precision == \"I8\":\n return np.random.rand(*shape).astype(np.int8)\n elif precision == \"U16\":\n return np.random.rand(*shape).astype(np.uint16)\n elif precision == \"I16\":\n return np.random.rand(*shape).astype(np.int16)\n else:\n raise Exception(\"Input precision is not supported: \" + precision)\n","sub_path":"openvino-samples-r2/python_samples/benchmark_app/benchmark/utils/inputs_filling.py","file_name":"inputs_filling.py","file_ext":"py","file_size_in_byte":8142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"16391521","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom forex_predictor.train_validate_test_predictors.analysis_utils import append_moving_wealth_row, filter_dataframe_by_days, filter_by_hours, print_analysis, plot_dataframe, add_columns_to_base_data, filter_by_buy_or_sell\n\nname = 'test4'\n\nbase_data = pd.read_csv(f'models/{name}/ann/analysis/base_results.csv') \nadd_columns_to_base_data(base_data)\n\n#Create filtered dataframes\nmondays = filter_dataframe_by_days(base_data, [0])\ntuesdays = filter_dataframe_by_days(base_data, [1])\nwednesdays = filter_dataframe_by_days(base_data, [2])\nthursdays = filter_dataframe_by_days(base_data, [3])\nfridays = filter_dataframe_by_days(base_data, [4])\nweekdays_1800_2200 = filter_by_hours(base_data, [18,19,20,21,22])\nbuys = filter_by_buy_or_sell(base_data, 'Buy')\nsells = filter_by_buy_or_sell(base_data, 'Sell')\n\n#Print analysis summaries of dataframes\nprint_analysis(base_data, 'All data')\nprint_analysis(mondays, 'mondays')\nprint_analysis(tuesdays, 'tuesdays')\nprint_analysis(wednesdays, 'wednesdays')\nprint_analysis(thursdays, 'thursdays')\nprint_analysis(fridays, 'fridays')\nprint_analysis(weekdays_1800_2200, 'weekdays 6pm-10pm')\nprint_analysis(buys, 'buys')\nprint_analysis(sells, 'sells')\n\n#Append moving wealth columns to dataframes for plotting timeseries data\nappend_moving_wealth_row(base_data, 10000)\nappend_moving_wealth_row(base_data, 10000, bid_ask_spread=0.0002)\nappend_moving_wealth_row(base_data, 10000, wealth_column_name='Leverage', bid_ask_spread=0.0002, leverage=10)\nappend_moving_wealth_row(mondays, 10000)\nappend_moving_wealth_row(mondays, 10000, bid_ask_spread=0.0002)\nappend_moving_wealth_row(mondays, 10000, wealth_column_name='Leverage', bid_ask_spread=0.0002, leverage=10)\n#Plot timeseries wealth gains\nplt.close('all')\nplot_dataframe(base_data, 'All Data', ['Wealth', 'Adjusted Wealth', 'Leverage'])\nplot_dataframe(mondays, 'Mondays', ['Wealth', 'Adjusted Wealth', 'Leverage'])\nplt.show()\n\n\n\n\n\n","sub_path":"forex_predictor/train_validate_test_predictors/ann/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"584442057","text":"import logging\nimport os\nimport time\nfrom datetime import datetime, timedelta\nfrom threading import Thread\n\nimport requests\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\nfrom django.db import connection\nfrom django.db.models import Q\nfrom django.db.transaction import atomic\nfrom phonenumber_field import phonenumber\n\nfrom ...models import City, Mall, SubwayStation, MallWorkingHours\n\nlogging.basicConfig(format='%(asctime)s %(levelname)s line %(lineno)d: %(message)s', datefmt='%Y-%m-%d %H:%M:%S')\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\ncity = None\n\nCITIES_POINTS = {\n 'Москва': [\n ('55.751691, 37.618530', 25000),\n ('55.751691, 37.618530', 5000),\n ('55.645198, 37.622213', 8000),\n ('55.680992, 37.766889', 8000),\n ('55.750389, 37.758669', 8000),\n ('55.825806, 37.707539', 8000),\n ('55.847094, 37.580208', 8000),\n ('55.813157, 37.476524', 8000),\n ('55.750004, 37.472034', 8000),\n ('55.689235, 37.506940', 8000),\n ('55.644044, 37.583099', 8000),\n ]\n}\nLANGUAGE_TO_MALLS_KEYWORDS = {\n 'ru': ['торговые центры', ],\n 'en': ['shopping malls', ],\n}\nGOOGLE_OK_RESP = 'OK'\nGOOGLE_ZERO_RESULTS_RESP = 'ZERO_RESULTS'\n\nMASS_SEARCH_URL = 'https://maps.googleapis.com/maps/api/place/radarsearch/json'\nPLACE_DETAILS_URL = 'https://maps.googleapis.com/maps/api/place/details/json'\nNEAREST_SEARCH_URL = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json'\n\n\ndef google_api_request(url, query_params):\n query_params['key'] = settings.GOOGLE_API_KEY\n resp = None\n while resp is None:\n try:\n resp = requests.get(url, query_params).json()\n except Exception as mes:\n resp = None\n logger.warning(\"Cannot do request: %s. I try again\", mes)\n time.sleep(1)\n\n if resp['status'] != GOOGLE_OK_RESP:\n if resp['status'] == GOOGLE_ZERO_RESULTS_RESP:\n return []\n raise Exception(\"Cannot do request with following params {}: {}\".format(\n query_params, resp.get('error_message') or resp['status']))\n data = resp.get('result') or resp.get('results')\n return data\n\n\ndef all_city_malls():\n if city.name not in CITIES_POINTS:\n raise Exception(\"Unsupported city name\")\n malls = set()\n for location, radius in CITIES_POINTS[city.name]:\n query_params = {\n 'location': location,\n 'radius': radius,\n }\n for keyword in LANGUAGE_TO_MALLS_KEYWORDS[city.language]:\n query_params['keyword'] = keyword\n results = google_api_request(MASS_SEARCH_URL, query_params)\n malls.update({place['place_id'] for place in results})\n # query_params = {\n # 'location': location,\n # 'radius': radius,\n # 'keyword': city.name,\n # 'types': 'shopping_mall'\n # }\n # results = google_api_request(MASS_SEARCH_URL, query_params)\n # malls.update({place['place_id'] for place in results})\n return malls\n\n\ndef nearest_metro(lat, lon):\n query_params = {\n 'location': '{}, {}'.format(lat, lon),\n 'rankby': 'distance',\n 'types': 'subway_station',\n 'language': city.language,\n }\n results = google_api_request(NEAREST_SEARCH_URL, query_params)\n if not results:\n return None\n return results[0]['name']\n\n\ndef time_with_weekday_to_utc(day_time, day, utc_offset):\n datetime_local = datetime.strptime(day_time, '%H%M')\n delta = timedelta(minutes=utc_offset)\n datetime_utc = datetime_local - delta\n if datetime_utc.time() < datetime_local.time() and utc_offset < 0:\n day += 1\n if datetime_utc.time() > datetime_local.time() and utc_offset > 0:\n day -= 1\n return datetime_utc.time(), day % 7\n\n\ndef get_place_house_number(place_info):\n house_number = None\n for component in place_info['address_components']:\n if 'street_number' in component['types']:\n house_number = component['short_name']\n break\n return house_number\n\n\ndef update_fields_from_input(update_fields_str):\n if not update_fields_str:\n return []\n update_fields = []\n valid_fields = {f.name for f in Mall._meta.get_fields()}\n for f in update_fields_str.split(','):\n f = f.strip()\n if f not in valid_fields:\n raise Exception(\"Invalid mall field: {}\".format(f))\n update_fields.append(f)\n return update_fields\n\n\ndef set_mall_working_hours(mall, mall_api_info):\n working_hours = mall_api_info.get('opening_hours')\n if working_hours is not None:\n utc_offset = mall_api_info['utc_offset']\n with atomic():\n with connection.cursor() as cursor:\n cursor.execute('LOCK TABLE {} IN SHARE ROW EXCLUSIVE MODE'.format(MallWorkingHours._meta.db_table))\n MallWorkingHours.objects.filter(mall=mall).delete()\n for period in working_hours['periods']:\n if 'close' not in period:\n mall.day_and_night = True\n mall.save()\n break\n closing_time, closing_day = time_with_weekday_to_utc(period['close']['time'],\n period['close']['day'], utc_offset)\n opening_time, opening_day = time_with_weekday_to_utc(period['open']['time'],\n period['open']['day'], utc_offset)\n MallWorkingHours.objects.create(mall=mall,\n opening_time=opening_time, opening_day=opening_day,\n closing_time=closing_time, closing_day=closing_day)\n\n\ndef trim_address(address):\n parts = address.split(',')\n if len(parts) < 4:\n return address\n return ','.join(parts[:-3])\n\n\n# noinspection PyTypeChecker\ndef info_about_mall(place_id, update_fields):\n try:\n mall_api_info = google_api_request(PLACE_DETAILS_URL,\n {'placeid': place_id, 'language': city.language})\n logger.info(\"Start mall %s, place id: %s.\", mall_api_info['name'], place_id)\n with atomic():\n with connection.cursor() as cursor:\n cursor.execute('LOCK TABLE {} IN SHARE ROW EXCLUSIVE MODE'.format(Mall._meta.db_table))\n mall = Mall.objects.filter(Q(search_names__name__iexact=mall_api_info['name']) |\n Q(name__iexact=mall_api_info['name'])).first()\n if mall is None or update_fields:\n location_lat = mall_api_info['geometry']['location']['lat']\n location_lon = mall_api_info['geometry']['location']['lng']\n metro_name = nearest_metro(location_lat, location_lon)\n if metro_name is not None:\n metro, created = SubwayStation.objects.get_or_create(name=metro_name)\n else:\n metro = None\n mall_data = dict(address=trim_address(mall_api_info['formatted_address']),\n house_number=get_place_house_number(mall_api_info),\n phone=phonenumber.to_python(mall_api_info.get('international_phone_number', '')),\n name=mall_api_info['name'],\n google_place_id=place_id,\n location='Point({} {})'.format(location_lat, location_lon),\n site=mall_api_info.get('website', ''),\n city=city,\n subway_station=metro)\n if mall is None:\n mall = Mall.objects.create(**mall_data)\n set_mall_working_hours(mall, mall_api_info)\n elif update_fields:\n updated_fields = []\n for field, value in mall_data.items():\n if field not in update_fields:\n continue\n setattr(mall, field, value)\n updated_fields.append(field)\n mall.save()\n if 'working_hours' in update_fields or 'day_and_night' in update_fields:\n set_mall_working_hours(mall, mall_api_info)\n except Exception as e:\n raise Exception(\"Some problems with {}: {}\".format(place_id, e))\n\n\nclass Command(BaseCommand):\n def add_arguments(self, parser):\n parser.add_argument('--city', type=str, default='Москва', help=\"City name.\")\n parser.add_argument('--cached-list', dest='cached_list', action='store_true')\n parser.add_argument('--no-cached-list', dest='cached_list', action='store_false')\n parser.set_defaults(cached_list=True)\n parser.add_argument('--update-fields', type=str, default='',\n help=\"By default malls that exist in our db are not updated. \"\n \"If you want to update old malls, specify fields to update separated by comma.\")\n\n def handle(self, *args, **options):\n global city\n update_fields = update_fields_from_input(options['update_fields'])\n city = options['city']\n city = City.objects.get(name=city)\n file_with_list = '.{}_malls_list.txt'.format(city.name)\n if options['cached_list'] and os.path.isfile(file_with_list):\n with open(file_with_list) as f:\n place_ids = {line.strip() for line in f}\n else:\n if options['cached_list']:\n logger.warning(\"Cannot open file with list of %s malls. Generate new...\", city.name)\n else:\n logger.info(\"Start generating list of malls\")\n place_ids = all_city_malls()\n with open(file_with_list, 'w') as f:\n f.write('\\n'.join(place_ids))\n logger.info(\"Start building workers\")\n threads = [Thread(target=info_about_mall, args=[place_id, update_fields]) for place_id in place_ids]\n logger.info(\"Start workers\")\n for t in threads:\n t.start()\n logger.info(\"Wait for workers\")\n for t in threads:\n t.join()\n logger.info(\"All workers finished\")\n","sub_path":"app/management/commands/get_malls_info.py","file_name":"get_malls_info.py","file_ext":"py","file_size_in_byte":10417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"599317354","text":"from django_filters.views import FilterView\r\n\r\nfrom jobopening.views import JobopeningListView, JobopeningDetailView, IndustryListView, \\\r\n FunctionalAreaListView, TagIndexView, LocationListView, IndexListView, job_search_filter\r\nfrom django.conf.urls import url\r\nfrom jobopening.views import job_submit, apply, job_search, contact_us\r\nfrom .models import Jobopening, Industry\r\n\r\n\r\nurlpatterns = [\r\n url(r'^job/$', JobopeningListView.as_view(), name='jobopening-list'),\r\n url(r'^job-submit/$', job_submit, name='post-job'),\r\n url(r'^apply/$', apply, name='apply'),\r\n url(r'^search/$', job_search_filter, name='jobsearch'),\r\n # url(r'^searchjob/$', job_search, name='searchjob'),\r\n url(r'^$', IndexListView.as_view(), name='index'),\r\n url(r'^contact-us/$', contact_us, name='contact_us'),\r\n\r\n url(r'^industry/(?P[-\\w]+)/$', IndustryListView.as_view(), name='industry'),\r\n url(r'^functional-area/(?P[-\\w]+)/$', FunctionalAreaListView.as_view(), name='functional_area'),\r\n url(r'^location/(?P[-\\w]+)/$', LocationListView.as_view(), name='location'),\r\n url(r'^job/(?P[-\\w]+)/$', JobopeningDetailView.as_view(), name='job-detail'),\r\n url(r'^tag/(?P[-\\w]+)/$', TagIndexView.as_view(), name='tagged'),\r\n\r\n]\r\n","sub_path":"jobopening/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"171913315","text":"#!/usr/bin/env python3\n# ------------------------------------------------------------------------ 79->\n# Author: ${name=Kelcey Damage}\n# Python: 3.5+\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# Doc\n# ------------------------------------------------------------------------ 79->\n\n# Imports\n# ------------------------------------------------------------------------ 79->\nimport os\nos.sys.path.append(\n os.path.dirname(\n os.path.dirname(\n os.path.abspath(__file__)\n )\n )\n )\nimport zmq\nfrom transport.dispatch import Dispatcher\nfrom common import datatypes\nfrom common.print_helpers import printc, Colours\nfrom transport.cache import Cache\nimport time\nimport numpy as np\nimport cbor\nimport io\n\n# Globals\n# ------------------------------------------------------------------------ 79->\nCOLOURS = Colours()\nCOUNT = 500000\nCACHE = Cache()\n\n# Classes\n# ------------------------------------------------------------------------ 79->\n\n\n# Functions\n# ------------------------------------------------------------------------ 79->\ndef map_to_meta(_dict):\n t = time.perf_counter()\n datatypes = [(x[0].decode(), 'a8') for x in list(_dict.items())]\n m = np.fromiter(\n _dict.items(),\n dtype=datatypes,\n count=len(_dict)\n )\n print('{0:.8f}'.format(time.perf_counter() - t))\n print(m.shape)\n return datatypes\n\n# Main\n# ------------------------------------------------------------------------ 79->\nif __name__ == '__main__':\n loop = COUNT\n seed = [[1.0, 2.0, 3.0] for x in range(loop)]\n seed2 = {b'foo': b'bar', b'baz': b'bar'}\n k = map_to_meta(seed2)\n s = time.time()\n dispatcher = Dispatcher()\n print('_'*79)\n pipeline = {}\n\n envelope = datatypes.Envelope(cached=False)\n tasks = ['task_multiply', 'task_multiply', 'task_multiply', 'task_multiply']\n data = [[1.0, 2.0, 3.0] for i in range(loop)]\n #t = time.perf_counter()\n envelope.pack(meta={'tasks': tasks, 'completed': [], 'kwargs': {}}, data=data)\n #print('PACK {0:.8f}'.format(time.perf_counter() - t))\n\n print('Start Job')\n t4 = time.perf_counter()\n envelope = dispatcher.send(envelope)\n printc('JOB COMPLETED: {0}s'.format(time.perf_counter() - t4), COLOURS.GREEN)\n\n\n print(envelope.header)\n print('-'*79)\n r = []\n data = envelope.result()\n data.setflags(write=1)\n t1 = time.perf_counter()\n for i in range(len(tasks)):\n for i in range(data.shape[0]):\n data[i] = np.multiply(data[i], data[i])\n print('CTRL w/ PyWrap\\t {0:.8f}'.format(time.perf_counter() - t1))\n\n print('JOB', envelope.result()[:10])\n print(envelope.header)\n\n","sub_path":"jobs/dummy_bench.py","file_name":"dummy_bench.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"390499185","text":"import random\n\nfrom flask import Flask, Response, request\nfrom getLines import VALID_LEVEL, VALID_TARGET, getLines\n\napp = Flask(__name__)\n\n@app.route('/api', methods=['GET'])\ndef api():\n config = {\n \"level\": \"max\",\n \"target\": \"female\"\n }\n level = request.args.get(\"level\")\n target = request.args.get(\"target\")\n\n if level in VALID_LEVEL:\n config[\"level\"] = level\n if target in VALID_TARGET:\n config[\"target\"] = target\n\n lines = getLines(config)\n\n return Response(random.choice(lines))\n\nif __name__ == \"__main__\":\n app.run(port=6675)","sub_path":"HorseHunterAPI.py","file_name":"HorseHunterAPI.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"449707194","text":"\"\"\"\npayment.py: CIS 211 assignment 4.2, Spring 2014\nauthor: Ian Garrett, igarrett@uoregon.edu\n\ncalculates and displays monthly payments given a year, loan amount, and interest rate.\ninteractive GUI used to assist with user input and display\n\"\"\"\nfrom tkinter import *\n\nroot = Tk()\n\nlabel_amount = Label(root, text='Enter loan amount')\nlabel_amount.grid(row=0,column=0)\nlabel_interest = Label(root, text='Enter interest')\nlabel_interest.grid(row=2,column=0)\nlabel_years = Label(root, text='Enter length of loan (years)')\nlabel_years.grid(row=4,column=0)\n\namount = Entry(root)\namount.grid(row=1,column=0)\ninterest = Entry(root)\ninterest.grid(row=3,column=0)\nyears = Entry(root)\nyears.grid(row=5,column=0)\n\ndef payment():\n\t\"\"\"\n\tcalculates the monthly payment on a loan given the amount, number of years\n\ton the loan, and the interest rate on the load.\n\t\"\"\"\n\tglobal lock\n\tamount_x = int(amount.get())\n\tinterest_x = float(interest.get())\n\tyears_x = int(years.get())\n\tr = (interest_x)/100/12\n\tp = (years_x)*12\n\tpayment_x = (r*amount_x)/(1-(1+r)**(-p))\n\tmonthly_payment.config(state=NORMAL)\n\tmonthly_payment.delete(0,END)\n\tmonthly_payment.insert(0,('%.2f' % payment_x))\n\tmonthly_payment.config(state=DISABLED)\n\nmonthly_payment = Entry(root)\nmonthly_payment.grid(row=7,column=0)\n\nbutton = Button(root, text='Compute monthly payment', command=payment)\nbutton.grid(row=6, column=0, pady = 10)\n\nif __name__ == '__main__':\n root.mainloop()","sub_path":"211_projects/Week_4/compress/payment.py","file_name":"payment.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"152116285","text":"class Solution:\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n from collections import defaultdict\n\n filtered = sorted([item for item in candidates if item <= target])\n\n combinations = defaultdict(list)\n for item in filtered:\n combinations[item].append([item])\n \n if filtered:\n for _ in range(target // filtered[0] + 1):\n new_entries = defaultdict(list)\n for item in filtered:\n for listsum in sorted(combinations.keys()):\n if item + listsum <= target:\n new_entries[item + listsum] += [sorted(x + [item]) for x in combinations[listsum]]\n else:\n break\n\n for key in new_entries.keys():\n for item in new_entries[key]:\n if item not in combinations[key]:\n combinations[key].append(item)\n\n return combinations[target]\n","sub_path":"39 Combination Sum.py","file_name":"39 Combination Sum.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"250121549","text":"import numpy as np\nimport lg_base.core.array_utils as hau\nimport copy\n\n\"\"\"\n filterobj = preprocess_raw('ahsrl',ahsrlconstants,ntime_ave)\"\"\"\n\nclass time_frame:\n def __init__(self,post_operator=None):\n self.post_operator=post_operator\n\n def cleanup(self,raw):\n if raw.times.shape[0] ==0:\n raw.start_time = None\n else: \n raw.start_time = raw.times[0]\n \n if raw.times.shape[0]>0:\n raw.end_time = raw.times[-1]\n else: \n raw.end_time = None \n\n def flush(self,raw=None):\n if raw is not None:\n self.cleanup(raw)\n if self.post_operator!=None:\n return self.post_operator.flush(raw)\n return raw\n\n\n\n def __call__(self,raw):\n #if these lines ever crash, no data was appended to no data. why would this run? \n self.cleanup(raw)\n\n if self.post_operator!=None:\n return self.post_operator(raw)\n return raw\n\n\n\nclass time_select:\n def __init__(self,ntime_ave,post_operator=None):\n self.ntime_ave = ntime_ave\n self.post_operator=post_operator\n self.Rem=hau.Time_Z_Group()\n\n def flush(self,raw=None):\n if raw is not None:\n self.Rem.append(raw)\n raw=self.Rem\n self.Rem=hau.Time_Z_Group(like=raw)\n if self.post_operator!=None:\n return self.post_operator.flush(raw)\n return raw\n \n def selectTimesMod_kt(self,raw):\n \"\"\" selectTimesMod(self,kt): \n Iterate thought all items in dictionary, add any remainder from\n last call then return vars(self) with number of times evenly divided\n by kt and a new remainder.\n \"\"\"\n kt=self.ntime_ave\n #entries in self.Rem.times but not in raw.times, copy Rem to Raw\n if hasattr(self.Rem,'times') and( not hasattr(raw,'times') or raw.times.shape[0] ==0):\n #for (name,value) in vars(self.Rem).items():\n # raw[name]=self.Rem[name]\n # self.Rem[name]=[]\n pass \n #note--if entries in raw.times but not in self.Rem.times\n else:\n if hasattr(raw,'times') and (not hasattr(self.Rem,'times') or self.Rem.times.shape[0] == 0):\n arrlen=raw.times.shape[0]\n self.Rem=copy.copy(raw)#copy.deepcopy(raw)\n #both Rem.times and raw.times have entries, concatenate Rem and raw\n #and define new remainder if it exists\n else:\n arrlen=raw.times.shape[0] + vars(self.Rem)['times'].shape[0]\n self.Rem.append(raw)\n\n last_index = arrlen-(arrlen%kt)\n mask =np.arange(arrlen)\n #mzero=mask<0\n #mrem= mask>=last_index\n #mret= mask0:\n setattr(raw,name,value[:last_index]) \n else:\n l=list(value.shape)\n l[0]=0\n setattr(raw,name,type(value)(np.ones(l),summode=value.summode,dtype=value.dtype))\n else:\n setattr(raw,name,copy.deepcopy(value))\n #if these lines ever crash, no data was appended to no data. why would this run? \n if raw.times.shape[0] ==0:\n raw.start_time = None\n else: \n raw.start_time = raw.times[0]\n \n if raw.times.shape[0]>0:\n raw.end_time = raw.times[-1]\n else: \n raw.end_time = None\n if self.Rem.times.shape[0] ==0:\n self.Rem.start_time = None\n else: \n self.Rem.start_time = self.Rem.times[0]\n \n if self.Rem.times.shape[0]>0:\n self.Rem.end_time = self.Rem.times[-1]\n else: \n self.Rem.end_time = None\n \n \n \n \n \n \n \n \n def __call__(self,raw):\n \"\"\" appends the contents of raw to any profiles stored in rem.\n It then selects first int(ns)hots/ntime_ave) profiles in the resulting\n buffer and does any processing that must be completed before time\n averaging on these profiles. It then time averages in ntime_ave\n blocks. The remaining profiles are held in rem to be appended on the\n next call.\"\"\"\n \n self.selectTimesMod_kt(raw)\n \n if self.post_operator!=None:\n return self.post_operator(raw)\n return raw\n\n\nclass time_ave:\n def __init__(self,ntime_ave,post_operator=None):\n self.ntime_ave = ntime_ave\n self.post_operator=post_operator\n\n def work(self,raw,ntime_ave):\n raw.binMean(ntime_ave,1,complete_only=False)\n raw.preprocess_ntime_ave = ntime_ave\n\n def flush(self,raw=None):\n if raw is not None and raw.times.size>0:\n self.work(raw,raw.times.size)\n\n if self.post_operator!=None:\n return self.post_operator.flush(raw)\n return raw\n\n def __call__(self,raw):\n\n self.work(raw,self.ntime_ave)\n\n if self.post_operator!=None:\n return self.post_operator(raw)\n return raw\n","sub_path":"hsrl/data_stream/preprocess_raw.py","file_name":"preprocess_raw.py","file_ext":"py","file_size_in_byte":5735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"476295363","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport csv\n\niterations = \"20\"\nit = 20\ntestCases = [\"1\", \"2\", \"3\", \"4\", \"5\"]\nmethods = [\"J\", \"GS\", \"SOR\"]\ndata = \"results/\"\nextension = \".txt\"\npath = \"plots/\"\n\nfor testCase in testCases:\n X = [*range(1, it+1, 1)]\n originY = []\n with open(data + testCase + \"_\" + iterations + extension,'r') as csvfile:\n plots = csv.reader(csvfile, delimiter=' ')\n for row in plots:\n originY.append(float(row[0]))\n originY = [sum(originY) / len(originY) ]*it\n\n for method in methods:\n Y = []\n with open(data + method + \"_\" + testCase + \"_\" + iterations + extension,'r') as csvfile:\n plots = csv.reader(csvfile, delimiter=' ')\n for row in plots:\n Y.append(float(row[0]))\n\n print('.', end='', flush=True)\n plt.clf()\n\n plt.plot(X, originY)\n plt.scatter(X, Y)\n plt.xticks(np.arange(0, 21, step=2))\n plt.title(\"funkcja: \" + testCase + \" | metoda: \" + method)\n plt.xlabel('iterations')\n plt.savefig(path + method + \"_\" + testCase + \"_\" + iterations + \".png\")\n","sub_path":"lab6/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"97101888","text":"\r\n\r\nimport sys\r\nimport os\r\nimport traceback\r\nimport StringIO\r\nimport urllib\r\n\r\n#kind of hack to get the bicicle repair man without having it in the pythonpath.\r\nsys.path.insert(1, os.path.join(os.path.dirname(sys.argv[0]), \r\n \"ThirdParty\", \"brm\"))\r\nimport ThirdParty.brm.bike as bike\r\n\r\n\r\n\r\nclass Refactoring(object):\r\n \r\n def __init__(self):\r\n self.progress = StringIO.StringIO()\r\n self.warning = StringIO.StringIO()\r\n self.init()\r\n\r\n def getLastProgressMsg(self):\r\n progress = self.progress.getvalue().split('\\n')\r\n msg = ''\r\n i = -1\r\n while msg == '' and i > -5:\r\n try:\r\n msg = progress[i]\r\n except:\r\n msg = ''\r\n i -= 1\r\n return msg\r\n \r\n def getLastProgressMsgs(self, v):\r\n progress = self.progress.getvalue().split('\\n')\r\n msg = ''\r\n i = -1\r\n while i > -v:\r\n try:\r\n msg += progress[i]+'\\n'\r\n except:\r\n pass\r\n i -= 1\r\n return msg\r\n\r\n def init(self):\r\n \"\"\"\r\n Private slot to handle the Reset action.\r\n \"\"\"\r\n self.brmctx = bike.init()\r\n self.brmctx.setProgressLogger(self.progress)\r\n self.brmctx.setWarningLogger(self.warning)\r\n \r\n def handleReset(self):\r\n \"\"\"\r\n Private slot to handle the Reset action.\r\n \"\"\"\r\n self.init()\r\n \r\n\r\n def extractMethod(self, filename, startline, startcolumn, \r\n endline, endcolumn, newname):\r\n '''\r\n Receives all as a string and changes to correct type.\r\n '''\r\n self.brmctx.extractMethod(filename, int(startline), int(startcolumn), \r\n int(endline), int(endcolumn), \r\n newname)\r\n savedfiles = self.brmctx.save()\r\n return str(savedfiles)\r\n\r\n\r\n def renameByCoordinates(self, filename, line, column, newname):\r\n '''\r\n Receives all as a string and changes to correct type.\r\n '''\r\n self.brmctx.renameByCoordinates(filename, int(line), int(column), newname)\r\n savedfiles = self.brmctx.save()\r\n return str(savedfiles)\r\n\r\n\r\n def inlineLocalVariable(self, filename, line, column):\r\n '''\r\n Receives all as a string and changes to correct type.\r\n '''\r\n self.brmctx.inlineLocalVariable(filename, int(line), int(column))\r\n savedfiles = self.brmctx.save()\r\n return str(savedfiles)\r\n \r\n\r\n def extractLocalVariable(self,filename, begin_line, begin_col,\r\n end_line, end_col, newname):\r\n '''\r\n Receives all as a string and changes to correct type.\r\n '''\r\n self.brmctx.extractLocalVariable(filename, int(begin_line), int(begin_col),\r\n int(end_line), int(end_col), newname)\r\n savedfiles = self.brmctx.save()\r\n return str(savedfiles)\r\n\r\n \r\n def findDefinition(self, filename, line, column):\r\n '''\r\n Receives all as a string and changes to correct type.\r\n '''\r\n defns = self.brmctx.findDefinitionByCoordinates(filename, int(line), int(column))\r\n \r\n ret = ''\r\n \r\n for ref in defns:\r\n ret += '(%s)'%str(ref)\r\n \r\n return '[%s]' % ret\r\n\r\n\r\n__Refactoring = None\r\n\r\ndef GetRefactorer():\r\n global __Refactoring\r\n if __Refactoring is None:\r\n __Refactoring = Refactoring()\r\n \r\n return __Refactoring\r\n \r\ndef restartRefactorerBuffer():\r\n r = GetRefactorer()\r\n r.warning.close()\r\n r.progress.close()\r\n\r\n r.warning.__init__()\r\n r.progress.__init__()\r\n\r\ndef restartRefactorer():\r\n global __Refactoring\r\n __Refactoring = Refactoring()\r\n \r\ndef HandleRefactorMessage(msg, keepAliveThread):\r\n '''\r\n The message received should have: the method of the class and its parameters.\r\n '''\r\n msgSplit = msg.split('|')\r\n \r\n func = msgSplit.pop(0)\r\n \r\n refactorer = GetRefactorer()\r\n func = getattr(refactorer, func)\r\n \r\n keepAliveThread.processMsgFunc = refactorer.getLastProgressMsg\r\n \r\n try:\r\n f = func(*msgSplit)\r\n restartRefactorerBuffer()\r\n s = urllib.quote_plus(f)\r\n return 'BIKE_OK:%s\\nEND@@'%(s)\r\n except:\r\n import sys\r\n s = StringIO.StringIO()\r\n exc_info = sys.exc_info()\r\n \r\n s.write(str(exc_info[1]))\r\n \r\n s.write('\\nWARNINGS:\\n\\n')\r\n s.write('%s\\n' % (refactorer.warning.getvalue(),))\r\n\r\n s.write('\\nPROGRESS:\\n\\n')\r\n s.write('%s\\n' % (refactorer.getLastProgressMsgs(8),))\r\n \r\n s.write('\\nDETAILS:\\n\\n')\r\n traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], limit=None, file = s)\r\n \r\n restartRefactorerBuffer()\r\n restartRefactorer()\r\n s = urllib.quote_plus(s.getvalue())\r\n return 'ERROR:%s\\nEND@@'%(s)\r\n \r\n\r\n","sub_path":"spell/tags/1.5.0/spel-dev/bin/plugins/org.python.pydev_1.4.2/PySrc/refactoring.py","file_name":"refactoring.py","file_ext":"py","file_size_in_byte":5028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"268241551","text":"import h5py\nimport numpy as np\n\nclass meep_object:\n \"\"\"Base object: has a material and a position\"\"\"\n\n def __init__(self, material, pos):\n self.material = material\n self.pos = np.array(pos)\n\n @staticmethod\n def write(objects, group):\n group['material'] = np.array([obj.material.name for obj in objects], dtype=h5py.special_dtype(vlen=str))\n group['pos'] = np.array([obj.pos for obj in objects])\n\nclass sphere(meep_object):\n \"\"\"Sphere object: has a radius\"\"\"\n\n def __init__(self, material, pos, radius):\n super().__init__(material, pos)\n self.radius = radius\n\n @staticmethod\n def write(spheres, filename):\n with h5py.File(filename, 'r+') as f:\n group = f[\"objects\"].create_group(\"spheres\")\n meep_object.write(spheres, group)\n group['radius'] = np.array([sphere.radius for sphere in spheres])\n\nclass cylinder(meep_object):\n \"\"\"Cylinder object: has a radius and height\"\"\"\n\n def __init__(self, material, pos, radius, height):\n super().__init__(material,pos)\n self.radius = radius\n self.height = height\n\n @staticmethod\n def write(cylinders, filename):\n with h5py.File(filename, 'r+') as f:\n group = f[\"objects\"].create_group(\"cylinders\")\n meep_object.write(cylinders, group)\n group['radius'] = np.array([cylinder.radius for cylinder in cylinders])\n group['height'] = np.array([cylinder.height for cylinder in cylinders])\n\nclass ellipsoid(meep_object):\n \"\"\"Ellipsoid object: has three axes lengths\"\"\"\n\n def __init__(self, material, pos, lx, ly, lz):\n super().__init__(material,pos)\n self.lx = lx\n self.ly = ly\n self.lz = lz\n\n @staticmethod\n def write(ellipsoids, filename):\n with h5py.File(filename, 'r+') as f:\n group = f[\"objects\"].create_group(\"ellipsoids\")\n meep_object.write(ellipsoids, group)\n\n group['lx'] = np.array([ellipsoid.lx for ellipsoid in ellipsoids])\n group['ly'] = np.array([ellipsoid.ly for ellipsoid in ellipsoids])\n group['lz'] = np.array([ellipsoid.lz for ellipsoid in ellipsoids])\n\nclass block(meep_object):\n \"\"\"Block object: has three axes lengths\"\"\"\n\n def __init__(self, material, pos, lx, ly, lz):\n super().__init__(material,pos)\n self.lx = lx\n self.ly = ly\n self.lz = lz\n\n @staticmethod\n def write(blocks, filename):\n with h5py.File(filename, 'r+') as f:\n group = f[\"objects\"].create_group(\"blocks\")\n meep_object.write(blocks, group)\n\n group['lx'] = np.array([block.lx for block in blocks])\n group['ly'] = np.array([block.ly for block in blocks])\n group['lz'] = np.array([block.lz for block in blocks])\n\n","sub_path":"pre_fdtd/objects.py","file_name":"objects.py","file_ext":"py","file_size_in_byte":2819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"22065063","text":"from PyQt5.Qt import *\nfrom index import Ui_widget\n\n\nclass IndexPane(QWidget, Ui_widget):\n show_release_pane_singal = pyqtSignal()\n show_my_pane_singal = pyqtSignal()\n search_btn_singal = pyqtSignal(str)\n\n def __init__(self, parent=None, *args, **kwargs):\n super().__init__(parent, *args, **kwargs)\n self.setupUi(self)\n\n def show_my(self):\n self.show_my_pane_singal.emit()\n\n def show_release(self):\n self.show_release_pane_singal.emit()\n\n def search_object(self):\n object_name = self.lineEdit.text()\n self.search_btn_singal.emit(object_name)\n\n\nif __name__ == '__main__':\n import sys\n\n app = QApplication(sys.argv)\n window = IndexPane()\n\n window.show()\n sys.exit(app.exec_())\n","sub_path":"Test/Index_pane.py","file_name":"Index_pane.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"378705166","text":"import codecs as c\nimport codecs\nimport gzip as gz\nimport multiprocessing\nimport optparse\nimport os\nimport re\nimport time\nimport threading\nfrom functools import wraps\n\n\ndef main():\n\toptparser = optparse.OptionParser()\n\toptparser.add_option('--in', dest='in_dir', help='Path to input directory')\n\toptparser.add_option('--out', dest='out', help='Path to output directory')\n\toptparser.add_option('--merge', dest='merge', action=\"store_true\", help='Merge multi-word named entities?')\n\toptparser.add_option('--log', dest='log', help='Path to logfile')\n\toptparser.add_option('--log_interval', dest='inter', type='int', help='Logging interval')\n\t(options, args) = optparser.parse_args()\n\tconvert_decow_to_plain(options.in_dir, options.out, options.log, options.merge, options.inter)\n\n\ndef convert_decow_to_plain(decow_dir, out_dir, log_path, merge_nes, log_interval):\n\tm_proc, s_proc = divmod(log_interval, 60)\n\th_proc, m_proc = divmod(m_proc, 60)\n\twith codecs.open(log_path, \"a\", \"utf-8\") as log_file:\n\t\tlog_file.write(alt(\"Starting logging...\\n\"))\n\t\tlog_file.write(alt(\"Corpus (parts) directory:\\t%s\\n\" %(decow_dir)))\n\t\tlog_file.write(alt(\"Output directory:\\t\\t%s\\n\" %(out_dir)))\n\t\tlog_file.write(alt(\"Logging path:\\t\\t%s\\n\" %(log_path)))\n\t\tlog_file.write(alt(\"Logging intervals:\\n\\t Every %2dh %2dm %2ds for metalog\\n\" %(h_proc, m_proc, s_proc)))\n\n\t@log_time(log_path, log_interval)\n\tdef _convert_decow_to_plain(decow_dir, out_dir, log_path, merge_nes, log_interval):\n\t\twith codecs.open(log_path, \"a\", \"utf-8\") as log_file:\n\t\t\tlog_file.write(alt(\"Preparing %i process(es)...\\n\" %(len(decow_dir))))\n\t\t\tinpaths = [path for path in os.listdir(decow_dir) if \".DS_Store\" not in path and \"decow\" in path]\n\t\t\tpool = multiprocessing.Pool(processes=len(inpaths))\n\t\t\tlog_file.write(alt(\"Starting process(es)!\\n\"))\n\t\t\tif merge_nes:\n\t\t\t\tpool.map(convert_part_merging, [(decow_dir + inpath, out_dir, log_path, log_interval) for inpath in inpaths])\n\t\t\telse:\n\t\t\t\tpool.map(convert_part, [(decow_dir + inpath, out_dir, log_path, log_interval) for inpath in inpaths])\n\n\t_convert_decow_to_plain(decow_dir, out_dir, log_path, merge_nes, log_interval)\n\n\ndef convert_part(argstuple):\n\tinpath, dir_outpath, log_path, interval = argstuple\n\n\t@log_time(log_path, interval)\n\tdef _convert_part(inpath, dir_outpath, log_path, interval):\n\t\tfile_n = get_file_number(inpath)\n\t\toutpath = dir_outpath + 'decow%s_out.txt' %(str(file_n))\n\t\twith gz.open(inpath, 'rb') as infile, c.open(outpath, 'wb', 'utf-8') as outfile:\n\t\t\tsentence = []\n\t\t\tfor line in infile:\n\t\t\t\tline = line.strip().decode(\"utf-8\")\n\t\t\t\tif line.startswith(u' 9 else \"0\" + file_n\n\n\ndef contains_tag(line):\n\tpattern = re.compile(\"<.+>\")\n\treturn pattern.search(line) is not None\n\n\ndef extract_sentence_id(tag):\n\tif \" interval * log_entries:\n\t\t\t\t\t\tm, s = divmod(elapsed_time, 60)\n\t\t\t\t\t\th, m = divmod(m, 60)\n\t\t\t\t\t\tlogfile.write(alt(\"Elapsed time for function '%s': %2dh %2dm %2ds\\n\"\n\t\t\t\t\t\t % (func.__name__, h, m, s)))\n\t\t\t\t\t\tlog_entries += 1\n\t\t\treturn result[0]\n\n\t\treturn wrapper\n\n\treturn log_time_decorator\n\n\ndef log_time_mp(logpath=\"log.txt\", interval=5):\n\n\tdef log_time_decorator(func):\n\t\t@wraps(func)\n\t\tdef wrapper(*args, **kwargs):\n\t\t\tresult = [None]\n\n\t\t\tdef return_value(*args, **kwargs):\n\t\t\t\tresult[0] = func(*args, **kwargs)\n\n\t\t\tt = threading.Thread(target=return_value, args=args, kwargs=kwargs)\n\t\t\tlog_entries = 0\n\t\t\twith codecs.open(logpath, \"a\", \"utf-8\") as logfile:\n\t\t\t\tstart_time = time.time()\n\t\t\t\tt.start()\n\t\t\t\twhile t.is_alive():\n\t\t\t\t\telapsed_time = (time.time() - start_time)\n\t\t\t\t\tif elapsed_time > interval * log_entries:\n\t\t\t\t\t\tm, s = divmod(elapsed_time, 60)\n\t\t\t\t\t\th, m = divmod(m, 60)\n\t\t\t\t\t\tlogfile.write(alt(\"Elapsed time for function '%s' of %s: %2dh %2dm %2ds\\n\"\n\t\t\t\t\t\t % (func.__name__, multiprocessing.current_process().name, h, m, s)))\n\t\t\t\t\t\tlog_entries += 1\n\t\t\treturn result[0]\n\n\t\treturn wrapper\n\n\treturn log_time_decorator\n\n\ndef alt(func):\n\treturn \"%s: %s\" % (time.strftime(\"%H:%M:%S\", time.gmtime()), func)\n\n\nif __name__ == '__main__':\n\tmain()","sub_path":"src/prep/corpus/convert_to_plain.py","file_name":"convert_to_plain.py","file_ext":"py","file_size_in_byte":7031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"138751076","text":"import numpy as np\n\nimport chainer\nimport chainer.functions as F\nfrom chainer import initializers\nimport chainer.links as L\n\n\nclass Alex(chainer.Chain):\n\n \"\"\"Single-GPU AlexNet without partition toward the channel axis.\"\"\"\n\n insize = 227\n\n def __init__(self):\n super(Alex, self).__init__(\n conv1=L.Convolution2D(3, 96, 11, stride=4),\n conv2=L.Convolution2D(96, 256, 5, pad=2),\n conv3=L.Convolution2D(256, 384, 3, pad=1),\n conv4=L.Convolution2D(384, 384, 3, pad=1),\n conv5=L.Convolution2D(384, 256, 3, pad=1),\n fc6=L.Linear(9216, 4096),\n fc7=L.Linear(4096, 4096),\n fc8=L.Linear(4096, 1000),\n )\n self.train = False\n\n def __call__(self, x, t):\n h = F.max_pooling_2d(F.local_response_normalization(\n F.relu(self.conv1(x))), 3, stride=2)\n h = F.max_pooling_2d(F.local_response_normalization(\n F.relu(self.conv2(h))), 3, stride=2)\n h = F.relu(self.conv3(h))\n h = F.relu(self.conv4(h))\n h = F.max_pooling_2d(F.relu(self.conv5(h)), 3, stride=2)\n h = F.dropout(F.relu(self.fc6(h)), train=self.train)\n h = F.dropout(F.relu(self.fc7(h)), train=self.train)\n h = self.fc8(h)\n\n loss = F.softmax_cross_entropy(h, t)\n chainer.report({'loss': loss, 'accuracy': F.accuracy(h, t)}, self)\n return loss\n\n\nclass AlexFp16(Alex):\n\n \"\"\"Single-GPU AlexNet without partition toward the channel axis.\"\"\"\n\n insize = 227\n\n def __init__(self):\n self.dtype = np.float16\n W = initializers.HeNormal(1 / np.sqrt(2), self.dtype)\n bias = initializers.Zero(self.dtype)\n chainer.Chain.__init__(\n self,\n conv1=L.Convolution2D(3, 96, 11, stride=4, initialW=W, bias=bias),\n conv2=L.Convolution2D(96, 256, 5, pad=2, initialW=W, bias=bias),\n conv3=L.Convolution2D(256, 384, 3, pad=1, initialW=W, bias=bias),\n conv4=L.Convolution2D(384, 384, 3, pad=1, initialW=W, bias=bias),\n conv5=L.Convolution2D(384, 256, 3, pad=1, initialW=W, bias=bias),\n fc6=L.Linear(9216, 4096, initialW=W, bias=bias),\n fc7=L.Linear(4096, 4096, initialW=W, bias=bias),\n fc8=L.Linear(4096, 1000, initialW=W, bias=bias),\n )\n self.train = True\n\n def __call__(self, x, t):\n return Alex.__call__(self, F.cast(x, self.dtype), t)\n","sub_path":"demos/selective_dualarm_stowing/scripts/bvlc_alex.py","file_name":"bvlc_alex.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"585880261","text":"#!/usr/bin/env python3\n\nfrom p139_myThread import MyThread\nimport time\n\n\ndef fib(x):\n time.sleep(0.005)\n if x < 2:\n return (1)\n else:\n return (fib(x - 2) + fib(x - 1))\n\n\ndef fac(x):\n time.sleep(0.1)\n if x < 2:\n return (1)\n else:\n return (x * fac(x - 1))\n\n\ndef sum(x):\n time.sleep(0.1)\n if x < 2:\n return (1)\n else:\n return (x + sum(x - 1))\n\n\nfuncs = [fib, fac, sum]\nn = 12\n\n\ndef main():\n print(\"*** SINGLE THREAD\")\n for func in funcs:\n print(\"starting {} at: {}\".format(func.__name__, time.ctime()))\n print(\"{}({}) = {}\".format(func.__name__, n, func(n)))\n print(\"{} finished at: {}\".format(func.__name__, time.ctime()))\n\n print(\"\\n*** MULTIPLE THREADS\")\n threads = []\n for func in funcs:\n t = MyThread(func, (n, ), func.__name__)\n threads.append(t)\n for t in threads:\n t.start()\n for t in threads:\n t.join()\n print(\"{}({}) = {}\".format(t.func.__name__, n, t.getResult()))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"chapter4/p140_mtfacfib.py","file_name":"p140_mtfacfib.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"226487087","text":"import requests\nimport json\n\napi_key = \"YOUR_API_KEY\"\napi_url = \"https://canar.io/_api/\"\n\n\n# Run a search against the canar.io database. Searches should be performed\n# exactly as they are outlined at https://canar.io/help/\ndef search(query):\n payload = {\"key\": api_key, \"action\": \"search\", \"query\": query}\n r = requests.get(api_url, params=payload)\n return r.json()\n\n\n# Returns the results for a reference ID\ndef view(item):\n payload = {\"key\": api_key, \"action\": \"view\", \"item\": item}\n r = requests.get(api_url, params=payload)\n return r.json()\n\n\n# Enables you to determine whether or not your key is working\ndef test():\n payload = {\"key\": api_key, \"action\": \"test\"}\n r = requests.get(api_url, params=payload)\n return r.json()\n\n\n# Users with the ability to upload data to the Canario database can use this\ndef store(title, text, source, source_url):\n if title is None:\n title = 'Untitled'\n payload = {\"key\": api_key, \"action\": \"store\", \"title\": title, \"text\": text, \"source\": source,\n \"source_url\": source_url}\n r = requests.get(api_url, params=payload)\n return r.json()\n\n\n# Return a list of all urls associated with a search\ndef get_urls(search):\n referenceids = []\n urls = []\n\n for result in search[\"data\"][\"results\"][\"results\"]:\n referenceids.append(result[\"referenceid\"])\n\n for refid in referenceids:\n urls.append(view(refid)[\"data\"][\"sources\"][0][\"url\"])\n return urls\n\n\n# Write JSON data to a file\ndef write_to_file(filename, data):\n with open(filename, 'wb') as f:\n f.write(json.dumps(data, indent=4))\n","sub_path":"pycanario/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"96594311","text":"__author__ = 'qiushi'\n\n\nclass Solution:\n # @param {integer[]} nums\n # @param {integer} target\n # @return {integer[]}\n def twoSum(self, nums, target):\n process = {}\n for index in range(len(nums)):\n if target - nums[index] in process:\n return [process[target - nums[index]] + 1, index + 1]\n process[nums[index]] = index\n","sub_path":"#1_two_sum/#1_two_sum.py","file_name":"#1_two_sum.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"235422130","text":"\"\"\"\n Author: Israel Dryer\n Modified: 2021-10-24\n Adapted from: https://images.idgesg.net/images/article/2018/08/cw_win10_utilities_ss_02-100769136-orig.jpg\n\"\"\"\nfrom pathlib import Path\nimport tkinter as tk\nfrom tkinter import ttk\nfrom ttkbootstrap import Style\n\nPATH = Path(__file__)\n\n\nclass Application(tk.Tk):\n\n def __init__(self):\n super().__init__()\n self.title('PC Cleaner')\n self.style = Style('pulse')\n self.cleaner = Cleaner(self)\n self.cleaner.pack(fill=tk.BOTH, expand=tk.YES)\n\n # custom styles\n self.style.configure(\n style='header.TLabel',\n background=self.style.colors.secondary,\n foreground=self.style.colors.info\n )\n # do not allow window resizing\n self.resizable(False, False)\n\n\nclass Cleaner(ttk.Frame):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n # application images\n self.logo_img = tk.PhotoImage(\n name='logo',\n file=PATH.parent / 'assets/icons8_broom_64px_1.png'\n )\n self.brush_img = tk.PhotoImage(\n name='cleaner',\n file=PATH.parent / 'assets/icons8_broom_64px.png'\n )\n self.registry_img = tk.PhotoImage(\n name='registry',\n file=PATH.parent / 'assets/icons8_registry_editor_64px.png'\n )\n self.tools_img = tk.PhotoImage(\n name='tools',\n file=PATH.parent / 'assets/icons8_wrench_64px.png'\n )\n self.options_img = tk.PhotoImage(\n name='options',\n file=PATH.parent / 'assets/icons8_settings_64px.png'\n )\n self.privacy_img = tk.PhotoImage(\n name='privacy',\n file=PATH.parent / 'assets/icons8_spy_80px.png'\n )\n self.junk_img = tk.PhotoImage(\n name='junk',\n file=PATH.parent / 'assets/icons8_trash_can_80px.png'\n )\n self.protect_img = tk.PhotoImage(\n name='protect',\n file=PATH.parent / 'assets/icons8_protect_40px.png'\n )\n\n # header\n header_frame = ttk.Frame(self, padding=20, bootstyle='secondary')\n header_frame.grid(row=0, column=0, columnspan=3, sticky=tk.EW)\n\n ttk.Label(\n master=header_frame,\n image='logo',\n style='header.TLabel'\n ).pack(side=tk.LEFT)\n\n logo_text = ttk.Label(\n master=header_frame,\n text='pc cleaner',\n font=('TkDefaultFixed', 30),\n style='header.TLabel'\n )\n logo_text.pack(side=tk.LEFT, padx=10)\n\n # action buttons\n action_frame = ttk.Frame(self)\n action_frame.grid(row=1, column=0, sticky=tk.NSEW)\n\n cleaner_btn = ttk.Button(\n master=action_frame,\n image='cleaner',\n text='cleaner',\n compound=tk.TOP,\n bootstyle='info'\n )\n cleaner_btn.pack(side=tk.TOP, fill=tk.BOTH, ipadx=10, ipady=10)\n\n registry_btn = ttk.Button(\n master=action_frame,\n image='registry',\n text='registry',\n compound=tk.TOP,\n bootstyle='info'\n )\n registry_btn.pack(side=tk.TOP, fill=tk.BOTH, ipadx=10, ipady=10)\n\n tools_btn = ttk.Button(\n master=action_frame,\n image='tools',\n text='tools',\n compound=tk.TOP,\n bootstyle='info'\n )\n tools_btn.pack(side=tk.TOP, fill=tk.BOTH, ipadx=10, ipady=10)\n\n options_btn = ttk.Button(\n master=action_frame,\n image='options',\n text='options',\n compound=tk.TOP,\n bootstyle='info'\n )\n options_btn.pack(side=tk.TOP, fill=tk.BOTH, ipadx=10, ipady=10)\n\n # option notebook\n notebook = ttk.Notebook(self)\n notebook.grid(row=1, column=1, sticky=tk.NSEW, pady=(25, 0))\n\n # windows tab\n windows_tab = ttk.Frame(notebook, padding=10)\n wt_scrollbar = tk.Scrollbar(windows_tab)\n wt_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)\n\n wt_canvas = tk.Canvas(\n master=windows_tab,\n border=0,\n highlightthickness=0,\n yscrollcommand=wt_scrollbar.set\n )\n wt_canvas.pack(side=tk.LEFT, fill=tk.BOTH)\n\n # adjust the scrollregion when the size of the canvas changes\n wt_canvas.bind(\n sequence='',\n func=lambda e: wt_canvas.configure(\n scrollregion=wt_canvas.bbox(tk.ALL))\n )\n wt_scrollbar.configure(command=wt_canvas.yview)\n scroll_frame = ttk.Frame(wt_canvas)\n wt_canvas.create_window((0, 0), window=scroll_frame, anchor=tk.NW)\n\n radio_options = [\n 'Internet Cache', 'Internet History', 'Cookies',\n 'Download History', 'Last Download Location',\n 'Session', 'Set Aside Tabs', 'Recently Typed URLs',\n 'Saved Form Information', 'Saved Password'\n ]\n\n edge = ttk.Labelframe(\n master=scroll_frame,\n text='Microsoft Edge',\n padding=(20, 5)\n )\n edge.pack(fill=tk.BOTH)\n\n explorer = ttk.Labelframe(\n master=scroll_frame,\n text='Internet Explorer',\n padding=(20, 5)\n )\n explorer.pack(fill=tk.BOTH, pady=10)\n\n # add radio buttons to each label frame section\n for section in [edge, explorer]:\n for opt in radio_options:\n cb = ttk.Checkbutton(section, text=opt, state=tk.NORMAL)\n cb.invoke()\n cb.pack(side=tk.TOP, pady=2, fill=tk.X)\n notebook.add(windows_tab, text='windows')\n\n # empty tab for looks\n notebook.add(ttk.Frame(notebook), text='applications')\n\n # results frame\n results_frame = ttk.Frame(self)\n results_frame.grid(row=1, column=2, sticky=tk.NSEW)\n\n # progressbar with text indicator\n pb_frame = ttk.Frame(results_frame, padding=(0, 10, 10, 10))\n pb_frame.pack(side=tk.TOP, fill=tk.X, expand=tk.YES)\n\n pb = ttk.Progressbar(\n master=pb_frame,\n bootstyle=('success', 'striped'),\n variable='progress'\n )\n pb.pack(side=tk.LEFT, fill=tk.X, expand=tk.YES, padx=(15, 10))\n\n ttk.Label(pb_frame, text='%').pack(side=tk.RIGHT)\n ttk.Label(pb_frame, textvariable='progress').pack(side=tk.RIGHT)\n self.setvar('progress', 78)\n\n # result cards\n cards_frame = ttk.Frame(\n master=results_frame,\n name='cards-frame',\n bootstyle='secondary button'\n )\n cards_frame.pack(fill=tk.BOTH, expand=tk.YES)\n\n # privacy card\n priv_card = ttk.Frame(\n master=cards_frame, \n padding=1, \n )\n priv_card.pack(side=tk.LEFT, fill=tk.BOTH, padx=(10, 5), pady=10)\n\n priv_container = ttk.Frame(\n master=priv_card, \n padding=40,\n )\n priv_container.pack(fill=tk.BOTH, expand=tk.YES)\n\n priv_lbl = ttk.Label(\n master=priv_container,\n image='privacy',\n text='PRIVACY',\n compound=tk.TOP,\n anchor=tk.CENTER\n )\n priv_lbl.pack(fill=tk.BOTH, padx=20, pady=(40, 0))\n\n ttk.Label(\n master=priv_container,\n textvariable='priv_lbl',\n bootstyle='primary'\n ).pack(pady=(0, 20))\n self.setvar('priv_lbl', '6025 tracking file(s) removed')\n\n # junk card\n junk_card = ttk.Frame(\n master=cards_frame,\n padding=1,\n )\n junk_card.pack(side=tk.LEFT, fill=tk.BOTH, padx=(5, 10), pady=10)\n \n junk_container = ttk.Frame(junk_card, padding=40)\n junk_container.pack(fill=tk.BOTH, expand=tk.YES)\n \n junk_lbl = ttk.Label(\n master=junk_container, \n image='junk',\n text='PRIVACY', \n compound=tk.TOP, \n anchor=tk.CENTER,\n )\n junk_lbl.pack(fill=tk.BOTH, padx=20, pady=(40, 0))\n \n ttk.Label(\n master=junk_container, \n textvariable='junk_lbl',\n bootstyle='primary', \n justify=tk.CENTER\n ).pack(pady=(0, 20))\n self.setvar('junk_lbl', '1,150 MB of unneccesary file(s)\\nremoved')\n\n # user notification\n note_frame = ttk.Frame(\n master=results_frame, \n bootstyle='secondary', \n padding=40\n )\n note_frame.pack(fill=tk.BOTH)\n \n note_msg = ttk.Label(\n master=note_frame, \n text='We recommend that you better protect your data', \n anchor=tk.CENTER,\n style='header.TLabel', \n font=('Helvetica', 12, 'italic')\n )\n note_msg.pack(fill=tk.BOTH)\n\n\nif __name__ == '__main__':\n\n Application().mainloop()\n","sub_path":"src/ttkbootstrap/gallery/pc_cleaner.py","file_name":"pc_cleaner.py","file_ext":"py","file_size_in_byte":8966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"75670868","text":"from num import NUM\nfrom sym import SYM\nimport re\n\n# This file holds the COLS class\n\nclass COLS():\n def __init__(self, t):\n if type(t) == list:\n nt = {}\n for item in t:\n nt[len(nt)] = item\n t = nt\n self.names = t\n self.all = {}\n self.x = {}\n self.y = {}\n self.klass = None\n\n for n in range(len(t)):\n s = t[n]\n col = NUM(n, s) if re.search(\"^[A-Z]+\", s) else SYM(n, s)\n self.all[len(self.all)] = col\n if not re.search(\"X$\", s):\n if re.search(\"!$\", s):\n self.klass = col\n if re.search(\"[!+-]$\", s):\n self.y[len(self.y)] = col\n else:\n self.x[len(self.x)] = col\n\n def add(self, row):\n # Adds the elements of the row to its correct column\n for _,t in enumerate([self.x, self.y]):\n for _,col in t.items():\n col.add(row.cells[col.at])","sub_path":"src/hw4/cols.py","file_name":"cols.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"326858649","text":"import os\nfrom pathlib import Path\nimport dash\nimport plotly.graph_objs as go\nimport dash_bootstrap_components as dbc\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output,State\nimport pandas as pd\nimport base64\nimport pandas as pd\n#import lorem\nimport numpy as np\nfrom scipy.stats import norm\nimport json\nfrom scipy.stats import norm\nimport copy\nimport csv\nimport plotly.express as px\nfrom collections import deque\nimport xarray as xr\nfrom scipy.stats import norm\n\n# from BOBfun import rose\n\n\n\n############################################################################################################################################################\n\n#################################################### TOKEN\nmapbox_access_token = \"pk.eyJ1IjoiamFja2x1byIsImEiOiJjajNlcnh3MzEwMHZtMzNueGw3NWw5ZXF5In0.fk8k06T96Ml9CLGgKmk81w\"\nStyle=\"mapbox://styles/seb2121/ck0goela506jn1cpi74entuub\"\nStyle=\"outdoors\"\nmapbox = dict(\naccesstoken = mapbox_access_token,\nstyle =Style\n)\n\n#################################################### color\n\ncolors = {\n 'background': '#111111',\n 'text': '#7FDBFF'\n}\n\n## Colours\ncolor_1 = \"#003399\"\ncolor_2 = \"#00ffff\"\ncolor_3 = \"#002277\"\ncolor_b = \"#F8F8FF\"\n\n\n\n\nscl = [0,\"rgb(255,0,0)\"],[0.125,\"rgb(255, 111, 0)\"],[0.25,\"rgb(255, 234, 0)\"],\\\n[0.375,\"rgb(151, 255, 0)\"],[0.5,\"rgb(44, 255, 150)\"],[0.625,\"rgb(0, 152, 255)\"],\\\n[0.75,\"rgb(0, 25, 255)\"],[0.875,\"rgb(0, 0, 200)\"],[1,\"rgb(150, 0, 90)\"]\n\nPic_One = os.path.dirname(os.path.abspath(__file__))\n\ndef encode_image(PicName):\n PicDIR= os.path.join(Pic_One, \"Picture\", PicName+\".png\")\n encoded = base64.b64encode(open(PicDIR, 'rb').read())\n return 'data:image/png;base64,{}'.format(encoded.decode())\n\n\n\nBasicStyle={\n 'padding-top': 20,\n 'padding-bottom': 20,\n \"height\": \"400px\",\n }\n\nSliderstyle= {\n \"height\": \"50px\",\n # 'margin-top': 25,\n # 'margin-bottom': 50,\n 'padding-top':30,\n 'padding-bottom': 30,\n # 'padding-left': \"5%\",\n # 'width':\"50%\",\n # 'float': 'hfgh',\n}\n\n\n######################### navbar\n\n\nnavbar = dbc.NavbarSimple(\n children=[\n dbc.NavItem(dbc.NavLink(\"CSIR\", href=\"https://www.csir.co.za/\")),\n dbc.DropdownMenu(\n children=[\n dbc.DropdownMenuItem(\"More pages\", header=True),\n dbc.DropdownMenuItem(\"Page 2\", href=\"/info\"),\n dbc.DropdownMenuItem(\"Page 3\", href=\"#\"),\n ],\n nav=True,\n in_navbar=True,\n label=\"More\",\n ),\n ],\n brand=\"Wind Energy Calculator\",\n brand_style={'font-size': 35},\n brand_href=\"#\",\n color=\"primary\",\n dark=True,)\n\n\n\n\n\n######################### Table\n\n\ntable_header = [html.Thead(html.Tr([html.Th(\"Turbine\",), html.Th(\"Max Power Output\"), html.Th(\"Class\"), html.Th(\"Design for\")],style={\"text-align\": \"center\"}))]\n\nrow1 = html.Tr([html.Td(\"Turbine 1\"),html.Td(\"2.7 MW\"), html.Td(\"Class 3\"), html.Td(\"Low Wind\")])\nrow2 = html.Tr([html.Td(\"Turbine 2\"),html.Td(\"2.78 MW\"), html.Td(\"Class 3\"), html.Td(\"Low Wind\")])\nrow3 = html.Tr([html.Td(\"Turbine 3\"),html.Td(\"3 MW\"),html.Td(\"Class 3\"), html.Td(\"Low Wind\")])\nrow4 = html.Tr([html.Td(\"Turbine 4\"),html.Td(\"3 Mw\"), html.Td(\"Class 2\"), html.Td(\"medium Wind\")])\n\ntable_body = [html.Tbody([row1, row2, row3, row4])]\n\ntable = dbc.Table(table_header + table_body,striped=False, bordered=True, hover=True,)\n\n\n\n######################### Text Instructions One\n\n\nText_Instructions_one = html.Div([\n # html.H1(children='Wind Energy Calculator',),\n\n\n dbc.Jumbotron([ html.H3(children='Instructions', ),\n html.P(children=\"The map of South Africa displays an estimated capacity factor or wind power of a \"\n \"specific turbine over a year at a particular height. The data entered below will \"\n \"be plotted on the map.\"),\n html.Ol([\n html.Li(children=\"Select one of the four turbine options (the different turbines with their \"\n \"corresponding maximum power outputs are displayed in the table below to the\"\n \" left).\"),\n html.Li(children=\"Select one of the four required hub heights.\"),\n html.Li(children=\"Select the type of estimate required, namely capacity factor or wind power.\"),\n html.Li(children=\"To submit the requirements, click the “Plot” button.\"),],),\n\n html.P(children=\"The card to right of the selection criteria displays an estimate of the capacity \"\n \"factor and wind power at a specific point selected on the map.\"),\n ])\n ],)\n\n\n######################### Text GenWind\n\nText_GenWind = html.Div([\n dbc.Jumbotron([\n html.H4(children='Power Graph and Rose Chart Display', ),\n html.P(children='Further analysis of the selected point on the map of South Africa is displayed in the power '\n 'graph and rose chart. The selection can be customised using the drop-down menus for hub '\n 'height(s) and turbine(s). This allows for a graphic represent of each of the selected '\n 'criteria.'),\n html.P(children='A normal distribution for each of the hub height’s selected is plotted on the graph. The axis '\n 'on the left estimates the wind probability density percentages based on time series data '\n 'collected. Power curves are plotted over the normal distribution graphs from the turbine '\n 'selections made. The power curve(s) are linked to the right axis and are displayed as power '\n 'generated (kW).'),\n html.P(children='The rose chart to the right of the graph represents the wind direction as a percentage based '\n 'on the hub height(s) selected.'),\n\n ])\n ],)\n\n######################### Text Three\n\nText_Method = html.Div([\n dbc.Jumbotron([\n html.H4(children='Method', ),\n html.P(children='Wind data from January 2009 to December 2013 was collected using NetCDF files at '\n 'four heights above the ground (50m, 80m, 100m and 150m). The data was used to '\n 'determine annual hourly wind speeds at each of the four heights. Data results at '\n 'each height were then converted into a probability density function to create a '\n 'normal distribution. Together with power curve data for various existing wind '\n 'turbines, the power output was calculated to estimate the capacity factor and '\n 'amount of energy that can be produced in a year at the different heights within '\n 'each 5x5km2 pixel for different turbines'),\n html.P(children=''),\n html.P(children='We would like to improve the app and include more types of turbines. Please refer '\n 'to the block in the top right and select whether you would like to add these and'\n ' more turbines to the app or/and if you would prefer to include your own turbine '\n 'information. Should you prefer to include your own turbines please indicate how '\n 'this data will be supplied e.g. raw data or an equation.'),\n\n\n ])\n ],)\n\nInfo_mine = html.Div([\n\n html.P(children='This project was done in collaboration with GIZ.'),\n html.P(children=''),\n html.P(children='For more information please contact:'),\n html.P(children=\"Sebastian Leask (sleask@csir.co.za)\")\n\n ],)\n\n######################### Picture\n\n\nPicture_CSIR= html.Div([\n dbc.Container(\n html.Img(src=encode_image(\"one\"),\n\n style={\n\n 'margin-top': 0,\n 'margin-right': 10,\n\n\n },)\n )\n ])\n\nPicture_Talbe= html.Div([\n html.Div(\n html.Img(src=encode_image(\"Table\"),\n\n style={\n 'height': '30%',\n 'width': '85%',\n 'float': 'left',\n 'position': 'relative',\n 'margin-top': 10,\n 'margin-right': 0,\n 'display': 'inline-block',\n 'padding-top': 20,\n\n },\n )\n )\n ])\n\nPicture_GIZ= html.Div([\n html.Div(\n html.Img(src='https://raw.githubusercontent.com/Futile21/heroku4/master/Picture/GIZ%20Cooperation%20logo.png?token=AMQTZBRNK5IX5F25EAY7NLS6HM2GY',\n\n style={\n # 'height': 150,\n # 'width': 500,\n # 'height': '5%',\n 'width': '40%',\n 'float': 'left',\n 'position': 'relative',\n 'margin-top': 10,\n 'margin-right': 0,\n 'display': 'inline-block',\n 'padding-top': 20,\n\n },\n )\n )\n ])\n\n\n\n\n######################################################### Dropdown\n\nDropdown_Height= html.Div([\n dcc.Dropdown(\n id='DropdownHeight',\n options=[\n {'label': '50m', 'value': \"50\", },\n {'label': '80m', 'value': \"80\", },\n {'label': '100m', 'value': \"100\", },\n {'label': '150m', 'value': \"150\", }, ],\n value=['50'],\n\n multi=True,\n ),\n ],)\n\nDropdown_Turb= html.Div([\n dcc.Dropdown(\n id='DropdownTurb',\n options=[\n {'label': 'Turbine 1', 'value': \"Turbine 1\", },\n {'label': 'Turbine 2', 'value': \"Turbine 2\", },\n {'label': 'Turbine 3', 'value': \"Turbine 3\", },\n {'label': 'Turbine 4', 'value': \"Turbine 4\", }, ],\n value=['Turbine 1'],\n\n multi=True,\n ),\n ],)\n\n######################################################### Radio\n\nRadio = html.Div([\n html.Div([html.H4(children='Selection Criteria',)]),\n dbc.Row([\n dbc.Col(\n html.Div([\n dbc.RadioItems(\n id='RadioTurb',\n options=[\n {'label': 'Turbine 1', 'value': \"Turbine 1\", },\n {'label': 'Turbine 2', 'value': \"Turbine 2\", },\n {'label': 'Turbine 3', 'value': \"Turbine 3\", },\n {'label': 'Turbine 4', 'value': \"Turbine 4\", }, ],\n value='Turbine 1',\n inline=True,\n\n ),],\n style=Sliderstyle\n ),width={\"size\": 10, \"offset\": 1},\n )\n ],align=\"center\",),\n dbc.Row([\n dbc.Col(\n html.Div([\n dbc.RadioItems(\n id='RadioHeight',\n options=[\n {'label': '50m', 'value': \"50\", },\n {'label': '80m', 'value': \"80\", },\n {'label': '100m', 'value': \"100\", },\n {'label': '150m', 'value': \"150\", }, ],\n value='50',\n inline=True,\n\n ), ],\n\n style=Sliderstyle\n ),width={\"size\": 10, \"offset\": 1},\n )\n ],align=\"center\",),\n dbc.Row([\n dbc.Col(\n html.Div([\n dbc.RadioItems(\n id='RadioPower',\n options=[\n {'label': 'Capacity Factor', 'value': \"Capacity Factor [%]\", },\n {'label': 'Wind Power', 'value': \"Wind Power [MWh/year]\", }, ],\n value='Capacity Factor [%]',\n inline=True,\n\n ),\n ]),\n width={\"size\": 8, \"offset\": 1},\n ),\n dbc.Col(\n html.Div([dbc.Button(\"Plot\", color=\"primary\", className=\"mr-1\",id='btn'),],\n style=Sliderstyle\n ),\n width={\"size\": 2, },\n ),\n ],align=\"center\",),\n\n\n ],)\n\n######################### CARD\n\nInfoCard = html.Div([\n dbc.Card([\n dbc.CardHeader(id=\"cardHeader\"),\n dbc.CardBody(\n [html.Div([\n html.H5(children=\"Test\", className=\"card-title\", id=\"cardmidT\"),\n html.H5(children=\"Test2\", className=\"card-text\", id=\"cardmidM\"),\n ],),\n ],\n # style={\"height\": \"125px\",},\n # align=\"center\",\n ),\n dbc.CardFooter(\n [html.Div([\n html.P(children=\"\", className=\"card-title\", id=\"cardLat\"),\n html.P(children=\"\", className=\"card-text\", id=\"cardLon\"),\n ],),\n ],\n ),\n ],\n outline=True,\n color=\"dark\",)\n ],)\n\n\n\n\n\n\n\n############################################################################################################################################################ Comp\n\n\nRSAlayout=dict(\n autosize=True,\n margin=go.layout.Margin(l=0, r=35, t=35, b=0,),\n colorbar=dict(title=\"Colorbar\",),\n title=\"South Africa Overview\",\n mapbox=dict(\n accesstoken=mapbox_access_token,\n center=dict(lat=-28, lon=22),\n style=Style,\n zoom=4,),)\n\n\n\nRoselayout=dict(\n title='Wind Speed Distribution',\n font_size=16,\n legend_font_size=16,\n polar_radialaxis_ticksuffix='%',\n orientation=90,\n )\n\n\n\n\nPowelayout = dict(\n annotations=[\n {\n \"y\": -0.1,\n \"text\": \"Wind speed (m/s)\",\n \"arrowhead\": 7,\n \"ax\": 0,\n \"ay\": -40,\n \"font\": {\"size\": 15},\n \"showarrow\": False,\n \"xref\": \"paper\",\n \"yref\": \"paper\",\n \"visible\": True,\n }\n ],\n autosize=True,\n dragmode=\"pan\",\n hovermode=\"closest\",\n legend={\n \"x\": 0.5,\n \"y\": -0.1,\n \"font\": {\"size\": 15},\n \"orientation\": \"h\",\n \"xanchor\": \"center\",\n \"bgcolor\": \"rgb(255, 255, 255, 0)\",\n },\n title=\"Normal distribution of Wind Vs Turbine Power\",\n xaxis={\n # \"title\": \"Wind speed (m/s)\",\n \"autorange\": True,\n \"nticks\": 19,\n # \"range\": [0.5, 18],\n \"showgrid\": True,\n \"tickfont\": {\n \"color\": \"rgb(68, 68, 68)\",\n \"size\": 1,\n },\n \"ticks\": \"\",\n \"type\": \"linear\",\n \"zeroline\": True,\n },\n yaxis={\n \"title\": \"Probability (%)\",\n \"title_font_size\": 30,\n \"autorange\": True,\n \"linecolor\": \"rgb(190, 191, 192)\",\n \"mirror\": True,\n \"nticks\": 9,\n \"range\": [0, 1],\n \"showgrid\": True,\n \"showline\": True,\n \"side\": \"left\",\n \"tickfont\": {\n \"color\": \"rgb(68, 68, 68)\",\n \"size\": 9,\n },\n \"ticks\": \"outside\",\n \"ticksuffix\": \" \",\n \"type\": \"linear\",\n \"zeroline\": False,\n\n },\n yaxis2={\n \"title\": \"Power Generated (kW)\",\n \"anchor\": \"x\",\n \"autorange\": True,\n \"exponentformat\": \"e\",\n \"linecolor\": \"rgb(190, 191, 192)\",\n \"nticks\": 9,\n \"overlaying\": \"y\",\n # \"range\": [0, 50],\n \"showgrid\": True,\n \"side\": \"right\",\n \"tickfont\": {\"size\": 9},\n \"tickprefix\": \" \",\n \"ticks\": \"outside\",\n \"type\": \"linear\",\n \"zerolinecolor\": \"rgb(190, 191, 192)\",\n },)\n\nRoselayout=go.Layout(\n polar=dict(\n radialaxis=dict(\n visible=True,\n ticksuffix='%',),\n ),\n showlegend=True,\n polar_angularaxis_rotation=90,)\n\n\n############################################################################################################################################################ Data\n\n# da=xr.open_mfdataset(r\"C:\\AllRun\\*10.nc\",combine='by_coords')\n# da=xr.open_dataset(r'C:\\Users\\\\futil\\OneDrive\\GIZ\\Internship\\seb_test_ring\\\\rose\\maker\\AllCoTurb.nc')\n\nWindDF=pd.read_csv('https://raw.githubusercontent.com/Futile21/CSV_wind/master/Test_CF003.csv')\nRoseDF=pd.read_csv('https://raw.githubusercontent.com/Futile21/CSV_wind/master/Test_Rose003.csv')\nTurbDF = pd.read_csv(\"https://raw.githubusercontent.com/Futile21/CSV_wind/master/PowerTurb4.csv\")\n\nxspace = np.linspace(-0.0, 25, 100)\nNamesDir=[\"N\",\"NNE\",\"NE\",\"ENE\",\"E\",\"ESE\",\"SE\",\"SSE\",\"S\",\"SSW\",\"SW\",\"WSW\",\"W\",\"WNW\",\"NW\",\"NNW\"]\n\n\n\n\n\n\n\nMapData = [\n go.Scattermapbox(\n lat=WindDF['lat'],\n lon=WindDF['lon'],\n mode=\"markers\",\n # hoverinfo=df['loc'].astype(str) + ' inches',\n # text=[i for i in list_of_locations],\n text=np.array(WindDF['CF-Turbine 1-50']).flatten(),\n marker=dict(\n color=np.array(WindDF['CF-Turbine 1-50']).flatten(), ################ LINK\n colorscale=scl,\n reversescale=True,\n opacity=0.35,\n size=8,\n colorbar=dict(\n # title=PowerType,\n titlefont=dict(size=18,family=\"Arial\"),\n titleside=\"right\",\n outlinecolor=\"rgba(68, 68, 68, 0)\",\n ticks=\"outside\",\n showticksuffix=\"last\",\n tickmode=\"auto\",\n ),\n ),\n ),\n ]\n\n\n############################################################################################################################################################ HTML part\n\n\nMapRSA= html.Div(\n [dcc.Graph(id=\"MapRSA\",figure=dict(data=MapData,layout=RSAlayout))],\n style={\n #'padding-top': 20,\n 'padding-bottom': 20,},\n )\n\nRoseColour = ['rgb(18, 0, 57)', 'rgb(77, 0, 153)', 'rgb(102, 0, 204)', 'rgb(128, 0, 255)', 'rgb(153, 51, 255)']\nNames=[\"N\",\"NNE\",\"NE\",\"ENE\",\"E\",\"ESE\",\"SE\",\"SSE\",\"S\",\"SSW\",\"SW\",\"WSW\",\"W\",\"WNW\",\"NW\",\"NNW\"]\n\n\n############ ############ ############\n\n# WSPD=da.sel(time=slice('2010-10','2010-11'))['WSPD']\n# WDRO=da.sel(time=slice('2010-10','2010-11'))['WDRO']\n# x=rose(1, WSPD, WDRO)\n#\n#\n# ############\n#\n# Rosetraces = []\n# cont = 0\n# for j in reversed(list(x[\"50\"].keys())):\n# # print(j)\n# # print(x[i][j])\n#\n# # print(\"\")\n# Rosetraces.append(\n# go.Barpolar(\n# r=x[\"100\"][j],\n# name=f'Greater {j} m/s',\n# marker_color=RoseColour[cont],\n# theta=Names,\n# ),\n# )\n# cont+=1\n#\n# Names=[\"N\",\"NNE\",\"NE\",\"ENE\",\"E\",\"ESE\",\"SE\",\"SSE\",\"S\",\"SSW\",\"SW\",\"WSW\",\"W\",\"WNW\",\"NW\",\"NNW\"]\n\nrose = html.Div([\n dcc.Graph(\n id='rose-graph',\n # figure={\n # 'data':Rosetraces,\n # 'layout': Roselayout\n # }\n )\n])\n\n############ ############ ############\n\nPowerGraph = html.Div([\n dcc.Graph(\n id='power-graph',\n )\n])\n\n\nfigurePOwer = html.Div([\n dcc.Graph(\n id='figurePOwer-graph',\n\n )\n])\n\n\n############################################################################################################################################################ HTML Layout\n\n\nlayout1 = html.Div([\n\n html.Div([navbar]),\n\n## Text_Instructions_one\n html.Div(\n dbc.Row([\n dbc.Col(dbc.Container([\n Text_Instructions_one, ]),\n md=9,\n sm=9,\n ),\n dbc.Col(\n Picture_CSIR,\n md=3,\n sm=3,\n ),\n ]),\n ),\n\n## Radio and InfoCard\n html.Div(\n dbc.Row([\n dbc.Col(dbc.Jumbotron(\n Radio, ),\n md=6,\n sm=12,\n width={\"offset\": 1},\n ),\n dbc.Col(\n InfoCard,\n md=2,\n sm=6,\n align=\"center\",\n width={\"offset\": 1},\n\n ),\n\n ])\n ),\n\n## Map of RSA\n html.Div(\n dbc.Row([\n dbc.Col(dbc.Container([MapRSA]),\n md=12,\n sm=12,\n align=\"center\",\n ),\n ]),\n ),\n\n\n## H4 Generalized Wind Climate\n html.Div(\n dbc.Row([\n dbc.Col(html.H4('Generalized Wind Climate'),\n align=\"center\",\n width=3,\n ),\n ],\n justify=\"center\",),\n style = {'padding-bottom': 20,},\n ),\n\n## Dropdown\n html.Div(\n dbc.Row([\n dbc.Col(dbc.Container(\n Dropdown_Height, ),\n md=4,\n sm=4,\n align=\"center\",\n width={\"offset\": 2},\n\n ),\n dbc.Col(dbc.Container(\n Dropdown_Turb, ),\n md=4,\n sm=4,\n align=\"center\",\n # width={\"offset\": 2},\n\n ),\n\n ])\n\n ),\n\n## Power Graph and Rose\n\n html.Div(\n dbc.Row([\n dbc.Col(dbc.Container(\n PowerGraph,),\n md=7,\n sm=12,\n ),\n dbc.Col(\n rose,\n md=4,\n sm=6,\n align=\"start\",\n ),\n\n ],no_gutters=True,)\n ),\n\n## Picture_GIZ and Info_mine\n html.Div(\n dbc.Row([\n dbc.Col(\n Picture_GIZ,\n md=6,\n sm=6,\n ),\n dbc.Col(\n Info_mine,\n md=6,\n sm=6,\n ),\n ])\n ),\n\n ])\n\n\nlayout2 = html.Div([\n\n## Opt 1\n html.Div(\n dbc.Row([\n dbc.Col(\n html.H3('Opt 1'),\n md=11,\n sm=11,\n ),\n dbc.Col(\n dcc.Link('Go to App', href='/'),\n md=1,\n sm=1,\n ),\n ]),\n ),\n\n## Text_Method\n html.Div(\n dbc.Row([\n dbc.Col(\n Text_Method,\n md=12,\n sm=12,\n ),\n ]),\n ),\n\n## table and Pic\n html.Div(\n dbc.Row([\n dbc.Col(\n html.Div(\n table,\n ),\n md=4,\n sm=12,\n align=\"center\",\n width={\"offset\": 1},\n\n ),\n dbc.Col(\n html.Div(\n Picture_Talbe),\n md=7,\n sm=12,\n ),\n ]),\n ),\n\n## Text_GenWind\n html.Div(\n dbc.Row([\n dbc.Col(\n Text_GenWind,\n md=12,\n sm=12,\n ),\n ]),\n ),\n\n ])\n\n\n\n############################################################################################################################################################ App\n\n\napp = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP,dbc.themes.GRID])\napp.config.suppress_callback_exceptions = True\n\napp.layout = html.Div([\n dcc.Location(id='url', refresh=False),\n html.Div(id='page-content')\n])\n\n############################################################################################################################################################ Callback\n\n\n@app.callback(Output('page-content', 'children'),\n [Input('url', 'pathname')])\ndef display_page(pathname):\n if pathname == '/':\n return layout1\n elif pathname == '/info':\n return layout2\n else:\n return '404'\n\n\n\n################################ CARD TOP\n\n@app.callback(Output(\"cardHeader\", \"children\"),\n [Input(\"RadioTurb\", \"value\"),\n Input(\"RadioHeight\", \"value\")\n ],)\ndef locDATA1(Turb,Height):\n return f\"{Turb} at {Height}m\"\n\n\n################################ CARD MID\n\n@app.callback(Output(\"cardmidT\", \"children\"),\n [Input(\"MapRSA\", \"clickData\"),\n Input(\"RadioTurb\", \"value\"),\n Input(\"RadioHeight\", \"value\"),\n ],)\ndef locDATA2(clickData,Turb,Height):\n if clickData is None:\n return \"\"\n else:\n ID = clickData['points'][0]['pointIndex']\n\n # CF= np.array(da[\"CF\"].sel(ID=ID,Turb=Turb,hgt=int(Height)))\n CF=np.array(WindDF[(WindDF['ID'] == ID)]['CF-'+Turb+'-'+Height]).flatten()\n\n return (\"CF is \"+str(CF)+\" %\")\n\n@app.callback(Output(\"cardmidM\", \"children\"),\n [Input(\"MapRSA\", \"clickData\" ),\n Input(\"RadioTurb\", \"value\"),\n Input(\"RadioHeight\", \"value\"),\n ],)\ndef locDATA3(clickData,Turb,Height):\n if clickData is None:\n return \"please Click on the Map\"\n else:\n ID = clickData['points'][0]['pointIndex']\n\n POWER=np.array(WindDF[(WindDF['ID'] == ID)]['WindPower-'+Turb+'-'+Height]).flatten()\n\n POWER_round = str(round(float(POWER), 1))\n return (\"Power is \" + str(POWER_round)+\" MWh per year\")\n\n\n################################ CARD BOTTOM\n\n@app.callback(Output(\"cardLat\", \"children\"),\n [Input(\"MapRSA\", \"clickData\" )],)\ndef locDATA4(clickData):\n if clickData is None:\n return \"\"\n\n else:\n XLAT = clickData['points'][0]['lat']\n XLONG = clickData['points'][0]['lon']\n\n lat =str( XLAT)\n\n lat1 = lat[1:3];lat2 = lat[4:6];lat3 = lat[6:8]\n LatSplt=lat1+\"\\N{DEGREE SIGN}\"+lat2+u\"\\u2032\"+lat3+u\"\\u2033S\"\n\n return (\"Latitude \"+LatSplt)\n\n@app.callback(Output(\"cardLon\", \"children\"),\n [Input(\"MapRSA\", \"clickData\" )],)\ndef locDATA4(clickData):\n if clickData is None:\n return \"\"\n\n else:\n XLAT = clickData['points'][0]['lat']\n XLONG = clickData['points'][0]['lon']\n\n long =str( XLONG)\n\n long1 = long[0:2];long2 = long[3:5];long3 = long[5:7]\n LongSlt=long1+\"\\N{DEGREE SIGN}\"+long2+u\"\\u2032\"+long3+u\"\\u2033E\"\n return (\"Longitude \" + LongSlt)\n\n\n################################ Power Graph\n\n@app.callback(Output('power-graph', 'figure'),\n [\n Input(\"MapRSA\", \"clickData\"),\n Input(\"DropdownTurb\", \"value\"),\n Input(\"DropdownHeight\", \"value\"),\n ])\ndef update_figurePower(clickData,DropdownTurb,DropdownHeight):\n\n if clickData is None:\n ID=0\n else:\n ID = clickData['points'][0]['pointIndex']\n\n PowerTraces = []\n for Height in DropdownHeight:\n\n loc = float(np.array(WindDF[(WindDF['ID'] == ID)]['loc-'+Height]))\n scale = float(np.array(np.array(WindDF[(WindDF['ID'] == ID)]['scale-'+Height])))\n\n PowerTraces.append(\n go.Scatter(\n x=xspace,\n y=norm.pdf(xspace, loc=float(loc), scale=float(scale)),\n name=Height+\" m\",\n )\n )\n\n for Turbtype in DropdownTurb:\n\n\n PowerTraces.append(\n go.Scatter(\n x=np.array(TurbDF['Speed']),\n y=np.array(TurbDF[Turbtype]),\n name=\"Turbine Power Curve\",\n yaxis=\"y2\",\n )\n )\n\n figure = dict(data=PowerTraces,layout=Powelayout)\n return figure\n\n\n################################ rose Graph\n\n@app.callback(Output('rose-graph', 'figure'),\n [Input(\"MapRSA\", \"clickData\"),\n Input(\"DropdownHeight\", \"value\"),])\ndef update_figureRose(clickData,DropdownHeight):\n\n if clickData is None:\n ID = 0\n else:\n ID = clickData['points'][0]['pointIndex']\n\n RoseTraces=[]\n for Height in DropdownHeight:\n Dir = list(map(lambda x: x + \"-\" + Height, NamesDir))\n Dir.append(Dir[0])\n rose = np.array(RoseDF[(RoseDF['ID'] == ID)][Dir]).flatten()\n Names = NamesDir\n Names.append(Names[0])\n\n RoseTraces.append(\n go.Scatterpolar(r=rose, theta=Names, fill='toself', name=Height+' m'))\n\n figure = dict(data=RoseTraces,layout=Roselayout)\n return figure\n\n\nserver = app.server\n\n\nif __name__ == '__main__':\n app.run_server()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":33632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"135361373","text":"from quex.input.setup import NotificationDB\nfrom quex.input.regular_expression.pattern import Pattern_Prep\nimport quex.input.regular_expression.core as regular_expression\nfrom quex.input.code.base import SourceRef, \\\n SourceRef_DEFAULT, \\\n SourceRefObject\nfrom quex.engine.state_machine.core import DFA \nimport quex.engine.state_machine.construction.sequentialize as sequentialize\nimport quex.engine.state_machine.algorithm.beautifier as beautifier \nimport quex.engine.state_machine.check.identity as identity\nimport quex.engine.state_machine.check.tail as tail\nfrom quex.engine.misc.tools import typed\nfrom quex.engine.misc.interval_handling import NumberSet\nfrom quex.engine.counter import IndentationCount_Pre, \\\n CountAction, \\\n CountActionMap, \\\n cc_type_name_db, \\\n cc_type_db\nimport quex.engine.misc.error as error\nimport quex.engine.misc.error_check as error_check\nfrom quex.engine.misc.file_in import check, \\\n check_or_die, \\\n skip_whitespace, \\\n read_identifier, \\\n read_integer\nfrom quex.constants import E_CharacterCountType\nfrom quex.blackboard import setup as Setup\n\nfrom collections import defaultdict\nfrom operator import itemgetter\n\nclass CountBase_Prep:\n @typed(sr=SourceRef)\n def __init__(self, sr, Name, IdentifierList):\n self.sr = sr\n self.name = Name\n self.identifier_list = IdentifierList\n self._ca_map_specifier = CountActionMap_Prep()\n\n def _base_parse(self, fh, IndentationSetupF=False):\n \"\"\"Parses pattern definitions of the form:\n \n [ \\t] => grid 4;\n [:intersection([:alpha:], [\\X064-\\X066]):] => space 1;\n\n In other words the right hand side *must* be a character set.\n\n ADAPTS: result to contain parsing information.\n \"\"\"\n\n # NOTE: Catching of EOF happens in caller: parse_section(...)\n #\n while 1 + 1 == 2:\n skip_whitespace(fh)\n if check(fh, \">\"): \n break\n \n # A regular expression state machine\n pattern, identifier, sr = _parse_definition_head(fh, self.identifier_list)\n if pattern is None and IndentationSetupF:\n error.log(\"Keyword '\\\\else' cannot be used in indentation setup.\", fh)\n\n # '_parse_definition_head()' ensures that only identifiers mentioned in \n # 'result' are accepted. \n if self.requires_count():\n count = _read_value_specifier(fh, identifier, 1)\n self.specify(identifier, pattern, count, sr)\n else:\n self.specify(identifier, pattern, sr)\n\n if not check(fh, \";\"):\n error.log(\"Missing ';' after '%s' specification.\" % identifier, fh)\n\n return # Must be followed by 'finalization'\n\nclass LineColumnCount_Prep(CountBase_Prep):\n \"\"\"Line/column number count specification.\n ___________________________________________________________________________\n The main result of the parsing the the Base's .count_command_map which is \n an instance of CountActionMap_Prep.\n ____________________________________________________________________________\n \"\"\"\n @typed(sr=SourceRef)\n def __init__(self, fh):\n sr = SourceRef.from_FileHandle(fh)\n self.__fh = fh\n CountBase_Prep.__init__(self, sr, \n \"Line/column counter\", \n (\"space\", \"grid\", \"newline\")) \n\n def parse(self):\n self._base_parse(self.__fh, IndentationSetupF=False)\n\n # Finalize / Produce 'LineColumnCount' object.\n # \n ca_map = self._ca_map_specifier.finalize(\n Setup.buffer_encoding.source_set.minimum(), \n Setup.buffer_encoding.source_set.least_greater_bound(), \n self.sr)\n check_grid_values_integer_multiples(ca_map)\n check_defined(ca_map, self.sr, E_CharacterCountType.LINE)\n return ca_map \n\n def requires_count(self):\n return True\n\n @typed(sr=SourceRef, Identifier=(str,unicode))\n def specify(self, Identifier, Pattern, Count, sr):\n if Pattern is None:\n self._ca_map_specifier.define_else(cc_type_db[Identifier], Count, sr)\n else:\n trigger_set = extract_trigger_set(sr, Identifier, Pattern) \n self._ca_map_specifier.add(trigger_set, cc_type_db[Identifier], Count, sr)\n\nclass IndentationCount_Prep(CountBase_Prep):\n \"\"\"Indentation counter specification.\n ____________________________________________________________________________\n The base's .count_command_map contains information about how to count the \n space at the beginning of the line. The count until the first non-whitespace\n is the 'indentation'. \n \n +bad:\n\n The spec contains information about what characters are not supposed to\n appear in indentation (bad characters). Depending on the philosophical\n basis, some might consider 'space' as evil, others consider 'tab' as evil.\n\n +newline:\n\n A detailed state machine can be defined for 'newline'. This might be \n '\\n|(\\r\\n)' or more complex things.\n\n +suppressor:\n\n A newline might be suppressed by '\\' for example. For that, it might be\n specified as 'newline suppressor'.\n ____________________________________________________________________________\n \"\"\"\n @typed(sr=SourceRef)\n def __init__(self, fh):\n sr = SourceRef.from_FileHandle(fh)\n self.__fh = fh\n self.whitespace_character_set = SourceRefObject(\"whitespace\", None)\n self.bad_space_character_set = SourceRefObject(\"bad\", None)\n self.sm_newline = SourceRefObject(\"newline\", None)\n self.sm_newline_suppressor = SourceRefObject(\"suppressor\", None)\n self.sm_comment_list = []\n\n # The base class defines the '._ca_map_specifier'.\n # However, in this class it is only used for error checking.\n CountBase_Prep.__init__(self, sr, \"Indentation counter\", \n (\"whitespace\", \"comment\", \"newline\", \"suppressor\", \"bad\"))\n\n def parse(self):\n self._base_parse(self.__fh, IndentationSetupF=True)\n\n # Finalize / Produce 'IndentationCount' object.\n # \n if self.whitespace_character_set.get() is None:\n whitespace = self.__whitespace_default()\n self.__specify_character_set(self.whitespace_character_set, \n \"whitespace\", whitespace, \n sr=SourceRef_DEFAULT)\n if self.sm_newline.get() is None:\n self.__specify_newline(self.__sm_newline_default(), SourceRef_DEFAULT)\n\n # -- consistency\n self._consistency_check()\n\n if self.sm_newline_suppressor.set_f():\n sm_suppressed_newline = sequentialize.do([self.sm_newline_suppressor.get(),\n self.sm_newline.get()])\n sm_suppressed_newline = beautifier.do(sm_suppressed_newline)\n else:\n sm_suppressed_newline = None\n\n def get_pattern(SM, PS, SR):\n if SM is None: return None\n return Pattern_Prep(SM, PatternString=PS, Sr=SR)\n\n pattern_comment_list = []\n for sm_comment in self.sm_comment_list:\n only_common_f, \\\n common_f = tail.do(self.sm_newline.get(), sm_comment.get())\n\n error_check.tail(only_common_f, common_f, \n \"indentation handler's newline\", self.sm_newline.sr, \n \"comment\", sm_comment.sr)\n pattern = get_pattern(sm_comment.get(), \n \"\", \n sm_comment.sr)\n pattern_comment_list.append(pattern)\n\n return IndentationCount_Pre(self.sr, \n self.whitespace_character_set.get(), \n self.bad_space_character_set.get(), \n get_pattern(self.sm_newline.get(), \n \"\",\n self.sm_newline.sr),\n get_pattern(sm_suppressed_newline, \n \"\", \n self.sm_newline_suppressor.sr),\n pattern_comment_list)\n\n def requires_count(self):\n return False\n\n def specify(self, identifier, pattern, sr):\n if identifier == \"whitespace\": \n self.__specify_character_set(self.whitespace_character_set, \n \"whitespace\", pattern, sr)\n elif identifier == \"bad\": \n self.__specify_character_set(self.bad_space_character_set, \n \"bad\", pattern, sr)\n elif identifier == \"newline\": \n self.__specify_newline(pattern.extract_sm(), sr)\n elif identifier == \"suppressor\": \n self.__specify_suppressor(pattern.extract_sm(), sr)\n elif identifier == \"comment\": \n self.__specify_comment(pattern.extract_sm(), sr)\n else: \n return False\n return True\n\n @typed(sr=SourceRef)\n def __specify_character_set(self, ref, Name, PatternOrNumberSet, sr):\n cset = extract_trigger_set(sr, Name, PatternOrNumberSet)\n self._ca_map_specifier.add(cset, cc_type_db[Name], None, sr)\n prev_cset = ref.get()\n if prev_cset is None: ref.set(cset, sr)\n else: prev_cset.unite_with(cset)\n\n @typed(sr=SourceRef)\n def __specify_newline(self, Sm, sr):\n assert Sm is not None \n _error_if_defined_before(self.sm_newline, sr)\n\n if not Sm.is_DFA_compliant(): Sm = beautifier.do(Sm)\n\n beginning_char_set = Sm.get_beginning_character_set()\n ending_char_set = Sm.get_ending_character_set()\n\n self._ca_map_specifier.add(beginning_char_set, \n E_CharacterCountType.X_BEGIN_NEWLINE, \n None, sr)\n\n # Do not consider a character from newline twice\n ending_char_set.subtract(beginning_char_set)\n if not ending_char_set.is_empty():\n self._ca_map_specifier.add(ending_char_set, \n E_CharacterCountType.X_END_NEWLINE, \n None, sr)\n\n self.sm_newline.set(Sm, sr)\n\n @typed(sr=SourceRef)\n def __specify_suppressor(self, Sm, sr):\n _error_if_defined_before(self.sm_newline_suppressor, sr)\n\n if not Sm.is_DFA_compliant(): Sm = beautifier.do(Sm)\n\n self._ca_map_specifier.add(Sm.get_beginning_character_set(), \n E_CharacterCountType.X_BEGIN_NEWLINE_SUPPRESSOR,\n None, sr)\n self.sm_newline_suppressor.set(Sm, sr)\n\n @typed(sr=SourceRef)\n def __specify_comment(self, Sm, sr):\n for before in self.sm_comment_list:\n if not identity.do(before.get(), Sm): continue\n error.log(\"'comment' has been defined before;\", sr, DontExitF=True)\n error.log(\"at this place.\", before.sr)\n\n if not Sm.is_DFA_compliant(): Sm = beautifier.do(Sm)\n\n self._ca_map_specifier.add(Sm.get_beginning_character_set(), \n E_CharacterCountType.X_BEGIN_COMMENT_TO_NEWLINE,\n None, sr)\n\n sm_comment = SourceRefObject(\"comment\", None)\n sm_comment.set(Sm, sr)\n self.sm_comment_list.append(sm_comment)\n\n def __sm_newline_default(self):\n \"\"\"Default newline: '(\\n)|(\\r\\n)'\n \"\"\"\n global cc_type_name_db\n\n newline_set = NumberSet(ord('\\n'))\n retour_set = NumberSet(ord('\\r'))\n\n before = self._ca_map_specifier.find_occupier(newline_set, set())\n if before is not None:\n error.log(\"Trying to implement default newline: '\\\\n' or '\\\\r\\\\n'.\\n\" \n \"The '\\\\n' option is not possible, since it has been occupied by '%s'.\\n\" \\\n \"No newline can be defined by default. \" \\\n \"Indentation handlers without newline are unfeasible.\"\n % cc_type_name_db[before.cc_type], before.sr) \n\n sm = DFA.from_character_set(newline_set)\n\n if Setup.dos_carriage_return_newline_f:\n before = self._ca_map_specifier.find_occupier(retour_set, set())\n if before is not None:\n error.warning(\"Trying to implement default newline: '\\\\n' or '\\\\r\\\\n'.\\n\" \n \"The '\\\\r\\\\n' option is not possible, since '\\\\r' has been occupied by '%s'.\" \\\n % cc_type_name_db[before.cc_type],\n before.sr, \n SuppressCode=NotificationDB.warning_default_newline_0D_impossible)\n else:\n sm.add_transition_sequence(sm.init_state_index, [retour_set, newline_set])\n\n return sm\n\n def __whitespace_default(self):\n \"\"\"Try to define default whitespace ' ' or '\\t' if their positions\n are not yet occupied in the count_command_map.\n \"\"\"\n cs0 = NumberSet(ord(\" \"))\n cs1 = NumberSet(ord(\"\\t\"))\n result = NumberSet()\n if not self._ca_map_specifier.find_occupier(cs0, set()):\n result.unite_with(cs0)\n if not self._ca_map_specifier.find_occupier(cs1, set()):\n result.unite_with(cs1)\n\n if result.is_empty():\n error.log(\"Trying to implement default whitespace ' ' or '\\\\t' failed.\\n\"\n \"Characters are occupied by other elements.\", self.sr)\n return result\n\n def _consistency_check(self):\n if self.sm_newline_suppressor.get() is not None \\\n and self.sm_newline.get() is None:\n error.log(\"A newline 'suppressor' has been defined.\\n\"\n \"But there is no 'newline' in indentation defintion.\", \n self.sm_newline_suppressor.sr)\n\n\nclass CountActionMap_Prep(object):\n \"\"\"Association of character sets with triggered count commands.\n ___________________________________________________________________________\n\n list: (character set, CountAction)\n\n where the 'character set' specifies a subset of characters for which there\n is a definition by the given 'parameter'. The character sets are disjoint.\n\n This map is used to determine whether actions on character sets are defined \n more than once. The CountAction contains source references. This allows\n for detailed error messages.\n ___________________________________________________________________________\n \"\"\"\n __slots__ = (\"__map\", \"__else\")\n def __init__(self):\n \"\"\"Primarily, the '__map' member stores the list of associations between\n character sets and the count command entry. The '__else' contains the \n count command which waits to be applied to the remaining set of characters.\n \"\"\"\n self.__map = CountActionMap()\n self.__else = None\n\n def finalize(self, GlobalMin, GlobalMax, SourceReference, ForLineColumnCountF=False):\n \"\"\"After all count commands have been assigned to characters, the \n remaining character set can be associated with the 'else-CountAction'.\n \"\"\"\n if self.__else is None: \n else_cmd = CountAction(E_CharacterCountType.COLUMN, 1, SourceRef_DEFAULT)\n error.warning(\"No '\\else' defined in counter setup. Assume '\\else => space 1;'\", SourceReference, \n SuppressCode=NotificationDB.warning_counter_setup_without_else)\n else: \n else_cmd = self.__else\n \n remaining_set = self.get_remaining_set(GlobalMin, GlobalMax)\n if not remaining_set.is_empty():\n self.__map.append((remaining_set, else_cmd))\n\n return self.__map\n\n @typed(sr=SourceRef, Identifier=E_CharacterCountType)\n def define_else(self, CC_Type, Value, sr):\n \"\"\"Define the '\\else' character set which is resolved AFTER everything has been \n defined.\n \"\"\"\n if self.__else is not None:\n error.log(\"'\\\\else has been defined more than once.\", sr, \n DontExitF=True)\n error.log(\"Previously, defined here.\", self.__else.sr)\n self.__else = CountAction(CC_Type, Value, sr)\n\n def add(self, CharSet, CC_Type, Value, sr):\n if CharSet.is_empty(): \n error.log(\"Empty character set found for '%s'.\" % cc_type_name_db[CC_Type], sr)\n elif CC_Type == E_CharacterCountType.GRID:\n self.check_grid_specification(Value, sr)\n self.check_intersection(CC_Type, CharSet, sr)\n self.__map.append((CharSet, CountAction(CC_Type, Value, sr)))\n\n def check_intersection(self, CcType, CharSet, sr):\n \"\"\"Check whether the given character set 'CharSet' intersects with \n a character set already mentioned in the map. Depending on the CcType\n of the new candidate certain count commands may be tolerated, i.e. \n their intersection is not considered.\n \"\"\"\n intersection_tolerated = {\n E_CharacterCountType.COLUMN: (),\n E_CharacterCountType.GRID: (),\n E_CharacterCountType.LINE: (),\n E_CharacterCountType.WHITESPACE: (),\n E_CharacterCountType.BAD: (), \n # Only to detect interference\n E_CharacterCountType.X_BEGIN_NEWLINE_SUPPRESSOR: (),\n E_CharacterCountType.X_BEGIN_NEWLINE: (E_CharacterCountType.X_END_NEWLINE,),\n E_CharacterCountType.X_END_NEWLINE: (E_CharacterCountType.X_BEGIN_NEWLINE,),\n E_CharacterCountType.X_BEGIN_COMMENT_TO_NEWLINE: (), \n }[CcType]\n\n interferer = self.find_occupier(CharSet, Tolerated=intersection_tolerated)\n if interferer is None:\n return\n _error_set_intersection(CcType, interferer, sr)\n\n def get_remaining_set(self, GlobalMin, GlobalMax):\n \"\"\"Return the set of characters which are not associated with count commands.\n Restrict the operation to characters from GlobalMin to GlobalMax (inclusively).\n \"\"\"\n result = self.__get_remaining_set()\n result.cut_lesser(GlobalMin)\n result.cut_greater_or_equal(GlobalMax)\n return result\n\n def find_occupier(self, CharSet, Tolerated):\n \"\"\"Find a command that occupies the given CharSet, at least partly.\n RETURN: None, if no such occupier exists.\n \"\"\"\n for character_set, before in self.__map:\n if before.cc_type in Tolerated: continue\n elif not character_set.has_intersection(CharSet): continue\n return before\n return None\n\n def __get_remaining_set(self):\n ignored = (E_CharacterCountType.BAD, \n E_CharacterCountType.X_BEGIN_NEWLINE_SUPPRESSOR, \n E_CharacterCountType.X_BEGIN_NEWLINE, \n E_CharacterCountType.X_END_NEWLINE) \n result = NumberSet()\n for character_set, info in self.__map:\n if info.cc_type in ignored: continue\n result.unite_with(character_set)\n return result.get_complement(Setup.buffer_encoding.source_set)\n\n def check_grid_specification(self, Value, sr):\n if Value == 0: \n error.log(\"A grid count of 0 is nonsense. May be define a space count of 0.\", sr)\n elif Value == 1:\n error.warning(\"Indentation grid counts of '1' are equivalent of to a space\\n\" + \\\n \"count of '1'. The latter is faster to compute.\",\n sr)\n\n def __str__(self):\n def _db_to_text(title, CountOpInfoList):\n txt = \"%s:\\n\" % title\n for character_set, info in sorted(CountOpInfoList, key=lambda x: x[0].minimum()):\n if type(info.value) in [str, unicode]:\n txt += \" %s by %s\\n\" % (info.value, character_set.get_utf8_string())\n else:\n txt += \" %3i by %s\\n\" % (info.value, character_set.get_utf8_string())\n return txt\n\n db_by_name = defaultdict(list)\n for character_set, info in self.__map:\n name = cc_type_name_db[info.cc_type]\n db_by_name[name].append((character_set, info))\n\n txt = [\n _db_to_text(cname, count_command_info_list)\n for cname, count_command_info_list in sorted(db_by_name.iteritems(), key=itemgetter(0))\n ]\n return \"\".join(txt)\n\ndef _parse_definition_head(fh, IdentifierList):\n\n if check(fh, \"\\\\default\"): \n error.log(\"'\\\\default' has been replaced by keyword '\\\\else' since quex 0.64.9!\", fh)\n elif check(fh, \"\\\\else\"): \n pattern = None\n else: \n pattern = regular_expression.parse(fh)\n\n skip_whitespace(fh)\n check_or_die(fh, \"=>\", \" after character set definition.\")\n\n skip_whitespace(fh)\n identifier = read_identifier(fh, OnMissingStr=\"Missing identifier following '=>'.\")\n error.verify_word_in_list(identifier, IdentifierList,\n \"Unrecognized specifier '%s'.\" % identifier, fh)\n skip_whitespace(fh)\n\n return pattern, identifier, SourceRef.from_FileHandle(fh)\n\ndef _read_value_specifier(fh, Keyword, Default=None):\n skip_whitespace(fh)\n value = read_integer(fh)\n if value is not None: return value\n\n # not a number received, is it an identifier?\n variable = read_identifier(fh)\n if variable != \"\": return variable\n elif Default is not None: return Default\n\n error.log(\"Missing integer or variable name after keyword '%s'.\" % Keyword, fh) \n\n_ca_map_default = None\ndef LineColumnCount_Default():\n global _ca_map_default\n\n if _ca_map_default is None:\n specifier = CountActionMap_Prep()\n specifier.add(NumberSet(ord('\\n')), E_CharacterCountType.LINE, 1, SourceRef_DEFAULT)\n specifier.add(NumberSet(ord('\\t')), E_CharacterCountType.GRID, 4, SourceRef_DEFAULT)\n specifier.define_else(E_CharacterCountType.COLUMN, 1, SourceRef_DEFAULT) # Define: \"\\else\"\n _ca_map_default = specifier.finalize(Setup.buffer_encoding.source_set.minimum(), \n Setup.buffer_encoding.source_set.least_greater_bound(), # Apply: \"\\else\"\n SourceRef_DEFAULT) \n return _ca_map_default\n\n\ndef _error_set_intersection(CcType, Before, sr):\n global cc_type_name_db\n\n note_f = False\n if CcType == E_CharacterCountType.X_END_NEWLINE \\\n or Before.cc_type == E_CharacterCountType.X_END_NEWLINE:\n note_f = True\n\n prefix = {\n E_CharacterCountType.COLUMN: \"\",\n E_CharacterCountType.GRID: \"\",\n E_CharacterCountType.LINE: \"\",\n E_CharacterCountType.BAD: \"\",\n E_CharacterCountType.WHITESPACE: \"\",\n E_CharacterCountType.X_BEGIN_NEWLINE_SUPPRESSOR: \"beginning \",\n E_CharacterCountType.X_BEGIN_COMMENT_TO_NEWLINE: \"beginning \",\n E_CharacterCountType.X_BEGIN_NEWLINE: \"beginning \",\n E_CharacterCountType.X_END_NEWLINE: \"ending \",\n }[CcType]\n\n error.log(\"The %scharacter set defined in '%s' intersects\" % (prefix, cc_type_name_db[CcType]),\n sr, DontExitF=True, WarningF=False)\n error.log(\"with '%s' at this place.\" % cc_type_name_db[Before.cc_type], \n Before.sr, DontExitF=note_f, WarningF=False)\n\n if note_f:\n error.log(\"Note, for example, 'newline' cannot end with a character which is subject\\n\"\n \"to indentation counting (i.e. 'space' or 'grid').\", sr)\n\ndef _error_if_defined_before(Before, sr):\n if not Before.set_f(): return\n\n error.log(\"'%s' has been defined before;\" % Before.name, sr, \n DontExitF=True)\n error.log(\"at this place.\", Before.sr)\n\ndef extract_trigger_set(sr, Keyword, Pattern):\n if Pattern is None:\n return None\n elif isinstance(Pattern, NumberSet):\n return Pattern\n\n def check_can_be_matched_by_single_character(SM):\n bad_f = False\n init_state = SM.get_init_state()\n if SM.get_init_state().is_acceptance(): \n bad_f = True\n elif len(SM.states) != 2:\n bad_f = True\n # Init state MUST transit to second state. Second state MUST not have any transitions\n elif len(init_state.target_map.get_target_state_index_list()) != 1:\n bad_f = True\n else:\n tmp = set(SM.states.keys())\n tmp.remove(SM.init_state_index)\n other_state_index = next(iter(tmp))\n if len(SM.states[other_state_index].target_map.get_target_state_index_list()) != 0:\n bad_f = True\n\n if bad_f:\n error.log(\"For '%s' only patterns are addmissible which\\n\" % Keyword + \\\n \"can be matched by a single character, e.g. \\\" \\\" or [a-z].\", sr)\n\n sm = Pattern.extract_sm()\n check_can_be_matched_by_single_character(sm)\n\n transition_map = sm.get_init_state().target_map.get_map()\n assert len(transition_map) == 1\n return transition_map.values()[0]\n\ndef check_grid_values_integer_multiples(CaMap):\n \"\"\"If there are no spaces and the grid is on a homogeneous scale,\n => then the grid can be transformed into 'easy-to-compute' spaces.\n \"\"\"\n grid_value_list = []\n min_info = None\n for character_set, info in CaMap:\n if info.cc_type == E_CharacterCountType.COLUMN: \n return\n elif info.cc_type != E_CharacterCountType.GRID: \n continue\n elif type(info.value) in (str, unicode): \n # If there is one single 'variable' grid value, \n # then no assumptions can be made.\n return\n grid_value_list.append(info.value)\n if min_info is None or info.value < min_info.value:\n min_info = info\n\n if min_info is None:\n return\n\n # Are all grid values a multiple of the minimum?\n if all(x % min_info.value == 0 for x in grid_value_list):\n error.warning(\"Setup does not contain spaces, only grids (tabulators). All grid\\n\" \\\n \"widths are multiples of %i. The grid setup %s is equivalent to\\n\" \\\n % (min_info.value, repr(sorted(grid_value_list))[1:-1]) + \\\n \"a setup with space counts %s. Space counts are faster to compute.\\n\" \\\n % repr(map(lambda x: x / min_info.value, sorted(grid_value_list)))[1:-1],\n min_info.sr)\n return\n\ndef check_defined(CaMap, SourceReference, CCT):\n \"\"\"Checks whether the character counter type has been defined in the \n map.\n \n THROWS: Error in case that is has not been defined.\n \"\"\"\n for character_set, info in CaMap:\n if info.cc_type == CCT: \n return\n\n error.warning(\"Setup does not define '%s'.\" % cc_type_name_db[CCT], SourceReference, \n SuppressCode=NotificationDB.warning_counter_setup_without_newline)\n\n\n\n","sub_path":"quex/input/files/specifier/counter.py","file_name":"counter.py","file_ext":"py","file_size_in_byte":28571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"587353266","text":"from sys import exit\nimport random\n\nprint(\"What is your name?\")\n\nname = raw_input(\"> \")\n\ndef start():\n print(\"Welcome to the ultimate quest for riches and glory!\")\n\n print(\"You may move any of eight cardinal directions, which are as follows: \\nn \\nne \\ne \\nse \\ns \\nsw \\nw \\nnw\")\n\n print(\"To use these directions, type the letters as are above, and not the full name\")\n\n print(\"Your goal is to reach the treausre room and to claim the ultimate prize, \\nThe Jewl of Babylon\")\n\n print(\"In order to get here, you will face a variety of differenct rooms and have to navigate your way through the world.\")\n\n print(\"In each room you will face several encounters, and if you prevail, then you will be able to select a direction and move on.\")\n\n print(\"In each encounter you will be faced with 2 choices. Just type the number of the choice you want, and press enter to select it.\")\n\n print(\"So good luck, and best of whishes %s\" % name)\n print(\"PS. Pro-Tip: Draw a map on real paper in the real world\")\n\n print(\"What direction would you like to go in?\")\n def der(direction):\n\n if direction == \"n\":\n souls()\n\n elif direction == \"ne\":\n cloth()\n\n elif direction == \"e\":\n pens()\n\n elif direction == \"se\":\n lava()\n\n elif direction == \"s\":\n pit()\n\n elif direction == \"sw\":\n hands()\n\n elif direction == \"w\":\n bugs()\n\n elif direction == \"nw\":\n pit()\n\n else:\n noder()\n\n print(\"What direction would you like to go in?\")\n\n der(raw_input(\"> \"))\n\n der(raw_input(\"> \"))\n\ndef start1():\n print(\"You are back at the start again!\")\n\n print(\"Which direction do you want to go in?\")\n\n def der(direction):\n\n if direction == \"n\":\n souls()\n\n elif direction == \"ne\":\n cloth()\n\n elif direction == \"e\":\n pens()\n\n elif direction == \"se\":\n lava()\n\n elif direction == \"s\":\n pit()\n\n elif direction == \"sw\":\n hands()\n\n elif direction == \"w\":\n bugs()\n\n elif direction == \"nw\":\n pit()\n\n else:\n noder()\n der(raw_input(\"> \"))\n\n print(\"What direction would you like to go in?\")\n\n der(raw_input(\"> \"))\n\ndef souls():\n def der(direction):\n\n if direction == \"n\":\n wall()\n\n print(\"What direction would you like to go in?\")\n\n der(raw_input(\">\"))\n\n elif direction == \"ne\":\n nothing()\n\n print(\"What direction would you like to go in?\")\n\n der(raw_input(\"> \"))\n\n elif direction == \"e\":\n cloth()\n\n elif direction == \"se\":\n pens()\n\n elif direction == \"s\":\n start1()\n\n elif direction == \"sw\":\n bugs()\n\n elif direction == \"w\":\n nothing()\n\n print(\"What direction would you like to go in?\")\n\n der(raw_input(\"> \"))\n\n elif direction == \"nw\":\n sound()\n\n else:\n noder()\n\n print(\"What direction would you like to go in?\")\n\n der(raw_input(\"> \"))\n\n print(\"You have entered the room of souls\")\n\n print(\"Before you there is a sad ghost, what do you do?\")\n\n print(\"1. Try and sneak past the ghost and into the next room\")\n\n print(\"2. Go and see what is wrong with the ghost, try and help it\")\n\n choice = raw_input(\"> \")\n\n if choice == \"1\":\n print(\"The ghost attacks, and you realize it was all a trick to test your morales\")\n\n print(\"You have two options\")\n\n print(\"1. Run away from the ghost\")\n\n print(\"2. Kneel down, and submit to death\")\n\n choice = raw_input(\"> \")\n\n if choice == \"1\":\n print(\"You ran so far away that you ended back at the begining of the maze!\")\n\n start1()\n\n elif choice == \"2\":\n die(\"The ghost killed you for being a bad person!\")\n\n elif choice == \"2\":\n print(\"You go over to help the ghost, and it is made well\")\n\n print(\"The ghost thanks you for helping and says depending on how you answer the next question he will diecide if he likes you\")\n\n print(\"True or False, is Gandolf a wizard?\")\n\n print(\"1. True\")\n\n print(\"2. False\")\n\n choice = raw_input(\"> \")\n\n if choice == \"1\" or \"True\" or \"true\":\n print(\"That is correct go ahead and make your choice\")\n\n print(\"What direction would you like to go in?\")\n\n der(raw_input(\"> \"))\n\n elif choice == \"2\" or \"False\" or \"false\":\n print(\"SUFFER MY WRATH!!!!!\")\n\n die(\"You were kille by a ghost for not knowing your Sc-Fi Fantasy\")\n\n else:\n print(\"That is not a valid answer, restart the room\")\n\n souls()\n\n else:\n print(\"That is not a valid answer, restart the room\")\n\n souls()\n\ndef cloth():\n def der(direction):\n if direction == \"n\":\n nothing()\n\n print(\"What direction would you like to go in?\")\n\n der(raw_input(\"> \"))\n\n elif direction == \"ne\":\n print(\"There is nothing there\")\n\n print(\"What direction would you like to go in?\")\n\n der(raw_input(\"> \"))\n\n elif direction == \"e\":\n tar()\n\n elif direction == \"se\":\n reading()\n\n elif direction == \"s\":\n pens()\n\n elif direction == \"sw\":\n start1()\n\n elif direction == \"w\":\n souls()\n\n elif direction == \"nw\":\n war()\n\n else:\n noder()\n\n print(\"What direction would you like to go in?\")\n\n der(raw_input(\"> \"))\n\n\n print(\"You have entered into the room of cloth, before you stands the great Sewing Machine\")\n\n print(\"You realize that the machine is running, and that if you continue to stand on the piece of cloth it will impale you! But when you try and move you see your feet are glued down!\\nWhat will you do?\")\n\n print(\"1. Try and unstick your feet in an effort to get loose\")\n\n print(\"2. You try and talk to the machine to make a diplomatic bargain\")\n\n choice = raw_input(\"> \")\n\n if choice == \"1\":\n chance = [0, 1]\n\n result = random.choice(chance)\n\n print(\"Alright, there is a 50/50 chance that you will escape, litterally, we will see what happens!\")\n\n if result == 1:\n print(\"You managed to escape! You run away from the sewing machine, and you are free to choose a direction\")\n\n print(\"What direction would you like to go in?\")\n\n der(raw_input(\"> \"))\n\n elif result == 0:\n print(\"We are very sorry, but you were not able to escape.\")\n\n die(\" You were impaled by a sewing machine, pathetic\")\n\n else:\n print(\"There is an ERROR\")\n\n cloth()\n\n elif choice == \"2\":\n print(\"The machine stops, and tells you to speak your mind\")\n\n print(\"What do you do?\")\n\n print(\"1. Make up a sob story about how you are trying to get back to your long lost love, and you will do anything for them\")\n\n print(\"2. Tell the truth, that you are a greedy treasure hunter looking to make lots of money, and you don't care what you have to do\")\n\n choice == raw_input(\"> \")\n\n if choice == \"1\":\n print(\"The sewing machine uses the built in lie detector function to tell you are lying!\")\n\n print(\"The machine decides to kill you for lying\")\n\n die(\"You lied to a lie detector\")\n\n elif choice == \"2\":\n print(\"The machine understands the greed of humans, and decides to let you go on with your quest\")\n\n print(\"What direction would you like to go in?\")\n\n der(raw_input(\"> \"))\n\n else:\n print(\"That is not a valid answer, restart the room\")\n\n cloth()\n\n else:\n print(\"That is not a valid answer, restart the romm\")\n\n cloth()\n\ndef pens():\n def der(direction):\n if direction == \"n\":\n cloth()\n\n elif direction == \"ne\":\n tar()\n\n elif direction == \"e\":\n reading()\n\n elif direction == \"se\":\n print(\"There is nothing there\")\n\n print(\"What direction would you like to go in?\")\n\n der(raw_input(\"> \"))\n\n elif direction == \"s\":\n lava()\n\n elif direction == \"sw\":\n pit()\n\n elif direction == \"w\":\n start1()\n\n elif direction == \"nw\":\n souls()\n\n else:\n noder()\n\n print(\"What direction would you like to go in?\")\n\n der(raw_input(\"> \"))\n\n print(\"Welcome to the room of pens!\")\n\n print(\"You are walking to the next door\")\n\n print(\"......................\")\n\n print(\"And then a pen comes down from the cieling stabbing you under it\")\n\n print(\"You are bleeding and will die very soon \\nWhat will you do?\")\n\n print(\"1. Remove the pen from your body, and go as fast as you can to the next door\")\n\n print(\"2. Know that death is coming, and call on the Pen Godess for help\")\n\n choice = raw_input(\"> \")\n\n if choice == \"1\":\n print(\"As you remove the pen some ink coomes out the tip, and enters your blood stream, giving you blood posining\")\n\n print(\"What will you do?\")\n\n print(\"1. Cut your main artery so that you bleed to death quikly\")\n\n print(\"2. Call on the Pen Godess's son for help\")\n\n choice = raw_input(\"> \")\n\n if choice == \"1\":\n die(\"You bleed to death painfully\")\n\n elif choice == \"2\":\n print(\"The demigod says that his mother probably would have helped, but you blew it, and he will kill you\")\n\n die(\"You were killed by a todler demigod\")\n\n else:\n print(\"That is not a valid answer, restart the room\")\n\n pens()\n\n elif choice == \"2\":\n print(\"The Godess answers you and removes the pen very carefully\")\n\n print(\"You die, but she revieves you, and says she will let you go on, but after a test\")\n\n print(\"She asks you what is better, Band or Orchestra\")\n\n print(\"1. Band \\n2. Orchestra\")\n\n choice = raw_input(\"> \")\n\n if choice == \"1\":\n print(\"I agree with you! You may pass\")\n\n print(\"What direction would you like to go in?\")\n\n der(raw_input(\"> \"))\n\n elif choice == \"2\":\n print(\"I do not agree with you, but I suppose that everyone is entitled to their own opnions so I will let you pass, but know I hate you now :)\")\n\n print(\"What direction would you like to go in?\")\n\n der(raw_input(\"> \"))\n\n else:\n print(\"That is not a valid answer, restart the room\")\n\n pens()\n else:\n print(\"That is not a valid answer, restart the room.\")\n\ndef hands():\n def der(direction):\n if direction == \"n\":\n bugs()\n\n elif direction == \"ne\":\n start1()\n\n elif direction == \"e\":\n pit()\n\n elif direction == \"se\":\n numbers()\n\n elif direction == \"s\":\n lava()\n\n elif direction == \"sw\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"w\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"nw\":\n pit()\n\n else:\n noder()\n\n der(raw_input(\"> \"))\n\n print(\"Welcome to the Hall of Hands\")\n\n print(\"After you walk in, you feel somethings touching you, and you look over and see thousands of hands on the wals!\")\n\n print(\"What will you do?\")\n\n print(\"1. Run through the room as fast as you possibly can to get to the door you see at the end of the hall\")\n\n print(\"2. Just go back to the start of the maze\")\n\n choice = raw_input(\"> \")\n\n if choice == \"1\":\n print(\"There is a 3/5 chance that you will survive, lets see what happnens \\n**suspense**\")\n\n chance = [1, 2, 3, 4, 5]\n\n result = random.choice(chance)\n\n if result > 3:\n print(\"Bad luck, and you may think this was intentional, but trust me, it was random draw\")\n\n die(\"Stupidity and bad descision making\")\n\n elif result < 4:\n print(\"You made it congrats!\")\n\n print(\"You make it to the end of the hall and are allowed to move on\")\n\n print(\"What direction would you like to go in?\")\n\n der(raw_input(\"> \"))\n\n else:\n print(\"For some reason there was an ERROR\")\n\n hands()\n\n elif choice == \"2\":\n print(\"It may take longer, but trust me, it was for the better..... maybe\")\n\n start1()\n\n else:\n print(\"That is not a valid answer, restart the room\")\n\n hands()\n\ndef bugs():\n def der(direction):\n if direction == \"n\":\n pit()\n\n elif direction == \"ne\":\n souls()\n\n elif direction == \"e\":\n start1()\n\n elif direction == \"se\":\n lava()\n\n elif direction == \"s\":\n hands()\n\n elif direction == \"sw\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"w\":\n lava()\n\n elif direction == \"nw\":\n rodent()\n\n else:\n noder()\n\n der(raw_input(\"> \"))\n\n print(\"You enter the room of bugs!\")\n\n print(\"In front of you is a caterpiller. \\nIt proceeds to telepathically tell you that you should squash it\")\n\n print(\"What do you do?\")\n\n print(\"1. Do what he said and squash it \\n2. Follow your instinct, and leave it be\")\n\n choice = raw_input(\"> \")\n\n if choice == \"1\":\n print(\"The caterpiller is very mad at you and then bites your arm! \\nWhat do you do?\")\n\n print(\"1. Run back to the start of the maze to get medical help \\n2. Stab yourself in the heart, but after, ask the caterpiller to revive you\")\n\n choice = raw_input(\"> \")\n\n if choice == \"1\":\n print(\"It may take a while, but that was probably the right choice\")\n\n start1()\n\n elif choice == \"2\":\n print(\"He understands your quest, and he gives you the rest of your life, and lets you do on with the quest\")\n\n print(\"What direction would you like to go in?\")\n\n der(raw_input(\"> \"))\n\n else:\n print(\"That is not a valid answer, restart the room\")\n\n bugs()\n\n elif choice == \"2\":\n print(\"The bug is happy with your kind heart, and justy needs you to swear an oath before letting you move on\")\n\n print(\"The Oath is: \\nI agree never to kill a bug ever again \\nWhat do you do?\")\n\n print(\"1. Agree to take the oath \\n2. Disagree\")\n\n choice = raw_input(\"> \")\n\n if choice == \"1\":\n print(\"The bug says that is unrealistic, and becomes mad at you\")\n\n die(\"Killed by a bug becuase you are not realistic\")\n\n elif choice == \"2\":\n print(\"The bug tells you that your answer is the more realistic one, and lets you pass\")\n\n print(\"What direction would you like to go in?\")\n\n der(raw_input(\"> \"))\n\n else:\n print(\"That is not a valid answer, restart the room\")\n\n bugs()\n\n else:\n print(\"That is not a valid answer, restart the room\")\n\n bugs()\n\ndef rodent():\n def der(direction):\n if direction == \"n\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"ne\":\n sound()\n\n elif direction == \"e\":\n lava()\n\n elif direction == \"se\":\n bugs()\n\n elif direction == \"s\":\n lava()\n\n elif direction == \"sw\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"w\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"nw\":\n nothing()\n\n der(raw_input(\"> \"))\n\n else:\n noder()\n\n der(raw_input(\"> \"))\n\n print(\"Welcome to the room of rodents \\nBefore you stands a giant rat\")\n\n print(\"The rat immediatly attacks you, and manages to lethally bite you, but in your pain, you are not able to run!\")\n\n print(\"The rat then transforms into a man, holding two syringes, one the cure, and the other instant death, but he does not tell you which is which\")\n\n print(\"What would you like to do? \\n1. Randomly grab a syringe and inject yourself \\n2. Attack the man, and hold both syringes to his neck, threatning to inject both if you do not tell him which is which\")\n\n choice = raw_input(\"> \")\n\n if choice == \"1\":\n chance = [0, 1]\n\n result = random.choice(chance)\n\n if result == 0:\n print(\"You are very lucky, you drew the right syringe, and were able to save yourself! \\nYou may move on\")\n\n print(\"What direction would you like to go in?\")\n\n der(raw_input(\"> \"))\n\n elif result == 1:\n print(\"Unfortunatley, you chose the wrong syringe, and you failed to save yourself\")\n\n die(\"You did not choose the right syringe\")\n\n else:\n print(\"For some reason there was an ERROR\")\n\n rodent()\n\n elif choice == \"2\":\n print(\"The man just lets you inject him with both, as they do not effect him. For he has immunity\")\n\n print(\"The man then attacks you, plain and simple\")\n\n die(\"Killed by an alchmeist with immunity, Bravo\")\n\n else:\n print(\"That is not a valid answer, restart the room\")\n\ndef sound():\n def der(direction):\n if direction == \"n\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"ne\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"e\":\n war()\n\n elif direction == \"se\":\n souls()\n\n elif direction == \"s\":\n pit()\n\n elif direction == \"sw\":\n rodent()\n\n elif direction == \"w\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"nw\":\n nothing()\n\n der(raw_input(\"> \"))\n\n else:\n noder()\n\n der(raw_input(\"> \"))\n\n print(\"Welcome to the hall of sound! \\nBeofore you stands a woman known as \\\"The Audiophile\\\" She will judge you based on your answer to one question\")\n\n print(\"She tells you that you have two choices \\n1. Answer the question that she will ask \\n2. Run away in fear of losing all the progress you have made\")\n\n choice = raw_input(\"> \")\n\n if choice == \"1\":\n print(\"Alright then, you are very brave answering this\")\n\n print(\"The question is, which of these two brands is superior? Beats or Sennheiser?\")\n\n print(\"1. Beats \\n2. Sennheiser\")\n\n choice = raw_input(\"> \")\n\n if choice == \"1\":\n print(\"You are evil. You like an overpriced company with terrible sound. I hate you. \")\n\n die(\"Commit suicide due to realizing your stupdity\")\n\n elif choice == \"2\":\n print(\"Very good!!!!!!! I was not expecting this answer, you are clearly informed and wise. \\nChoose a direction\")\n\n der(raw_input(\"> \"))\n\n else:\n print(\"That is not an option, restart the room\")\n\n sound()\n\n elif choice == \"2\":\n print(\"Unlike the previous rooms, I am more harsh, I do not deem you worthy to continue, as to continue, you must be brave\")\n\n die(\"Killed by the sound woman due to lack of bravery\")\n\n else:\n print(\"That is not an option, restart the room\")\n\n sound()\n\ndef war():\n def der(direction):\n if direction == \"n\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"ne\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"e\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"se\":\n cloth()\n\n elif direction == \"s\":\n wall()\n\n der(raw_input(\"> \"))\n\n elif direction == \"sw\":\n lava()\n\n elif direction == \"w\":\n sound()\n\n elif direction == \"nw\":\n nothing()\n\n der(raw_input(\"> \"))\n\n else:\n noder()\n\n der(raw_input(\"> \"))\n\n print(\"Welcome to the Hall of War! \\nIn this place, Ares, the god of war rules, he is all powerfull!\")\n\n print(\"He comes to you and asks, \\\"What is your quest?\\\"\")\n\n print(\"How will you answer? \\n1. To seek the Holy Grail! \\n2. To obtain the ultimate treasure!\")\n\n choice = raw_input(\"> \")\n\n if choice == \"1\":\n print(\"Good job, two more questions ensue.\")\n\n print(\"What is the air-speed velocity of an unladen swallow? \\nHow will you answer?\")\n\n print(\"1. What do you mean? An African or European swallow? \\n2. 35.536 kmh\")\n\n choice = raw_input(\"> \")\n\n if choice == \"1\":\n print(\"Right again! Only one more question. \\n Who was the first person to attempt to cross the bridge of death?\")\n\n print(\"1. King Arthur \\n2. Sir Launcelot of Camelot\")\n\n choice = raw_input(\"> \")\n\n if choice == \"2\":\n print(\"Very good! That is correct. You have passed the test of Ares and may now move on\")\n\n print(\"What direction do you want to go in?\")\n\n der(raw_input(\"> \"))\n\n elif choice == \"1\":\n print(\"Unfortunaley that is incorrect and I, god of war will have to kill you know\")\n\n die(\"Lack of Monty-Python knowledge\")\n\n else:\n print(\"That is not a valid answer, restart the room\")\n\n war()\n\n elif choice == \"2\":\n print(\"I'm very sorry, that is incorrect, I will have to kill you know with my war magic\")\n\n die(\"Lack of Monty-Python knowledge\")\n\n else:\n print(\"That is not a valid answer, restart the room\")\n\n war()\n\n elif choice == \"2\":\n print(\"That may be the truth, but it is not the answer that we were looking for. Restart the room\")\n\n war()\n\n else:\n print(\"That is not a valid answer, restart the room\")\n\n war()\n\ndef numbers():\n def der(direction):\n if direction == \"n\":\n pit()\n\n elif direction == \"ne\":\n lava()\n\n elif direction == \"e\":\n electric()\n\n elif direction == \"se\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"s\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"sw\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"w\":\n lava()\n\n elif direction == \"nw\":\n hands()\n\n else:\n noder()\n\n der(raw_input(\"> \"))\n\n print(\"This is the room of numbers, before you stands a man named Fibonacci he is an all-knowing being\")\n\n print(\"He will know ask you a very very basic math question, it is simple, there are three questions, to get to the next one must pass the current one\")\n\n print(\"What does the Fibonacci Sequence have to do with nature? No searching online!!!\")\n\n print(\"1. Nothing in nature will ever be a number from the sequence \\n2. Everything in nature is from the sequence\")\n\n choice = raw_input(\"> \")\n\n if choice == \"1\":\n print(\"That is incorrect, I'm very sorry to have to do this\")\n\n die(\"You were overun with integers, and they smothered you\")\n\n elif choice == \"2\":\n print(\"Bravo! That is right, on to the next question\")\n\n print(\"What is scientific notation?\")\n\n print(\"1. A way of expressing numbers that are normally too lare to deal with \\n2. A way of adding and subtracting numbers to make single numbers\")\n\n choice = raw_input(\"> \")\n\n if choice == \"1\":\n print(\"Right again! Only one more question, and you can move on!\")\n\n print(\"What is the proper mathematical term for a division bar? No searching online!\")\n\n print(\"1. Virgule \\n2. Vinculum\")\n\n choice = raw_input(\"> \")\n\n if choice == \"1\":\n print(\"I'm sorry that is incorrect, we will kill you now.\")\n\n die(\"Millions of failed test force you into depression, you commit suicide\")\n\n elif choice == \"2\":\n print(\"Congratulations, you passed the test, finish your journey\")\n\n print(\"What direction would you like to go in?\")\n\n der(raw_input(\"> \"))\n\n else:\n print(\"That is not a valid answer, restart the room\")\n\n numbers()\n\n elif choice == \"2\":\n print(\"That is not the correct answer.\")\n\n die(\"Mr. Fibonacci kills you with a nine\")\n\n else:\n print(\"That is not a valid answer, restart the room\")\n\n numbers()\n\n else:\n print(\"Tha is not a valid answer, restart the room\")\n\n numbers()\n\ndef electric():\n def der(direction):\n if direction == \"n\":\n lava()\n\n elif direction == \"ne\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"e\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"se\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"s\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"sw\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"w\":\n numbers()\n\n elif direction == \"nw\":\n pit()\n\n else:\n noder()\n\n der(raw_input(\"> \"))\n\n print(\"Welcome to the room of Electricity it is by far the most remore room on the map, and quite desolate\")\n\n print(\"There are thunderbolts coming from the cieling, you have a 4/7 chance of being hit by one, or you can just jump of the cliff next to you and restart\")\n\n print(\"1. Brave the thunderbolts \\n2. Jump the cliff\")\n\n choice = raw_input(\"> \")\n\n if choice == \"1\":\n chance = [1, 2, 3, 4, 5, 6, 7]\n\n result = random.choice(chance)\n\n if result < 5:\n print(\"You were not able to make it across the field\")\n\n die(\"Struck by lightning\")\n\n elif result > 4:\n print(\"What a lucky person! Good job making it across, you are now able to move on to your next direction\")\n\n der(raw_input(\"> \"))\n\n else:\n print(\"That is not an option, restart the room\")\n\n electric()\n\n elif choice == \"2\":\n print(\"Sometimes, the easy way is the right way after all\")\n\n start1()\n\n else:\n print(\"That is not a valid answer, restart the room\")\n\n electric()\n\ndef reading():\n def der(direction):\n if direction == \"n\":\n tar()\n\n elif direction == \"ne\":\n treasure()\n\n elif direction == \"e\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"se\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"s\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"sw\":\n lava()\n\n elif direction == \"w\":\n pens()\n\n elif direction == \"nw\":\n cloth()\n\n else:\n noder()\n\n der(raw_input(\"> \"))\n\n print(\"Welcome to the room of reading before you stands Frodo Baggins, who has some questions to ask you.\")\n\n print(\"The first question is, where was the man that wrote about me born? No searching online\")\n\n print(\"1. England \\n2. South Africa\")\n\n choice = raw_input(\"> \")\n\n if choice == \"1\":\n print(\"You are incorrect I will now attack you with Sting\")\n\n die(\"Killed by a little man with an elf dagger\")\n\n elif choice == \"2\":\n print(\"Very good! That is correct\")\n\n print(\"The next question is, what do you call it when something is made out to be better than it is in literacy\")\n\n print(\"1. Euphamism \\n2. Hyperbole\")\n\n choice = raw_input(\"> \")\n\n if choice == \"1\":\n print(\"Wonderful job on those questions, you may move on to the door \\nWhat direction would you like to go in?\")\n\n der(raw_input(\"> \"))\n\n elif choice == \"2\":\n print(\"I'm very sorry, that is incorrect\")\n\n die(\"You are possed by Sarumon and forced of the roof of a building\")\n\n else:\n print(\"That is not a valid answer, restart the room\")\n\n reading()\n\n else:\n print(\"That is not a valid answer, restar the rom\")\n\n reading()\n\ndef tar():\n def der(direction):\n if direction == \"n\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"ne\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"e\":\n wall()\n\n der(raw_input(\"> \"))\n\n elif direction == \"se\":\n nothing()\n\n der(raw_input(\"> \"))\n\n elif direction == \"s\":\n reading()\n\n elif direction == \"sw\":\n pens()\n\n elif direction == \"w\":\n cloth()\n\n elif direction == \"nw\":\n nothing()\n\n der(raw_input(\"> \"))\n\n else:\n noder()\n\n der(raw_input(\"> \"))\n\n print(\"Welcome to the hall of tar before you stands a monster that is made up of boiling hot tar\")\n\n print(\"What will you do?\")\n\n print(\"1. As the monster runs at you bolt past it to get to the door \\n2. Call on the Ice god and have him freeze the whole room\")\n\n choice = raw_input(\"> \")\n\n if choice == \"1\":\n print(\"You manage to get past the moster, but right before the door you trip and fall into a puddle of tar\")\n\n die(\"Face melted off by tar\")\n\n elif choice == \"2\":\n print(\"The Ice god sees how close you are, and comes to help you. He freezes the room, but also freezes you with it, what will you do?\")\n\n print(\"1. Call on the Fire godess to help \\n2. Just wait in the ice\")\n\n choice = raw_input(\"> \")\n\n if choice == \"1\":\n print(\"The gods are sick of hearing your voice, so they ignore you\")\n\n die(\"You get frostbite and hypothermia\")\n\n elif choice == \"2\":\n print(\"The Ice god sees your agony, and comes to fix it for you. He melts the ice around you \\nYou go to the door\")\n\n print(\"What direction would you like to go in?\")\n\n der(raw_input(\"> \"))\n\n else:\n print(\"That is not a valid answer, restart the room\")\n\n tar()\n\n else:\n print(\"That is not a valid answer, restart the room\")\n\n tar()\n\ndef treasure():\n print(\"Congratulations! You have reached the clock room. This is the most challenging room of all, and you are the first to ever attempt it\")\n\n print(\"A man looking like a clock comes to you and tells you the first question.\")\n\n print(\"What was the name of the Archduke of Austria-Hungary that was assasinated to start WW1? No internet \")\n\n print(\"This time type in the name, single spaced with caps at the begining of each word.\")\n\n choice = raw_input(\"> \")\n\n if choice == \"Franz Ferdinand\":\n print(\"Amazing! That is the correct answer, I didn't think that you would be able to get it.\")\n\n print(\"The next question is: \\nWhich European country first allowed women to vote?\")\n\n print(\"Type in the name of the country, with a capital letter at the begining and nothing else, no internet\")\n\n choice = raw_input(\"> \")\n\n if choice == \"Finland\":\n print(\"Right again, only two more questions!\")\n\n print(\"Next, \\nWhat band did the man that the Sousaphone is named after conduct, type it with single spaces, and no caps, no internet\")\n\n choice = raw_input(\"> \")\n\n if choice == \"united states marine band\" or \"us marine band\":\n print(\"Only one more question, and then you can move on!\")\n\n print(\"What is the programming language Python named after?\")\n\n print(\"type with capital letters at the begining of each word and single spaced, no internet\")\n\n choice = raw_input(\"> \")\n\n if choice == \"Monty Python\":\n print(\"You have done it, you are the first to complete the room of clocks, and I will now reaveal to you the secret\")\n\n print(\"The secret is that this is actually the treasure room, and you have claimed the prize, The Jewl of Babylon.\")\n\n print(\"%s, your name will go down in history as the name of the person that found the Jewl and passed the tresure room.\" % name)\n\n print(\"Thank you for playing. I hope you enjoy your victory, farewell!\")\n\n exit(0)\n\n else:\n print(\"That is either not the correct answer, or the answer is invalid, restart the game\")\n\n start1()\n\n else:\n print(\"That is either not the correct answer, or the answer is invalid, restart the game\")\n\n start1()\n\n else:\n print(\"That is either not the correct answer, or the answer is invalid, restart the game\")\n\n start1()\n\n elif 8200 < choice < 8300:\n print(\"That is not the correct, but it is very close, so I will not send you to the start, rather back a few rooms.\")\n\n tar()\n\n else:\n print(\"That is either not the correct answer, or the answer is invalid, restart the game\")\n\n start1()\n\ndef die(why):\n print(\"You died becuase %s\" % why)\n\n def leave():\n print(\"Which of the following would you like to do?\")\n\n print(\"1. Exit the game\")\n\n print(\"2. Restart the game\")\n\n choice = raw_input(\"> \")\n\n if choice == \"2\":\n start()\n\n elif choice == \"1\":\n exit(0)\n\n else:\n print(\"That is not a valid answer\")\n\n leave()\n\n leave()\n\ndef lava():\n print(\"You tripped and fell.\")\n\n die(\"You fell into lava!\")\n\ndef wall():\n print(\"You can not pass because there is a wall, go another way.\")\n\n print(\"What direction do you want to go?\")\n\ndef pit():\n print(\"You slip on a napkin and fall\")\n\n die(\"When you fell you landed in a botomless pit, where you starve\")\n\ndef nothing():\n print(\"There is nothing there, please pick another direction\")\n\ndef noder():\n print(\"That is not a direction, try again, remember use lowercase letters without a space, for example, ne\")\n\n print(\"Which way do you want to go?\")\n\nstart()\n","sub_path":"PY/game2.py","file_name":"game2.py","file_ext":"py","file_size_in_byte":34791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"577911759","text":"# Мотивация рассчитывается по следующей формуле:\n# если дерби или тур > 33 и dist <= 3 - 1 для обеих команд\n# иначе если тур > 16\n# если 1 - (dist / 3) / left < 0 или > 1 вернуть 0\n# иначе вернуть 1 - (dist / 3) / left\n\n\nimport useful_functions as uf\nimport re\n\n\nTOURS = 39\nkey_positions = {1, 2, 3, 4, 5, 6, 17, 18}\nderbies = {'Арсенал': {'Тоттенхэм Хотспур', 'Челси'},\n 'Ливерпуль': {'Эвертон'},\n 'Манчестер Юнайтед': {'Манчестер Сити', 'Ливерпуль'},\n 'Сандерленд': {'Ньюкасл Юнайтед'}\n }\n\n\ndef get_key_pos_scores(soup):\n res = set()\n for i, team in enumerate(soup):\n if i - 1 in key_positions:\n res.add(int(team.findAll(text=re.compile('[0-9]+'))[-1]))\n return res\n\n\ndef get_motivation(url, driver):\n \"\"\"Getting motivation for the match\"\"\"\n soup = uf.get_soup(url)\n res = []\n\n #: adding names\n res += uf.get_names(soup)\n teams = res\n\n #: magic with names and derbies\n for i in {0, 1}:\n if res[i] in derbies and res[1 - i] in derbies[res[i]]:\n res = res + [1, 1]\n return res\n\n #: season end or start\n tour = uf.get_tour_number(soup)\n if tour > 33:\n res += [1, 1]\n return res\n if tour < 16:\n res += [0, 0]\n return res\n\n #: moving to statto\n date = uf.get_date(soup)\n statto = uf.get_statto_soup(driver, date)\n statto_all = statto.findAll('form')[1].findAll('tr')\n statto_teams = [uf.championat_statto[x] for x in teams]\n\n #: getting teams scores and key positions points\n info = uf.get_statto_teams_info(statto_teams[0], statto_teams[1], statto)\n team1_score = uf.get_statto_score(info[0])\n team2_score = uf.get_statto_score(info[1])\n key_pos_scores = get_key_pos_scores(statto_all)\n\n #: getting min distance to key position for each team\n dist1 = min(list(filter(lambda x: x, [abs(x - team1_score) for x in key_pos_scores])))\n dist2 = min(list(filter(lambda x: x, [abs(x - team2_score) for x in key_pos_scores])))\n\n #: finally getting res\n left = TOURS - tour\n val = 1 - (dist1 / 3) / left\n if val < 0 or val > 1:\n res.append(0)\n else:\n res.append(val)\n val = 1 - (dist2 / 3) / left\n if val < 0 or val > 1:\n res.append(0)\n else:\n res.append(val)\n return res\n\n\ndef get_all_motivation(path=\"./extracted_motivation_13_14.txt\"):\n \"\"\"Getting all motivation\"\"\"\n with uf.ChromeDriver() as driver, open(path, 'w', encoding='windows-1251') as handle:\n soup = uf.get_soup()\n handle.write(\"name1\\tname2\\tmotivation1\\tmotivation2\\n\")\n matches = soup.findAll(attrs={'class': '_res'})\n for cnt, match in enumerate(matches):\n print(cnt + 1)\n trying = 0\n error = False\n while True:\n try:\n motivation = get_motivation('http://www.championat.com' + match.findAll('a')[0]['href'], driver)\n break\n except Exception as e:\n trying += 1\n print('On try {0} smth went wrong: {1}'.format(trying, e))\n if trying == 5:\n print('I give up; shit happens. Check it out!')\n print(e)\n error = True\n break\n continue\n if error:\n continue\n handle.write('\\t'.join(str(e) for e in motivation) + '\\n')\n if cnt % 5 == 4:\n handle.flush()\n print(\"Extraction completed\")\n handle.flush()","sub_path":"Extraction/season_2013_2014/motivation_extraction.py","file_name":"motivation_extraction.py","file_ext":"py","file_size_in_byte":3813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"98239303","text":"import numpy as np \nfrom keras.preprocessing import image\nfrom keras.applications.vgg16 import preprocess_input\ndef predictnumber(file_path,model):\n #file_path = '/Users/like/python_item/item_python_code/18.jpg'\n img = image.load_img(file_path, target_size=(30, 46))\n x = image.img_to_array(img)\n \n x = np.expand_dims(x, axis=0)\n x = preprocess_input(x)\n \n \n predict_test = model.predict_classes(x)\n #inverted = encoder.inverse_transform([predict_test])\n return predict_test\n #print(inverted[0]","sub_path":"5.机器学习/src/CardNumberRecognition/predictnumber.py","file_name":"predictnumber.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"109112569","text":"'''\nCreated on 24.3.2010\n\n@author: Vasek\n'''\n\n# Copyright (c) 2007, Enthought, Inc.\n# License: BSD Style.# Imports: \nfrom random \\\n import randint, choice\n \nfrom traits.api \\\n import HasStrictTraits, Str, Int, Float, List, Bool, Property, Enum\n \nfrom traitsui.api \\\n import View, Item, TableEditor\n \nfrom traitsui.table_column \\\n import ObjectColumn\n \nfrom traitsui.extras.checkbox_column \\\n import CheckboxColumn\n \n\n# Create a specialized column to set the text color differently based upon\n# whether or not the player is in the lineup:\nclass TabColumn ( ObjectColumn ):\n \n # Override some default settings for the column:\n width = 0.1\n horizontal_alignment = 'center'\n\n# def get_text_color ( self, object ):\n# return [ 'light grey', 'black' ][ object.num ]\n \n \n# The 'players' trait table editor:\ntab_editor = TableEditor( \n sortable=False,\n #configurable=False,\n auto_size=False,\n sort_model=False,\n selection_mode=( 'cells' ),\n columns=[ TabColumn( name='num', label='Num',\n width=0.08, editable=False ),\n TabColumn( name='name', label='Name', width=0.15,\n horizontal_alignment='left' ),\n TabColumn( name='distrib', label='Distribution' , width=0.15, cell_color='wheat' ),\n TabColumn( name='descript', label='Descriptors', width=0.2 ),\n TabColumn( name='mean', label='Mean' ),\n TabColumn( name='std', label='Std' ),\n TabColumn( name='cov', label='COV' ),\n TabColumn( name='skew', label='Skew' ),\n TabColumn( name='kurt', label='Kurtosis' ),\n TabColumn( name='status', label='Status' )\n ] )\n\n# 'Player' class: \nclass RV ( HasStrictTraits ):\n \n # Trait definitions: \n num = Int\n name = Str\n distrib = Enum( 'Normal', 'Uniform', 'Weibull', modified=True )\n descript = Enum( 'Moments', 'Parameters', 'Moments and parameters', modified=True )\n mean = Float\n std = Float\n cov = Float\n skew = Float\n kurt = Float\n status = Str\n #average = Property( Float )\n \n \n def _get_average ( self ):\n \"\"\" Computes the player's batting average from the current statistics.\n \"\"\"\n if self.at_bats == 0:\n return 0.0\n \n return float( self.singles + self.doubles + \n self.triples + self.home_runs ) / self.at_bats\n\n \nclass Team ( HasStrictTraits ):\n \n # Trait definitions:\n RVs = List( RV )\n \n # Trait view definitions:\n traits_view = View( \n Item( 'RVs',\n show_label=False,\n editor=tab_editor\n ),\n title='Random variable',\n width=1,\n height=0.5,\n resizable=True\n )\n\n\ndef random_RV ( name ): \n \"\"\" Generates and returns a random player.\n \"\"\"\n p = RV( num=randint( 0, 10 ),\n name=name,\n distrib=choice( ['Normal', 'Uniform', 'Weibull'] ),\n descript=choice( ['Moments', 'Parameters', 'Moments and parameters'] ),\n mean=randint( 0, 50 ),\n std=randint( 0, 50 ),\n cov=randint( 0, 30 ),\n skew=randint( 0, 20 ),\n kurt=randint( 0, 5 ),\n status='OK' ) \n return p\n \n# Create the demo: \ndemo = view = Team( RVs=[ random_RV( name ) for name in [\n 'Dave', 'Mike', 'Joe', 'Tom', 'Dick', 'Harry', 'Dirk', 'Fields', 'Stretch'\n]] )\n\n# Run the demo (if invoked from the command line):\nif __name__ == '__main__':\n demo.configure_traits()\n","sub_path":"scratch/enthought_tests/my_table.py","file_name":"my_table.py","file_ext":"py","file_size_in_byte":3684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"110700444","text":"### OSINT Commands\n# Anything OSINT related\ntry:\n from core.helper import *\nexcept ImportError:\n from helper import *\nimport re\n\n#-> !cid \nasync def cidSearch(room, event):\n await aiLog(event)\n args = event.body.split()\n initialNum = args[1]\n phonenumber = await getDigits(initialNum)\n\n # This is an easier way of accessing this api which was used in Wish\n #SECRETS = await loadYML('secrets.yml')\n api_key = SECRETS[\"keys\"][\"twilio\"]\n if len(api_key) == 0:\n return \"Please set up a Twilio API key!\"\n url = 'https://'+api_key+'@lookups.twilio.com/v1/PhoneNumbers/{}?Type=carrier'.format(phonenumber)\n\n res = requests.get(url)\n\n data = json.loads(res.text)\n # print(data) # For debug \n try:\n if data['carrier']:\n carrier_name = data['carrier']['name']\n carrier_type = data['carrier']['type']\n caller_name = data['caller_name']\n country_code = data['country_code'] \n phone_number = data['phone_number']\n text = '''\n Results for: {}\\n\n \n Carrier: {}\n Type: {}\n Caller name: {}\n Country Code: {}\n '''.format(phone_number, carrier_name, carrier_type, caller_name, country_code)\n return '
' + text + '
'\n except Exception as aiEx:\n text = 'Something broke :('\n await crashLog(event,aiEx)\n return '
' + text + '
'\n\n#-> !dg \n# later expand to a strip function that detects what kind of link it is\n# uses verify_google function from helper.py\n# TODO write a wrapper, have this return false and then send message based on that?\nasync def degoogle(room, event):\n try:\n await aiLog(event)\n args = event.body.split()\n if len(args) >= 2:\n url = args[1]\n else:\n text = 'usage: !dg to degoogle a link and extract just the target url!'\n return '
' + text + '
'\n if await verify_google(url):\n result = False\n segments = re.split('(&q|url|usg|sa|url\\?q)=', url)\n if segments:\n for i in range(1, len(segments)):\n segment = segments[i]\n if len(segment) >= 12:\n if segment[0:4] == 'http':\n validate_segment = urllib.parse.unquote(segment)\n if (validate_segment[0:7] == 'http://' or validate_segment[0:8] == 'https://'):\n if re.match(r'^https?://[\\w\\-]+\\.[\\w\\-]+', validate_segment):\n result = segment[0:-1] if segment[-1] == '&' else segment\n\n # selective url decoding + re-encoding\n result = re.sub(r'%20', '+', result)\n decoded = urllib.parse.unquote(result)\n decoded = re.sub(r'\\|', '%7C', decoded)\n decoded = re.sub(r'\\\"', '%22', decoded)\n decoded = re.sub(r'\\>', '%3E', decoded)\n decoded = re.sub(r'\\<', '%3C', decoded) \n\n degoogled = decoded\n return '
' + degoogled + '
'\n if not result:\n text = 'failed to extract url!'\n return '
' + text + '
'\n else:\n text = 'not a valid google search result link!'\n return '
' + text + '
'\n except Exception as aiEx:\n text = 'Something broke :('\n await crashLog(event,aiEx)\n return '
' + text + '
'\n\n# !gs \n# search google for your query and return all cleaned results + descriptions\nasync def degoogle_all(room, event):\n try:\n await aiLog(event)\n args = event.body.split()\n if len(args) >= 2:\n query = args[1]\n if len(args) >= 3:\n for i in range(2, len(args)):\n query += \" \" + args[i]\n if query[-1] == \" \":\n query = query[0:-1]\n else:\n text = 'usage: !gs to search google and return sanitized result links!'\n return '
' + text + '
'\n\n url = await make_google_link(query)\n r = requests.get(url)\n #match_result_segment = r'
.*?(?=<[spandiv]{3,4})\"><[spandiv]{3,4} class=\"[A-Za-z\\d ]+\">.*?(?=<[spandiv]{3,4})'\n matches = re.findall(match_result_segment, r.text)\n \n if matches:\n\n valid_matches = []\n \n for match in matches:\n #if match[-6:] == '
':\n if match[-6:] == '
' or match[-7:] == '
':\n valid_matches.append(match)\n\n if valid_matches:\n result_block = [] # append dicts, each w url and desc\n\n for match in valid_matches:\n url = \"\"\n desc = \"\"\n find_url = re.split(')\">|', match)\n for segment in find_desc:\n if segment and segment[0] != \"<\":\n desc = segment\n if url and desc:\n url = re.sub(r'%20', '+', url)\n url = urllib.parse.unquote(url)\n url = re.sub(r'\\|', '%7C', url)\n url = re.sub(r'\\\"', '%22', url)\n url = re.sub(r'\\>', '%3E', url)\n url = re.sub(r'\\<', '%3C', url)\n if url[-1] == '.':\n url = url[0:-1] + '%2E'\n desc = re.sub(r'&', '&', desc)\n # possibly others in the future ^^^\n\n result = {'desc': desc, 'url': url}\n result_block.append(result)\n\n \n if result_block:\n final_string = \"-- search results --\\n\\n\"\n for result in result_block:\n final_string += result['desc'] + '\\n' + result['url'] + '\\n\\n'\n if final_string[-2:] == '\\n\\n':\n final_string = final_string[:-2]\n\n return '
' + final_string + '
'\n \n else:\n text = \"no results\"\n return '
' + text + '
'\n except Exception as aiEx:\n text = 'Something broke :('\n await crashLog(event,aiEx)\n return '
' + text + '
'\n\n\n\n# Get random user data\nasync def fakeID(room, event):\n await aiLog(event)\n url = 'http://randomuser.me/api/'\n res = requests.get(url)\n data = json.loads(res.text)\n #print(data)\n output = \"\"\n \n ### Basic info\n output += \"

\"\n #nameTitle = data['results'][0]['name']['title']\n nameFirst = data['results'][0]['name']['first']\n nameLast = data['results'][0]['name']['last']\n nameFull = nameFirst + \" \" + nameLast\n output += nameFull + \"

\"\n fakeDOB = data['results'][0]['dob']['date']\n fakeAge = data['results'][0]['dob']['age']\n\n ### Location Info \n locStreet = data['results'][0]['location']['street']\n locCity = data['results'][0]['location']['city']\n locState = data['results'][0]['location']['state']\n locPostal = data['results'][0]['location']['postcode']\n locLat = data['results'][0]['location']['coordinates']['latitude']\n locLon = data['results'][0]['location']['coordinates']['longitude']\n locTZ = data['results'][0]['location']['timezone']['offset'] # GMT + \n locDesc = data['results'][0]['location']['timezone']['description'] \n locFullTZ = \"GMT \"+locTZ+\" \"+locDesc\n output += str(locStreet[\"number\"]) + \" \" + locStreet[\"name\"] + \" \" + locCity + \" \" + locState + str(locPostal) +'
'\n output += '
--- Info ---\\n'\n    output += 'Age........: ' + str(fakeAge) + '\\n'\n    output += 'DOB........: ' + fakeDOB + '\\n'\n    output += 'Timezone...: ' + locFullTZ + '\\n'\n    output += 'Geo........: ' + locLat + \",\" + locLon +'\\n'\n    output += '\\n'\n\n    # contact\n    output += '--- Contact ---\\n'\n    conPhone  = data['results'][0]['phone']\n    conCell   = data['results'][0]['cell']\n    conEmail  = data['results'][0]['email']\n    output += 'Phone......: ' + conPhone + '\\n'\n    output += 'Cell.......: ' + conCell  + '\\n'\n    output += 'Email......: ' + conEmail + '\\n'\n    output += '\\n'\n\n    # Userdata\n    output += '--- User Data ---\\n'\n    usrUUID   = data['results'][0]['login']['uuid']\n    usrUSER   = data['results'][0]['login']['username']\n    usrPASS   = data['results'][0]['login']['password']\n    usrSALT   = data['results'][0]['login']['salt']\n    usrMD5    = data['results'][0]['login']['md5']\n    usrSHA1   = data['results'][0]['login']['sha1']\n    usrSHA256 = data['results'][0]['login']['sha256']\n    usrRgDate = data['results'][0]['registered']['date']\n    usrAccAge = data['results'][0]['registered']['age']\n    usrPic    = data['results'][0]['picture']['large']\n    output += 'Username...: ' + usrUSER + '\\n'\n    output += 'Password...: ' + usrPASS + '\\n'\n    output += 'Salt.......: ' + usrSALT + '\\n'\n    output += 'MD5........: ' + usrMD5 + '\\n'\n    output += 'SHA1.......: ' + usrSHA1 + '\\n'\n    output += 'SHA256.....: ' + usrSHA256 + '\\n'\n    output += 'Registered.: ' + usrRgDate + '\\n'\n    output += 'Account Age: ' + str(usrAccAge) + ' years\\n'\n    output += 'Profile Pic: ' + usrPic + '\\n'\n    output += '
'\n return output\n\nasync def vtSearch(room, event):\n #SECRETS = await loadYML('secrets.yml')\n vtApiKey = SECRETS[\"keys\"][\"virus_total\"]\n if len(vtApiKey) == 0:\n return \"Please set up a Virus Total API key!\"\n vtHeaders = {'x-apikey': vtApiKey}\n await aiLog(event)\n try:\n args = event.body.split()\n vtHash = args[1]\n vtOut = \"\"\n url = 'https://www.virustotal.com/api/v3/files/{}'.format(vtHash)\n res = requests.get(url, headers=vtHeaders)\n data = json.loads(res.text)\n vtd = data[\"data\"][\"attributes\"]\n vtID = data[\"data\"][\"id\"]\n vtMagic = vtd[\"magic\"]\n vtMD5 = vtd[\"md5\"]\n vtSHA1 = vtd[\"sha1\"]\n vtSHA256 = vtd[\"sha256\"]\n vtTags = vtd[\"tags\"]\n vtTyped = vtd[\"type_description\"]\n aRes = data[\"data\"][\"attributes\"][\"last_analysis_results\"]\n vtOut += \"--- File Meta ---\\n\"\n vtOut += \" VTID....: {}\\n\".format(vtID)\n vtOut += \" Magic...: {}\\n\".format(vtMagic)\n vtOut += \" MD5.....: {}\\n\".format(vtMD5)\n vtOut += \" SHA1....: {}\\n\".format(vtSHA1)\n vtOut += \" SHA256..: {}\\n\".format(vtSHA256)\n vtOut += \" Type....: {}\\n\".format(vtTyped)\n vtOut += \" Tags....: {}\\n\".format(vtTags)\n if \"exiftool\" in vtd:\n vtExif = vtd[\"exiftool\"]\n vtOut += \"\\n--- Exif Data ---\\n\"\n for eK, eV in vtExif.items():\n vtOut += \" {}: {}\\n\".format(eK,eV)\n vtOut += \"\\n--- Detections ---\\n\"\n for i in aRes:\n eRes = aRes[i][\"result\"]\n eName = aRes[i][\"engine_name\"]\n if eRes != None:\n vtOut += \" {}: {}\\n\".format(eName,eRes)\n else:\n continue\n stats = data[\"data\"][\"attributes\"][\"last_analysis_stats\"]\n vtOut += \"\\n--- Stats ---\\n\"\n for s, v in stats.items():\n vtOut += \" {}: {}\\n\".format(s,v)\n vtOut += \"\\nLINK: {}\".format(data[\"data\"][\"links\"][\"self\"])\n return '
' + vtOut + '
'\n except Exception as aiEx:\n text = 'No Results or API Key Exhausted!'\n await crashLog(event,aiEx)\n return '
' + text + '
'\n","sub_path":"core/osint.py","file_name":"osint.py","file_ext":"py","file_size_in_byte":12531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"185288256","text":"import maya.cmds as mc\nfrom os.path import abspath, dirname, join, splitext\n# Note: mydialog.ui must already exist\nclass ikfkSwitchUI:\n ui = 'IKFKSwitch'\n uiFile = join(abspath(dirname(__file__)),(splitext(__file__)[0]+'.ui'))\n def __init__(self):\n pass\n def build(self):\n if mc.window(self.ui, ex=1):\n mc.deleteUI(self.ui)\n self.ui = mc.loadUI(uiFile=self.uiFile)\n mc.button( 'pickFK', e=1, c=self.FKButton )\n mc.button( 'pickIK', e=1, c=self.IKButton )\n mc.button('switch_2', e=1, c='')\n def FKButton(self, *args):\n fk = mc.ls( sl=True )\n if fk == []:\n mc.error( 'select something' )\n else:\n mc.textField( 'fkText', e=1, text=fk[0] )\n def IKButton(self, *args):\n ik = mc.ls(sl=True)[0]\n mc.textField( 'ikText', e=1, text=ik )\n def show(self):\n mc.showWindow(self.ui)\ndef ikfkSwich():\n ui = ikfkSwitchUI()\n ui.build()\n ui.show()\nif __name__ == '__main__':\n ikfkSwich()","sub_path":"IKFKSwich.py","file_name":"IKFKSwich.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"526267212","text":"import csv\nimport os\n\nimport magic\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n#filename = '/home/jazon/project/epr/data/raw/test_data/testB.csv'\n\n\ndef open_spectre(filename):\n \"\"\"Otwiera plik z danymi potrzebnymi do sporzadzenia wykresu\"\"\"\n\n with open(filename, newline='') as f:\n reader = csv.reader(f, delimiter=\"\\t\")\n spectre = []\n wavelength = []\n value = []\n for row in reader:\n try:\n if ((type(float(row[0])) is float) and (type(float(row[1])) is float)):\n spectre.append(row)\n #wavelength.append(float(row[0]))\n #value.append(float(row[1]))\n except ValueError:\n print(f\"Niepoprawny plik: {filename}\".filename)\n finally:\n continue\n\n spectre.sort(key=lambda x: x[0])\n wavelength = [float(item[0]) for item in spectre]\n value = [float(item[1]) for item in spectre]\n\n return wavelength, value\n\ndef draw_plot(wavelength, value, result, filename):\n\n fig, ax = plt.subplots()\n ax.plot(wavelength, value)\n right = 1\n top = 1\n font = {'family': 'serif',\n 'color': 'darkred',\n 'weight': 'normal',\n 'size': 16,\n }\n amplitude = result['amplitude']\n info = f'Amplitude: {amplitude}.'\n\n ax.text(right, top, info,\n horizontalalignment='right',\n verticalalignment='top',\n transform=ax.transAxes,\n fontdict=font)\n ax.set(xlabel='Wavelength (nm)', ylabel='absorbance ([a.u.])',\n title=filename)\n# ax.grid()\n fig.savefig(filename + '.png')\n plt.show()\n plt.close()\n\n\n#wavelength = [3.1, 3.2, 3.3, 3.4, 3.5]\n#value = [386.0, 346.0, 228.0, 482.0, 399.0]\n# result = {'minimum': 228.0,\n# 'maximum': 482.0,\n# 'amplitude': 254.0\n# }\n#filename = 'test.csv'\n#draw_plot(wavelength, value, result)\n\ndef analyse_dpph(value):\n\n try:\n amplitude = max(value) - min(value)\n return {'minimum': min(value),\n 'maximum': max(value),\n 'amplitude': amplitude}\n except ValueError:\n raise print(\"Lista wartosci jest pusta!\")\n\n\npath = '/home/jazon/project/epr/data/raw'\n\ndef check_location(path):\n docstring_ornament = '###------------------------------------###'\n try:\n os.chdir(path)\n return True\n except IOError:\n print(docstring_ornament)\n print(\"Sprawdz polozenie plikow!\")\n print(docstring_ornament)\n return False\n\ndef istextfile(filename):\n\n \"\"\"Sprawdza czy element folderu jest plikiem tekstowym\"\"\"\n \n if os.path.isfile(filename):\n if magic.from_file(filename, mime=True) == 'text/plain':\n return True\n else:\n return False\n else:\n return False\n\nif check_location(path):\n f= open(\"wyniki.txt\",\"w+\")\n files_list = os.listdir()\n files_list.sort()\n for filename in files_list:\n #print(filename)\n if istextfile(filename):\n data = open_spectre(filename)\n result = analyse_dpph(data[1])\n draw_plot(data[0], data[1], result, filename)\n line = filename + \"\\t\" + str(result['minimum']) + \"\\t\" + str(result['maximum']) + \"\\t\" + str(result['amplitude']) + \"\\n\"\n f.write(line)\n else:\n continue\n f.close()\n","sub_path":"code/m_file.py","file_name":"m_file.py","file_ext":"py","file_size_in_byte":3409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"15620156","text":"from .program import run\n\nimport unittest\nfrom unittest.mock import Mock, patch\n\nclass SmellsPerContributionTest(unittest.TestCase):\n\n def setUp(self):\n self.env = Mock()\n self.env.read_dump.return_value = { \"javaComposition\": 171 }\n self.env.get_derived_resource.return_value = 171\n\n def test_run(self):\n res = {\n 'file': 'contributions/java/some-file.java'\n }\n run(self.env, res)\n\n self.env.write_dump.assert_called_with('smellsPerContribution', { \"javaComposition\": 171 })\n\ndef test():\n suite = unittest.TestLoader().loadTestsFromTestCase(SmellsPerContributionTest)\n unittest.TextTestRunner(verbosity=2).run(suite)\n","sub_path":"modules/smellsPerContribution/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"476922473","text":"from django.conf.urls import url\nfrom . import views\nfrom django.contrib import admin\n\nurlpatterns=[\n url(r'^$',views.article_of_day,name='articleToday'),\n url(r'^archives/(\\d{4}-\\d{2}-\\d{2})/$',views.past_days_article,name = 'pastArticle'),\n url(r'^article/(\\d+)',views.article,name ='article'),\n url(r'admin/', admin.site.urls, name='admin' ),\n url(r'',(views.article_of_day), name='articleOfDay') \n\n \n]\n\n","sub_path":"travelkenya/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"354343789","text":"# pip install pytest\n# pytest tests\\test_bn.py\n\nfrom pgmpy.factors.discrete import TabularCPD\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom pgmpy.estimators import TreeSearch\nfrom pgmpy.models import BayesianModel\nimport networkx as nx\nimport bnlearn as bnlearn\nfrom pgmpy.inference import VariableElimination\nfrom pgmpy.estimators import BDeuScore, K2Score, BicScore\nimport bnlearn as bn\n\ndef test_import_DAG():\n DAG = bn.import_DAG('Sprinkler')\n # TEST 1: check output is unchanged\n assert [*DAG.keys()]==['model','adjmat']\n # TEST 2: Check model output is unchanged\n assert DAG['adjmat'].sum().sum()==4\n # TEST 3:\n assert 'pgmpy.models.BayesianModel.BayesianModel' in str(type(DAG['model']))\n # TEST 4:\n DAG = bn.import_DAG('alarm', verbose=0)\n assert [*DAG.keys()]==['model','adjmat']\n DAG = bn.import_DAG('andes', verbose=0)\n assert [*DAG.keys()]==['model','adjmat']\n DAG = bn.import_DAG('asia', verbose=0)\n assert [*DAG.keys()]==['model','adjmat']\n\n\ndef test_make_DAG():\n edges = [('Cloudy', 'Sprinkler')]\n DAG = bn.make_DAG(edges)\n # TEST 1\n assert 'pgmpy.models.BayesianModel.BayesianModel' in str(type(DAG['model']))\n # TEST 2\n cpt_cloudy = TabularCPD(variable='Cloudy', variable_card=2, values=[[0.3], [0.7]])\n cpt_sprinkler = TabularCPD(variable='Sprinkler', variable_card=2, values=[[0.4, 0.9], [0.6, 0.1]], evidence=['Cloudy'], evidence_card=[2])\n assert bn.make_DAG(DAG, CPD=[cpt_cloudy, cpt_sprinkler], checkmodel=True)\n\n\ndef test_make_DAG():\n # TEST 1:\n df = bn.import_example()\n assert df.shape==(1000,4)\n\n\ndef test_sampling():\n # TEST 1:\n model = bn.import_DAG('Sprinkler')\n n = np.random.randint(10,1000)\n df = bn.sampling(model, n=n)\n assert df.shape==(n, 4)\n\n\ndef test_to_undirected():\n # TEST 1:\n randdata=['sprinkler','alarm','andes','asia','sachs']\n n = np.random.randint(0,len(randdata))\n DAG = bn.import_DAG(randdata[n], CPD=False, verbose=0)\n assert (DAG['adjmat'].sum().sum()*2)==bn.to_undirected(DAG['adjmat']).sum().sum()\n\n\ndef test_compare_networks():\n DAG = bn.import_DAG('Sprinkler', verbose=0)\n G = bn.compare_networks(DAG, DAG, showfig=False)\n assert np.all(G[0]==[[12,0],[0,4]])\n\n\ndef test_adjmat2vec():\n DAG = bn.import_DAG('Sprinkler', verbose=0)\n out = bn.adjmat2vec(DAG['adjmat'])\n assert np.all(out['source']==['Cloudy','Cloudy','Sprinkler','Rain'])\n\n\ndef test_vec2adjmat():\n DAG = bn.import_DAG('Sprinkler', verbose=0)\n out = bn.adjmat2vec(DAG['adjmat'])\n # TEST: conversion\n assert bn.vec2adjmat(out['source'], out['target']).shape==DAG['adjmat'].shape\n\n\ndef test_structure_learning():\n import bnlearn as bn\n df = bn.import_example()\n model = bn.structure_learning.fit(df)\n assert [*model.keys()]==['model', 'model_edges', 'adjmat', 'config']\n model = bn.structure_learning.fit(df, methodtype='hc', scoretype='bic')\n assert [*model.keys()]==['model', 'model_edges', 'adjmat', 'config']\n model = bn.structure_learning.fit(df, methodtype='hc', scoretype='k2')\n assert [*model.keys()]==['model', 'model_edges', 'adjmat', 'config']\n model = bn.structure_learning.fit(df, methodtype='cs', scoretype='bdeu')\n assert [*model.keys()]==['undirected', 'undirected_edges', 'pdag', 'pdag_edges', 'dag', 'dag_edges', 'model', 'model_edges', 'adjmat', 'config']\n model = bn.structure_learning.fit(df, methodtype='cs', scoretype='k2')\n assert [*model.keys()]==['undirected', 'undirected_edges', 'pdag', 'pdag_edges', 'dag', 'dag_edges', 'model', 'model_edges', 'adjmat', 'config']\n model = bn.structure_learning.fit(df, methodtype='ex', scoretype='bdeu')\n assert [*model.keys()]==['model', 'model_edges', 'adjmat', 'config']\n model = bn.structure_learning.fit(df, methodtype='ex', scoretype='k2')\n assert [*model.keys()]==['model', 'model_edges', 'adjmat', 'config']\n model = bn.structure_learning.fit(df, methodtype='cl', root_node='Cloudy')\n assert [*model.keys()]==['model', 'model_edges', 'adjmat', 'config']\n model = bn.structure_learning.fit(df, methodtype='tan', root_node='Cloudy', class_node='Rain')\n assert [*model.keys()]==['model', 'model_edges', 'adjmat', 'config']\n\n # Test the filtering\n DAG = bn.import_DAG('asia')\n # Sampling\n df = bn.sampling(DAG, n=1000)\n # Structure learning of sampled dataset\n model = bn.structure_learning.fit(df)\n assert np.all(np.isin(model['adjmat'].columns.values, ['smoke', 'bronc', 'lung', 'asia', 'tub', 'either', 'dysp', 'xray']))\n\n # hc filter on edges\n model = bn.structure_learning.fit(df, methodtype='hc', white_list=['smoke', 'either'], bw_list_method='nodes')\n assert np.all(model['adjmat'].columns.values==['smoke', 'either'])\n model = bn.structure_learning.fit(df, methodtype='hc', white_list=[('smoke', 'either')], bw_list_method='edges')\n assert np.all(np.isin(model['adjmat'].columns.values, ['smoke', 'bronc', 'lung', 'asia', 'tub', 'either', 'dysp', 'xray']))\n model = bn.structure_learning.fit(df, methodtype='hc', black_list=['smoke', 'either'], bw_list_method='nodes')\n assert np.all(np.isin(model['adjmat'].columns.values, ['bronc', 'lung', 'asia', 'tub', 'dysp', 'xray']))\n model = bn.structure_learning.fit(df, methodtype='hc', scoretype='bic', black_list=['smoke', 'either'], bw_list_method='edges')\n assert np.all(np.isin(model['adjmat'].columns.values, ['smoke', 'bronc', 'lung', 'asia', 'tub', 'either', 'dysp', 'xray']))\n # hc filter on node\n model = bn.structure_learning.fit(df, methodtype='ex', white_list=['smoke', 'either'], bw_list_method='nodes')\n assert np.all(model['adjmat'].columns.values==['either', 'smoke'])\n model = bn.structure_learning.fit(df, methodtype='ex', black_list=['asia', 'tub', 'either', 'dysp', 'xray'], bw_list_method='nodes')\n assert np.all(model['adjmat'].columns.values==['bronc', 'lung', 'smoke'])\n # cs filter\n model = bn.structure_learning.fit(df, methodtype='cs', white_list=['smoke', 'either'], bw_list_method='nodes')\n assert np.all(np.isin(model['adjmat'].columns.values, ['smoke', 'either']))\n model= bn.structure_learning.fit(df, methodtype='cs', black_list=['asia', 'tub', 'either', 'dysp', 'xray'], bw_list_method='nodes')\n assert np.all(np.isin(model['adjmat'].columns.values, ['smoke', 'lung', 'bronc']))\n # cl filter\n model = bn.structure_learning.fit(df, methodtype='cl', white_list=['smoke', 'either'], bw_list_method='nodes', root_node='smoke')\n assert np.all(model['adjmat'].columns.values==['smoke', 'either'])\n # tan\n model = bn.structure_learning.fit(df, methodtype='tan', white_list=['smoke', 'either'], bw_list_method='nodes', root_node='smoke', class_node='either')\n assert np.all(model['adjmat'].columns.values==['smoke', 'either'])\n\n \n df=bnlearn.import_example(data='andes')\n \n # PGMPY\n est = TreeSearch(df)\n dag = est.estimate(estimator_type=\"tan\",class_node='DISPLACEM0')\n bnq = BayesianModel(dag.edges())\n bnq.fit(df, estimator=None) # None means maximum likelihood estimator\n bn_infer = VariableElimination(bnq)\n q = bn_infer.query(variables=['DISPLACEM0'], evidence={'RApp1':1})\n print(q)\n \n # BNLEARN\n model = bnlearn.structure_learning.fit(df, methodtype='tan', class_node='DISPLACEM0', scoretype='bic')\n model_bn = bnlearn.parameter_learning.fit(model, df, methodtype='ml') # maximum likelihood estimator\n query=bnlearn.inference.fit(model_bn, variables=['DISPLACEM0'], evidence={'RApp1':1})\n \n # DAG COMPARISON\n assert np.all(model_bn['adjmat']==model['adjmat'])\n assert dag.edges()==model['model'].edges()\n assert dag.edges()==model['model_edges']\n \n # COMPARE THE CPDs names\n qbn_cpd = []\n bn_cpd = []\n for cpd in bnq.get_cpds(): qbn_cpd.append(cpd.variable)\n for cpd in model_bn['model'].get_cpds(): bn_cpd.append(cpd.variable)\n \n assert len(bn_cpd)==len(qbn_cpd)\n assert np.all(np.isin(bn_cpd, qbn_cpd))\n \n # COMPARE THE CPD VALUES\n nr_diff = 0\n for cpd_bnlearn in model_bn['model'].get_cpds():\n for cpd_pgmpy in bnq.get_cpds():\n if cpd_bnlearn.variable==cpd_pgmpy.variable:\n assert np.all(cpd_bnlearn.values==cpd_pgmpy.values)\n # if not np.all(cpd_bnlearn.values==cpd_pgmpy.values):\n # print('%s-%s'%(cpd_bnlearn.variable, cpd_pgmpy.variable))\n # print(cpd_bnlearn)\n # print(cpd_pgmpy)\n # nr_diff=nr_diff+1\n # input('press enter to see the next difference in CPD.')\n\n\ndef test_parameter_learning():\n df = bn.import_example()\n model = bn.import_DAG('sprinkler', CPD=False)\n model_update = bn.parameter_learning.fit(model, df)\n assert [*model_update.keys()]==['model', 'adjmat', 'config']\n\n\ndef test_inference():\n DAG = bn.import_DAG('sprinkler')\n q1 = bn.inference.fit(DAG, variables=['Wet_Grass'], evidence={'Rain':1, 'Sprinkler':0, 'Cloudy':1}, to_df=False, verbose=0)\n assert 'pgmpy.factors.discrete.DiscreteFactor.DiscreteFactor' in str(type(q1))\n assert q1.df is None\n q1 = bn.inference.fit(DAG, variables=['Wet_Grass'], evidence={'Rain':1, 'Sprinkler':0, 'Cloudy':1}, to_df=True, verbose=0)\n assert q1.df is not None\n\ndef test_query2df():\n DAG = bn.import_DAG('sprinkler')\n query = bn.inference.fit(DAG, variables=['Wet_Grass'], evidence={'Rain':1, 'Sprinkler':0, 'Cloudy':1}, to_df=False, verbose=0)\n df = bn.query2df(query)\n assert df.shape==(2,2)\n assert np.all(df.columns==['Wet_Grass', 'p'])\n query = bn.inference.fit(DAG, variables=['Wet_Grass', 'Sprinkler'], evidence={'Rain':1, 'Cloudy':1}, to_df=False, verbose=0)\n df = bn.query2df(query)\n assert np.all(np.isin(df.columns, ['Sprinkler', 'Wet_Grass', 'p']))\n assert df.shape==(4,3)\n\ndef test_predict():\n df = bn.import_example('asia')\n edges = [('smoke', 'lung'),\n ('smoke', 'bronc'),\n ('lung', 'xray'),\n ('bronc', 'xray')]\n \n # Make the actual Bayesian DAG\n DAG = bn.make_DAG(edges, verbose=0)\n model = bn.parameter_learning.fit(DAG, df, verbose=3)\n # Generate some data based on DAG\n Xtest = bn.sampling(model, n=100)\n out = bn.predict(model, Xtest, variables=['bronc','xray'])\n assert np.all(np.isin(out.columns, ['bronc', 'xray', 'p']))\n assert out.shape==(100,3)\n out = bn.predict(model, Xtest, variables=['smoke','bronc','lung','xray'])\n assert np.all(np.isin(out.columns, ['xray', 'bronc', 'lung', 'smoke', 'p']))\n assert out.shape==(100,5)\n out = bn.predict(model, Xtest, variables='smoke')\n assert np.all(out.columns==['smoke', 'p'])\n assert out.shape==(100,2)\n\ndef test_topological_sort():\n DAG = bn.import_DAG('sprinkler')\n # Check DAG input\n assert bn.topological_sort(DAG, 'Rain')==['Rain', 'Wet_Grass']\n assert bn.topological_sort(DAG)==['Cloudy', 'Sprinkler', 'Rain', 'Wet_Grass']\n # Different inputs\n assert bn.topological_sort(DAG['adjmat'], 'Rain')==['Rain', 'Wet_Grass']\n assert bn.topological_sort(bn.adjmat2vec(DAG['adjmat']), 'Rain')==['Rain', 'Sprinkler']\n # Check model output\n df = bn.import_example('sprinkler')\n model = bn.structure_learning.fit(df, methodtype='chow-liu', root_node='Wet_Grass')\n assert bn.topological_sort(model, 'Rain')==['Rain', 'Cloudy', 'Sprinkler']\n \ndef test_save():\n # Load asia DAG\n df = bn.import_example('asia')\n model = bn.structure_learning.fit(df, methodtype='tan', class_node='lung')\n bn.save(model, overwrite=True)\n # Load the DAG\n model_load = bn.load()\n assert model.keys()==model_load.keys()\n for key in model.keys():\n if not key=='model':\n assert np.all(model[key]==model_load[key])\n\n edges = [('smoke', 'lung'),\n ('smoke', 'bronc'),\n ('lung', 'xray'),\n ('bronc', 'xray')]\n \n # Make the actual Bayesian DAG\n DAG = bn.make_DAG(edges, verbose=0)\n # Save the DAG\n bn.save(DAG, overwrite=True)\n # Load the DAG\n DAGload = bn.load()\n # Compare\n assert DAG.keys()==DAGload.keys()\n for key in DAG.keys():\n if not key=='model':\n assert np.all(DAG[key]==DAGload[key])\n\n # Learn its parameters from data and perform the inference.\n model = bn.parameter_learning.fit(DAG, df, verbose=0)\n # Save the DAG\n bn.save(model, overwrite=True)\n # Load the DAG\n model_load = bn.load()\n # Compare\n assert model.keys()==model_load.keys()\n for key in model.keys():\n if not key=='model':\n assert np.all(model[key]==model_load[key])\n\n","sub_path":"tests/test_bnlearn.py","file_name":"test_bnlearn.py","file_ext":"py","file_size_in_byte":12628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"512179122","text":"# Calculate the blocking probability of each cell.\r\n# Assume the cellular system has uniform traffic load in each cell\r\nimport numpy as np\r\ndef erlangB_recursion(A,N):\r\n InvB = 1.0\r\n for j in range(1,N):\r\n Pb = A*InvB/(j+ A*InvB)\r\n InvB=Pb\r\n return Pb\r\n\r\ndef efpa_uniform(lamda,u,theta,dwell):\r\n N=int(input(\"please input N:\"))\r\n for i in range(8):\r\n A=theta/(u+dwell)\r\n Pb=erlangB_recursion(A,N)\r\n Ph=dwell/(dwell+u)\r\n theta=lamda+(1-Pb)*theta*Ph\r\n print(\"theta\",theta)\r\n print('A:', A)\r\n print('Pb:',Pb)\r\n\r\n\r\n\r\n\r\nefpa_uniform(45,1/3,60,1/2)","sub_path":"EFPA.py","file_name":"EFPA.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"205016426","text":"#Downloads teacher data for each year and subject for both the district and the state\n\n#url = 'http://profiles.doe.mass.edu/state_report/enrollmentbyracegender.aspx?mode=district&year=2015&Continue.x=6&Continue.y=6&export_excel=yes'\n\n#file_loc = '/Users/taranraghuram/Documents/Project Euler/MA/Enrollment' + '/' + str(2015) + '.xls'\n\nimport urllib.request\n\nyears = range(1994,2016)\n\ndomains = ['school', 'district']\n\nfor year in years:\n \n for domain in domains:\n \n url = 'http://profiles.doe.mass.edu/state_report/enrollmentbyracegender.aspx?mode=' + domain + '&year=' + str(year) + '&Continue.x=6&Continue.y=6&export_excel=yes'\n \n file_loc = '/Users/taranraghuram/Documents/Project Euler/MA/Enrollment by Race' + '/' + str(year) + '_' + domain + '.xls'\n \n urllib.request.urlretrieve(url,file_loc)\n\n #print(year, domain)\n\n","sub_path":"Python Stuff/Project Euler/MA/Enrollment by Race/Enrollment by Race.py","file_name":"Enrollment by Race.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"237580303","text":"# def honai(n,s,i,e):\n# if n==0:\n# return 1\n# honai(n-1,s,i,e)\n# move(s,i)\n# honai(n-1,s,i)\n# honai(4,\"a\",\"b\",\"c\")\n\n\n# while True:\n# n=int(input())\n# if n==42 :\n# break\n# else :\n# print(n)\n\n\nn=int(input())\nfor i in range(n):\n c=input()\n print(int(c[::-1]))","sub_path":"super.py","file_name":"super.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"486098670","text":"import cv2\nimport numpy as np\n\nclass Segment:\n def __init__(self, segments=5):\n self.segments = segments\n \n def kmeans(self, image, iteration=10, epsilon=0.2):\n # reduce noise\n image = cv2.GaussianBlur(image, (7, 7), 0)\n vectorized = image.reshape(-1, 3)\n vectorized = np.float32(vectorized)\n criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, iteration, epsilon)\n ret, label, center = cv2.kmeans(vectorized, self.segments, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)\n res = center[label.flatten()]\n segmented_image = res.reshape((image.shape))\n return label.reshape((image.shape[0], image.shape[1])), segmented_image.astype('uint8')\n \n def extract_clean_component(self, image, label_image, label, flip=False):\n if(flip):\n label_image = (label_image - 1) * -1\n contours, _ = cv2.findContours(label_image.astype('uint8'), 1, 2)\n areas = [cv2.contourArea(c) for c in contours]\n idx = np.argmax(areas)\n mask = np.zeros(image.shape, np.uint8)\n cv2.drawContours(mask, contours, idx, (255, 255, 255), -1)\n out = np.zeros(image.shape, np.uint8)\n mask = cv2.cvtColor(mask, cv2.COLOR_RGB2GRAY)\n out[mask != 0] = image[mask != 0]\n return out\n \n def extract_component(self, image, label_image, label):\n component = np.zeros(image.shape, np.uint8)\n component[label_image==label] = image[label_image==label]\n return component\n \n def extract_object(self, image, label_image):\n if(label_image[0, 0] == 0):\n return self.extract_clean_component(image, label_image, 1)\n else:\n return self.extract_clean_component(image, label_image, 1, True)","sub_path":"segmentation.py","file_name":"segmentation.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"355837862","text":"# Created by PyCharm Professional.\n# User: romandemyanchuk\n# Date: 07.11.2020\n# Time: 22:27\n# To change this template use File | Settings | File and Code Templates.\n\n\"\"\"\nModule for searching and processing connections\nbetween service_id_sender and id_service_recipient\n\nWe search for the service from which the user makes \"Share\":\nprocessing_service [Apple Music or Spotify]\n\nWe define the service to which \"Share\" occurs and we look for existing IDs in the table \"tracks_ids\",\ndepending on the search result in the database and the definition of the service from which \"Share is sent\"\nand the service to which \"Share is received\", the logic is executed\n\"\"\"\n\nimport typing\nimport logging\n\nfrom aiopg.sa import SAConnection\n\nfrom src.api.root.settings import SPOTIFY, APPLE_MUSIC\nfrom src.api.v1.core.engine.queries.conversion import (\n SelectTracksIds,\n InsertTracksIds,\n)\n\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.WARNING)\n\n\nclass MatchingTracksIDs:\n def __init__(\n self,\n processing_service: str,\n track_id: str,\n conn: SAConnection,\n to_users_id: int,\n ):\n self.conn = conn\n self.track_id = track_id\n self.to_users_id = to_users_id\n self.processing_service = processing_service\n\n self.tracks_ids_select = SelectTracksIds(conn=conn)\n self.tracks_ids_insert = InsertTracksIds(conn=conn)\n\n async def __check_track_id(self, name_service_to_search: str) -> typing.Any or None:\n \"\"\"\n method for search conversions id's in \"tracks_ids\" table\n name_service_to_search: string [Apple Music or Spotify]\n\n return track_id from table or None\n \"\"\"\n if name_service_to_search == SPOTIFY:\n data = await self.tracks_ids_select.conversion_ids_by_spotify(\n spotify_id=self.track_id\n )\n elif name_service_to_search == APPLE_MUSIC:\n data = await self.tracks_ids_select.conversion_ids_by_apple_music(\n apple_music_id=self.track_id\n )\n return data.id if data else None\n\n async def __insert_track_id(self, desired_track_id: str, desired_data: dict) -> int:\n \"\"\"\n We write one track_id to the table to its corresponding service_name\n \"\"\"\n service_name = self.processing_service\n instance = await self.tracks_ids_insert.insert_apple_music_and_spotify_ids(\n apple_music_id=self.track_id\n if service_name == APPLE_MUSIC\n else desired_track_id, # noqa\n spotify_id=self.track_id if service_name == SPOTIFY else desired_track_id,\n desired_track_data=desired_data,\n )\n return instance.id\n\n async def processing(self) -> int:\n service_name = self.processing_service\n db_track_id = await self.__check_track_id(name_service_to_search=service_name)\n return db_track_id\n\n async def append_tracks_processing(\n self, desired_track_id: str, desired_data: dict\n ) -> int:\n db_track_id = await self.__insert_track_id(\n desired_track_id=desired_track_id, desired_data=desired_data\n )\n return db_track_id\n\n async def get_track(self, track_id) -> typing.Any or None:\n data = await self.tracks_ids_select.conversion_ids_by_id(\n id=track_id\n )\n return data if data else None\n","sub_path":"src/api/v1/core/logic/matching/matching.py","file_name":"matching.py","file_ext":"py","file_size_in_byte":3386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"445988779","text":"import mysql.connector\r\nfrom datetime import datetime\r\n#database creation\r\nmydb = mysql.connector.connect(host =\"localhost\", user = \"root\", password = \"lucknow\")\r\nmycursor = mydb.cursor()\r\nmycursor.execute('create database if not exists Covid_Management')\r\nmycursor.execute('use Covid_Management')\r\nmycursor.execute('create table if not exists staff(sno varchar(25) not null, name varchar(25) not null,\\\r\n age varchar(25) not null,gender char(1) not null, post varchar(25) not null,salary varchar(25) not null)')\r\nmycursor.execute('create table if not exists patients(sno varchar(25) not null, name varchar(25) not null,\\\r\n age varchar(25) not null,gender char(1) not null, date date not null)')\r\nmycursor.execute('create table if not exists login(admin varchar(25) not null, password varchar(25) not null)')\r\nmycursor.execute('create table if not exists sno(patient varchar(25) not null, staff varchar(25) not null)')\r\nmycursor.execute('select* from sno')\r\nz = 0\r\nfor i in mycursor:\r\n z = 1\r\nif z == 0:\r\n mycursor.execute('insert into sno values(\"0\",\"0\")')\r\nmydb.commit()\r\nj = 0\r\nmycursor.execute(\"select * from login\")\r\nfor i in mycursor:\r\n j = 1\r\nif j==0:\r\n mycursor.execute(\"insert into login values('Admin', 'ng' )\")\r\n mydb.commit()\r\nloop1 = \"y\"\r\nwhile (loop1 == \"y\"):\r\n print(\"______________________________\")\r\n print(\"1. Admin\")\r\n print(\"2. Patient\")\r\n print(\"3. Exit\")\r\n print(\"______________________________\")\r\n ch1 = int(input(\"Enter choice:\"))\r\n if ch1 == 1:\r\n password_ = '12345678'\r\n pas = input('Enter password(12345678) :')\r\n mycursor.execute(\"select * from login\")\r\n for i in mycursor:\r\n username,password = i\r\n if (pas == password_):\r\n loop2 = \"n\"\r\n while (loop2 == \"n\" ):\r\n print(\"______________________________\")\r\n print(\"1. Add Patient\")\r\n print(\"2. Add Staff\")\r\n print(\"3. Display Patient's Records\")\r\n print(\"4. Display Staff Records\")\r\n print(\"5. View time\")\r\n print(\"6. Remove Patient\")\r\n print(\"7. Remove Staff\")\r\n print(\"8. Logout\")\r\n print(\"______________________________\")\r\n ch2 = int(input(\"Enter Choice: \"))\r\n if ch2==1:\r\n loop3 = \"y\"\r\n while loop3 == \"y\" :\r\n name = input('Enter patients name: ')\r\n age = input(\"Enter age: \")\r\n gender=input('Enter gender(m/f/o): ')\r\n date = (input(\"Enter Date of testing positive (yyyy-mm-dd): \"))\r\n mycursor.execute('select * from sno')\r\n for i in mycursor:\r\n patient,staff = i\r\n patient = int(patient)+1\r\n mycursor.execute(\"insert into patients values('\"+str(patient)+\"','\"+name+\"','\"+age+\"','\"+gender+\"','\"+date+\"')\")\r\n mycursor.execute(\"update sno set patient = '\"+str(patient)+\"'\")\r\n mydb.commit() \r\n print(\"data of Patient has been saved successfully\")\r\n mycursor.execute(\"select* from patients\")\r\n t = 0\r\n for i in mycursor:\r\n t+=1\r\n t_id1,name1,age1,gender1,date1 = i\r\n print(f\"Active Corona infected patients : {patient}\")\r\n print(f\"Active Corona Cases: {t}\")\r\n print(f\"This patient with id{t_id1} will be in Quarantine for 14 days From {date1}\")\r\n loop3 = input(\"Do you want to add data of more patients(y/n): \").lower\r\n loop2 = input(\"Do you want to logout?(y/n): \")\r\n elif ch2==2:\r\n loop3 = \"y\"\r\n while loop3 == \"y\" :\r\n name = input(\"Enter Name of New Staff Memeber: \")\r\n age = input('age: ')\r\n gender=input('Enter gender(m/f/o): ')\r\n post = input(\"Enter post: \")\r\n salary =(input(\"Enter Salary: \"))\r\n mycursor.execute('select * from sno')\r\n for i in mycursor:\r\n patient,staff = i\r\n staff = int(staff)+1\r\n mycursor.execute(\"insert into patients values('\"+str(patient)+\"','\"+name+\"','\"+age+\"','\"+gender+\"','\"+date+\"')\")\r\n mycursor.execute(\"update sno set staff='\"+str(staff)+\"'\")\r\n mydb.commit()\r\n print(f\"staff with id {staff} has been saved successfully\")\r\n mycursor.execute(\"Select * from staff\")\r\n t = 0\r\n for i in mycursor:\r\n t+=1\r\n print(f\"Active Staff Members: {t}\")\r\n loop3 = input(\"Do you wnat to enter More Staff People?(y/n): \")\r\n loop2 = input(\"Do you want to logout?(y/n): \")\r\n elif ch2==3:\r\n idd = input(\"Enter patient's ID: \")\r\n t_id2,name2,age2,gender2,date2 = [\"\",\"\",\"\",\"\",\"\",]\r\n mycursor.execute(\"select * from patients where sno = '\"+idd+\"' \")\r\n for i in mycursor:\r\n t_id2,name2,age2,gender2,date2 = i\r\n print(\"|ID|NAME|AGE|GENDER|CORONA DETECTED DATE|\")\r\n print(f\"|{t_id2}|{name2}|{age2}|{gender2}|{date2}|\")\r\n elif ch2 == 4:\r\n idd = input(\"Enter Staff Member's ID: \")\r\n t_id3,name3,age3,gender3,post3,salary3 = [\"\",\"\",\"\",\"\",\"\",\"\"]\r\n mycursor.execute(\"select * from staff where sn0 = '\"+idd+\"' \")\r\n for i in mycursor:\r\n t_id3,name3,age3,gender3,post3,salary3 = i\r\n print(\"|ID|NAME|AGE|GENDER|POST|SALARY|\")\r\n print(f\"|{t_id3}|{name3}|{age3}|{gender3}|{salary3}|\")\r\n elif ch2 == 5:\r\n now = datetime.now()\r\n \r\n print(\"now =\", now)\r\n elif ch2==6:\r\n loop3 = \"y\"\r\n while loop3 == \"y\" :\r\n idd = input(\"Enter patient ID: \")\r\n mycursor.execute(\"delete from patients where sno = '\"+idd+\"'\")\r\n mydb.commit()\r\n print(\"Patient removed successfully\")\r\n loop3 = input(\"Do you want to Remove more Patients?(y/n): \")\r\n elif ch2==7:\r\n loop3 = \"y\"\r\n while loop3 == \"y\" :\r\n idd = input(\"Enter staff ID: \")\r\n mycursor.execute(\"delete from staff where sno = '\"+idd+\"'\")\r\n mydb.commit()\r\n print(\"Staff removed successfully\")\r\n loop3 = input(\"Do you want to Remove more Staff?(y/n): \")\r\n elif ch2 ==8:\r\n break\r\n elif ch1==2:\r\n print(\"Welcome to this short test for Covid-19\")\r\n icough = input(\"Have you been coughing frequently?(y/n): \").lower()\r\n dry_cough = \"n\"\r\n if icough == \"y\" :\r\n dry_cough = input(\"Is it dry cough?(y/n): \").lower()\r\n sneeze = input(\"Have you been sneezing frequently?(y/n): \").lower()\r\n pain = input(\"Have you been experiencing body pain?(y/n): \").lower()\r\n weakness = input(\"Have you been experiencing weakness?(y/n): \").lower()\r\n mucus = input(\"Have you been experiencing mucus while coughing and/or otherwise?(y/n): \").lower()\r\n itemp = int(input(\"Enter your current body temprature in farahneit: \"))\r\n if itemp<100 :\r\n temp = \"Low\"\r\n else:\r\n temp = \"High\"\r\n breathe = input(\"Have you been experiencing difficulty while breathing?(y/n): \").lower()\r\n if 'n' in {dry_cough,sneeze ,pain, weakness,breathe} and temp =='Low':\r\n print(\"You are not covid Positive, just rest, do consult a doctor if problem persists\")\r\n elif 'y' in {dry_cough,sneeze ,pain, weakness,breathe} and temp == \"High\":\r\n print(\"Sorry to say, but according to the test results you maybe SUFFERING FROM CORONAVIRUS/COVID-19\")\r\n name = input(\"Enter name: \")\r\n age = input(\"Enter age: \")\r\n gender = input(\"Enter gender(m/f/o): \")\r\n mycursor.execute(\"select * from sno\")\r\n for i in mycursor:\r\n patient,staff = i\r\n patient = int(patient)+1\r\n mycursor.execute(\"insert into patients values('\"+str(patient)+\"','\"+name+\"','\"+age+\"','\"+gender+\"',now())\")\r\n mycursor.execute(\"update sno set patient = '\"+str(patient)+\"'\")\r\n mydb.commit()\r\n print(\"data of patient has been saved\")\r\n print(f\"Total number of CORONA INFECTED PATIENTS: {patient}\")\r\n mycursor.execute(\"select * from patients\")\r\n t = 0\r\n for i in mycursor:\r\n t+=1\r\n print(f\"Active CORONA CASES: {t}\")\r\n mycursor.execute(\"select * from patients\")\r\n for i in mycursor:\r\n t_id5,name5,age5,gender5,date5 = i\r\n print(f\"This patient with ID {t_id5} will be in Quarantine for 14 days from {date5}\")\r\n else:\r\n print(\"Dont worry.. Its probably just a cold\")\r\n elif ch1 == 3:\r\n break","sub_path":"main_project.py","file_name":"main_project.py","file_ext":"py","file_size_in_byte":9719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"444554514","text":"# pip install WordCloud\r\nfrom models import StockDb\r\nimport json\r\nfrom wordcloud import WordCloud\r\n\r\n\r\nstart_date = input('please input start date(yyyy-mm-dd): ')\r\nend_date = input('please input end date(yyyy-mm-dd): ')\r\n\r\ndb_path = 'week4/invest.db3'\r\n\r\ndb = StockDb()\r\ndb.openDB(db_path)\r\n\r\nkeyword_count = {}\r\n\r\narticles = db.searchArticle(start_date, end_date)\r\nfor article in articles:\r\n# print(article)\r\n keywords = json.loads(article.keywords)\r\n for keyword in keywords:\r\n if keyword in keyword_count:\r\n keyword_count[keyword] += keywords[keyword]\r\n else:\r\n keyword_count[keyword] = keywords[keyword]\r\n\r\nprint(keyword_count)\r\n\r\ndb.closeDB()\r\n\r\n# consola.ttf 不行,因為字體不支援中文編碼\r\nwc = WordCloud(font_path='./msjh.ttf').generate_from_frequencies(keyword_count)\r\nwc.to_file('./week4/stock.png')\r\n\r\n# 特殊使用方式\r\n# https://amueller.github.io/word_cloud/auto_examples/parrot.html","sub_path":"week4/lab06_read_db_wordcloud.py","file_name":"lab06_read_db_wordcloud.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"598784850","text":"#!/usr/bin/python2\n\nfrom bookcrawl.spiders.bookspider import BookSpider\nfrom bookcrawl.spiders.amazonspider import AmazonSpider\nfrom bookcrawl.assigner import BookAssigner\nfrom scrapy.crawler import Crawler\nfrom scrapy import log, signals\nfrom twisted.internet import reactor\nfrom scrapy.utils.project import get_project_settings\n\ndef google_assignments_at(assignment_location):\n assigner = BookAssigner(assignment_location)\n assignments = assigner.assignment_iterator()\n for task in assignments:\n spider = BookSpider(target_info_array=task)\n settings = get_project_settings()\n settings.overrides['FEED_FORMAT'] = 'json'\n settings.overrides['FEED_URI'] = 'google_result.json' \n crawler = Crawler(settings)\n crawler.signals.connect(reactor.stop, signal=signals.spider_closed)\n crawler.configure()\n crawler.crawl(spider)\n crawler.start()\n log.start()\n reactor.run()\n\ndef main():\n google_assignments_at(\"assignments.txt\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"bookcrawl/test_googler.py","file_name":"test_googler.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"589774752","text":"import requests\nheaders ={\n \"Authorization\": \"Token 8e233860bb6a1d3c9753dc131b534a3f1fc8e20d\"\n}\na = requests.get('http://opsdb.test-istio.gome.inc/v1/server', headers=headers)\ntmp = a.json()\nwhile tmp:\n tmp = requests.get(tmp['next'], headers=headers).json()\n for x in tmp['results']:\n data = {\n \"name\": x['name'],\n \"namespace\": None,\n \"cpu\": x['cpu'],\n \"ip\": x['ip'],\n \"labels\": [\n {\"k\": \"model_name\", \"v\": x[\"model_name\"]},\n {\"k\": \"site_name\", \"v\": x[\"site_name\"]},\n {\"k\": \"company\", \"v\": x[\"company\"]},\n {\"k\": \"os_id\", \"v\": x[\"os_id\"]},\n {\"k\": \"cpu\", \"v\": x[\"cpu\"]},\n ]\n }\n r = requests.post(\"http://127.0.0.1:8000/v1/mysql/\", json=data)\n print(r.text)","sub_path":"test_import.py","file_name":"test_import.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"96663848","text":"import numpy as np\r\nfrom monte_carlo_tree import move, score, monte_carlo\r\nimport time\r\nstart_time = time.time()\r\n\r\n# np.random.seed(2)\r\n# tf.set_random_seed(2)\r\n\r\nrandom_move_probability = 0.5 # todo: modify probability!\r\n# small chance that disc drop to other columns, intentionally set high and won't save random move as training data\r\nR = 6 # 6 # number of rows (board height)\r\nC = 7 # 7 # number of columns (board width)\r\nwin_num = 4 # 4 # number of symbol in line to win\r\nif win_num > C or win_num > R:\r\n raise ValueError('win_num is larger than board dimension!')\r\nBLANK = \"_\"\r\n\r\nsave_title = \"R_\" + str(R) + \"_C_\" + str(C) +\"_win_num_\" + str(win_num) + \"_\"\r\nsave_data = []\r\nsave_col = []\r\n\r\n\r\ndef monte_carlo_player(state, parent_row, parent_col):\r\n if state[parent_row][parent_col] == \"x\": symbol = \"o\"\r\n else: symbol = \"x\" # if \"o\" or \"_\"(0th turn)\r\n v, depth, move_col = monte_carlo(state, symbol, parent_row, parent_col, R, C, win_num)\r\n return move_row, move_col, symbol\r\n\r\n\r\ndef random_player(state, parent_row, parent_col):\r\n if state[parent_row][parent_col] == \"x\": symbol = \"o\"\r\n else: symbol = \"x\"\r\n valid_moves = np.nonzero(state[0][:] == BLANK)[0]\r\n move_col = valid_moves[np.random.choice(valid_moves.shape[0])]\r\n return move_row, move_col, symbol\r\n\r\n\r\ndef human_player(state, parent_row, parent_col):\r\n if state[parent_row][parent_col] == \"x\": symbol = \"o\"\r\n else: symbol = \"x\"\r\n valid_moves = np.nonzero(state[0][:] == BLANK)[0]\r\n for i in range(100000):\r\n move_col = int(input(\"You play '\" + symbol + \"', please choose a column from: \" + np.array2string(valid_moves)))\r\n if np.isin(move_col, valid_moves): break\r\n else: print(\"Your choice is not valid, please re-enter!\")\r\n return move_row, move_col, symbol\r\n\r\n\r\ndef random_move_save(state, symbol, move_col, player):\r\n if player == \"monte_carlo\":\r\n save_state = np.zeros(state.shape)\r\n if symbol == \"o\": sym = -1\r\n else: sym = 1\r\n save_state[np.where(state == \"x\")] = sym\r\n save_state[np.where(state == \"o\")] = -sym\r\n save_data.append(save_state)\r\n save_col.append(move_col)\r\n if np.random.random() < random_move_probability:\r\n valid_moves = np.nonzero(state[0][:] == BLANK)[0]\r\n valid_moves = np.delete(valid_moves, np.argwhere(valid_moves == move_col))\r\n if valid_moves.shape[0] != 0:\r\n move_col = valid_moves[np.random.choice(valid_moves.shape[0])]\r\n print(\"Go to the random column!\")\r\n child, move_row = move(state, symbol, move_col, R, C, win_num)\r\n return child, move_col, move_row\r\n\r\n\r\ndef print_col_coordinate():\r\n pstring = \" \"\r\n for i in range(C): pstring = pstring + str(i) + \" \"\r\n print(pstring)\r\n\r\n\r\nplayer1 = \"monte_carlo\"\r\nplayer2 = \"monte_carlo\"\r\n\r\nfor game_repetition in range(100):\r\n state = np.full((R, C), BLANK)\r\n symbol = \"x\" # second player \"o\"\r\n move_row = 0\r\n move_col = 0\r\n for turn in range(R*C):\r\n if turn % 2 == 0:\r\n player = player1\r\n else:\r\n player = player2\r\n print(\"\\n\", game_repetition, \"th game, turn\", turn, \".\", player, \"player's turn\")\r\n\r\n if player == \"monte_carlo\":\r\n print(\"Thinking...\")\r\n move_row, move_col, symbol = monte_carlo_player(state, move_row, move_col)\r\n elif player == \"random\":\r\n move_row, move_col, symbol = random_player(state, move_row, move_col)\r\n elif player == \"human\":\r\n move_row, move_col, symbol = human_player(state, move_row, move_col)\r\n state, move_col, move_row = random_move_save(state, symbol, move_col, player)\r\n print(state)\r\n print_col_coordinate()\r\n print(\"'\" + symbol + \"' played at\", move_col)\r\n\r\n v = score(state, move_row, move_col, R, C, win_num)\r\n if v in [-1, 1]:\r\n print(\"\\nMatch end, \" + player + \" with '\" + symbol + \"' wins!\")\r\n break\r\n elif (state != BLANK).all():\r\n print(\"\\nMatch end, draw!\")\r\n break\r\n\r\nnp.save('CNN_data/' + save_title + 'data.npy', save_data)\r\nnp.save('CNN_data/' + save_title + 'col.npy', save_col)\r\n# print(np.load('CNN_data/' + save_title + 'data.npy'))\r\n# print(np.load('CNN_data/' + save_title + 'col.npy'))\r\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\r\n","sub_path":"main_CNN_training_data.py","file_name":"main_CNN_training_data.py","file_ext":"py","file_size_in_byte":4363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"509486402","text":"from google.appengine.ext import ndb\r\nimport jinja2\r\nimport os\r\nimport webapp2\r\n\r\nthe_jinja_env = jinja2.Environment(\r\n loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),\r\n extensions=['jinja2.ext.autoescape'],\r\n autoescape=True)\r\n\r\nclass RegisterHandler(webapp2.RequestHandler):\r\n def get(self):\r\n donation_template = the_jinja_env.get_template('donation.html')\r\n self.response.out.write(donation_template.render())\r\n def post(self):\r\n template1 = the_jinja_env.get_template('donation.html')\r\n Name = self.request.get('name')\r\n Email = self.request.get('email')\r\n Phone = self.request.get('phone')\r\n Item_description = self.request.get('item description')\r\n User = NewUser(Name=Name, Email=Email, Phone=Phone, Item_description=Item_description)\r\n User.put()\r\n self.response.out.write(donation_template.render())\r\n\r\nclass Home(webapp2.RequestHandler):\r\n def get(self):\r\n template = the_jinja_env.get_template('index.html')\r\n self.response.out.write(template.render())\r\n\r\nclass About(webapp2.RequestHandler):\r\n def get(self):\r\n template = the_jinja_env.get_template('info.html')\r\n self.response.out.write(template.render())\r\n\r\nclass GetInvolved(webapp2.RequestHandler):\r\n def get(self):\r\n template = the_jinja_env.get_template('kyr.html')\r\n self.response.out.write(template.render())\r\n\r\nclass Biographies(webapp2.RequestHandler):\r\n def get(self):\r\n template = the_jinja_env.get_template('volunteer.html')\r\n self.response.out.write(template.render())\r\n\r\nclass Donate(webapp2.RequestHandler):\r\n def get(self):\r\n template = the_jinja_env.get_template('htc.html')\r\n self.response.out.write(template.render())\r\n\r\nclass Vision(webapp2.RequestHandler):\r\n def get(self):\r\n template = the_jinja_env.get_template('vision.html')\r\n self.response.out.write(template.render())\r\n\r\napp = webapp2.WSGIApplication([\r\n ('/register', RegisterHandler),\r\n ('/', Home),\r\n ('/vision', Vision),\r\n ('/getinvolved', GetInvolved),\r\n ('/biographies', Biographies),\r\n ('/donate1', RegisterHandler),\r\n ('/donate', Donate),\r\n ('/about', About),\r\n], debug=True)\r\n#info about us\r\n#vision Vision\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"301271100","text":"import scrapy\nfrom scrapy.selector import Selector\nfrom spiders.items import SpidersItem\n\nclass MaoyanSpider(scrapy.Spider):\n\n name = 'maoyan'\n allowed_domains = ['maoyan.com']\n start_urls = ['https://maoyan.com/films?showType=3']\n\n def start_requests(self):\n url = 'https://maoyan.com/films?showType=3'\n yield scrapy.Request(url=url, callback=self.parse)\n\n def parse(self, response):\n movie_list = Selector(response=response).xpath('//div[@class=\"movie-item film-channel\"]')\n for i in range(10):\n movie = movie_list[i]\n item = SpidersItem()\n item['movie_name'] = movie.xpath('.//span[contains(@class,\"name\")]/text()').extract_first()\n type_date = movie.xpath('.//span[@class=\"hover-tag\"]/../text()').extract()\n item['movie_type'] = type_date[1].strip('\\n').strip()\n item['movie_time'] = type_date[5].strip('\\n').strip()\n yield item\n\n","sub_path":"week01/homeWork2/spiders/spiders/spiders/maoyan.py","file_name":"maoyan.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"423007033","text":"# Copyright 2016 Open Source Robotics Foundation, Inc.\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\nfrom launch.exit_handler import ignore_exit_handler, restart_exit_handler\nfrom ros2run.api import get_executable_path\n\n\ndef launch(launch_descriptor, argv):\n ld = launch_descriptor\n package = 'turtlebot2_drivers'\n ld.add_process(\n cmd=[get_executable_path(package_name=package, executable_name='kobuki_node')],\n name='kobuki_node',\n exit_handler=restart_exit_handler,\n )\n package = 'astra_camera'\n ld.add_process(\n cmd=[\n get_executable_path(package_name=package, executable_name='astra_camera_node'),\n '-dw', '320', '-dh', '240', '-C', '-I'],\n name='astra_camera_node',\n exit_handler=restart_exit_handler,\n )\n package = 'turtlebot2_follower'\n ld.add_process(\n cmd=[get_executable_path(package_name=package, executable_name='follower')],\n name='follower',\n exit_handler=restart_exit_handler,\n )\n package = 'teleop_twist_joy'\n ld.add_process(\n cmd=[get_executable_path(package_name=package, executable_name='teleop_node')],\n name='teleop_node',\n # The teleop node is optional, we don't care if it actually launches\n exit_handler=ignore_exit_handler,\n )\n package = 'joy'\n ld.add_process(\n cmd=[get_executable_path(package_name=package, executable_name='joy_node')],\n name='joy',\n # The joy node is optional, we don't care if it actually launches\n exit_handler=ignore_exit_handler,\n )\n\n return ld\n","sub_path":"Milestone1/turtlebot2_follower/launch/turtlebot_follow.py","file_name":"turtlebot_follow.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"266068216","text":"# -*- coding: utf-8 -*-\nimport cherrypy\nfrom pymongo import MongoClient\nclient = MongoClient('mongodb://localhost:27017/')\ndb_topics = client.test.topics\n\n\nclass Topics(object):\n exposed = True\n\n @cherrypy.tools.json_out()\n def GET(self, id=None):\n if id:\n return db_topics.find_one({\"_id\": id})\n else:\n return db_topics.find()\n\n @cherrypy.tools.json_in()\n @cherrypy.tools.json_out()\n def POST(self, id=None):\n topic = db_topics.insert_one(cherrypy.request.json)\n return db_topics.find_one(topic.inserted_id)\n\n @cherrypy.tools.json_in()\n @cherrypy.tools.json_out()\n def PUT(self, id=None):\n db_topics.update_one(\n {\"_id\": id},\n cherrypy.request.json\n )\n return db_topics.find_one({\"_id\": id})\n\n @cherrypy.tools.json_out()\n def DELETE(self, id=None):\n db_topics.delete_one({\"_id\": id})\n return db_topics.find()\n\nif __name__ == '__main__':\n conf = {\n '/': {\n 'request.dispatch': cherrypy.dispatch.MethodDispatcher(),\n 'tools.sessions.on': True,\n 'tools.response_headers.on': True,\n 'tools.response_headers.headers': [('Content-Type', 'text/plain')],\n }\n }\n cherrypy.quickstart(Topics(), '/topics/', conf)\n","sub_path":"modules/topics.py","file_name":"topics.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"283563934","text":"# Configuration file for the Sphinx documentation builder.\n#\n# This file only contains a selection of the most common options. For a full\n# list see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\n# -- Path setup --------------------------------------------------------------\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#\nimport re\nimport sys\nimport os\nimport sphinx_rtd_theme\nimport striplog\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\nsys.path.insert(0, os.path.abspath('../striplog'))\n\n\n# -- Project information -----------------------------------------------------\n# The master toctree document.\nmaster_doc = 'index'\n\n# General information about the project.\nproject = 'striplog'\ncopyright = '2020, Agile Scientific'\nauthor = 'Agile Scientific'\n\n# The full version, including alpha/beta/rc tags\nverstr = 'unknown'\nVERSIONFILE = \"../striplog/_version.py\"\nwith open(VERSIONFILE, \"r\")as f:\n verstrline = f.read().strip()\n pattern = re.compile(r\"__version__ = ['\\\"](.*)['\\\"]\")\n mo = pattern.search(verstrline)\nif mo:\n verstr = mo.group(1)\n print(\"Version \"+verstr)\nelse:\n raise RuntimeError(\"Unable to find version string in %s.\" % (VERSIONFILE,))\n\n# The short X.Y version.\nversion = verstr[:3]\n# The full version, including alpha/beta/rc tags.\nrelease = verstr\n\n\n# -- General configuration ---------------------------------------------------\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\n 'nbsphinx',\n 'nbsphinx_link',\n 'sphinxcontrib.apidoc',\n 'sphinx.ext.todo',\n 'sphinx.ext.coverage',\n 'sphinx.ext.mathjax',\n 'sphinx.ext.viewcode',\n 'sphinx.ext.napoleon',\n]\n\n# Autosummary pages will be generated by sphinx-autogen. Otherwise, the\n# imported members won't be documented.\napidoc_module_dir = '../striplog'\napidoc_excluded_paths = ['tests']\napidoc_toc_file = 'api_toc'\napidoc_separate_modules = True\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path.\nexclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']\n\n# If true, the current module name will be prepended to all description\n# unit titles (such as .. function::).\nadd_module_names = True\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = 'sphinx'\n# -- Options for HTML output -------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\n#\nhtml_theme = \"sphinx_rtd_theme\"\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = ['_static']\n\n# Add any paths that contain custom themes here, relative to this directory.\nhtml_theme_path = [sphinx_rtd_theme.get_html_theme_path()]\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = 'striplogdoc'\n\n# -- Options for LaTeX output ---------------------------------------------\n\nlatex_elements = {\n# The paper size ('letterpaper' or 'a4paper').\n#'papersize': 'letterpaper',\n\n# The font size ('10pt', '11pt' or '12pt').\n#'pointsize': '10pt',\n\n# Additional stuff for the LaTeX preamble.\n#'preamble': '',\n}\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title,\n# author, documentclass [howto, manual, or own class]).\nlatex_documents = [\n ('index', 'striplog.tex', u'striplog Documentation',\n u'Matt Hall, Agile Geoscience Ltd', 'manual'),\n]\n\n# The name of an image file (relative to this directory) to place at the top of\n# the title page.\n#latex_logo = None\n\n# For \"manual\" documents, if this is true, then toplevel headings are parts,\n# not chapters.\n#latex_use_parts = False\n\n# If true, show page references after internal links.\n#latex_show_pagerefs = False\n\n# If true, show URL addresses after external links.\n#latex_show_urls = False\n\n# Documents to append as an appendix to all manuals.\n#latex_appendices = []\n\n# If false, no module index is generated.\n#latex_domain_indices = True\n\n\n# -- Options for manual page output ---------------------------------------\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\nman_pages = [\n ('index', 'striplog', u'striplog Documentation',\n [u'Matt Hall, Agile Geoscience Ltd'], 1)\n]\n\n# If true, show URL addresses after external links.\n#man_show_urls = False\n\n\n# -- Options for Texinfo output -------------------------------------------\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n# dir menu entry, description, category)\ntexinfo_documents = [\n ('index', 'striplog', u'striplog Documentation',\n u' Matt Hall, Agile Geoscience Ltd', 'striplog', 'One line description of project.',\n 'Miscellaneous'),\n]\n\n# Documents to append as an appendix to all manuals.\n#texinfo_appendices = []\n\n# If false, no module index is generated.\n#texinfo_domain_indices = True\n\n# How to display URL addresses: 'footnote', 'no', or 'inline'.\n#texinfo_show_urls = 'footnote'\n\n# If true, do not generate a @detailmenu in the \"Top\" node's menu.\n#texinfo_no_detailmenu = False","sub_path":"docs/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":5955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"307686105","text":"import time\nimport struct\nimport numpy as np\nfrom queue import Queue\nfrom scipy.fftpack import fft, fftshift\nfrom numpy.lib.stride_tricks import as_strided\nfrom scipy.integrate._ivp.radau import P\n\nglobal cycle\ncycle = 0\n\n\ndef DFT(x):\n \"\"\"Compute the Discrete Fourier Transform of the 1D array x\"\"\"\n N = len(x)\n n = np.arange(N)\n k = n.reshape((N, 1))\n M = np.exp(-2j * np.pi * k * n / N)\n return np.dot(M, x)\n\n\ndef FFT(x):\n \"\"\"A recursive implementation of the 1D Cooley-Tukey FFT\"\"\"\n N = len(x)\n if N % 2 > 0:\n raise ValueError(\"size of x must be a power of 2\")\n elif N <= 2: # this cutoff should be optimized\n return DFT(x)\n else:\n X_even = FFT(x[::2])\n X_odd = FFT(x[1::2])\n factor = np.exp(-2.0j * np.pi * np.arange(N) / N)\n return np.concatenate([X_even + factor[:N // 2] * X_odd,\n X_even + factor[N // 2:] * X_odd])\n\n\ndef FFT_vectorized(x):\n \"\"\"A vectorized, non-recursive version of the Cooley-Tukey FFT\"\"\"\n N = len(x)\n if np.log2(N) % 1 > 0:\n raise ValueError(\"size of x must be a power of 2\")\n # N_min here is equivalent to the stopping condition above,\n # and should be a power of 2\n N_min = min(N, 2)\n # Perform an O[N^2] DFT on all length-N_min sub-problems at once\n n = np.arange(N_min)\n k = n[:, None]\n M = np.exp(-2j * np.pi * n * k / N_min)\n X = np.dot(M, np.array(x).reshape((N_min, -1)))\n # build-up each level of the recursive calculation all at once\n while X.shape[0] < N:\n X_even = X[:, :X.shape[1] // 2]\n X_odd = X[:, X.shape[1] // 2:]\n factor = np.exp(-1j * np.pi * np.arange(X.shape[0])\n / X.shape[0])[:, None]\n X = np.vstack([X_even + factor * X_odd,\n X_even - factor * X_odd])\n\n return X.ravel()\n\n\ndef complex_mult(cell_index, x, y):\n \"\"\"Complex multiplication: (X * conjugate(X))\"\"\"\n list_3 = []\n for i in range(len(x)):\n real_part = x[i].real * y[i].real - x[i].imag * y[i].imag\n image_part = x[i].imag * y[i].real + x[i].real * y[i].imag\n complex_result = real_part + image_part * 1j\n list_3.append(complex_result)\n global cycle\n if cell_index == 0: # Add for PE[0]\n cycle += 1\n\n return list_3\n\n\ndef getTwiddle(NFFT):\n \"\"\"Generate the twiddle factors\"\"\"\n W = np.r_[[1.0 + 1.0j] * NFFT]\n for k in range(NFFT):\n W[k] = np.exp(-2.0j * np.pi * k / NFFT)\n\n return W\n\n\ndef rFFT(cell_index, x):\n \"\"\"\n Recursive FFT implementation.\n References\n -- http://www.cse.uiuc.edu/iem/fft/rcrsvfft/\n -- \"A Simple and Efficient FFT Implementation in C++\"\n by Vlodymyr Myrnyy\n \"\"\"\n n = len(x)\n if n == 1:\n return x\n w = getTwiddle(n)\n m = n // 2\n X = np.ones(m, float) * 1j\n Y = np.ones(m, float) * 1j\n for k in range(m):\n X[k] = x[2 * k]\n Y[k] = x[2 * k + 1]\n X = rFFT(cell_index, X)\n Y = rFFT(cell_index, Y)\n F = np.ones(n, float) * 1j\n for k in range(n):\n i = (k % m)\n F[k] = X[i] + w[k] * Y[i]\n global cycle\n if cell_index == 0: # Add for PE[0]\n cycle += 1\n\n return F\n\n\nclass LinearArrayCell:\n def __init__(self, cell_size):\n self.cell_size = cell_size\n self.cell_index = 0\n self.cell_input = None\n self.single_in = 0\n self.single_out = 0\n self.data_to_compute_1 = Queue(maxsize=self.cell_size)\n self.data_to_compute_2 = Queue(maxsize=self.cell_size)\n self.alpha = [0] * 8\n self.alpha_top = []\n self.alpha_bottom = []\n self.cell_shift = Queue()\n self.cell_partial_result = Queue()\n self.cell_output = Queue()\n self.signal_index = 0\n\n def connect(self, cell_index, array, array_size, iterations):\n self.cell_index = cell_index\n if iterations % array_size == 0: # a group of data completed loop in all cells\n if self.signal_index > 0:\n self.clear_shift()\n self.cell_input = array.input[self.signal_index][self.cell_index]\n self.signal_index += 1\n else:\n self.cell_input = array.cells[self.cell_index - 1] # shift registers\n\n def cell_read(self): # load all data needed for a cell\n # global cycle\n if type(self.cell_input) is Queue: # from input FIFO\n for _ in range(self.cell_size):\n if self.cell_input.empty():\n self.single_in = 0\n else:\n self.single_in = self.cell_input.get()\n self.data_to_compute_1.put(self.single_in)\n self.data_to_compute_2.put(self.single_in.real - self.single_in.imag * 1j) # conjugate\n # cycle += 1\n else: # from shift registers (only for data, not for conjugate(data))\n for _ in range(self.cell_size):\n self.single_in = self.cell_input.cell_shift.get()\n self.data_to_compute_1.put(self.single_in)\n # self.data_to_compute_2.put(self.single_in.real - self.single_in.imag * 1j)\n # cycle += 1\n\n def compute(self, cell_index, last_cell, prev_alpha, iterations):\n global cycle\n list_1 = list(self.data_to_compute_1.queue)\n list_2 = list(self.data_to_compute_2.queue)\n cm = complex_mult(cell_index, list_1, list_2)\n fft_res = rFFT(cell_index, cm)\n # print(f'Compare rFFT with built-in FFT at PE {iterations}:', np.allclose(rFFT(cm), fft(cm)))\n fft_shift = fftshift(fft_res)[len(fft_res) // 2 - 8: len(fft_res) // 2 + 8] # fft_res[8:23]\n fft_abs = np.abs(fft_shift)\n if cell_index == 0: # Add for PE[0]\n cycle += 16\n if iterations == 0:\n self.alpha_top = fft_abs[len(fft_abs) // 2: len(fft_abs)] # previous top: fft_abs[8:15]\n else: # iteration 1 to N-1\n if not last_cell:\n # self.alpha = self.alpha_top # initialize alpha with previous top: fft_abs[8:15]\n self.alpha_bottom = fft_abs[0: len(fft_abs) // 2] # current bottom: fft_abs[0:7]\n for i in range(len(fft_abs) // 2):\n # alpha = max(top of (k-1) iteration, bottom of k iteration, alpha of previous PE) #\n if self.alpha_top[i] < self.alpha_bottom[i]:\n self.alpha[i] = self.alpha_bottom[i] # update alpha\n else:\n self.alpha[i] = self.alpha_top[i] # update alpha\n if self.alpha[i] < prev_alpha[i]:\n self.alpha[i] = prev_alpha[i] # update alpha\n if cell_index == 0: # Add for PE[0]\n cycle += 2\n self.alpha_top = fft_abs[len(fft_abs) // 2: len(fft_abs)] # update alpha_top to current iteration\n else: # last PE in each iteration\n for i in range(len(fft_abs) // 2):\n if self.alpha_top[i] < prev_alpha[i]: # top of previous iteration Vs. alpha of previous PE\n self.alpha[i] = prev_alpha[i]\n else:\n self.alpha[i] = self.alpha_top[i]\n if cell_index == 0: # Add for PE[0]\n cycle += 1\n # self.alpha = self.alpha_top # final output: alpha\n\n def shift(self):\n # global cycle\n for _ in range(self.cell_size):\n self.single_out = self.data_to_compute_1.get()\n self.cell_shift.put(self.single_out)\n # cycle += 1\n\n def clear_shift(self): # to clear shift data from cell_shift queue when complete an input signal\n for _ in range(self.cell_size):\n self.cell_shift.get()\n self.data_to_compute_2.get()\n\n\nclass LinearArray:\n def __init__(self, array_size, cell_size, fifo_input):\n self.array_size = array_size\n self.cell_size = cell_size\n self.input = fifo_input\n self.iterations = 0\n self.cells = []\n self.result = []\n\n for _ in range(self.array_size):\n cell = LinearArrayCell(self.cell_size)\n self.cells.append(cell)\n self.num_cells = len(self.cells)\n\n def connect(self):\n for cell_index, cell in enumerate(self.cells):\n cell.connect(cell_index, self, self.array_size, self.iterations)\n\n def read(self):\n for cell in self.cells:\n cell.cell_read()\n\n def compute(self):\n last_cell = False\n for i in range(self.num_cells):\n if i == self.num_cells - 1:\n last_cell = True\n if i == 0: # cell 0: prev_alpha = [0, 0, 0, 0, 0, 0, 0, 0]\n self.cells[i].compute(i, last_cell, [0 for _ in range(8)], self.iterations)\n else: # cell i: prev_alpha = cells[i-1].alpha\n self.cells[i].compute(i, last_cell, self.cells[i - 1].alpha, self.iterations)\n if self.iterations > 0:\n self.num_cells -= 1\n\n def shift(self):\n for cell in self.cells:\n cell.shift()\n\n def run(self, total_iterations):\n for _ in range(total_iterations):\n self.connect()\n self.read()\n global cycle\n cycle += 32\n self.compute()\n self.shift()\n self.iterations += 1\n self.result.append(self.cells[0].alpha_top) # output alpha_top of PE[0]\n self.cells.pop(0)\n for cell in self.cells:\n self.result.append(cell.alpha)\n return self.result\n\n\ndef sliding_window(x, w, s):\n shape = (((x.shape[0] - w) // s + 1), w)\n strides = (x.strides[0] * s, x.strides[0])\n return as_strided(x, shape, strides)\n\n\ndef normalize_complex_arr(a):\n # a_oo = a - a.real.min() - 1j * a.imag.min() # origin offsetted\n # return a_oo / np.abs(a_oo).max()\n return a / np.abs(a).max()\n\n\ndef to_fixed(f, e):\n \"\"\"\n f is the input floating point number\n e is the number of fractional bits in the Q format.\n Example in Q1.15 format e = 15\n \"\"\"\n a = f * (2 ** e)\n b = int(round(a))\n if a < 0:\n # next three lines turns b into it's 2's complement.\n b = abs(b)\n b = ~b\n b = b + 1\n return b\n\n\ndef to_hex(val):\n \"\"\"Covert signed int to hex in two's complement\"\"\"\n return \"%s\" % (\"0000%x\" % (val & 0xffffffff))[-4:]\n\n\ndef main():\n # print(\"Hello World!\")\n signals = 1\n pes = int(input('Please enter the No. of PEs: ')) # 256, 16, 8\n registers = 32 # 32, 32, 32\n total_iter = signals * pes\n input_queue = [[Queue() for _ in range(pes)] for _ in range(signals)]\n input_cycle = registers # * pes\n compute_cycle = registers + registers * np.log2(registers) + registers / 2 + registers / 2\n shift_cycle = registers\n output_cycle = registers # * pes\n total_cycle = int(input_cycle + compute_cycle + (shift_cycle + compute_cycle) * (pes - 1)) + output_cycle\n total_time = total_cycle * 2 / 1000\n print('Theoretical number of cycles = {:d}. FPGA time = {:f} us at 500MHz.'.format(total_cycle, total_time))\n\n \"\"\"The following part is to generate the inputs for PE array which should match with MATLAB simulation\"\"\"\n # input channelization\n N = int(input('please enter N: ')) # 2048, 128, 64\n Np = pes # 256, 16, 8\n L = Np // 4 # 64, 4, 2\n P = N // L\n NN = (P - 1) * L + Np\n # Random data\n # a = np.array([0, 0.1, 0.2, 0.3])\n # x = np.tile(a, 32) # 560, 32\n # Load data from RFML dataset\n x = np.load('data/part18.npy')\n xs = np.zeros(NN, dtype=complex) # xs = np.zeros(NN)\n for i in range(P * L):\n xs[i] = x[i]\n # xs = sliding_window(x, Np, L) # x, Np, L\n b = np.zeros(1, dtype=complex) # b = np.zeros(1)\n xs2 = np.tile(b, (pes, registers))\n for k in range(P):\n xs2[:, k] = xs[k * L:k * L + Np]\n # windowing\n w = np.hamming(Np)\n ww = np.tile(w, (P, 1))\n xw = xs2 * ww.transpose()\n xw = xw.transpose()\n # first FFT\n XFFT1 = fft(xw, axis=1)\n # normalization\n XFFT1_norm = normalize_complex_arr(XFFT1)\n # FFT shift\n # XFFT1_shift = fftshift(XFFT1, axes=1)\n XFFT1_shift = fftshift(XFFT1_norm, axes=1)\n # calculating complex demodulates\n f = np.arange(Np) / float(Np) - .5\n t = np.arange(P) * L\n f = np.tile(f, (P, 1))\n t = np.tile(t.reshape(P, 1), (1, Np))\n # Down conversion\n XD = XFFT1_shift * np.exp(-1j * 2 * np.pi * f * t)\n XD = XD.transpose() # size: Np * P = 32 * 8\n \"\"\"The following code is added to generate the hex representation of PE array input\"\"\"\n np.savetxt(\"data/array_input.txt\", XD) # save to text (floating-point complex values)\n XD_1d = XD.flatten()\n XD_real_int = np.array([(to_fixed(x.real, 15)) for x in XD_1d]) # 16-bit signed int for real\n XD_imag_int = np.array([(to_fixed(x.imag, 15)) for x in XD_1d]) # 16-bit signed int for image\n XD_imag_int_neg = np.array([-x for x in XD_imag_int])\n XD_real_hex = np.array(([to_hex(x) for x in XD_real_int])) # MSB 16-bit hex for real\n XD_imag_hex = np.array([to_hex(x) for x in XD_imag_int]) # MSB 16-bit hex for image\n XD_imag_hex_conj = np.array([to_hex(x) for x in XD_imag_int_neg])\n XD_hex = np.array(list(map(str.__add__, XD_real_hex, XD_imag_hex))) # combine\n XD_hex = np.array(['0x' + s for s in XD_hex]) # add '0x'\n XD_hex_conj = np.array(list(map(str.__add__, XD_real_hex, XD_imag_hex_conj)))\n XD_hex_conj = np.array(['0x' + s for s in XD_hex_conj])\n '''\n XD_int = np.array([(x << 16) + y for x, y in zip(XD_real_int, XD_imag_int)])\n XD_int_conj = np.array([(x << 16) - y for x, y in zip(XD_real_int, XD_imag_int)])\n XD_hex = np.array([to_hex(x, 32) for x in XD_int])\n XD_hex_conj = np.array([to_hex(x, 32) for x in XD_int_conj])\n '''\n concat_no = 32\n set_no = len(XD_hex) // concat_no\n XD_hex_xy = []\n for set in range(set_no):\n XD_hex_xy[set * concat_no * 2:(set + 1) * concat_no * 2] = np.concatenate(\n (XD_hex[set * concat_no:(set + 1) * concat_no], XD_hex_conj[set * concat_no:(set + 1) * concat_no]))\n np.savetxt(\"data/array_input_hex.txt\", XD_hex_xy, fmt=\"%s\") # save to text for FPGA process\n # np.savetxt(\"data/array_y_hex.txt\", XD_hex_conj, fmt=\"%s\") # save to text for FPGA process\n # Use the down conversion results as the inputs of PE arrays\n for signal in range(signals):\n for pe in range(pes):\n for register in range(registers):\n pe_input = XD[pe][register]\n input_queue[signal][pe].put(pe_input)\n ''' \n for signal in range(signals):\n for pe in range(pes):\n if signal == 0:\n for index in range(pe * registers, (pe + 1) * registers):\n complex_data = index / 256 # + (index + 1) / 256 * 1j\n input_queue[signal][pe].put(complex_data)\n if signal > 0:\n for index in reversed(range(pe * registers, (pe + 1) * registers)):\n complex_data = index / 256 + (index + 1) / 256 * 1j\n input_queue[signal][pe].put(complex_data)\n '''\n # print(list(input_queue[0][-1].queue))\n myArray = LinearArray(pes, registers, input_queue)\n start_time = time.time()\n scd = myArray.run(total_iter) # run (signal*pes) times\n end_time = time.time()\n cpu_time = end_time - start_time\n # pe_cycle = cycle // pes\n pe_cycle = cycle\n print('----{:.4f} seconds on CPU----'.format(cpu_time))\n print('Real total number of cycles on PE = {}'.format(pe_cycle))\n # print('----alpha profile of SCD matrix----')\n scd_alpha = []\n for index, alpha in enumerate(scd):\n # print('alpha[{:d}] = {:f}'.format(index, *alpha))\n # print(len(alpha))\n print('alpha[{:d}] = {}'.format(index, [np.round(element, 4) for element in alpha]))\n scd_alpha += list(alpha)[::-1]\n # scd_alpha.extend(alpha.tolist().reverse())\n np.savetxt(\"data/scd_result.txt\", scd) # save to text\n np.save(\"data/part18_alpha.npy\", scd_alpha) # save to numpy file\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"linear_alpha_input.py","file_name":"linear_alpha_input.py","file_ext":"py","file_size_in_byte":16177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"565588838","text":"#\n# Copyright (c) 2016 Stefan Seefeld\n# All rights reserved.\n#\n# This file is part of Faber. It is made available under the\n# Boost Software License, Version 1.0.\n# (Consult LICENSE or http://www.boost.org/LICENSE_1_0.txt)\n\nfrom __future__ import absolute_import\nfrom . import _bjam\nfrom ._bjam import DependencyError # noqa F401\nfrom ..utils import capture_output\nfrom ..artefact import notfile, intermediate\nfrom ..cache import filecache\nfrom ..utils import aslist\nfrom types import FunctionType, MethodType\nfrom os import makedirs, remove, rmdir\nfrom os.path import dirname, lexists\nfrom collections import defaultdict\nimport logging\n\n__all__ = ['init', 'clean', 'finish',\n 'variables', 'define_artefact', 'add_dependency', 'define_recipe',\n 'run', 'update', 'print_dependency_graph', 'DependencyError']\n\nlogger = logging.getLogger('scheduler')\nsummary_logger = logging.getLogger('summary')\n\n#\n# The bjam backend only operates on strings (action names,\n# target names, filenames), so this module translates between\n# action and artefact instances and their corresponding ids.\n#\n\nartefacts = {} # map ids to instances\nboundnames = {} # map bound names (filenames) to instances\nactions = {} # map ids to instances\nrecipes = [] # register (action, targets)\n\nfiles = None\nintermediates = []\nkeep_intermediates = False\nnoexec = False\n\nsummary = defaultdict(int)\n\n\ndef _format_count(msg, what):\n number = summary[what]\n if number:\n summary_logger.info(msg.format(number, 's' if number > 1 else ''))\n\n\ndef _report_recipe(name, target, status, cmd, time, stdout, stderr):\n a = actions.get(name)\n if a:\n if isinstance(target, list):\n target = [artefacts[t] for t in target]\n else:\n target = [artefacts[target]]\n if status == 0:\n intermediates.extend([t._filename for t in target\n if t.attrs & intermediate])\n files.extend([t._filename for t in target if not t.attrs & notfile])\n\n a.__status__(target, status == 0, cmd, time, stdout, stderr)\n\n\ndef _report_artefact(name, status, failed):\n a = artefacts[name]\n if failed:\n failed = artefacts[failed]\n msg = '...skipped {} for lack of {}...'.format(a.boundname, failed.boundname)\n if a.logfile:\n a.logfile.write(msg + '\\n')\n else:\n summary_logger.info(msg)\n a.__status__(status == 0)\n\n\ndef _report(what, *args):\n if what == '__summary__':\n failed, skipped, made = args\n summary['failed'] += failed\n summary['skipped'] += skipped\n summary['made'] += made\n elif what == '__recipe__':\n _report_recipe(*args)\n elif what == '__artefact__':\n _report_artefact(*args)\n else:\n raise ValueError('invalid report')\n\n\ndef _prepare(recipe, target):\n \"\"\"Prepare target variables and filename before running recipe.\"\"\"\n\n r = actions[recipe]\n t = artefacts[target]\n t.features.eval(update=False)\n if not t.attrs & notfile:\n bind_filename(t)\n d = dirname(t._filename) or '.'\n if not lexists(d):\n makedirs(d)\n vars = r.map(t.features)\n if vars:\n logger.info('setting variables for {}: {}'.format(t.id, vars))\n return vars\n\n\ndef _pyaction(name, func):\n \"\"\"command actions report their execution back.\n Python callables are executed differently, so we wrap them here\n to be able to capture and report their status.\"\"\"\n\n from ..action import action, CallError\n\n def wrapper(target, source, **kwds):\n tt = [boundnames[t] for t in target]\n ss = [boundnames.get(s, s) for s in source]\n with capture_output() as (out, err):\n status = True\n cmd = None\n # This little hack allows us to instruct the scheduler\n # to run certain (python) functions even in 'noexec'\n # mode, such as the ones to assemble compound artefacts.\n if not noexec or hasattr(func, '__noexec__'):\n try:\n status = func(tt, ss)\n # let users indicate failure by explicitly returning 'False'\n if status is not False:\n status = True\n except _bjam.DependencyError:\n # dependency errors are fatal - there is no point\n # in carrying on...\n raise\n except CallError as e:\n status = False\n cmd = e.cmd\n except Exception as e:\n # while normal exceptions simply result in update\n # failures.\n print(e)\n import traceback as tb\n tb.print_exc()\n status = False\n if not cmd:\n cmd = action.command_string(func, target, source, kwds)\n target = [t.id for t in tt]\n _report_recipe(name, target, 0 if status else 1, cmd, -1.,\n out.getvalue(), err.getvalue())\n return status\n return wrapper\n\n\ndef init(params, builddir, readonly=False, **options):\n global noexec, files, keep_intermediates\n # enable DEBUG_MAKEPROG and DEBUG_FATE if 'process' flag is set.\n log = (1 << 3) + (1 << 13) if options.get('log', 0) else 0\n noexec = options.get('noexec', False)\n files = filecache(builddir, params) if not readonly else ()\n keep_intermediates = options.get('intermediates', False)\n _bjam.init(_prepare, _report,\n log,\n noexec,\n options.get('jobs', 1),\n options.get('timeout', 0),\n options.get('force', False))\n\n\ndef clean(level=1):\n dirs = []\n # remove file artefacts...\n for f in files:\n # We may encounter symbolic links during the cleanup\n # which no longer refer to existing files. To be able\n # to detect them we need to use `lexists`...\n if lexists(f):\n dirs.append(dirname(f))\n remove(f)\n if files:\n files.clear()\n # ...then clean up empty build directories\n dirs = sorted(set(dirs), reverse=True)\n root = '' if files.root == '.' else files.root\n for d in dirs:\n try:\n while d != root:\n rmdir(d)\n d = dirname(d)\n except OSError: # directory wasn't empty, move on\n continue\n\n\ndef finish():\n global files\n # Remove intermediate files\n if not keep_intermediates:\n for i in intermediates:\n if lexists(i):\n remove(i)\n\n # print cumulative summary\n _format_count('...failed updating {} artefact{}...', 'failed')\n _format_count('...skipped {} artefact{}...', 'skipped')\n _format_count('...made {} artefact{}...', 'made')\n\n artefacts.clear()\n boundnames.clear()\n actions.clear()\n del files\n del recipes[:]\n _bjam.finish()\n\n\ndef variables(a):\n logger.info('getting variables for {}'.format(a.id))\n return _bjam.get_target_variables(a.id)\n\n\ndef define_artefact(a, bind=False):\n logger.info('define artefact {}'.format(a.id))\n artefacts[a.id] = a\n if a.attrs & notfile:\n boundnames[a.id] = a\n _bjam.define_target(a.id, a.attrs)\n if bind:\n bind_filename(a)\n\n\ndef bind_filename(a):\n logger.info('bind filename {} {}'.format(a.id, a._filename))\n boundnames[a._filename] = a\n return _bjam.bind_filename(a.id, a._filename, lexists(a._filename))\n\n\ndef add_dependency(a, deps):\n deps = [d.id for d in aslist(deps)]\n logger.info('declare dependencies {} -> {}'\n .format(a.id, deps))\n return _bjam.add_dependency(a.id, deps)\n\n\ndef define_recipe(a, targets, sources=[]):\n if a.id not in actions:\n logger.info('define action {} = {}'.format(a.id, a.command))\n actions[a.id] = a\n func = a.command\n if type(func) in (FunctionType, MethodType):\n func = _pyaction(a.id, func)\n _bjam.define_action(a.id, func, [])\n\n targets = [t.id for t in targets]\n if (a.id, tuple(targets)) not in recipes:\n recipes.append((a.id, tuple(targets)))\n sources = [s.id for s in sources]\n logger.info('define recipe {}({}, {})'\n .format(a.id, targets, sources))\n return _bjam.define_recipe(a.id, targets, sources)\n\n\ndef run(command):\n logger.info('run {}'.format(command))\n status, stdout, stderr = _bjam.run(command)\n return status == 0, stdout, stderr\n\n\ndef update(artefacts=[]):\n return _bjam.update([a.id for a in aslist(artefacts)]) == 0\n\n\ndef print_dependency_graph(artefacts=[]):\n return _bjam.print_dependency_graph([a.id for a in aslist(artefacts)])\n","sub_path":"src/faber/scheduler/bjam.py","file_name":"bjam.py","file_ext":"py","file_size_in_byte":8722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"35233949","text":"from Projects.DeepLearningTechniques.MobileNet_v2.iris.dataloader import DataLoader\nfrom Projects.DeepLearningTechniques.MobileNet_v2.iris.mobilenet_v2_model import *\nfrom Projects.DeepLearningTechniques.MobileNet_v2.iris.cam import GradCAM, GuidedGradCAM\n\nimport numpy as np\nimport time\nimport os\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\nclass Neuralnet:\n def __init__(self, is_training, save_type=None):\n self.is_training = is_training\n self.save_type = save_type\n\n def train(self):\n loader = DataLoader(batch_size=flags.FLAGS.batch_size, data_path=flags.FLAGS.data_path)\n print('>> DataLoader created')\n\n train_num = loader.train_len // flags.FLAGS.batch_size\n # test_num = loader.test_len // flags.FLAGS.batch_size\n train_batch1, train_batch2, train_batch3, train_batch4, train_batch5, train_batch6 = loader.train_loader()\n # test_batch = loader.test_loader()\n\n config = tf.ConfigProto(\n gpu_options=tf.GPUOptions(allow_growth=True, per_process_gpu_memory_fraction=1)\n )\n\n with tf.Session(config=config) as sess:\n model = Model(sess=sess, is_training=self.is_training, name='model')\n model.build()\n\n print('>> Tensorflow session built. Variables initialized.')\n sess.run(tf.global_variables_initializer())\n\n self._saver = tf.train.Saver()\n\n ckpt_st = tf.train.get_checkpoint_state(flags.FLAGS.trained_param_path)\n\n if ckpt_st is not None:\n # self._saver.restore(sess, ckpt_st.model_checkpoint_path)\n print('>> Model Restored')\n\n '''텐서플로우 그래프 저장'''\n tf.train.write_graph(sess.graph_def, flags.FLAGS.trained_param_path, 'graph.pbtxt')\n print('>> Graph saved')\n\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n print('>> Running started.')\n\n for epoch in range(1, flags.FLAGS.epochs+1):\n tot_train_acc, tot_train_loss = [], []\n tot_test_acc, tot_test_loss = [],[]\n\n '''Model Train'''\n train_st = time.time()\n for step in range(1, train_num+1):\n train_data_1, train_data_2, train_data_3, train_data_4, train_data_5, train_data_6 = \\\n sess.run([train_batch1, train_batch2, train_batch3, train_batch4, train_batch5, train_batch6])\n train_batch_x = np.concatenate([train_data_1[0], train_data_2[0], train_data_3[0], train_data_4[0], train_data_5[0], train_data_6[0]])\n train_batch_y = np.concatenate([train_data_1[1], train_data_2[1], train_data_3[1], train_data_4[1], train_data_5[1], train_data_6[1]])\n # train_batch_x = np.concatenate([train_data_1[0], train_data_3[0], train_data_4[0], train_data_5[0], train_data_6[0]])\n # train_batch_y = np.concatenate([train_data_1[1], train_data_3[1], train_data_4[1], train_data_5[1], train_data_6[1]])\n\n st = time.time()\n step_train_acc, step_train_loss = [], []\n\n for idx in range(0, 60, flags.FLAGS.batch_size):\n train_acc, train_loss, _ = model.train(x=train_batch_x[idx:idx+flags.FLAGS.batch_size],\n y=train_batch_y[idx:idx+flags.FLAGS.batch_size])\n step_train_acc.append(train_acc)\n step_train_loss.append(train_loss)\n tot_train_acc.append(train_acc)\n tot_train_loss.append(train_loss)\n\n et = time.time()\n\n step_train_acc = float(np.mean(np.array(step_train_acc)))\n step_train_loss = float(np.mean(np.array(step_train_loss)))\n print(\">> [Step-Train] epoch/step: [%d/%d], Accuracy: %.6f, Loss: %.6f, step_time: %.2f\"\n % (epoch, step, step_train_acc, step_train_loss, et - st))\n train_et = time.time()\n tot_train_time = train_et - train_st\n\n '''Model Test'''\n # for step in range(1, test_num + 1):\n # test_data = sess.run(test_batch)\n # test_batch_x, test_batch_y = test_data\n #\n # test_acc, test_loss = model.validate(x=test_batch_x, y=test_batch_y)\n #\n # tot_test_acc.append(test_acc)\n # tot_test_loss.append(test_loss)\n\n tot_train_acc = float(np.mean(np.array(tot_train_acc)))\n tot_train_loss = float(np.mean(np.array(tot_train_loss)))\n\n # tot_test_acc = float(np.mean(np.array(tot_test_acc)))\n # tot_test_loss = float(np.mean(np.array(tot_test_loss)))\n\n print('>> [Total-Train] epoch: [%d], Accuracy: %.6f, Loss: %.6f, time: %.2f'\n % (epoch, tot_train_acc, tot_train_loss, tot_train_time))\n # print('>> [Total-Test] epoch: [%d], Accuracy: %.6f, Loss: %.6f'\n # % (epoch, tot_test_acc, tot_test_loss))\n\n # self.db.mon_data_to_db(epoch, tot_train_acc, tot_test_acc, tot_train_loss, tot_test_loss, tot_train_time, tot_test_time)\n\n # kernel = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, 'right/output_layer/logit/W_conv2d')[0]\n # print(sess.run(kernel))\n\n ## Save model\n os.makedirs(os.path.join(flags.FLAGS.trained_param_path), exist_ok=True)\n self._saver.save(sess, os.path.join(flags.FLAGS.trained_param_path, 'dementia_param'), global_step=epoch)\n print('>> [Model saved] epoch: %d' % (epoch))\n\n coord.request_stop()\n coord.join(threads)\n\n # self.db.close_conn()\n\n def cam_test(self, sort='grad_cam'):\n sample_num = 3 # 클래스 당 테스트 샘플0 개수\n class_num = 2 # 전체 클래스 개수\n batch_size = sample_num * class_num\n img_size = (224, 400)\n sample_path = '/home/kyh/dataset/gelontoxon_cam'\n\n def save_matplot_img(cam_outputs, sample_num, class_num, file_name):\n f = plt.figure(figsize=(10, 8))\n plt.suptitle('CAM (Class Activation Mapping)', fontsize=20)\n outer = gridspec.GridSpec(1, 1, wspace=0.2, hspace=0.2)\n\n inner = gridspec.GridSpecFromSubplotSpec(class_num, sample_num, subplot_spec=outer[0], wspace=0.1, hspace=0.1)\n\n for cls in range(class_num):\n for sample in range(sample_num):\n subplot = plt.Subplot(f, inner[sample + cls * sample_num])\n subplot.axis('off')\n subplot.imshow(cam_outputs[sample + cls * sample_num])\n f.add_subplot(subplot)\n\n f.savefig(os.path.join('/home/kyh/PycharmProjects/PythonRepository/Projects/DeepLearningTechniques/MobileNet_v2/cam_image', file_name))\n print('>> CAM Complete')\n\n def get_file_names():\n filename_list, label_list = [], []\n\n for cls in range(class_num):\n file_names = [[os.path.join(path, file) for file in files] for path, dir, files in os.walk(os.path.join(sample_path, str(cls)))]\n file_names = np.asarray(file_names).flatten()\n\n random_sort = np.random.permutation(file_names.shape[0])\n file_names = file_names[random_sort][:sample_num]\n\n for f_name in file_names:\n filename_list.append(f_name)\n label_list.append(cls)\n\n filename_list = np.asarray(filename_list)\n label_list = np.asarray(label_list)\n\n filename_tensor = tf.convert_to_tensor(filename_list, dtype=tf.string)\n label_tensor = tf.convert_to_tensor(label_list, dtype=tf.int32)\n\n return filename_tensor, label_tensor\n\n def normal_data(x, y):\n with tf.variable_scope('normal_data'):\n data = tf.read_file(x)\n data = tf.image.decode_png(data, channels=3, name='decode_img')\n data = tf.image.resize_images(data, size=img_size)\n data = tf.divide(data, 255.)\n return data, y\n\n def data_loader(filename_data, label_data):\n with tf.variable_scope('data_loader'):\n dataset = tf.contrib.data.Dataset.from_tensor_slices((filename_data, label_data)).repeat()\n\n normal_dataset_map = dataset.map(normal_data).batch(batch_size)\n normal_iterator = normal_dataset_map.make_one_shot_iterator()\n normal_batch_input = normal_iterator.get_next()\n\n return normal_batch_input\n\n filename_tensor, label_tensor = get_file_names()\n normal_batch_input = data_loader(filename_tensor, label_tensor)\n\n with tf.Session() as sess:\n filename_batch = sess.run(filename_tensor)\n data_batch = sess.run(normal_batch_input)\n\n model = Model(sess=sess, is_training=self.is_training, name='model')\n model.build()\n\n if sort == 'grad_cam':\n grad_cam = GradCAM(instance=model, sample_size=sample_num * class_num)\n grad_cam.build()\n else:\n guided_cam = GuidedGradCAM(instance=model, sample_size=sample_num * class_num)\n guided_cam.build()\n\n self._saver = tf.train.Saver()\n ckpt_st = tf.train.get_checkpoint_state(os.path.join(flags.FLAGS.trained_param_path))\n\n if ckpt_st is not None:\n '''restore 시에는 tf.global_variables_initializer() 가 필요 없다.'''\n self._saver.restore(sess, ckpt_st.model_checkpoint_path)\n print('>> Model Restored')\n\n if sort == 'grad_cam':\n # 원본 영상과 Grad CAM 을 합친 결과\n grad_outputs = grad_cam.visualize(data_batch[0], filename_batch)\n save_matplot_img(grad_outputs, sample_num, class_num, 'grad_cam.png')\n else:\n guided_outputs = guided_cam.visualize(data_batch[0], filename_batch)\n save_matplot_img(guided_outputs, sample_num, class_num, 'guided_cam.png')\n\n '''텐서플로우 그래프 저장'''\n os.makedirs(os.path.join(flags.FLAGS.deploy_log_dir), exist_ok=True)\n tf.train.write_graph(sess.graph_def, flags.FLAGS.deploy_log_dir, 'graph.pbtxt')\n self._saver.save(sess, os.path.join(flags.FLAGS.deploy_log_dir, 'dementia_param'))\n\n '''PB File Save'''\n # builder = tf.saved_model.builder.SavedModelBuilder(os.path.join(flags.FLAGS.deploy_log_dir, 'dementia_cam'))\n # builder.add_meta_graph_and_variables(sess, [tf.saved_model.tag_constants.SERVING])\n # builder.save()\n\nneuralnet = Neuralnet(is_training=True)\n# neuralnet.cam_test(sort='guided_cam')\n# neuralnet.cam_test(sort='grad_cam')\nneuralnet.train()","sub_path":"Projects/DeepLearningTechniques/MobileNet_v2/iris/mobilenet_v2_main.py","file_name":"mobilenet_v2_main.py","file_ext":"py","file_size_in_byte":11159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"605339131","text":"# future\nfrom __future__ import annotations\n\n# stdlib\nimport secrets\nfrom typing import Any\nfrom typing import Callable\nfrom typing import Dict\nfrom typing import List\nfrom typing import Optional\nfrom typing import Tuple\nfrom typing import Union\n\n# third party\nimport numpy as np\nimport pandas as pd\nimport torch as th\n\n# syft absolute\nimport syft as sy\n\n# relative\nfrom ... import lib\nfrom ...ast.klass import pointerize_args_and_kwargs\nfrom ...core.adp.data_subject_ledger import DataSubjectLedger\nfrom ...util import inherit_tags\nfrom ..common.serde.capnp import CapnpModule\nfrom ..common.serde.capnp import chunk_bytes\nfrom ..common.serde.capnp import combine_bytes\nfrom ..common.serde.capnp import get_capnp_schema\nfrom ..common.serde.capnp import serde_magic_header\nfrom ..common.serde.serializable import serializable\nfrom ..common.uid import UID\nfrom ..node.abstract.node import AbstractNodeClient\nfrom ..node.common.action import smpc_action_functions\nfrom ..node.common.action.run_class_method_smpc_action import RunClassMethodSMPCAction\n\n# from ..node.domain.client import DomainClient\nfrom ..pointer.pointer import Pointer\nfrom .ancestors import PhiTensorAncestor\nfrom .autodp.gamma_tensor import GammaTensor\nfrom .autodp.gamma_tensor import TensorWrappedGammaTensorPointer\nfrom .autodp.phi_tensor import PhiTensor\nfrom .autodp.phi_tensor import TensorWrappedPhiTensorPointer\nfrom .config import DEFAULT_FLOAT_NUMPY_TYPE\nfrom .config import DEFAULT_INT_NUMPY_TYPE\nfrom .fixed_precision_tensor_ancestor import FixedPrecisionTensorAncestor\nfrom .passthrough import PassthroughTensor # type: ignore\nfrom .smpc import context\nfrom .smpc import utils\nfrom .smpc.mpc_tensor import MPCTensor\n\n\nclass TensorPointer(Pointer):\n\n # Must set these at class init time despite\n # the fact that klass.Class tries to override them (unsuccessfully)\n __name__ = \"TensorPointer\"\n __module__ = \"syft.core.tensor.tensor\"\n\n def __init__(\n self,\n client: Any,\n id_at_location: Optional[UID] = None,\n object_type: str = \"\",\n tags: Optional[List[str]] = None,\n description: str = \"\",\n public_shape: Optional[Tuple[int, ...]] = None,\n public_dtype: Optional[Union[str, np.dtype]] = None,\n ):\n\n super().__init__(\n client=client,\n id_at_location=id_at_location,\n object_type=object_type,\n tags=tags,\n description=description,\n )\n\n self.public_shape = public_shape\n\n if isinstance(public_dtype, str):\n self.public_dtype = np.dtype(public_dtype)\n else:\n self.public_dtype = public_dtype\n\n def share(self, *parties: Tuple[AbstractNodeClient, ...]) -> MPCTensor:\n all_parties = list(parties) + [self.client]\n ring_size = utils.TYPE_TO_RING_SIZE.get(self.public_dtype, None)\n self_mpc = MPCTensor(\n secret=self,\n shape=self.public_shape,\n parties=all_parties,\n ring_size=ring_size,\n )\n return self_mpc\n\n def _apply_tensor_op(\n self,\n other: Any,\n op_str: str,\n *args: Tuple[Any, ...],\n **kwargs: Any,\n ) -> Any:\n # we want to get the return type which matches the attr_path_and_name\n # so we ask lib_ast for the return type name that matches out\n # attr_path_and_name and then use that to get the actual pointer klass\n # then set the result to that pointer klass\n\n op = f\"__{op_str}__\" if op_str != \"concatenate\" else \"concatenate\"\n # remove this to dunder method before merge.\n attr_path_and_name = f\"syft.core.tensor.tensor.Tensor.{op}\"\n seed_id_locations = kwargs.pop(\"seed_id_locations\", None)\n if seed_id_locations is None:\n seed_id_locations = secrets.randbits(64)\n\n id_at_location = smpc_action_functions.get_id_at_location_from_op(\n seed_id_locations, op\n )\n\n # QUESTION can the id_at_location be None?\n result_id_at_location = id_at_location\n\n result = TensorPointer(client=self.client)\n result.id_at_location = result_id_at_location\n\n if result_id_at_location is not None:\n # first downcast anything primitive which is not already PyPrimitive\n (\n downcast_args,\n downcast_kwargs,\n ) = lib.python.util.downcast_args_and_kwargs(\n args=[self, other], kwargs=kwargs\n )\n\n # then we convert anything which isnt a pointer into a pointer\n pointer_args, pointer_kwargs = pointerize_args_and_kwargs(\n args=downcast_args,\n kwargs=downcast_kwargs,\n client=self.client,\n gc_enabled=False,\n )\n\n cmd = RunClassMethodSMPCAction(\n path=attr_path_and_name,\n _self=self,\n args=pointer_args,\n kwargs=pointer_kwargs,\n id_at_location=result_id_at_location,\n seed_id_locations=seed_id_locations,\n address=self.client.address,\n )\n self.client.send_immediate_msg_without_reply(msg=cmd)\n\n inherit_tags(\n attr_path_and_name=attr_path_and_name,\n result=result,\n self_obj=self,\n args=[other],\n kwargs={},\n )\n\n result_public_shape = None\n result_public_dtype = None\n\n if isinstance(other, TensorPointer):\n other_shape = other.public_shape\n other_dtype = other.public_dtype\n elif isinstance(other, (int, float)):\n other_shape = (1,)\n other_dtype = np.int32\n elif isinstance(other, bool):\n other_shape = (1,)\n other_dtype = np.dtype(\"bool\")\n elif isinstance(other, np.ndarray):\n other_shape = other.shape\n other_dtype = other.dtype\n\n else:\n raise ValueError(f\"Invalid Type for TensorPointer:{type(other)}\")\n\n if self.public_shape is not None and other_shape is not None:\n result_public_shape = utils.get_shape(\n op_str, self.public_shape, other_shape\n )\n\n if self.public_dtype is not None and other_dtype is not None:\n if self.public_dtype != other_dtype:\n raise ValueError(\n f\"Type for self and other do not match ({self.public_dtype} vs {other_dtype})\"\n )\n result_public_dtype = self.public_dtype\n\n result.public_shape = result_public_shape\n result.public_dtype = result_public_dtype\n\n return result\n\n @staticmethod\n def _apply_op(\n self: TensorPointer,\n other: Union[TensorPointer, MPCTensor, int, float, np.ndarray],\n op_str: str,\n **kwargs: Dict[str, Any],\n ) -> Union[MPCTensor, TensorPointer]:\n \"\"\"Performs the operation based on op_str\n\n Args:\n other (Union[TensorPointer,MPCTensor,int,float,np.ndarray]): second operand.\n\n Returns:\n Tuple[MPCTensor,Union[MPCTensor,int,float,np.ndarray]] : Result of the operation\n \"\"\"\n if isinstance(other, TensorPointer) and self.client != other.client:\n parties = [self.client, other.client]\n self_mpc = MPCTensor(secret=self, shape=self.public_shape, parties=parties)\n other_mpc = MPCTensor(\n secret=other, shape=other.public_shape, parties=parties\n )\n func = getattr(self_mpc, op_str)\n return func(other_mpc)\n elif isinstance(other, MPCTensor):\n # \"self\" should be secretly shared\n other_mpc, self_mpc = MPCTensor.sanity_checks(other, self)\n func = getattr(self_mpc, op_str)\n return func(other_mpc)\n\n return self._apply_tensor_op(other=other, op_str=op_str, **kwargs)\n\n def __add__(\n self,\n other: Union[TensorPointer, MPCTensor, int, float, np.ndarray],\n **kwargs: Dict[str, Any],\n ) -> Union[TensorPointer, MPCTensor]:\n \"\"\"Apply the \"add\" operation between \"self\" and \"other\"\n\n Args:\n y (Union[TensorPointer,MPCTensor,int,float,np.ndarray]) : second operand.\n\n Returns:\n Union[TensorPointer,MPCTensor] : Result of the operation.\n \"\"\"\n return TensorPointer._apply_op(self, other, \"add\", **kwargs)\n\n def __sub__(\n self,\n other: Union[TensorPointer, MPCTensor, int, float, np.ndarray],\n **kwargs: Dict[str, Any],\n ) -> Union[TensorPointer, MPCTensor]:\n \"\"\"Apply the \"sub\" operation between \"self\" and \"other\"\n\n Args:\n y (Union[TensorPointer,MPCTensor,int,float,np.ndarray]) : second operand.\n\n Returns:\n Union[TensorPointer,MPCTensor] : Result of the operation.\n \"\"\"\n return TensorPointer._apply_op(self, other, \"sub\", **kwargs)\n\n def __mul__(\n self,\n other: Union[TensorPointer, MPCTensor, int, float, np.ndarray],\n **kwargs: Dict[str, Any],\n ) -> Union[TensorPointer, MPCTensor]:\n \"\"\"Apply the \"mul\" operation between \"self\" and \"other\"\n\n Args:\n y (Union[TensorPointer,MPCTensor,int,float,np.ndarray]) : second operand.\n\n Returns:\n Union[TensorPointer,MPCTensor] : Result of the operation.\n \"\"\"\n return TensorPointer._apply_op(self, other, \"mul\", **kwargs)\n\n def __matmul__(\n self,\n other: Union[TensorPointer, MPCTensor, int, float, np.ndarray],\n **kwargs: Dict[str, Any],\n ) -> Union[TensorPointer, MPCTensor]:\n \"\"\"Apply the \"matmul\" operation between \"self\" and \"other\"\n\n Args:\n y (Union[TensorPointer,MPCTensor,int,float,np.ndarray]) : second operand.\n\n Returns:\n Union[TensorPointer,MPCTensor] : Result of the operation.\n \"\"\"\n return TensorPointer._apply_op(self, other, \"matmul\", **kwargs)\n\n def __truediv__(\n self,\n other: Union[TensorPointer, MPCTensor, int, float, np.ndarray],\n **kwargs: Dict[str, Any],\n ) -> Union[TensorPointer, MPCTensor]:\n \"\"\"Apply the \"mul\" operation between \"self\" and \"other\"\n\n Args:\n y (Union[TensorPointer,MPCTensor,int,float,np.ndarray]) : second operand.\n\n Returns:\n Union[TensorPointer,MPCTensor] : Result of the operation.\n \"\"\"\n return TensorPointer._apply_op(self, other, \"truediv\", **kwargs)\n\n def __rtruediv__(\n self,\n other: Union[TensorPointer, MPCTensor, int, float, np.ndarray],\n **kwargs: Dict[str, Any],\n ) -> Union[TensorPointer, MPCTensor]:\n \"\"\"Apply the \"mul\" operation between \"self\" and \"other\"\n\n Args:\n y (Union[TensorPointer,MPCTensor,int,float,np.ndarray]) : second operand.\n\n Returns:\n Union[TensorPointer,MPCTensor] : Result of the operation.\n \"\"\"\n raise NotImplementedError\n\n def __lt__(\n self, other: Union[TensorPointer, MPCTensor, int, float, np.ndarray]\n ) -> Union[TensorPointer, MPCTensor]:\n \"\"\"Apply the \"lt\" operation between \"self\" and \"other\"\n\n Args:\n y (Union[TensorPointer,MPCTensor,int,float,np.ndarray]) : second operand.\n\n Returns:\n Union[TensorPointer,MPCTensor] : Result of the operation.\n \"\"\"\n\n return TensorPointer._apply_op(self, other, \"lt\")\n\n def __gt__(\n self, other: Union[TensorPointer, MPCTensor, int, float, np.ndarray]\n ) -> Union[TensorPointer, MPCTensor]:\n \"\"\"Apply the \"gt\" operation between \"self\" and \"other\"\n\n Args:\n y (Union[TensorPointer,MPCTensor,int,float,np.ndarray]) : second operand.\n\n Returns:\n Union[TensorPointer,MPCTensor] : Result of the operation.\n \"\"\"\n\n return TensorPointer._apply_op(self, other, \"gt\")\n\n def __ge__(\n self, other: Union[TensorPointer, MPCTensor, int, float, np.ndarray]\n ) -> Union[TensorPointer, MPCTensor]:\n \"\"\"Apply the \"ge\" operation between \"self\" and \"other\"\n\n Args:\n y (Union[TensorPointer,MPCTensor,int,float,np.ndarray]) : second operand.\n\n Returns:\n Union[TensorPointer,MPCTensor] : Result of the operation.\n \"\"\"\n\n return TensorPointer._apply_op(self, other, \"ge\")\n\n def __le__(\n self, other: Union[TensorPointer, MPCTensor, int, float, np.ndarray]\n ) -> Union[TensorPointer, MPCTensor]:\n \"\"\"Apply the \"le\" operation between \"self\" and \"other\"\n\n Args:\n y (Union[TensorPointer,MPCTensor,int,float,np.ndarray]) : second operand.\n\n Returns:\n Union[TensorPointer,MPCTensor] : Result of the operation.\n \"\"\"\n\n return TensorPointer._apply_op(self, other, \"le\")\n\n def __eq__( # type: ignore\n self, other: Union[TensorPointer, MPCTensor, int, float, np.ndarray]\n ) -> Union[TensorPointer, MPCTensor]:\n \"\"\"Apply the \"eq\" operation between \"self\" and \"other\"\n\n Args:\n y (Union[TensorPointer,MPCTensor,int,float,np.ndarray]) : second operand.\n\n Returns:\n Union[TensorPointer,MPCTensor] : Result of the operation.\n \"\"\"\n\n return TensorPointer._apply_op(self, other, \"eq\")\n\n def __ne__( # type: ignore\n self, other: Union[TensorPointer, MPCTensor, int, float, np.ndarray]\n ) -> Union[TensorPointer, MPCTensor]:\n \"\"\"Apply the \"ne\" operation between \"self\" and \"other\"\n\n Args:\n y (Union[TensorPointer,MPCTensor,int,float,np.ndarray]) : second operand.\n\n Returns:\n Union[TensorPointer,MPCTensor] : Result of the operation.\n \"\"\"\n\n return TensorPointer._apply_op(self, other, \"ne\")\n\n def concatenate(\n self,\n other: TensorPointer,\n *args: List[Any],\n **kwargs: Dict[str, Any],\n ) -> Union[TensorPointer, MPCTensor]:\n \"\"\"Apply the \"add\" operation between \"self\" and \"other\"\n\n Args:\n y (Union[TensorPointer,MPCTensor,int,float,np.ndarray]) : second operand.\n\n Returns:\n Union[TensorPointer,MPCTensor] : Result of the operation.\n \"\"\"\n return TensorPointer._apply_op(self, other, \"concatenate\")\n\n\ndef to32bit(np_array: np.ndarray, verbose: bool = True) -> np.ndarray:\n\n if np_array.dtype == np.int64:\n if verbose:\n print(\"Casting internal tensor to int32\")\n out = np_array.astype(np.int32)\n\n elif np_array.dtype == np.float64:\n\n if verbose:\n print(\"Casting internal tensor to float32\")\n out = np_array.astype(np.float32)\n\n else:\n out = np_array\n\n return out\n\n\n@serializable(capnp_bytes=True)\nclass Tensor(\n PassthroughTensor,\n PhiTensorAncestor,\n FixedPrecisionTensorAncestor,\n # MPCTensorAncestor,\n):\n\n # __attr_allowlist__ = [\"child\", \"tag_name\", \"public_shape\", \"public_dtype\"]\n\n PointerClassOverride = TensorPointer\n\n def __init__(\n self,\n child: Any,\n public_shape: Optional[Tuple[int, ...]] = None,\n public_dtype: Optional[str] = None,\n ) -> None:\n \"\"\"data must be a list of numpy array\"\"\"\n\n if isinstance(child, list) or np.isscalar(child):\n child = np.array(child)\n\n if isinstance(child, th.Tensor):\n print(\n \"Converting PyTorch tensor to numpy tensor for internal representation...\"\n )\n child = child.numpy()\n\n # Added for convenience- might need to double check if dtype changes?\n if isinstance(child, pd.Series):\n child = child.to_numpy()\n\n if (\n not isinstance(child, PassthroughTensor)\n and not isinstance(child, np.ndarray)\n and not isinstance(child, GammaTensor)\n ):\n\n raise Exception(\n f\"Data: {child} ,type: {type(child)} must be list or nd.array \"\n )\n\n # Temp fix for windows\n if getattr(child, \"dtype\", None):\n if \"int\" in str(child.dtype) and \"64\" not in str(child.dtype):\n child = child.astype(DEFAULT_INT_NUMPY_TYPE) # type: ignore\n if \"float\" in str(child.dtype) and \"64\" not in str(child.dtype):\n child = child.astype(DEFAULT_FLOAT_NUMPY_TYPE) # type: ignore\n\n if not isinstance(child, (np.ndarray, PassthroughTensor, GammaTensor)) or (\n getattr(child, \"dtype\", None)\n not in [DEFAULT_INT_NUMPY_TYPE, DEFAULT_FLOAT_NUMPY_TYPE, np.bool_]\n and getattr(child, \"dtype\", None) is not None\n ):\n raise TypeError(\n \"You tried to pass an a tensor of type:\"\n + str(type(child))\n + \" with child.dtype == \"\n + str(getattr(child, \"dtype\", None))\n + \". Syft tensor objects only supports numpy objects of \"\n + f\"{DEFAULT_INT_NUMPY_TYPE,DEFAULT_FLOAT_NUMPY_TYPE,np.bool_}. \"\n + \"Please pass in either the supported types or change the default types in syft/core/tensor/config.py \"\n )\n\n kwargs = {\"child\": child}\n super().__init__(**kwargs)\n\n # set public shape to be the shape of the data since we have access to it at present\n if public_shape is None:\n public_shape = tuple(self.shape)\n\n # set public dtype to be the dtype of the data since we have access to it at present\n if public_dtype is None:\n public_dtype = str(self.dtype)\n\n self.tag_name: str = \"\"\n self.public_shape = public_shape\n self.public_dtype = public_dtype\n\n def tag(self, name: str) -> Tensor:\n self.tag_name = name\n return self\n\n def exp(self) -> Tensor:\n if hasattr(self.child, \"exp\"):\n return self.__class__(self.child.exp())\n else:\n raise ValueError(\"Tensor Chain does not have exp function\")\n\n def reciprocal(self) -> Tensor:\n if hasattr(self.child, \"reciprocal\"):\n return self.__class__(self.child.reciprocal())\n else:\n raise ValueError(\"Tensor Chain does not have reciprocal function\")\n\n def softmax(self) -> Tensor:\n if hasattr(self.child, \"softmax\"):\n return self.__class__(self.child.softmax())\n else:\n raise ValueError(\"Tensor Chain does not have softmax function\")\n\n def one_hot(self) -> Tensor:\n if hasattr(self.child, \"one_hot\"):\n return self.__class__(self.child.one_hot())\n else:\n raise ValueError(\"Tensor Chain does not have one_hot function\")\n\n @property\n def shape(self) -> Tuple[Any, ...]:\n try:\n return self.child.shape\n except Exception: # nosec\n return self.public_shape\n\n @property\n def proxy_public_kwargs(self) -> Dict[str, Any]:\n return {\"public_shape\": self.public_shape, \"public_dtype\": self.public_dtype}\n\n def init_pointer(\n self,\n client: Any,\n id_at_location: Optional[UID] = None,\n object_type: str = \"\",\n tags: Optional[List[str]] = None,\n description: str = \"\",\n ) -> Pointer:\n # relative\n\n if isinstance(self.child, PhiTensor):\n return TensorWrappedPhiTensorPointer(\n data_subjects=self.child.data_subjects,\n client=client,\n id_at_location=id_at_location,\n object_type=object_type,\n tags=tags,\n description=description,\n min_vals=self.child.min_vals,\n max_vals=self.child.max_vals,\n public_shape=getattr(self, \"public_shape\", None),\n public_dtype=getattr(self, \"public_dtype\", None),\n )\n elif isinstance(self.child, GammaTensor):\n return TensorWrappedGammaTensorPointer(\n data_subjects=self.child.data_subjects,\n client=client,\n id_at_location=id_at_location,\n object_type=object_type,\n tags=tags,\n description=description,\n min_vals=self.child.min_vals,\n max_vals=self.child.max_vals,\n public_shape=getattr(self, \"public_shape\", None),\n public_dtype=getattr(self, \"public_dtype\", None),\n )\n else:\n return TensorPointer(\n client=client,\n id_at_location=id_at_location,\n object_type=object_type,\n tags=tags,\n description=description,\n public_shape=getattr(self, \"public_shape\", None),\n public_dtype=getattr(self, \"public_dtype\", None),\n )\n\n def publish(\n self,\n get_budget_for_user: Callable,\n deduct_epsilon_for_user: Callable,\n ledger: DataSubjectLedger,\n sigma: float,\n ) -> Any:\n return self.child.publish(\n get_budget_for_user, deduct_epsilon_for_user, ledger, sigma\n )\n\n # TODO: remove after moving private compare to sharetensor level\n def bit_decomposition(self, ring_size: Union[int, str], bitwise: bool) -> None:\n context.tensor_values = self\n if isinstance(self.child, PhiTensor):\n self.child.child.child.bit_decomposition(ring_size, bitwise)\n else:\n self.child.bit_decomposition(ring_size, bitwise)\n\n return None\n\n def mpc_swap(self, other: Tensor) -> Tensor:\n self.child.child = other.child.child\n return self\n\n def _object2bytes(self) -> bytes:\n schema = get_capnp_schema(schema_file=\"tensor.capnp\")\n tensor_struct: CapnpModule = schema.Tensor # type: ignore\n tensor_msg = tensor_struct.new_message()\n\n # this is how we dispatch correct deserialization of bytes\n tensor_msg.magicHeader = serde_magic_header(type(self))\n\n chunk_bytes(sy.serialize(self.child, to_bytes=True), \"child\", tensor_msg)\n\n tensor_msg.publicShape = sy.serialize(self.public_shape, to_bytes=True)\n\n # upcast the String class before setting to capnp\n public_dtype_func = getattr(\n self.public_dtype, \"upcast\", lambda: self.public_dtype\n )\n tensor_msg.publicDtype = public_dtype_func()\n tensor_msg.tagName = self.tag_name\n\n return tensor_msg.to_bytes_packed()\n\n @staticmethod\n def _bytes2object(buf: bytes) -> Tensor:\n schema = get_capnp_schema(schema_file=\"tensor.capnp\")\n tensor_struct: CapnpModule = schema.Tensor # type: ignore\n # https://stackoverflow.com/questions/48458839/capnproto-maximum-filesize\n MAX_TRAVERSAL_LIMIT = 2**64 - 1\n tensor_msg = tensor_struct.from_bytes_packed(\n buf, traversal_limit_in_words=MAX_TRAVERSAL_LIMIT\n )\n\n tensor = Tensor(\n child=sy.deserialize(combine_bytes(tensor_msg.child), from_bytes=True),\n public_shape=sy.deserialize(tensor_msg.publicShape, from_bytes=True),\n public_dtype=tensor_msg.publicDtype,\n )\n tensor.tag_name = tensor_msg.tagName\n\n return tensor\n","sub_path":"packages/syft/src/syft/core/tensor/tensor.py","file_name":"tensor.py","file_ext":"py","file_size_in_byte":23167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"143978447","text":"import subprocess,os\n\nclass cd:\n \"\"\"Context manager for changing the current working directory\"\"\"\n def __init__(self, newPath):\n self.newPath = os.path.expanduser(newPath)\n\n def __enter__(self):\n self.savedPath = os.getcwd()\n os.chdir(self.newPath)\n\n def __exit__(self, etype, value, traceback):\n os.chdir(self.savedPath)\n\nfolders = os.listdir()\ndont = [\"ignore\",\"sync.py\"]\nfor me in dont:\n if me in folders:\n folders.remove(me)\n\nfor folder in folders:\n # enter the directory like this:\n with cd(folder):\n os.system(\"git pull\")\n os.system(\"git add *\")\n os.system(\"git commit -m 'Auto'\")\n os.system(\"git push\")\n os.system(\"rmdir /q /s \" + folder)\n","sub_path":"remote_and_delete.py","file_name":"remote_and_delete.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"87444849","text":"from django.shortcuts import render\nfrom .models import *\nfrom django.http import JsonResponse\nimport json\n\n\ndef course_category(request):\n courses = Category.objects.all()\n category=[]\n for course in courses:\n Question_category={}\n Question_category['id']=course.id\n Question_category['category'] = course.category\n category.append(Question_category)\n return JsonResponse(category,safe=False)\n\n\ndef questions(request, id):\n all_questions = Question.objects.filter(category=id)[:10]\n results = []\n\n for raw_question in all_questions:\n\n question = {}\n question['id'] = raw_question.id\n question['category'] = raw_question.category.category\n question['question'] = raw_question.question\n question['correct_answer'] = raw_question.correct_answer\n options = []\n options.append(raw_question.option_one)\n options.append(raw_question.option_two)\n if raw_question.option_three != '':\n options.append(raw_question.option_three)\n\n if raw_question.option_four != '':\n options.append(raw_question.option_four)\n\n question['options'] = options\n results.append(question)\n\n\n\n return JsonResponse(results, safe=False)\n","sub_path":"questions/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"126953736","text":"import numpy as np\r\nimport talib as ta\r\nimport pandas as pd\r\nimport datetime as dt\r\n\r\n\r\ndef init(context):\r\n scheduler.run_monthly(pick_stocks,tradingday = 1,time_rule = 'before_trading')\r\n scheduler.run_weekly(rebalance,weekday = 3)\r\n # 调仓参数\r\n context.hold_cycle = 21\r\n context.hold_periods = 0\r\n context.stock_list = []\r\n \r\n\r\n\r\n # 分配策略的市值比例\r\n context.FFScore_ratio = 1.0\r\n # 上市不足 60 天的剔除掉\r\n\r\n\r\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~每天开盘前~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\ndef before_trading(context):\r\n pass \r\n\r\ndef pick_stocks(context,bar_dict):\r\n ##---------------筛选前1000支股票--------------\r\n num_stocks = 1000\r\n fundamental_df = get_fundamentals(\r\n query(\r\n fundamentals.eod_derivative_indicator.market_cap\r\n ).order_by(fundamentals.eod_derivative_indicator.market_cap).limit(num_stocks))\r\n \r\n universe = filter_paused_stock(list(fundamental_df.columns))\r\n\r\n ##--------------开始筛选白马股---------------------##\r\n ## 每股收益 0.25\r\n EPS_df = get_fundamentals(\r\n query(\r\n fundamentals.income_statement.basic_earnings_per_share\r\n ).filter(\r\n fundamentals.income_statement.stockcode.in_(universe)\r\n )\r\n )\r\n EPS_df = EPS_df.T\r\n EPS_df[EPS_df.basic_earnings_per_share>=0.25] = 2\r\n EPS_df[EPS_df.basic_earnings_per_share<0.25] = 0\r\n EPS_df = EPS_df.fillna(value=0) \r\n \r\n ## 每股净资产 3.00\r\n VPS_df = get_fundamentals(\r\n query(\r\n fundamentals.financial_indicator.book_value_per_share\r\n ).filter(\r\n fundamentals.financial_indicator.stockcode.in_(universe)\r\n )\r\n )\r\n VPS_df = VPS_df.T\r\n VPS_df[VPS_df.book_value_per_share>=3] = 1\r\n VPS_df[VPS_df.book_value_per_share<3] = 0\r\n VPS_df = VPS_df.fillna(value=0) \r\n \r\n ## 净资产收益率 10%\r\n ROE_df = get_fundamentals(\r\n query(\r\n fundamentals.financial_indicator.return_on_equity\r\n ).filter(\r\n fundamentals.financial_indicator.stockcode.in_(universe)\r\n )\r\n )\r\n ROE_df = ROE_df.T\r\n ROE_df[ROE_df.return_on_equity>=0.10] = 1\r\n ROE_df[ROE_df.return_on_equity<0.10] = 0\r\n ROE_df = ROE_df.fillna(value=0)\r\n \r\n ## 主营业务收入增长率 30%\r\n # 读取今年的数据\r\n OR_df_new = get_fundamentals(\r\n query(\r\n fundamentals.income_statement.operating_revenue\r\n ).filter(\r\n fundamentals.income_statement.stockcode.in_(universe)\r\n )\r\n )\r\n OR_df_new = OR_df_new.T\r\n # 读取去年的数据\r\n OR_df_old = get_fundamentals(\r\n query(\r\n fundamentals.income_statement.operating_revenue\r\n ).filter(\r\n fundamentals.income_statement.stockcode.in_(universe)\r\n ),entry_date = context.now.date() - dt.timedelta(366)\r\n )\r\n OR_df_old = OR_df_old.T\r\n ORR_df = (OR_df_new - OR_df_old) / OR_df_old\r\n ORR_df[ORR_df.operating_revenue>=0.30] = 1\r\n ORR_df[ORR_df.operating_revenue<0.30] = 0\r\n ORR_df = ORR_df.fillna(value=0) \r\n \r\n ## 净利润增长率 30% ==> 扣除非经常损益得同比增长率\r\n IDNF_df = get_fundamentals(\r\n query(\r\n fundamentals.financial_indicator.inc_adjusted_net_profit\r\n ).filter(\r\n fundamentals.financial_indicator.stockcode.in_(universe)\r\n )\r\n )\r\n IDNF_df = IDNF_df.T\r\n IDNF_df[IDNF_df.inc_adjusted_net_profit>=30] = 1\r\n IDNF_df[IDNF_df.inc_adjusted_net_profit<30] = 0\r\n IDNF_df = IDNF_df.fillna(value=0) \r\n \r\n ## 市盈率 50倍(待定)\r\n ##-------------最后把所有的表格接到一起,计算排序,选出得分最高的股票\r\n total_df = pd.concat([EPS_df,VPS_df,ROE_df,ORR_df,IDNF_df],axis = 1)\r\n total_df['score'] = EPS_df['basic_earnings_per_share'] + VPS_df['book_value_per_share'] + ROE_df['return_on_equity'] + ORR_df['operating_revenue'] + IDNF_df['inc_adjusted_net_profit']\r\n total_df = total_df.sort(['score'], ascending=[False])\r\n context.stocks= list(total_df[total_df.score >= 4].index)\r\n logger.info(context.stocks)\r\n print(context.stocks)\r\n \r\n# 过滤停牌股票\r\ndef filter_paused_stock(stock_list):\r\n return [stock for stock in stock_list if not is_suspended(stock)]\r\n\r\n \r\n \r\n \r\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~每天盘中~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \r\ndef rebalance(context,bar_dict):\r\n # 把当前持仓的股票,但不在今日候选列表中的做卖出处理\r\n reStock_list(context,bar_dict)\r\n context.stock_list = filter_paused_stock(context.stock_list)\r\n for stock in context.portfolio.positions.keys():\r\n if stock not in context.stock_list:\r\n #logger.info('[%s不在股票池中,平仓]',%(instruments(stock).symbol))\r\n order_target_percent(stock, 0) \r\n if len(context.stock_list) > 2: \r\n for stock in context.stock_list:\r\n order_target_percent(stock,0.98/len(context.stock_list))\r\n else:\r\n for stock in context.portfolio.positions.keys():\r\n order_target_percent(stock, 0)\r\n \r\n## 根据信号调整stock_list\r\ndef reStock_list(context,bar_dict):\r\n context.stock_list = []\r\n for stock in context.stocks:\r\n if Judge_Sell_Buy(stock) == 1:\r\n context.stock_list.append(stock)\r\n \r\n\r\n# 判断股票是否处于较好得买入时机\r\ndef Judge_Sell_Buy(order_book_id):\r\n bar_count = 15\r\n frequency = '1d'\r\n high = []\r\n low = []\r\n close = []\r\n his_inf = history_bars(order_book_id, bar_count, frequency, fields=None, skip_suspended=True, include_now=False)\r\n for i in range(len(his_inf)):\r\n high.append(his_inf[i][2])\r\n low.append(his_inf[i][3])\r\n close.append(his_inf[i][4])\r\n high = np.array(high)\r\n low = np.array(low)\r\n close = np.array(close)\r\n SAR_index =ta.SAR(high, low, acceleration=0, maximum=0)\r\n if SAR_index[-1] > close[-1]:\r\n signal = 1\r\n elif SAR_index[-1] < close[-1]:\r\n signal = -1\r\n elif SAR_index == close[-1]:\r\n if SAR_index[-1] > close[-1]:\r\n signal = -1\r\n elif SAR_index[-1] < close[-1]:\r\n signal = 1\r\n return signal\r\n \r\ndef handle_bar(context, bar_dict):\r\n pass\r\n\r\n\r\n# after_trading函数会在每天交易结束后被调用,当天只会被调用一次\r\ndef after_trading(context):\r\n pass\r\n\r\n","sub_path":"strategy/github/白马.py","file_name":"白马.py","file_ext":"py","file_size_in_byte":6553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"156621057","text":"# -*- coding: utf-8 -*-\nfrom django.db import models\nfrom south.modelsinspector import add_introspection_rules\nfrom django.utils import timezone\n\nimport json\n\nclass DeliveryScoreRangeField(models.TextField):\n description = u\"배송점수별 배송비 표. {{ field[(점수)]=(배송비) }} 일 때, (점수)이하의 점수에 대해 (배송비)가 부과됨\"\n __metaclass__ = models.SubfieldBase\n \n def to_python(self, value):\n\n if not isinstance(value, unicode):\n return value\n\n try:\n parsed_value = json.loads(value)\n except ValueError as e:\n raise e\n\n res = {}\n for k,v in parsed_value.iteritems():\n res[int(k)] = int(v)\n return res\n\n def get_prep_value(self, value):\n\n if value is None: return ''\n\n if isinstance(value,dict):\n try:\n return json.dumps(value)\n except ValueError as e :\n raise e\n else:\n return ''\n\nadd_introspection_rules([],[\"^delivery\\.models\\.DeliveryScoreRangeField\"])\n\nclass DeliveryRegionPenaltyField(models.TextField):\n description = u\"지역별 배송비 증가량 표. {{ field[(배송지)]=(배송비) }} 일 때, 주소가 (배송지)로 시작할 때, (배송비)가 부과됨\"\n __metaclass__ = models.SubfieldBase\n\n def to_python(self, value):\n if not isinstance(value, unicode):\n return value\n try:\n parsed_value = json.loads(value,encoding='utf8')\n except ValueError as e:\n raise e\n\n res = {}\n for k,v in parsed_value.iteritems():\n res[k] = int(v)\n return res\n\n def get_prep_value(self, value):\n if value is None: return ''\n\n if isinstance(value,dict):\n try:\n return json.dumps(value)\n except ValueError as e:\n raise e\n\nadd_introspection_rules([],[\"^delivery\\.models\\.DeliveryRegionPenaltyField\"])\n\n\n\nclass DeliveryPolicy(models.Model):\n name = models.CharField(max_length=30, db_index=True, verbose_name=u'배송정책 이름')\n comment = models.TextField(verbose_name=u'배송정책 설명')\n producer = models.ForeignKey('shop.Producer',verbose_name=u'생산자')\n\n score_range_producer = DeliveryScoreRangeField(blank=True,verbose_name=u'점수별 소비자 배송비',null=True)\n regional_penalty_producer = DeliveryRegionPenaltyField(blank=True,verbose_name=u'지역별 추가 소비자 배송비',null=True)\n\n score_range_customer = DeliveryScoreRangeField(blank=True,verbose_name=u'점수별 생산자 배송비',null=True)\n regional_penalty_customer = DeliveryRegionPenaltyField(blank=True,verbose_name=u'지역별 추가 생산자 배송비',null=True)\n\n multiple_delivery = models.BooleanField(verbose_name=u'반복배송',default=False)\n delivery_period = models.IntegerField(default=0,verbose_name=u'배송 주기 (주 단위)')\n delivery_repetition = models.IntegerField(default=0,verbose_name=u'배송 횟수')\n delivery_weekday = models.CommaSeparatedIntegerField(blank=True,max_length=20, null=True,verbose_name=u'배송 요일') # 배송 요일 0-월, 1-화, ..., 6-일\n\n class Meta:\n verbose_name = u'배송정책'\n verbose_name_plural = verbose_name\n\n def expand_date_to_send(self, start_date):\n if self.multiple_delivery: remaining = self.delivery_repetition\n else: remaining = 1\n\n res = []\n weekday = map(int, self.delivery_weekday.split(','))\n while remaining > 0:\n if start_date.weekday() in weekday:\n remaining -= 1\n res.append(start_date)\n start_date += timezone.timedelta(1)\n return res\n\n\n def price(self, score_customer, score_producer, primary_address):\n # 점수 테이블에 따라 배송비 계산\n res = 0 #변수 초기화\n assigned = False\n lastrng = None\n scores = self.score_range_producer.keys()\n scores.sort()\n for rng in scores:\n lastrng = rng\n if rng >= score_producer: res = self.score_range_producer[rng]; assigned = True; break\n if not assigned: res = self.score_range_producer[lastrng]\n\n\n # 무료배송이 아니라면, 제주도 등의 지역에 대한 배송비 추가\n if res > 0:\n for region in self.regional_penalty_producer.keys():\n if len(region)>0 and primary_address.startswith(region):\n res += self.regional_penalty_producer[region]\n break\n\n price_producer = res\n\n res = 0\n assigned = False\n lastrng = None\n scores = self.score_range_customer.keys()\n scores.sort()\n for rng in scores:\n lastrng = rng\n if rng >= score_customer:\n res = self.score_range_customer[rng]\n assigned = True\n break\n if not assigned: res = self.score_range_customer[lastrng]\n\n # 무료배송이 아니라면, 제주도 등의 지역에 대한 배송비 추가\n if res > 0:\n for region in self.regional_penalty_customer.keys():\n if len(region)>0 and primary_address.startswith(region):\n res += self.regional_penalty_customer[region]\n break\n\n price_customer = res\n return (price_customer, price_producer)\n \n def __unicode__(self):\n return self.name + u'[%d]' % self.id\n\n\nclass Zipcode(models.Model):\n keyword = models.CharField(max_length=14, db_index=True, verbose_name=u'검색용 키워드')\n address = models.CharField(max_length=150, db_index=True, verbose_name=u'주소')\n zipcode = models.CharField(max_length=7, verbose_name=u'우편번호')\n\n","sub_path":"src/hellonature/delivery/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"111098110","text":"#!/usr/bin/env python\n\nimport re\nimport sys\nimport json\nimport os.path\nimport subprocess\nfrom itertools import islice\nfrom collections import Counter\nfrom math import ceil\n\n\nDATA_DIR = 'data'\nDESCRIPTIONS = os.path.join(DATA_DIR, 'details.txt')\nDESCRIPTIONS_TABLE = os.path.join(DATA_DIR, 'descriptions.tsv')\nID_COLUMN = 0\nTEST = os.path.join(DATA_DIR, 'ozon_test.txt')\nSPLIT = 'split'\nTMP_TABLES_DIR = os.path.join(DATA_DIR, 'tmp')\nRESULTS = 'ozon_recoms.txt'\n\n\ndef normalize_text(text):\n text = text.lower()\n words = re.findall(r'[\\d\\w]+', text, re.U)\n text = ' '.join(words)\n return text\n\n\ndef read_descriptions(path=DESCRIPTIONS):\n with open(path) as file:\n for line in file:\n data = json.loads(line)\n id = int(data['itemid'])\n descriptions = {}\n for key, value in data.iteritems():\n match = re.match(r'attr(\\d+)', key)\n if match:\n index = int(match.group(1))\n value = normalize_text(value)\n descriptions[index] = value\n yield id, descriptions\n\n\ndef log_progress(stream, every=1000, total=None):\n if total:\n every = total / 200 # every 0.5%\n for index, record in enumerate(stream):\n if index % every == 0:\n if total:\n progress = float(index) / total\n progress = '{0:0.2f}%'.format(progress * 100)\n else:\n progress = index\n print >>sys.stderr, progress,\n yield record\n\n\ndef write_descriptions(descriptions, path=DESCRIPTIONS_TABLE):\n with open(path, 'w') as file:\n for id, description in descriptions:\n description = '\\t'.join(\n u'{index}:{value}'.format(index=index, value=value)\n for index, value in sorted(description.iteritems())\n )\n file.write(\n u'{id}\\t{description}\\n'.format(\n id=id,\n description=description\n ).encode('utf8')\n )\n\n\ndef parse_description(line):\n items = line.rstrip('\\n').split('\\t')\n id = int(items[0])\n description = {}\n for item in items[1:]:\n index, value = item.split(':', 1)\n index = int(index)\n value = value.decode('utf8')\n description[index] = value\n return id, description\n\n\ndef get_id(id, path=DESCRIPTIONS_TABLE):\n look = subprocess.Popen(\n ['look', str(id), path],\n stdout=subprocess.PIPE\n )\n for line in look.stdout:\n found, description = parse_description(line)\n if found == id:\n look.terminate()\n return description\n\n\ndef get_table_size(table):\n output = subprocess.check_output(['wc', '-l', table])\n size, _ = output.split(None, 1)\n return int(size)\n\n\ndef sort_table(table, by, chunks=20):\n if not isinstance(by, (list, tuple)):\n by = (by,)\n size = get_table_size(table) / chunks\n tmp = os.path.join(TMP_TABLES_DIR, SPLIT)\n try:\n print >>sys.stderr, ('Split in {} chunks, prefix: {}'\n .format(chunks, tmp))\n subprocess.check_call(\n ['split', '-l', str(size), table, tmp],\n env={'LC_ALL': 'C'}\n )\n ks = ['-k{0},{0}'.format(_ + 1) for _ in by]\n tmps = [os.path.join(TMP_TABLES_DIR, _)\n for _ in os.listdir(TMP_TABLES_DIR)]\n for index, chunk in enumerate(tmps):\n print >>sys.stderr, 'Sort {}/{}: {}'.format(\n index + 1, chunks, chunk\n )\n subprocess.check_call(\n ['sort', '-t', '\\t'] + ks + ['-o', chunk, chunk],\n env={'LC_ALL': 'C'}\n )\n print >>sys.stderr, 'Merge into', table\n subprocess.check_call(\n ['sort', '-t', '\\t'] + ks + ['-m'] + tmps + ['-o', table],\n env={'LC_ALL': 'C'}\n )\n finally:\n for name in os.listdir(TMP_TABLES_DIR):\n path = os.path.join(TMP_TABLES_DIR, name)\n os.remove(path)\n\n\ndef get_text_similarity(left, right):\n left = set(left.split())\n right = set(right.split())\n return float(len(left & right)) / len(left | right)\n\n\ndef get_descriptions_similarity(left, right):\n if left.viewkeys() == right.viewkeys():\n sum = 0\n count = 0\n for index in left:\n sum += get_text_similarity(left[index], right[index])\n count += 1\n return sum / count\n\n\ndef read_test(path=TEST):\n with open(path) as file:\n for line in file:\n data = json.loads(line)\n id = int(data['item'])\n yield id\n\n\ndef read_normal_descriptions(path=DESCRIPTIONS_TABLE):\n with open(path) as file:\n for line in file:\n try:\n id, description = parse_description(line)\n except ValueError:\n pass\n else:\n yield id, description\n\n\ndef get_similar_descriptions(description, descriptions):\n similarities = Counter()\n for id, candidate in descriptions:\n if candidate:\n similarity = get_descriptions_similarity(description, candidate)\n similarities[id] = similarity\n return similarities\n\n\ndef make_result(id, similarities, top=1000):\n recoms = {}\n for item, similarity in similarities.most_common(top):\n recoms[str(item)] = int(ceil(similarity * 100))\n return {\n 'item': str(id),\n 'recoms': recoms\n }\n\n\ndef make_results(ids, similarities):\n for id in ids:\n similarity = similarities.get(id, Counter())\n yield make_result(id, similarity)\n\n\ndef write_results(results, path=RESULTS):\n with open(path, 'w') as file:\n for result in results:\n file.write(json.dumps(result) + '\\n')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"22271301","text":"import os\nimport sqlite3\nfrom flask import Flask, request, session, g, redirect, url_for, \\\n abort, render_template, flash\n\nfrom venmo import VenmoClient, VenmoExpiredToken\nimport simplejson\nimport phonenumbers\n\napp = Flask(__name__)\nCLIENT_ID = 1377\nSCOPES = \"make_payments,access_profile,access_friends\"\napp.secret_key = os.urandom(24)\n\nCLIENT_SECRET = os.environ.get('VENMOCSV_CLIENT_SECRET')\nENVIRONMENT = os.environ.get('VENMOCSV_ENVIRONMENT')\n\ndef _login_user(access_token):\n session['access_token'] = access_token\n session['logged_in'] = True\n\ndef _login_with_token_or_code():\n if ENVIRONMENT == 'PRODUCTION':\n code = request.args.get('code')\n if code:\n access_token = VenmoClient.get_access_token_from_code(code, CLIENT_ID, CLIENT_SECRET)\n if access_token:\n _login_user(access_token)\n\n else:\n access_token = request.args.get('access_token')\n if access_token:\n _login_user(access_token)\n \n@app.route('/')\ndef main():\n _login_with_token_or_code() \n response_type = \"code\" if ENVIRONMENT == 'PRODUCTION' else \"token\"\n authorization_url = VenmoClient.get_authorization_url(CLIENT_ID, SCOPES, response_type=response_type)\n return render_template('index.html', authorization_url=authorization_url)\n\n@app.route('/upload_csv', methods=['POST'])\ndef upload_csv():\n if not logged_in():\n return logout()\n\n file = request.files.get('file')\n if not file:\n raise\n else:\n payments_list = _parse_file(file)\n\n return render_template('confirm_payments.html', payments=payments_list)\n\ndef _pay_phone(phone, amount, note, audience='public'):\n #makes payment and returns response\n access_token = session.get('access_token')\n if not access_token:\n return logout()\n client = VenmoClient(access_token)\n\n try:\n response = client.make_payment(amount=amount, note=note, audience=audience, phone=phone)\n except VenmoExpiredToken:\n return logout()\n \n return response\n \n\n@app.route(\"/ajax/pay_phone\", methods=['POST'])\ndef pay_phone_endpoint():\n if not logged_in():\n return logout()\n\n note = request.form.get('note')\n amount = request.form.get('amount')\n phone = request.form.get('phone')\n if not phone or not amount or not note:\n _return_home_with_error(\"Something went wrong. Try again\")\n \n response = _pay_phone(phone, amount, note)\n response_dict = simplejson.loads(response)\n if response_dict.get('error'):\n raise Exception(response)\n\n return response \n\ndef _return_home_with_error(message):\n pass\n\ndef logged_in():\n if session.get('logged_in'):\n return True\n return False\n\n@app.route('/logout')\ndef logout_endpoint():\n return logout()\n\ndef logout():\n session.pop('access_token', None)\n session.pop('logged_in', None)\n return redirect('/?state=logged_out')\n\ndef _parse_file(file):\n #returns list of payments\n payments_list = []\n for line in file.readlines():\n cols = line.split(',')\n phone_number = cols[0]\n\n try:\n pnum = phonenumbers.parse(phone_number, \"US\")\n phone_number = int(\"{0}{1}\".format(pnum.country_code, pnum.national_number))\n except:\n continue\n\n if phone_number:\n payment_dict = {'phone':phone_number}\n payments_list.append(payment_dict)\n\n return payments_list\n\n \nif __name__ == '__main__':\n app.run()\n","sub_path":"venmocsv.py","file_name":"venmocsv.py","file_ext":"py","file_size_in_byte":3490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"449296699","text":"import test_cases as tc\n\nVICE_URL = \"https://www.vice.com/en_us\"\n\n\ndef test_kuid_article(proxy, driver):\n name = 'vice_article_kuid'\n tc.capture_requests(proxy, name)\n driver.get(VICE_URL)\n tc.select_article(driver)\n tc.verify_kuid(proxy, name)\n\n\ndef test_ksg_article(proxy, driver):\n name = 'vice_article_ksg'\n tc.capture_requests(proxy, name)\n driver.get(VICE_URL)\n tc.select_article(driver)\n tc.verify_ksg(proxy, name)\n","sub_path":"smoke/test_krux.py","file_name":"test_krux.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"527465384","text":"# encoding: utf-8\nimport csv\nimport requests\n\ndef get_gtfs_list_from_transport_datagouv_api():\n import json\n\n url = 'https://transport.data.gouv.fr/api/datasets'\n resp = requests.get(url)\n\n gtfs_sources = []\n for dataset in resp.json():\n for resource in dataset['resources']:\n gtfs = {}\n gtfs[\"ID\"] = dataset.get('datagouv_id', None)\n gtfs[\"Licence\"] = \"\"\n gtfs[\"Source link\"] = resource.get('url', None)\n gtfs[\"Description\"] = dataset['title'] + resource.get('title', None)\n gtfs[\"Download\"] = resource.get('url', None)\n\n gtfs_sources.append(gtfs)\n return gtfs_sources\n\ndef get_gtfs_list_from_transport_datagouv_rss_feed():\n import xml.etree.ElementTree as ET\n url = 'https://transport.data.gouv.fr/atom.xml'\n resp = requests.get(url)\n root = ET.fromstring(resp.content)\n\n gtfs_sources = []\n\n for a_gtfs in root.findall('{http://www.w3.org/2005/Atom}entry'):\n gtfs = {}\n gtfs[\"ID\"] = a_gtfs.find('{http://www.w3.org/2005/Atom}id').text.split('/')[-1]\n gtfs[\"Licence\"] = \"\"\n gtfs[\"Source link\"] = a_gtfs.find('{http://www.w3.org/2005/Atom}id').text\n gtfs[\"Description\"] = a_gtfs.find('{http://www.w3.org/2005/Atom}title').text\n gtfs[\"Download\"] = a_gtfs.find('{http://www.w3.org/2005/Atom}link').attrib['href']\n\n gtfs_sources.append(gtfs)\n return gtfs_sources\n\ndef get_gtfs_list_from_navitia_io():\n navitiaio_sources = [\n \"https://navitia.opendatasoft.com/explore/dataset/fr-se/download/?format=json&timezone=Europe/Berlin\",\n \"https://navitia.opendatasoft.com/explore/dataset/fr-sw/download/?format=json&timezone=Europe/Berlin\",\n \"https://navitia.opendatasoft.com/explore/dataset/fr-ne/download/?format=json&timezone=Europe/Berlin\",\n \"https://navitia.opendatasoft.com/explore/dataset/fr-nw/download/?format=json&timezone=Europe/Berlin\"\n ]\n\n gtfs_sources = []\n for source in navitiaio_sources:\n json_list = requests.get(source).json()\n for dataset in json_list:\n #if dataset['fields']['type_file'] != \"provider\" : continue\n if dataset['fields']['format'] != \"GTFS\" : continue\n gtfs = {}\n gtfs[\"ID\"] = dataset['fields'][\"id\"]\n gtfs[\"Licence\"] = dataset['fields'].get(\"licence\", None)\n gtfs[\"Source link\"] = dataset['fields'].get(\"source_link\", None)\n gtfs[\"Description\"] = dataset['fields'].get(\"description\", None)\n gtfs[\"Download\"] = \"https://navitia.opendatasoft.com/api/datasets/1.0/{}/images/{}\".format(\n dataset[\"datasetid\"],\n dataset[\"fields\"][\"download\"][\"id\"]\n )\n gtfs_sources.append(gtfs)\n # on ajoute le jeu de données du STIF :\n gtfs = {}\n gtfs[\"ID\"] = \"fr-idf-OIF\"\n gtfs[\"Licence\"] = \"ODbL\"\n gtfs[\"Source link\"] = \"http://opendata.stif.info/explore\"\n gtfs[\"Description\"] = \"Transport in Paris and Suburb\"\n gtfs[\"Download\"] = \"https://navitia.opendatasoft.com/api/datasets/1.0/fr-idf/images/14bd1111dd3d3e845924bb0876e175b1\"\n gtfs_sources.append(gtfs)\n\n return gtfs_sources\n\n\ngtfs_sources = get_gtfs_list_from_navitia_io()\n\nfieldnames = [\"ID\", \"Licence\", \"Source link\", \"Description\", \"Download\"]\nwith open(\"sources_GTFS.csv\", 'w') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n for g in gtfs_sources:\n writer.writerow(g)\n","sub_path":"get_GTFS_List.py","file_name":"get_GTFS_List.py","file_ext":"py","file_size_in_byte":3487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"290623846","text":"from setuptools import setup, find_packages\n\ndef format(input, start = 0):\n\tresult = ''\n\tindent = False\n\tcount = 0\n\n\twith open(input, 'r') as file:\n\t\tfor line in file:\n\t\t\tif count > start:\n\t\t\t\tif line[:1] == '\\t' and not indent:\n\t\t\t\t\tindent = True\n\t\t\t\t\tresult += '::\\n\\n'\n\n\t\t\t\tif line[:1].isalnum() and indent:\n\t\t\t\t\tindent = False\n\n\t\t\t\tresult += line.replace('> ', '\\t').replace('>', '')\n\t\t\tcount += 1\n\n\treturn result\n\nblurb = ('Caboodle is a Python module for web browsing, web scraping or web '\n\t'automation developed to provide an all-in-one (kit and caboodle) utility '\n\t'for anything the web has to offer.\\n'\n)\n\nsetup(\n\tname = 'Caboodle',\n\tversion = '1.0.2',\n\tauthor = 'Justin Willis',\n\tauthor_email = 'sirJustin.Willis@gmail.com',\n\tpackages = find_packages(),\n\turl = 'https://bitbucket.org/bkvaluemeal/caboodle',\n\tlicense = 'ISC License',\n\tdescription =\n\t\t'A Python module for web browsing, web scraping or web automation',\n\tlong_description = blurb + format('README.md', 3),\n\tclassifiers = [\n\t\t'Development Status :: 5 - Production/Stable',\n\t\t'Environment :: Console',\n\t\t'Intended Audience :: Developers',\n\t\t'License :: OSI Approved :: ISC License (ISCL)',\n\t\t'Operating System :: OS Independent',\n\t\t'Programming Language :: Python :: 2',\n\t\t'Programming Language :: Python :: 2.6',\n\t\t'Programming Language :: Python :: 2.7',\n\t\t'Programming Language :: Python :: 3',\n\t\t'Topic :: Other/Nonlisted Topic'\n\t],\n\tkeywords = 'web browsing scraping automation',\n\tinstall_requires = [\n\t\t'Pillow',\n\t\t'pyscreenshot',\n\t\t'Requests',\n\t\t'Selenium'\n\t]\n)\n","sub_path":"pypi_install_script/Caboodle-1.0.2.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"238753596","text":"#!/usr/bin/env python3\r\nimport math\r\nimport random\r\nimport sys\r\n\r\n#check if a number is prime in base10\r\ndef checkPrime(J):\r\n for i in range(2,math.floor(math.sqrt(J))):\r\n if (J % i) == 0:\r\n print(J,\"is not a prime number\")\r\n print(i,\"times\",J//i,\"is\",J)\r\n return i\r\n print(J,\"is a prime number\")\r\n return J\r\n\r\n#check if a binary string interpret in base 2..10 is prime for all those base\r\n#return a divisor for each base -1 if J is prime\r\ndef checkFullPrime(J):\r\n divisorSet=[]\r\n for i in range(2,11):\r\n Ji=int(J,i)\r\n p=checkPrime(Ji)\r\n if p==Ji:\r\n return -1\r\n else:\r\n divisorSet.append(str(p))\r\n return divisorSet\r\n\r\n\r\ndef main():\r\n inFile=open(\"dataset1.txt\",'r')\r\n outFile=open(\"output1.txt\",'w')\r\n print(\"Nombre de cas : \"+str(int(inFile.readline())))\r\n dataset=inFile.readline().split(' ')\r\n numberSize=int(dataset[0])\r\n numberSize=numberSize-2\r\n caseNumber=int(dataset[1])\r\n random.seed()\r\n #a and b are the raznge in which the number is generate, there are choose to be sure the generate number respect the size ask in input.\r\n a=pow(2,numberSize-1)\r\n print(a)\r\n b=pow(2,numberSize)-1\r\n print(b)\r\n outFile.write(\"Case #1:\\n\");\r\n print(\"starting generating numbers\")\r\n jamCoin=[]\r\n for i in range(0,caseNumber):\r\n divisorSet=-1\r\n while divisorSet==-1:\r\n N=random.randint(a,b)\r\n print(N)\r\n if N in jamCoin:#we don't want to accidentaly generate twice the same number\r\n continue\r\n J=bin(N)\r\n J='1'+J[2::]+'1'\r\n print(J)\r\n divisorSet=checkFullPrime(J)\r\n print(divisorSet)\r\n divisorString=\" \".join(divisorSet)\r\n outFile.write(str(J)+\" \"+divisorString +\"\\n\");\r\n jamCoin.append(J)\r\n inFile.close()\r\n outFile.close()\r\n return\r\n\r\n\r\n\r\nmain()","sub_path":"codes/CodeJamCrawler/16_0_3/Nol/codeJam3_small.py","file_name":"codeJam3_small.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"641430547","text":"\nfrom math import log\n\n\n\nSNUM=7\n\ndef transform(snum, loop_size):\n val=1\n for i in range(loop_size):\n val*=snum\n val%=20201227\n return val\n\n\n#transform(1,8)\n\n\ndef loop_size(snum, t):\n count=0\n val=1\n while val != t:\n val*=snum\n val%=20201227\n count+=1\n return count\n\n\ndoor=8335663\nkey=8614349\n\n\n#door=17807724\n#key=5764801\n\ndoor_loop_size = loop_size(7, door)\nkey_size = loop_size(7, key)\n#print(transform(1, door_loop_size+key_size))\nprint(transform(transform(7,door_loop_size), key_size))\nprint(transform(transform(7,key_size), door_loop_size))\n\n\n\nkey = loop_size(1, door)\n\ntransform(transform(1,8),11)\ntransform(transform(1,11),8)\ntransform(1, 8+11)\n","sub_path":"solutions/day25.py","file_name":"day25.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"351729181","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 30 15:38:05 2018\n\n@author: Cagri\n\"\"\"\n\"\"\"\nutils_orn:\nModel loader and result re-plotter in case of necessity to re-produce the results.\nResults can be plotted either using \"out.pickle\" file or running the predictor\nfor validation and test generators. If the results will be re-produced from the\npredictions, batch sizes and other parameters must be checked before running the\ncode in order to assure the coherence of the re-produced results and the \noriginal ones.\n\nTis codefile must be in the same directory with \"train\", \"validation\" and \"test\"\nfolders and the application specific \"RotNet\" data generator. Output will be \nsaved to \"output\" folder in the same directory.\n\"\"\"\nimport keras, math, csv, os, itertools, cv2\nimport matplotlib.pyplot as plt\nimport numpy as np, pickle as pk, datetime as dt\nfrom rotnet import RotNetGen\nfrom itertools import cycle\nfrom scipy import interp\nfrom sklearn.metrics import confusion_matrix, roc_curve, auc\nfrom sklearn.preprocessing import label_binarize\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.applications.vgg16 import preprocess_input\n\n#%% Additional functions-------------------------------------------------------\n# Write events to a csv file\ndef statsWrite(text):\n stats_csv = os.path.join(save_dir, 'load_orienter_stats.csv')\n if os.path.exists(stats_csv): mode = 'a'\n else: mode = 'w'\n split_text = text.split()\n with open(stats_csv, mode=mode, newline='') as stats:\n csv_writer = csv.writer(stats, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n csv_writer.writerow(split_text)\n stats.close()\n\ndef pickleSave(dictionary):\n with open(os.path.join(save_dir, 'out.pickle'), 'ab') as file_pi:\n pk.dump(dictionary, file_pi)\n file_pi.close() \n\n#%% Plot functions------------------------------------------------------------- \n# History plot of the CNN model\ndef historyPlots(history, fsize=15):\n acc = history['acc']\n val_acc = history['val_acc']\n loss = history['loss']\n val_loss = history['val_loss']\n epochs = range(len(acc))\n xint = range(min(epochs), math.ceil(max(epochs))+1)\n plt.plot(epochs, acc, 'b', label='Training acc')\n plt.plot(epochs, val_acc, 'r', label='Validation acc')\n plt.title('Train and validation accuracy', fontsize=fsize)\n plt.xlabel('Epochs', fontsize=fsize); plt.ylabel('Accuracy', fontsize=fsize);\n plt.grid(color='k', linestyle='--', linewidth=1)\n plt.xticks(xint); plt.legend(); fig = plt.gcf()\n plt.tight_layout(); plt.show()\n fig.savefig(os.path.join(save_dir, 'train-val_acc.png'), dpi=100)\n plt.plot(epochs, loss, 'b', label='Training loss')\n plt.plot(epochs, val_loss, 'r', label='Validation loss')\n plt.title('Train and validation loss', fontsize=fsize)\n plt.legend();plt.xlabel('Epochs', fontsize=fsize); plt.ylabel('Loss', fontsize=fsize);\n plt.grid(color='k', linestyle='--', linewidth=1)\n plt.xticks(xint);plt.legend(); fig = plt.gcf()\n plt.tight_layout(); plt.show()\n fig.savefig(os.path.join(save_dir, 'train-val_loss.png'), dpi=100)\n\n# Confusion matrix\ndef confMatrix(true_labels, pred_labels, classes, check, normalize=False, fsize=15):\n cmap=plt.cm.Blues\n cm = confusion_matrix(true_labels, pred_labels)\n if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] \n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n# plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=0, fontsize=fsize)\n plt.yticks(tick_marks, classes, rotation=0, fontsize=fsize)\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt), fontsize=fsize,\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\") \n plt.title(check+' confusion matrix', fontsize=fsize) \n plt.xlabel('Predicted label', fontsize=fsize); plt.ylabel('True label', fontsize=fsize) \n fig = plt.gcf(); plt.tight_layout(); plt.show()\n fig.savefig(os.path.join(save_dir, check+'_conf_matrix.png'), dpi=100)\n \n# ROC curves \ndef rocCurve(true_labels, predictions, classes, check, fsize=15): \n n_classes = len(classes)\n true_labels = label_binarize(true_labels, np.linspace(0,n_classes,n_classes+1))\n true_labels = true_labels[:,:-1]\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n for i in range(len(classes)):\n fpr[i], tpr[i], _ = roc_curve(true_labels[:, i], predictions[:, i])\n roc_auc[i] = auc(fpr[i], tpr[i]) \n # Compute micro-average ROC curve and ROC area\n fpr[\"micro\"], tpr[\"micro\"], _ = roc_curve(true_labels.ravel(), predictions.ravel())\n roc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"]) \n all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)])) \n # Then interpolate all ROC curves at this points\n mean_tpr = np.zeros_like(all_fpr)\n for i in range(n_classes):\n mean_tpr += interp(all_fpr, fpr[i], tpr[i]) \n # Finally average it and compute AUC\n mean_tpr /= n_classes \n fpr[\"macro\"] = all_fpr\n tpr[\"macro\"] = mean_tpr\n roc_auc[\"macro\"] = auc(fpr[\"macro\"], tpr[\"macro\"]) \n # Plot all ROC curves\n plt.figure()\n if n_classes > 2:\n plt.plot(fpr[\"micro\"], tpr[\"micro\"], label='micro-avg. ROC curve (AUC = {0:0.2f})'\n ''.format(roc_auc[\"micro\"]), color='darkorange', linestyle=':', linewidth=3) \n plt.plot(fpr[\"macro\"], tpr[\"macro\"], label='macro-avg. ROC curve (AUC = {0:0.2f})' \n ''.format(roc_auc[\"macro\"]), color='indigo', linestyle=':', linewidth=3) \n colors = cycle(['blue', 'green', 'red', 'cyan', 'magenta'])\n for i, color in zip(range(n_classes), colors):\n plt.plot(fpr[i], tpr[i], color=color, lw=1.5,\n label='ROC curve of class {0} (AUC = {1:0.2f})' ''.format(i, roc_auc[i])) \n plt.plot([0, 1], [0, 1], 'k--', lw=1)\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel('False Positive Rate', fontsize=fsize)\n plt.ylabel('True Positive Rate', fontsize=fsize)\n plt.title(check+' ROC curve', fontsize=fsize)\n plt.legend(loc=\"lower right\")\n plt.grid()\n fig = plt.gcf(); plt.tight_layout(); plt.show()\n fig.savefig(os.path.join(save_dir, check+'_ROC_curve.png'), dpi=100)\n\n\n# Unidentified images prediction results\ndef unidentPredictions(item):\n fnames = item.filenames\n predictions = model.predict_generator(item, steps=item.samples/item.batch_size, verbose=1)\n predicted_classes = np.argmax(predictions, axis=1)\n pred_confidence = np.amax(predictions, axis=1)\n unin_predicted_classes = np.argmax(predictions, axis=1)\n unique, counts = np.unique(unin_predicted_classes, return_counts=True)\n pred_result = ' '.join(map(str, [unique, counts])) \n statsWrite(' ')\n statsWrite('Unidentified images predictions results: '+pred_result)\n statsWrite('Pred-Confidence/F.name')\n for i in range(len(fnames)): \n pred_result = [predicted_classes[i], pred_confidence[i], ',', fnames[i]] \n pred_result = ' '.join(map(str, pred_result))\n statsWrite(pred_result)\n \n\n# Validation and test errors\ndef results(item, check):\n # Initialize variables \n fnames = item.filenames\n label2idx = item.class_indices\n idx2label = dict((v,k) for k,v in label2idx.items())\n values = {}\n idx_list = []\n for key, value in idx2label.items():\n key = str(key)+':'\n value = str(value)\n temp = [key, value]\n idx_list += temp\n idx_list = ' '.join(map(str, idx_list))\n \n # Generate correct step number for each call\n steps = item.samples/item.batch_size\n \n # Make predictions and find errors\n predictions = model.predict_generator(item, steps=steps, verbose=1)\n ground_truth = item.classes\n predicted_classes = np.argmax(predictions, axis=1)\n for i in range(len(predicted_classes)):\n if np.max(predictions[i])<0.9:\n predicted_classes[i] = 0\n pred_confidence = np.amax(predictions, axis=1)\n errors = np.where(predicted_classes != ground_truth)[0]\n print(\"{} errors = {}/{}\".format(check,len(errors),len(item.classes)))\n \n # List errors into the stats.csv\n statsWrite(' ')\n statsWrite(check+' errors: '+str(len(errors)))\n statsWrite('Actual-Pred-Confidence/F.name')\n statsWrite(idx_list)\n for i in range(len(errors)): \n pred_result = [ground_truth[errors[i]], predicted_classes[errors[i]], \n pred_confidence[errors[i]], ',', fnames[errors[i]]]\n pred_result = ' '.join(map(str, pred_result))\n statsWrite(pred_result)\n \n # Generate plots, return values and write values to the pickle file\n values['ground_truth'] = ground_truth\n values['predictions'] = predictions\n values['predicted_classes'] = predicted_classes\n values['label2idx'] = label2idx\n pickleSave(values)\n \n # Plot and return the outputs\n rocCurve(ground_truth, predictions, label2idx, check)\n confMatrix(ground_truth, predicted_classes, label2idx, check, normalize=False)\n return values\n\n#%% Main function to re-produce the results from the predictions---------------\nif __name__ == '__main__':\n # Image directories\n root_dir = os.getcwd()\n train_dir = os.path.join(root_dir, 'train')\n validation_dir = os.path.join(root_dir, 'validation')\n test_dir = os.path.join(root_dir, 'rma_sim')\n save_dir = os.path.join(root_dir, 'output')\n if not os.path.exists(save_dir): os.mkdir(save_dir)\n \n # Initialize stats file\n statsWrite('LOAD MODEL: ORIENTATION CORRECTION CLASSIFIER')\n statsWrite('Start time: '+str(dt.datetime.now()))\n \n val_batchsize = 128\n tst_batchsize = 128\n image_size = 224\n lr = 0.5e-3 \n target_angles = [0, 90, 180, 270, 'undef']\n tst_classes = dict(zip([str(i) for i in (target_angles)], list(range(len(target_angles)))))\n \n model = keras.models.load_model(os.path.join(root_dir, 'best_model.h5'), compile=False)\n \n # Data Generator for validation data\n test_datagen = ImageDataGenerator(preprocessing_function = preprocess_input)\n test_generator = test_datagen.flow_from_directory(test_dir, \n target_size=(image_size, image_size), classes=tst_classes,\n batch_size=tst_batchsize, class_mode='categorical', shuffle=False)\n\n test_outs = results(test_generator, 'Test')\n \n statsWrite('Stop time: '+str(dt.datetime.now()))\n print('DONE SUCCESSFULLY')\n\n#%% Results can be plotted from the pickle file \n # Get numerical outputs from the pickle file and plot the results\n # 0: history, 1: validation, 2: test\n out_vals = []\n with (open(os.path.join(root_dir, 'out.pickle'), \"rb\")) as outs_pickle:\n while True:\n try:\n out_vals.append(pk.load(outs_pickle))\n except EOFError:\n break\n # History plots\n historyPlots(out_vals[0])\n \n # Validation plots\n rocCurve(out_vals[0]['ground_truth'], out_vals[0]['predictions'], \n out_vals[0]['label2idx'], 'Holidays balanced')\n confMatrix(out_vals[0]['ground_truth'], out_vals[0]['predicted_classes'], \n out_vals[0]['label2idx'], 'Holidays balanced', normalize=False)\n \n # Test plots\n rocCurve(out_vals[2]['ground_truth'], out_vals[2]['predictions'], \n out_vals[2]['label2idx'], 'Test')\n confMatrix(out_vals[2]['ground_truth'], out_vals[2]['predicted_classes'], \n out_vals[2]['label2idx'], 'Test', normalize=False)\n#","sub_path":"orientation-detector/model_load.py","file_name":"model_load.py","file_ext":"py","file_size_in_byte":11856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"39012569","text":"import sqlite3\nfrom typing import List\n\nfrom discord import User, Guild, TextChannel\n\n\ndef dict_factory(cursor, row):\n d = {}\n for idx, col in enumerate(cursor.description):\n d[col[0]] = row[idx]\n return d\n\n\nclass Database:\n def __init__(self, filename: str = \"covid.db\") -> None:\n self._conn = sqlite3.connect(filename)\n self._conn.row_factory = dict_factory\n\n def add_guild(self, guild: Guild, country_name: str = None, dataset_id: str = None):\n c = self._conn.cursor()\n c.execute(\n \"INSERT OR IGNORE INTO guild (guildId) VALUES (?);\",\n (guild.id,),\n )\n if dataset_id:\n c.execute(\n \"UPDATE guild SET countryName = ?, datasetId = ? WHERE guildId = ?;\",\n (country_name, dataset_id, guild.id),\n )\n self._conn.commit()\n\n def remove_guild(self, guild: Guild):\n c = self._conn.cursor()\n c.execute(\n \"DELETE FROM guild WHERE guildId = ?;\",\n (guild.id,),\n )\n self._conn.commit()\n\n def add_channel(self, user: User, channel: TextChannel, run_at: str):\n c = self._conn.cursor()\n c.execute(\n \"REPLACE INTO channel \"\n \"(guildId, channelId, addedById, addedByName, runAt) \"\n \"VALUES (?, ?, ?, ?, ?);\",\n (\n channel.guild.id,\n channel.id,\n user.id,\n f\"{user.name}#{user.discriminator}\",\n run_at,\n ),\n )\n self._conn.commit()\n\n def get_by_guild(self, guild: Guild) -> List[dict]:\n c = self._conn.cursor()\n c.execute(\n \"SELECT channel.guildId, channelId, countryName, datasetId, mentionEveryone, runAt \"\n \"FROM guild LEFT JOIN channel \"\n \"WHERE guild.guildId = ?;\",\n (guild.id,),\n )\n return c.fetchall()\n\n def get_by_channel(self, channel: TextChannel) -> dict:\n c = self._conn.cursor()\n c.execute(\n \"SELECT \"\n \"channel.guildId, channelId, countryName, datasetId, mentionEveryone, runAt \"\n \"FROM channel JOIN guild \"\n \"WHERE channel.guildId = ? AND channel.channelId = ?;\",\n (channel.guild.id, channel.id),\n )\n return c.fetchone()\n\n def get_all(self) -> List[dict]:\n c = self._conn.cursor()\n c.execute(\n \"SELECT channel.guildId, channelId, countryName, datasetId, mentionEveryone, runAt \"\n \"FROM guild LEFT JOIN channel \"\n \"WHERE runAt IS NOT NULL;\"\n )\n return c.fetchall()\n","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":2642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"360187962","text":"# -*- coding: utf-8 -*-\nimport unittest\n\nfrom mahjong.player import Player\nfrom mahjong.table import Table\nfrom utils.tests import TestMixin\n\n\nclass CallRiichiTestCase(unittest.TestCase, TestMixin):\n\n def test_should_call_riichi_and_tanki_wait(self):\n table = Table()\n table.count_of_remaining_tiles = 60\n player = Player(table, 0, 0, False)\n player.scores = 25000\n\n tiles = self._string_to_136_array(sou='123456', pin='12345', man='34')\n tile = self._string_to_136_tile(pin='6')\n player.init_hand(tiles)\n player.draw_tile(tile)\n player.discard_tile()\n\n self.assertEqual(player.can_call_riichi(), False)\n\n tiles = self._string_to_136_array(sou='1133557799', pin='113')\n tile = self._string_to_136_tile(pin='6')\n player.init_hand(tiles)\n player.draw_tile(tile)\n player.discard_tile()\n\n # for chitoitsu it is ok to have a pair wait\n self.assertEqual(player.can_call_riichi(), True)\n","sub_path":"project/mahjong/ai/tests/tests_riichi.py","file_name":"tests_riichi.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"587424874","text":"class Node:\n def __init__(self, data=None, next_node=None):\n self.data = data\n self.next_node = next_node\n\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n self.last_node = None\n\n def to_list(self):\n \"\"\"\n Create linked list\n \"\"\"\n l = []\n if self.head is None:\n return l\n \n node = self.head\n while node:\n l.append(node.data)\n node = node.next_node\n return l\n\n def print_linked_list(self):\n \"\"\"\n Print the linked list\n \"\"\"\n linked_list_string = \"\"\n node = self.head\n if node is None:\n print(Node)\n while node:\n linked_list_string += f\" {str(node.data)} ->\"\n node = node.next_node\n\n linked_list_string += \" None\"\n print(linked_list_string)\n\n def insert_beginning(self, data):\n \"\"\"\n Add element to the beginning of the linked list\n \"\"\"\n if self.head is None:\n self.head = Node(data, None)\n self.last_node = self.head\n\n new_node = Node(data, self.head)\n self.head = new_node\n\n def append_to_end(self, data):\n \"\"\"\n Append element to the end of the linked list\n \"\"\"\n if self.head is None:\n self.insert_beginning(data)\n return\n\n self.last_node.next_node = Node(data, None)\n self_last_node = self.last_node.next_node\n\n def get_user_by_id(self, user_id: int) -> None:\n \"\"\"\n Get user from the linked list by id\n \"\"\"\n node = self.head\n while node:\n if node.data[\"id\"] is int(user_id):\n return node.data\n node = node.next_node\n return None\n","sub_path":"linked_list.py","file_name":"linked_list.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"84197021","text":"'''Functions - Assignment-3 - Using Bisection Search to Make the Program Faster'''\n\n# value as you did in Assignment 2.\n\ndef debt_topay(balance_amount, ann_interest_rate, amount):\n '''Function for debt to pay'''\n balance_amount_temp = balance_amount\n index = 1\n while index <= 12:\n month_intr = ann_interest_rate/12\n month_up_bal = balance_amount_temp - amount\n balance_amount_temp = month_up_bal + (month_intr*month_up_bal)\n index = index+1\n return balance_amount_temp\n\ndef payingdebtoffinayear(balance, annual_interestrate):\n '''Function for debt in year'''\n balance_amount_temp = balance\n approx_amnt = 0.03\n month_intr = annual_interestrate/12.0\n high = (balance*(1+month_intr)**12)/12.0\n low = balance/12\n middle = (low + high)/2.0\n while abs(debt_topay(balance_amount_temp, annual_interestrate, middle)) >= approx_amnt:\n if approx_amnt < debt_topay(balance_amount_temp, annual_interestrate, middle):\n low = middle\n else:\n high = middle\n middle = (low + high)/2.0\n num = middle\n return \"Lowest Payment: \"+str(round(num, 2))\ndef main():\n '''Main Function'''\n data = input()\n # data = \"4773 0.2\"\n data = data.split(' ')\n data = list(map(float, data))\n print(payingdebtoffinayear(data[0], data[1]))\nif __name__ == \"__main__\":\n main()\n","sub_path":"Module 7/Functions - Assignment-3/assignment3.py","file_name":"assignment3.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"557954101","text":"#!/usr/bin/env Python\n# coding=utf-8\nimport numpy as np\nimport os\nimport sys\nimport shutil\nimport time\nimport logging\nimport urllib\nimport math\nimport random\nfrom PIL import Image\nimport tensorflow as tf\nimport pydensecrf.densecrf as dcrf\nfrom pydensecrf.utils import create_pairwise_bilateral, create_pairwise_gaussian, unary_from_softmax\n\nsys.path.append(\"/media/jionie/Disk1/OrganSegC2F/models-master/slim/\")\n\n# Add path to the cloned library\nsys.path.append(\"/media/jionie/Disk1/OrganSegC2F/tf-image-segmentation-master\")\n\nfrom tf_image_segmentation.models.fcn_8s import FCN_8s\nfrom tf_image_segmentation.models.fcn_8s_new import FCN_8s_new\nfrom loss import *\nimport matplotlib.pyplot as plt\nimport cv2\n\nfcn_8s_checkpoint_path = '/media/jionie/Disk1/checkpoints/fcn_8s_checkpoint/model_fcn8s_final.ckpt'\ndata_path = \"/media/jionie/Disk1\"\ncurrent_fold = 3\norgan_number = 1\nlow_range = 100\nhigh_range = 240\nslice_threshold = 0.98\nslice_thickness = 3\norgan_ID = 1\ntrain_plane = \"Z\"\nwd = 5e-4\ninitial_learning_rate = 1e-5\ngamma = 0.5\ncheckpoint_path = '/media/jionie/Disk1/checkpoints/coarse/fcn_vgg/'\nsummary_save_dir1 = '/media/jionie/Disk1/train_summary/coarse/fcn_vgg/coarse-' + train_plane + str(current_fold)\nsummary_save_dir2 = '/media/jionie/Disk1/train_summary/coarse_eval/fcn_vgg/coarse-' + train_plane + str(current_fold)\nbatch_size = 1\nis_save = True\nnumber_of_classes = 21\nmax_iterations = round(80000/batch_size)\nresult_path = os.path.join(data_path, '/results')\nis_retrain = False\n\n\n\nimage_path = os.path.join(data_path, 'images')\nimage_path_ = {}\nfor plane in ['X', 'Y', 'Z']:\n image_path_[plane] = os.path.join(data_path, 'images_' + plane)\n if not os.path.exists(image_path_[plane]):\n os.makedirs(image_path_[plane])\nlabel_path = os.path.join(data_path, 'labels')\nlabel_path_ = {}\nfor plane in ['X', 'Y', 'Z']:\n label_path_[plane] = os.path.join(data_path, 'labels_' + plane)\n if not os.path.exists(label_path_[plane]):\n os.makedirs(label_path_[plane])\nlist_path = os.path.join(data_path, 'lists')\nif not os.path.exists(list_path):\n os.makedirs(list_path)\ncoarse_list_training = {}\nfine_list_training = {}\ncoarse_list_retraining = {}\nfine_list_retraining = {}\nfor plane in ['X', 'Y', 'Z']:\n coarse_list_training[plane] = os.path.join(list_path, 'coarse_' + plane + '.txt')\n fine_list_training[plane] = os.path.join(list_path, 'fine_' + plane + '.txt')\n\n\n####################################################################################################\n# returning the binary label map by the organ ID (especially useful under overlapping cases)\n# label: the label matrix\n# organ_ID: the organ ID\ndef is_organ(label, organ_ID):\n return label == organ_ID\n\n\n####################################################################################################\n# determining if a sample belongs to the training set by the fold number\n# total_samples: the total number of samples\n# i: sample ID, an integer in [0, total_samples - 1]\n# folds: the total number of folds\n# current_fold: the current fold ID, an integer in [0, folds - 1]\ndef in_training_set(total_samples, i, folds, current_fold):\n fold_remainder = folds - total_samples % folds\n fold_size = (total_samples - total_samples % folds) / folds\n start_index = fold_size * current_fold + max(0, current_fold - fold_remainder)\n end_index = fold_size * (current_fold + 1) + max(0, current_fold + 1 - fold_remainder)\n return not (i >= start_index and i < end_index)\n\n####################################################################################################\n# returning the filename of the training set according to the current fold ID\ndef training_set_filename(current_fold):\n return os.path.join(list_path, 'training_' + 'FD' + str(current_fold) + '.txt')\n\n\n####################################################################################################\n# returning the filename of the testing set according to the current fold ID\ndef testing_set_filename(current_fold):\n return os.path.join(list_path, 'testing_' + 'FD' + str(current_fold) + '.txt')\n\n\n\n\n\nclass Data():\n\n def __init__(self, mode):\n self.mode = mode\n \n def setup(self):\n if self.mode == 'train':\n with open(training_set_filename(current_fold), 'r') as f1:\n image_list = f1.read().splitlines() #for example traing_FD0.txt 20 /DATA3_DB7/data/zhcao/segmentation/DATA/images/0021.npy /DATA3_DB7/data/zhcao/segmentation/DATA/labels/0021.npy\n if self.mode == 'test':\n with open(testing_set_filename(current_fold), 'r') as f1:\n image_list = f1.read().splitlines() \n self.training_image_set = np.zeros((len(image_list)), dtype = np.int)\n for i in range(len(image_list)):\n s = image_list[i].split(' ')\n self.training_image_set[i] = int(s[0])\n\n if is_retrain :\n with open(coarse_list_retraining[train_plane], 'r') as f2:\n slice_list = f2.read().splitlines() \n else:\n with open(coarse_list_training[train_plane], 'r') as f2:\n slice_list = f2.read().splitlines() # for example traing_X.txt 0 0 /DATA3_DB7/data/zhcao/segmentation/DATA/images_X/0001/0000.npy /DATA3_DB7/data/zhcao/segmentation/DATA/labels_X/0001/0000.npy 100.0 0 0 0 0 0\n \n self.slices = len(slice_list) #total slices\n self.image_ID = np.zeros((self.slices), dtype = np.int) # record image index\n self.slice_ID = np.zeros((self.slices), dtype = np.int) # record slice index of image index\n self.image_filename = ['' for l in range(self.slices)] # record image_filename for every slice\n self.label_filename = ['' for l in range(self.slices)] # record label_filename for every slice\n self.average = np.zeros((self.slices))\n self.pixels = np.zeros((self.slices), dtype = np.int)\n for l in range(self.slices):\n s = slice_list[l].split(' ')\n self.image_ID[l] = s[0] # for example in training_X.txt first col 0 of line 1 indicate image 0\n self.slice_ID[l] = s[1] # for example in training_X.txt second col 0 of line 1 indicate slice 0 of image 0\n self.image_filename[l] = s[2] # for example in training_X.txt /DATA3_DB7/data/zhcao/segmentation/DATA/images_X/0001/0000.npy\n self.label_filename[l] = s[3] # for example in training_X.txt /DATA3_DB7/data/zhcao/segmentation/DATA/labels_X/0001/0000.npy\n self.average[l] = float(s[4])\n self.pixels[l] = int(s[organ_ID * 5])\n \n if slice_threshold <= 1:\n pixels_index = sorted(range(self.slices), key = lambda l: self.pixels[l]) # sorted range(self.slices) based on self.pixels[l], l belongs to range(self.slices), lambda l returns self.pixels[l]\n last_index = int(math.floor((self.pixels > 0).sum() * slice_threshold)) # floor the integer\n min_pixels = self.pixels[pixels_index[-last_index]] # the last last_index pixel (sorted)\n\n else:\n min_pixels = slice_threshold\n self.active_index = [l for l, p in enumerate(self.pixels) if p >= min_pixels] # return index, pixels which pixels>=min_pixel in unsorted pixels to get slices which has organs\n self.active_index = [p for l, p in enumerate(self.active_index) if self.image_ID[p] in self.training_image_set ]\n self.index_ = -1\n self.next_slice_index()\n\n\n def shuffle_data(self):\n\n random.shuffle(self.active_index)\n \n def next_slice_index(self):\n self.index_ += 1\n if self.index_ == len(self.active_index):\n self.index_ = 0\n self.index1 = self.active_index[self.index_]\n \n self.index0 = self.index1 - 1\n if self.index1 == 0 or self.slice_ID[self.index0] != self.slice_ID[self.index1] - 1:\n self.index0 = self.index1\n self.index2 = self.index1 + 1\n if self.index1 == self.slices - 1 or \\\n self.slice_ID[self.index2] != self.slice_ID[self.index1] + 1:\n self.index2 = self.index1\n\n\n def image_label(self):\n\n return self.image_filename[self.index1], self.label_filename[self.index1]\n\n def load_data(self):\n\n if slice_thickness == 1:\n\n label1 = np.load(self.label_filename[self.index1])\n width = label1.shape[0]\n height = label1.shape[1]\n label = np.repeat(label1.reshape(width, height, 1), 3, axis = 2)\n \n image1 = np.load(self.image_filename[self.index1]).astype(np.float32)\n image = np.repeat(image1.reshape(width, height, 1), 3, axis = 2)\n \n\n elif slice_thickness == 3:\n \n label1 = np.load(self.label_filename[self.index1])\n \n width = label1.shape[0]\n height = label1.shape[1]\n\n label0 = np.load(self.label_filename[self.index0])\n label2 = np.load(self.label_filename[self.index2])\n \n\n image1 = np.load(self.image_filename[self.index1]).astype(np.float32)\n image0 = np.load(self.image_filename[self.index0]).astype(np.float32)\n image2 = np.load(self.image_filename[self.index2]).astype(np.float32)\n\n\n image = np.concatenate((image0.reshape(width, height, 1), \\\n image1.reshape(width, height, 1), image2.reshape(width, height, 1)), axis=2)\n\n label = np.concatenate((label0.reshape(width, height, 1), \\\n label1.reshape(width, height, 1), label2.reshape(width, height, 1)), axis=2)\n\n image = image.astype(np.float32)\n image[image < low_range] = low_range\n image[image > high_range] = high_range\n image = (image - low_range) / (high_range - low_range)\n image = (image*255).astype(np.int32)\n label = is_organ(label, organ_ID).astype(np.int32)\n\n return image, label\n\ndef get_next_batch(data, batch_size=32):\n\n batches = []\n image_mini_batch = []\n label_mini_batch = []\n index_mini_batch = 0\n\n while index_mini_batch < batch_size:\n\n data.next_slice_index()\n\n image, label = data.load_data()\n image_mini_batch.append(image)\n label_mini_batch.append(label)\n\n index_mini_batch += 1\n\n batches.append((np.array(image_mini_batch), np.array(label_mini_batch)))\n\n return batches\n\n\n\ndef resized_parameter(input_parameter, multiple):\n\n input_parameter = float(input_parameter)\n output_parameter = math.ceil(input_parameter / multiple) * multiple\n\n return output_parameter\n\n\n####################################################################################################\n# computing the DSC together with other values based on the label and prediction volumes\ndef DSC_computation(label, pred):\n pred_sum = pred.sum()\n label_sum = label.sum()\n inter_sum = np.multiply(pred, label)\n inter_sum = inter_sum.sum()\n return 2 * float(inter_sum) / (pred_sum + label_sum), inter_sum, pred_sum, label_sum\n\n\n####################################################################################################\n\ndef post_processing(F, S, threshold, organ_ID):\n if F.sum() == 0:\n return F\n if F.sum() >= np.product(F.shape) / 2:\n return F\n height = F.shape[0]\n width = F.shape[1]\n depth = F.shape[2]\n ll = np.array(np.nonzero(S))\n marked = np.zeros_like(F, dtype = np.bool)\n queue = np.zeros((F.sum(), 3), dtype = np.int)\n volume = np.zeros(F.sum(), dtype = np.int)\n head = 0\n tail = 0\n bestHead = 0\n bestTail = 0\n bestHead2 = 0\n bestTail2 = 0\n for l in range(ll.shape[1]):\n if not marked[ll[0, l], ll[1, l], ll[2, l]]:\n temp = head\n marked[ll[0, l], ll[1, l], ll[2, l]] = True\n queue[tail, :] = [ll[0, l], ll[1, l], ll[2, l]]\n tail = tail + 1\n while (head < tail):\n t1 = queue[head, 0]\n t2 = queue[head, 1]\n t3 = queue[head, 2]\n if t1 > 0 and F[t1 - 1, t2, t3] and not marked[t1 - 1, t2, t3]:\n marked[t1 - 1, t2, t3] = True\n queue[tail, :] = [t1 - 1, t2, t3]\n tail = tail + 1\n if t1 < height - 1 and F[t1 + 1, t2, t3] and not marked[t1 + 1, t2, t3]:\n marked[t1 + 1, t2, t3] = True\n queue[tail, :] = [t1 + 1, t2, t3]\n tail = tail + 1\n if t2 > 0 and F[t1, t2 - 1, t3] and not marked[t1, t2 - 1, t3]:\n marked[t1, t2 - 1, t3] = True\n queue[tail, :] = [t1, t2 - 1, t3]\n tail = tail + 1\n if t2 < width - 1 and F[t1, t2 + 1, t3] and not marked[t1, t2 + 1, t3]:\n marked[t1, t2 + 1, t3] = True\n queue[tail, :] = [t1, t2 + 1, t3]\n tail = tail + 1\n if t3 > 0 and F[t1, t2, t3 - 1] and not marked[t1, t2, t3 - 1]:\n marked[t1, t2, t3 - 1] = True\n queue[tail, :] = [t1, t2, t3 - 1]\n tail = tail + 1\n if t3 < depth - 1 and F[t1, t2, t3 + 1] and not marked[t1, t2, t3 + 1]:\n marked[t1, t2, t3 + 1] = True\n queue[tail, :] = [t1, t2, t3 + 1]\n tail = tail + 1\n head = head + 1\n if tail - temp > bestTail - bestHead:\n bestHead2 = bestHead\n bestTail2 = bestTail\n bestHead = temp\n bestTail = tail\n elif tail - temp > bestTail2 - bestHead2:\n bestHead2 = temp\n bestTail2 = tail\n volume[temp: tail] = tail - temp\n volume = volume[0: tail]\n target_voxel = np.where(volume >= (bestTail - bestHead) * threshold)\n F0 = np.zeros_like(F, dtype = np.bool)\n F0[tuple(map(tuple, np.transpose(queue[target_voxel, :])))] = True\n return F0\n\n####################################################################################################\n# dense CRF\ndef dense_crf(probs, img=None, n_iters=10, n_classes=2,\n sxy_gaussian=(1,1), compat_gaussian=4,\n kernel_gaussian=dcrf.DIAG_KERNEL,\n normalisation_gaussian=dcrf.NORMALIZE_SYMMETRIC,\n sxy_bilateral=(10, 10), compat_bilateral=5,\n srgb_bilateral=(5, 5, 5),\n kernel_bilateral=dcrf.DIAG_KERNEL,\n normalisation_bilateral=dcrf.NORMALIZE_SYMMETRIC):\n \"\"\"DenseCRF over unnormalised predictions.\n More details on the arguments at https://github.com/lucasb-eyer/pydensecrf.\n \n Args:\n probs: class probabilities per pixel.\n img: if given, the pairwise bilateral potential on raw RGB values will be computed.\n n_iters: number of iterations of MAP inference.\n sxy_gaussian: standard deviations for the location component of the colour-independent term.\n compat_gaussian: label compatibilities for the colour-independent term (can be a number, a 1D array, or a 2D array).\n kernel_gaussian: kernel precision matrix for the colour-independent term (can take values CONST_KERNEL, DIAG_KERNEL, or FULL_KERNEL).\n normalisation_gaussian: normalisation for the colour-independent term (possible values are NO_NORMALIZATION, NORMALIZE_BEFORE, NORMALIZE_AFTER, NORMALIZE_SYMMETRIC).\n sxy_bilateral: standard deviations for the location component of the colour-dependent term.\n compat_bilateral: label compatibilities for the colour-dependent term (can be a number, a 1D array, or a 2D array).\n srgb_bilateral: standard deviations for the colour component of the colour-dependent term.\n kernel_bilateral: kernel precision matrix for the colour-dependent term (can take values CONST_KERNEL, DIAG_KERNEL, or FULL_KERNEL).\n normalisation_bilateral: normalisation for the colour-dependent term (possible values are NO_NORMALIZATION, NORMALIZE_BEFORE, NORMALIZE_AFTER, NORMALIZE_SYMMETRIC).\n \n Returns:\n Refined predictions after MAP inference.\n \"\"\"\n _, h, w, _ = probs.shape\n \n \n probs = probs[0].transpose(2, 0, 1).copy(order='C') # Need a contiguous array.\n \n d = dcrf.DenseCRF2D(w, h, n_classes) # Define DenseCRF model.\n U = unary_from_softmax(probs) # Unary potential.\n U = U.reshape((n_classes, -1)) # Needs to be flat.\n d.setUnaryEnergy(U)\n energy = create_pairwise_gaussian(sxy_gaussian, [w, h])\n d.addPairwiseEnergy(energy, compat=compat_gaussian)\n\n if img is not None:\n assert(img.shape[1:3] == (h, w)), \"The image height and width must coincide with dimensions of the logits.\"\n energy = create_pairwise_bilateral(sdims=sxy_bilateral, schan=srgb_bilateral[0], img=img, chdim=-1)\n d.addPairwiseEnergy(energy, compat=compat_bilateral)\n\n Q = d.inference(n_iters)\n preds = np.array(Q, dtype=np.float32).reshape((n_classes, h, w)).transpose(1, 2, 0)\n return np.expand_dims(preds, 0)","sub_path":"OrganSegC2F_Fcn/input_data_coarse.py","file_name":"input_data_coarse.py","file_ext":"py","file_size_in_byte":17127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"195435873","text":"import numpy as np\nimport json\nimport random\nimport string\nfrom augment_data import *\n\ndef read_and_store(list_path):\n with open(list_path) as f:\n content = []\n for line in f:\n line = line.strip().split(' ')\n content.append(line)\n return content\n\ndef read_and_store2(list_path):\n with open(list_path) as f:\n content = []\n for line in f:\n line = line.strip()\n content.append(line)\n return content\n\ndef read_and_write(w_path, list_to_wr):\n with open(w_path, \"w\") as output:\n for k, val in enumerate(list_to_wr):\n output.write(val + '\\n')\n return None\n\n\ndef read_json(json_fn):\n with open(json_fn) as data_file:\n data_loaded = json.load(data_file)\n return data_loaded\n\n\ndef erase_punc(desc):\n punc_list = string.punctuation\n\n new_desc = []\n for k, letter in enumerate(desc):\n if letter in punc_list:\n new_desc.append(' ') \n else: \n new_desc.append(letter)\n new_desc = ''.join(new_desc)\n new_desc = new_desc.replace(' ', ' ') \n new_desc = new_desc.replace(' ', ' ') \n new_desc = new_desc.replace(' ', ' ') \n return new_desc \n\nif __name__ == '__main__':\n \n json_dict = read_json('../data/com2des_TJ.json')\n \n data_out = []\n for key, val in json_dict.items():\n sep_let = list(key)\n for desc in val:\n COM = ' '.join(sep_let).strip() \n # DES = erase_punc(desc)\n DES = desc \n data_out.append(COM + '@'+ DES)\n random.shuffle(data_out)\n\n random.seed(0)\n split_ratio = 0.9\n train_set = data_out[:int(split_ratio*len(data_out))]\n dev_set = data_out[int(split_ratio*len(data_out)):]\n \n read_and_write('../data/com-eng_train.txt', train_set)\n read_and_write('../data/com-eng_test.txt', dev_set)\n # read_and_write('../data/com-eng_train_unclean.txt', train_set)\n # read_and_write('../data/com-eng_test_unclean.txt', dev_set)\n\n stoflw_test_set = read_and_store2('../data/com2des_RP_170pages_stackoverflow.txt')\n\n data_out = []\n for key, val in enumerate(stoflw_test_set):\n split_list = val.split('@')\n # print(split_list)\n sep_let = split_list[0]\n desc = split_list[1]\n # print(desc)\n COM = ' '.join(sep_let).strip() \n DES = erase_punc(desc)\n data_out.append(COM + '@'+ DES)\n random.shuffle(data_out)\n\n random.seed(0)\n split_ratio = 0.9\n \n read_and_write('../data/com-eng_stoflw_test.txt', data_out)\n\n\n # Parameters\n # data_file = \"../data/com-eng_train.txt\" # file containing the original command-description pairs\n # data_file = \"../data/com-eng_train_toy.txt\" file containing the original command-description pairs\n # out_data_file = \"../data/com-eng_train_aug.txt\" output file where the new augmented pairs are written\n\n # max_num_syn = 3 maximum number of synonyms per word to be used for augmentation\n\n # FLAG_POS_Stanf = 1 when set to 0, it uses the averaged perceptron tagger from nltk else uses stanford POS tagger\n # FLAG_Save_Verbs2Syns_dict = 0 flag to save the verbs-synonyms dictionary to file. Need to manually set path for dictionary\n\n # Function call\n # augment_eng2linux_Data(data_file, out_data_file, max_num_syn, FLAG_POS_Stanf, FLAG_Save_Verbs2Syns_dict)\n\n","sub_path":"dualenc_seq2seq/data_prep.py","file_name":"data_prep.py","file_ext":"py","file_size_in_byte":3394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"516038084","text":"# 以下解法ML\n\nclass Solution:\n # @param {integer} n\n # @return {integer}\n def countDigitOne(self, n):\n \tif n == 0: return 0\n \tsubString = ''\n \tfor i in range(1,n+1):\n \t\tsubString += 'i'\n \tcount = 0\n \tfor i in range(len(subString)):\n \t\tif subString[i] == '1':\n \t\t\tcount += 1\n \treturn count\n\n# 一下是新解法, 但看不懂 \n# https://leetcode.com/discuss/44281/4-lines-o-log-n-c-java-python\n# http://blog.csdn.net/xudli/article/details/46798619\n\nclass Solution:\n # @param {integer} n\n # @return {integer}\n def countDigitOne(self, n):\n ones, m = 0, 1\n while m <= n:\n ones += (n/m + 8) / 10 * m + (n/m % 10 == 1) * (n%m + 1)\n m *= 10\n return ones\n \n","sub_path":"python/number_of_digit_one.py","file_name":"number_of_digit_one.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"555968366","text":"import sys\r\n\r\nimport pygame\r\n\r\nfrom bullet import Bullet\r\n\r\nfrom time import sleep\r\n\r\n\r\ndef check_keydown_events(event,stats, ai_settings, screen, ship, bullets):\r\n '''响应按键'''\r\n \r\n #按下右键时,飞船连续移动开关打开\r\n if event.key==pygame.K_RIGHT:\r\n ship.moving_right=True\r\n \r\n #按下左键时,飞船连续移动开关打开\r\n elif event.key==pygame.K_LEFT:\r\n ship.moving_left=True\r\n \r\n elif event.key==pygame.K_UP:\r\n ship.moving_top=True\r\n \r\n elif event.key==pygame.K_DOWN:\r\n ship.moving_bottom=True\r\n \r\n elif event.key==pygame.K_SPACE:\r\n fire_bullet(ai_settings, screen, ship, bullets)\r\n \r\n elif event.key==pygame.K_q:\r\n sys.exit() \r\n \r\n elif event.key==pygame.K_p:\r\n start_game(stats,bullets,ai_settings,ship)\r\n \r\n \r\ndef check_keyup_events(event,ship):\r\n '''响应松开'''\r\n #松开右键时,飞船连续移动开关关闭\r\n if event.key==pygame.K_RIGHT:\r\n ship.moving_right=False\r\n #松开左键时,飞船连续移动开关关闭\r\n if event.key==pygame.K_LEFT:\r\n ship.moving_left=False\r\n \r\n if event.key==pygame.K_UP:\r\n ship.moving_top=False\r\n \r\n if event.key==pygame.K_DOWN:\r\n ship.moving_bottom=False\r\n\r\ndef check_events(ai_settings, stats,play_button,screen, ship, bullets):\r\n '''响应按键和鼠标事件'''\r\n #监视鼠标和电脑事件\r\n for event in pygame.event.get():\r\n \r\n if event.type==pygame.QUIT:#鼠标点击关闭窗口\r\n sys.exit()#退出程序\r\n \r\n #监测按键\r\n elif event.type==pygame.KEYDOWN:\r\n check_keydown_events(event,stats, ai_settings, screen, ship, bullets)\r\n \r\n #监测松键\r\n elif event.type==pygame.KEYUP: \r\n check_keyup_events(event,ship)\r\n \r\n #检测点击屏幕\r\n elif event.type==pygame.MOUSEBUTTONDOWN:#点击屏幕行为\r\n mouse_x,mouse_y=pygame.mouse.get_pos()#它返回一个元组,其中包含玩家单击时鼠标的x 和y 坐标\r\n check_play_button(ai_settings,stats,play_button,ship,bullets,mouse_x,mouse_y)\r\n \r\n \r\ndef fire_bullet(ai_settings,screen,ship,bullets):\r\n '''如果子弹还没达到上限,就再发一颗子弹'''\r\n if len(bullets)<=ai_settings.bullets_allowed:\r\n new_bullet=Bullet(ai_settings, screen, ship)\r\n #创建一颗子弹并加入编组bullets中\r\n bullets.add(new_bullet)\r\n \r\n\r\n \r\ndef update_screen(ai_settings,stats,play_button,ship, bullets,rectangle,rectangles):\r\n '''更新屏幕上的图像并切换到新屏幕'''\r\n\r\n #每次循环时都重绘屏幕\r\n\r\n #在飞船和外星人后面重绘所有子弹\r\n for bullet in bullets.sprites():#方法bullets.sprites() 返回一个列表,其中包含编组\r\n #bullets 中的所有精灵。为在屏幕上绘制发射的所有子弹\r\n bullet.draw_bullet()\r\n #检查子弹和矩形的碰撞,并删除相应子弹\r\n checke_bullet_anlien_collisions(ai_settings,bullets,rectangle,rectangles)\r\n \r\n #记录未击中矩形的子弹,并删除子弹\r\n not_hit(stats,bullets)\r\n \r\n #超过限定子弹未击中,结束游戏\r\n stop_game(stats,bullets,ship)\r\n #在屏幕上绘制矩形\r\n rectangle.draw_bullet()\r\n \r\n if not stats.game_active:\r\n \r\n play_button.draw_button()#为了让按钮处于屏幕顶层,绘制完其他元素再绘制按钮\r\n \r\n \r\ndef update_bullets(bullets):\r\n '''更新子弹位置'''\r\n #更新子弹位置\r\n bullets.update()\r\n \r\ndef update_rectangles(ai_settings,rectangle):\r\n '''更新矩形位置'''\r\n global i\r\n if i==ai_settings.upgrade_number:#如果矩形被击中5次,移动速度加快\r\n ai_settings.increase_speed()\r\n i=0 #速度升级后次数累计归零重新开始计数\r\n print(ai_settings.rectangle_speed)\r\n rectangle.update(ai_settings)\r\n\r\ni=0 \r\ndef checke_bullet_anlien_collisions(ai_settings,bullets,rectangle,rectangles):\r\n '''检查子弹和矩形的碰撞'''\r\n #检查是否有子弹击中了矩形\r\n #如果有,就删除相应的子弹\r\n bullet_list=pygame.sprite.spritecollideany(rectangle,bullets)\r\n global i #i是子弹与矩形发生碰撞的次数累计\r\n \r\n if bullet_list != None:\r\n i+=1\r\n\r\n collision=pygame.sprite.groupcollide(bullets,rectangles,True,False)\r\n\r\n '''这行代码遍历编组bullets 中的每颗子弹,再遍历编组aliens 中的每个外星人。每当有子弹和外星人\r\n #的rect 重叠时,groupcollide() 就在它返回的字典中添加一 个键-值对。两个实参True 告诉\r\n #Pygame删除发生碰撞的子弹和外星人。(要模拟能够穿行到屏幕顶端的高能子弹——消灭它击中的每个外星\r\n #人,可将第一个布尔实参设置 为False ,并让第二个布尔实参为True 。这样被击中的外星人将消失,\r\n #但所有的子弹都始终有效,直到抵达屏幕顶端后消失。)'''\r\n \r\ndef count_not_hit(bullets):\r\n '''记录未击中矩形的子弹,并删除子弹'''\r\n count=0\r\n #删除已消失子弹\r\n for bullet in bullets.copy():\r\n if bullet.rect.left>1200:\r\n count+=1\r\n bullets.remove(bullet)\r\n \r\n print(len(bullets))\r\n \r\ndef check_play_button(ai_settings,stats,play_button,ship,bullets,mouse_x,mouse_y):\r\n '''在玩家单击play按钮时开始新游戏'''\r\n #测试点是否在矩形内,前面需要一个rect对象,检测点是否在其内\r\n button_clicked=play_button.rect.collidepoint(mouse_x,mouse_y)\r\n if button_clicked and not stats.game_active: #如果游戏在运行点击play区域也不会重置信息 \r\n start_game(stats,bullets,ai_settings,ship)\r\n \r\ndef start_game(stats,bullets,ai_settings,ship):\r\n '''开始游戏'''\r\n #隐藏光标\r\n pygame.mouse.set_visible(False)\r\n #重置游戏统计信息 \r\n stats.reset_stats()\r\n stats.game_active=True\r\n ai_settings.initialize_dynamic_settings()\r\n \r\n #清空子弹列表\r\n bullets.empty()\r\n #让飞船居中\r\n ship.center_ship()\r\n ship.update()\r\n ship.blitme()\r\n \r\ndef not_hit(stats,bullets):\r\n '''没有射击到矩形,删除屏幕外子弹'''\r\n for bullet in bullets.sprites():#加了s的\r\n if bullet.rect.right>=bullet.screen_rect.right :\r\n #将hit_limit减1\r\n stats.hit_limit-=1\r\n bullets.remove(bullet)\r\n \r\ndef stop_game(stats,bullets,ship): \r\n if stats.hit_limit==0:\r\n #暂停\r\n sleep(0.5)\r\n \r\n #清空子弹列表\r\n bullets.empty()\r\n \r\n #将飞船放到屏幕底端中央\r\n ship.center_ship()\r\n \r\n stats.game_active=False\r\n pygame.mouse.set_visible(True)#鼠标可见\r\n \r\n","sub_path":"game_functions.py","file_name":"game_functions.py","file_ext":"py","file_size_in_byte":7192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"39506231","text":"\"\"\"\n\nVocê deverá escrever um programa na linguagem Python, versão 3, que permita a uma \"vítima\" jogar o NIM contra o\ncomputador. O computador, é claro, deverá seguir a estratégia vencedora descrita acima.\n\nSejam n o número de peças inicial e m o número máximo de peças que é possível retirar em uma rodada. Para garantir que\no computador ganhe sempre, é preciso considerar os dois cenários possíveis para o início do jogo:\n\n Se n é múltiplo de (m+1), o computador deve ser \"generoso\" e convidar o jogador a iniciar a partida;\n Caso contrário, o computador toma a inciativa de começar o jogo.\n\nUma vez iniciado o jogo, a estratégia do computador para ganhar consiste em deixar sempre um número de peças que seja\nmúltiplo de (m+1) ao jogador. Caso isso não seja possível, deverá tirar o número máximo de peças possíveis.\n\nSeu trabalho, então, será implementar o Jogo e fazer com que o computador se utilize da estratégia vencedora.\n\nCom o objetivo do EP já definido, uma dúvida que deve surgir nesse momento é como modelar o jogo de forma que possa ser\nimplementado em Python 3 correspondendo rigorosamente às especificações descritas até agora.\n\nPara facilitar seu trabalho e permitir a correção automática do exercício, apresentamos a seguir um modelo, isto é, uma\ndescrição em linhas gerais de um conjunto de funções que resolve o problema proposto neste EP. Embora sejam possíveis\noutras abordagens, é preciso atender exatamente o que está definido abaixo para que a correção automática do trabalho\nfuncione corretamente.\n\nO programa deve implementar:\n\n Uma função computador_escolhe_jogada que recebe, como parâmetros, os números n e m descritos acima e devolve um\n inteiro correspondente à próxima jogada do computador de acordo com a estratégia vencedora.\n Uma função usuario_escolhe_jogada que recebe os mesmos parâmetros, solicita que o jogador informe sua jogada e\n verifica se o valor informado é válido. Se o valor informado for válido, a função deve devolvê-lo; caso contrário,\n deve solicitar novamente ao usuário que informe uma jogada válida.\n Uma função partida que não recebe nenhum parâmetro, solicita ao usuário que informe os valores de n e m e inicia o\n jogo, alternando entre jogadas do computador e do usuário (ou seja, chamadas às duas funções anteriores). A escolha\n da jogada inicial deve ser feita em função da estratégia vencedora, como dito anteriormente. A cada jogada, deve\n ser impresso na tela o estado atual do jogo, ou seja, quantas peças foram removidas na última jogada e quantas\n restam na mesa. Quando a última peça é removida, essa função imprime na tela a mensagem \"O computador ganhou!\"\n ou \"Você ganhou!\" conforme o caso.\n\nObserve que, para isso funcionar, seu programa deve sempre \"lembrar\" qual é o número de peças atualmente no tabuleiro e\nqual é o máximo de peças a retirar em cada jogada.\n\n\"\"\"\n\n\ndef partida():\n\n # Solicita ao usuário os valores de n e m:\n n = int(input(\"Quantas peças? \"))\n m = int(input(\"\\nLimite de peças por jogada? \"))\n\n # Define uma variável para controlar a vez do computador:\n vez_computador = True\n\n # Decide quem iniciará o jogo:\n if n % (m+1) == 0:\n vez_computador = False\n print(\"\\nVocê começa!\")\n else:\n vez_computador = True\n print(\"\\nComputador começa!\")\n\n # Execute enquanto houver peças no jogo:\n while n > 0:\n\n if vez_computador:\n jogada = computador_escolhe_jogada(n, m)\n vez_computador = False\n print(\"\\nComputador retirou\", m, \"peça(s).\")\n else:\n jogada = usuario_escolhe_jogada(n, m)\n vez_computador = True\n print(\"\\nVocê retirou\", m, \"peça(s).\")\n\n # Retira as peças do jogo:\n n = n - jogada\n\n # Mostra o estado atual do jogo:\n print(\"\\nAgora resta(m)\", n, \"peça(s) no tabuleiro\")\n\n # Fim de jogo, verifica quem ganhou:\n if vez_computador:\n print(\"\\nVocê ganhou!\")\n return 1\n else:\n print(\"\\nO computador ganhou!\")\n return 0\n\n\ndef usuario_escolhe_jogada(n, m):\n\n # Define o número de peças do usuário:\n jogada = 0\n\n # Enquanto o número não for válido\n while jogada == 0:\n\n # Solicita ao usuário quantas peças irá tirar:\n jogada = int(input(\"\\nQuantas peças você vai tirar? \"))\n\n # Condições: jogada < n, jogada < m, jogada > 0\n if jogada > n or jogada < 1 or jogada > m:\n print(\"Oops! Jogada inválida! Tente de novo.\\n\")\n\n\n # Valor inválido, continue solicitando ao usuário:\n jogada = 0\n\n # Número de peças válido, então retorne-o:\n return jogada\n\ndef computador_escolhe_jogada(n, m):\n\n # Pode retirar todas as peças?\n if n <= m:\n\n # Retira todas as peças e ganha o jogo:\n return n\n\n else:\n\n # Verifica se é possível deixar uma quantia múltipla de m+1:\n quantidade = n % (m+1)\n\n if quantidade > 0:\n return quantidade\n\n # Não é, então tire m peças:\n return m\n\ndef campeonato():\n\n # Pontuações:\n usuario = 0\n computador = 0\n rodada = 1\n\n while rodada <= 3:\n # Executa a partida:\n print(\"\\n********** Rodada\", rodada, \"**********\\n\")\n vencedor = partida()\n\n # Verifica o resultado, somando a pontuação:\n if vencedor == 1:\n # Usuário venceu:\n usuario = usuario + 1\n else:\n # Computador venceu:\n computador = computador + 1\n\n rodada = rodada + 1\n # Exibe o placar final:\n print(\"\\n**** Final do campeonato! ****\")\n print(\"\\nPlacar: Você\", usuario, \"X\", computador, \"Computador\")\n\n\nprint(\"Bem-vindo ao jogo do NIM! Escolha:\\n\")\nescolha = int(input(\"1 - para jogar uma partida isolada \\n2 - para jogar um campeonato \"))\n\nif escolha != 1 and escolha != 2:\n print(\"Escolha inválida. Tente novamente.\\n\")\n escolha = int(input(\"1 - para jogar uma partida isolada \\n2 - para jogar um campeonato \"))\nif escolha == 1:\n partida()\nelif escolha == 2:\n campeonato()\n\n\n","sub_path":"Coursera - Parte 1/Semana 6/jogoNim.py","file_name":"jogoNim.py","file_ext":"py","file_size_in_byte":6209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"402335261","text":"import os\nimport tornado.escape\nimport settings\nimport hashlib\nimport json\nimport mgr.redistip as redis\n\nimport base64\n\n\ndef getResultFromCache(rh):\n key = rh._Srv[\"url\"] + \"\\t\" + \"\\t\".join(\n [x + \"=\" + rh.get_argument(x) for x in sorted(rh.request.arguments)])\n key = str(base64.b64encode(bytes(key, encoding=\"utf8\")), encoding=\"utf-8\")\n return redis.GLOBAREDIS.get(key)\n\n\ndef write2Cache(rh, response):\n if rh._Srv[\"cachetype\"] == \"N\":\n return\n key = rh._Srv[\"url\"] + \"\\t\" + \"\\t\".join(\n [x + \"=\" + rh.get_argument(x) for x in sorted(rh.request.arguments)])\n key = str(base64.b64encode(bytes(key, encoding=\"utf8\")), encoding=\"utf-8\")\n if settings.DEBUG:\n settings.debugLogger.debug(\"create cache[\" + key + \"]:\")\n print(key)\n redis.GLOBAREDIS.set(key, response, ex=settings.DEFAULTCACHETIME)\n\n\ndef wirteMsg2file(msg, srv, filename, request=None):\n m2 = hashlib.md5()\n m2.update(bytes(srv[\"url\"], encoding=\"utf-8\"))\n dirname = m2.hexdigest()\n pathname = settings.MSGLOGPATH + os.sep + dirname\n if not (os.path.exists(pathname)):\n try:\n os.makedirs(pathname)\n except Exception as e:\n settings.errorLogger.error('创建缓存目录报错,' + pathname)\n settings.errorLogger.error(e)\n return\n try:\n file = open(pathname + os.sep + filename, 'w')\n try:\n if not (request is None):\n file.write(json.dumps(request, cls=redis.DateTimeEncoder, ensure_ascii=False))\n if \"msglog\" in srv:\n if srv[\"msglog\"] != \"N\":\n file.write(\"\\n====respone====\\n\")\n file.write(msg)\n finally:\n file.close()\n\n except OSError as oserror:\n settings.errorLogger.error('创建缓存文件报错,' + pathname + os.sep + filename)\n settings.errorLogger.error(oserror)\n","sub_path":"jobs/msgcache.py","file_name":"msgcache.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"65937839","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import fields, models, api\n\nclass Lead2OpportunityPartner(models.TransientModel):\n \n ######################\n # Private attributes #\n ######################\n _inherit = \"crm.lead2opportunity.partner\"\n\n ###################\n # Default methods #\n ###################\n \n ######################\n # Fields declaration #\n ######################\n team_id = fields.Many2one(string=\"Service\",\n comodel_name=\"crm.team\")\n stage_id = fields.Many2one(comodel_name=\"crm.stage\",\n store=True,\n string=\"Stage\")\n site_id = fields.Many2one(string=\"Site\",\n comodel_name=\"crm.site\")\n site_dependent = fields.Boolean(string=\"Site Dependent\",\n related=\"stage_id.site_dependent\")\n \n ##############################\n # Compute and search methods #\n ##############################\n\n ############################\n # Constrains and onchanges #\n ############################\n @api.onchange(\"team_id\")\n def _onchange_sales_team(self):\n self.site_id = False\n stage_id = self.env[\"crm.stage\"].sudo().search([(\"team_id\",\"=\",self.team_id.id)], limit=1).id\n stage = self.env[\"crm.stage\"].sudo().browse(stage_id)\n self.stage_id = stage_id\n self.user_id = False\n if not self.stage_id.site_dependent:\n self.user_id = stage.sudo().get_assignee()\n\n @api.onchange(\"site_id\")\n def _onchange_site_id(self):\n self.user_id = self.stage_id.sudo().get_assignee(site=self.site_id)\n \n #########################\n # CRUD method overrides #\n #########################\n \n ##################\n # Action methods #\n ##################\n @api.multi\n def action_apply(self):\n self.ensure_one()\n super(Lead2OpportunityPartner, self.sudo().with_context(stage_id=self.stage_id.id,site_id=self.site_id.id)).action_apply()\n return self.env.ref(\"crm.crm_lead_all_leads\").read()[0]\n \n ####################\n # Business methods #\n ####################\n\n","sub_path":"ausphin_special/wizards/crm_lead2opportunity_partner.py","file_name":"crm_lead2opportunity_partner.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"99338617","text":"'''\nComplete this function that modifies a list of integers.\n\n1) For numbers that are multiples of three replace the integer with the string \"Fizz\".\n\n2) For numbers that are multiples of five replace the integer with the string \"Buzz\".\n\n3) For numbers that are multiples of both three AND five replace the integer\n with the string \"FizzBuzz\"\n\nYour function should take in a list of integers as input.\nYour function should not modify the input list.\nYour function should return an updated list with integers and strings.\n'''\n\ndef fizzbuzz(intList):\n outlist = []\n for n in intList:\n if n % 3 == 0 and n % 5 == 0:\n outlist.append('FizzBuzz') \n elif n % 3 == 0:\n outlist.append('Fizz') \n elif n % 5 == 0:\n outlist.append('Buzz') \n else:\n outlist.append(n)\n return outlist\n\n '''\n Your fizzbuzz function. The grader will run `fizzbuzz(intList)` to check if your\n function returns the correct output.\n \n intList: list containing integers\n\n Make sure you write the script so that your algorithm is part of the\n function; you do not need to call the function yourself.\n '''\n\n\n\na = [6,30,7,25,3,1,0,15]\n#a = [0]\nresult = fizzbuzz(a)\nprint(result)","sub_path":"DataAnalyst/_Readiness Assessment/Fizbuzz/Fizbuzz/Fizbuzz.py","file_name":"Fizbuzz.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"543056616","text":"\"\"\"Crunchy: serving up interactive Python tutorials\n\n\"\"\"\nfrom optparse import OptionParser\nimport os\nimport random\nimport socket\ntry:\n import webbrowser\nexcept:\n print(\"Module webbrowser not available; you must be using Jython!\")\n\nimport src.interface\nREQUIRED = 2.4\nif src.interface.python_version < REQUIRED:\n print(\"Crunchy requires at least Python version %s\"%REQUIRED)\n raise SystemExit\n\n# We generate a random string that will be appended to javascript functions\n# (like /exec and /doctest) used to communicate with the Python server and\n# that will be used in any other instances where a session has to be identified.\nsrc.interface.plugin['session_random_id'] = str(int(random.random()*1000000000)) + str(\n int(random.random()*1000000000))\n\nif src.interface.python_version < 3:\n from urllib import quote_plus\n from urlparse import urlsplit\nelse:\n from urllib.parse import quote_plus\n from urllib.parse import urlsplit\n\nimport account_manager\n\ndef find_port(start=8001):\n \"\"\"finds the first free port on 127.0.0.1 starting at start\"\"\"\n finalport = None\n testsock = socket.socket()\n testn = start\n while not finalport and (testn < 65536):\n try:\n testsock.bind(('127.0.0.1', testn))\n finalport = testn\n except socket.error:\n testn += 1\n testsock.close()\n return finalport\n\ndef run_crunchy(host='127.0.0.1', port=None, url=None):\n '''starts Crunchy\n\n * set the port to the value specified, or looks for a free one\n * open a web browser at given url, or a default if not specified\n '''\n # delay importing these until we've parsed the options.\n import src.configuration\n import src.http_serve as http_serve\n import src.pluginloader as pluginloader\n\n if port is None:\n port = find_port()\n else:\n port = find_port(start=port)\n server = http_serve.MyHTTPServer((host, port),\n http_serve.HTTPRequestHandler)\n\n ## plugins will register possible additional keywords that\n ## configuration.py should have access to, before it is initialized\n pluginloader.init_plugin_system(server)\n src.configuration.init()\n ##\n\n base_url = 'http://' + host + ':' + str(port)\n if url is None:\n url = base_url + '/index.html'\n else:\n url = base_url + url\n open_browser(url)\n # print this info so that, if the right browser does not open,\n # the user can copy and paste the URL\n print('\\nCrunchy Server: serving up interactive tutorials at URL ' +\n url + '\\n')\n server.still_serving = True\n while server.still_serving:\n try:\n server.handle_request()\n except KeyboardInterrupt:\n print(\"Received Keyboard Interrupt, Quitting...\")\n server.still_serving = False\n server.server_close()\n\nusage = '''python crunchy.py [options]\n\nIf your browser does not start or does not open a new tab on its own,\nor you have a non-supported browser that starts instead, start Firefox and copy\nthe url displayed in the terminal that appeared when you launched Crunchy into\nthe address bar (that's the white rectangular box at the top\nof your browser that contains stuff like [http:// ...]).\nThe url to be copied there should be something like:\nhttp://127.0.0.1:8002/\nCopy this in and press enter - Crunchy's first page should be displayed.'''\n\ndef parse_options():\n '''parse command line options'''\n parser = OptionParser(usage)\n url_help = \"\"\"Uses a different start page when starting Crunchy\n Remote files: http://... (example: http://docs.python.org)\n Local files: absolute_path.[htm, html, rst, txt, py, pyw]\n \"\"\"\n\n\n ##### NOTE\n # Many options have been commented out as they have not been fully tested\n # since the introduction of user accounts. In this way, a user that\n # types python crunchy.py --help will not be presented with a lot of\n # untested options. And note that even some that are not\n # commented out may not work as expected.\n # This will need to be fixed.\n\n\n #safe_url_help = \"\"\"Uses a different start page when starting Crunchy\n # and treats the site as completely trusted; this means that\n # nothing (including scripts) is removed from the pages.\n #\n # Use ONLY if you absolutely trust the site.\n # Remote files: http://... (example: http://docs.python.org)\n # Local files: absolute_path.[htm, html, rst, txt, py, pyw]\n # \"\"\"\n #interactive_help = \"\"\"Somewhat equivalent to normal \"python -i script.py\".\n # Ignored if --url is used.\n # \"\"\"\n #automated_help = \"\"\"Used when running automated tests to disable request\n # for authentication and to prevent security\n # advisory confirmation from appearing when launching\n # Crunchy.\"\"\"\n parser.add_option(\"--url\", action=\"store\", type=\"string\", dest=\"url\",\n help=url_help)\n\n #parser.add_option(\"--completely_trusted\", action=\"store\", type=\"string\",\n # dest=\"safe_url\", help=safe_url_help)\n #parser.add_option(\"--automated\", action=\"store_true\",\n # dest=\"automated\", help=automated_help)\n #parser.add_option(\"--i\", action=\"store\", type=\"string\", dest=\"interactive\",\n # help=interactive_help)\n parser.add_option(\"--port\", action=\"store\", type=\"int\", dest=\"port\",\n help=\"Specifies the port number to try first (default is 8001) \")\n parser.add_option(\"--single\", action=\"store_true\", dest=\"single_user\",\n help=\"Start session in Single User Mode.\")\n #parser.add_option(\"-d\", \"--debug\", action=\"store_true\", dest=\"debug\",\n # help=\"Enables interactive settings of debug flags \"+\\\n # \"(useful for developers)\")\n #parser.add_option(\"--debug_ALL\", action=\"store_true\", dest=\"debug_all\",\n # help=\"Sets ALL the debug flags to True right from the start \"+\\\n # \"(useful for developers in case of major problems; not fully implemented)\")\n parser.add_option(\"--accounts_file\", action=\"store\", type=\"string\",\n dest=\"accounts_file\",\n help=\"Selects a user accounts file path different from default (.PASSWD)\")\n # a dummy option to get it to work with py2app:\n parser.add_option(\"-p\")\n (options, dummy) = parser.parse_args()\n #if options.debug:\n # src.interface.debug_flag = True\n #else:\n # src.interface.debug_flag = False\n #if options.debug_all:\n # src.interface.debug_flag = True\n # for key in src.interface.debug:\n # src.interface.debug[key] = True\n url = None\n src.interface.completely_safe_url = None\n if options.url:\n url = convert_url(options.url)\n #if options.safe_url:\n # src.interface.completely_safe_url = urlsplit(options.safe_url)[1]\n # url = convert_url(options.safe_url)\n #elif options.interactive:\n # src.interface.interactive = True\n # url = convert_url(options.interactive)\n #if options.automated:\n # src.interface.config['initial_security_set'] = True\n # src.interface.config['automated'] = True\n port = None\n if options.port:\n port = options.port\n if options.accounts_file:\n if os.path.exists(options.accounts_file):\n src.interface.accounts = account_manager.Accounts(\n options.accounts_file)\n else:\n print(\"Specifid account file does not exists.\")\n raise SystemExit\n elif options.single_user:\n src.interface.accounts = account_manager.Accounts(False)\n else:\n src.interface.accounts = account_manager.Accounts()\n if src.interface.accounts == {}: # can happen with empty password file\n src.interface.accounts = account_manager.Accounts(False)\n return url, port\n\ndef convert_url(url):\n '''converts a url into a form used by Crunchy'''\n if src.interface.interactive:\n if 'py' in url.split('.')[-1]:\n url = \"/py?url=%s\" % quote_plus(url)\n return url\n else:\n print(\"invalid file type for --i option.\")\n raise SystemExit\n if url.startswith(\"http:\"):\n url = \"/remote?url=%s\" % quote_plus(url)\n elif os.path.exists(url):\n if 'htm' in url.split('.')[-1]:\n url = \"/local?url=%s\" % quote_plus(url)\n elif url.split('.')[-1] in ['rst', 'txt']:\n url = \"/rst?url=%s\" % quote_plus(url)\n elif 'py' in url.split('.')[-1]:\n url = \"/py?url=%s\" % quote_plus(url)\n else:\n print(\"unknown url file type\")\n raise SystemExit\n else:\n print(\"url specified can not be found.\")\n raise SystemExit\n return url\n\ndef open_browser(url):\n \"\"\"\n Open the browser. This function does its best to open Firefox as it's\n the only browser we test Crunchy in.\n \"\"\"\n try:\n client = webbrowser.get(\"firefox\")\n client.open(url)\n return\n except:\n try:\n client = webbrowser.get()\n client.open(url)\n return\n except:\n print('Please open %s in Firefox.' % url)\n\nif __name__ == \"__main__\":\n _url, _port = parse_options()\n run_crunchy(port=_port, url=_url)\n","sub_path":"crunchy/crunchy.py","file_name":"crunchy.py","file_ext":"py","file_size_in_byte":9543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"494866261","text":"\"\"\"\nModule For the ListParser\n\"\"\"\nimport argparse\nfrom conjur.argument_parser.parser_utils import command_description, command_epilog, formatter, \\\n title_formatter\nfrom conjur.wrapper.argparse_wrapper import ArgparseWrapper\n\n# pylint: disable=too-few-public-methods\nclass ListParser:\n \"\"\"Partial class of the ArgParseBuilder.\n This class add the List subparser to the ArgParseBuilder parser.\"\"\"\n\n def __init__(self):\n self.resource_subparsers = None # here to reduce warnings on resource_subparsers not exist\n raise NotImplementedError(\"this is partial class of ArgParseBuilder\")\n\n def add_list_parser(self):\n \"\"\"\n Method adds list parser functionality to parser\n \"\"\"\n list_subparser = self._create_list_parser()\n self._add_list_options(list_subparser)\n\n return self\n\n def _create_list_parser(self):\n list_name = 'list - List resources within an organization\\'s account'\n list_usage = 'conjur [global options] list [options] [args]'\n\n list_subparser = self.resource_subparsers \\\n .add_parser('list',\n help='List all available resources belonging to this account',\n description=command_description(list_name,\n list_usage),\n epilog=command_epilog(\n 'conjur list --kind=variable\\t\\t\\t'\n 'Filters list by variable\\n'\n ' conjur list --limit=20\\t\\t\\t'\n 'Lists first 20 resources\\n'\n ' conjur list --offset=4\\t\\t\\t'\n 'Skips the first 4 resources in the list and displays all the rest\\n'\n ' conjur list --role=myorg:user:superuser\\t'\n 'Shows resources that superuser is entitled to see\\n'\n ' conjur list --search=superuser\\t\\t'\n 'Searches for resources with superuser\\n'),\n usage=argparse.SUPPRESS,\n add_help=False,\n formatter_class=formatter)\n\n return list_subparser\n\n @staticmethod\n def _add_list_options(list_subparser: ArgparseWrapper):\n list_options = list_subparser.add_argument_group(title=title_formatter(\"Options\"))\n list_options.add_argument('-i', '--inspect',\n action='store_true', dest='inspect',\n help='Optional- list the metadata for resources')\n list_options.add_argument('-k', '--kind',\n action='store', metavar='VALUE', dest='kind',\n help='Optional- filter resources by specified kind '\n '(user | host | layer | group '\n '| policy | variable | webservice)')\n list_options.add_argument('-l', '--limit',\n action='store', metavar='VALUE', dest='limit',\n help='Optional- limit list of resources to specified number')\n list_options.add_argument('-o', '--offset',\n action='store', metavar='VALUE', dest='offset',\n help='Optional- skip specified number of resources')\n list_options.add_argument('-r', '--role',\n action='store', metavar='VALUE', dest='role',\n help='Optional- retrieve list of resources that specified role '\n 'is entitled to see (must specify role’s full ID)')\n list_options.add_argument('-s', '--search',\n action='store', metavar='VALUE', dest='search',\n help='Optional- search for resources based on specified query')\n list_options.add_argument('-h', '--help', action='help',\n help='Display help screen and exit')\n","sub_path":"conjur/argument_parser/_list_parser.py","file_name":"_list_parser.py","file_ext":"py","file_size_in_byte":4131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"472915470","text":"import autoarray as aa\nimport autoarray.plot as aplt\n\nmask = aa.mask.circular(shape_2d=(7, 7), pixel_scales=0.3, radius=0.6)\n\nimaging = aa.imaging(\n image=aa.array.ones(shape_2d=(7, 7), pixel_scales=0.3),\n noise_map=aa.array.ones(shape_2d=(7, 7), pixel_scales=0.3),\n psf=aa.kernel.ones(shape_2d=(3, 3), pixel_scales=0.3),\n)\n\nmasked_imaging = aa.masked.imaging(imaging=imaging, mask=mask)\n\ngrid_7x7 = aa.grid.from_mask(mask=mask)\nrectangular_grid = aa.grid_rectangular.overlay_grid(grid=grid_7x7, shape_2d=(3, 3))\nrectangular_mapper = aa.mapper(grid=grid_7x7, pixelization_grid=rectangular_grid)\n\nregularization = aa.reg.Constant(coefficient=1.0)\n\ninversion = aa.inversion(\n masked_dataset=masked_imaging,\n mapper=rectangular_mapper,\n regularization=regularization,\n)\n\naplt.inversion.subplot_inversion(\n inversion=inversion,\n image_positions=[(0.05, 0.05)],\n lines=[(0.0, 0.0), (0.1, 0.1)],\n image_pixel_indexes=[0],\n source_pixel_indexes=[5],\n)\n","sub_path":"test_autoarray/inversion_rectangular/subplot.py","file_name":"subplot.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"403231799","text":"import sys, os, numpy as np\nfrom PIL import Image, ImageDraw, ImageFont\nfrom PIL.ImageColor import getcolor, getrgb\nfrom PIL.ImageOps import grayscale\nfrom crfrnn_model import get_crfrnn_model_def\n\nGenImSize = 128\nFitImSize = 500\n\ndef MakeCellImage(x, y, r, i):\n im = Image.new(mode='F', size=(GenImSize, GenImSize))\n draw = ImageDraw.Draw(im)\n draw.ellipse(xy=[x-r, y-r, x+r, y+r], fill='White')\n im = np.array(im).astype(np.float32)\n im *= (i / 255.0)\n return im\n\ndef MakeRandomCellImage(n):\n im = np.zeros(shape=(GenImSize, GenImSize))\n for i in range(n):\n radius = np.random.randint(low=-5, high=10) + 10\n intensity = (np.random.randn() * 0.1) + 0.5\n intensity = max(min(intensity, 1.0), 0.0)\n position = np.random.randint(low=radius, high=GenImSize-radius, size=2)\n im += MakeCellImage(position[0], position[1], radius, intensity)\n \n im_rand = im + (np.random.randn(im.shape[0], im.shape[1]) * 0.1) + 0.2\n im_rand[im_rand < 0] = 0\n im_rand[im_rand > 1] = 1\n im[im > 0] = 1\n im[im < 1] = 0\n return im, im_rand\n\ndef MakeInputData(n):\n im, im_rand = MakeRandomCellImage(n)\n im_rand_ = Image.fromarray(im_rand)\n im_rand_ = im_rand_.resize((FitImSize, FitImSize), Image.ANTIALIAS)\n im_rand_ = np.array(im_rand_)\n im_rand_ = im_rand_.astype(np.float32)\n im_rand_ -= np.mean(im_rand_.flatten())\n im_rand_ /= np.std(im_rand_.flatten())\n\n # return im, im_rand, im_rand_[np.newaxis, :, :, np.newaxis]\n return im, im_rand, im_rand_.reshape(1, FitImSize, FitImSize, 1)\n\ndef image_tint(im, tint='#ff0000'):\n\n src = Image.new('RGB', im.size)\n src.paste(im)\n\n tr, tg, tb = getrgb(tint)\n tl = getcolor(tint, \"L\") # tint color's overall luminosity\n if not tl: tl = 1 # avoid division by zero\n tl = float(tl) # compute luminosity preserving tint factors\n sr, sg, sb = map(lambda tv: tv/tl, (tr, tg, tb)) # per component adjustments\n\n # create look-up tables to map luminosity to adjusted tint\n # (using floating-point math only to compute table)\n luts = (list(map(lambda lr: int(lr*sr + 0.5), range(256))) +\n list(map(lambda lg: int(lg*sg + 0.5), range(256))) +\n list(map(lambda lb: int(lb*sb + 0.5), range(256))))\n l = grayscale(src) # 8-bit luminosity version of whole image\n if Image.getmodebands(src.mode) < 4:\n merge_args = (src.mode, (l, l, l)) # for RGB verion of grayscale\n else: # include copy of src image's alpha layer\n a = Image.new(\"L\", src.size)\n a.putdata(src.getdata(3))\n merge_args = (src.mode, (l, l, l, a)) # for RGBA verion of grayscale\n luts += range(256) # for 1:1 mapping of copied alpha values\n\n return Image.merge(*merge_args).point(luts)\n\nsaved_model_path = \"SegmentationModel_Weights.h5\"\nnTest = 128\n\nfont = ImageFont.truetype(\"/usr/share/fonts/TTF/Anonymous Pro.ttf\", 8, encoding=\"unic\")\nlabel_seg_gt = u\"Segmentation (Ground Truth)\"\nlabel_im = u\"Image\"\nlabel_seg = u\"Computed Segmentation\"\ntext_width_gt, text_height_gt = font.getsize(label_seg_gt)\ntext_width_im, text_height_im = font.getsize(label_im)\ntext_width_seg, text_height_seg = font.getsize(label_seg)\n\nmodel = get_crfrnn_model_def()\nmodel.load_weights(saved_model_path, by_name=True)\n\nfor i in range(nTest):\n seg_gt, im, im_input = MakeInputData(n=np.random.randint(low=1, high=5))\n probs = model.predict(im_input, verbose=False)[0, :, :, :]\n labels = probs.argmax(axis=2)\n\n seg_gt = Image.fromarray((seg_gt * 255).astype(\"uint8\"))\n im = Image.fromarray((im * 255).astype(\"uint8\"))\n labels = Image.fromarray((labels * 255).astype(\"uint8\"))\n labels = labels.resize((GenImSize, GenImSize), Image.NEAREST)\n\n seg_gt = image_tint(seg_gt, tint='#8AFAAB')\n im = image_tint(im, tint='#8AA0FA')\n labels = image_tint(labels, tint='#F98A8A')\n\n draw_gt = ImageDraw.Draw(seg_gt)\n draw_gt.text((int((GenImSize-text_width_gt)/2), 1), label_seg_gt, 'green', font)\n draw_im = ImageDraw.Draw(im)\n draw_im.text((int((GenImSize-text_width_im)/2), 1), label_im, 'blue', font)\n draw_seg = ImageDraw.Draw(labels)\n draw_seg.text((int((GenImSize-text_width_seg)/2), 1), label_seg, 'red', font)\n\n full_im = Image.new('RGB', (3 * GenImSize, GenImSize))\n full_im.paste(im, (0, 0))\n full_im.paste(seg_gt, (GenImSize, 0))\n full_im.paste(labels, (2 * GenImSize, 0))\n\n full_im.save(\"testOutput/test_{}.png\".format(i))\n sys.stdout.write(\"Testing: {0:.2f}%\".format(100.0 * (i+1) / (nTest)) + '\\r')\n sys.stdout.flush()\n \nprint(\"Testing: {0:.2f}%\".format(100.0 * (i+1) / (nTest)))\n # seg_gt.save(\"testOutput/seg_gt_{}.png\".format(i))\n # im.save(\"testOutput/im_{}.png\".format(i))\n # labels.save(\"testOutput/seg_{}.png\".format(i))\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"408264256","text":"# coding=utf-8\n__author__ = 'chenasraf'\n\nimport os, re\nfrom bson.objectid import ObjectId\nfrom back.commons import logging\n\n\nclass MediaScanner:\n FILE_PATTERN = r'\\.(mkv|avi|mp4|mpg)$'\n\n def __init__(self, db, func_done):\n self.db = db\n self.libraries = db.libraries.find()\n self.media = db.media\n self.new_files = []\n self.old_files = []\n self.all_files = []\n self.func_done = func_done\n\n def scan_directory(self, library_id, dir_name, library_dir, recursive):\n logging.info(\" |- Scanning directory: %s %s\" % (dir_name, '(recursive)' if recursive else ''))\n dirs = []\n for file_name in os.listdir(dir_name):\n\n full_path = os.path.join(dir_name, file_name)\n relative_name = full_path[len(library_dir)+1:]\n if os.path.isfile(full_path) and re.search(self.FILE_PATTERN, file_name, re.IGNORECASE):\n if not self.media.find_one({\"full_path\": full_path}):\n media_id = self.media.insert({\n \"file_name\": file_name,\n \"full_path\": full_path,\n \"relative_name\": relative_name,\n \"path\": dir_name,\n \"library_id\": ObjectId(library_id),\n \"metadata\": {}\n })\n\n final_media_id = media_id\n self.new_files.append(final_media_id)\n logging.info(u\" | ∟ Added media: %s\" % file_name)\n else:\n final_media_id = self.media.find_one({\"full_path\": full_path})['_id']\n self.old_files.append(final_media_id)\n logging.info(u\" | ∟ Already exists: %s\" % file_name)\n\n self.all_files.append(final_media_id)\n\n elif recursive and os.path.isdir(full_path) and not file_name.startswith('.'):\n dirs.append(full_path)\n\n if recursive and len(dirs) > 0:\n for scan_dir in dirs:\n self.scan_directory(library_id, scan_dir, library_dir, recursive)\n\n def start(self):\n for library in self.libraries:\n logging.info('Scanning library: \"%s\"' % library['name'])\n\n for location in library['locations']:\n recursive = False\n if 'recursive' in location:\n recursive = location['recursive']\n\n self.scan_directory(library['_id'], location['path'], location['path'], recursive)\n\n logging.info('Finished scanning library: \"%s\"' % library['name'])\n\n logging.info(\"Finished scanning libraries.\")\n logging.info(\"New media files: \" + ', '.join(map(str, self.new_files)))\n logging.info(\"Already existing files: \" + ', '.join(map(str, self.old_files)))\n\n if hasattr(self.func_done, '__call__'):\n self.func_done(self.all_files)\n","sub_path":"back/media_scanner.py","file_name":"media_scanner.py","file_ext":"py","file_size_in_byte":2922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"16265709","text":"# configs for twitter homework.\n\nimport requests\nfrom requests_oauthlib import OAuth1\nimport pandas as pd\n\n#replace with your own personal twitter API keys\nauth = OAuth1()\n\n#API endpoint and search string for functions find_user, get_followers\nuser_base_url = 'https://api.twitter.com/1.1/users/lookup.json'\nuser_search = '?screen_name='\n\n#user is a string field relating to twitter usernames, keys are none by default but can be set to extract specific fields\n#for example ['name', 'followers_count']\n\ndef find_user(user, keys=None):\n results = requests.get(user_base_url + user_search + user.replace('@', ''), auth=auth).json()[0]\n\n if keys != None:\n reduced_results = {}\n for key in keys:\n reduced_results[key] = results[key]\n return reduced_results\n\n else:\n return results\n\n#test prompts for find_user function to be used for testing\n# find_user('@GA', keys=['name', 'screen_name', 'followers_count', 'friends_count'])\n# find_user('@GA')\n\n#screen_name is a string field relating to twitter usernames, as above keys are defaulted to None, to_df is also\n#set to False by default, toggling to True will return results in a pd DataFrame.\n\ndef get_followers(screen_name, keys=None, to_df=False):\n results = requests.get(user_base_url + user_search + screen_name.replace('@', ''), auth=auth).json()[0]\n\n if keys != None:\n reduced_results = {}\n for key in keys:\n reduced_results[key] = results[key]\n if to_df == True:\n df = pd.DataFrame(reduced_results, index=[0]) # setting index as 0 as pandas is enforcing an index\n return df\n else:\n return reduced_results\n\n else:\n if to_df == True:\n df = pd.DataFrame(results, index=[0]) # setting index as 0 as pandas is enforcing an index\n return df\n else:\n return results\n\n#test prompts for get_followers function to be used for testing\n# get_followers('@GA', keys=['name', 'screen_name', 'followers_count', 'friends_count'], to_df=True)\n# get_followers('@GA')\n# get_followers('GA')\n# get_followers('GA', keys=['name', 'followers_count'])\n# get_followers('GA', keys=['name', 'followers_count'], to_df=True)\n# get_followers('GA', to_df=True)\n\n# function friends_of_friends : goal is to find mutual friends between two users.\n# I got stuck at trying to return numerous names or ids when those keys are passed through. When they are not\n# passed through, I get the entire dictionary, do you know what's causing this?\n\nfriends_base_url = 'https://api.twitter.com/1.1/friends/list.json'\nuser_search = '?screen_name='\n\n\ndef friends_of_friends(name1, name2, keys=None, to_df=False):\n names = [name1, name2]\n name_list = [name.replace('@', '') for name in names]\n\n results = [requests.get(friends_base_url + user_search + name, auth=auth).json() for name in name_list]\n\n followers = [i['users'] for i in results]\n\n flat_list = []\n for sublist in followers:\n results = [sublist for sublist in sublist]\n\n if keys != None:\n\n reduced_list = []\n for user in results:\n user_dict = {}\n for key in keys:\n user_dict[key] = user[key]\n reduced_list.append(user_dict)\n\n if to_df != False:\n return pd.DataFrame(reduced_list)\n\n else:\n return reduced_list\n\n elif to_df != False:\n return pd.DataFrame(results)\n\n else:\n return results\n\n#test prompts for friends_of_friends\n# friends_of_friends('Beyonce', 'MariahCarey')\n# friends_of_friends('Beyonce', 'MariahCarey', keys=['name'], to_df=True)\n# friends_of_friends('Beyonce', 'MariahCarey', to_df=True)\n\n#find_hashtag function, work in progress\n\n# base_url = 'https://api.twitter.com/1.1/search/tweets.json'\n#\n# def find_hashtag(hashtag, count=None, result_type=None):\n# # creating a tweet variable from the hashtag input, replacing hash with ''\n# clean_hashtag = hashtag.replace('#', '')\n# tweets = '?qtext=%23' + f\"{clean_hashtag}\"\n#\n# # creating a count variable for count input\n# if count != None:\n# count = '&count=' + f\"{count}\"\n#\n# # creating a result_type variable\n# if result_type != None:\n# result_type = 'result_type=' + f\"{result_type}\"\n#\n# # results from API endpoint, currently not configured for count and result_type\n# search_results = requests.get(base_url + tweets, auth=auth).json()\n# return search_results\n#\n# # if keys != None:\n# # reduced_results_list = []\n# # for result in search_results:\n# # new_user_dict = {}\n# # for key in keys:\n# # new_user_dict[key] = result[key]\n# # reduced_results_list.append(new_user_dict)\n#\n# find_hashtag('#DataScience')","sub_path":"Homework/Unit1/Twitter/twitter.py","file_name":"twitter.py","file_ext":"py","file_size_in_byte":4888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"349433145","text":"import datetime\n\nimport numpy as np\nimport pandas as pd\nimport pytest\nfrom sklearn.exceptions import NotFittedError\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.metrics import mean_squared_error\nfrom testfixtures import LogCapture\n\nimport greykite.common.constants as cst\nfrom greykite.algo.forecast.silverkite.forecast_silverkite import SilverkiteForecast\nfrom greykite.common.data_loader import DataLoader\nfrom greykite.common.features.timeseries_features import convert_date_to_continuous_time\nfrom greykite.common.python_utils import assert_equal\nfrom greykite.common.testing_utils import daily_data_reg\nfrom greykite.common.testing_utils import generate_df_for_tests\nfrom greykite.common.testing_utils import generate_df_with_reg_for_tests\nfrom greykite.sklearn.estimator.base_silverkite_estimator import BaseSilverkiteEstimator\nfrom greykite.sklearn.estimator.testing_utils import params_components\n\n\n@pytest.fixture\ndef params():\n autoreg_dict = {\n \"lag_dict\": {\"orders\": [7]},\n \"agg_lag_dict\": {\n \"orders_list\": [[7, 7 * 2, 7 * 3]],\n \"interval_list\": [(7, 7 * 2)]},\n \"series_na_fill_func\": lambda s: s.bfill().ffill()}\n uncertainty_dict = {\n \"uncertainty_method\": \"simple_conditional_residuals\",\n \"params\": {\n \"conditional_cols\": [\"dow\"],\n \"quantiles\": [0.025, 0.975],\n \"quantile_estimation_method\": \"normal_fit\",\n \"sample_size_thresh\": 5,\n \"small_sample_size_method\": \"std_quantiles\",\n \"small_sample_size_quantile\": 0.98}}\n return {\n \"origin_for_time_vars\": convert_date_to_continuous_time(datetime.datetime(2018, 1, 3)),\n \"extra_pred_cols\": [\"ct1\", \"regressor1\", \"regressor2\"],\n \"train_test_thresh\": None,\n \"training_fraction\": None,\n \"fit_algorithm\": \"sgd\",\n \"fit_algorithm_params\": {\"alpha\": 0.1},\n \"daily_event_df_dict\": None,\n \"changepoints_dict\": None,\n \"fs_components_df\": pd.DataFrame({\n \"name\": [\"tow\"],\n \"period\": [7.0],\n \"order\": [3],\n \"seas_names\": [None]}),\n \"autoreg_dict\": autoreg_dict,\n \"min_admissible_value\": None,\n \"max_admissible_value\": None,\n \"uncertainty_dict\": uncertainty_dict\n }\n\n\n@pytest.fixture\ndef daily_data():\n return generate_df_for_tests(\n freq=\"D\",\n periods=1000,\n train_start_date=datetime.datetime(2018, 1, 1),\n conti_year_origin=2018)\n\n\n@pytest.fixture\ndef daily_data_with_reg():\n return daily_data_reg()\n\n\n@pytest.fixture\ndef X():\n periods = 11\n return pd.DataFrame({\n cst.TIME_COL: pd.date_range(\"2018-01-01\", periods=periods, freq=\"D\"),\n cst.VALUE_COL: np.arange(1, periods + 1)\n })\n\n\n@pytest.fixture\ndef df_pt():\n \"\"\"fetches the Peyton Manning pageview data\"\"\"\n dl = DataLoader()\n return dl.load_peyton_manning()\n\n\ndef test_init(params):\n \"\"\"Checks if parameters are passed to BaseSilverkiteEstimator correctly\"\"\"\n coverage = 0.95\n uncertainty_dict = {\n \"uncertainty_method\": \"simple_conditional_residuals\",\n \"params\": {\n \"conditional_cols\": [\"dow\"],\n \"quantiles\": [0.025, 0.975],\n \"quantile_estimation_method\": \"normal_fit\",\n \"sample_size_thresh\": 5,\n \"small_sample_size_method\": \"std_quantiles\",\n \"small_sample_size_quantile\": 0.98}}\n model = BaseSilverkiteEstimator(\n score_func=mean_squared_error,\n coverage=coverage,\n null_model_params=None,\n uncertainty_dict=uncertainty_dict)\n\n assert model.score_func == mean_squared_error\n assert model.coverage == coverage\n assert model.null_model_params is None\n assert model.uncertainty_dict == uncertainty_dict\n\n assert model.model_dict is None\n assert model.pred_cols is None\n assert model.feature_cols is None\n assert model.df is None\n assert model.coef_ is None\n\n\ndef test_null_model(X):\n \"\"\"Checks null model\"\"\"\n model = BaseSilverkiteEstimator(null_model_params={\n \"strategy\": \"quantile\",\n \"constant\": None,\n \"quantile\": 0.8})\n\n model.fit(X)\n y = np.repeat(2.0, X.shape[0])\n null_score = model.null_model.score(X, y=y)\n assert null_score == mean_squared_error(y, np.repeat(9.0, X.shape[0]))\n\n # tests if different score function gets propagated to null model\n model = BaseSilverkiteEstimator(\n score_func=mean_absolute_error,\n null_model_params={\"strategy\": \"quantile\",\n \"constant\": None,\n \"quantile\": 0.8})\n model.fit(X)\n y = np.repeat(2.0, X.shape[0])\n null_score = model.null_model.score(X, y=y)\n assert null_score == mean_absolute_error(y, np.repeat(9.0, X.shape[0]))\n # checks that `df` is set\n assert_equal(X, model.df)\n\n\ndef test_fit_predict(daily_data):\n \"\"\"Checks fit and predict function with null model\"\"\"\n model = BaseSilverkiteEstimator(null_model_params={\"strategy\": \"mean\"})\n train_df = daily_data[\"train_df\"]\n test_df = daily_data[\"test_df\"]\n assert model.last_predicted_X_ is None\n assert model.cached_predictions_ is None\n\n with pytest.raises(\n NotFittedError,\n match=\"Call `fit` before calling `predict`.\"):\n model.predict(train_df)\n\n # Every subclass `fit` follows these steps\n model.fit(\n train_df,\n time_col=cst.TIME_COL,\n value_col=cst.VALUE_COL)\n # Checks that `df` is set, but other variables aren't\n assert_equal(model.df, train_df)\n assert model.pred_cols is None\n assert model.feature_cols is None\n assert model.coef_ is None\n\n with pytest.raises(ValueError, match=\"Must set `self.model_dict` before calling this function.\"):\n model.finish_fit()\n\n silverkite = SilverkiteForecast()\n model.model_dict = silverkite.forecast(\n df=train_df,\n time_col=cst.TIME_COL,\n value_col=cst.VALUE_COL,\n origin_for_time_vars=None,\n extra_pred_cols=None,\n train_test_thresh=None,\n training_fraction=None,\n fit_algorithm=\"linear\",\n fit_algorithm_params=None,\n daily_event_df_dict=None,\n changepoints_dict=None,\n fs_components_df=pd.DataFrame({\n \"name\": [\"tod\", \"tow\", \"conti_year\"],\n \"period\": [24.0, 7.0, 1.0],\n \"order\": [3, 3, 5],\n \"seas_names\": [\"daily\", \"weekly\", \"yearly\"]}),\n autoreg_dict=None,\n min_admissible_value=None,\n max_admissible_value=None,\n uncertainty_dict=None\n )\n\n with pytest.raises(\n NotFittedError,\n match=\"Subclass must call `finish_fit` inside the `fit` method.\"):\n model.predict(train_df)\n assert model.last_predicted_X_ is not None # attempted prediction\n assert model.cached_predictions_ is None\n\n model.finish_fit()\n # Checks that other variables are set\n assert_equal(model.pred_cols, model.model_dict[\"pred_cols\"])\n assert_equal(model.feature_cols, model.model_dict[\"x_mat\"].columns)\n assert_equal(model.coef_, pd.DataFrame(\n model.model_dict[\"ml_model\"].coef_,\n index=model.feature_cols))\n\n # Predicts on a new dataset\n with LogCapture(cst.LOGGER_NAME) as log_capture:\n predicted = model.predict(test_df)\n assert_equal(model.last_predicted_X_, test_df)\n assert_equal(model.cached_predictions_, predicted)\n log_capture.check() # no log messages (not using cached predictions)\n\n # Uses cached predictions\n with LogCapture(cst.LOGGER_NAME) as log_capture:\n assert_equal(model.predict(test_df), predicted)\n log_capture.check(\n (cst.LOGGER_NAME, \"DEBUG\", \"Returning cached predictions.\")\n )\n\n # Predicts on a different dataset\n with LogCapture(cst.LOGGER_NAME) as log_capture:\n predicted = model.predict(train_df)\n assert_equal(model.last_predicted_X_, train_df)\n assert_equal(model.cached_predictions_, predicted)\n log_capture.check() # no log messages (not using cached predictions)\n\n # .fit() clears the cached result\n model.fit(train_df, time_col=cst.TIME_COL, value_col=cst.VALUE_COL)\n assert model.last_predicted_X_ is None\n assert model.cached_predictions_ is None\n\n\ndef test_score_function(daily_data_with_reg):\n \"\"\"Checks score function without null model, with regressors\"\"\"\n model = BaseSilverkiteEstimator()\n train_df = daily_data_with_reg[\"train_df\"]\n test_df = daily_data_with_reg[\"test_df\"]\n\n # every subclass `fit` follows these steps\n model.fit(\n X=train_df,\n time_col=cst.TIME_COL,\n value_col=cst.VALUE_COL)\n silverkite = SilverkiteForecast()\n model.model_dict = silverkite.forecast(\n df=train_df,\n time_col=cst.TIME_COL,\n value_col=cst.VALUE_COL,\n origin_for_time_vars=None,\n extra_pred_cols=[\"ct1\", \"regressor1\", \"regressor2\"],\n train_test_thresh=None,\n training_fraction=None,\n fit_algorithm=\"linear\",\n fit_algorithm_params=None,\n daily_event_df_dict=None,\n changepoints_dict=None,\n fs_components_df=pd.DataFrame({\n \"name\": [\"tod\", \"tow\", \"conti_year\"],\n \"period\": [24.0, 7.0, 1.0],\n \"order\": [3, 3, 5],\n \"seas_names\": [\"daily\", \"weekly\", \"yearly\"]}),\n autoreg_dict=None,\n min_admissible_value=None,\n max_admissible_value=None,\n uncertainty_dict=None\n )\n model.finish_fit()\n\n score = model.score(test_df, test_df[cst.VALUE_COL])\n pred_df = model.predict(test_df)\n assert list(pred_df.columns) == [cst.TIME_COL, cst.PREDICTED_COL]\n assert score == pytest.approx(mean_squared_error(\n pred_df[cst.PREDICTED_COL],\n test_df[cst.VALUE_COL]))\n assert score == pytest.approx(4.6, rel=1e-1)\n\n\ndef test_set_uncertainty_dict(daily_data):\n \"\"\"Tests __set_uncertainty_dict\"\"\"\n train_df = daily_data[\"train_df\"]\n\n # both provided\n coverage = 0.95\n uncertainty_dict = {\n \"uncertainty_method\": \"simple_conditional_residuals\",\n \"params\": {\n \"conditional_cols\": [\"dow_hr\"],\n \"quantiles\": [0.025, 0.975],\n \"quantile_estimation_method\": \"normal_fit\",\n \"sample_size_thresh\": 20,\n \"small_sample_size_method\": \"std_quantiles\",\n \"small_sample_size_quantile\": 0.98}}\n model = BaseSilverkiteEstimator(\n coverage=coverage,\n uncertainty_dict=uncertainty_dict)\n model.fit(train_df)\n expected_dict = uncertainty_dict\n assert_equal(model.uncertainty_dict, expected_dict)\n assert_equal(model.coverage, coverage)\n\n # only coverage provided\n coverage = 0.90\n uncertainty_dict = None\n model = BaseSilverkiteEstimator(\n coverage=coverage,\n uncertainty_dict=uncertainty_dict)\n model.fit(train_df)\n expected_dict = {\n \"uncertainty_method\": \"simple_conditional_residuals\",\n \"params\": {\n \"conditional_cols\": [\"dow_hr\"],\n \"quantiles\": [0.05, 0.95],\n \"quantile_estimation_method\": \"normal_fit\",\n \"sample_size_thresh\": 5,\n \"small_sample_size_method\": \"std_quantiles\",\n \"small_sample_size_quantile\": 0.98}}\n assert_equal(model.uncertainty_dict, expected_dict)\n assert_equal(model.coverage, coverage)\n\n # both missing\n coverage = None\n uncertainty_dict = None\n model = BaseSilverkiteEstimator(\n coverage=coverage,\n uncertainty_dict=uncertainty_dict)\n model.fit(train_df)\n expected_dict = None\n assert_equal(model.uncertainty_dict, expected_dict)\n assert_equal(model.coverage, None)\n\n # only uncertainty provided\n coverage = None\n uncertainty_dict = {\n \"uncertainty_method\": \"simple_conditional_residuals\",\n \"params\": {\n \"conditional_cols\": [\"dow_hr\"],\n \"quantiles\": [0.05, 0.95],\n \"quantile_estimation_method\": \"normal_fit\",\n \"sample_size_thresh\": 5,\n \"small_sample_size_method\": \"std_quantiles\",\n \"small_sample_size_quantile\": 0.98}}\n model = BaseSilverkiteEstimator(\n coverage=coverage,\n uncertainty_dict=uncertainty_dict)\n model.fit(train_df)\n expected_dict = uncertainty_dict\n assert_equal(model.uncertainty_dict, expected_dict)\n assert_equal(model.coverage, 0.90)\n\n\ndef test_summary(daily_data):\n \"\"\"Checks summary function returns without error\"\"\"\n model = BaseSilverkiteEstimator()\n train_df = daily_data[\"train_df\"]\n model.summary()\n\n model.fit(\n train_df,\n time_col=cst.TIME_COL,\n value_col=cst.VALUE_COL)\n model.summary()\n\n\ndef test_silverkite_with_components_daily_data():\n \"\"\"Tests get_components, plot_components, plot_trend,\n plot_seasonalities with daily data and missing input values.\n \"\"\"\n daily_data = generate_df_with_reg_for_tests(\n freq=\"D\",\n periods=20,\n train_start_date=datetime.datetime(2018, 1, 1),\n conti_year_origin=2018)\n train_df = daily_data[\"train_df\"].copy()\n train_df.loc[[2, 4, 7], cst.VALUE_COL] = np.nan # creates missing values\n\n params_daily = params_components() # SilverkiteEstimator parameters\n # converts into parameters for `forecast_silverkite`\n coverage = params_daily.pop(\"coverage\")\n # removes daily seasonality terms\n params_daily[\"fs_components_df\"] = pd.DataFrame({\n \"name\": [\"tow\", \"ct1\"],\n \"period\": [7.0, 1.0],\n \"order\": [4, 5],\n \"seas_names\": [\"weekly\", \"yearly\"]})\n\n model = BaseSilverkiteEstimator(\n coverage=coverage,\n uncertainty_dict=params_daily[\"uncertainty_dict\"])\n\n with pytest.raises(\n NotFittedError,\n match=\"Call `fit` before calling `plot_components`.\"):\n model.plot_components()\n\n with pytest.warns(Warning):\n # suppress warnings from conf_interval.py and sklearn\n # a subclass's fit() method will have these steps\n model.fit(\n X=train_df,\n time_col=cst.TIME_COL,\n value_col=cst.VALUE_COL)\n silverkite = SilverkiteForecast()\n model.model_dict = silverkite.forecast(\n df=train_df,\n time_col=cst.TIME_COL,\n value_col=cst.VALUE_COL,\n **params_daily)\n model.finish_fit()\n\n # Tests plot_components\n with pytest.warns(Warning) as record:\n title = \"Custom component plot\"\n model._set_silverkite_diagnostics_params()\n fig = model.plot_components(names=[\"trend\", \"YEARLY_SEASONALITY\", \"DUMMY\"], title=title)\n expected_rows = 3\n assert len(fig.data) == expected_rows + 1 # includes changepoints\n assert [fig.data[i].name for i in range(expected_rows)] == \\\n [cst.VALUE_COL, \"trend\", \"YEARLY_SEASONALITY\"]\n\n assert fig.layout.xaxis.title[\"text\"] == cst.TIME_COL\n assert fig.layout.xaxis2.title[\"text\"] == cst.TIME_COL\n assert fig.layout.xaxis3.title[\"text\"] == \"Time of year\"\n\n assert fig.layout.yaxis.title[\"text\"] == cst.VALUE_COL\n assert fig.layout.yaxis2.title[\"text\"] == \"trend\"\n assert fig.layout.yaxis3.title[\"text\"] == \"yearly\"\n\n assert fig.layout.title[\"text\"] == title\n assert f\"The following components have not been specified in the model: \" \\\n f\"{{'DUMMY'}}, plotting the rest.\" in record[0].message.args[0]\n\n # Missing component error\n with pytest.raises(\n ValueError,\n match=\"None of the provided components have been specified in the model.\"):\n model.plot_components(names=[\"DUMMY\"])\n\n # Tests plot_trend\n title = \"Custom trend plot\"\n fig = model.plot_trend(title=title)\n expected_rows = 2\n assert len(fig.data) == expected_rows + 1 # includes changepoints\n assert [fig.data[i].name for i in range(expected_rows)] == [cst.VALUE_COL, \"trend\"]\n\n assert fig.layout.xaxis.title[\"text\"] == cst.TIME_COL\n assert fig.layout.xaxis2.title[\"text\"] == cst.TIME_COL\n\n assert fig.layout.yaxis.title[\"text\"] == cst.VALUE_COL\n assert fig.layout.yaxis2.title[\"text\"] == \"trend\"\n\n assert fig.layout.title[\"text\"] == title\n\n # Tests plot_seasonalities\n with pytest.warns(Warning):\n # suppresses the warning on seasonalities removed\n title = \"Custom seasonality plot\"\n fig = model.plot_seasonalities(title=title)\n expected_rows = 3\n assert len(fig.data) == expected_rows\n assert [fig.data[i].name for i in range(expected_rows)] == \\\n [cst.VALUE_COL, \"WEEKLY_SEASONALITY\", \"YEARLY_SEASONALITY\"]\n\n assert fig.layout.xaxis.title[\"text\"] == cst.TIME_COL\n assert fig.layout.xaxis2.title[\"text\"] == \"Day of week\"\n assert fig.layout.xaxis3.title[\"text\"] == \"Time of year\"\n\n assert fig.layout.yaxis.title[\"text\"] == cst.VALUE_COL\n assert fig.layout.yaxis2.title[\"text\"] == \"weekly\"\n assert fig.layout.yaxis3.title[\"text\"] == \"yearly\"\n\n assert fig.layout.title[\"text\"] == title\n\n # Component plot error if `fit_algorithm` is \"rf\" or \"gradient_boosting\"\n params_daily[\"fit_algorithm\"] = \"rf\"\n model = BaseSilverkiteEstimator(\n coverage=coverage,\n uncertainty_dict=params_daily[\"uncertainty_dict\"])\n with pytest.warns(Warning):\n # suppress warnings from conf_interval.py and sklearn\n # a subclass's fit() method will have these steps\n model.fit(\n X=train_df,\n time_col=cst.TIME_COL,\n value_col=cst.VALUE_COL)\n model.model_dict = silverkite.forecast(\n df=train_df,\n time_col=cst.TIME_COL,\n value_col=cst.VALUE_COL,\n **params_daily)\n model.finish_fit()\n assert model.coef_ is None\n with pytest.raises(\n NotImplementedError,\n match=\"Component plot has only been implemented for additive linear models.\"):\n model.plot_components()\n\n with pytest.raises(\n NotImplementedError,\n match=\"Component plot has only been implemented for additive linear models.\"):\n model.plot_trend()\n\n with pytest.raises(\n NotImplementedError,\n match=\"Component plot has only been implemented for additive linear models.\"):\n model.plot_seasonalities()\n\n\ndef test_silverkite_with_components_hourly_data():\n \"\"\"Tests get_components, plot_components, plot_trend,\n plot_seasonalities with hourly data\n \"\"\"\n hourly_data = generate_df_with_reg_for_tests(\n freq=\"H\",\n periods=24 * 4,\n train_start_date=datetime.datetime(2018, 1, 1),\n conti_year_origin=2018)\n train_df = hourly_data.get(\"train_df\").copy()\n params_hourly = params_components()\n\n # converts into parameters for `forecast_silverkite`\n coverage = params_hourly.pop(\"coverage\")\n model = BaseSilverkiteEstimator(\n coverage=coverage,\n uncertainty_dict=params_hourly[\"uncertainty_dict\"])\n model.fit(\n X=train_df,\n time_col=cst.TIME_COL,\n value_col=cst.VALUE_COL)\n silverkite = SilverkiteForecast()\n model.model_dict = silverkite.forecast(\n df=train_df,\n time_col=cst.TIME_COL,\n value_col=cst.VALUE_COL,\n **params_hourly)\n model.finish_fit()\n\n # Test plot_components\n with pytest.warns(Warning) as record:\n title = \"Custom component plot\"\n fig = model.plot_components(names=[\"trend\", \"DAILY_SEASONALITY\", \"DUMMY\"], title=title)\n expected_rows = 3 + 1 # includes changepoints\n assert len(fig.data) == expected_rows\n assert [fig.data[i].name for i in range(expected_rows)] == \\\n [cst.VALUE_COL, \"trend\", \"DAILY_SEASONALITY\", \"trend change point\"]\n\n assert fig.layout.xaxis.title[\"text\"] == cst.TIME_COL\n assert fig.layout.xaxis2.title[\"text\"] == cst.TIME_COL\n assert fig.layout.xaxis3.title[\"text\"] == \"Hour of day\"\n\n assert fig.layout.yaxis.title[\"text\"] == cst.VALUE_COL\n assert fig.layout.yaxis2.title[\"text\"] == \"trend\"\n assert fig.layout.yaxis3.title[\"text\"] == \"daily\"\n\n assert fig.layout.title[\"text\"] == title\n assert f\"The following components have not been specified in the model: \" \\\n f\"{{'DUMMY'}}, plotting the rest.\" in record[0].message.args[0]\n\n # Test plot_trend\n title = \"Custom trend plot\"\n fig = model.plot_trend(title=title)\n expected_rows = 2\n assert len(fig.data) == expected_rows + 1 # includes changepoints\n assert [fig.data[i].name for i in range(expected_rows)] == [cst.VALUE_COL, \"trend\"]\n\n assert fig.layout.xaxis.title[\"text\"] == cst.TIME_COL\n assert fig.layout.xaxis2.title[\"text\"] == cst.TIME_COL\n\n assert fig.layout.yaxis.title[\"text\"] == cst.VALUE_COL\n assert fig.layout.yaxis2.title[\"text\"] == \"trend\"\n\n assert fig.layout.title[\"text\"] == title\n\n # Test plot_seasonalities\n with pytest.warns(Warning):\n # suppresses the warning on seasonalities removed\n title = \"Custom seasonality plot\"\n fig = model.plot_seasonalities(title=title)\n expected_rows = 4\n assert len(fig.data) == expected_rows\n assert [fig.data[i].name for i in range(expected_rows)] == \\\n [cst.VALUE_COL, \"DAILY_SEASONALITY\", \"WEEKLY_SEASONALITY\", \"YEARLY_SEASONALITY\"]\n\n assert fig.layout.xaxis.title[\"text\"] == cst.TIME_COL\n assert fig.layout.xaxis2.title[\"text\"] == \"Hour of day\"\n assert fig.layout.xaxis3.title[\"text\"] == \"Day of week\"\n assert fig.layout.xaxis4.title[\"text\"] == \"Time of year\"\n\n assert fig.layout.yaxis.title[\"text\"] == cst.VALUE_COL\n assert fig.layout.yaxis2.title[\"text\"] == \"daily\"\n assert fig.layout.yaxis3.title[\"text\"] == \"weekly\"\n assert fig.layout.yaxis4.title[\"text\"] == \"yearly\"\n\n assert fig.layout.title[\"text\"] == title\n\n\ndef test_plot_trend_changepoint_detection(df_pt):\n model = BaseSilverkiteEstimator()\n model.fit(\n X=df_pt,\n time_col=cst.TIME_COL,\n value_col=cst.VALUE_COL)\n params = {\n \"changepoints_dict\": {\"method\": \"auto\"}}\n silverkite = SilverkiteForecast()\n model.model_dict = silverkite.forecast(\n df=df_pt,\n time_col=cst.TIME_COL,\n value_col=cst.VALUE_COL,\n **params)\n model.finish_fit()\n fig = model.plot_trend_changepoint_detection()\n assert fig is not None\n assert fig.layout.title[\"text\"] == \"Timeseries Plot with detected trend change points\"\n assert fig.layout.yaxis.title[\"text\"] == cst.VALUE_COL\n assert fig.layout.xaxis.title[\"text\"] == \"Dates\"\n # tests given parameters\n fig = model.plot_trend_changepoint_detection(\n dict(trend_change=False))\n assert fig is not None\n assert fig.layout.title[\"text\"] == \"Timeseries Plot\"\n assert fig.layout.yaxis.title[\"text\"] == cst.VALUE_COL\n assert fig.layout.xaxis.title[\"text\"] == \"Dates\"\n\n\ndef test_model_summary(df_pt):\n model = BaseSilverkiteEstimator()\n model.fit(\n X=df_pt.iloc[:100], # speeds up\n time_col=cst.TIME_COL,\n value_col=cst.VALUE_COL)\n params = {\n \"fit_algorithm\": \"linear\",\n \"training_fraction\": 0.8}\n silverkite = SilverkiteForecast()\n model.model_dict = silverkite.forecast(\n df=df_pt.iloc[:100],\n time_col=cst.TIME_COL,\n value_col=cst.VALUE_COL,\n **params)\n model.finish_fit()\n summary = model.summary()\n summary.__str__()\n summary.__repr__()\n assert summary is not None\n\n\ndef test_pred_category(df_pt):\n model = BaseSilverkiteEstimator()\n # property is not available without fitting.\n with pytest.raises(\n NotFittedError,\n match=\"Must fit before getting predictor category.\"):\n print(model.pred_category)\n model.fit(\n X=df_pt.iloc[:100], # speeds up\n time_col=cst.TIME_COL,\n value_col=cst.VALUE_COL)\n params = {\n \"fit_algorithm\": \"linear\",\n \"training_fraction\": 0.8,\n \"extra_pred_cols\": [\"ct1\", \"x\", \"x:ct1\"]}\n df_pt[\"x\"] = np.random.randn(df_pt.shape[0])\n silverkite = SilverkiteForecast()\n model.model_dict = silverkite.forecast(\n df=df_pt.iloc[:100],\n time_col=cst.TIME_COL,\n value_col=cst.VALUE_COL,\n **params)\n model.extra_pred_cols = [\"ct1\", \"x\", \"x:ct1\"] # set in subclass initialization\n # _pred_category is None before trying to access pred_category\n assert model._pred_category is None\n model.finish_fit()\n pred_category = model.pred_category\n # _pred_category is updated after trying to access pred_category\n assert model._pred_category is not None\n assert pred_category[\"intercept\"] == [\"Intercept\"]\n assert pred_category[\"time_features\"] == [\"ct1\", \"x:ct1\"]\n assert pred_category[\"event_features\"] == []\n assert pred_category[\"trend_features\"] == [\"ct1\", \"x:ct1\"]\n assert pred_category[\"seasonality_features\"] == [\"sin1_tod_daily\",\n \"cos1_tod_daily\",\n \"sin2_tod_daily\",\n \"cos2_tod_daily\",\n \"sin3_tod_daily\",\n \"cos3_tod_daily\",\n \"sin1_tow_weekly\",\n \"cos1_tow_weekly\",\n \"sin2_tow_weekly\",\n \"cos2_tow_weekly\",\n \"sin3_tow_weekly\",\n \"cos3_tow_weekly\",\n \"sin1_toy_yearly\",\n \"cos1_toy_yearly\",\n \"sin2_toy_yearly\",\n \"cos2_toy_yearly\",\n \"sin3_toy_yearly\",\n \"cos3_toy_yearly\",\n \"sin4_toy_yearly\",\n \"cos4_toy_yearly\",\n \"sin5_toy_yearly\",\n \"cos5_toy_yearly\"]\n assert pred_category[\"lag_features\"] == []\n assert pred_category[\"regressor_features\"] == [\"x\", \"x:ct1\"]\n assert pred_category[\"interaction_features\"] == [\"x:ct1\"]\n","sub_path":"greykite/tests/sklearn/estimator/test_base_silverkite_estimator.py","file_name":"test_base_silverkite_estimator.py","file_ext":"py","file_size_in_byte":26672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"274840860","text":"import numpy as np\nimport pandas as pd\nfrom fmri_utils.load_data.work_openfmri import UseOpenfmri\n\n#-----------------------------------------------------\n# Classifiers settings\n#-----------------------------------------------------\nfrom fmri_utils.estimators import Decoder\n# Param grid\nalphas = {'alpha': [0.001, 0.005, 0.01, 0.1, 1.]}\nCs = {'C': [1, 10, 100, 150, 200]}\nl1_ratios = {'l1_ratio': [0.1, 0.2, 0.5, 0.7, 0.8, 0.9]}\nalphas_l1_ratios = {'alpha': [0.001, 0.005, 0.01, 0.1, 1.],\n 'l1_ratio': [0.2, 0.5, 0.7, 0.9]}\nn_components = {'n_components': [1, 2, 5, 7, 8, 10, 15, 20]}\n\nclassifiers = {'ridge': alphas,\n 'svc_l1': Cs,\n 'svc_l2': Cs,\n 'logistic_l1': Cs,\n 'logistic_l2': Cs,\n 'lasso': alphas,\n 'enet': alphas_l1_ratios,\n 'pcr': n_components,\n # 'smooth_lasso': alphas_l1_ratios,\n # 'gnb': None,\n # 'lda': n_components\n }\n\n#-----------------------------------------------------\n# Loading the Data\n#-----------------------------------------------------\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.cross_validation import ShuffleSplit\nfrom sklearn.cross_validation import LeavePLabelOut\n\nroot_dir = '/volatile/andres/brain_codes/DATA'\n# for the cross validation\nstudy_id = dict(ds105='run', ds107='subject')\n\ndata = UseOpenfmri(root_dir, study_id.keys(), n_jobs=1)\ndata.load()\n# get the general info (is not necessary)\ndata.get_info()\n# select each map per run\ndata.process_contrast(study_id, verbose=1, run=data.all_run)\n\n# Experiment settings\nds105 = [['face_vs_baseline', 'cat_vs_baseline'],\n ['face_vs_baseline', 'house_vs_baseline'],\n ['cat_vs_baseline', 'house_vs_baseline'],\n ['bottle_vs_baseline', 'scissors_vs_baseline'],\n ['shoe_vs_baseline', 'house_vs_baseline'],\n ['shoe_vs_baseline', 'face_vs_baseline']],\n\nhenson2010faces = [['unfamiliar_faces_vs_baseline', 'famous_faces_vs_baseline'],\n ['famous_faces_vs_baseline', 'scrambled_faces_vs_baseline']]\n\n\n#-----------------------------------------------------\n# Loading the Data\n#-----------------------------------------------------\nfrom nilearn.input_data import NiftiMasker\nmasker = NiftiMasker(smoothing_fwhm=2, standardize=False)\n\n# XXX For each experiment\ncontrasts = np.unique(ds105)\n\ntarget = data.select_and_encode_target(contrasts=contrasts, study='ds105')\n\n# Load all the data and mask it\n\n# XXX For each classifier\n\n# XXX For each session\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"529487927","text":"import xlrd\nimport QuantLib as ql\nfrom WindPy import *\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime\nimport Utilities.svi_calibration_utility as svi_util\n\n###############################################################################\n## Settings\nw.start()\nevalDate = ql.Date(3,7,2017)\ncalendar = ql.UnitedStates()\ndaycounter = ql.ActualActual()\nql.Settings.instance().evaluationDate = evalDate\n################################################################################\n## spx 18 day market data\nspx_idx = 2429.01\nbook = xlrd.open_workbook('spx18D_20170703.xlsx')\nsheet = book.sheet_by_index(0)\nstrikes = []\nbid_call = []\nask_call = []\nvol_call = []\nbid_put = []\nask_put = []\nvol_put = []\nmaturity_date = ql.Date(20,10,2017)\n\nfor i in range(3,sheet.nrows):\n if sheet.col(1)[i].value != sheet.col(15)[i].value : print('strikes are not equal!!')\n strikes.append(sheet.col(1)[i].value)\n bid_call.append(sheet.col(2)[i].value)\n ask_call.append(sheet.col(3)[i].value)\n vol_call.append(sheet.col(5)[i].value/100)\n bid_put.append(sheet.col(16)[i].value)\n ask_put.append(sheet.col(17)[i].value)\n vol_put.append(sheet.col(19)[i].value/100)\n\n# us treasury bond yild term structure\n#book_curve = xlrd.open_workbook('uscurve_20170703.xlsx')\n#sheet_curve = book_curve.sheet_by_index(0)\n#col_rates = sheet_curve.col(2)\n#libiorData = w.wsd(\"LIUSDON.IR,LIUSD1W.IR,LIUSD1M.IR,LIUSD2M.IR,LIUSD3M.IR,LIUSD6M.IR,LIUSD12M.IR\", \"ytm_b\", \"2017-07-03\", \"2017-07-03\", \"returnType=3\")\n#rates = np.divide(libiorData.Data[0],100)\nrates = np.divide( [1.17167, 1.18833, 1.22689, 1.25389, 1.30072, 1.456, 1.74844], 100)\ndates = [calendar.advance(evalDate,ql.Period(1,ql.Days)),\n calendar.advance(evalDate,ql.Period(1,ql.Weeks)),\n calendar.advance(evalDate,ql.Period(1,ql.Months)),\n calendar.advance(evalDate,ql.Period(2,ql.Months)),\n calendar.advance(evalDate,ql.Period(3,ql.Months)),\n calendar.advance(evalDate,ql.Period(6,ql.Months)),\n calendar.advance(evalDate,ql.Period(1,ql.Years))]\ncurve = ql.ForwardCurve(dates,rates,daycounter)\nref_date = curve.referenceDate()\nmax_date = curve.maxDate()\ndates = np.array([datetime.date(ref_date.year(),ref_date.month(),ref_date.dayOfMonth()) + datetime.timedelta(days=i) for i in range(max_date - ref_date)])\ntimes = np.linspace(0.0, (max_date-ref_date)/365,100)\nrates = [curve.zeroRate(t,ql.Continuous).rate() for t in times]\n#plt.figure(1)\n#plt.plot(times,rates)\n#plt.title('US treasury yts 2017/07/03')\n\n###############################################################################\n## Implement SVI model\nvols = vol_call\nprint('vols: ',vols)\nexpiration_date = maturity_date\nspot = spx_idx\nrisk_free_rate = curve.zeroRate(expiration_date,daycounter,ql.Continuous).rate()\nprint('rf: ',risk_free_rate)\n\n## Calibrate parameters\nmethod = 'nm'\n## 'ols' for SLSQP method, optimizing a, d, c, m, sigma together by one objfuction;\n## 'nm' for Nelder-Mead simplex method\ninit_adc = [1,1,1] # Never used for ols optimization\nlog_forward_moneyness, totalvariance,volatility, _a_star, _d_star, _c_star, m_star, sigma_star \\\n = svi_util.svi_calibration_helper(method,evalDate, init_adc, calendar, daycounter, risk_free_rate, vols, expiration_date, strikes, spot)\nx_svi = np.arange(min(log_forward_moneyness), max(log_forward_moneyness), 0.1 / 100) # log_forward_moneyness\ny_svi = np.divide((x_svi - m_star),sigma_star)\ntv_svi = _a_star + _d_star*y_svi + _c_star* np.sqrt(y_svi**2 + 1) # totalvariance objective fution values\n\n\nprint('_a_star, _d_star, _c_star, m_star, sigma_star: ',_a_star, _d_star, _c_star, m_star, sigma_star)\nx = [_a_star, _d_star, _c_star, m_star, sigma_star]\nprint('x : ',x)\n# Constraints: 0 <= c <=4sigma; |d| <= c and |d| <= 4sigma - c; 0 <= a <= max{vi}\nif 0 <= _a_star<= max(totalvariance): print('1 bnd succeeded')\nelse: print('1 bnd failed')\nif -4*sigma_star<= _d_star <= 4*sigma_star : print('2 bnd succeeded')\nelse: print('2 bnd failed')\nif 0<=_c_star<=4*sigma_star: print('3 bnd succeeded')\nelse: print('3 bnd failed')\nif x[2] - abs(x[1]) >= 0: print('1 cons succeeded')\nelse: print('1 cons failed')\nif 4 * sigma_star - x[2] - abs(x[1]) : print('2 cons succeeded')\nelse: print('2 cons failed')\n\n########################################################################################################################\n## Get a,b,rho\nttm = daycounter.yearFraction(evalDate,expiration_date)\na_star = np.divide(_a_star, ttm)\nb_star = np.divide(_c_star, (sigma_star * ttm))\nrho_star = np.divide(_d_star, _c_star)\ntv_svi2 = np.multiply( a_star + b_star * (rho_star * (x_svi - m_star) + np.sqrt((x_svi - m_star) ** 2 + sigma_star ** 2)), ttm)\n\nprint('c = b`rho`t',_c_star,b_star*sigma_star*ttm)\nprint('d = rho*b*sigma*t',_d_star,rho_star*b_star*sigma_star*ttm)\nprint('_a = a*t', _a_star,a_star*ttm)\nprint('a_star,b_star,rho_star,m_star,sigma_star: ',a_star,b_star,rho_star,m_star,sigma_star)\n########################################################################################################################\n##\n\n\n########################################################################################################################\n# plot input data -- moneyness-imliedvol\nplt.figure(2)\nplt.plot(log_forward_moneyness, totalvariance, 'ro')\n# Plot SVI volatility smile -- moneyness-impliedVol\nplt.plot(x_svi, tv_svi, 'b--')\nt = str(daycounter.yearFraction(evalDate, expiration_date))\nplt.title('SVI total variance, T = ' + t)\n\n#################################################################################q#######################################\n## Double check parameters calculation -- two lines should be exactly the same\nplt.figure(3)\nplt.plot(x_svi, tv_svi, 'b--')\nplt.plot(x_svi, tv_svi2, 'r--')\n\n\nplt.show()\n","sub_path":"svi_model/svi_calibration_spx18D.py","file_name":"svi_calibration_spx18D.py","file_ext":"py","file_size_in_byte":5784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"18698641","text":"# -*- coding:utf-8 -*-\nimport os\nimport time\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\nimport numpy as np\nimport tensorflow as tf\nfrom scipy.misc import imsave\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nmnist = input_data.read_data_sets('../data/MNIST_data/', one_hot=True)\ntry:\n xrange = range\nexcept:\n xrange = range\n# --------------------------------------------\nflags = tf.app.flags\nflags.DEFINE_integer(\"batch_size\", 100, \"batch_size\")\nflags.DEFINE_bool(\"if_train\", True, \"if_Train=True then train else predict\")\nFLAGS = flags.FLAGS\n\n\n# -----------------------------------------\nclass Params(object):\n def __init__(self):\n # model params\n self.if_train = FLAGS.if_train\n self.batch_size = FLAGS.batch_size\n self.learning_rate = 0.0002\n self.beta1 = 0.5 # momentum term for adam\n self.img_dim = [28, 28, 1] # the size of image\n self.y_dim = 10\n self.z_dim = 100 # the dimension of noise z\n self.epoch = 50 # the number of max epoch\n\n\nclass GAN(object):\n def __init__(self, sess, params):\n self.model_path = \"../models/\"\n self.model_name = \"gdn_model.ckpt\"\n self.img_path = \"../data/images/\"\n self.if_train = params.if_train\n self.batch_size = params.batch_size # must be even number\n self.learning_rate = params.learning_rate\n self.beta1 = params.beta1\n self.img_dim = params.img_dim\n self.z_dim = params.z_dim # the dimension of noise z\n self.y_dim = params.y_dim\n self.epoch = params.epoch # the number of max epoch\n self.sess = sess\n self.build_model() # initializer\n #\n if not os.path.exists(self.model_path):\n os.mkdir(self.model_path)\n if not os.path.exists(self.img_path):\n os.mkdir(self.img_path)\n\n def leaky_relu(self, x, leakiness=0.2, name='leaky_relu'):\n \"\"\"Relu, with optional leaky support.\"\"\"\n return tf.maximum(x, x * leakiness, name=name)\n\n def flatten(self, x):\n x_shape = x.get_shape()\n x_rank = len(x_shape) # x.get_shape().ndims\n if (x_rank is None) or (x_rank < 2):\n raise ValueError('Inputs must have a least 2 dimensions.')\n shp = x_shape.as_list()\n flattened_shape = np.prod(shp[1:x_rank])\n resh1 = tf.reshape(x, [-1, flattened_shape])\n return resh1\n\n def image_concat(self, x, y):\n x_shape = x.get_shape()\n # []* [None,28,28,10]\n new_y = tf.reshape(y, [self.batch_size, 1, 1, self.y_dim])\n new_y = new_y * tf.ones([self.batch_size, x_shape[1], x_shape[2], self.y_dim])\n return tf.concat([x, new_y], -1)\n\n def dis_dnn(self, x_image, training=False):\n x = tf.reshape(x_image, (-1, 28 * 28))\n x = tf.layers.dense(x, 256, activation=tf.nn.relu, name=\"fc1\")\n x = tf.layers.dense(x, 1, activation=None, name=\"fc3\")\n return x\n\n def gen_dnn(self, noise, training=False):\n x = tf.layers.dense(noise, 256, activation=tf.nn.relu, name=\"fc2\")\n x = tf.layers.dense(x, 28 * 28, activation=tf.nn.relu, name=\"fc3\")\n x = tf.reshape(x, [-1, 28, 28, 1])\n return x\n\n def dis_dcn(self, x_image, label, training=False):\n c = self.img_dim[2]\n depths = [c] + [32, 64]\n activation_fn = self.leaky_relu\n # x_image.shape=[28,28,1]\n with tf.variable_scope('conv1'):\n x_image = self.image_concat(x_image, label)\n outputs = tf.layers.conv2d(x_image, depths[1], [5, 5], strides=(2, 2), padding='SAME')\n outputs = activation_fn(tf.layers.batch_normalization(outputs, training=training))\n # 14*14*32\n with tf.variable_scope('conv2'):\n outputs = tf.layers.conv2d(outputs, depths[2], [5, 5], strides=(2, 2), padding='SAME')\n outputs = activation_fn(tf.layers.batch_normalization(outputs, training=training))\n # 7*7*64\n with tf.variable_scope('fc'):\n # flatten\n reshape = self.flatten(outputs)\n # fc\n outputs = tf.layers.dense(reshape, 1, name='outputs')\n return outputs\n\n def gen_dcn(self, noise, label, training=False):\n # 论文中使用的是4层反卷积,它的图片大小是64*64\n # 在这里,mnist的图片是28*28, 则不能通过4层反卷积,只能是2层反卷积 7*7*32\n # 还有一种办法,通过 tf.image.resize_images函数调整图像的大小。\n [h, w, c] = self.img_dim\n depths = [c] + [32, 64]\n depths.reverse()\n with tf.variable_scope('fc'):\n x = tf.concat([noise, label], axis=1)\n outputs = tf.layers.dense(x, int(h / 4 * w / 4 * depths[0]))\n outputs = tf.reshape(outputs, [-1, int(h / 4), int(w / 4), depths[0]])\n outputs = tf.nn.relu(tf.layers.batch_normalization(outputs, training=training), name='outputs')\n # 7 *7 * 64\n with tf.variable_scope('deconv1'):\n outputs = tf.layers.conv2d_transpose(outputs, depths[1], [5, 5], strides=(2, 2), padding='SAME')\n outputs = tf.nn.relu(tf.layers.batch_normalization(outputs, training=training), name='outputs')\n # 14 * 14 * 32\n with tf.variable_scope('deconv2'):\n outputs = tf.layers.conv2d_transpose(outputs, depths[2], [5, 5], strides=(2, 2), padding='SAME')\n outputs = tf.nn.tanh(outputs, name='outputs')\n # 28 * 28 * 1\n return outputs\n\n def discriminator(self, inputs, label, reuse, if_train=False):\n \"\"\"\n :param inputs: shape=[None,h,w,c]\n \"\"\"\n with tf.variable_scope(\"dis\", reuse=reuse):\n outputs = self.dis_dcn(inputs, label, if_train)\n logits = tf.nn.sigmoid(outputs)\n return logits\n\n def generator(self, noise, label, reuse=False, if_train=False):\n \"\"\"\n :return: tensor = [None,h,w,c]\n \"\"\"\n with tf.variable_scope(\"gen\", reuse=reuse):\n x = self.gen_dcn(noise, label, training=if_train)\n return x\n\n def build_model(self):\n \"\"\"\n 要考虑if_train\n :return:\n \"\"\"\n # y 表示label\n self.label = tf.placeholder(tf.float32, shape=[None, self.y_dim], name='label')\n # x_img表示真实图片\n self.x = tf.placeholder(tf.float32, shape=[None, self.img_dim[0], self.img_dim[1], self.img_dim[2]],\n name='real_img')\n # z 表示随机噪声\n self.z = tf.placeholder(tf.float32, shape=[None, self.z_dim], name='noise')\n # 由生成器生成图像 G\n self.G_img = self.generator(self.z, self.label, reuse=False,\n if_train=self.if_train) # shape=[batch_size,28,28,1]\n # 真实图像送入判别器\n d_logits_r = self.discriminator(self.x, self.label, reuse=False, if_train=self.if_train)\n # 生成图像送入辨别器\n d_logits_f = self.discriminator(self.G_img, self.label, reuse=True, if_train=self.if_train)\n # 判别(器)网络对于真实图片输入,希望输出为1, 对于伪造输入输出0\n d_loss_r = tf.reduce_mean(tf.log(tf.clip_by_value(d_logits_r, 1e-10, 1.0)))\n d_loss_f = tf.reduce_mean(tf.log(tf.clip_by_value(1.0 - d_logits_f, 1e-10, 1.0)))\n self.d_loss = -(d_loss_r + d_loss_f)\n self.g_loss = -tf.reduce_mean(tf.log(tf.clip_by_value(d_logits_f, 1e-10, 1.0)))\n all_vars = tf.trainable_variables()\n g_vars = [v for v in all_vars if 'gen' in v.name]\n d_vars = [v for v in all_vars if 'dis' in v.name]\n for v in all_vars:\n print(v)\n self.opt_d = tf.train.AdamOptimizer(self.learning_rate, beta1=0.5).minimize(self.d_loss, var_list=d_vars)\n self.opt_g = tf.train.AdamOptimizer(self.learning_rate, beta1=0.5).minimize(self.g_loss, var_list=g_vars)\n self.saver = tf.train.Saver()\n #\n if self.if_train:\n init = tf.global_variables_initializer()\n self.sess.run(init)\n else:\n ckpt = tf.train.get_checkpoint_state(self.model_path)\n self.saver.restore(self.sess, ckpt.model_checkpoint_path)\n print('model load done')\n\n def train(self):\n for epoch_i in range(self.epoch):\n iters = int(50000 / self.batch_size)\n for step in range(iters):\n t1 = time.time()\n # input\n with tf.device('/cpu:1'):\n batch_x, batch_y = mnist.train.next_batch(self.batch_size) # x.shape=[100,784]\n batch_x = batch_x.reshape(self.batch_size, self.img_dim[0], self.img_dim[1], self.img_dim[2])\n batch_z = np.random.uniform(-1.0, 1.0, [self.batch_size, self.z_dim])\n # update the Discrimater k times\n _, loss_d, = self.sess.run([self.opt_d, self.d_loss],\n feed_dict={self.x: batch_x, self.z: batch_z, self.label: batch_y})\n # update the Generator one time\n _, loss_g, = self.sess.run([self.opt_g, self.g_loss],\n feed_dict={self.x: batch_x, self.z: batch_z, self.label: batch_y})\n dispaly_step = 500\n if (step + 1) % dispaly_step == 0:\n t2 = time.time()\n print(\"[cost %3f][epoch:%2d/%2d][iter:%4d/%4d],loss_d:%5f,loss_g:%4f \"\n % (t2 - t1, epoch_i, self.epoch, step + 1, iters, loss_d, loss_g))\n #\n img_name = \"sample{}_{}.jpg\".format(epoch_i, (step + 1) // dispaly_step)\n print(\"saving image: %s\" % (img_name))\n self.save_images(os.path.join(self.img_path, img_name), if_transform=True)\n # 每隔n=1 epoch,保存模型\n # if (epoch_i + 1) % 1 == 0:\n # checkpoint_path = os.path.join(self.model_path, self.model_name )\n # self.saver.save(self.sess, checkpoint_path, global_step=epoch_i)\n\n def save_images(self, save_path, if_transform=False, ):\n k = 10\n test_z = np.random.uniform(-1.0, 1.0, size=[k ** 2, self.z_dim])\n # 生成条件y\n test_y = np.zeros([k ** 2, self.y_dim])\n for i in range(k):\n y_i = np.random.randint(0, self.y_dim - 1)\n for j in range(k):\n test_y[i * k + j, y_i] = 1\n x = self.sess.run(self.G_img, feed_dict={self.z: test_z, self.label: test_y})\n # x = np.random.uniform(-1, 1, [100, 28, 28, 1])\n x = np.squeeze(x)\n # 数值从[-1, 1] -> [0,255]\n if if_transform:\n x = (255.0 * (x + 1) / 2) # .astype('uint8')\n h, w, c = self.img_dim[0], self.img_dim[1], self.img_dim[2]\n if c == 1:\n img = np.zeros((h * k, w * k))\n else:\n img = np.zeros((h * k, w * k, 3))\n for i in range(k):\n for j in range(k):\n n = i * k + j\n img[h * i:h * (i + 1), w * j:w * (j + 1)] = x[n]\n imsave(save_path, img)\n\n\n# ------------------------------------------------------------------------\nCONFIG = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False)\nCONFIG.gpu_options.allow_growth = True\n\n\ndef main():\n sess = tf.InteractiveSession(config=CONFIG)\n params = Params()\n model = GAN(sess, params)\n model.train()\n # model.save_images(\"../data/images/test.jpg\",True)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"GANs/Condition GAN.py","file_name":"Condition GAN.py","file_ext":"py","file_size_in_byte":11553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"300928292","text":"\nimport requests\nfrom bs4 import BeautifulSoup\n\n\ndef get_all_title_name(url):\n \"\"\"\n 获取第一页的所有通知的标题\n :return:\n \"\"\"\n title_name_list = []\n r = requests.get(url, timeout=30)\n\n # 解决中文乱码问题\n if r.encoding == 'ISO-8859-1':\n encodings = requests.utils.get_encodings_from_content(r.text)\n if encodings:\n encoding = encodings[0]\n else:\n encoding = r.apparent_encoding\n else:\n encoding = r.encoding\n encode_content = r.content.decode(encoding, 'replace').encode('utf-8', 'replace').decode('utf-8')\n\n # 获得网页源代码\n soup = BeautifulSoup(encode_content, 'lxml')\n\n # 获取首页所有通知的标题\n name_content_list = soup.find_all('h3', {'class': 'media-heading'})\n for name in name_content_list:\n title_name_list.append(name.text)\n\n # 返回首页所有的通知标题\n return title_name_list\n\n\ndef get_all_title_date(url):\n \"\"\"\n 获取第一页的所有通知的日期\n :return:\n \"\"\"\n title_date_list = []\n r = requests.get(url, timeout=30)\n\n # 解决中文乱码问题\n if r.encoding == 'ISO-8859-1':\n encodings = requests.utils.get_encodings_from_content(r.text)\n if encodings:\n encoding = encodings[0]\n else:\n encoding = r.apparent_encoding\n else:\n encoding = r.encoding\n encode_content = r.content.decode(encoding, 'replace').encode('utf-8', 'replace').decode('utf-8')\n\n # 获得网页源代码\n soup = BeautifulSoup(encode_content, 'lxml')\n\n # 获取首页所有通知的日期和月份年份信息\n day_content_list = soup.find_all('strong')\n year_month_content_list = soup.find_all('small')\n\n # 首页展示12条通知信息\n for i in range(12):\n title_date_list.append(year_month_content_list[i].text + '-' + day_content_list[i].text)\n\n # 返回首页所有的通知日期\n return title_date_list\n\n\ndef get_all_title_link(url):\n \"\"\"\n 获取第一页的所有通知的URL\n :return:\n \"\"\"\n title_list = []\n title_link_list = []\n title_name_list = []\n r = requests.get(url, timeout=30)\n\n # 解决中文乱码问题\n if r.encoding == 'ISO-8859-1':\n encodings = requests.utils.get_encodings_from_content(r.text)\n if encodings:\n encoding = encodings[0]\n else:\n encoding = r.apparent_encoding\n else:\n encoding = r.encoding\n encode_content = r.content.decode(encoding, 'replace').encode('utf-8', 'replace').decode('utf-8')\n\n # 获得网页源代码\n soup = BeautifulSoup(encode_content, 'lxml')\n # 获取title信息的主体\n title_body = soup.find_all('div', {'class': 'col-lg-12 col-md-12'})\n\n # 获取首页所有通知的链接\n link_content_list = title_body[0].find_all('a')\n # 网站通用头链接\n head_url = 'https://zh.jnu.edu.cn/'\n for link in link_content_list:\n title_link_list.append((head_url, link['href'][1:]))\n\n # # 获取首页所有通知的标题\n # name_content_list = soup.find_all('h3', {'class': 'media-heading'})\n # for name in name_content_list:\n # title_name_list.append(name.text)\n #\n # # 首页总共有12条通知\n # for i in range(12):\n # title_list.append((title_name_list[i], title_link_list[i]))\n\n # 返回首页所有的通知链接\n return title_link_list\n\n\ndef get_notification_txt(notification_type, notification_url):\n \"\"\"\n 写入txt文件函数\n \"\"\"\n # notification_type代表属于通知类型(校区公告、讲座报告、学生通知及教师通知等)\n # notification_url代表相应通知类��的总url\n file_name = notification_type + '_notification.txt'\n title_link_list = get_all_title_link(notification_url)\n title_name_list = get_all_title_name(notification_url)\n title_date_list = get_all_title_date(notification_url)\n\n title_list_file = open(file_name, mode='w', encoding='utf-8')\n for i in range(12):\n # number_str = str(i + 1) + '.'\n # title_list_file.write(number_str)\n # title_list_file.write('\\n')\n title_list_file.writelines(title_name_list[i])\n title_list_file.write('\\n')\n title_list_file.writelines(title_date_list[i])\n title_list_file.write('\\n')\n title_list_file.writelines(title_link_list[i])\n title_list_file.write('\\n')\n title_list_file.close()\n\n\ndef main():\n get_notification_txt('Campus', 'https://zh.jnu.edu.cn/8366/list.htm')\n get_notification_txt('Lecture', 'https://zh.jnu.edu.cn/8367/list.htm')\n get_notification_txt('Student', 'https://zh.jnu.edu.cn/8378/list.htm')\n get_notification_txt('Teacher', 'https://zh.jnu.edu.cn/8379/list.htm')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"WindowsFormsApp1/Properties/Get_Notifications/Get_Notifications.py","file_name":"Get_Notifications.py","file_ext":"py","file_size_in_byte":4794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"607209696","text":"import mysql.connector\r\nimport pandas as pd\r\nimport json\r\nimport re\r\nshop_file = pd.read_csv(r'path') # path to 3-p5s3708k.csv\r\npeach = shop_file.values.tolist()\r\ndf = pd.read_excel(r'path') #path to 5-awte8wbd.xlsx\r\ncategory_title_fa = df[df.columns[5]]\r\nctg = category_title_fa.values.tolist()\r\nattributes = df[df.columns[9]]\r\nattr = attributes.values.tolist()\r\ntitle_alt = df['title_alt'][:].values.tolist()\r\nprid = df[df.columns[0]].values.tolist()\r\nprtifa = df[df.columns[1]].values.tolist()\r\nprtien = df[df.columns[2]].values.tolist()\r\nurl = df[df.columns[3]].values.tolist()\r\nctgkey = df[df.columns[6]].values.tolist()\r\nbrnamefa = df[df.columns[7]].values.tolist()\r\nbrnameen = df[df.columns[8]].values.tolist()\r\nbookind = []\r\npuzzleind = []\r\nmouseind = []\r\nkeyboardind = []\r\nglassind = []\r\nphonecaseind = []\r\ncount1 = 0\r\nfor word in prtien:\r\n if word != word:\r\n prtien[count1] = \"NULL\"\r\n count1 += 1\r\ncount2 = 0\r\nfor word in url:\r\n if word != word:\r\n url[count2] = \"NULL\"\r\n count2 += 1\r\ncount3 = 0\r\nfor word in ctgkey:\r\n if word != word:\r\n ctgkey[count3] = \"NULL\"\r\n count3 += 1\r\n\r\n# indexes of each product:\r\n\r\nfor i in range(0, len(ctg)):\r\n if ctg[i] == \"کتاب چاپی\":\r\n bookind.append(i)\r\nfor i in range(0, len(ctg)):\r\n if category_title_fa[i] == \"پازل\":\r\n puzzleind.append(i)\r\n\r\nfor i in range(0, len(ctg)):\r\n if ctg[i] == \"ماوس (موشواره)\":\r\n mouseind.append(i)\r\n\r\nfor i in range(0, len(ctg)):\r\n if ctg[i] == \"کیبورد (صفحه کلید)\":\r\n keyboardind.append(i)\r\n\r\nfor i in range(0, len(ctg)):\r\n if ctg[i] == \"کیف و کاور گوشی\":\r\n phonecaseind.append(i)\r\n\r\nfor i in range(0, len(ctg)):\r\n if ctg[i] == \"محافظ صفحه نمایش گوشی\":\r\n glassind.append(i)\r\n\r\nbooks_attr_list = []\r\nbook_attributes = []\r\nattr_dict = {}\r\n# book_attributes:\r\n\r\nfor i in range(0, len(bookind)):\r\n if attr[bookind[i]] == attr[bookind[i]]:\r\n books_attr_list.append(json.loads(attr[bookind[i]])) # list of lists of dictionaries\r\n\r\nfor i in range(0, len(books_attr_list)): # for every row in excel\r\n for j in range(0, len(books_attr_list[i])): # for each dictionary of a row\r\n attr_dict[books_attr_list[i][j].get(\"Key\")] = books_attr_list[i][j].get(\"Value\")\r\n book_attributes.append(attr_dict.copy())\r\n attr_dict.clear()\r\n\r\n# puzzle attributes:\r\n\r\npuzzle_attr_list = []\r\npuzzle_attributes = []\r\nfor i in range(0, len(puzzleind)):\r\n if attr[puzzleind[i]] == attr[puzzleind[i]]:\r\n puzzle_attr_list.append(json.loads(attr[puzzleind[i]]))\r\n\r\nfor i in range(0, len(puzzle_attr_list)): # for every row in excel\r\n for j in range(0, len(puzzle_attr_list[i])): # for each dictionary of a row\r\n attr_dict[puzzle_attr_list[i][j].get(\"Key\")] = puzzle_attr_list[i][j].get(\"Value\")\r\n puzzle_attributes.append(attr_dict.copy())\r\n attr_dict.clear()\r\n\r\n# mouse attributes:\r\n\r\nmouse_attr_list = []\r\nmouse_attributes = []\r\nfor i in range(0, len(mouseind)):\r\n if attr[mouseind[i]] == attr[mouseind[i]]:\r\n mouse_attr_list.append(json.loads(attr[mouseind[i]]))\r\n\r\nfor i in range(0, len(mouse_attr_list)): # for every row in excel\r\n for j in range(0, len(mouse_attr_list[i])): # for each dictionary of a row\r\n attr_dict[mouse_attr_list[i][j].get(\"Key\")] = mouse_attr_list[i][j].get(\"Value\")\r\n mouse_attributes.append(attr_dict.copy())\r\n attr_dict.clear()\r\n\r\n# keyboard attributes:\r\n\r\nkeyboard_attr_list = []\r\nkeyboard_attributes = []\r\n\r\nfor i in range(0, len(keyboardind)):\r\n if attr[keyboardind[i]] == attr[keyboardind[i]]:\r\n keyboard_attr_list.append(json.loads(attr[keyboardind[i]]))\r\n\r\nfor i in range(0, len(keyboard_attr_list)): # for every row in excel\r\n\r\n for j in range(0, len(keyboard_attr_list[i])): # for each dictionary of a row\r\n attr_dict[keyboard_attr_list[i][j].get(\"Key\")] = keyboard_attr_list[i][j].get(\"Value\")\r\n keyboard_attributes.append(attr_dict.copy())\r\n attr_dict.clear()\r\n\r\n# glass attributes:\r\n\r\nglass_attr_list = []\r\nglass_attributes = []\r\n\r\nfor i in range(0, len(glassind)):\r\n if attr[glassind[i]] == attr[glassind[i]]:\r\n glass_attr_list.append(json.loads(attr[glassind[i]]))\r\n\r\nfor i in range(0, len(glass_attr_list)): # for every row in excel\r\n\r\n for j in range(0, len(glass_attr_list[i])): # for each dictionary of a row\r\n attr_dict[glass_attr_list[i][j].get(\"Key\")] = glass_attr_list[i][j].get(\"Value\")\r\n glass_attributes.append(attr_dict.copy())\r\n attr_dict.clear()\r\n\r\n# case attributes:\r\n\r\nphonecase_attr_list = []\r\nphonecase_attributes = []\r\n\r\nfor i in range(0, len(phonecaseind)):\r\n if attr[phonecaseind[i]] == attr[phonecaseind[i]]:\r\n phonecase_attr_list.append(json.loads(attr[phonecaseind[i]]))\r\n\r\nfor i in range(0, len(phonecase_attr_list)): # for every row in excel\r\n\r\n for j in range(0, len(phonecase_attr_list[i])): # for each dictionary of a row\r\n attr_dict[phonecase_attr_list[i][j].get(\"Key\")] = phonecase_attr_list[i][j].get(\"Value\")\r\n phonecase_attributes.append(attr_dict.copy())\r\n attr_dict.clear()\r\n\r\n# keys for columns of each attribute table\r\n\r\nbook_keys = book_attributes[0].keys()\r\npuzzle_keys = puzzle_attributes[0].keys()\r\nmouse_keys = mouse_attributes[0].keys()\r\nkeyboard_keys = keyboard_attributes[0].keys()\r\nphonecase_keys = phonecase_attributes[1].keys()\r\nglass_keys = glass_attributes[0].keys()\r\n\r\n# title_alt parsing\r\n\r\ntitle_alt_lists = []\r\nfor i in range(len(title_alt)):\r\n s = str(title_alt[i])\r\n title_alt_lists.append(set(re.split(',|،|-|/', s.lower())))\r\nbook_title_alt = []\r\npuzzle_title_alt = []\r\nmouse_title_alt = []\r\nkeyboard_title_alt = []\r\nphonecase_title_alt = []\r\nglass_title_alt = []\r\nfor i in range(len(bookind)):\r\n book_title_alt.append(list(title_alt_lists[bookind[i]]))\r\nfor i in range(len(puzzleind)):\r\n puzzle_title_alt.append(list(title_alt_lists[puzzleind[i]]))\r\nfor i in range(len(mouseind)):\r\n mouse_title_alt.append(list(title_alt_lists[mouseind[i]]))\r\nfor i in range(len(keyboardind)):\r\n keyboard_title_alt.append(list(title_alt_lists[keyboardind[i]]))\r\nfor i in range(len(phonecaseind)):\r\n phonecase_title_alt.append(list(title_alt_lists[phonecaseind[i]]))\r\nfor i in range(len(glassind)):\r\n glass_title_alt.append(list(title_alt_lists[glassind[i]]))\r\n\r\n# -------------------------------------------------------------------------------------------------------\r\nmydb = mysql.connector.connect(\r\n host=\"localhost\",\r\n user=\"root\",\r\n passwd=\"YOUR_PASSWORD\", #fill\r\n database=\"DATABASE_NAME\" #fill\r\n)\r\nmycursor = mydb.cursor()\r\nmycursor.execute(\"USE DATABASE_NAME\") #fill\r\n\r\n# creating table attribute , title , others\r\nmycursor.execute(\"CREATE TABLE IF NOT EXISTS big_table (product_id INT NOT NULL,product_title_fa VARCHAR(255),category_title_fa VARCHAR(255),brand_name_fa VARCHAR(255),PRIMARY KEY (product_id))\")\r\nmycursor.execute(\"CREATE TABLE IF NOT EXISTS category(category_title_fa VARCHAR(255),category_keywords varchar(255),primary key(category_title_fa))\")\r\nmycursor.execute(\"CREATE TABLE IF NOT EXISTS url(product_title_fa VARCHAR(255),product_title_en VARCHAR(255),url VARCHAR(255),PRIMARY KEY(product_title_fa) )\")\r\nmycursor.execute(\"CREATE TABLE IF NOT EXISTS brand(brand_name_fa VARCHAR(255),brand_name_en VARCHAR(255),primary key(brand_name_fa))\")\r\ntable_name_attributes = [\"book_attributes\", \"puzzle_attributes\", \"mouse_attributes\", \"keyboard_attributes\",\r\n \"phonecase_attributes\", \"glass_attributes\"]\r\ntable_column = [book_keys, puzzle_keys, mouse_keys, keyboard_keys, phonecase_keys, glass_keys]\r\nfor table_names, table_column in zip(table_name_attributes, table_column):\r\n sql = 'CREATE TABLE IF NOT EXISTS {} (product_id INT NOT NULL,' + '`{}` TEXT, ' * len(\r\n table_column) + 'PRIMARY KEY (product_id),FOREIGN KEY (product_id) REFERENCES big_table(product_id))'\r\n sql = sql.format(table_names, *table_column)\r\n mycursor.execute(sql)\r\n\r\n sql = \"\"\"CREATE TABLE IF NOT EXISTS title (product_id INT,title_alt VARCHAR(255),\r\n primary key (product_id,title_alt))\"\"\"\r\n sql = sql.format()\r\n mycursor.execute(sql)\r\nmydb.commit()\r\n# ------------------------------------------------------------------------------------------------------------\r\n# inserting data into title table:\r\ntitle_names = [book_title_alt, puzzle_title_alt, mouse_title_alt, keyboard_title_alt, phonecase_title_alt,glass_title_alt]\r\nind_list = [bookind, puzzleind, mouseind, keyboardind, phonecaseind, glassind]\r\nfor guz,guz_ind in zip(title_names,ind_list):\r\n for i in range(0, len(guz)):\r\n for j in range(0, len(guz[i])):\r\n sql = \"\"\"INSERT INTO title(product_id,title_alt) VALUES (%s,%s)\"\"\"\r\n val = (prid[guz_ind[i]], guz[i][j])\r\n try:\r\n mycursor.execute(sql, val)\r\n except:\r\n continue\r\nmydb.commit()\r\n\r\n# --------------------------------------------------\r\n# insert into big table\r\nfor index in ind_list:\r\n for m in range(0, len(index)):\r\n sql = \"INSERT INTO big_table(product_id, product_title_fa, category_title_fa, brand_name_fa) VALUES (%s,%s,%s,%s)\"\r\n val = (prid[index[m]], prtifa[index[m]], ctg[index[m]], brnamefa[index[m]])\r\n mycursor.execute(sql, val)\r\nmydb.commit()\r\n# insert into category table\r\nfor index in ind_list:\r\n for m in range(0, len(index)):\r\n sql = \"insert into category(category_title_fa, category_keywords) VALUES (%s,%s)\"\r\n val = (ctg[index[m]], brnamefa[index[m]])\r\n try:\r\n mycursor.execute(sql, val)\r\n except:\r\n continue\r\nmydb.commit()\r\n# insert into url table\r\nfor index in ind_list:\r\n for m in range(0, len(index)):\r\n sql = \"insert into url(product_title_fa, product_title_en, url) VALUES (%s,%s,%s)\"\r\n val = (prtifa[index[m]], prtien[index[m]],url[index[m]])\r\n try:\r\n mycursor.execute(sql, val)\r\n except:\r\n continue\r\nmydb.commit()\r\n# insert into brand table\r\nfor index in ind_list:\r\n for m in range(0, len(index)):\r\n sql = \"insert into brand(brand_name_fa,brand_name_en) VALUES (%s,%s)\"\r\n val = (brnamefa[index[m]], brnameen[index[m]])\r\n try:\r\n mycursor.execute(sql, val)\r\n except:\r\n continue\r\nmydb.commit()\r\n# -----------------------------------------------------------------------------------------------\r\n# insert into attribute tables\r\n# insert to book attributes\r\n\r\ngolabi_attribute = [book_attributes, puzzle_attributes, mouse_attributes, keyboard_attributes, phonecase_attributes,\r\n glass_attributes]\r\nfor tab_name, ind, att_name in zip(table_name_attributes, ind_list, golabi_attribute):\r\n i = 0\r\n for row in att_name:\r\n cols = ''\r\n vals = ''\r\n for key in row:\r\n cols += \" `{}` , \"\r\n cols = cols.format(key)\r\n vals += \" '{}' , \"\r\n vals = vals.format(row.get(key))\r\n cols = cols[:-2]\r\n vals = vals[:-2]\r\n sql = \"\"\"INSERT INTO {}(product_id, {} ) VALUES ({},{})\"\"\"\r\n pid = prid[ind[i]]\r\n sql = sql.format(tab_name, cols, pid, vals)\r\n try:\r\n mycursor.execute(sql)\r\n except:\r\n print(\"Digikala ride\")\r\n i += 1\r\n if len(ind) > len(att_name):\r\n j = len(att_name)\r\n nullstring = \"NULL, \" * len(att_name[1].keys())\r\n nullstring = nullstring[0:-2]\r\n while j < len(ind):\r\n sql = \"\"\"INSERT INTO {}(product_id, {} ) VALUES ({},{})\"\"\".format(tab_name, cols, prid[ind[j]], nullstring)\r\n try:\r\n mycursor.execute(sql)\r\n except:\r\n print(\"Digikala ride\")\r\n j += 1\r\nmydb.commit()\r\n# -----------------------------------------------------------------------------------------------\r\n# Indexing\r\n\r\nsql = \"\"\"CREATE TABLE IF NOT EXISTS orders(\r\nid INT NOT NULL auto_increment,\r\nID_Order INT NOT NULL,\r\nID_Customer INT,\r\nID_Item INT,\r\nDateTime_CartFinalize VARCHAR(255),\r\nAmount_Gross_Order INT,\r\nCity_name_fa VARCHAR(255),\r\nQuantity_Item INT,\r\nPRIMARY KEY(id))\"\"\"\r\nmycursor.execute(sql)\r\nsqlind = \"\"\"CREATE INDEX dt ON orders(DateTime_CartFinalize)\"\"\"\r\n# mycursor.execute(sqlind)\r\nsqlins = \"\"\"INSERT INTO orders(ID_Order,ID_Customer,ID_Item,DateTime_CartFinalize,Amount_Gross_Order,City_name_fa,Quantity_Item)\r\n VALUES (%s,%s,%s,%s,%s,%s,%s)\"\"\"\r\nfor i in peach:\r\n try:\r\n mycursor.execute(sqlins, i)\r\n except:\r\n continue\r\n\r\nmydb.commit()\r\nmycursor.close()\r\nmydb.close()\r\n","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":12595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"207162192","text":"from collections import Counter\nfrom sklearn.metrics import f1_score,precision_score,recall_score\nimport codecs,json\nimport numpy as np\nimport os,math,sys\nsys.path.append(\"./\")\n\n\n\ndef evalDiscrete(all_t,all_y):\n all_t = [t_e for y_e, t_e in zip(all_y, all_t) if t_e > -1]\n all_y = [y_e for y_e, t_e in zip(all_y, all_t) if t_e > -1]\n correct_num = len([1 for y_e, tag_e in zip(all_y, all_t) if y_e == tag_e])\n wrong_num = len([1 for y_e, tag_e in zip(all_y, all_t) if y_e != tag_e])\n if len(set(all_t))==2:\n avemethod='binary'\n eval_hash={}\n eval_hash[\"fscore\"]=f1_score(all_t,all_y,average=avemethod)\n eval_val=eval_hash[\"fscore\"]\n eval_hash[\"precision\"]=precision_score(all_t,all_y,average=avemethod)\n eval_hash[\"recall\"]=recall_score(all_t,all_y,average=avemethod)\n eval_hash[\"correct\"]=correct_num\n eval_hash[\"wrong\"]=wrong_num\n eval_hash[\"rateofone\"]=round(sum(all_t) / len(all_t), 3)\n else:\n print('set_t',set(all_t))\n avemethod='micro'\n f_list=adjust_f1_score(all_t,all_y, average=None)\n eval_hash={fi:round(fscr,4) for fi,fscr in enumerate(f_list)}\n eval_hash['fmacro']=np.mean(f_list)\n eval_val=eval_hash['fmacro']\n eval_hash['count_p']=Counter(all_y).most_common()\n eval_hash['count_t']=Counter(all_t).most_common()\n print('f_list:{}'.format(f_list))\n print('fmacro:{}'.format(np.mean(f_list)))\n return eval_val,eval_hash\n","sub_path":"src/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"528061808","text":"from __future__ import print_function\n\nimport skeletonBuilder\n\nclass Style(skeletonBuilder.Writer):\n #\n # @brief Write a source file\n #\n # @param functions A list of function-objects to write\n def writeOutput(self, options, functionList, templateParameters, precompiler):\n # open the output file for writing\n output = open(options.outputFile, 'w')\n\n precompiler.insert(0, \"define _GNU_SOURCE\")\n templateParameters[\"includes\"].append(\"dlfcn.h\")\n\n self.writeHeaderBegin(output, functionList, templateParameters[\"includes\"], templateParameters[\"globalOnce\"], precompiler);\n\n print(\"static char* dllib = RTLD_NEXT;\", file=output)\n\n for function in functionList:\n print(function.getDefinitionPointer(), file=output)\n print(\"\\tstatic int initialized_dlsym = 0;\\n\", file=output)\n\n print(\"\\nstatic void sioxSymbolInit() {\\ninitialized_dlsym = 1;\", file=output)\n for function in functionList:\n print(function.getDlsym(), file=output)\n\n print(\"}\", file=output)\n\n print(\"\\nstatic void sioxInit() {\\n\", file=output)\n print(\"\\tif(initialized_dlsym == 0) sioxSymbolInit();\", file=output)\n # write all init-templates\n for function in functionList:\n functionVariables = self.functionVariables(function)\n\n for templ in function.usedTemplateList:\n outputString = templ.output('init', functionVariables)\n if outputString != '':\n print('\\t', outputString, end='\\n', sep='', file=output)\n for function in reversed(functionList):\n functionVariables = self.functionVariables(function)\n\n for templ in function.usedTemplateList:\n outputString = templ.output('initLast', functionVariables)\n if outputString != '':\n print('\\t', outputString, end='\\n', sep='', file=output)\n print(\"}\", file=output)\n\n print(\"\\nstatic void sioxFinal() {\", file=output)\n # write all final-functions\n for function in functionList:\n functionVariables = self.functionVariables(function)\n for templ in function.usedTemplateList:\n outputString = templ.output('final', functionVariables)\n if outputString != '':\n print('\\t', outputString, end='\\n', sep='', file=output)\n\n print(\"}\", file=output)\n\n for function in functionList:\n\n # a variable to save the return-value\n returnType = function.type\n\n if returnType != \"void\":\n functionCall = '\\tret = ' + function.getCallPointer() + ';\\n'\n else:\n functionCall = '\\t' + function.getCallPointer() + ';\\n'\n\n functionVariables = self.functionVariables(function, \"if(initialized_dlsym == 0) sioxSymbolInit();\\n\" + functionCall + \"\\n\")\n\n # write function signature\n print(function.getDefinition(), end='\\n{\\n', sep=' ',\n file=output)\n\n # look for va_lists because they need special treament\n if function.parameterList[-1].type == \"...\":\n print('\\tva_list valist;', file=output)\n print(\n '\\tva_start(valist, %s);' % function.parameterList[-2].name,\n file=output)\n # print( '\\t%s val = va_arg(valist, %s);' % (function.parameterList[-2].type, function.parameterList[-2].type), file=output)\n # set the name to args\n function.parameterList[-1].name = \"val\"\n\n if returnType != \"void\":\n print('\\t', returnType, ' ret;', end='\\n', sep='',\n file=output)\n\n self.writeBefore(function, output, functionVariables)\n\n # write the function call\n print(functionCall, file=output)\n\n self.writeAfter(function, output, functionVariables)\n\n # look for va_lists because they need special treament\n if function.parameterList[-1].type == \"...\":\n print(\"\\tva_end(valist);\", file=output)\n\n # write the return statement and close the function\n if returnType != \"void\":\n print('\\treturn ret;\\n}', end='\\n\\n', file=output)\n\n else:\n print('\\n}', end='\\n\\n', file=output)\n\n # close the file\n output.close()\n","sub_path":"tools/gen/lib/styles/dlsym.py","file_name":"dlsym.py","file_ext":"py","file_size_in_byte":4432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"264192411","text":"from abc import ABC, abstractmethod\n\nimport numpy as np\n\n\nclass ActionNoise(ABC):\n \"\"\"\n Base class for Action Noise\n\n :param mean: Mean of noise distribution\n :param std: Standard deviation of noise distribution\n :type mean: float\n :type std: float\n \"\"\"\n\n def __init__(self, mean: float, std: float):\n # super().__init__(mean, std)\n self._mean = mean\n self._std = std\n\n @abstractmethod\n def __call__(self) -> None:\n raise NotImplementedError\n\n @property\n def mean(self) -> float:\n \"\"\"\n Returns mean of noise distribution\n \"\"\"\n return self._mean\n\n @property\n def std(self) -> float:\n \"\"\"\n Returns standard deviation of noise distribution\n \"\"\"\n return self._std\n\n\nclass NormalActionNoise(ActionNoise):\n \"\"\"\n Normal implementation of Action Noise\n\n :param mean: Mean of noise distribution\n :param std: Standard deviation of noise distribution\n :type mean: float\n :type std: float\n \"\"\"\n\n def __init__(self, mean: float, std: float):\n super(NormalActionNoise, self).__init__(mean, std)\n\n def __call__(self) -> float:\n \"\"\"\n Return action noise randomly sampled from noise distribution\n \"\"\"\n return np.random.normal(self._mean, self._std)\n\n def reset(self) -> None:\n pass\n\n\nclass OrnsteinUhlenbeckActionNoise(ActionNoise):\n \"\"\"\n Ornstein Uhlenbeck implementation of Action Noise\n\n :param mean: Mean of noise distribution\n :param std: Standard deviation of noise distribution\n :param theta: Parameter used to solve the Ornstein Uhlenbeck process\n :param dt: Small parameter used to solve the Ornstein Uhlenbeck process\n :param initial_noise: Initial noise distribution\n :type mean: float\n :type std: float\n :type theta: float\n :type dt: float\n :type initial_noise: Numpy array\n \"\"\"\n\n def __init__(\n self,\n mean: float,\n std: float,\n theta: float = 0.15,\n dt: float = 1e-2,\n initial_noise: np.ndarray = None,\n ):\n super(OrnsteinUhlenbeckActionNoise, self).__init__(mean, std)\n self._theta = theta\n self._mean = mean\n self._std = std\n self._dt = dt\n self._initial_noise = initial_noise\n self.noise_prev = None\n self.reset()\n\n def __call__(self) -> float:\n \"\"\"\n (Return action noise randomly sampled from noise distribution\naccording to the Ornstein Uhlenbeck process)\n \"\"\"\n noise = (\n self.noise_prev\n + self._theta * (self._mean - self.noise_prev) * self._dt\n + (self._std * np.sqrt(self._dt) * np.random.normal(size=self._mean.shape))\n )\n self.noise_prev = noise\n return noise\n\n def reset(self) -> None:\n \"\"\"\n Reset the initial noise value for the noise distribution sampling\n \"\"\"\n self.noise_prev = (\n self._initial_noise\n if self._initial_noise is not None\n else np.zeros_like(self._mean)\n )\n","sub_path":"genrl/deep/common/noise.py","file_name":"noise.py","file_ext":"py","file_size_in_byte":3083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"70645556","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\ndef max_in_list(list):\n\t\"\"\"Una funcion para encontrar la cadena mas larga en una lista de strings\"\"\"\n\tmax=list[0]\n\tfor att in list[1:]:\n\t\tif len(att)>len(max):\n\t\t\tmax=att\n\t\telif len(att)==len(max):\n\t\t\tmax=max+','+att\n\treturn max\n\ndef parse_listOfObjects_to_listOfStrings(list):\n\t\"\"\"Una funcion para convertir una lista de objectos en una lista de strings\"\"\"\n\tresult=[]\n\tfor item in list[:]:\n\t\tresult.append(str(item))\n\treturn result\n\nmessage=\"Proporcione la lista de la cual se busca encontrar la cadena mas larga, debe estar en el formato: palabra1,palabra2,palabra3...palabraN; ejemplo: unapalabra,otrapalabra,aquellapalabra,maspalabras - \"\nlistAsString=input(message)\nif len(listAsString)>0:\n\tlistOfStrings=listAsString.split(',')\n\tlist=parse_listOfObjects_to_listOfStrings(listOfStrings)\n\tif len(list)>0:\n\t\tprint(\"La palabra(s) mas grande(s) es(son): \",max_in_list(list))\nelse:\n\tprint(\"No se ha proporcionado una lista\")\n","sub_path":"basic_codes/002_palabra_mas_larga.py","file_name":"002_palabra_mas_larga.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"559002720","text":"def possiable(a,b):\n a=list(a)\n b=list(b)\n length=len(a)\n count=0\n for i in range(length):\n if(a[i]==b[i]):\n count=count+1\n if(count==length-1):\n return True\n else:\n return False\ndef next(now,wordlist,end):\n if(now in wordlist):\n wordlist.pop(wordlist.index(now))\n path=now+\" \"\n if(possiable(now,end)):\n return path\n for i in wordlist:\n save=wordlist.copy()\n if(possiable(i,now)):\n path=path+i\n save.pop(save.index(i))\n return path+next(i,save,end)\n return []\nbegin=input(\"\")\nend=input(\"\")\nnow=begin\npaths=[]\nwordlist=eval(input(\"\"))\nsave=wordlist\nlast_step=False\nfor i in wordlist:\n if(possiable(end,i)):\n last_step=True\nfirst_step=False\nfor i in wordlist:\n if(possiable(begin,i)):\n first_step=True\nif(not last_step):\n print(\"[]\")\nelif(not first_step):\n print(\"[]\")\nelse:\n while(True):\n a=next(now,wordlist,end).split(\"+\")\n if(a==[]):\n break\n else:\n paths.append(a)\n wordlist.pop(wordlist.index(a[1]))\n print(paths)\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ","sub_path":"Code/CodeRecords/2747/60636/237631.py","file_name":"237631.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"5451408","text":"#!/usr/bin/env python3\n#\n# Extract hyperopt result and put it in a CSV file.\n#\n# usage: extract_hyperopt_result.py [-h] [-i INPUT] [-o OUTPUT]\n\nimport re\nimport json\nimport csv\nimport argparse\nimport sys\nimport os\nimport select\n\ndef extract(input_file):\n pattern = \"^.* +([0-9]+)\\/([0-9]+): +([0-9]+).+\\. +([0-9]+)\\/([0-9]+)\\/([0-9]+) +.+(-?[0-9]+\\.[0-9]+)%\\. +Median.+(-?[0-9]+\\.[0-9]+)%\\. +.+ +(-?[0-9]+\\.[0-9]+) +([A-Z]+) +\\( +(-?[0-9]+\\.[0-9]+)Σ%\\)\\. +.+ +([0-9]+\\.?[0-9]*) +.+: +(-?[0-9]+\\.[0-9]+)\"\n columns = ['all','epoch','nb_epoch','trades','wins','draws','losses','avg_profit','median_profit','total_profit', 'profit_unit', 'profit_percent','avg_duration','objective']\n\n # Read hyperopt result\n for line in input_file:\n if re.search(\"Wins/Draws/Losses\", line):\n result = re.match(pattern, line)\n if result != None: \n dict_data = {col_name:result.group(n) for n, col_name in enumerate(columns) }\n \n # Remove 1st column\n dict_data.pop('all')\n\n # Get the params part in json format\n elif re.search(\"{\\\"params\\\"\", line):\n json_param = json.loads(line)\n break\n\n if 'dict_data' in locals() and 'json_param' in locals() :\n dict_data.update(json_param['params'])\n \n return dict_data\n else:\n sys.exit('Expected input not found...') \n\ndef convert(dict_data, csv_file_name):\n\n if not os.path.isfile(csv_file_name):\n # Create file with header\n with open(csv_file_name, 'w') as csv_file:\n writer = csv.DictWriter(csv_file, fieldnames=dict_data.keys())\n writer.writeheader()\n writer.writerow(dict_data)\n else:\n # Add a line\n with open(csv_file_name, 'a') as csv_file:\n writer = csv.DictWriter(csv_file, fieldnames=dict_data.keys())\n writer.writerow(dict_data)\n\ndef main(argv):\n parser = argparse.ArgumentParser(description='Extract hyperopt result and put it in a CSV file.')\n parser.add_argument('-i', '--input', help='Input file (Default: stdin)')\n parser.add_argument('-o', '--output', default='./hyperopt_res.csv', help='Output file')\n parser.add_argument('-s', '--strategie', help='Used strategie')\n parser.add_argument('-l', '--lossFunction', help='Used loss function')\n parser.add_argument('-t', '--timeframe', help='Used timeframe')\n\n args = parser.parse_args()\n\n if args.input:\n if os.path.isfile(args.input):\n with open(args.input, 'r') as input_file:\n dict_data = extract(input_file)\n else:\n sys.exit('\\\"' + args.input + '\\\" is not a valid file...')\n else:\n # Check if stdin datas are available\n if select.select([sys.stdin,],[],[],0.0)[0]:\n dict_data = extract(sys.stdin)\n else:\n sys.exit(\"Not data from stdin...\")\n\n if args.strategie:\n dict_data['strategie'] = args.strategie\n\n if args.lossFunction:\n dict_data['lossFunction'] = args.lossFunction\n\n if args.timeframe:\n dict_data['timeframe'] = args.timeframe\n\n convert(dict_data, args.output)\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n\n","sub_path":"scripts/extract_hyperopt_result.py","file_name":"extract_hyperopt_result.py","file_ext":"py","file_size_in_byte":3221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"280031176","text":"from django.shortcuts import render,redirect\nfrom customer import forms\nfrom django.contrib.auth import authenticate,login,logout\nfrom django.views.generic import TemplateView,ListView,DetailView,DeleteView,CreateView\nfrom django.contrib.auth.models import User\nfrom owner.models import Mobile\nfrom customer.models import Cart,Orders\nfrom django.contrib import messages\nfrom.decorators import signin_required\nfrom django.utils.decorators import method_decorator\nfrom .filters import MobileFilter\n# Create your views here.\nclass RegistrationView(TemplateView):\n form_class=forms.RegistrationForm\n template_name = \"registration.html\"\n model=User\n context={}\n\n def get(self, request, *args, **kwargs):\n form=self.form_class\n self.context[\"form\"]=form\n return render(request,self.template_name,self.context)\n\n def post(self,request,*args,**kwargs):\n form=self.form_class(request.POST)\n if form.is_valid():\n form.save()\n return redirect(\"signin\")\n\nclass SignInView(TemplateView):\n template_name = \"login.html\"\n form_class=forms.LoginForm\n cotext={}\n def get(self, request, *args, **kwargs):\n form=self.form_class\n self.cotext[\"form\"]=form\n return render(request,self.template_name,self.cotext)\n\n def post(self,request, *args, **kwargs):\n form = self.form_class(request.POST)\n if form.is_valid():\n username=form.cleaned_data[\"username\"]\n password=form.cleaned_data[\"password\"]\n user=authenticate(request,username=username,password=password)\n if user:\n login(request,user)\n return redirect(\"customerhome\")\n\n\n@method_decorator(signin_required,name=\"dispatch\")\nclass CustomerHome(ListView):\n template_name = \"customerhomepage.html\"\n model = Mobile\n context_object_name = \"mobiles\"\n\n@method_decorator(signin_required,name=\"dispatch\")\nclass ProductDetail(DetailView):\n template_name = \"product_detail.html\"\n model = Mobile\n context_object_name = \"mobile\"\n pk_url_kwarg = 'pk'\n\n\n@method_decorator(signin_required,name=\"dispatch\")\nclass AddCartView(TemplateView):\n model=Cart\n def get(self, request, *args, **kwargs):\n product_id=kwargs[\"id\"]\n product=Mobile.objects.get(id=product_id)\n user=request.user\n cart=Cart(product=product,user=user)\n cart.save()\n messages.success(request,\"Added to cart\")\n return redirect(\"customerhome\")\n\n@method_decorator(signin_required,name=\"dispatch\")\nclass ViewCart(ListView):\n model = Cart\n template_name = \"cart_detail.html\"\n context_object_name = \"items\"\n\n def get_queryset(self):\n queryset=self.model.objects.filter(user=self.request.user,status=\"in_cart\")\n return queryset\n\n@method_decorator(signin_required,name=\"dispatch\")\nclass CartRemove(DeleteView):\n model = Cart\n def get(self, request, *args, **kwargs):\n cart_id=kwargs[\"c_id\"]\n cart=Cart.objects.get(id=cart_id)\n cart.delete()\n return redirect(\"cartdetails\")\n\n@method_decorator(signin_required,name=\"dispatch\")\nclass OrderView(CreateView):\n template_name = \"order_place.html\"\n form_class = forms.OrderForm\n model = Orders\n def post(self, request, *args, **kwargs):\n form=self.form_class(request.POST)\n if form.is_valid():\n order=form.save(commit=False)\n cart_id=kwargs[\"c_id\"]\n product_id=kwargs[\"p_id\"]\n cart=Cart.objects.get(id=cart_id)\n product=Mobile.objects.get(id=product_id)\n order.product=product\n order.user=request.user\n order.save()\n cart.status=\"order_placed\"\n cart.save()\n return redirect(\"customerhome\")\n\n@method_decorator(signin_required,name=\"dispatch\")\nclass MyOrders(ListView):\n template_name = \"myorders.html\"\n context_object_name = \"orders\"\n model = Orders\n def get_queryset(self):\n queryset=self.model.objects.filter(user=self.request.user)\n return queryset\n@method_decorator(signin_required,name=\"dispatch\")\nclass OrderRemove(DeleteView):\n model = Orders\n def get(self, request, *args, **kwargs):\n order_id=kwargs[\"o_id\"]\n order=Orders.objects.get(id=order_id)\n order.delete()\n return redirect(\"myorder\")\n\n@method_decorator(signin_required,name=\"dispatch\")\nclass OrderDetail(DetailView):\n template_name = \"order_detail.html\"\n model = Orders\n context_object_name = \"order\"\n pk_url_kwarg = 'pk'\n\n\n@method_decorator(signin_required,name=\"dispatch\")\nclass SignOutView(TemplateView):\n def get(self, request, *args, **kwargs):\n logout(request)\n return redirect(\"signin\")\n\nclass MobileFilterView(TemplateView):\n template_name = \"search.html\"\n def get(self, request, *args, **kwargs):\n form=MobileFilter(request.GET,queryset=Mobile.objects.all())\n return render(request,self.template_name,{\"filter\":form})","sub_path":"customer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"312643982","text":"import requests, json\nfrom PIL import Image\nfrom PIL import ImageEnhance\nimport pytesseract, cv2\nimport numpy as np\nimport time, datetime, re, hashlib, os, sys, shutil\nfrom time import sleep\nfrom selenium.common.exceptions import NoSuchElementException, NoSuchAttributeException, TimeoutException\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom fake_useragent import UserAgent\n\nclass WeixinApi:\n def __init__(self):\n self.url = 'https://api.newrank.cn/api/sync/weixin/data/combine/search'\n self.response = ''\n\n\n def doGet(self, kw):\n key = {'Key': '183860ef3cd34f42ba8a757cc',}\n data = {\n 'includeAllWords': kw,\n 'from': '2020-01-05 15:00:00',\n 'to': '2020-01-05 15:50:00',\n 'size': 5,\n }\n\n response = requests.post(url = self.url, data = data, headers = key)\n self.response = response.text\n #\n # with open('newrand.json', 'r', encoding = 'utf-8') as f:\n # self.response = f.read()\n # f.close()\n\n with open('newrand.json', 'w+', encoding = 'utf-8') as f:\n f.write(self.response)\n f.write('\\n')\n\n # return response.text\n # print(self.response)\n\n\n\n\n def obtain(self):\n content = json.loads(self.response, strict = False)\n code = content.get('code')\n urlList = []\n\n if code == 0:\n newsList = content.get('data')\n for item in newsList:\n try:\n ctime = item.get('updateTime')\n title = item.get('title')\n summary = item.get('summary')\n imageUrl = item.get('imageUrl')\n link = item.get('url')\n\n # print(ctime, title, desc, picUrl, link)\n urlList.append(link.strip())\n except:\n continue\n\n # print(urlList)\n self.getURL(urlList)\n self.browser.quit()\n\n def getURL(self, url):\n options = webdriver.FirefoxOptions()\n userAgent = ['MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1',\n 'Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30'\n ]\n options.add_argument('user-agent=%s' % userAgent[1])\n script = 'Object.defineProperties(navigator, {webdriver:{get:()=>undefined}})'\n\n self.browser = webdriver.Firefox()\n self.browser.execute_script(script)\n\n # options = webdriver.ChromeOptions()\n # options.add_experimental_option(\"excludeSwitches\", [\"enable-automation\"])\n # options.add_experimental_option('useAutomationExtension', False)\n # userAgent = [\n # 'MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1',\n # 'Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',\n # ]\n # options.add_argument('user-agent=%s' % userAgent[1])\n # self.browser = webdriver.Chrome(options = options, executable_path = r'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe')\n # self.browser.execute_cdp_cmd(\"Page.addScriptToEvaluateOnNewDocument\", {\n # \"source\": \"\"\"\n # Object.defineProperty(navigator, 'webdriver', {\n # get: () => undefined\n # })\n # \"\"\"\n # })\n\n self.browser.set_window_position(x = 630, y = 0)\n # element = self.browser.find_element_by_tag_name('body')\n # element.send_keys(Keys.CONTROL + 't')\n\n for link in url:\n try:\n self.openUrl(link)\n # break\n except Exception as e:\n print('Exception: ', e)\n continue\n\n\n def openUrl(self, url):\n try:\n # url = '''https://mp.weixin.qq.com/s?src=11×tamp=1609816613&ver=2809&signature=mANNSjONrRLyR4WwpU2YLEPjmvXQ2gxWntG*rvRTW9yzsnEmNYK2m9t4-Af3XWhYCtTvTk9fBqQejhRqgrc9S1wZenMBxJBoO3LjP*AdbdSYawY1Mwc4FNy6IqdxLLLF&new=1'''\n # print(url, '\\n')\n self.browser.get(url)\n except TimeoutException:\n pass\n\n pageHTML = ''\n try:\n pageHTML = self.browser.find_element_by_css_selector('div.rich_media_content').get_attribute('innerHTML')\n except NoSuchElementException:\n try:\n # verife = self.browser.find_element_by_css_selector('div.content-box > p.p3 > label').text\n verife = self.browser.find_element_by_css_selector('#verify-form > p:nth-child(5)').text\n if '验证码' in verife:\n print('有验证码')\n return\n except NoSuchElementException:\n pageHTML = self.browser.page_source\n\n prefix = int(time.time())\n htmlPath = './html/' + str(prefix) + '_weixin.html'\n with open(htmlPath, 'w+', encoding = 'utf-8') as f:\n f.write(pageHTML)\n # f.write('\\n')\n\n # self.browser.quit()\n sleep(2)\n\n def downloadFile(self, store_path):\n imgObj = self.browser.find_element_by_css_selector('p.p4 span.s1 a img#seccodeImage')\n\n url = imgObj.get_attribute('src')\n print('url:',url)\n filename = url.split('tc=')[-1]\n filepath = os.path.join(store_path, filename) + '.png'\n imgObj.screenshot(filepath)\n\n\n # imgData = requests.get(url, allow_redirects = True).content\n # with open(filepath, 'wb') as handler:\n # handler.write(imgData)\n\n return filepath\n\n def ocrCode(self):\n\n # filename = 'D:\\PyProject\\/Non-project\\crawl\\weixin_project\\/1609228332.png'\n # img = cv2.imread(filename, 0)\n # print(np.shape(img))\n # kernel = np.ones((1, 1), np.uint8)\n # dilate = cv2.dilate(img, kernel, iterations = 1)\n # cv2.imwrite('D:\\PyProject\\/Non-project\\crawl\\weixin_project\\/new_1609228332.png', dilate)\n\n img = Image.open('D:\\PyProject\\/Non-project\\crawl\\weixin_project\\/new_1609228332.png')\n img = img.convert('RGB') # L\n # img.show()\n enhancer = ImageEnhance.Color(img)\n enhancer = enhancer.enhance(0)\n enhancer = ImageEnhance.Brightness(enhancer)\n enhancer = enhancer.enhance(2)\n enhancer = ImageEnhance.Contrast(enhancer)\n enhancer = enhancer.enhance(8)\n enhancer = ImageEnhance.Sharpness(enhancer)\n img = enhancer.enhance(20)\n code = pytesseract.image_to_string(img)\n\n # threshold = 140\n # table = []\n # for i in range(256):\n # if i < threshold:\n # table.append(0)\n # else:\n # table.append(1)\n #\n # out = img.point(table, '1')\n # img = img.convert('RGB')\n # print(pytesseract.image_to_string(img))\n # print('ocr str:', code.strip())\n print('The code: %s' % code.strip())\n\n\n def removeHTML(self):\n filepath = './html'\n del_list = os.listdir(filepath)\n for f in del_list:\n file_path = os.path.join(filepath, f)\n if os.path.isfile(file_path):\n os.remove(file_path)\n elif os.path.isdir(file_path):\n shutil.rmtree(file_path)\n\n\n\nif __name__ == '__main__':\n keyword = '五粮液'\n\n wx = WeixinApi()\n # wx.removeHTML()\n wx.doGet(keyword)\n r = wx.obtain()\n\n # print(r)\n","sub_path":"crawl/weixin_project/newrand.py","file_name":"newrand.py","file_ext":"py","file_size_in_byte":7921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"115440451","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport datetime\nfrom decimal import Decimal\nimport django.contrib.auth.models\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('auth', '0006_require_contenttypes_0002'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='BaseModel',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('is_active', models.BooleanField(default=True)),\n ('time_created', models.DateTimeField(default=datetime.datetime.now)),\n ('time_modified', models.DateTimeField(default=datetime.datetime.now)),\n ],\n ),\n migrations.CreateModel(\n name='User',\n fields=[\n ('user_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL)),\n ('address_line_1', models.CharField(max_length=100)),\n ('address_line_2', models.CharField(max_length=100, blank=True)),\n ('city', models.CharField(max_length=50)),\n ('state', models.CharField(max_length=50)),\n ('zipcode', models.CharField(max_length=10)),\n ('phone', models.BigIntegerField()),\n ],\n options={\n 'abstract': False,\n 'verbose_name': 'user',\n 'verbose_name_plural': 'users',\n },\n bases=('auth.user',),\n managers=[\n ('objects', django.contrib.auth.models.UserManager()),\n ],\n ),\n migrations.CreateModel(\n name='AuctionEvent',\n fields=[\n ('basemodel_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='bidding.BaseModel')),\n ('shipping_method', models.IntegerField(choices=[(1, b'USPS'), (2, b'FedEx'), (3, b'UPS'), (4, b'DHL')])),\n ('shipping_detail', models.CharField(max_length=100, blank=True)),\n ('payment_detail', models.CharField(max_length=200, blank=True)),\n ('start_time', models.DateTimeField(help_text='Format (Hour & Minute are optional): 10/25/2006 14:30')),\n ('end_time', models.DateTimeField(help_text='Format (Hour & Minute are optional): 10/25/2006 14:30')),\n ('starting_price', models.DecimalField(default=Decimal('0.00'), max_digits=5, decimal_places=2)),\n ('shipping_fee', models.DecimalField(default=Decimal('0.00'), max_digits=5, decimal_places=2)),\n ('reserve_price', models.DecimalField(default=Decimal('0.00'), max_digits=5, decimal_places=2, blank=True)),\n ],\n bases=('bidding.basemodel',),\n ),\n migrations.CreateModel(\n name='Bid',\n fields=[\n ('basemodel_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='bidding.BaseModel')),\n ('amount', models.DecimalField(default=Decimal('0.00'), help_text='All bids are final. Price in US dollars.', max_digits=5, decimal_places=2)),\n ('auction_event', models.ForeignKey(related_name='bids', to='bidding.AuctionEvent')),\n ('bidder', models.ForeignKey(related_name='bids', to='bidding.User')),\n ],\n bases=('bidding.basemodel',),\n ),\n migrations.CreateModel(\n name='Item',\n fields=[\n ('basemodel_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='bidding.BaseModel')),\n ('title', models.CharField(max_length=200)),\n ('picture', models.ImageField(upload_to=b'images')),\n ('description', models.TextField(blank=True)),\n ('condition', models.IntegerField(choices=[(1, b'Used'), (2, b'Used Like New'), (3, b'New')])),\n ('status', models.IntegerField(default=1, choices=[(1, b'Idle'), (2, b'Running'), (3, b'On Hold'), (4, b'Sold'), (5, b'Expired'), (6, b'Disputed')])),\n ],\n bases=('bidding.basemodel',),\n ),\n migrations.CreateModel(\n name='ItemCategory',\n fields=[\n ('basemodel_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='bidding.BaseModel')),\n ('title', models.CharField(max_length=100)),\n ('pic', models.ImageField(upload_to=b'images')),\n ('description', models.TextField(blank=True)),\n ('parent', models.ForeignKey(blank=True, to='bidding.ItemCategory', null=True)),\n ],\n bases=('bidding.basemodel',),\n ),\n migrations.CreateModel(\n name='Sales',\n fields=[\n ('basemodel_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='bidding.BaseModel')),\n ('payment_status', models.IntegerField(default=1, choices=[(1, b'Processing'), (2, b'Cleared'), (3, b'Disputed'), (4, b'Refunded')])),\n ('invoice_number', models.CharField(unique=True, max_length=200)),\n ('auction_event', models.ForeignKey(related_name='sales', to='bidding.AuctionEvent')),\n ],\n bases=('bidding.basemodel',),\n ),\n migrations.CreateModel(\n name='Seller',\n fields=[\n ('basemodel_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='bidding.BaseModel')),\n ('paypal_email', models.EmailField(max_length=254)),\n ('default_shipping_method', models.IntegerField(default=1, choices=[(1, b'USPS'), (2, b'FedEx'), (3, b'UPS'), (4, b'DHL')])),\n ('default_shipping_detail', models.CharField(max_length=100, null=True, blank=True)),\n ('default_payment_detail', models.CharField(max_length=200, null=True, blank=True)),\n ('user', models.OneToOneField(related_name='seller', to='bidding.User')),\n ],\n bases=('bidding.basemodel',),\n ),\n migrations.AddField(\n model_name='item',\n name='category',\n field=models.ForeignKey(related_name='auction_items', to='bidding.ItemCategory'),\n ),\n migrations.AddField(\n model_name='item',\n name='seller',\n field=models.ForeignKey(related_name='auction_items', to='bidding.User'),\n ),\n migrations.AddField(\n model_name='auctionevent',\n name='item',\n field=models.ForeignKey(related_name='auction_events', to='bidding.Item'),\n ),\n migrations.AddField(\n model_name='auctionevent',\n name='winning_bidder',\n field=models.ForeignKey(related_name='won_auctions', blank=True, to='bidding.User', null=True),\n ),\n ]\n","sub_path":"auction/hpbid/bidding/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":7205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"643828761","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nCollect Kafka metrics using jolokia agent\n\n### Example Configuration\n\n```\n host = localhost\n port = 8778\n```\n\"\"\"\n\nfrom jolokia import JolokiaCollector, MBean\nimport re\nimport sys\n\nclass KafkaJolokiaCollector(JolokiaCollector):\n TOTAL_TOPICS = re.compile('kafka\\.server:name=.*PerSec,type=BrokerTopicMetrics')\n\n def collect_bean(self, prefix, obj):\n if isinstance(obj, dict) and \"Count\" in obj:\n counter_val = obj[\"Count\"]\n self.parse_dimension_bean(prefix, \"count\", counter_val)\n else:\n for k, v in obj.iteritems():\n if type(v) in [int, float, long]:\n self.parse_dimension_bean(prefix, k, v)\n elif isinstance(v, dict):\n self.collect_bean(\"%s.%s\" % (prefix, k), v)\n elif isinstance(v, list):\n self.interpret_bean_with_list(\"%s.%s\" % (prefix, k), v)\n\n def patch_dimensions(self, bean, dims):\n metric_name = dims.pop(\"name\", None)\n metric_type = dims.pop(\"type\", None)\n # If the prefix matches the TOTAL_TOPICS regular expression it means\n # that, metric has no topic associated with it and is really for all topics on that broker\n if re.match(self.TOTAL_TOPICS, bean.prefix):\n dims[\"topic\"] = \"_TOTAL_\"\n return metric_name, metric_type, dims\n\n def patch_metric_name(self, bean, metric_name_list):\n if self.config.get('prefix', None):\n metric_name_list = [self.config['prefix']] + metric_name_list\n\n metric_name_list.append(bean.bean_key.lower())\n return metric_name_list\n","sub_path":"src/diamond/collectors/jolokia/kafka_jolokia.py","file_name":"kafka_jolokia.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"477534565","text":"#!/usr/bin/env python3\n\n# Node Robot in file movearm.py\n# Robot.puckup_db() - orient toward the dumbbell in front of the robot, within .5 meters of robot, move forward, and raise overhead\n# Robot.putdown_db() - put down the dumbbell where robot is, back away slightly\n#\n# to operate, need: roscore, roslaunch q_learning_project turtlebot3_intro_robo_manipulation.launch\n# roslaunch turtlebot3_manipulation_moveit_config move_group.launch\n# rosrun q_learning_project movearm.py\n\n\nimport rospy\n\n# import the moveit_commander, which allows us to control the arms\nimport moveit_commander\nimport numpy as np\nimport math\nfrom sensor_msgs.msg import LaserScan\nfrom geometry_msgs.msg import Twist\nfrom geometry_msgs.msg import Vector3\nfrom q_learning_project.msg import ArmCommand, ArmResult\n\n\nclass Robot(object):\n def __init__(self):\n\n # initialize this node\n rospy.init_node(\"q_learning_control_arm\")\n\n # the interface to the group of joints making up the turtlebot3\n # openmanipulator arm\n self.move_group_arm = moveit_commander.MoveGroupCommander(\"arm\")\n\n # the interface to the group of joints making up the turtlebot3\n # openmanipulator gripper\n self.move_group_gripper = moveit_commander.MoveGroupCommander(\"gripper\")\n\n # Declare node as a subscriber to the scan topic and\n # set self.process_scan as the function to be used for callback\n rospy.Subscriber(\"/scan\", LaserScan, self.process_scan)\n rospy.Subscriber(\"/q_learning/arm_cmd\", ArmCommand, self.command_received)\n\n # Get a publisher to the cmd_vel topic\n self.twist_pub = rospy.Publisher(\"/cmd_vel\", Twist, queue_size=10)\n self.resp_pub = rospy.Publisher(\"/q_learning/arm_res\", ArmResult, queue_size=10)\n\n # Create a default twist msg (all values 0)\n lin = Vector3()\n ang = Vector3()\n self.twist = Twist(linear=lin, angular=ang)\n self.moving = False\n\n def home_pose(self):\n arm_joint_goal = [0.0, -1.0, 0.3, 0.7]\n self.move_group_arm.go(arm_joint_goal, wait=True)\n self.move_group_arm.stop()\n\n def open_gripper(self):\n gripper_joint_goal = self.move_group_gripper.get_current_joint_values()\n gripper_joint_goal[0] = 0.019\n gripper_joint_goal[1] = 0.019\n self.move_group_gripper.go(gripper_joint_goal, wait=True)\n self.move_group_gripper.stop()\n\n def close_gripper(self):\n gripper_joint_goal = self.move_group_gripper.get_current_joint_values()\n gripper_joint_goal = [0.008, 0.008]\n self.move_group_gripper.go(gripper_joint_goal, wait=True)\n self.move_group_gripper.stop()\n\n def reach_dumbbell(self):\n arm_joint_goal = self.move_group_arm.get_current_joint_values()\n arm_joint_goal[0] = 0.0\n arm_joint_goal[1] = 0.85\n arm_joint_goal[2] = -0.4\n arm_joint_goal[3] = -0.55\n self.move_group_arm.go(arm_joint_goal, wait=True)\n self.move_group_arm.stop()\n\n def lift_dumbbell(self):\n arm_joint_goal = self.move_group_arm.get_current_joint_values()\n arm_joint_goal = [0.0, -0.8, -0.2, 0.3]\n self.move_group_arm.go(arm_joint_goal, wait=True)\n self.move_group_arm.stop()\n rospy.sleep(1)\n\n def set_dumbbell(self):\n arm_joint_goal = self.move_group_arm.get_current_joint_values()\n arm_joint_goal = [0.0, 0.95, -0.75, -0.3]\n self.move_group_arm.go(arm_joint_goal, wait=True)\n self.move_group_arm.stop()\n self.open_gripper()\n self.twist.linear.x = -0.07\n self.twist_pub.publish(self.twist)\n rospy.sleep(4)\n self.twist.linear.x = 0\n self.twist_pub.publish(self.twist)\n\n def approach_dumbbell(self, db_dir: float, db_dist: float):\n err_lin_min = 0.22 # stay 1/4 meters away from the dumbbell\n kp_lin = 0.1\n\n err_ang_min = 0.005\n kp_ang = math.pi / 2\n\n twist = Twist()\n\n if abs(db_dir) > err_ang_min:\n twist.angular.z = kp_ang * db_dir\n\n if db_dist > err_lin_min: # if we are far enough from the db\n twist.linear.x = kp_lin * db_dist\n else:\n self.moving = False\n\n self.twist_pub.publish(twist)\n\n def process_scan(self, data):\n def rad_signed(deg: int) -> float:\n return math.radians(deg - 360 if deg > 180 else deg)\n\n if not self.moving:\n return\n\n angled = [*enumerate(data.ranges)]\n\n front_ranges = [\n (rad_signed(deg), dist)\n for (deg, dist) in angled[350:] + angled[:10]\n if math.isfinite(dist)\n ]\n\n if not front_ranges:\n self.resp_pub.publish(ArmResult(error=\"no front scan data\"))\n return\n\n (dirs, dists) = [*zip(*front_ranges)]\n\n dir_min = (dirs[0] + dirs[-1]) / 2.0 if len(dirs) > 1 else dirs[0]\n\n dist_min = min(dists)\n\n self.approach_dumbbell(dir_min, dist_min)\n\n def pickup_db(self):\n rate = rospy.Rate(1)\n rate.sleep()\n self.moving = False # boolean for moving toward db\n self.twist_pub.publish(Twist()) # stop moving\n\n self.home_pose()\n\n self.open_gripper()\n\n self.reach_dumbbell()\n\n self.moving = True\n while self.moving == True:\n rospy.sleep(0.1) # Wait for movement to stop\n\n self.close_gripper()\n rate.sleep()\n\n self.lift_dumbbell()\n rate.sleep()\n\n def putdown_db(self):\n self.twist.linear.x = 0\n self.twist_pub.publish(Twist()) # stop\n\n self.set_dumbbell()\n self.open_gripper()\n self.home_pose()\n\n def command_received(self, data: ArmCommand):\n\n response = ArmResult()\n if data.command == \"up\":\n self.pickup_db()\n response.result = \"up\"\n elif data.command == \"down\":\n self.putdown_db()\n response.result = \"down\"\n else:\n response.error = \"unknown command\"\n self.resp_pub.publish(response)\n\n def run(self):\n rate = rospy.Rate(1)\n connections = self.resp_pub.get_num_connections()\n while connections < 1:\n rate.sleep()\n connections = self.resp_pub.get_num_connections()\n\n rospy.spin()\n\n\nif __name__ == \"__main__\":\n\n node = Robot()\n node.run()\n","sub_path":"scripts/control_arm.py","file_name":"control_arm.py","file_ext":"py","file_size_in_byte":6382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"561288736","text":"import argparse\n\nfrom igibson.challenge.behavior_challenge import BehaviorChallenge\n\nfrom rl_agent import PPOAgent\nfrom simple_agent import RandomAgent\n\n\ndef get_agent(agent_class, ckpt_path=\"\"):\n if agent_class == \"Random\":\n return RandomAgent()\n elif agent_class == \"PPO\":\n return PPOAgent(ckpt_path)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--agent-class\", type=str, default=\"Random\", choices=[\"Random\", \"PPO\"])\n parser.add_argument(\"--ckpt-path\", default=\"\", type=str)\n\n args = parser.parse_args()\n\n agent = get_agent(agent_class=args.agent_class, ckpt_path=args.ckpt_path)\n challenge = BehaviorChallenge()\n challenge.submit(agent)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"94387043","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nfrom xml.dom.minidom import parse\nimport xml.dom.minidom\nimport datetime\nimport os\nimport sys\nfrom poolrate import poolrate\n\ndef writelog(data,cfg,filename):\n\t## write XML log file\n\tlogdir = cfg['General']['log_dir']\n\n\tprint('Logging into ' + logdir + filename + ' ... ',end=\"\")\n\tsys.stdout.flush()\n\tlog = '\\n'\n\ttime = filename.strip(\"log-\").strip(\".xml\")\n\n\tlog += \"\\n\\t\\n\"\n\n\tfor mminer in data:\n\t\tlog += \"\\t\\n\"\n\t\tlog += \"\\t\\t\" + mminer[0] + \"\\n\"\n\t\tfor miner in mminer[1:]:\n\t\t\tlog += \"\\t\\t\\n\"\n\t\t\tlog += \"\\t\\t\\t\" + miner[0] + \"\\n\"\n\t\t\tlog += \"\\t\\t\\t\" + miner[1] + \"\\n\"\n\t\t\tlog += \"\\t\\t\\t\" + miner[2] + \"\\n\"\n\t\t\tlog += \"\\t\\t\\t\" + miner[3] + \"\\n\"\n\t\t\tfor dev_stat in miner[4]:\n\t\t\t\tlog += \"\\t\\t\\t\\n\"\n\t\t\t\tlog += \"\\t\\t\\t\\t\" + dev_stat[0] + \"\\n\"\n\t\t\t\tlog += \"\\t\\t\\t\\t\" + dev_stat[1] + \"\\n\"\n\t\t\t\tlog += \"\\t\\t\\t\\t\" + dev_stat[2] + \"\\n\"\n\t\t\t\tlog += \"\\t\\t\\t\\t\" + str(dev_stat[3]) + \"\\n\"\n\t\t\t\tfor temp in dev_stat[4]:\n\t\t\t\t\tlog += \"\\t\\t\\t\\t\" + temp + \"\\n\"\n\t\t\t\tfor fan in dev_stat[5]:\n\t\t\t\t\tlog += \"\\t\\t\\t\\t\" + fan + \"\\n\"\n\t\t\t\tlog += \"\\t\\t\\t\\n\"\n\t\t\tfor pool_stat in miner[5]:\n\t\t\t\tlog += \"\\t\\t\\t\\n\"\n\t\t\t\tlog += \"\\t\\t\\t\\t\" + pool_stat[0] + \"\\n\"\n\t\t\t\tlog += \"\\t\\t\\t\\t\" + pool_stat[1] + \"\\n\"\n\t\t\t\tlog += \"\\t\\t\\t\\n\"\n\t\t\tlog += \"\\t\\t\\t\" + miner[6] + \"\\n\"\n\t\t\tlog += \"\\t\\t\\n\"\n\t\tlog += \"\\t\\n\"\n\tlog += \"\"\n\n\tlogfile = open(logdir + filename, 'w')\n\tlogfile.write(log)\n\tlogfile.close()\n\tprint('Done.')\n\ndef readlog(logdir,filename):\n\t## read XML log file\n\tdata = []\n\tDOMTree = xml.dom.minidom.parse( logdir + filename )\n\tlog = DOMTree.documentElement\n\ttime = datetime.datetime.strptime(log.getElementsByTagName(\"time\")[0].childNodes[0].data,\"%Y_%m_%d_%H_%M\")\n\n\tfor mminerXML in log.getElementsByTagName(\"miner\"):\n\t\tmminer = []\n\t\tmminer.append(mminerXML.getElementsByTagName(\"IP\")[0].childNodes[0].data)\n\t\tfor minerXML in mminerXML.getElementsByTagName(\"subminer\"):\n\t\t\tdev = []\n\t\t\tpool = []\n\t\t\tminer = []\n\t\t\tminer.append(minerXML.getElementsByTagName(\"Port\")[0].childNodes[0].data)\n\t\t\tminer.append(minerXML.getElementsByTagName(\"Status\")[0].childNodes[0].data)\n\t\t\tminer.append(minerXML.getElementsByTagName(\"Elapsed\")[0].childNodes[0].data)\n\t\t\tminer.append(minerXML.getElementsByTagName(\"TotalMH\")[0].childNodes[0].data)\n\t\t\tfor dev_statXML in minerXML.getElementsByTagName(\"dev\"):\n\t\t\t\tdev_stat=[]\n\t\t\t\tdev_stat.append(dev_statXML.getElementsByTagName(\"DeviceElapsed\")[0].childNodes[0].data)\n\t\t\t\tdev_stat.append(dev_statXML.getElementsByTagName(\"TotalMH\")[0].childNodes[0].data)\n\t\t\t\tdev_stat.append(dev_statXML.getElementsByTagName(\"MaxTemperature\")[0].childNodes[0].data)\n\t\t\t\tdev_stat.append(dev_statXML.getElementsByTagName(\"ModuleNumber\")[0].childNodes[0].data)\n\t\t\t\ttemp=[]\n\t\t\t\tfor tempXML in dev_statXML.getElementsByTagName(\"Temperature\"):\n\t\t\t\t\ttemp.append(tempXML.childNodes[0].data)\n\t\t\t\tdev_stat.append(temp)\n\t\t\t\tfan=[]\n\t\t\t\tfor fanXML in dev_statXML.getElementsByTagName(\"FanSpeed\"):\n\t\t\t\t\tfan.append(fanXML.childNodes[0].data)\n\t\t\t\tdev_stat.append(fan)\n\t\t\t\tdev.append(dev_stat)\n\t\t\tfor pool_statXML in minerXML.getElementsByTagName(\"pool\"):\n\t\t\t\tpool_stat=[]\n\t\t\t\tpool_stat.append(pool_statXML.getElementsByTagName(\"Status\")[0].childNodes[0].data)\n\t\t\t\tpool_stat.append(pool_statXML.getElementsByTagName(\"URL\")[0].childNodes[0].data)\n\t\t\t\tpool.append(pool_stat)\n\t\t\tminer.append(dev)\n\t\t\tminer.append(pool)\n\t\t\ttry:\n\t\t\t\tminer.append(minerXML.getElementsByTagName(\"MHS15min\")[0].childNodes[0].data)\n\t\t\texcept:\n\t\t\t\tminer.append('0')\n\t\t\tmminer.append(miner)\n\t\tdata.append(mminer)\n\n\treturn (data,time)\n\nif __name__ == '__main__':\n\tlogdir = './log/'\n\tlogname = 'log-example.xml'\n\t(data,time) = readlog(logdir,logname)\n\n\tfor miner in data:\n\t\tprint(miner[0] + ': ' + miner[1] + ' ' + miner[2] + ' ' + miner[3])\n\t\ti = 1\n\t\tfor dev_stat in miner[4]:\n\t\t\tprint('\\tModule #' + str(i) + ':')\n\t\t\tprint('\\t\\tDevice Elapsed: ' + dev_stat[0])\n\t\t\tprint('\\t\\tTotal MH: ' + dev_stat[1])\n\t\t\tprint('\\t\\tTemperature: ' + dev_stat[2])\n\t\t\tprint('\\t\\tModules Number: ' + str(dev_stat[3]))\n\t\t\tprint('\\t\\tTemperature List: ' + ','.join(dev_stat[4]))\n\t\t\tprint('\\t\\tFan Speed List: ' + ','.join(dev_stat[5]))\n\t\t\ti += 1\n\n\t\ti = 1\n\t\tfor pool_stat in miner[5]:\n\t\t\tprint('\\tPool #' + str(i) + ':')\n\t\t\tprint('\\t\\tURL: ' + pool_stat[0])\n\t\t\tprint('\\t\\tStatus: ' + pool_stat[1])\n\t\t\ti += 1\n\t\tprint(\"------------------------------------------------------------------------------\")\n\n","sub_path":"farm-manager/status-report/statlogging.py","file_name":"statlogging.py","file_ext":"py","file_size_in_byte":4758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"129614000","text":"import re\n\nimport fasttext\nimport numpy as np\nfrom modin import pandas as pd\nfrom bs4 import BeautifulSoup\nimport ray\n\nray.init()\n\nPRETRAINED_MODEL_PATH = 'lid.176.bin'\nmodel = fasttext.load_model(PRETRAINED_MODEL_PATH)\n\n\ndef clean_data(elem):\n if not isinstance(elem, str):\n return np.nan\n elem = BeautifulSoup(elem, \"lxml\").text\n sub = re.compile(r\"\\\\\")\n elem = re.sub(sub, '', elem)\n pred = model.predict(elem.lower())\n language = pred[0][0].replace('__label__', '')\n if language != 'en':\n return np.nan\n return elem\n\n\nchunk = 0\nfor df in pd.read_csv('amazon_reviews_us_Books_v1_02.tsv', delimiter='\\t', error_bad_lines=False, chunksize=50000):\n df['review_body'] = [clean_data(x) for x in df['review_body']]\n df.dropna(axis=0, inplace=True)\n df.reset_index(drop=True, inplace=True)\n df.to_csv('books_v1_02_cleaned_{}.csv'.format(chunk))\n chunk += 1\n","sub_path":"clean_dataset.py","file_name":"clean_dataset.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"427970233","text":"old_str = '男'\nnew_str = '女'\nf_name = '员工表.txt'\n\nf= open(file= f_name, mode= 'r+', encoding= 'utf-8')\n#print(f.read())很愚蠢的写法,每次调用f.read()都会导致文件光标往后移动\nf_read = f.read()\n\n#第一种方法 :f.seek(0)\n#注意:这种方法有缺陷,如果内存内容比原文本文件少,会有覆盖不了的地方\nf.seek(0)\n\n#第二种方法:注意,从当前光标位置开始往后截断\nf.seek(0)\nf.truncate()\nf.flush()\n\nf_read = f_read.replace(old_str, new_str)\nf.write(f_read)\nf.close()\n\n\n","sub_path":"OldBoy/old/day21/文件修改/占内存修改/占内存修改.py","file_name":"占内存修改.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"181613304","text":"import math\nfrom copy import deepcopy\nfrom pathlib import Path\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom .common import Conv, DWConv\n\nthop = None\n\n\ndef fuse_conv_and_bn(conv, bn):\n # Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/\n fusedconv = (\n nn.Conv2d(\n conv.in_channels,\n conv.out_channels,\n kernel_size=conv.kernel_size,\n stride=conv.stride,\n padding=conv.padding,\n groups=conv.groups,\n bias=True,\n )\n .requires_grad_(False)\n .to(conv.weight.device)\n )\n\n # prepare filters\n w_conv = conv.weight.clone().view(conv.out_channels, -1)\n w_bn = torch.diag(\n bn.weight.div(torch.sqrt(bn.eps + bn.running_var))\n )\n fusedconv.weight.copy_(\n torch.mm(w_bn, w_conv).view(fusedconv.weight.shape)\n )\n\n # prepare spatial bias\n b_conv = (\n torch.zeros(conv.weight.size(0), device=conv.weight.device)\n if conv.bias is None\n else conv.bias\n )\n b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(\n torch.sqrt(bn.running_var + bn.eps)\n )\n fusedconv.bias.copy_(\n torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn\n )\n\n return fusedconv\n\n\ndef model_info(model, verbose=False, img_size=640):\n # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320]\n n_p = sum(\n x.numel() for x in model.parameters()\n ) # number parameters\n n_g = sum(\n x.numel() for x in model.parameters() if x.requires_grad\n ) # number gradients\n\n try: # FLOPs\n from thop import profile\n\n stride = (\n max(int(model.stride.max()), 32)\n if hasattr(model, \"stride\")\n else 32\n )\n img = torch.zeros(\n (1, model.yaml.get(\"ch\", 3), stride, stride),\n device=next(model.parameters()).device,\n ) # input\n flops = (\n profile(deepcopy(model), inputs=(img,), verbose=False)[0]\n / 1e9\n * 2\n ) # stride GFLOPs\n img_size = (\n img_size\n if isinstance(img_size, list)\n else [img_size, img_size]\n ) # expand if int/float\n fs = \", %.1f GFLOPs\" % (\n flops * img_size[0] / stride * img_size[1] / stride\n ) # 640x640 GFLOPs\n except (ImportError, Exception):\n fs = \"\"\n\n\nclass Detect(nn.Module):\n stride = None # strides computed during build\n onnx_dynamic = False # ONNX export parameter\n\n def __init__(\n self, nc=80, anchors=(), ch=(), inplace=True\n ): # detection layer\n super().__init__()\n self.nc = nc # number of classes\n self.no = nc + 5 # number of outputs per anchor\n self.nl = len(anchors) # number of detection layers\n self.na = len(anchors[0]) // 2 # number of anchors\n self.grid = [torch.zeros(1)] * self.nl # init grid\n a = torch.tensor(anchors).float().view(self.nl, -1, 2)\n self.register_buffer(\"anchors\", a) # shape(nl,na,2)\n self.register_buffer(\n \"anchor_grid\", a.clone().view(self.nl, 1, -1, 1, 1, 2)\n ) # shape(nl,1,na,1,1,2)\n self.m = nn.ModuleList(\n nn.Conv2d(x, self.no * self.na, 1) for x in ch\n ) # output conv\n self.inplace = (\n inplace # use in-place ops (e.g. slice assignment)\n )\n\n def forward(self, x):\n z = [] # inference output\n for i in range(self.nl):\n x[i] = self.m[i](x[i]) # conv\n bs, _, ny, nx = x[\n i\n ].shape # x(bs,255,20,20) to x(bs,3,20,20,85)\n x[i] = (\n x[i]\n .view(bs, self.na, self.no, ny, nx)\n .permute(0, 1, 3, 4, 2)\n .contiguous()\n )\n\n if not self.training: # inference\n if (\n self.grid[i].shape[2:4] != x[i].shape[2:4]\n or self.onnx_dynamic\n ):\n self.grid[i] = self._make_grid(nx, ny).to(\n x[i].device\n )\n\n y = x[i].sigmoid()\n if self.inplace:\n y[..., 0:2] = (\n y[..., 0:2] * 2.0 - 0.5 + self.grid[i]\n ) * self.stride[\n i\n ] # xy\n y[..., 2:4] = (\n y[..., 2:4] * 2\n ) ** 2 * self.anchor_grid[\n i\n ] # wh\n else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953\n xy = (\n y[..., 0:2] * 2.0 - 0.5 + self.grid[i]\n ) * self.stride[\n i\n ] # xy\n wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[\n i\n ].view(\n 1, self.na, 1, 1, 2\n ) # wh\n y = torch.cat((xy, wh, y[..., 4:]), -1)\n z.append(y.view(bs, -1, self.no))\n\n return x if self.training else (torch.cat(z, 1), x)\n\n @staticmethod\n def _make_grid(nx=20, ny=20):\n yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])\n return (\n torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()\n )\n\n\nclass Model(nn.Module):\n def __init__(\n self, cfg=\"yolov5s.yaml\", ch=3, nc=None, anchors=None\n ): # model, input channels, number of classes\n super().__init__()\n if isinstance(cfg, dict):\n self.yaml = cfg # model dict\n else: # is *.yaml\n import yaml # for torch hub\n\n self.yaml_file = Path(cfg).name\n with open(cfg) as f:\n self.yaml = yaml.safe_load(f) # model dict\n\n # Define model\n ch = self.yaml[\"ch\"] = self.yaml.get(\n \"ch\", ch\n ) # input channels\n if nc and nc != self.yaml[\"nc\"]:\n self.yaml[\"nc\"] = nc # override yaml value\n if anchors:\n self.yaml[\"anchors\"] = round(\n anchors\n ) # override yaml value\n self.model, self.save = parse_model(\n deepcopy(self.yaml), ch=[ch]\n ) # model, savelist\n self.names = [\n str(i) for i in range(self.yaml[\"nc\"])\n ] # default names\n self.inplace = self.yaml.get(\"inplace\", True)\n\n # Build strides, anchors\n m = self.model[-1] # Detect()\n if isinstance(m, Detect):\n s = 256 # 2x min stride\n m.inplace = self.inplace\n m.stride = torch.tensor(\n [\n s / x.shape[-2]\n for x in self.forward(torch.zeros(1, ch, s, s))\n ]\n ) # forward\n m.anchors /= m.stride.view(-1, 1, 1)\n check_anchor_order(m)\n self.stride = m.stride\n self._initialize_biases() # only run once\n\n # Init weights, biases\n initialize_weights(self)\n self.info()\n\n def forward(\n self, x, augment=False, profile=False, visualize=False\n ):\n if augment:\n return self.forward_augment(\n x\n ) # augmented inference, None\n return self.forward_once(\n x, profile, visualize\n ) # single-scale inference, train\n\n def forward_augment(self, x):\n img_size = x.shape[-2:] # height, width\n s = [1, 0.83, 0.67] # scales\n f = [None, 3, None] # flips (2-ud, 3-lr)\n y = [] # outputs\n for si, fi in zip(s, f):\n xi = scale_img(\n x.flip(fi) if fi else x, si, gs=int(self.stride.max())\n )\n yi = self.forward_once(xi)[0] # forward\n # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save\n yi = self._descale_pred(yi, fi, si, img_size)\n y.append(yi)\n return torch.cat(y, 1), None # augmented inference, train\n\n def forward_once(self, x, profile=False, visualize=False):\n y, dt = [], [] # outputs\n for m in self.model:\n if m.f != -1: # if not from previous layer\n x = (\n y[m.f]\n if isinstance(m.f, int)\n else [x if j == -1 else y[j] for j in m.f]\n ) # from earlier layers\n\n if profile:\n c = isinstance(m, Detect) # copy input as inplace fix\n o = (\n thop.profile(\n m,\n inputs=(x.copy() if c else x,),\n verbose=False,\n )[0]\n / 1e9\n * 2\n if thop\n else 0\n ) # FLOPs\n t = time_sync()\n for _ in range(10):\n m(x.copy() if c else x)\n dt.append((time_sync() - t) * 100)\n\n x = m(x) # run\n y.append(x if m.i in self.save else None) # save output\n\n if visualize:\n feature_visualization(\n x, m.type, m.i, save_dir=visualize\n )\n\n return x\n\n def _descale_pred(self, p, flips, scale, img_size):\n # de-scale predictions following augmented inference (inverse operation)\n if self.inplace:\n p[..., :4] /= scale # de-scale\n if flips == 2:\n p[..., 1] = img_size[0] - p[..., 1] # de-flip ud\n elif flips == 3:\n p[..., 0] = img_size[1] - p[..., 0] # de-flip lr\n else:\n x, y, wh = (\n p[..., 0:1] / scale,\n p[..., 1:2] / scale,\n p[..., 2:4] / scale,\n ) # de-scale\n if flips == 2:\n y = img_size[0] - y # de-flip ud\n elif flips == 3:\n x = img_size[1] - x # de-flip lr\n p = torch.cat((x, y, wh, p[..., 4:]), -1)\n return p\n\n def _initialize_biases(\n self, cf=None\n ): # initialize biases into Detect(), cf is class frequency\n # https://arxiv.org/abs/1708.02002 section 3.3\n # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.\n m = self.model[-1] # Detect() module\n for mi, s in zip(m.m, m.stride): # from\n b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)\n b.data[:, 4] += math.log(\n 8 / (640 / s) ** 2\n ) # obj (8 objects per 640 image)\n b.data[:, 5:] += (\n math.log(0.6 / (m.nc - 0.99))\n if cf is None\n else torch.log(cf / cf.sum())\n ) # cls\n mi.bias = torch.nn.Parameter(\n b.view(-1), requires_grad=True\n )\n\n def _print_biases(self):\n m = self.model[-1] # Detect() module\n for mi in m.m: # from\n b = (\n mi.bias.detach().view(m.na, -1).T\n ) # conv.bias(255) to (3,85)\n\n def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers\n\n for m in self.model.modules():\n if isinstance(m, (Conv, DWConv)) and hasattr(m, \"bn\"):\n m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv\n delattr(m, \"bn\") # remove batchnorm\n m.forward = m.forward_fuse # update forward\n self.info()\n return self\n\n def autoshape(self): # add AutoShape module\n m = AutoShape(self) # wrap model\n copy_attr(\n m,\n self,\n include=(\"yaml\", \"nc\", \"hyp\", \"names\", \"stride\"),\n exclude=(),\n ) # copy attributes\n return m\n\n def info(\n self, verbose=False, img_size=640\n ): # print model information\n model_info(self, verbose, img_size)\n","sub_path":"src/vtccvision/models/yolov5/_models/yolo.py","file_name":"yolo.py","file_ext":"py","file_size_in_byte":12111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"333302943","text":"import os\nfrom os import walk\n\n\n# (1) Identifier tag to add at beginning of files\n# (make it \"\" if you don't want identifiers in front of file names)\ntag = \"IRL2\"\n\n# (2) Path to the files -- their original location\nogPath = \"/home/bymyself/Pictures/Pictures2021/temp\"\n\nfileList = []\nfor (dirpath, dirnames, filenames) in walk(ogPath):\n fileList.extend(filenames)\n break\n\n# (3) Choose Mode\nmode = input(\"[p]icture or [v]ideo wallpaper?\\n\").lower()\nif \"p\" not in mode:\n import subprocess\n\n\n \nfileNumberIdentifier = 1\nfor fName in fileList:\n \n # The Wallpaper Folder being Put in System/Resources\n codeLength = 0\n if \".\" in str(fName):\n nameParts = fName.split(\".\")\n codeLength = len(nameParts[len(nameParts)-1])\n nameNoCode = str(fName)[:(-1 * codeLength)]\n folder = tag + \"_\" + str(fileNumberIdentifier) + \"_\" + nameNoCode\n folder = folder.replace(\" \", \"\")\n illegalCharacters = [\"#\", \"%\", \"&\", \"{\", \"}\", \"\\\\\", \"<\", \">\", \"*\", \"?\", \"/\", \"$\", \"ノ\",\\\n \"!\", \"'\", '\"', \":\", \"@\", \"+\", \"~\", \"`\", \"|\", \"=\", \"(\", \")\", \".\", \"-\"]\n for character in illegalCharacters:\n if character in folder:\n folder = folder.replace(character, \"_\")\n os.system(\"mkdir \" + folder)\n \n # Config File\n cFileChoice = \"configVideo\"\n if \"p\" in mode:\n cFileChoice = \"configPicture\"\n config = open(cFileChoice, \"r\")\n lines = config.readlines()\n if \"p\" not in mode:\n lines[2] = \"VideoFileName=\" + str(fName) + \"\\n\"\n cLocation = folder + \"/\" + \"config\"\n newConfig = open(cLocation, \"w\")\n for _ in lines:\n newConfig.write(_.strip(\"\\n\") + \"\\n\")\n newConfig.close()\n\n # Copy Original Picture/Video to New BG Folder\n initialLoc = ogPath + \"/\" + \"'\" + str(fName) + \"'\"\n os.system(\"cp \" + initialLoc + \" \" + folder)\n \n # For Videos: Generate Thumbnail\n if \"p\" not in mode:\n tempName = \"aaaaaaaaaaaaaaa\"\n while tempName in fileList:\n tempName += \"z\"\n tempName += \".\" + str(nameParts[len(nameParts)-1])\n tempName = tempName.replace(\" \",\"\")\n tempCreateCmd = \"mv \" + folder + \"/\" + \"'\" + fName + \"'\" + \" \" + folder + \"/\" + tempName\n os.system(tempCreateCmd)\n video_input_path = folder + \"/\" + tempName\n img_output_path = folder + \"/wallpaper.jpg\"\n subprocess.call(['ffmpeg', '-i', video_input_path, '-ss', '00:00:05.000', '-vframes', '1', img_output_path])\n backToOgName = \"mv \" + video_input_path + \" \" + folder + \"/\" + \"'\" + fName + \"'\"\n os.system(backToOgName)\n \n # For Pictures: Rename img file to 'wallpaper.jpg' (required)\n if \"p\" in mode:\n locPic = folder + \"/\" + \"'\" + fName + \"'\"\n filecode = \"jpg\"\n possibleFilecodes = [\"jpg\", \"png\", \"tif\", \"raw\", \"eps\", \"gif\", \"psd\", \"xcf\", \\\n \"ai\", \"cdr\", \"bmp\", \"jpeg\", \"cr2\", \"nef\", \"orf\", \\\n \"sr2\", \"jpe\", \"jif\", \"jfif\", \"jfi\", \"webp\", \"k25\", \\\n \"nrw\", \"arw\", \"dib\", \"heif\", \"heic\", \"ind\", \"indd\", \\\n \"indt\", \"jp2\", \"j2k\", \"jpf\", \"jpx\", \"jpm\", \"mj2\", \\\n \"svg\", \"svgz\"]\n for code in possibleFilecodes: \n if code in str(fName)[-5:]:\n filecode = code\n if str(fName)[-3:] not in possibleFilecodes and str(fName)[-4:] not in possibleFilecodes and str(fName)[-5:] not in possibleFilecodes:\n print(\"can't get file type/code in original file for: \" + str(fName))\n print(\"Make sure it is a picture file\")\n quit()\n newName = folder + \"/\" + \"wallpaper.\" + filecode\n renamePicCommand = \"mv \" + locPic + \" \" + newName\n os.system(renamePicCommand)\n \n # Move to Resources System Folder (make sure sudo password check is not enabled)\n mvToSystemCommand = \"sudo mv \" + folder + \" /System/Resources/Komorebi\"\n os.system(mvToSystemCommand)\n \n fileNumberIdentifier+=1\n \n ### Uncomment to Delete Original Files\n # os.systemm(\"sudo rm \" + initialLoc)\n \n\n###\n### Deleting Folders in System/Resources incase of mistake\n### (1) comment out the stuff above EXCEPT the variables \"tag\" and \"ogPath\"\n### (2) un-comment the stuff below then run\n###\n\n# folderID = 1\n# for i in fileList\n# folder_name_del = tag + \"_\" + str(folderID) + \"_*\"\n# deleteCommand = \"sudo rm -r /System/Resources/Komorebi/\" + folder_name_del\n# os.system(deleteCommand)\n# folderID += 1\n\n# Delete all quickly: \"sudo rm -r $TAGNAME$*\"\n","sub_path":"automation-scripts/p/komo_video_wallpaper_batch/komo.py","file_name":"komo.py","file_ext":"py","file_size_in_byte":4552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"243344944","text":"#args - arguments , ** \n\ndef add(a,b):\n return a + b\n \ndef new_add(*args):\n # 1,2,3,4\n # (1,2,3,4), # ([])\n #gathers data as tuple\n total = 0\n for num in args:\n total += num\n return total \n \n \nprint(new_add(1,2,3))\n\n#good practice \nl = (1,2,3,4) # or l = [1,2,3,4]\nprint(new_add(*l))\n \n#kwargs - keyword arguments , ** \ndef func(**kwargs):\n # { 'name':'Imad Beyg', 'age':28 }\n # gather data as dictionary\n print(kwargs) \n print(type(kwargs))\n \nfunc(name = 'Imad', age = 28)\n \n# kwargs , args , normal , default \n# PADK - paramter , args , default , kwargs \n \ndef func2(name, *args, last_name = 'unknown', **kwargs):\n print(name)\n print(args)\n print(last_name)\n print(kwargs)\n \nfunc2('Imad', 1,2,3, last_name = 'Beyg',a = 1, b = 2)","sub_path":"detailed-exercises/78-args-kwargs.py","file_name":"78-args-kwargs.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"612099813","text":"import unittest\nfrom test_classpkg.basePageBaidu import BaiduPage\nfrom time import sleep\nfrom selenium import webdriver\nfrom ddt import ddt,data,unpack\n\n#课题1,数据参数化----》通过\n#课题2,运行控制器控制案例顺序,案例获取从多个目录\n#课题3,用例报错了需要继续执行-------》断言失败了,是正常执行得\n#问题4,为何断言不匹配,案例失败了,但是生成得测试报告是通过得---》执行文件和当前文件不匹配导致\n@ddt\nclass TestBaiduPage(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.driver = webdriver.Chrome()\n\n @classmethod\n def tearDownClass(cls):\n cls.driver.quit()\n\n @data({\"search_key\":\"selenium\"}, {\"search_key\": \"ddt\"},{\"search_key\":\"unittest\"})\n @unpack\n def test_baiduPage_case(self,search_key):\n page = BaiduPage(self.driver)\n #page.open(\"https://www.baidu.com\")\n page.open()\n '''方法一:自定义方法元素定位\n page.search_input(search_key)\n page.search_button()\n '''\n '''方法二:poium方法元素定位'''\n page.search_input = search_key\n page.search_button.click()\n\n sleep(2)\n self.assertEqual(page.get_title(),search_key+\"_百度搜索\")\n print(page.get_title())\n\n\nif __name__ == \"__main__\":\n unittest.main(verbosity=2)\n\n","sub_path":"test_case/test_baiduPage.py","file_name":"test_baiduPage.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"165876465","text":"\"\"\"\nMask R-CNN\nConfigurations and data loading code for MS COCO.\n\nCopyright (c) 2017 Matterport, Inc.\nLicensed under the MIT License (see LICENSE for details)\nWritten by Waleed Abdulla\n\n------------------------------------------------------------\n\nUsage: import the module (see Jupyter notebooks for examples), or run from\n the command line as such:\n\n # Train a new model starting from pre-trained COCO weights\n python3 coco.py train --dataset=/path/to/coco/ --model=coco\n\n # Train a new model starting from ImageNet weights. Also auto download COCO dataset\n python3 coco.py train --dataset=/path/to/coco/ --model=imagenet --download=True\n\n # Continue training a model that you had trained earlier\n python3 coco.py train --dataset=/path/to/coco/ --model=/path/to/weights.h5\n\n # Continue training the last model you trained\n python3 coco.py train --dataset=/path/to/coco/ --model=last\n\n # Run COCO evaluatoin on the last model you trained\n python3 coco.py evaluate --dataset=/path/to/coco/ --model=last\n\"\"\"\n\nimport os\nimport sys\nimport time\nimport numpy as np\nimport urllib\nimport shutil\nimport zipfile\n\n# Download and install the Python COCO tools from https://github.com/waleedka/coco\n# That's a fork from the original https://github.com/pdollar/coco with a bug\n# fix for Python 3.\n# I submitted a pull request https://github.com/cocodataset/cocoapi/pull/50\n# If the PR is merged then use the original repo.\n# Note: Edit PythonAPI/Makefile and replace \"python\" with \"python3\".\nfrom pycocotools.coco import COCO\nfrom pycocotools.cocoeval import COCOeval\nfrom pycocotools import mask as maskUtils\n\nDEFAULT_DATASET_YEAR = \"2014\"\n\n############################################################\n# Dataset\n############################################################\n\nclass Dataset(object):\n \"\"\"The base class for dataset classes.\n To use it, create a new class that adds functions specific to the dataset\n you want to use. For example:\n\n class CatsAndDogsDataset(Dataset):\n def load_cats_and_dogs(self):\n ...\n def load_mask(self, image_id):\n ...\n def image_reference(self, image_id):\n ...\n\n See COCODataset and ShapesDataset as examples.\n \"\"\"\n\n def __init__(self, class_map=None):\n self._image_ids = []\n self.image_info = []\n # Background is always the first class\n self.class_info = [{\"source\": \"\", \"id\": 0, \"name\": \"BG\"}]\n self.source_class_ids = {}\n\n def add_class(self, source, class_id, class_name):\n assert \".\" not in source, \"Source name cannot contain a dot\"\n # Does the class exist already?\n for info in self.class_info:\n if info['source'] == source and info[\"id\"] == class_id:\n # source.class_id combination already available, skip\n return\n # Add the class\n self.class_info.append({\n \"source\": source,\n \"id\": class_id,\n \"name\": class_name,\n })\n\n def add_image(self, source, image_id, path, **kwargs):\n image_info = {\n \"id\": image_id,\n \"source\": source,\n \"path\": path,\n }\n image_info.update(kwargs)\n self.image_info.append(image_info)\n\n def image_reference(self, image_id):\n \"\"\"Return a link to the image in its source Website or details about\n the image that help looking it up or debugging it.\n\n Override for your dataset, but pass to this function\n if you encounter images not in your dataset.\n \"\"\"\n return \"\"\n\n def prepare(self, class_map=None):\n \"\"\"Prepares the Dataset class for use.\n\n TODO: class map is not supported yet. When done, it should handle mapping\n classes from different datasets to the same class ID.\n \"\"\"\n\n def clean_name(name):\n \"\"\"Returns a shorter version of object names for cleaner display.\"\"\"\n return \",\".join(name.split(\",\")[:1])\n\n # Build (or rebuild) everything else from the info dicts.\n self.num_classes = len(self.class_info)\n self.class_ids = np.arange(self.num_classes)\n self.class_names = [clean_name(c[\"name\"]) for c in self.class_info]\n self.num_images = len(self.image_info)\n self._image_ids = np.arange(self.num_images)\n\n # Mapping from source class and image IDs to internal IDs\n self.class_from_source_map = {\"{}.{}\".format(info['source'], info['id']): id\n for info, id in zip(self.class_info, self.class_ids)}\n self.image_from_source_map = {\"{}.{}\".format(info['source'], info['id']): id\n for info, id in zip(self.image_info, self.image_ids)}\n\n # Map sources to class_ids they support\n self.sources = list(set([i['source'] for i in self.class_info]))\n self.source_class_ids = {}\n # Loop over datasets\n for source in self.sources:\n self.source_class_ids[source] = []\n # Find classes that belong to this dataset\n for i, info in enumerate(self.class_info):\n # Include BG class in all datasets\n if i == 0 or source == info['source']:\n self.source_class_ids[source].append(i)\n\n def map_source_class_id(self, source_class_id):\n \"\"\"Takes a source class ID and returns the int class ID assigned to it.\n\n For example:\n dataset.map_source_class_id(\"coco.12\") -> 23\n \"\"\"\n return self.class_from_source_map[source_class_id]\n\n def get_source_class_id(self, class_id, source):\n \"\"\"Map an internal class ID to the corresponding class ID in the source dataset.\"\"\"\n info = self.class_info[class_id]\n assert info['source'] == source\n return info['id']\n\n def append_data(self, class_info, image_info):\n self.external_to_class_id = {}\n for i, c in enumerate(self.class_info):\n for ds, id in c[\"map\"]:\n self.external_to_class_id[ds + str(id)] = i\n\n # Map external image IDs to internal ones.\n self.external_to_image_id = {}\n for i, info in enumerate(self.image_info):\n self.external_to_image_id[info[\"ds\"] + str(info[\"id\"])] = i\n\n @property\n def image_ids(self):\n return self._image_ids\n\n def source_image_link(self, image_id):\n \"\"\"Returns the path or URL to the image.\n Override this to return a URL to the image if it's availble online for easy\n debugging.\n \"\"\"\n return self.image_info[image_id][\"path\"]\n\nclass CocoDataset(Dataset):\n def load_coco(self, dataset_dir, subset, year=DEFAULT_DATASET_YEAR, class_ids=None,\n class_map=None, return_coco=False, auto_download=False):\n \"\"\"Load a subset of the COCO dataset.\n dataset_dir: The root directory of the COCO dataset.\n subset: What to load (train, val, minival, valminusminival)\n year: What dataset year to load (2014, 2017) as a string, not an integer\n class_ids: If provided, only loads images that have the given classes.\n class_map: TODO: Not implemented yet. Supports maping classes from\n different datasets to the same class ID.\n return_coco: If True, returns the COCO object.\n auto_download: Automatically download and unzip MS-COCO images and annotations\n \"\"\"\n\n if auto_download is True:\n self.auto_download(dataset_dir, subset, year)\n\n coco = COCO(\"{}/annotations/instances_{}{}.json\".format(dataset_dir, subset, year))\n if subset == \"minival\" or subset == \"valminusminival\":\n subset = \"val\"\n image_dir = \"{}/{}{}\".format(dataset_dir, subset, year)\n\n # Load all classes or a subset?\n if not class_ids:\n # All classes\n class_ids = sorted(coco.getCatIds())\n\n # All images or a subset?\n if class_ids:\n image_ids = []\n for id in class_ids:\n image_ids.extend(list(coco.getImgIds(catIds=[id])))\n # Remove duplicates\n image_ids = list(set(image_ids))\n else:\n # All images\n image_ids = list(coco.imgs.keys())\n\n # Add classes\n for i in class_ids:\n self.add_class(\"coco\", i, coco.loadCats(i)[0][\"name\"])\n\n # Add images\n for i in image_ids:\n self.add_image(\n \"coco\", image_id=i,\n path=os.path.join(image_dir, coco.imgs[i]['file_name']),\n width=coco.imgs[i][\"width\"],\n height=coco.imgs[i][\"height\"],\n annotations=coco.loadAnns(coco.getAnnIds(\n imgIds=[i], catIds=class_ids, iscrowd=None)))\n if return_coco:\n return coco\n\n def auto_download(self, dataDir, dataType, dataYear):\n \"\"\"Download the COCO dataset/annotations if requested.\n dataDir: The root directory of the COCO dataset.\n dataType: What to load (train, val, minival, valminusminival)\n dataYear: What dataset year to load (2014, 2017) as a string, not an integer\n Note:\n For 2014, use \"train\", \"val\", \"minival\", or \"valminusminival\"\n For 2017, only \"train\" and \"val\" annotations are available\n \"\"\"\n\n # Setup paths and file names\n if dataType == \"minival\" or dataType == \"valminusminival\":\n imgDir = \"{}/{}{}\".format(dataDir, \"val\", dataYear)\n imgZipFile = \"{}/{}{}.zip\".format(dataDir, \"val\", dataYear)\n imgURL = \"http://images.cocodataset.org/zips/{}{}.zip\".format(\"val\", dataYear)\n else:\n imgDir = \"{}/{}{}\".format(dataDir, dataType, dataYear)\n imgZipFile = \"{}/{}{}.zip\".format(dataDir, dataType, dataYear)\n imgURL = \"http://images.cocodataset.org/zips/{}{}.zip\".format(dataType, dataYear)\n # print(\"Image paths:\"); print(imgDir); print(imgZipFile); print(imgURL)\n\n # Create main folder if it doesn't exist yet\n if not os.path.exists(dataDir):\n os.makedirs(dataDir)\n\n # Download images if not available locally\n if not os.path.exists(imgDir):\n os.makedirs(imgDir)\n print(\"Downloading images to \" + imgZipFile + \" ...\")\n with urllib.request.urlopen(imgURL) as resp, open(imgZipFile, 'wb') as out:\n shutil.copyfileobj(resp, out)\n print(\"... done downloading.\")\n print(\"Unzipping \" + imgZipFile)\n with zipfile.ZipFile(imgZipFile, \"r\") as zip_ref:\n zip_ref.extractall(dataDir)\n print(\"... done unzipping\")\n print(\"Will use images in \" + imgDir)\n\n # Setup annotations data paths\n annDir = \"{}/annotations\".format(dataDir)\n if dataType == \"minival\":\n annZipFile = \"{}/instances_minival2014.json.zip\".format(dataDir)\n annFile = \"{}/instances_minival2014.json\".format(annDir)\n annURL = \"https://dl.dropboxusercontent.com/s/o43o90bna78omob/instances_minival2014.json.zip?dl=0\"\n unZipDir = annDir\n elif dataType == \"valminusminival\":\n annZipFile = \"{}/instances_valminusminival2014.json.zip\".format(dataDir)\n annFile = \"{}/instances_valminusminival2014.json\".format(annDir)\n annURL = \"https://dl.dropboxusercontent.com/s/s3tw5zcg7395368/instances_valminusminival2014.json.zip?dl=0\"\n unZipDir = annDir\n else:\n annZipFile = \"{}/annotations_trainval{}.zip\".format(dataDir, dataYear)\n annFile = \"{}/instances_{}{}.json\".format(annDir, dataType, dataYear)\n annURL = \"http://images.cocodataset.org/annotations/annotations_trainval{}.zip\".format(dataYear)\n unZipDir = dataDir\n # print(\"Annotations paths:\"); print(annDir); print(annFile); print(annZipFile); print(annURL)\n\n # Download annotations if not available locally\n if not os.path.exists(annDir):\n os.makedirs(annDir)\n if not os.path.exists(annFile):\n if not os.path.exists(annZipFile):\n print(\"Downloading zipped annotations to \" + annZipFile + \" ...\")\n with urllib.request.urlopen(annURL) as resp, open(annZipFile, 'wb') as out:\n shutil.copyfileobj(resp, out)\n print(\"... done downloading.\")\n print(\"Unzipping \" + annZipFile)\n with zipfile.ZipFile(annZipFile, \"r\") as zip_ref:\n zip_ref.extractall(unZipDir)\n print(\"... done unzipping\")\n print(\"Will use annotations in \" + annFile)\n\nif __name__ == '__main__':\n import argparse\n\n # Parse command line arguments\n parser = argparse.ArgumentParser(\n description='Download MS COCO dataset.')\n parser.add_argument('--dataset', required=True,\n metavar=\"/path/to/coco/\",\n help='Directory of the MS-COCO dataset')\n parser.add_argument('--year', required=False,\n default=DEFAULT_DATASET_YEAR,\n metavar=\"\",\n help='Year of the MS-COCO dataset (2014 or 2017) (default=2014)')\n args = parser.parse_args()\n\n # Training dataset. Use the training set and 35K from the\n # validation set, as as in the Mask RCNN paper.\n dataset_train = CocoDataset()\n dataset_train.load_coco(args.dataset, \"train\", year=args.year, auto_download=True)\n dataset_train.load_coco(args.dataset, \"valminusminival\", year=args.year, auto_download=True)\n\n # Validation dataset\n dataset_val = CocoDataset()\n dataset_val.load_coco(args.dataset, \"minival\", year=args.year, auto_download=True)\n","sub_path":"object_detection/data_download.py","file_name":"data_download.py","file_ext":"py","file_size_in_byte":13728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"380623442","text":"#!/usr/bin/python3\n\nimport sys\nimport argparse\nimport requests\nimport json\n\nfrom github import Github\nfrom packaging import version\nfrom packaging.version import parse as parse_version\n\n\nclass KernelUpdaterClient(Github):\n def __init__(self, account, branch, token=None):\n super().__init__(login_or_token=token)\n self.user = self.get_user(account)\n self.repo = self.user.get_repo('qubes-linux-kernel')\n self.branch = branch\n self.token = token\n\n def get_version_qubes(self):\n content = self.repo.get_contents('version', ref=self.branch)\n return content.decoded_content.decode('utf8').replace('\\n', '')\n\n def get_version_upstream(self):\n url_releases = 'https://www.kernel.org/releases.json'\n r = requests.get(url_releases)\n latest_upstream = None\n if 200 <= r.status_code < 300:\n content = json.loads(r.content.decode('utf-8'))\n releases = [rel['version'] for rel in content['releases'] if\n rel['moniker'] in ('stable', 'longterm')]\n\n releases.sort(key=parse_version, reverse=True)\n\n if 'stable-' in self.branch:\n branch_version = self.branch.split('-')[1]\n releases = [rel for rel in releases if\n rel.startswith(branch_version)]\n\n latest_upstream = releases[0]\n else:\n print('An error occurred while downloading \"%s\"' % url_releases)\n\n return latest_upstream\n\n def is_autopr_present(self, version):\n present = False\n for pr in list(self.repo.get_pulls()):\n if 'UPDATE: ' + version in pr.title:\n present = True\n break\n return present\n\n def is_update_needed(self):\n version_qubes = self.get_version_qubes()\n version_upstream = self.get_version_upstream()\n if version_qubes and version_upstream:\n if (not self.is_autopr_present(version_upstream)) and (\n version.parse(version_qubes) < version.parse(version_upstream)):\n return version_upstream\n\n def create_pullrequest(self, base, head):\n # example of head: 'fepitre:v4.19.30'\n parsed_head = head.split(':')\n if len(parsed_head) == 2:\n version = parsed_head[1].lstrip('update-v')\n else:\n print(\n 'An error occurred while parsing \"repo:branch\" from %s' % head)\n sys.exit(1)\n\n self.repo.create_pull(title=\"UPDATE: \" + version,\n body=\"Update to kernel-\" + version,\n base=base,\n head=head,\n maintainer_can_modify=True)\n\n\ndef parse_args(argv):\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--check-update', required=False, action='store_true')\n parser.add_argument('--create-pullrequest', required=False,\n action='store_true')\n parser.add_argument('--token', required=False)\n parser.add_argument('--base', required=True)\n parser.add_argument('--head', required=False)\n\n args = parser.parse_args(argv[1:])\n\n return args\n\n\ndef main(argv):\n args = parse_args(argv)\n token = None\n\n # Token is only needed for PR\n if args.token:\n try:\n with open(args.token, 'r') as f:\n token = f.read().replace('\\n', '')\n except IOError:\n print(\n \"An error occurred while reading token file '%s'\" % args.token)\n\n # example of args.base: 'fepitre:stable-4.19'\n parsed_base = args.base.split(':')\n if len(parsed_base) == 2:\n account = parsed_base[0]\n branch = parsed_base[1]\n else:\n print(\n 'An error occurred while parsing \"repo:branch\" from %s' % args.base)\n sys.exit(1)\n\n client = KernelUpdaterClient(account=account, branch=branch, token=token)\n\n if args.check_update:\n is_update_needed = client.is_update_needed()\n if is_update_needed is not None:\n print(is_update_needed)\n\n if args.create_pullrequest and args.base and args.head:\n client.create_pullrequest(branch, args.head)\n\n return 0\n\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv))\n","sub_path":"kernel-updater.py","file_name":"kernel-updater.py","file_ext":"py","file_size_in_byte":4286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"77627797","text":"import inspect\nfrom urllib.parse import urljoin\n\nfrom rest_framework import viewsets, views\nfrom rest_framework.schemas.generators import BaseSchemaGenerator\n\nfrom drf_spectacular.plumbing import (\n ComponentRegistry, warn, alpha_operation_sorter, reset_generator_stats, build_root_object\n)\nfrom drf_spectacular.settings import spectacular_settings\n\n\nclass SchemaGenerator(BaseSchemaGenerator):\n def __init__(self, *args, **kwargs):\n self.registry = ComponentRegistry()\n super().__init__(*args, **kwargs)\n\n def create_view(self, callback, method, request=None):\n \"\"\"\n customized create_view which is called when all routes are traversed. part of this\n is instantiating views with default params. in case of custom routes (@action) the\n custom AutoSchema is injected properly through 'initkwargs' on view. However, when\n decorating plain views like retrieve, this initialization logic is not running.\n Therefore forcefully set the schema if @extend_schema decorator was used.\n \"\"\"\n view = super().create_view(callback, method, request)\n\n if isinstance(view, viewsets.GenericViewSet) or isinstance(view, viewsets.ViewSet):\n action = getattr(view, view.action)\n elif isinstance(view, views.APIView):\n action = getattr(view, method.lower())\n else:\n warn(\n 'Using not supported View class. Class must be derived from APIView '\n 'or any of its subclasses like GenericApiView, GenericViewSet.'\n )\n return view\n\n # in case of @extend_schema, manually init custom schema class here due to\n # weakref reverse schema.view bug for multi annotations.\n schema = getattr(action, 'kwargs', {}).get('schema', None)\n if schema and inspect.isclass(schema):\n view.schema = schema()\n\n return view\n\n def get_endpoints(self, request):\n \"\"\" sorted endpoints by operation \"\"\"\n self._initialise_endpoints()\n _, endpoints = self._get_paths_and_endpoints(request)\n\n if spectacular_settings.OPERATION_SORTER == 'alpha':\n return sorted(endpoints, key=alpha_operation_sorter)\n else:\n # default to DRF method sorting\n return endpoints\n\n def parse(self, request=None):\n \"\"\" Iterate endpoints generating per method path operations. \"\"\"\n result = {}\n\n for path, method, view in self.get_endpoints(request):\n if not self.has_view_permissions(path, method, view):\n continue\n\n # beware that every access to schema yields a fresh object (descriptor pattern)\n operation = view.schema.get_operation(path, method, self.registry)\n\n # operation was manually removed via @extend_schema\n if not operation:\n continue\n\n # Normalise path for any provided mount url.\n if path.startswith('/'):\n path = path[1:]\n path = urljoin(self.url or '/', path)\n\n result.setdefault(path, {})\n result[path][method.lower()] = operation\n\n return result\n\n def get_schema(self, request=None, public=False):\n \"\"\" Generate a OpenAPI schema. \"\"\"\n reset_generator_stats()\n return build_root_object(\n paths=self.parse(None if public else request),\n components=self.registry.build(spectacular_settings.APPEND_COMPONENTS),\n )\n","sub_path":"drf_spectacular/generators.py","file_name":"generators.py","file_ext":"py","file_size_in_byte":3492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"20415711","text":"import math\n\ndef get_primes(num):\n primes = []\n for i in range(1,num+1):\n isPrime = True\n for p in primes:\n if i % p == 0:\n isPrime = False\n break\n if isPrime and i != 1:\n primes.append(i)\n return primes\n\n\nm = int(input())\nn = int(input())\nprimes_m = set(get_primes(m-1))\nprimes_n = set(get_primes(n))\nresult = primes_n - primes_m\nif len(result) == 0:\n print(-1)\nelse:\n print(sum(result))\n print(min(result))\n\ndef eratos(num):\n result = [True for _ in range(num+1)]\n for i in range(2, math.ceil(math.sqrt(num))):\n if result[i]:\n for j in range(i*2, num+1, i):\n result[j] = False\n return result\n\n\n\n\n","sub_path":"boj/python/2581.py","file_name":"2581.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"277598153","text":"from mock import Mock\nfrom ming.orm import ThreadLocalORMSession\n\nfrom allura.tests.unit import WithDatabase\nfrom allura.tests.unit.factories import create_post, create_discussion\nfrom allura import model\nfrom allura.controllers.discuss import ModerationController\nfrom allura.tests.unit import patches\n\n\nclass TestWhenModerating(WithDatabase):\n patches = [patches.fake_app_patch,\n patches.fake_redirect_patch,\n patches.fake_request_patch,\n patches.disable_notifications_patch]\n\n def setUp(self):\n super(TestWhenModerating, self).setUp()\n create_post('mypost')\n discussion_controller = Mock()\n self.controller = ModerationController(discussion_controller)\n\n def test_that_it_can_approve(self):\n self.moderate_post(approve=True)\n assert self.get_post().status == 'ok'\n\n def test_that_it_can_mark_as_spam(self):\n self.moderate_post(spam=True)\n assert self.get_post().status == 'spam'\n\n def test_that_it_can_be_deleted(self):\n self.moderate_post(delete=True)\n assert self.get_post() is None\n\n def moderate_post(self, **kwargs):\n self.controller.save_moderation(post=[dict(checked=True, full_slug=self.get_post().full_slug)],\n **kwargs)\n ThreadLocalORMSession.flush_all()\n\n def get_post(self):\n return model.Post.query.get(slug='mypost')\n\n\nclass TestIndexWithNoPosts(WithDatabase):\n patches = [patches.fake_app_patch]\n\n def test_that_it_returns_no_posts(self):\n discussion = create_discussion()\n template_variables = show_moderation_index(discussion)\n assert template_variables['posts'].all() == []\n\n\nclass TestIndexWithAPostInTheDiscussion(WithDatabase):\n patches = [patches.fake_app_patch]\n\n def setUp(self):\n super(TestIndexWithAPostInTheDiscussion, self).setUp()\n self.post = create_post('mypost')\n discussion = self.post.discussion\n self.template_variables = show_moderation_index(discussion)\n\n def test_that_it_returns_posts(self):\n assert self.template_variables['posts'].all() == [self.post]\n\n def test_that_it_sets_paging_metadata(self):\n assert self.template_variables['page'] == 0\n assert self.template_variables['limit'] == 50\n assert self.template_variables['pgnum'] == 1\n assert self.template_variables['pages'] == 1\n\n\ndef show_moderation_index(discussion, **kwargs_for_controller):\n discussion_controller = Mock()\n discussion_controller.discussion = discussion\n controller = ModerationController(discussion_controller)\n template_variables = controller.index(**kwargs_for_controller)\n return template_variables\n\n","sub_path":"Allura/allura/tests/unit/controllers/test_discussion_moderation_controller.py","file_name":"test_discussion_moderation_controller.py","file_ext":"py","file_size_in_byte":2725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"358930597","text":"import sys\nimport json\nimport re\nimport csv\nimport pandas as pd\nimport numpy as np\nimport pylab\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport scipy.sparse\n\n \ndef rms(y, predict):\n diff = [w1 - w2 for (w1,w2) in zip(y, predict)]\n return np.sqrt(np.mean([x**2 for x in diff])) \n \ndef main():\n training_directory = \"C:/Users/rthomas/Desktop/Kaggle/Sysrec/yelp_training_set\"\n business_train = pd.read_csv(training_directory + \"/yelp_training_set_business.csv\")\n user_train = pd.read_csv(training_directory + \"/yelp_training_set_user.csv\")\n checkin_train = pd.read_csv(training_directory + \"/yelp_training_set_checkin.csv\")\n review_train = pd.read_csv(training_directory + \"/yelp_training_set_review.csv\")\n test_directory = \"C:/Users/rthomas/Desktop/Kaggle/Sysrec/yelp_test_set\"\n business_test = pd.read_csv(test_directory + \"/yelp_test_set_business.csv\")\n user_test = pd.read_csv(test_directory + \"/yelp_test_set_user.csv\")\n checkin_test = pd.read_csv(test_directory + \"/yelp_test_set_checkin.csv\")\n review_test = pd.read_csv(test_directory + \"/yelp_test_set_review.csv\")\n review_test['order'] = review_test.index\n gender = pd.read_table(\"C:/Users/rthomas/Desktop/Kaggle/Sysrec/mf.txt\")\n\n business_all = pd.concat([business_train, business_test])\n review_all = pd.concat([review_train, review_test])\n user_all = pd.concat([user_train, user_test])\n user_all['name_upper'] = [n.upper() for n in user_all['name']]\n user_all = pd.merge(user_all, gender, how='left', left_on='name_upper', right_on='name')\n all_train = pd.merge(pd.merge(review_train, user_all, how='left', on=\"user_id\"),business_all, how='left', on=\"business_id\")\n review_test_ext = pd.merge(pd.merge(review_test, user_all, how='left', on='user_id'),business_all, how='left', on='business_id')\n review_test_ext.sort(['order'], inplace=True)\n \n # Averages by (business_id, gender) pairs\n groups = all_train.groupby(['business_id','mf'])\n group_counts = groups['user_id'].count()\n group_stars = groups['stars_x'].mean()\n bus_gen_dict = {group_stars.index[i]: group_stars[i] for i in range(len(group_stars))}\n count_dict = {group_counts.index[i]: group_counts[i] for i in range(len(group_counts))}\n \n # Averages for all male users and all female users\n groupsmf = all_train.groupby(['mf'])\n group_stars_mf = groupsmf['stars_x'].mean()\n \n datu2 = user_all['average_stars'].values\n avg_stars_all_u = np.mean(np.ma.masked_array(datu2,np.isnan(datu2)))\n datb2 = business_all['stars'].values\n avg_stars_all_b = np.mean(np.ma.masked_array(datb2,np.isnan(datb2)))\n\n test_pairs = [tuple(x) for x in review_test_ext[['user_id','business_id','average_stars','stars', 'mf']].values]\n\n with open('C:/Users/rthomas/Desktop/Kaggle/Sysrec/genderbenchmark2.csv', 'wb') as csvfile:\n mywriter = csv.writer(csvfile, delimiter=',', quotechar=' ', quoting=csv.QUOTE_MINIMAL)\n # for testing:\n #mywriter.writerow(['avg m', 'avg f', 'all u', 'all b'])\n #mywriter.writerow([group_stars_mf['m'], group_stars_mf['f'], avg_stars_all_b, avg_stars_all_u])\n #mywriter.writerow(['user_id', 'business_id', 'stars this u', 'stars this b', 'mf', 'stars', 'what'])\n mywriter.writerow(['user_id', 'business_id', 'stars'])\n for r in test_pairs:\n uid = r[0]\n bid = r[1]\n stars_this_u = r[2]\n stars_this_b = r[3]\n mf = r[4]\n # check if we can infer the user's gender\n if mf in ('m','f'):\n # check if there is an average rating by gender for this business (with at least 9 users having rated it)\n if (bid, mf) in bus_gen_dict.keys() and count_dict[(bid, mf)] > 8:\n stars = bus_gen_dict[(bid, mf)]\n what = 'bus_gen_dict'\n # check if there is an average rating for the business\n elif not np.isnan(stars_this_b):\n # check if there is an average rating for the user\n if not np.isnan(stars_this_u):\n stars = stars_this_b + (stars_this_u - group_stars_mf[mf])\n what = 'option 2'\n else:\n stars = stars_this_b\n what = 'option 3'\n # check if there is an average rating for this user\n elif not np.isnan(stars_this_u):\n stars = avg_stars_all_b + (stars_this_u - group_stars_mf[mf])\n what = 'option 4'\n # otherwise assign average rating for that gender\n else:\n stars = group_stars_mf[mf]\n what = 'option 5'\n else:\n # check if there is an average rating for the business\n if not np.isnan(stars_this_b):\n # check if there is an average rating for this user\n if not np.isnan(stars_this_u):\n stars = stars_this_b + (stars_this_u - avg_stars_all_u)\n what = 'option 6'\n else:\n stars = stars_this_b\n what = 'option 7'\n # check if there is an average rating for this user \n elif not np.isnan(stars_this_u):\n stars = avg_stars_all_b + (stars_this_u - avg_stars_all_u)\n what = 'option 8'\n else:\n stars = avg_stars_all_b\n what = 'option 9'\n stars = min(stars,5)\n stars = max(stars,1)\n mywriter.writerow([uid, bid, stars])\n # for testing\n #mywriter.writerow([uid, bid, stars_this_u, stars_this_b, mf, stars, what])\n \nif __name__ == '__main__':\n main()\n","sub_path":"ML/src/sysrec.py","file_name":"sysrec.py","file_ext":"py","file_size_in_byte":5871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"80978108","text":"from keras.models import Sequential\nfrom keras.layers import Dense\nimport numpy\nimport matplotlib.pyplot as plt\nimport math\nfrom pandas import read_csv\nfrom pandas import Series\nfrom sklearn.metrics import mean_squared_error\nfrom pandas import DataFrame\nfrom pandas import concat\nfrom keras.layers import LSTM\nfrom math import sqrt\nfrom sklearn.preprocessing import MinMaxScaler\nfrom keras.layers.core import Activation, Dropout\nfrom keras.models import load_model\nimport truefx as tfx\nimport time\n\nTRAIN_TO_TEST_RATIO = 0.67\nFORECAST_STEPS = 2\nCOLUMNS_TO_READ_FROM_INPUT = [7]\n#COLUMNS_TO_READ_FROM_INPUT = [0]\nNEURON_COUNT = 32\nEPOCH_COUNT = 600\n#INPUT_FILE = \"input\\\\test_2kolumny_14wierszy.txt\"\n#INPUT_FILE = \"input\\\\sinwave.csv\"\nINPUT_FILE = \"input\\\\EURUSD_1000.txt\"\n#INPUT_FILE = \"input\\\\EURUSD_10000.txt\"\n#INPUT_FILE = \"input\\\\EURUSD_max.txt\"\n#INPUT_FILE = \"input\\\\subsequentNumbers_200.txt\"\n#INPUT_FILE = \"input\\\\subsequentNumbers_30.txt\"\nFEATURE_COLUMNS = [0]\nTARGET_COLUMN = 0\nRANDOM_SEED = 7\nTIME_WINDOW_WIDTH = 30\nBATCH_SIZE = 100\nLOAD_LAST_MODEL = False\nLAST_MODEL_FILEPATH = \"lastModel\\\\model.hdf5\"\nCHECK_NAIVE_PREDICTION = False\nPLOT_NAIVE_PREDICTION = False\n\ndef loadInput():\n return read_csv(INPUT_FILE, header = None, usecols = COLUMNS_TO_READ_FROM_INPUT).values\n\ndef build_model(layers):\n model = Sequential()\n\n model.add(LSTM(\n input_dim=layers[0],\n output_dim=layers[1],\n return_sequences=True))\n model.add(Dropout(0.2))\n\n model.add(LSTM(\n layers[2],\n return_sequences=False))\n model.add(Dropout(0.2))\n\n model.add(Dense(\n output_dim=layers[3]))\n model.add(Activation(\"linear\"))\n\n model.compile(loss=\"mse\", optimizer=\"rmsprop\")\n\n return model\n\ndef computeNaivePredictions(rawInput):\n features = rawInput[:-FORECAST_STEPS, FEATURE_COLUMNS]\n\n targets = rawInput[FORECAST_STEPS:, TARGET_COLUMN]\n\n predictions = list()\n\n for i in range(len(features)):\n featuresEntry = features[i]\n\n predictedValue = featuresEntry[TARGET_COLUMN]\n\n predictions.append(predictedValue)\n\n return predictions\n\ndef plot(rawInput, trainPredict, testPredict, naivePredictions):\n trainPredictPlot = numpy.empty_like(rawInput[:, TARGET_COLUMN])\n trainPredictPlot[:] = numpy.nan\n start = TIME_WINDOW_WIDTH + FORECAST_STEPS - 1\n end = start + len(trainPredict)\n trainPredictPlot[start:end] = trainPredict\n\n testPredictPlot = numpy.empty_like(rawInput[:, TARGET_COLUMN])\n testPredictPlot[:] = numpy.nan\n start = -len(testPredict)\n testPredictPlot[start:] = testPredict\n\n naivePredictionsPlot = None\n\n if PLOT_NAIVE_PREDICTION:\n naivePredictionsPlot = numpy.empty_like(rawInput[:, TARGET_COLUMN])\n naivePredictionsPlot[:] = numpy.nan\n start = FORECAST_STEPS\n naivePredictionsPlot[start:] = naivePredictions\n\n plt.plot(rawInput[:, TARGET_COLUMN])\n\n if PLOT_NAIVE_PREDICTION:\n plt.plot(naivePredictionsPlot)\n\n plt.plot(trainPredictPlot)\n plt.plot(testPredictPlot)\n plt.show()\n\ndef printNaivePredictionError(naivePredictions, rawInput):\n\n targets = rawInput[FORECAST_STEPS:, TARGET_COLUMN]\n \n error = sqrt(mean_squared_error(targets, naivePredictions))\n\n print('{} - Naive prediction error'.format(error))\n\ndef printTrainError(trainPredictions, y_train):\n error = sqrt(mean_squared_error(y_train, trainPredictions))\n\n print('{} - Training data prediction error'.format(error))\n\ndef printTestError(testPredictions, y_test):\n error = sqrt(mean_squared_error(y_test, testPredictions))\n\n print('{} - Test data prediction error'.format(error))\n\ndef extractInputTrainingPart(input):\n end = int(TRAIN_TO_TEST_RATIO * len(input))\n\n return input[:end]\n\ndef extractInputTestPart(input):\n start = int(TRAIN_TO_TEST_RATIO * len(input))\n\n return input[start:]\n\ndef extractWindows(input):\n windowCount = len(input) - TIME_WINDOW_WIDTH - FORECAST_STEPS + 1\n\n windows = []\n\n for i in range(windowCount):\n window = []\n\n for j in range(TIME_WINDOW_WIDTH):\n featureCollection = input[i + j, FEATURE_COLUMNS]\n window.append(featureCollection)\n\n windows.append(window)\n\n return numpy.array(windows)\n\ndef extractTargets(input):\n targetCount = len(input) - TIME_WINDOW_WIDTH - FORECAST_STEPS + 1\n\n targets = []\n\n for i in range(targetCount):\n index = i + TIME_WINDOW_WIDTH + FORECAST_STEPS - 1\n target = input[index, TARGET_COLUMN]\n\n targets.append(target)\n\n return numpy.array(targets)\n\ndef extractWindowsAndTargets(input):\n windows = extractWindows(input)\n targets = extractTargets(input)\n\n return windows, targets\n\ndef extractTrainFeaturesAndTargets(input):\n inputTrainingPart = extractInputTrainingPart(input)\n\n return extractWindowsAndTargets(inputTrainingPart)\n\ndef extractTestFeaturesAndTargets(input):\n inputTestPart = extractInputTestPart(input)\n\n return extractWindowsAndTargets(inputTestPart)\n\ndef normalizeFeatureWindowsAndTargets(featureWindows, targets):\n scalers = []\n normalizedFeatureWindows = []\n normalizedTargets = []\n\n windowCount = len(featureWindows)\n\n for w in range(windowCount):\n featureWindow = featureWindows[w]\n target = targets[w]\n\n scaler = MinMaxScaler(feature_range = (-1, 1))\n\n for i in range(featureWindow.shape[1]):\n temp = numpy.array(featureWindow[:, i]).reshape((len(featureWindow[:, i]), 1))\n\n scaler = scaler.partial_fit(temp)\n\n temp = numpy.array([target]).reshape((len([target]), 1))\n scaler = scaler.partial_fit(temp)\n\n normalizedFeatureWindow = scaler.transform(featureWindow)\n normalizedTarget = scaler.transform(temp)[0]\n\n scalers.append(scaler)\n normalizedFeatureWindows.append(normalizedFeatureWindow)\n normalizedTargets.append(normalizedTarget)\n\n return scalers, numpy.array(normalizedFeatureWindows), numpy.array(normalizedTargets)\n\n###################################################################################\n\n#session = tfx._get_session('00:00:01.0')\n\n#(username, password) = tfx._init_credentials('rychu', 'namssik1')\n#is_registered = tfx._is_registered(username, password)\n\n#while True:\n# time.sleep(1)\n\n# session = tfx._get_session('00:00:01.0')\n\n# (username, password) = tfx._init_credentials('rychu', 'namssik1')\n# is_registered = tfx._is_registered(username, password)\n\n# data = tfx.read('EUR/USD', username='rychu', password='namssik1', force_unregistered=False, session=session)\n# print(data)\n\nnumpy.random.seed(RANDOM_SEED)\n\nrawInput = loadInput()\n\nnaivePredictions = None\n\nif CHECK_NAIVE_PREDICTION:\n naivePredictions = computeNaivePredictions(rawInput)\n\nX_train, y_train = extractTrainFeaturesAndTargets(rawInput)\nX_test, y_test = extractTestFeaturesAndTargets(rawInput)\n\ntrainScalers, X_trainNormalized, y_trainNormalized = normalizeFeatureWindowsAndTargets(X_train, y_train)\ntestScalers, X_testNormalized, y_testNormalized = normalizeFeatureWindowsAndTargets(X_test, y_test)\n\nmodel = None\n\nif LOAD_LAST_MODEL:\n model = load_model(LAST_MODEL_FILEPATH)\nelse:\n model = build_model([X_trainNormalized.shape[2], 50, 100, 1])\n\n model.fit(X_trainNormalized, y_trainNormalized, batch_size = BATCH_SIZE, epochs = EPOCH_COUNT)\n\n model.save(LAST_MODEL_FILEPATH)\n\ntrainPredictions = model.predict(X_trainNormalized)\n\ntrainPredictions = numpy.reshape(trainPredictions, trainPredictions.shape[0])\n\nfor i in range(len(trainPredictions)):\n trainPrediction = trainPredictions[i]\n trainScaler = trainScalers[i]\n\n temp = numpy.array([trainPrediction]).reshape((len([trainPrediction]), 1))\n\n trainPrediction = trainScaler.inverse_transform(temp)[0]\n\n trainPredictions[i] = trainPrediction\n\n###############\n\ntestPredictions = model.predict(X_testNormalized)\n\ntestPredictions = numpy.reshape(testPredictions, testPredictions.shape[0])\n\nfor i in range(len(testPredictions)):\n testPrediction = testPredictions[i]\n testScaler = testScalers[i]\n\n temp = numpy.array([testPrediction]).reshape((len([testPrediction]), 1))\n\n testPrediction = testScaler.inverse_transform(temp)[0]\n\n testPredictions[i] = testPrediction\n\nif CHECK_NAIVE_PREDICTION:\n printNaivePredictionError(naivePredictions, rawInput)\n\nprintTrainError(trainPredictions, y_train)\nprintTestError(testPredictions, y_test)\n\nplot(rawInput, trainPredictions, testPredictions, naivePredictions)","sub_path":"magic_test.py","file_name":"magic_test.py","file_ext":"py","file_size_in_byte":8474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"377053363","text":"# ##### BEGIN GPL LICENSE BLOCK #####\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software Foundation,\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n# ##### END GPL LICENSE BLOCK #####\n\nimport bpy\nfrom mathutils import Vector, Matrix\nfrom rna_prop_ui import rna_idprop_ui_prop_get\nfrom math import pi, cos, sin\nimport re\n\nfrom rigify.utils import make_deformer_name, make_mechanism_name\nfrom rigify.utils import strip_org, copy_bone\nfrom rigify.utils import create_widget\nfrom rigify.utils import create_circle_polygon\nfrom rigify.utils import align_bone_z_axis\n\n\ndef strip_numbers(name):\n \"\"\" Returns the name with trailing numbers stripped from it.\n \"\"\"\n # regexp = re.compile(\"\\.[0-9]+$\")\n matches = re.findall(\"\\.[0-9]+$\", name)\n if matches:\n match = matches[-1]\n return name[:-len(match)], name[-len(match):]\n else:\n return name, ''\n\n\ndef strip_LR(name):\n \"\"\" Returns the name with side suffix stripped from it.\n \"\"\"\n matches = re.findall(\"\\.[LR]$\", name)\n if matches:\n return name[:-len(matches[-1])]\n else:\n return name\n\n\ndef strip_LR_numbers(name):\n stripped, numbers = strip_numbers(name)\n return strip_LR(stripped) + numbers\n\n\ndef layers_to_index(layers):\n \"\"\"Return the first toggled layer in a layer list.\"\"\"\n for i, l in enumerate(layers):\n if l:\n return i\n\ndef create_deformation(obj,\n bone_name,\n member_index=0,\n bone_index=0,\n extra_offset=0.0,\n new_name=''):\n bpy.ops.object.mode_set(mode='EDIT')\n eb = obj.data.edit_bones\n\n org_bone_e = eb[bone_name]\n def_bone_e = eb.new(bone_name)\n\n# bone = copy_bone(obj, bone_name, strip_org(bone_name))\n# bone_e = eb[bone]\n\n if new_name == '':\n new_name = bone_name\n def_name = make_deformer_name(strip_org(new_name))\n def_bone_e.name = def_name\n# def_bone_e.name = strip_org(bone_name)\n\n def_bone_e.parent = org_bone_e\n def_bone_e.use_connect = False\n\n def_bone_e.head = org_bone_e.head\n def_bone_e.tail = org_bone_e.tail\n align_bone_z_axis(obj, def_name, Vector((0, -1, 0)))\n # def_bone_e.tail.z += org_bone_e.length * 0.5\n\n bpy.ops.object.mode_set(mode='POSE')\n\n def_bone_p = obj.pose.bones[def_name]\n def_bone_p['member_index'] = member_index\n def_bone_p['bone_index'] = bone_index\n def_bone_p['extra_offset'] = extra_offset\n\n # Driver\n driver = obj.driver_add('pose.bones[\"{}\"].location'.format(def_name), 2)\n driver.driver.expression = (\n 'member_index * 0.01 * -(flip*2-1) + bone_index * 0.001 * -(flip*2-1) - extra_offset * 0.01'\n )\n var_mi = driver.driver.variables.new()\n var_bi = driver.driver.variables.new()\n var_flip = driver.driver.variables.new()\n var_eo = driver.driver.variables.new()\n\n var_mi.type = 'SINGLE_PROP'\n var_mi.name = 'member_index'\n var_mi.targets[0].id_type = 'OBJECT'\n var_mi.targets[0].id = obj\n var_mi.targets[0].data_path = (\n 'pose.bones[\"{}\"][\"member_index\"]'.format(def_name)\n )\n\n var_bi.type = 'SINGLE_PROP'\n var_bi.name = 'bone_index'\n var_bi.targets[0].id_type = 'OBJECT'\n var_bi.targets[0].id = obj\n var_bi.targets[0].data_path = (\n 'pose.bones[\"{}\"][\"bone_index\"]'.format(def_name)\n )\n\n var_eo.type = 'SINGLE_PROP'\n var_eo.name = 'extra_offset'\n var_eo.targets[0].id_type = 'OBJECT'\n var_eo.targets[0].id = obj\n var_eo.targets[0].data_path = (\n 'pose.bones[\"{}\"][\"extra_offset\"]'.format(def_name)\n )\n\n var_flip.type = 'SINGLE_PROP'\n var_flip.name = 'flip'\n var_flip.targets[0].id_type = 'OBJECT'\n var_flip.targets[0].id = obj\n var_flip.targets[0].data_path = 'pose.bones[\"root\"][\"flip\"]'\n\n bpy.ops.object.mode_set(mode='EDIT')\n return def_name\n\n\n# def create_ik_child_of(obj, bone, pelvis_name):\n# # TODO get real bone name. From UI?\n# flip_bone_name = 'MCH-Flip'\n# pb = obj.pose.bones\n# bone_p = pb[bone]\n#\n# con1 = bone_p.constraints.new('CHILD_OF')\n# con1.name = \"Child Normal\"\n# con1.target = obj\n# con1.subtarget = pelvis_name\n# con1.inverse_matrix = pb[pelvis_name].matrix.inverted()\n#\n# con2 = bone_p.constraints.new('CHILD_OF')\n# con2.name = \"Child Flipped\"\n# con2.target = obj\n# con2.subtarget = flip_bone_name\n# con2.inverse_matrix = pb[flip_bone_name].matrix.inverted()\n#\n# # Drivers\n# driver = obj.driver_add(con1.path_from_id(\"influence\"))\n# driver.driver.expression = 'pelvis_follow'\n# var_pf = driver.driver.variables.new()\n#\n# var_pf.type = 'SINGLE_PROP'\n# var_pf.name = 'pelvis_follow'\n# var_pf.targets[0].id_type = 'OBJECT'\n# var_pf.targets[0].id = obj\n# var_pf.targets[0].data_path = bone_p.path_from_id() + '[\"pelvis_follow\"]'\n#\n# driver = obj.driver_add(con2.path_from_id(\"influence\"))\n# driver.driver.expression = '1-pelvis_follow'\n# var_pf = driver.driver.variables.new()\n#\n# var_pf.type = 'SINGLE_PROP'\n# var_pf.name = 'pelvis_follow'\n# var_pf.targets[0].id_type = 'OBJECT'\n# var_pf.targets[0].id = obj\n# var_pf.targets[0].data_path = bone_p.path_from_id() + '[\"pelvis_follow\"]'\n\n\ndef make_follow(obj, b, target, ctrl_name=None, follow_name=None):\n eb = obj.data.edit_bones\n\n # Control bone\n if ctrl_name is None:\n ctrl_name = strip_org(b)\n ctrl_bone = copy_bone(obj, b, ctrl_name)\n\n # Follow bone\n if follow_name is None:\n follow_name = make_mechanism_name(strip_org(b)) + \".follow\"\n follow_bone = copy_bone(\n obj,\n b,\n follow_name\n )\n eb[follow_bone].tail = eb[follow_bone].head + Vector((0, 0, 0.1))\n align_bone_z_axis(obj, follow_bone, Vector((0, 1, 0)))\n\n # Parenting\n bone_parent_name = eb[b].parent.name\n eb[ctrl_bone].use_connect = False\n eb[follow_bone].parent = eb[bone_parent_name]\n eb[ctrl_bone].use_connect = False\n eb[ctrl_bone].parent = eb[follow_bone]\n\n bpy.ops.object.mode_set(mode='OBJECT')\n pb = obj.pose.bones\n\n # Set up custom properties\n prop = rna_idprop_ui_prop_get(pb[ctrl_bone], \"follow\", create=True)\n pb[ctrl_bone][\"follow\"] = 1.0\n prop[\"soft_min\"] = 0.0\n prop[\"soft_max\"] = 1.0\n prop[\"min\"] = 0.0\n prop[\"max\"] = 1.0\n\n # Get follow bone's parent chain\n parent_chain = pb[follow_bone].parent_recursive\n parent_chain = [strip_org(b.name) for b in parent_chain]\n parent_chain.reverse()\n\n for i_c, parent_name in enumerate(parent_chain):\n con = pb[follow_bone].constraints.new('COPY_ROTATION')\n con.name = 'follow_' + parent_name\n con.target = obj\n con.subtarget = parent_name\n con.use_offset = True\n con.use_x = True\n con.use_y = True\n con.use_z = True\n if i_c == len(parent_chain) - 1:\n con.invert_x = True\n con.invert_y = True\n con.invert_z = True\n con.invert_z = True\n con.target_space = 'LOCAL'\n con.owner_space = 'LOCAL'\n # TODO investigate strange behaviour with FLIP\n\n # Drivers\n driver = obj.driver_add(con.path_from_id(\"influence\"))\n driver.driver.expression = '1-follow'\n var_pf = driver.driver.variables.new()\n\n var_pf.type = 'SINGLE_PROP'\n var_pf.name = 'follow'\n var_pf.targets[0].id_type = 'OBJECT'\n var_pf.targets[0].id = obj\n var_pf.targets[0].data_path = pb[ctrl_bone].path_from_id() + '[\"follow\"]'\n bpy.ops.object.mode_set(mode='EDIT')\n\n return ctrl_bone, follow_bone\n\n\ndef create_axis_line_widget(rig,\n bone_name,\n length=1,\n axis='X',\n bone_transform_name=None):\n \"\"\" Creates a basic line widget which remains horizontal.\n \"\"\"\n obj = create_widget(rig, bone_name, bone_transform_name)\n if obj is not None:\n\n pbone = rig.pose.bones[bone_name]\n # print(pbone.matrix.translation)\n pos = pbone.matrix.translation\n\n assert(axis in 'XYZ')\n if axis == 'X':\n verts = [(-1, 0, 0), (1, 0, 0)]\n if axis == 'Y':\n verts = [(0, -1, 0), (0, 1, 0)]\n if axis == 'Z':\n verts = [(0, 0, -1), (0, 0, 1)]\n\n verts = [pbone.matrix.inverted()\n * (pos + Vector(v)*length) for v in verts]\n\n edges = [(0, 1)]\n mesh = obj.data\n mesh.from_pydata(verts, edges, [])\n mesh.update()\n\n\ndef create_capsule_polygon(number_verts, length, width=0.1,\n length_co=0, width_co=2,\n overshoot=False):\n \"\"\" Create a capsule shape.\n number_verts: number of vertices of the poligon\n length: the length of the capsule\n width: the width of the capsule\n \"\"\"\n\n verts = []\n edges = []\n\n v_ind = 0\n for side in [-1, 1]:\n for i in range(0, number_verts//2+1):\n angle = 2*pi*i/number_verts - pi / 2 - (side+1) * (pi/2)\n vert = [0, 0, 0]\n vert[length_co] = cos(angle) * width/2 - (length - width/2) * side\n if overshoot:\n vert[length_co] -= (width / 2) * side\n vert[width_co] = sin(angle) * width/2\n verts.append(vert)\n if v_ind < number_verts+1:\n edges.append((v_ind, v_ind+1))\n v_ind += 1\n\n edges.append((0, number_verts + 1))\n\n return verts, edges\n\n\ndef create_capsule_widget(rig,\n bone_name,\n length=None,\n width=None,\n head_tail=0.0,\n horizontal=True,\n overshoot=False,\n bone_transform_name=None):\n \"\"\" Create a basic line widget which optionally remains horizontal.\n \"\"\"\n obj = create_widget(rig, bone_name, bone_transform_name)\n if obj is not None:\n\n pbone = rig.pose.bones[bone_name]\n # print(pbone.matrix.translation)\n pos = pbone.matrix.translation\n\n if length is None:\n length = pbone.length * 2\n if width is None:\n width = length * 0.1\n\n if horizontal:\n head_tail_vector = pbone.vector * head_tail\n verts, edges = create_capsule_polygon(16, length, width, overshoot=overshoot)\n verts = [(pbone.matrix * pbone.length).inverted()\n @ (pos + Vector(v) + head_tail_vector) for v in verts]\n else:\n head_tail_vector = Vector((0, 1, 0)) * head_tail\n verts, edges = create_capsule_polygon(16, length, width, 1, 0, overshoot=overshoot)\n verts = [(Vector(v) + head_tail_vector) for v in verts]\n\n mesh = obj.data\n mesh.from_pydata(verts, edges, [])\n mesh.update()\n\n\ndef create_aligned_polygon_widget(rig,\n bone_name,\n vertex_points,\n bone_transform_name=None):\n \"\"\" Creates a basic line widget which remains horizontal.\n \"\"\"\n obj = create_widget(rig, bone_name, bone_transform_name)\n if obj is not None:\n\n pbone = rig.pose.bones[bone_name]\n\n verts = [Vector((x, 0.0, y)) for x, y in vertex_points]\n edges = []\n for i in range(len(verts)):\n edges.append((i, i+1))\n edges[-1] = (0, len(verts)-1)\n\n verts = [(pbone.matrix * pbone.length).inverted() @ (v) for v in verts]\n\n mesh = obj.data\n mesh.from_pydata(verts, edges, [])\n mesh.update()\n\n\ndef create_aligned_circle_widget(rig,\n bone_name,\n number_verts=32,\n radius=1.0,\n width_ratio=1.0,\n head_tail=0.0,\n bone_transform_name=None):\n \"\"\" Creates a circle widget, aligned to view.\n \"\"\"\n obj = create_widget(rig, bone_name, bone_transform_name)\n if obj is not None:\n pbone = rig.pose.bones[bone_name]\n # print(pbone.matrix.translation)\n pos = pbone.matrix.translation\n\n verts, edges = create_circle_polygon(number_verts, 'Z', radius)\n head_tail_vector = Vector((0, head_tail, 0)) * pbone.length\n verts = [1/pbone.length\n * ((Vector(v) @ Matrix.Scale(width_ratio, 3, Vector((1, 0, 0))))\n + head_tail_vector) for v in verts]\n mesh = obj.data\n mesh.from_pydata(verts, edges, [])\n mesh.update()\n\n\ndef create_aligned_crescent_widget(rig,\n bone_name,\n radius=1.0,\n head_tail=0.0,\n bone_transform_name=None):\n \"\"\" Creates a crescent widget, aligned to view.\n \"\"\"\n obj = create_widget(rig, bone_name, bone_transform_name)\n if obj is not None:\n\n pbone = rig.pose.bones[bone_name]\n # print(pbone.matrix.translation)\n pos = pbone.matrix.translation\n\n verts = [\n Vector((-0.3826834559440613,\n 3.5762786865234375e-07,\n 0.9238792061805725)),\n Vector((-0.5555702447891235,\n 3.5762786865234375e-07,\n 0.8314692974090576)),\n Vector((-0.7071067690849304,\n 3.5762786865234375e-07,\n 0.7071064710617065)),\n Vector((-0.8314696550369263,\n 2.980232238769531e-07,\n 0.5555698871612549)),\n Vector((-0.9238795042037964,\n 3.2782554626464844e-07,\n 0.382683128118515)),\n Vector((-0.9807852506637573,\n 2.980232238769531e-07,\n 0.19509007036685944)),\n Vector((-1.0,\n 2.84984679410627e-07,\n -2.0948681367372046e-07)),\n Vector((-0.9807853102684021,\n 2.682209014892578e-07,\n -0.19509048759937286)),\n Vector((-0.9238795638084412,\n 2.682209014892578e-07,\n -0.38268357515335083)),\n Vector((-0.8314696550369263,\n 2.384185791015625e-07,\n -0.5555704832077026)),\n Vector((-0.7071067690849304,\n 2.384185791015625e-07,\n -0.7071070671081543)),\n Vector((-0.5555701851844788,\n 2.384185791015625e-07,\n -0.8314699530601501)),\n Vector((-0.38268327713012695,\n 2.384185791015625e-07,\n -0.9238799214363098)),\n Vector((-0.19509008526802063,\n 2.384185791015625e-07,\n -0.980785608291626)),\n Vector((3.2584136988589307e-07,\n 2.384185791015625e-07,\n -1.000000238418579)),\n Vector((0.19509072601795197,\n 2.384185791015625e-07,\n -0.9807854890823364)),\n Vector((0.38268381357192993,\n 2.384185791015625e-07,\n -0.923284649848938)),\n Vector((0.22629565000534058,\n 2.384185791015625e-07,\n -0.9575635194778442)),\n Vector((0.06365743279457092,\n 2.384185791015625e-07,\n -0.954291045665741)),\n Vector((-0.09898078441619873,\n 2.384185791015625e-07,\n -0.9143458008766174)),\n Vector((-0.2553688883781433,\n 2.384185791015625e-07,\n -0.8406103253364563)),\n Vector((-0.39949703216552734,\n 2.384185791015625e-07,\n -0.737377941608429)),\n Vector((-0.5258263349533081,\n 2.384185791015625e-07,\n -0.6102247834205627)),\n Vector((-0.6295021176338196,\n 2.384185791015625e-07,\n -0.465727299451828)),\n Vector((-0.7065401673316956,\n 2.682209014892578e-07,\n -0.3110540509223938)),\n Vector((-0.7539799809455872,\n 2.682209014892578e-07,\n -0.15349547564983368)),\n Vector((-0.7699984908103943,\n 2.84984679410627e-07,\n -1.378889180614351e-07)),\n Vector((-0.7539798617362976,\n 2.980232238769531e-07,\n 0.153495192527771)),\n Vector((-0.706540048122406,\n 3.2782554626464844e-07,\n 0.31105372309684753)),\n Vector((-0.6295021176338196,\n 2.980232238769531e-07,\n 0.4657267928123474)),\n Vector((-0.5258263349533081,\n 3.5762786865234375e-07,\n 0.6102243065834045)),\n Vector((-0.3994970917701721,\n 3.5762786865234375e-07,\n 0.737377405166626)),\n Vector((-0.25536900758743286,\n 3.5762786865234375e-07,\n 0.8406097292900085)),\n Vector((-0.09898099303245544,\n 3.5762786865234375e-07,\n 0.9143452048301697)),\n Vector((0.06365716457366943,\n 3.5762786865234375e-07,\n 0.9542905688285828)),\n Vector((0.22629405558109283,\n 3.5762786865234375e-07,\n 0.9575631022453308)),\n Vector((0.3826821446418762,\n 3.5762786865234375e-07,\n 0.9232847094535828)),\n Vector((0.19508881866931915,\n 3.5762786865234375e-07,\n 0.9807852506637573)),\n Vector((0.0,\n 3.5762786865234375e-07,\n 0.9999997019767761))]\n\n edges = []\n for i in range(len(verts)):\n edges.append((i, i+1))\n edges[-1] = (0, len(verts)-1)\n\n head_tail_vector = pbone.vector * head_tail\n verts = [(pbone.matrix * pbone.length).inverted()\n @ (pos + Vector(v) + head_tail_vector)\n * radius\n for v in verts]\n\n mesh = obj.data\n mesh.from_pydata(verts, edges, [])\n mesh.update()\n\n\ndef create_half_ellipse_polygon(number_verts, width=1.0, height=0.5):\n \"\"\"\\\nCreates a half ellipse.\n number_verts: number of vertices of the polygon\n radius: the radius of the circle\n head_tail: where along the length of\n the bone the circle is (0.0=head, 1.0=tail)\n\"\"\"\n verts = []\n edges = []\n angle = pi / number_verts\n i = 0\n\n while i <= (number_verts):\n a = cos(i * angle)\n b = sin(i * angle)\n\n verts.append((a * width, 0.0, b * height))\n\n if i < (number_verts):\n edges.append((i, i + 1))\n\n i += 1\n\n edges.append((0, number_verts))\n\n return verts, edges\n\n\ndef create_aligned_half_ellipse_widget(rig,\n bone_name,\n width,\n height,\n bone_transform_name=None,\n head_tail=0.0):\n \"\"\" Creates a half ellipse widget, aligned to view.\n \"\"\"\n obj = create_widget(rig, bone_name, bone_transform_name)\n if obj is not None:\n\n pbone = rig.pose.bones[bone_name]\n # print(pbone.matrix.translation)\n pos = pbone.matrix.translation\n\n verts, edges = create_half_ellipse_polygon(16, width, height)\n\n head_tail_vector = pbone.vector * head_tail\n verts = [(pbone.matrix * pbone.length).inverted()\n * (pos + Vector(v) + head_tail_vector)\n for v in verts]\n\n mesh = obj.data\n mesh.from_pydata(verts, edges, [])\n mesh.update()\n\n\ndef assign_bone_group(rig, bone_name, bone_group):\n \"\"\" Assign bone to bone group.\n \"\"\"\n\n if not bone_group in rig.pose.bone_groups:\n rig.pose.bone_groups.new(bone_group)\n rig.pose.bones[bone_name].bone_group = rig.pose.bone_groups[bone_group]\n","sub_path":"rigs/pantin/pantin_utils.py","file_name":"pantin_utils.py","file_ext":"py","file_size_in_byte":21018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"530575490","text":"import numpy as np\n\ndef icclim_output_file_defaults(arg):\n # first embryo towards collecting certain stuff at a central place\n\n defaults = {'file_name' : './icclim_out.nc',\n 'netcdf_version' : 'NETCDF3_CLASSIC',\n 'variable_type_str' : 'f4',\n 'variable_calender' : 'gregorian'}\n\n if defaults['variable_type_str'] in ['f', 'f4']:\n # 1.e20 is used by CMIP, otherwise the netCDF4 library default is preferrable \n # as it can be recasted back and forth between float32 and float64\n # defaults['_FillValue'] = netCDF4.default_fillvals['f4']\n defaults['_FillValue'] = np.float32(1.e20) \n defaults['missing_value'] = defaults['_FillValue']\n defaults['variable_type_name'] = 'float32' \n else:\n # what goes here should be patterned from above, e.g.:\n # if defaults['variable_type'] in ['d', 'f8']:\n # # defaults['_FillValue'] = netCDF4.default_fillvals['f8']\n # defaults['_FillValue'] = numpy.float64(1.e20) \n # defaults['missing_value'] = defaults['_FillValue']\n # defaults['variable_type_name'] = 'float64' \n # else\n\n raise NotImplementedError('Coding error in function icclim_output_file_defaults: '\n + 'only \"f\" / \"f4\" / \"float32\" output is implemented')\n\n return defaults[arg]\n\ndef check_ncVar(ncVar):\n try: \n tmp = ncVar.valid_min\n in_valid = True\n except AttributeError:\n try:\n tmp = ncVar.valid_max\n in_valid = True\n except AttributeError:\n try:\n tmp = ncVar.valid_range\n in_valid = True\n except AttributeError:\n in_valid = False\n \n return in_valid\n\ndef check_fill_value(ncVar):\n # 1) Check if _FillValue and/or missing_value exist in the input file\n try:\n in_fillval = ncVar._FillValue\n except AttributeError:\n in_fillval = None\n try:\n in_missval = ncVar.missing_value\n except AttributeError: \n in_missval = None\n\n if in_fillval is None and in_missval is None:\n # 2) If neither exist then assume that the default value is not used as a valid number in the input file(s)\n # However, given the value this seems very (VERY!) unlikely\n fill_val = icclim_output_file_defaults('missing_value')\n else:\n # 3) _FillValue or missing_value is present in the input file ...\n if ncVar.dtype.name != icclim_output_file_defaults('missing_value').dtype.name:\n # 4) ... and input data type is not the same as the output data type\n # This works out only if it is the netCDF4 default _FillValue, or we have a problem\n if in_fillval == netCDF4.default_fillvals[ncVar.dtype.str[1:]]:\n fill_val = in_fillval\n else:\n if in_missval == netCDF4.default_fillvals[ncVar.dtype.str[1:]]:\n fill_val = in_missval\n else:\n # Only error out here when really necessary...\n # Above code is really to trying to avoid coming here\n raise NotImplementedError('Input variable type <' \n + ncVar.dtype.name \n + '> not the same as output data type <' \n + icclim_output_file_defaults('missing_value').dtype.name \n + '>\\\\nThis is only possible if the input files are without missing values and _FillValue'\n + '\\\\nor the they (either one, or both) are exatly equal the netCDF4 default _FillValue')\n else:\n # 5) ... and the input data type is the same as the output data type\n # so use the value fro mthe input file (missing_value thakes precedence over _FillValue)\n if in_missval is None:\n fill_val = in_fillval\n else:\n fill_val = in_missval\n\n return fill_val","sub_path":"icclim/util/check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":4132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"454002647","text":"from rest_framework import permissions\n\nclass IsInstructorOrReadOnly(permissions.BasePermission):\n def has_permission(self, request, view):\n if request.method in permissions.SAFE_METHODS:\n return True\n\n user = request.user\n if user.is_authenticated():\n parents_query_dict = view.get_parents_query_dict()\n instructor_lookup = parents_query_dict.get('instructor', None)\n if instructor_lookup is not None:\n if instructor_lookup == str(user.pk):\n return True\n\n return False","sub_path":"pingo_space/schedule/permissions.py","file_name":"permissions.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"398164193","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('employees', '0008_userdata_is_billable'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='userdata',\n name='current_employee',\n field=models.BooleanField(verbose_name='Is Current Employee', default=True),\n ),\n migrations.AlterField(\n model_name='userdata',\n name='is_18f_employee',\n field=models.BooleanField(verbose_name='Is 18F Employee', default=True),\n ),\n migrations.AlterField(\n model_name='userdata',\n name='is_billable',\n field=models.BooleanField(verbose_name='Is 18F Billable Employee', default=True),\n ),\n migrations.AlterField(\n model_name='userdata',\n name='unit',\n field=models.IntegerField(verbose_name='Select 18F unit', choices=[(0, 'Operations-Team Operations'), (1, 'Operations-Talent'), (2, 'Operations-Infrastructure'), (3, 'Operations-Front Office'), (4, 'Chapters-Acquisition Managers'), (5, 'Chapters-Engineering'), (6, 'Chapters-Experience Design'), (7, 'Chapters-Product'), (8, 'Chapters-Strategists'), (9, 'Business-Acquisition Services'), (10, 'Business-Custom Partner Solutions'), (11, 'Business-Learn'), (12, 'Business-Products & Platforms'), (13, 'Business-Transformation Services'), (14, 'PIF-Fellows'), (15, 'PIF-Operations'), (16, 'Unknown / N/A')], blank=True, null=True),\n ),\n ]\n","sub_path":"tock/employees/migrations/0009_auto_20160709_0124.py","file_name":"0009_auto_20160709_0124.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"465067759","text":"from pathlib import Path\n\nfrom trame import controller as ctrl\nfrom trame.html import vuetify, vtk\nfrom trame.layouts import SinglePage\n\nfrom vtkmodules.vtkIOXML import vtkXMLUnstructuredGridReader\n\nfrom vtkmodules.vtkRenderingCore import (\n vtkRenderer,\n vtkRenderWindow,\n vtkRenderWindowInteractor,\n vtkDataSetMapper,\n vtkActor,\n)\nfrom vtkmodules.vtkInteractionStyle import vtkInteractorStyleSwitch # noqa\n\n\nDATA_DIR = Path(Path(__file__).parent.parent.parent.parent, \"data\")\nMESH_PATH = str(Path(DATA_DIR, \"mesh.vtu\"))\n\n# -----------------------------------------------------------------------------\n# VTK pipeline\n# -----------------------------------------------------------------------------\n\nreader = vtkXMLUnstructuredGridReader()\nreader.SetFileName(MESH_PATH)\n\nrenderer = vtkRenderer()\nrenderWindow = vtkRenderWindow()\nrenderWindow.AddRenderer(renderer)\n\nrenderWindowInteractor = vtkRenderWindowInteractor()\nrenderWindowInteractor.SetRenderWindow(renderWindow)\nrenderWindowInteractor.GetInteractorStyle().SetCurrentStyleToTrackballCamera()\n\nmapper = vtkDataSetMapper()\nactor = vtkActor()\nactor.GetProperty().SetEdgeVisibility(1)\nmapper.SetInputConnection(reader.GetOutputPort())\nactor.SetMapper(mapper)\nrenderer.AddActor(actor)\nrenderer.ResetCamera()\nrenderWindow.Render()\n\n# -----------------------------------------------------------------------------\n# GUI\n# -----------------------------------------------------------------------------\n\nlayout = SinglePage(\"VTK.js rendering\", on_ready=ctrl.on_ready)\nlayout.title.set_text(\"Test mesh exchange\")\n\nwith layout.content:\n with vuetify.VContainer(fluid=True, classes=\"pa-0 fill-height\"):\n with vtk.VtkLocalView(renderWindow) as view:\n layout.logo.click = view.reset_camera\n ctrl.on_ready = view.update\n\n# -----------------------------------------------------------------------------\n# Main\n# -----------------------------------------------------------------------------\n\nif __name__ == \"__main__\":\n layout.start()\n","sub_path":"examples/validation/tests/ErrorTests/mesh-encoding/mesh-export-local.py","file_name":"mesh-export-local.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"633791459","text":"import os\nimport asyncio\nfrom metaapi_cloud_sdk import MetaApi\nfrom metaapi_cloud_sdk.clients.metaApi.tradeException import TradeException\nfrom datetime import datetime, timedelta\n\n# Note: for information on how to use this example code please read https://metaapi.cloud/docs/client/usingCodeExamples\n\ntoken = os.getenv('TOKEN') or ''\naccountId = os.getenv('ACCOUNT_ID') or ''\n\n\nasync def test_meta_api_synchronization():\n api = MetaApi(token)\n try:\n account = await api.metatrader_account_api.get_account(accountId)\n initial_state = account.state\n deployed_states = ['DEPLOYING', 'DEPLOYED']\n\n if initial_state not in deployed_states:\n # wait until account is deployed and connected to broker\n print('Deploying account')\n await account.deploy()\n\n print('Waiting for API server to connect to broker (may take couple of minutes)')\n await account.wait_connected()\n\n # connect to MetaApi API\n connection = await account.get_rpc_connection()\n\n # wait until terminal state synchronized to the local state\n print('Waiting for SDK to synchronize to terminal state (may take some time depending on your history size)')\n await connection.wait_synchronized()\n\n # invoke RPC API (replace ticket numbers with actual ticket numbers which exist in your MT account)\n print('Testing MetaAPI RPC API')\n print('account information:', await connection.get_account_information())\n print('positions:', await connection.get_positions())\n # print(await connection.get_position('1234567'))\n print('open orders:', await connection.get_orders())\n # print(await connection.get_order('1234567'))\n print('history orders by ticket:', await connection.get_history_orders_by_ticket('1234567'))\n print('history orders by position:', await connection.get_history_orders_by_position('1234567'))\n print('history orders (~last 3 months):',\n await connection.get_history_orders_by_time_range(datetime.utcnow() - timedelta(days=90),\n datetime.utcnow()))\n print('history deals by ticket:', await connection.get_deals_by_ticket('1234567'))\n print('history deals by position:', await connection.get_deals_by_position('1234567'))\n print('history deals (~last 3 months):',\n await connection.get_deals_by_time_range(datetime.utcnow() - timedelta(days=90), datetime.utcnow()))\n\n # trade\n print('Submitting pending order')\n try:\n result = await connection.create_limit_buy_order('GBPUSD', 0.07, 1.0, 0.9, 2.0,\n {'comment': 'comm', 'clientId': 'TE_GBPUSD_7hyINWqAlE'})\n print('Trade successful, result code is ' + result['stringCode'])\n except Exception as err:\n print('Trade failed with error:')\n print(api.format_error(err))\n if initial_state not in deployed_states:\n # undeploy account if it was undeployed\n print('Undeploying account')\n await account.undeploy()\n\n except Exception as err:\n print(api.format_error(err))\n exit()\n\nasyncio.run(test_meta_api_synchronization())\n","sub_path":"examples/exampleGenerator/rpcExample.py","file_name":"rpcExample.py","file_ext":"py","file_size_in_byte":3364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"46474189","text":"from __future__ import annotations\nfrom typing import Set, List\nfrom collections import namedtuple\nfrom enum import Enum\nimport math\nimport random\n\nWIDTH = 7\nHEIGHT = 6\n\n\nFOURS = [\n 'XXXX',\n 'OOOO'\n ]\n\nTHREES = [\n ' XXX',\n 'X XX',\n 'XX X',\n 'XXX ',\n\n ' OOO',\n 'O OO',\n 'OO O',\n 'OOO '\n ]\n\nMINOR_COMBOS = {\n 'XX ': 5,\n ' XX ': 5,\n ' XX': 5,\n 'X X ': 5,\n ' X X': 5,\n 'X X': 5,\n 'X ': 1,\n ' X ': 1,\n ' X ': 1,\n ' X': 1,\n\n 'OO ': -5,\n ' OO ': -5,\n ' OO': -5,\n 'O O ': -5,\n ' O O': -5,\n 'O O': -5,\n 'O ': -1,\n ' O ': -1,\n ' O ': -1,\n ' O': -1,\n }\n\n\nIndex = namedtuple('Index', 'row col')\n\nclass EndState(Enum):\n NOT_DONE = 0\n O_WIN = 1\n X_WIN = 2\n TIE = 3\n\n\nclass Threat:\n def __init__(self, index: Index, turn: str):\n self.idx: Index = index\n self.turn: str = turn\n \n def is_one_away(self, other) -> bool:\n return abs(self.idx.row - other.idx.row) == 1 and self.idx.col == other.idx.col\n\n def __eq__(self, o: object) -> bool:\n return self.idx == o.idx and self.turn == o.turn\n\n def __hash__(self) -> int:\n return hash(self.idx.row) + hash(self.idx.col) + hash(self.turn)\n\n\nPOSITIVE = 1\nNEGATIVE = -1\nEVEN = 0\nODD = 1\n\nX_WIN = 10**8\nO_WIN = -X_WIN\n \nclass Board:\n\n def __init__(self, board=None, turn=None, prev_move=-1):\n self.board: List[str] = board or [' '*WIDTH for _ in range(HEIGHT)]\n self.turn: str = turn or 'X'\n self.prev_move: int = prev_move\n\n # end_state, x_threats and o_threats are all set(filled) in preliminiary_evaluation()\n self.end_state: EndState = EndState.NOT_DONE\n self.x_threats: Set[Threat] = set()\n self.o_threats: Set[Threat] = set()\n\n self._value = self.preliminary_evaluation()\n\n def __repr__(self) -> str:\n ret = \"\"\n ret += \"\\n\" + self.turn + \" to play\\n\"\n for i,row in enumerate(self.board):\n ret += str(HEIGHT-i)\n for spot in row:\n ret += \"|\" + spot\n ret += \"|\\n\"\n ret += \" 1 2 3 4 5 6 7\\n\\n\"\n return ret\n\n \n def print(self):\n print(\"\\n\" + self.turn + \" to play\")\n for i,row in enumerate(self.board):\n print(str(HEIGHT-i), end=\"\")\n for spot in row:\n print(\"|\" + spot, end=\"\")\n print(\"|\")\n print(\" 1 2 3 4 5 6 7\\n\")\n self._print()\n\n\n def _print(self):\n print(\"b = Board(\")\n print(\" ['\" + self.board[0] + \"',\")\n print(\" '\" + self.board[1] + \"',\")\n print(\" '\" + self.board[2] + \"',\")\n print(\" '\" + self.board[3] + \"',\")\n print(\" '\" + self.board[4] + \"',\")\n print(\" '\" + self.board[5] + \"'],\")\n print(\" '\" + self.turn + \"')\")\n\n def is_legal_move(self, col) -> bool:\n return self.board[0][col] == ' '\n\n def play(self, col: int) -> Board:\n if not self.is_legal_move(col):\n print(\"Move: \" + str(col))\n raise RuntimeError(\"Move is not legal\")\n for i in range(len(self.board)):\n if i == HEIGHT-1 or self.board[i + 1][col] != ' ':\n board = self.board.copy()\n board[i] = self.board[i][:col] + self.turn + self.board[i][col+1:]\n if self.turn == 'X':\n turn = 'O'\n else:\n turn = 'X'\n return Board(board=board, turn=turn, prev_move=col)\n\n def get_next_states(self) -> List[Board]:\n next_states = []\n for i in range(WIDTH):\n if self.is_legal_move(i):\n next_states.append(self.play(i))\n if next_states == []:\n self.end_state = EndState.TIE\n random.shuffle(next_states)\n return next_states\n\n def game_over(self):\n return self.end_state != EndState.NOT_DONE\n\n def preliminary_evaluation(self):\n value = 0\n\n # horizontals\n for i in range(HEIGHT):\n value += self._value_and_threats([Index(i,j) for j in range(WIDTH)])\n\n # vertical\n for j in range(WIDTH):\n value += self._value_and_threats([Index(i,j) for i in range(HEIGHT)])\n\n # diagonal top-left to bottom-right\n for i in range(4):\n value += self._value_and_threats(self.get_primary_diagonal(Index(0,i)))\n for i in range(1,3):\n value += self._value_and_threats(self.get_primary_diagonal(Index(i,0)))\n\n # diagonal top-right to bottom-left\n for i in range(3,7):\n value += self._value_and_threats(self.get_secondary_diagonal(Index(0,i)))\n for i in range(1,3):\n value += self._value_and_threats(self.get_secondary_diagonal(Index(i,6)))\n\n if self.end_state == EndState.NOT_DONE and self.check_for_tie():\n return 0\n\n return value\n\n def check_for_tie(self):\n if self.board[0].count(' ') == 0:\n self.end_state = EndState.TIE\n return True\n return False\n\n def _value_and_threats(self, indices: list[Index]) -> int:\n line = self._stringify(indices)\n value = 0\n for combo in FOURS:\n if combo in line:\n if 'X' in combo:\n self.end_state = EndState.X_WIN\n value = X_WIN\n else: # 'O' in combo:\n self.end_state = EndState.O_WIN\n value = -X_WIN\n for combo in THREES:\n if combo in line:\n \"\"\" Get index that contains threat\"\"\"\n index = indices[line.index(combo) + combo.index(' ')]\n if 'X' in combo:\n self.x_threats.add(Threat(index, 'X'))\n else:\n self.o_threats.add(Threat(index, 'O'))\n for combo in MINOR_COMBOS:\n if combo in line:\n value += MINOR_COMBOS[combo]\n\n return value\n\n # Take a list of Indices and return a string containing their values on the current board\n def _stringify(self, indices: list[Index]) -> str:\n ret = \"\"\n for index in indices:\n ret += self.board[index.row][index.col]\n return ret\n\n def evaluate(self) -> int:\n \"\"\" looks at threats on board and assigns value based on\n - how many there are\n - where they are in relation to each other\n - where they are in relation to parity of player\n \"\"\"\n value = self._value\n value += self._count_threats(self.x_threats, POSITIVE)\n value += self._count_threats(self.o_threats, NEGATIVE)\n value += self._check_threats_immediacy(self.x_threats, POSITIVE)\n value += self._check_threats_immediacy(self.o_threats, NEGATIVE)\n # value += self._check_threats_parity(self.x_threats, ODD, POSITIVE)\n # value += self._check_threats_parity(self.o_threats, EVEN, POSITIVE)\n value += self._check_threats_parity2()\n\n return value\n\n @staticmethod\n def _count_threats(threats: set[Threat], factor) -> int:\n \"\"\" Get points for every threat, 50 points per row (going down), \"\"\"\n return sum(50 * factor * (t.idx.row + 1) for t in threats)\n\n def _check_threats_immediacy(self, threats: set[Threat], factor) -> int:\n \"\"\" Checks if threats are:\n 1 immediate (are playable next turn)\n 2 stacked (one on top another)\n 3 immediate and stacked (one is immediate and other is on top of it)\n\n 1 is winning if more than one threat is found\n 2 is just good\n 3 is immediately winning.\"\"\"\n immediates = set()\n value = 0\n for t1 in threats:\n if t1.idx.row == HEIGHT - 1 or self.board[t1.idx.row + 1][t1.idx.col] != ' ':\n if t1.turn == self.turn:\n return 10_000 * factor\n immediates.add(t1)\n if len(immediates) > 1:\n return 10_000 * factor\n for t2 in threats:\n if t1.is_one_away(t2):\n if t1 in immediates:\n return 10_000 * factor\n value += 100 * factor\n return value\n\n @staticmethod\n def _check_threats_parity(threats: set[Threat], parity, factor) -> int:\n \"\"\" adds points if a threat is found in that players parity \"\"\"\n value = 0\n for threat in threats:\n if threat.idx.row % 2 == parity:\n value += 1000 * factor \n return value\n\n def _check_threats_parity2(self) -> int:\n def under(threat: Threat, other_threats: Set[Threat]) -> bool:\n for other_threat in other_threats:\n if threat.idx.col == other_threat.idx.col and threat.idx.row < other_threat.idx.row:\n return True\n return False\n\n x_odd_threats = {threat for threat in self.x_threats if threat.idx.row % 2 == 1}\n # x_even_threats = {threat for threat in self.x_threats if threat.idx.row % 2 == 0}\n o_odd_threats = {threat for threat in self.o_threats if threat.idx.row % 2 == 1}\n o_even_threats = {threat for threat in self.o_threats if threat.idx.row % 2 == 0}\n\n x_odd_threats = {x_threat for x_threat in x_odd_threats if under(x_threat, o_even_threats)}\n o_even_threats = {o_threat for o_threat in o_even_threats if under(o_threat, x_odd_threats)}\n\n # X\n for x_threat in x_odd_threats:\n if all(o_threat.idx.col != x_threat.idx.col for o_threat in o_odd_threats):\n # good for X\n return 1000\n if len(x_odd_threats) - len(o_odd_threats) == 1:\n # good for X\n return 1000\n if len(x_odd_threats) == 3:\n # good for X\n return 1000\n \n # O\n if len(o_even_threats) == 1 and len(x_odd_threats) == 0:\n # good for o\n return -1000\n if len(o_odd_threats) == 2:\n o_odd_threat_cols = {o_threat.idx.col for o_threat in o_odd_threats}\n x_odd_threat_cols = {x_threat.idx.col for x_threat in x_odd_threats}\n if all(x_col in o_odd_threat_cols for x_col in x_odd_threat_cols):\n # good for o\n return -1000\n return 0\n\n def get_column(self, i) -> list[tuple(int,int)]:\n ret = []\n for j in range(self.board):\n ret.append((i,j))\n return ret\n \n def get_primary_diagonal(self, index: Index) -> list[Index]:\n ret = []\n while index.row != -1 and index.col != -1 and index.row != HEIGHT and index.col != WIDTH:\n ret.append(index)\n index = Index(index.row + 1, index.col + 1)\n return ret\n\n def get_secondary_diagonal(self, index: Index) -> list[tuple(int,int)]:\n ret = []\n while index.row != -1 and index.col != -1 and index.row != HEIGHT and index.col != WIDTH:\n ret.append(index)\n index = Index(index.row + 1, index.col - 1)\n return ret\n","sub_path":"connect-four/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":11255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"159405079","text":"import sys\nsys.setrecursionlimit(2000)\nprint(sys.getrecursionlimit())\n\ni=0\ndef greet():\n global i\n i+=1\n print(\"hello\",1)\n greet()\n\ngreet()\n\n\ndef fac(n):\n if(n==0):\n return 1\n return n*fac(n-1)\n\nresult=fac(5)\nprint(result)","sub_path":"class/practice_recursion.py","file_name":"practice_recursion.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"387522471","text":"from random import randint, uniform\nimport matplotlib.pyplot as plt\nfrom copy import deepcopy\nfrom scipy import stats\nimport pandas as pd\nimport numpy as np\nimport matplotlib\nimport sklearn\nimport pickle\nimport random\nimport math\nimport os\n\nclass CPMG_simulation:\n def __init__(self, DFT_array):\n # DFT_array = \"/home/ghkim/CPMG/DFT_array_nosame.npy\"\n self.DFT_list = np.load(DFT_array)\n self.wL_value = 3451144\n self.step = 1e-8 \n self.Gaussian_co = 8.0370e-11\n self.n_value = 1024\n self.n_pulse = 16 \n # time table generation\n self.time_table = np.zeros(self.n_value)\n for t in range(self.n_value):\n self.time_table[t] = t*self.step\n\n self.noise_width = 2 # Noise 간격\n self.noise_height = 0.1 # Noise 높이(실험치 반영)\n\n def set_param_noise(self, noise_width, noise_height):\n self.noise_width = noise_width \n self.noise_height = noise_height \n\n def set_n_value(self, n_value):\n self.n_value = n_value\n \n def set_n_pulse(self, n_pulse):\n self.n_pulse = n_pulse\n\n def get_Mlist(self, idx):\n if isinstance(idx, int):\n A = self.DFT_list[idx, 0]\n B = self.DFT_list[idx, 1]\n wL_value = self.wL_value\n time_table = self.time_table\n M_list = np.ones([len(time_table)]) ## 이 부분은 매우 중요. 2pi가 곱해져야 제대로 나옴. 중복계산도 고려해봐야함!!\n\n M_list_temp = np.zeros([len(time_table)])\n for i, t in enumerate(time_table):\n w_tilda = pow(pow(A+wL_value, 2) + B*B, 1/2)\n alpha = w_tilda * t\n beta = wL_value * t\n mz = (A + wL_value) / w_tilda\n mx = B / w_tilda\n\n pi = math.acos(math.cos(alpha) * math.cos(beta) - mz * math.sin(alpha) * math.sin(beta))\n K1 = (1 - math.cos(alpha)) * (1 - math.cos(beta))\n K2 = 1 + math.cos(pi)\n K = pow(mx,2) * (K1 / K2)\n M = 1 - K * pow(math.sin(self.n_pulse * pi/2), 2)\n M_list_temp[i] = M\n \n M_list *= M_list_temp\n return M_list\n else:\n wL_value = self.wL_value\n time_table = self.time_table\n M_list = np.ones([len(time_table)])\n\n for ix in idx:\n A = self.DFT_list[ix, 0]\n B = self.DFT_list[ix, 1]\n \n M_list_temp = np.zeros([len(time_table)])\n for i, t in enumerate(time_table):\n w_tilda = pow(pow(A+wL_value, 2) + B*B, 1/2)\n alpha = w_tilda * t\n beta = wL_value * t\n mz = (A + wL_value) / w_tilda\n mx = B / w_tilda\n\n pi = math.acos(math.cos(alpha) * math.cos(beta) - mz * math.sin(alpha) * math.sin(beta))\n K1 = (1 - math.cos(alpha)) * (1 - math.cos(beta))\n K2 = 1 + math.cos(pi)\n K = pow(mx,2) * (K1 / K2)\n M = 1 - K * pow(math.sin(self.n_pulse * pi/2), 2)\n M_list_temp[i] = M\n \n M_list *= M_list_temp\n return M_list\n\n def noise_generator(self, px_table):\n random.seed(a=None) # 난수발생이 항상 다를 수 있도록\n noise = np.zeros(len(self.time_table))\n\n for i in range(len(self.time_table)):\n if i % self.noise_width == 0: # Noise 발생\n noise[i] += uniform(-self.noise_height, self.noise_height)\n if i > 1:\n mid = (noise[i] - noise[i-self.noise_width]) / self.noise_width\n for j in range(1, self.noise_width):\n noise[i+j-self.noise_width] += mid * j\n px_table_noise = px_table + noise\n return px_table_noise\n\n def generator(self, index, mode = \"noise\"):\n M_list = self.get_Mlist(index)\n px_table = (M_list + 1) / 2\n\n slope = np.zeros(len(self.time_table))\n for idx, i in enumerate(self.time_table):\n slope[idx] = np.exp(-i*i / self.Gaussian_co)\n \n px_table_slope = px_table * slope \n px_table_noise = self.noise_generator(px_table_slope)\n\n if mode == \"original\":\n return px_table\n elif mode == \"slope\":\n return px_table_slope\n elif mode == \"noise\":\n return px_table_noise\n elif mode == \"all\":\n return (px_table, px_table_slope, px_table_noise)\n\n# np.save(save_npy_dir+\"/{}_{}_{}_px_table.npy\".format(n_peaks, wL_value, Gaussian_co), total_px_table) ## slope만 추가\n# np.save(save_npy_dir+\"/{}_{}_{}_px_table_slope.npy\".format(n_peaks, wL_value, Gaussian_co), total_px_table_slope) ## slope만 추가\n# np.save(save_npy_dir+\"/{}_{}_{}_px_table_noise.npy\".format(n_peaks, wL_value, Gaussian_co), total_px_table_noise) ## slope에 noise가 추가\n# np.save(save_npy_dir+\"/{}_{}_{}_ABlist.npy\".format(n_peaks, wL_value, Gaussian_co), AB_arr)\n \n def generator_fromN(self, N, mode = \"noise\"):\n index = np.array([randint(1, len(self.DFT_list)) for i in range(N)])\n print(index)\n return self.generator(index, mode)\n \n \nif __name__ == \"__main__\":\n cpmg = CPMG_simulation()\n print(cpmg.get_Mlist(0))\n \n","sub_path":"generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":5525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"121760700","text":"import sys\nsys.setrecursionlimit(100000)\n\ndef dfs(x, y):\n visited[x][y] = True\n\n direction = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n for dx, dy in direction:\n nx, ny = x + dx, y + dy\n if nx < 0 or nx >= n or ny < 0 or ny >= m:\n continue\n if ground[nx][ny] == 1 and not visited[nx][ny]:\n dfs(nx, ny)\n\n\nt = int(input())\n\nfor _ in range(t):\n m, n, k = map(int, input().split())\n\n count = 0\n ground = [[0] * m for _ in range(n)]\n visited = [[False] * m for _ in range(n)]\n\n for _ in range(k):\n y, x = map(int, input().split())\n ground[x][y] = 1\n\n for i in range(n):\n for j in range(m):\n if ground[i][j] == 1 and not visited[i][j]:\n dfs(i, j)\n count += 1\n\n print(count)","sub_path":"1012.py","file_name":"1012.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"560917666","text":"#!/usr/bin/env python3\n\"\"\"\nHelper functions for the Bayesian-HMM package. Should not be called directly by the\nuser.\n\"\"\"\n# Support typehinting.\nfrom __future__ import annotations\nfrom typing import Union, Generator, Iterator, Dict, Optional\n\nimport numpy as np\nimport random\nimport itertools\nimport string\n\nfrom scipy.stats import norm as normal\nfrom scipy.stats import gamma\n\n\n# Shorthand for a numeric type.\nNumeric = Union[int, float]\n\n\n# used to give human-friendly labels to states as they are created\ndef label_generator(labels: str = string.ascii_lowercase) -> Generator[str, None, None]:\n \"\"\"\n :param labels: set of labels to choose from. Should not be numeric.\n :return: a generator which yields unique labels of the form\n a, b, ..., z, a1, b1, ...\n \"\"\"\n x, y, z = 0, 0, \"\"\n while True:\n if x < len(labels):\n yield labels[x] + z\n x += 1\n if x == len(labels):\n y += 1\n z = str(y)\n x = 0\n\n\n# used to choose from new states after resampling latent states\ndef dirichlet_process_generator(alpha: Numeric = 1, \n output_generator: Iterator[Union[str, int]] = None\n ) -> Generator[Union[str, int], None, None]:\n \n \"\"\"\n Returns a generator object which yields subsequent draws from a single dirichlet\n process.\n :param alpha: alpha parameter of the Dirichlet process\n :param output_generator: generator which yields unique symbols (likely hdphmm.state_generator)\n :return: generator object\n \"\"\"\n\n # this should not be the case, since output_generator = self.state_generator\n if output_generator is None:\n\n # generate increasing integers starting at 0\n output_generator = itertools.count(start=0, step=1)\n \n count = 0\n weights = {}\n \n while True:\n\n # if draw from unif(0,1) greater than ratio of count to count + alpha param, \n # we generate a new state from self.state_generator\n # Note: The larger the alpha prior is, the more likely we will draw new values \n if random.uniform(0, 1) > (count / (count + alpha)):\n\n # generate the next state from self.state_generator\n val = next(output_generator)\n # assign a weight of 1 to the generated state \n weights[val] = 1\n\n # otherwise, we will continue to reinforce existing states importance by randomly drawing \n # one of said states in proportion to its weight, adding to that weight, and \n # ultimately yielding that state instead of a new one \n else:\n\n val = np.random.choice(list(weights.keys()), 1, p=list(x / count for x in weights.values()))[0]\n weights[val] += 1\n \n count += 1\n \n # we yield the state we drew (be it brand new or one previously generated\n # and the originally initialised states would be icnorporated into the weights dict\n yield val\n\n\n# used to ensure all hyperparameters have non-zero values\ndef max_dict(d: Dict[str, Numeric], eps: Numeric = 1e-8) -> Dict[str, Numeric]:\n \n return {k: max(float(v), eps) for k, v in d.items()}\n\n\ndef shrink_probabilities(d: Dict[Optional[str], Numeric], eps: Numeric = 1e-12) -> Dict[Optional[str], Numeric]:\n\n denom = sum(d.values()) + len(d) * eps\n\n return {k: (float(v) + eps) / denom for k, v in d.items()}\n\ndef normal_gamma_rvs(mu, _lambda, alpha, beta, size=1, random_state=None):\n\n \"\"\"\n Draw from a normal-gamma distribution prior for conjugate gaussian likelihood distribution\n when both mu and sigma are uncertain. \n The gamma distribution is the prior\n for the precision parameter (i.e. 1/variance or scale) of the normal distribution \n :params mu: location parameter for normal distribution \n :params _lambda: sample size parameter for estimating mu\n :params alpha: shape parameter for gamma distribution https://en.wikipedia.org/wiki/Normal-gamma_distribution\n :params beta: rate (i.e. 1/scale) parameter for gamma distribution\n :size: size of the sample\n :return: new location and scale (variance) params top\n \"\"\"\n\n # draw precision, tau from gamma distribution \n tau = gamma.rvs(loc=alpha, scale=1/beta, size=size, random_state=random_state)\n\n mu_new = normal.rvs(loc=mu, scale=1/(_lambda*tau), size=size, random_state=random_state)\n\n return [(mu_new[i], 1/tau[i]) for i in range(size)]\n\ndef normal_gamma_pdf(x_tuple, prior_mu, prior_lambda, prior_alpha, prior_beta):\n\n sample_mu, sample_sigma = x_tuple\n sample_tau = 1/sample_sigma\n\n gamma_density = gamma.pdf(sample_tau, prior_alpha, scale=prior_beta)\n normal_density = normal.pdf(sample_mu, loc=prior_mu, scale=1/())\n\n normal_gamma_density = np.log(gamma_density) + np.log(normal_density)\n\n return normal_gamma_density\n\n\n\n\n\n\n\n\n\n","sub_path":"bayesian_hmm/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"151563739","text":"\"\"\"\nGeneric regression model for machine learning problems based on Keras\n\n@author: Francesco Baldisserri\n@creation date: 06/03/2020\n\"\"\"\n\nimport os\nimport scipy\nimport shutil\nimport numpy as np\nfrom tensorflow import keras\nfrom sklearn.preprocessing import OneHotEncoder\nfrom tensorflow.keras.layers import Dense, Flatten, BatchNormalization, Dropout\nfrom tensorflow.keras.callbacks import EarlyStopping, TensorBoard\nfrom sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin\nkeras.backend.set_floatx(\"float16\")\n\n\n# TODO: Refactor with Estimator template: https://github.com/scikit-learn-contrib/project-template/blob/master/skltemplate/_template.py\nclass KerasDenseRegressor(BaseEstimator, RegressorMixin):\n def __init__(self, units=(64, 64), dropout=0, activation=\"relu\",\n batch_norm=False, batch_size=None, optimizer=\"nadam\",\n kernel_init=\"glorot_normal\", val_split=0, epochs=10,\n loss=\"mean_squared_error\", out_act=\"linear\",\n n_iter_no_change=None, tensorboard=False,\n custom_objects=None, _estimator_type=\"regressor\"):\n self.units = units\n self.dropout = dropout\n self.activation = activation\n self.batch_norm = batch_norm\n self.batch_size = batch_size\n self.optimizer = optimizer\n self.kernel_init = kernel_init\n self.val_split = val_split\n self.epochs = epochs\n self.loss = loss\n self.out_act = out_act\n self.n_iter_no_change = n_iter_no_change\n self.tensorboard = tensorboard\n self.model = None\n self.custom_objects = custom_objects\n self._estimator_type = _estimator_type\n\n def fit(self, X, y, metrics=None):\n X_val, y_val = self._validate_array(X), self._validate_array(y)\n self._build_model(X_val, y_val, metrics)\n calls = []\n if self.tensorboard:\n params = \"-\".join([param + \"_\" + str(value)\n for param, value in self.get_params().items()])\n calls += [TensorBoard(log_dir=os.path.join(\"logs\", params))]\n if self.n_iter_no_change is not None:\n early_stop_metric = \"val_loss\" if self.val_split > 0 else \"loss\"\n calls += [EarlyStopping(monitor=early_stop_metric,\n patience=self.n_iter_no_change,\n restore_best_weights=True)]\n return self.model.fit(X_val, y_val, epochs=self.epochs,\n callbacks=calls, validation_split=self.val_split)\n\n def predict(self, X):\n return self.model.predict(self._validate_array(X))\n\n def _build_model(self, X, y, metrics):\n \"\"\" Build Keras model according to input parameters \"\"\"\n layers = [Flatten()] if len(X.shape[1:]) > 1 else []\n for units in self.units:\n if self.dropout > 0: layers += [Dropout(self.dropout)]\n layers += [Dense(units,\n activation=self.activation,\n kernel_initializer=self.kernel_init)]\n if self.batch_norm: layers += [BatchNormalization()]\n out_shape = y.shape[1] if len(y.shape) > 1 else 1\n layers += [Dense(out_shape, activation=self.out_act)]\n self.model = keras.models.Sequential(layers)\n self.model.compile(loss=self.loss,\n optimizer=self.optimizer,\n metrics=metrics)\n\n def _validate_array(self, array):\n if isinstance(array, list):\n validated_array = np.array(array)\n elif scipy.sparse.issparse(array):\n validated_array = array.todense()\n else:\n validated_array = array\n return validated_array\n\n def __getstate__(self):\n state = self.__dict__.copy()\n if self.model is not None:\n keras.models.save_model(self.model, \"temp\", overwrite=True)\n shutil.make_archive(\"temp\", \"zip\", \"temp\")\n shutil.rmtree(\"temp\")\n with open(\"temp.zip\", mode=\"rb\") as temp:\n state[\"model\"] = temp.read()\n os.remove(\"temp.zip\")\n return state\n\n def __setstate__(self, state):\n self.__dict__ = state\n if state[\"model\"] is not None:\n with open(\"temp.zip\", mode=\"wb\") as temp:\n temp.write(state[\"model\"])\n temp.flush()\n shutil.unpack_archive(\"temp.zip\", \"temp\")\n os.remove(\"temp.zip\")\n self.model = keras.models.load_model(\"temp\",\n custom_objects=self.custom_objects)\n shutil.rmtree(\"temp\")\n\n\nclass KerasDenseClassifier(KerasDenseRegressor, ClassifierMixin):\n def __init__(self, units=(64, 64), dropout=0, activation=\"relu\",\n batch_norm=False, batch_size=None, optimizer=\"nadam\",\n kernel_init=\"glorot_normal\", val_split=0, epochs=10,\n loss=\"categorical_crossentropy\", out_act=\"softmax\",\n n_iter_no_change=None, tensorboard=False,\n custom_objects = None, _estimator_type=\"regressor\"):\n self.encoder = OneHotEncoder()\n super().__init__(units=units, dropout=dropout,\n activation=activation, batch_norm=batch_norm,\n batch_size=batch_size, optimizer=optimizer,\n kernel_init=kernel_init, val_split=val_split,\n epochs=epochs, loss=loss, out_act=out_act,\n n_iter_no_change=n_iter_no_change,\n tensorboard=tensorboard,\n custom_objects=custom_objects)\n\n def fit(self, X, y): # Suboptimally using Softmax also for 2-class problems\n if y.ndim == 1:\n y = np.array(y).reshape(-1, 1)\n y_enc = self.encoder.fit_transform(y)\n return super().fit(X, y_enc, [\"accuracy\"])\n\n def predict(self, X):\n y_enc = super().predict(X)\n return self.encoder.inverse_transform(y_enc)\n\n def predict_proba(self, X):\n return self.model.predict_proba(X)\n","sub_path":"sibyl/models/kerasdense.py","file_name":"kerasdense.py","file_ext":"py","file_size_in_byte":6116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"620269937","text":"from .models import Post,News,Gallery,Associate\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.urls import reverse_lazy\nfrom .forms import NewsForm,GalleryForm,ContactForm,AssociateForm,Career\nfrom django.core.mail import EmailMessage\nfrom django.template.loader import get_template\nfrom django.db.models import Q\nfrom django.views import View\nfrom django.views.generic import (ListView,\n DetailView,\n CreateView,\n UpdateView,\n DeleteView\n )\nfrom django.shortcuts import render,redirect\nfrom django.db.models import Count\nfrom newsapi import NewsApiClient\n\n# News Update Logic\ndef news(request):\n newsapi = NewsApiClient(api_key=\"a59e5f24831a4322b535578654582973\")\n topheadlines = newsapi.get_top_headlines(sources='the-times-of-india, business-insider, cnn, google-news')\n articles = topheadlines['articles']\n\n desc = []\n news = []\n img = []\n content = []\n publishedAt = []\n url = []\n\n for i in range(len(articles)):\n myarticles = articles[i]\n\n news.append(myarticles['title'])\n desc.append(myarticles['description'])\n img.append(myarticles['urlToImage'])\n content.append(myarticles['content'])\n publishedAt.append(myarticles['publishedAt'])\n url.append(myarticles['url'])\n\n\n\n mylist = zip(news, desc, img, content, publishedAt, url)\n return render(request, 'news_link.html', context={\"mylist\":mylist})\n\n\n# Blog Logic\nclass PostListView(ListView):\n model = Post\n template_name = 'posts.html'\n ordering = ['-timestamp']\n paginate_by = 4\n def get_context_data(self, **kwargs):\n context = super(PostListView, self).get_context_data(**kwargs)\n context['tags'] = Post.objects.order_by('-timestamp')[0:5]\n context['Category_count'] = Post.objects.values('categories__title').annotate(Count('categories__title'))\n return context\n\nclass PostDetailView(DetailView):\n model = Post\n template_name = 'post_detail.html'\n def get_context_data(self, **kwargs):\n context = super(PostDetailView, self).get_context_data(**kwargs)\n context['tags'] = Post.objects.order_by('-timestamp')[0:5]\n return context\n\nclass PostCreateView(CreateView):\n model = Post\n template_name = 'post_form.html'\n fields = ['title','overview','content','thumbnail','categories']\n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n return super().dispatch(*args, **kwargs)\n\nclass PostUpdateView(UpdateView):\n model = Post\n template_name = 'post_form.html'\n fields = ['title','overview','content','thumbnail','categories']\n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n return super().dispatch(*args, **kwargs)\n\nclass PostDeleteView(DeleteView):\n model = Post\n template_name = 'post_confirm_delete.html'\n success_url = '/posts/posts/'\n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n return super().dispatch(*args, **kwargs)\n\n\n# Search Logic\ndef search(request):\n queryset = Post.objects.order_by('-timestamp')\n latest = Post.objects.order_by('-timestamp')[0:4]\n query = request.GET.get('q')\n if query:\n queryset = queryset.filter(\n Q(title__icontains=query) |\n Q(overview__icontains=query)\n ).distinct()\n context= {\n 'queryset': queryset,\n 'latest': latest\n }\n return render(request,'search_results.html',context)\n\n#Team\ndef team(request):\n form = AssociateForm(request.POST or None, request.FILES or None)\n if request.method == 'POST' and form.is_valid():\n form.save()\n posts = Associate.objects.all()\n context = {\n 'form': form,\n 'posts': posts,\n }\n return render(request,'team.html',context)\n\n# Gallery Logic\ndef modal(request):\n form = GalleryForm(request.POST or None, request.FILES or None)\n if request.method == 'POST' and form.is_valid():\n for f in form:\n f.save()\n Gallery_pics = Gallery.objects.all()\n context = {\n 'form': form,\n 'Gallery_pics': Gallery_pics\n }\n return render(request, 'modal.html',context)\n\ndef post_remove(request, pk):\n post = get_object_or_404(pics, pk=pk)\n post.delete()\n return redirect('post_list')\n\n# Career form view\ndef career(request):\n Contact_Form = Career\n if request.method == 'POST':\n form = Contact_Form(request.POST, request.FILES)\n # if form.is_valid():\n first_name = request.POST.get('first_name')\n last_name = request.POST.get('last_name')\n email = request.POST.get('email')\n phone_no = request.POST.get('phone_no')\n gender = request.POST.get('gender')\n position = request.POST.get('position')\n dob = request.POST.get('dob')\n qualification = request.POST.get('qualification')\n native = request.POST.get('native')\n registration = request.POST.get('registration')\n application_no = request.POST.get('application_no')\n last_comapny = request.POST.get('last_comapny')\n years = request.POST.get('years')\n months = request.POST.get('months')\n comments = request.POST.get('comments')\n attach = request.FILES.get('attach')\n\n template = get_template('Career.txt')\n context = {\n 'first_name' : first_name,\n 'last_name' : last_name,\n 'email' : email,\n 'phone_no': phone_no,\n 'gender': gender,\n 'position': position,\n 'dob': dob,\n 'qualification': qualification,\n 'native': native,\n 'registration': registration,\n 'application_no': application_no,\n 'last_comapny': last_comapny,\n 'years': years,\n 'months': months,\n 'comments': comments,\n }\n\n content = template.render(context)\n subject = first_name + \" \" + last_name + \"-\" + registration;\n email = EmailMessage(\n subject,\n content,\n \"Ranj CS.\" + '',\n ['consult@ranjcs.com'],\n headers = { 'Reply To': email }\n )\n email.attach(attach.name, attach.read(), attach.content_type)\n email.send()\n\n return redirect('/')\n return render(request, 'career.html', {'form':Contact_Form })\n\n\n# Contact form view\ndef Contact(request):\n Contact_Form = ContactForm\n if request.method == 'POST':\n form = Contact_Form(data=request.POST)\n\n if form.is_valid():\n contact_name = request.POST.get('contact_name')\n contact_email = request.POST.get('contact_email')\n contact_subject = request.POST.get('contact_subject')\n contact_content = request.POST.get('content')\n\n template = get_template('contact_form.txt')\n context = {\n 'contact_name' : contact_name,\n 'contact_email' : contact_email,\n 'contact_subject' : contact_subject,\n 'contact_content' : contact_content,\n }\n\n content = template.render(context)\n\n email = EmailMessage(\n contact_subject,\n content,\n \"Ranj Co.\" + '',\n ['consult@ranjcs.com'],\n headers = { 'Reply To': contact_email }\n )\n\n email.send()\n\n return redirect('.')\n return render(request, 'contact.html', {'form':Contact_Form })\n\ndef services(request):\n return render(request,'services.html')\n","sub_path":"posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"638751937","text":"# Code for Vegeneres Cipher\n\n# List of all the Alphabets using List Comprehension\nlst = [chr(x) for x in range(65, 91)]\n\n# Creating Vegeneres Table using for loops\n\n# # 2D List to Store the Vegeneres Table\n# arr = []\n# for i in range(0, 26):\n# # List to store rows Alphabets respective to their Index\n# temp = []\n# c = i\n# for j in range(0, 26):\n# # Appending the Alphabets in the temporary list(row) \n# temp.append(lst[c % 26])\n# c += 1\n# # now Appending the row in the 2D list\n# arr.append(temp)\n\n# Provide Options\nprint(\"Welcome to Ph@ntom's Cipher :::\")\nprint(\"1 >>> Encrypt\")\nprint(\"2 >>> Decrypt\")\n\n# Input the Plain Text and the Corresponding Key\nch = int(input('>>>'))\nif ch == 1:\n print(\"Enter the Text to be Encrypted\")\n # Taking the input and converting into UpperCase\n str = input('-->>>').upper()\n print(\"Enter the Key\")\n # Taking the Key in UpperCase and Converting it into a List \n Key = list(input(\"should contain NO Spaces >>>\").upper())\n # Length of the Key\n l = len(Key)\n # Removing any Spaces Available in the Plain Text\n # Plain = list(\"\".join(str.split()))\n # List Containing the Cipher Text\n Cipher = []\n for i in range(len(str)):\n if str[i] != ' ':\n k = lst.index(Key[i % l])\n m = lst.index(str[i])\n Cipher.append(lst[(m + k) % 26])\n else:\n Cipher.append(' ')\n \n # Print out the Cipher Text\n print(\"The Encrypted Text is :::\")\n print(\"\".join(Cipher))\n\nelif ch == 2:\n print(\"Enter the Text to be Derypted\")\n # Taking the input and converting into UpperCase\n str = input('-->>>').upper()\n print(\"Enter the Key\")\n # Taking the Key in UpperCase and Converting it into a List \n Key = list(input(\"should contain NO Spaces >>>\").upper())\n # Length of the Key\n l = len(Key)\n # Removing any Spaces Available in the Encrypted Text\n # Cipher = list(\"\".join(str.split()))\n # List Containing the Decrypted Text\n Decipher = []\n for i in range(len(str)):\n if str[i] != ' ':\n k = lst.index(Key[i % l])\n m = lst.index(str[i])\n Decipher.append(lst[(m - k) % 26])\n else:\n Decipher.append(' ')\n\n # Print out the Decrypted Text\n print(\"The Decrypted Text is :::\")\n print(\"\".join(Decipher))\n\n\n\n\n","sub_path":"Coding/Python_Prgs/Crypto/Vegeneres_Cipher.py","file_name":"Vegeneres_Cipher.py","file_ext":"py","file_size_in_byte":2360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"543050909","text":"from bfirst_step.config.Log import *\nfrom bfirst_step.config.LogBug import *\nimport re\n\nlogbug = LogBug()\nlogger = Log()\n\nclass common_return_value:\n @staticmethod\n def testxubao(self, StatusMessage):\n if StatusMessage == '续保成功':\n return True\n else:\n #logbug.debug(\"续保--异常信息为:{}\".format(StatusMessage,))\n return False\n @staticmethod\n def testbaojia(self, baojiaStatusMessage):\n falg = True\n if baojiaStatusMessage == '请求发送成功':\n return falg\n else:\n #logbug.debug(\"报价--异常信息为:{}\".format(baojiaStatusMessage))\n return\n\n @staticmethod\n def Offerresults(self, result):\n #results1 = re.findall('重复投保', results, re.S|re.M)\n if result == '获取报价信息成功':\n return True\n else:\n return False\n\n @staticmethod\n def Offer_the_results(self, results):\n results12 = str(results)\n results1 = re.findall('重复投保', results12, re.S|re.M)\n if results1 == ['重复投保']:\n return True\n else:\n return False\n\n @staticmethod\n def Offer_results(self, results1):\n results = str(results1)\n results2 = re.findall('同类型的险种', results, re.S|re.M)\n if results2 == ['同类型的险种']:\n return True\n else:\n return False\n # @staticmethod\n # def dict_get(dict1, objkey, default=None):\n # for k, v in dict1.items():\n # if k == objkey:\n # return v\n # else:\n # if type(v) is dict:\n # ret = dict_get(v, objkey)\n # if ret is not default:\n # return ret\n\n @staticmethod\n def sum_insured(self, suminsured):\n baojiajg = suminsured\n BizTotal = baojiajg.res['Item']['BizTotal']#商业\n TaxTotal = baojiajg.res['Item']['TaxTotal']#车船\n ForceTotal = baojiajg.res['Item']['ForceTotal']#交强\n return BizTotal, TaxTotal, ForceTotal","sub_path":"bfirst_step/private_method/privates/common_return.py","file_name":"common_return.py","file_ext":"py","file_size_in_byte":2112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"511093034","text":"from django.shortcuts import render\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom .models import *\nfrom django.contrib.auth import authenticate, login\nfrom mainApp.models import Gigster,Requester\n\ndef refresh(obj):\n token = sub('-','',str(uuid4()))\n while AuthToken.objects.filter(token = token).exists():\n token = sub('-','',str(uuid4()))\n obj.token = token\n refresh_token = sub('-','',str(uuid4()))\n while AuthToken.objects.filter(refresh_token = refresh_token).exists():\n token = sub('-','',str(uuid4()))\n obj.refresh_token = refresh_token\n obj.save()\n\n@api_view(['POST'])\ndef token(request):\n print('*****************')\n print('*****************')\n print('*****************')\n print('*****************')\n print('*****************')\n print(request.data)\n\n # return Response(request)\n \n \n # data = request.data\n # err = {}\n # expire = 3600*720\n # if 'clientid' not in data:\n # err['clientid'] = 'required'\n # if 'clientsecret' not in data:\n # err['clientsecret'] = 'required'\n # if 'granttype' not in data:\n # err['granttype'] = 'required'\n # if err:\n # return Response({'error/s':err},status= status.HTTP_400_BAD_REQUEST)\n # if data['granttype'] == 'password':\n # if 'username' not in data:\n # err['username'] = 'required'\n # if 'password' not in data:\n # err['password'] = 'required'\n # if 'usertype' not in data:\n # err['usertype'] = 'required'\n # else:\n # if data['usertype'] not in ('gigster','requester'):\n # err['usertype'] = 'invalid user'\n # elif data['granttype'] == 'refeshtoken':\n # if 'refreshtoken' not in data:\n # err['refreshtoken'] = 'required'\n # else:\n # return Response({'error':'unsupported grant type'})\n # if err:\n # return Response({'error/s':err},status= status.HTTP_400_BAD_REQUEST)\n # else:\n # client = Client.objects.filter(client_id = data['clientid'],client_secret = data['clientsecret'])\n # if client.exists():\n # if data['granttype'] == 'password':\n # if data['usertype'] == 'gigster':\n # user = Gigster.objects.select_related('user__user','sub').filter(user__user__email = data['username'])\n # if data['usertype'] == 'requester':\n # user = Requester.objects.select_related('user__user').filter(user__user__email = data['username'])\n # if not user.exists():\n # return Response({'error':'Invalid user'},status= status.HTTP_401_UNAUTHORIZED)\n # else:\n # user = list(user)[0]\n # auth = authenticate(username=data['username'], password=data['password'])\n # if auth:\n # if 'sub' in request.GET and data['usertype'] == 'requester' and request.GET['sub'] !='main':\n # if user.sub.link != request.GET['sub']:\n # return Response({'error':'Invalid Credentials'},status=status.HTTP_401_UNAUTHORIZED)\n # token = AuthToken(client = list(client)[0],user = user.user.user,expires = expire)\n # token.save()\n # return Response({\n # 'token':token.token,\n # 'refreshtoken':token.refresh_token,\n # 'expires':token.expires,\n # 'user':data['username']\n # })\n # else:\n # return Response({'error':'Invalid Credentials'},status=status.HTTP_401_UNAUTHORIZED)\n # elif data['granttype'] == 'refreshtoken':\n # token = AuthToken.objects.select_related('user').filter(refresh_token = data['refreshtoken'])\n # if token.exists() and not token.first().revoked:\n # if (datetime.now - token.added).total_seconds > token.expire :\n # return Response({'error':'time expired'},status= status.HTTP_401_UNAUTHORIZED)\n # token = list(token)[0]\n # refresh(token)\n # return Response({\n # 'token':token.token,\n # 'refreshtoken':token.refresh_token,\n # 'expires':token.expires,\n # 'user':token.user.username\n # })\n # else:\n # err = 'invalid token'\n # else:\n # return Reponse({'error':'unsupported grant type'})\n # else:\n # err = 'invalid client'\n # return Response({'error/s':err},status= status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['POST'])\ndef revoke(request):\n data = request.data\n err = {}\n if 'client_id' not in data:\n err['client_id'] = 'required'\n if 'client_secret' not in data:\n err['client_secret'] = 'required'\n if 'token' not in data:\n err['token'] = 'required'\n if err:\n return Response({'error/s':err})\n else:\n client = Client.objects.filter(client_id = data['client_id'],client_secret = data['client_secret'])\n if client.exists():\n token = AuthToken.objects.filter(token = data['token'])\n if token.exists() and not token.first().revoked:\n token = list(token)[0]\n token.revoked = True\n token.save()\n return Response({'token':token.token,'revoked':True})\n else:\n err = 'already revoked'\n else:\n err = 'invalid client'\n return Response({'error/s':err})\n","sub_path":"mysite/oauth/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"249238343","text":"import numpy as np\nimport os\nimport re\nimport h5py\nimport subprocess\nfrom spyci import spyci\n\nimport matplotlib.pyplot as plt\n\n\nclass SpiceInterface():\n '''\n A library to interface to Spice simulators (NGSpice, Xyce, Spectre, TSpice etc...)\n\n Contains high level constructs to manipulate and run simulations without relying\n on simulator specfic netlist constructions.\n\n Will be developed into a library to allow for high programmatic control of electronic\n circuit simulation, design and verification. \n '''\n\n def __init__(self, simulator='ngspice', verbose=True, netlist_path=None):\n '''\n Instantiate the object\n '''\n\n # store the setup information internally\n self.config = {}\n self.simulation = {}\n self.config['simulator'] = simulator\n self.config['verbose'] = verbose\n\n # if provided read in the base netlist\n if netlist_path:\n self.read_netlist_file(netlist_path)\n\n\n\n def read_netlist_file(self, netlist_path):\n '''\n Read in a netlist from file\n '''\n\n with open(netlist_path) as f:\n self.simulation['netlist'] = f.read()\n\n\n\n def set_parameters(self, parameters):\n '''\n Set parameters inside the netlist\n\n Parameters should be passed as an array with with sub-arrays with\n the first element parameter string and the second element a value.\n\n ie. [['vds', 1.8], ['vbs', 0.2], ['ids', 1e-6]]\n '''\n\n # keep a list of the of parameter values to print to terminal\n log_information = \"New netlist parameter values: \"\n\n # loop through each parameter updating the value\n for parameter in parameters:\n sub_string = \".param %s=%f\" % (parameter[0], parameter[1])\n self.simulation['netlist'] = re.sub(r'\\.param %s=.*' % parameter[0], sub_string, self.simulation['netlist'])\n\n # append to the log string\n log_information += '%s=%f ' % (parameter[0], parameter[1])\n\n # update user\n if self.config['verbose']:\n print(log_information)\n\n\n\n def set_temp(self, temp):\n '''\n Set the simulation temperature\n '''\n\n # change the temperature in the netlist\n sub_string = \".param temp=%f\" % temp\n self.simulation['netlist'] = re.sub(r'\\.param temp=.*', sub_string, self.simulation['netlist'])\n sub_string = \".temp %f\" % temp\n self.simulation['netlist'] = re.sub(r'\\.temp .*', sub_string, self.simulation['netlist'])\n\n # update user\n if self.config['verbose']:\n log_information = \"New temperature: %f\" % temp\n print(log_information)\n\n\n\n def set_corner(self, corner):\n '''\n Set the simulation corner\n '''\n\n # change the temperature in the netlist\n sub_string = \".lib sky130_fd_pr/models/sky130.lib.spice %s\" % corner\n self.simulation['netlist'] = re.sub(r'\\.lib sky130_fd_pr/models/sky130.lib.spice .*', sub_string, self.simulation['netlist'])\n\n # update user\n if self.config['verbose']:\n log_information = \"New corner: %s\" % corner\n print(log_information)\n\n\n\n def run_simulation(self):\n '''\n Run simulation\n '''\n\n # select the simulation interface to use\n if self.config['simulator'] == 'ngspice':\n\n # write the temporary netlist\n with open('spiceinterface_temp.spice', 'w') as f:\n f.write(self.simulation['netlist'])\n\n # run ngspice\n bash_command = \"ngspice -b -r spiceinterface_temp.raw -o spiceinterface_temp.out spiceinterface_temp.spice\"\n process = subprocess.Popen(bash_command.split(), stdout=subprocess.PIPE)\n output, error = process.communicate()\n\n # check if error occured\n with open('spiceinterface_temp.spice') as f:\n sim_log = f.read()\n if 'fatal' in sim_log:\n print(sim_log)\n\n # read in the results of the simulation\n self.simulation_data = spyci.load_raw(\"spiceinterface_temp.raw\")\n\n else:\n assert False, 'The simulator (%s) is not currently supported' % self.config['simulator'] \n\n\n\n def set_dc_sweep(self, parameter, start, end, number_steps):\n '''\n Set the values for a DC sweep\n '''\n\n # calculate the step size\n step_size = (end - start)/(number_steps-1) \n\n # update the netlist\n sub_string = \".dc %s %0.12f %0.12f %0.12f\" % (parameter, start, end, step_size)\n self.simulation['netlist'] = re.sub(r'\\.dc .*', sub_string, self.simulation['netlist'])\n\n\n\n def get_signal(self, signal_name, factor=1.0):\n '''\n Return a signal from the simulation results\n '''\n\n # find where the node is in the data\n for data_i, data_var in enumerate(self.simulation_data['vars']):\n\n if data_var['name'] == signal_name:\n index = data_i\n\n # extract each data point and convert to real list\n data_real = []\n for n in range(len(self.simulation_data['values'])):\n\n data_real.append(factor*np.real(self.simulation_data['values'][n][index]))\n\n return data_real\n\n\n\n def measure_frequency(self, node, netlist=None, measure_after_factor=None, threshold=0.9, hysteresis=0.05):\n '''\n Measure the frequency from time domain signal\n '''\n\n # extract each data point and convert to real list\n data_real = self.get_signal('v('+node+')')\n analysis_time = self.get_signal('time')\n\n\n # trim the data\n if measure_after_factor:\n data_real = data_real[int(len(data_real)*measure_after_factor):]\n\n # define the high and low thresholds for calculating edges\n threshold_low = threshold - hysteresis\n threshold_high = threshold + hysteresis\n\n # find first rising edge\n for i in range(2,len(data_real)):\n if (float(data_real[i]) > threshold) and (float(data_real[i-1]) > threshold) and (float(data_real[i-2]) < threshold):\n first_index = i\n first_time = analysis_time[i]\n break\n\n # find second rising edge\n for i in range(first_index+3, len(data_real)):\n if (float(data_real[i]) > threshold) and (float(data_real[i-1]) > threshold) and (float(data_real[i-2]) < threshold):\n second_index = i\n second_time = analysis_time[i]\n break\n\n # find third rising edge\n for i in range(second_index+3, len(data_real)):\n if (float(data_real[i]) > threshold) and (float(data_real[i-1]) > threshold) and (float(data_real[i-2]) < threshold):\n third_index = i\n third_time = analysis_time[i]\n break\n\n return 1.0/(third_time-second_time)\n\n\n\n def measure_mos_op(self, device, w, l_list, polarity='nmos', vds=[0,1.8,11], vbs=[0,1.8,11], temp=27, corner='tt'):\n '''\n Measure the operating point of an MOS\n '''\n\n # load the characterisation bench\n self.read_netlist_file('mos_characterise.spice')\n\n # set the MOS name\n self.simulation['netlist'] = re.sub(r'(.*)mos(.*)', r'\\1'+device+r'\\2', self.simulation['netlist'])\n\n # set the temperature and corner\n self.set_temp(temp)\n self.set_corner(corner)\n\n # define the list of op parameters\n op_params = [\"id\", \"vth\", \"vgs\", \"vds\", \"vbs\", \"gm\", \"gds\", \"gmbs\", \"vdsat\", \"cgg\", \"cgs\", \"cgd\", \"cgb\", \"cbs\", \"cdd\"]\n save_string = ''\n for op_param in op_params:\n save_string += '@M.XM.m' + device + '[' + op_param + '] '\n self.simulation['netlist'] = re.sub(r'SAVE_TO_BE_POPULATED', save_string, self.simulation['netlist'])\n\n # create the sweep values\n vds_list = np.linspace(vds[0], vds[1], vds[2])\n vbs_list = np.linspace(vbs[0], vbs[1], vbs[2])\n\n # run an initial simulation to find out how many drain current sweep values are present\n self.run_simulation()\n num_id = len(self.simulation_data['values'])\n\n\n # prepopulate the reuslts dictionary\n op_values = {}\n for param in op_params:\n op_values[param] = np.zeros((len(l_list), len(vds_list), len(vbs_list), num_id))\n\n # loop through each parameter value\n for vbs_i, vbs in enumerate(vbs_list):\n for vds_i, vds in enumerate(vds_list):\n for l_i, l in enumerate(l_list):\n\n # update user\n if self.config['verbose']:\n print('-'*150)\n print('Beginning new OP setting')\n\n # modify the netlist\n parameters = [['vbs', vbs], ['vds', vds], ['l', l]]\n netlist = self.set_parameters(parameters)\n\n # run the simulation\n try:\n self.run_simulation()\n\n # collect the op parameter values\n for data_i, data_var in enumerate(self.simulation_data['vars']):\n\n # try and extract the op parameter - this will fail if the variable is something else\n try:\n op_param = data_var['name'].split('[')[1].split(']')[0]\n\n # extract each data point and convert to real list\n data_real = []\n for n in range(len(self.simulation_data['values'])):\n data_real.append(np.real(self.simulation_data['values'][n][data_i]))\n\n # save the sweep data to the dictionary\n op_values[op_param][l_i][vds_i][vbs_i] = data_real\n\n except IndexError:\n pass\n \n # simulation failed - most likely to MOS being in a weird region\n # just ignore this and move on. the point will be filled with zeros\n except:\n pass\n\n\n # save the data to file\n hdf_file = h5py.File('results/' + device + '.hdf5', 'w')\n for key, values in op_values.items():\n hdf_file.create_dataset(key, data=values)\n\n # save the indexing information\n indexing_group = hdf_file.create_group('indexing')\n indexing = [['vbs', vbs_list], ['vds', vds_list], ['l', l_list]]\n for index in indexing:\n indexing_group.create_dataset(index[0], data=index[1])\n\n\n\n def sweep_parameter(self, parameter, start, end, number_steps, signals, sweeptype='singlestep'):\n '''\n Sweep the temperature and provide the resulting signals\n '''\n\n # start/stop the simulator for each sweep step\n # this is slower but more flexible\n if sweeptype == 'singlestep':\n\n # create temperature list\n parameter_list = np.linspace(start, end, number_steps)\n\n # create a results dictionary\n results = {}\n results[parameter] = parameter_list\n\n # create arrays for the signals\n for signal in signals:\n results[signal] = []\n\n # loop through the temperatures\n for parameter_value in parameter_list:\n\n # update the netlist\n if parameter == 'temp':\n self.set_temp(parameter_value)\n else:\n self.set_parameters([[parameter, float(parameter_value)]])\n\n # run the simulation\n self.run_simulation()\n\n # grab the results\n for signal in signals:\n\n temp_signal = self.get_signal(signal)\n\n # if a single point is returned we don't want unnecessary list depth\n if len(temp_signal) == 1:\n results[signal] = temp_signal[0]\n else:\n results[signal] = temp_signal\n\n # edit the DC sweep commad\n elif sweeptype == 'dcsweep':\n\n # edit the netlist DC sweep command\n self.set_dc_sweep(parameter, start, end, number_steps)\n\n # run the simulation\n self.run_simulation()\n\n # create a results dictionary\n results = {}\n for signal in signals:\n\n if signal == 'temp':\n results[signal] = np.linspace(start, end, number_steps)\n else:\n results[signal] = self.get_signal(signal)\n\n return results","sub_path":"library/python/SpiceInterface.py","file_name":"SpiceInterface.py","file_ext":"py","file_size_in_byte":12858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"626817294","text":"import cv2\nimport numpy as np\nimport math\n\ndef log_transform(img,constant):\n r,c = img.shape\n for i in range(0,r):\n for j in range(0,c):\n img[i,j] = constant*math.log10(1+img[i,j])\n return img\n\nman8 = cv2.imread(\"img/man8.png\",2)\nman8_log_trans = log_transform(man8,75)\ncv2.imwrite(\"img/man8_log_trans.png\",man8_log_trans)\n","sub_path":"imgproc/Lab/python/log_transform.py","file_name":"log_transform.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"490750684","text":"# coding=utf-8\n\nimport multiprocessing\nimport serial\nimport socket\nimport os\nimport fuckargs\nimport json\nimport time\n\ndef get_bit():\n return int( hex( ord( ser.read() ) ), 16 )\n\ndef get_bits( n ):\n s = int( hex( ord( ser.read() ) ), 16 )\n s = [s]\n if n == 1:\n return s\n else:\n return s + get_bits( n-1 )\n\ndef find( head1, head2 ):\n s = get_bit()\n while s != head1:\n s = get_bit()\n s = get_bit()\n if s != head2:\n return find( head1, head2 )\n else:\n return get_bits(9)\n\ndef get_now_result():\n \n # 加速度输出\n axl, axh, ayl, ayh, azl, azh, tl, th, sum = find( 0x55, 0x51 )\n ax = (( axh<<8)|axl)/32768.0*16\n ay = (( ayh<<8)|ayl)/32768.0*16\n az = (( azh<<8)|azl)/32768.0*16\n if az > 16: az = az - 32\n if ax > 16: ax = ax - 32\n if ay > 16: ay = ay - 32\n t1 = ((th<<8)|tl)/340.0 +36.53\n\n # 角速度输出\n axl, axh, ayl, ayh, azl, azh, tl, th, sum = find( 0x55, 0x52 )\n wx = (( axh<<8)|axl)/32768.0*2000\n wy = (( ayh<<8)|ayl)/32768.0*2000\n wz = (( azh<<8)|azl)/32768.0*2000\n if wz > 2000: wz = wz - 4000\n if wx > 2000: wx = wx - 4000\n if wy > 2000: wy = wy - 4000\n t2 = ((th<<8)|tl)/340.0 + 36.53\n\n # 角度输出\n axl, axh, ayl, ayh, azl, azh, tl, th, sum = find( 0x55, 0x53 )\n rx = (( axh<<8)|axl)/32768.0*180\n ry = (( ayh<<8)|ayl)/32768.0*180\n rz = (( azh<<8)|azl)/32768.0*180\n t3 = ((th<<8)|tl)/340.0 + 36.53\n \n # 平均温度\n t = (t1 + t2 + t3) / 3.0\n \n # unix/linux 时间戳\n now = time.time()\n\n res_dict = { \"ax\" : ax, \\\n \"ay\" : ay, \\\n \"az\" : az, \\\n \"wx\" : wx, \\\n \"wy\" : wy, \\\n \"wz\" : wz, \\\n \"rx\" : rx, \\\n \"ry\" : ry, \\\n \"rz\" : rz, \\\n \"temp\" : t, \\\n \"timestamp\" : now }\n\n res_dict_str = json.dumps( res_dict )\n\n return res_dict_str\n\n\n# 串口通讯\n# 频率的决定者以硬件的串口通讯频率决定\ndef get_serial_info( result_str ):\n os.system( \"echo %d >>pid_repo\" % os.getpid() ) # store the pid\n while True:\n result_str.value = get_now_result()\n\n# socket server\ndef socket_server( result_str ):\n os.system( \"echo %d >>pid_repo\" % os.getpid() ) # store the pid\n host = fuckargs.get( \"host\" ) # Symbolic name meaning all available interfaces\n port = int( fuckargs.get(\"port\") ) # Arbitrary non-privileged port\n s = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) #定义socket类型,网络通信,TCP\n s.bind( (host, port) ) #套接字绑定的IP与端口\n s.listen( 5 ) #开始TCP监听\n while True:\n conn, addr = s.accept() #接受TCP连接,并返回新的套接字与IP地址\n # print 'Connected by', addr #输出客户端的IP地址\n try:\n while True:\n data=conn.recv(1024) #把接收的数据实例化\n conn.sendall( result_str.value )\n except:\n conn.close() #关闭连接\n\n# Main process\n\nser = serial.Serial( fuckargs.get(\"usb\"), int( fuckargs.get(\"bits\") ) )\nstring_dict = multiprocessing.Array( \"c\", '{\"ax\":-10000, \"ay\":-10000, \"az\":-10000,\"wx\":-10000,\"wy\":-10000,\"wz\":-10000,\"rx\":-10000,\"ry\":-10000,\"rz\":-10000,\"temp\":-10000,\"timestamp\":-100000000000001450420046.871339}'*3)\n\nos.system( \"echo %d >>pid_repo\" % os.getpid() ) # store the pid\n\np_serial = multiprocessing.Process( target=get_serial_info, args=(string_dict,) )\np_socket = multiprocessing.Process( target=socket_server, args=(string_dict,) )\n\np_serial.start()\np_socket.start()\n","sub_path":"acc/acc_01_for_mac_linux/process_worker.py","file_name":"process_worker.py","file_ext":"py","file_size_in_byte":3639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"445421327","text":"\"\"\"\nQuestion 90\nQuestion\nPlease write a program which count and print the numbers\nof each character in a string input by console.\n\nExample: If the following string is given as input to the program:\n\nabcdefgabc\n\nThen, the output of the program should be:\n\na,2\nc,2\nb,2\ne,1\nd,1\ng,1\nf,1\n\nHints\nUse dict to store key/value pairs. Use dict.get() method to lookup a key with default value.\n\"\"\"\n\ns = input()\n\n# ord() gets the ascii value of a char\nfor letter in range(ord('a'), ord('z')+1):\n # chr() gets the char of an ascii value\n letter = chr(letter)\n cnt = s.count(letter)\n if cnt > 0:\n print(\"{}, {}\".format(letter, cnt))\n","sub_path":"Python-Files/Day-22/Question-90-alternative-solution-2.py","file_name":"Question-90-alternative-solution-2.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"353237114","text":"from KinoApi.models import CustomUser\nfrom rest_framework.parsers import JSONParser\nfrom KinoApi.serializers import UserSerializer, EmailSerializer\nfrom django.views.generic.base import TemplateView\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.authtoken.views import ObtainAuthToken\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\n\n\nclass UserCountView(APIView):\n renderer_classes = (JSONRenderer, )\n\n def get(self, request, pk=None):\n user_count = CustomUser.objects.count()\n content = {'user_count': user_count}\n\n return Response( content, content_type='application/json' )\n\nclass UserAuthView(ObtainAuthToken):\n parser_classes = (JSONParser,)\n renderer_classes = (JSONRenderer, )\n\n def post(self, request, pk=None):\n errors = {}\n \n try:\n email = request.data['email']\n except:\n errors['email'] = 'is required'\n \n try:\n password = request.data['password']\n except:\n errors['password'] = 'is required'\n\n if len(errors.keys()) > 0:\n return Response(\n errors, \n status=status.HTTP_400_BAD_REQUEST, \n content_type='application/json' \n )\n\n try:\n user = CustomUser.objects.get(email=email)\n except Exception as error:\n print(error)\n return Response(\n {'email': 'юзера с таким emailом не существует'}, \n status=status.HTTP_403_FORBIDDEN, \n content_type='application/json' \n )\n\n try:\n valid = user.check_password(password)\n if not valid:\n raise ValueError(\"Password Incorrect\")\n except Exception as error:\n print(error)\n return Response(\n {'password': 'неверный пароль'}, \n status=status.HTTP_403_FORBIDDEN, \n content_type='application/json' \n )\n\n token, created = Token.objects.get_or_create(user=user)\n content = {\n 'token': token.key,\n 'user': {\n 'username': user.username,\n 'id': user.pk,\n 'email': user.email\n }\n }\n return Response(\n content, \n status=status.HTTP_201_CREATED, \n content_type='application/json' \n )\n\nclass UserRegistarationView(APIView):\n parser_classes = (JSONParser,)\n renderer_classes = (JSONRenderer, )\n\n def post(self, request, pk=None):\n try:\n data = {\n 'email': request.data.get('email'),\n 'username': request.data.get('username'),\n 'password': request.data.get('password')\n }\n except:\n return Response(\n {'err': 'не передано одно из полей'}, \n status=status.HTTP_400_BAD_REQUEST, \n content_type='application/json' \n )\n \n serialized = UserSerializer(data=data)\n\n if serialized.is_valid():\n try:\n user = CustomUser.objects.create_user(\n serialized.data['username'],\n serialized.data['email'],\n serialized.data['password']\n )\n except Exception as error:\n print(error)\n return Response(\n {'err': 'юзер уже существует'}, \n status=status.HTTP_400_BAD_REQUEST, \n content_type='application/json' \n )\n token, created = Token.objects.get_or_create(user=user)\n content = {\n 'token': token.key,\n 'user': {\n 'username': user.username,\n 'id': user.pk,\n 'email': user.email\n }\n }\n return Response(\n content, \n status=status.HTTP_201_CREATED, \n content_type='application/json' \n )\n else:\n return Response(\n serialized._errors, \n status=status.HTTP_400_BAD_REQUEST, \n content_type='application/json' \n )\n\n\nclass UserRestorePassView(APIView):\n renderer_classes = (JSONRenderer, )\n\n def get(self, request, pk=None):\n user_count = CustomUser.objects.count()\n content = {'user_count': user_count}\n\n response = Response()\n response['Content-Type'] = 'application/json'\n return Response(content)\n\nclass UserMeView(ObtainAuthToken):\n renderer_classes = (JSONRenderer, )\n\n def get(self, request):\n #print( \n # request.query_params.get('id'),\n # request.META['HTTP_AUTHORIZATION']\n #)\n\n if not('HTTP_AUTHORIZATION' in request.META):\n return Response(\n {'token': 'need this field'}, \n status=status.HTTP_403_FORBIDDEN, \n content_type='application/json' \n )\n\n tokenValue = request.META['HTTP_AUTHORIZATION'].split()[1]\n try:\n token = Token.objects.get(key=tokenValue)\n except:\n return Response(\n {'token': 'user this token not found'}, \n status=status.HTTP_403_FORBIDDEN, \n content_type='application/json' \n )\n\n user = CustomUser.objects.get(pk=token.user_id)\n serialisedUser = UserSerializer(data=user)\n serialisedUser.is_valid()\n\n content = {\n 'user': {\n 'username': user.username,\n 'id': user.id,\n 'email': user.email,\n }\n }\n\n response = Response()\n response['Content-Type'] = 'application/json'\n return Response(content)","sub_path":"KinoApi/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"249222578","text":"# -*- coding: utf-8 -*-\nfrom collections import namedtuple\n\nimport sqlparse\nimport click\n\n\ndef parse_query(query):\n query_info = namedtuple('QueryInfo',\n ('string', 'fields', 'table', 'database'))\n query_info.fields = []\n\n parsed = sqlparse.format(query, keyword_case='upper')\n parsed = sqlparse.parse(parsed)[0]\n tokens = parsed.tokens\n\n if parsed.get_type() != 'SELECT':\n click.echo('Skipping \"%s\": Not a SELECT statement.' % query)\n return\n\n # Valid query type\n query_info.string = str(parsed)\n\n dml, from_, where = _get_key_tokens(tokens)\n token_list = sqlparse.sql.TokenList(tokens)\n\n # Get Fields\n query_info.fields = _get_fields(token_list, dml)\n if not query_info.fields:\n click.echo('Skipping \"%s\": No fields found.' % parsed)\n return\n\n # Get Tables/Databases\n database, table = _get_table_database(token_list, from_)\n if not database:\n click.echo('Skipping \"%s\": Cannot find database')\n return\n query_info.database, query_info.table = database, table\n return query_info\n\n\ndef _get_key_tokens(tokens):\n dml = None\n from_ = None\n where = None\n for token in tokens:\n if str(token.ttype) == 'Token.Keyword.DML':\n dml = token\n continue\n if str(token.ttype) == 'Token.Keyword' and token.value == 'FROM':\n from_ = token\n continue\n if isinstance(token, sqlparse.sql.Where):\n where = token\n return dml, from_, where\n\n\ndef _get_fields(token_list, dml):\n fields = []\n select_index = token_list.token_index(dml)\n field_tokens = token_list.token_next(select_index)\n if isinstance(field_tokens, sqlparse.sql.Identifier):\n fields = [field_tokens.value]\n elif isinstance(field_tokens, sqlparse.sql.IdentifierList):\n for token in field_tokens.get_identifiers():\n fields.append(token.value)\n return fields\n\n\ndef _get_table_database(token_list, from_):\n from_index = token_list.token_index(from_)\n table_tokens = token_list.token_next(from_index)\n table_splitted = table_tokens.value.split('.')\n try:\n database, table = table_splitted[0], table_splitted[1]\n return database, table\n except IndexError:\n return None, None\n","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":2304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"175700296","text":"# -*- coding:utf-8 -*-\n\nimport pymel.core as pm\n\nimport Core_ModelingChecker.checkBase as checkBase\nreload(checkBase)\n\nCLASS_NAME = \"VisibilityOff\"\n\nTITLE = \"Visibility Off\"\nDESCRIPTION = u\"비져블이 꺼져있는 오브젝트를 검사 합니다.\"\nBUTTONS = [\"Check\", \"Select\", \"Visible\"]\n\nclass VisibilityOff(checkBase.CheckBase):\n def __init__(self):\n self.moduleName = CLASS_NAME\n super(VisibilityOff, self).__init__()\n \n def Check(self):\n inVisibileNodes = pm.ls(type= \"transform\", invisible=True)\n defaultCamNodes = self.findDefaultCamera()\n \n nodes = list(set(inVisibileNodes) - set(defaultCamNodes))\n return nodes\n \n def Execute(self, nodes):\n for node in nodes:\n node.visibility.set(True)\n \n\n \n \n ","sub_path":"GMK_ModelingChecker/Check_Modules/visibilityOff.py","file_name":"visibilityOff.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"412155102","text":"# -*- coding: utf-8 -*-\n# @Author: Lu Shaohao(Bravo)\n# @Date: 2019-10-10 20:40:22\n# @Last Modified by: Lu Shaohao(Bravo)\n# @Last Modified time: 2019-10-10 21:26:46\n\nimport argparse\nimport os\nfrom mmdet.apis import init_detector\nfrom detection_api_ei_canshu import BKXQS_detector\nfrom tqdm import tqdm\nimport pickle\nimport sys,cv2\nfrom PIL import Image,ImageFont,ImageDraw\nif __name__ == \"__main__\":\n os.environ['CUDA_VISIBLE_DEVICES']='0'\n argparser = argparse.ArgumentParser(description='test phase')\n argparser.add_argument('-m', type=str, default='/media/zkzx/2dc91e84-4382-41e7-9940-a171405bac53/detection/model_output')\n argparser.add_argument('-t', type=str, default='/media/zkzx/2dc91e84-4382-41e7-9940-a171405bac53/detection')\n args = argparser.parse_args()\n\n model_path = args.m\n test_path = os.path.join(args.t, 'photo')\n rst_path = os.path.join(args.t, 'results')\n #if not os.path.exists(test_path):\n #os.makedirs(test_path)\n if not os.path.exists(rst_path):\n os.makedirs(rst_path)\n\n ckpt_step1 = os.path.join(model_path,'model_output/region', 'epoch_29.pth')\n ckpt_step2 = os.path.join(model_path,'model_output/screw', 'epoch_20.pth')\n #ckpt_step1 = os.path.join(model_path, 'step1.pth')\n #ckpt_step2 = os.path.join(model_path, 'step2.pth')\n pwd = os.path.abspath(os.path.dirname(__file__))\n config_step1 = '%s/configs/rcnn_region.py'%pwd\n config_step2 = '%s/configs/rcnn_screw.py'%pwd\n model_step1 = init_detector(config_step1, ckpt_step1, device='cuda:0')\n model_step2 = init_detector(config_step2, ckpt_step2, device='cuda:0')\n test_imgs = []\n for roots, dirs, files in os.walk(test_path):\n for file in files:\n print(file)\n if file.split('.')[-1] == 'jpg' or file.split('.')[-1] == 'JPG':\n test_imgs.append(os.path.join(roots, file))\n # test_imgs = os.listdir(test_path)\n #print(test_imgs)\n pbar=tqdm(range(len(test_imgs)))\n pkl_rst = []\n labellist= ['JYZ_C_DTC','JYZ_C_BL','JYZ_C_CZ','JYZ_C_FH',\"JYZ_SQZB\",\"JYZ_WDSQZB\"]\n colorSelect={'JYZ_C_DTC': (0, 255, 255), 'JYZ_C_BL': (0, 255, 255), 'JYZ_C_CZ': (0, 255, 255), 'JYZ_C_FH': (0, 255, 255),\n \"JYZ_SQZB\": (0, 0, 255), \"JYZ_WDSQZB\": (0, 0, 255)}\n basedir = os.path.abspath(os.path.dirname(__file__))\n for img_path in test_imgs:\n pbar.update(1)\n try:\n\n pbar.update(1)\n #img_path = img#os.path.join(test_path, img)\n rst = BKXQS_detector(model_step1, model_step2, img_path, thres=0.48, min_size=250)\n img = Image.open(img_path) # cv2.imread(img_path)\n img_Draw = ImageDraw.Draw(img)\n img_font = ImageFont.truetype(os.path.join(basedir, \"simhei.ttf\"), 30, encoding='utf-8')\n red = (255, 0, 0) # (0,0,255)\n #with open(os.path.join(rst_path, rst['fname'] + '.txt'), 'w') as f:\n f_text_dir=img_path.replace(img_path.split('/')[-1], '').replace('jpg','txt').replace('photo','results')\n if not os.path.isdir(f_text_dir):\n os.makedirs(f_text_dir)\n with open(img_path.replace('jpg','txt').replace('photo','results'), 'w') as f:\n for (x0, y0, x1, y1, conf,labelnum) in rst['detections']:\n if conf < 0.76:\n continue\n x0 = int(float(x0))\n y0 = int(float(y0))\n x1 = int(float(x1))\n y1 = int(float(y1))\n f.write('{} {} {} {} {} {}\\n'.format(labellist[int(labelnum)],conf, x0, y0, x1, y1))\n #cv2.rectangle(img,(x0,y0),(x1,y1),(0,0,255),2)\n #cv2.putText(img,'BKXQS',(x0,y0-30),os.path.join(basedir,\"simhei.ttf\"),(0,0,255),2)\n strTxt = labellist[int(labelnum)] + \" %s\"%conf\n img_Draw.text((x0, y0 - 30), strTxt, colorSelect[labellist[int(labelnum)]], font=img_font)\n img_Draw.rectangle((x0, y0, x1, y1), outline=colorSelect[labellist[int(labelnum)]], width=2)\n f.close()\n savedir = img_path.replace(img_path.split('/')[-1], '').replace('photo', 'predicted_jyz_zb')\n savepath = img_path.replace('photo', 'predicted_jyz_zb')\n #print(savepath)\n if not os.path.isdir(savedir):\n os.makedirs(savedir)\n img.save(savepath, quality=95, subsampling=0)\n except Exception as e:\n print(\"%s is broken %s !!!\\n\"%(test_path,e))\n continue\n # #img_path = os.path.join(test_path, img)\n # rst = BKXQS_detector(model_step1, model_step2, img, thres=0.48, min_size=250)\n # pkl_rst.append(rst)\n # with open(os.path.join(rst_path, rst['fname']+'.txt'), 'w') as f:\n # for (x0, y0, x1, y1, conf,labelnum) in rst['detections']:\n # f.write('{} {} {} {} {} {}\\n'.format(labellist[int(labelnum)], conf, int(float(x0)), int(float(y0)),\n # int(float(x1)), int(float(y1))))\n # #f.write('JYZ_ZW {} {} {} {} {}\\n'.format(conf, int(float(x0)), int(float(y0)), int(float(x1)), int(float(y1))))\n with open('test_20191017.pkl', 'wb') as f:\n pickle.dump(pkl_rst , f)\n\n sys.stdout.write('Process end with exit code 0\\n')\n","sub_path":"bin/test_canshujisuan_pl.py","file_name":"test_canshujisuan_pl.py","file_ext":"py","file_size_in_byte":5326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"324116680","text":"#encoding: utf-8\nfrom OpenOrange import *\n\nParentDiscountMap = SuperClass('DiscountMap', \"Master\", __file__)\nclass DiscountMap(ParentDiscountMap): \n buffer = RecordBuffer(\"DiscountMap\")\n \n \n def defaults(self):\n self.Model = 0\n\n def getDiscount(self,artcode,qty,amount=0,weight=0,volume=0):\n \"\"\" If no specific discount is found return the general one \"\"\"\n if (self.Model==0): v = qty\n elif (self.Model==1): v = amount\n elif (self.Model==2): v = weight\n elif (self.Model==3): v = volume\n from Item import Item\n from DiscountMatrix import DiscountMatrix\n i = Item.bring(artcode)\n if not i: \n return None\n for drow in self.DiscountMapRows:\n if (not drow.ItemGroup) or (drow.Type == 1 and drow.ItemGroup==artcode) or (drow.Type == 0 and drow.ItemGroup==i.ItemGroup): \n if (drow.DiscountMatrix and drow.Percent == 0):\n dm = DiscountMatrix.bring(drow.DiscountMatrix)\n if dm:\n return dm.getDiscount(v)\n return drow.Percent\n return self.Discount\n","sub_path":"standard/records/DiscountMap.py","file_name":"DiscountMap.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"281296545","text":"\"\"\"soft reset demo.\"\"\"\n\nfrom nanpy.arduinotree import ArduinoTree\nfrom nanpy.serialmanager import SerialManager\n\n\ndef print_millis(a):\n print ('uptime: %s sec' % (a.api.millis() / 1000.0))\n\n\ndef reset_demo():\n connection = SerialManager()\n a = ArduinoTree(connection=connection)\n print_millis(a)\n print ('soft reset')\n a.soft_reset()\n print_millis(a)\n\nif __name__ == '__main__':\n reset_demo()\n","sub_path":"venv/lib/python3.7/site-packages/nanpy/examples/reset.py","file_name":"reset.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"403111633","text":"'''\r\nCreated on Dec 18, 2017\r\n\r\n@author: xuwang\r\n'''\r\nimport rawpy\r\nimport imageio\r\nimport os\r\nimport argparse\r\n#------------------------------------------------------------------------\r\nap = argparse.ArgumentParser()\r\nap.add_argument(\"-s\", \"--srcPath\", required=True,\r\n help=\"source image folder\")\r\n# ap.add_argument(\"-t\", \"--tgtPath\", required=True,\r\n# help=\"target folder to save the maker list\")\r\nargs = ap.parse_args()\r\nsrcImagePath = args.srcPath\r\n# tgtImagePath = args.tgtPath\r\n#------------------------------------------------------------------------\r\nexten = 'dng'\r\nimList=[]\r\nfor dirpath, dirnames, files in os.walk(srcImagePath):\r\n for name in files:\r\n if name.lower().endswith(exten):\r\n imList.append(os.path.join(dirpath, name))\r\nprint(\"Total images in the path: %d\" % len(imList))\r\nfor img in imList:\r\n with rawpy.imread(img) as raw:\r\n# rgb = raw.postprocess(demosaic_algorithm=None, use_auto_wb=True, output_color = rawpy.ColorSpace.Adobe, half_size=True)\r\n# rgb = raw.postprocess(demosaic_algorithm=rawpy.DemosaicAlgorithm.LINEAR, output_color=rawpy.ColorSpace.sRGB, use_camera_wb=True) # Linear, sRGB\r\n rgb = raw.postprocess(demosaic_algorithm=rawpy.DemosaicAlgorithm.LINEAR, output_color=rawpy.ColorSpace.raw, use_camera_wb=True) # Linear, raw\r\n print(img)\r\n imageio.imsave(img.replace('.dng','.tif'), rgb)\r\n\r\n \r\n","sub_path":"dngConversion.py","file_name":"dngConversion.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"147963960","text":"from __future__ import absolute_import, division, print_function, unicode_literals\n\n#import logging\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nfrom matplotlib import pyplot as plt\n#%matplotlib inline\n\nimport yaml\nimport sys\n\nfrom madminer.core import MadMiner\nfrom madminer.delphes import DelphesProcessor\nfrom madminer.sampling import combine_and_shuffle\nfrom madminer.sampling import SampleAugmenter\nfrom madminer.sampling import constant_benchmark_theta, multiple_benchmark_thetas, random_morphing_thetas,constant_morphing_theta\nfrom madminer.ml import MLForge\nfrom madminer.plotting import plot_2d_morphing_basis, plot_distributions\n\n#tunning for evaluation\ninputs_file = sys.argv[1] \nwith open(inputs_file) as f:\n inputs = yaml.safe_load(f)\n\nmethod = str(inputs['method'])\n\n#folder with trained files\neval_folder_path = str(sys.argv[2]) \n\n#configurate file \nh5_file = sys.argv[3]\n\n\n#create test sample\nsa = SampleAugmenter(h5_file) #'data/madminer_example_shuffled.h5'\n\ntest=inputs['test_samples']\n_ = sa.extract_samples_test(\n theta=eval(test['sampling_method'])(test['argument']),\n n_samples=int(test['nsamples']), #change too\n folder='/home/data/test',\n filename='test'\n)\n\n#evaluate\nforge = MLForge() #Estimator() v.0.3\nforge.load(eval_folder_path+'/'+method) #'methods/alices'\n\n\n#?\ntheta_denom = np.array([[0.,0.]])\nnp.save('/home/data/test/theta_ref.npy', theta_denom)\n\n\n#perform the test + evaluation score acconding to method\nif( method in ['alice', 'alices', 'carl', 'nde', 'rascal', 'rolr', 'scandal'] ):\n\t\n\t#make and save grid\n\tevaluation = inputs['evaluation']['theta_each']\n\ttheta_each = np.linspace( float(evaluation['start']), float(evaluation['stop']), int(evaluation['num']) ) \n\ttheta0, theta1 = np.meshgrid(theta_each, theta_each)\n\ttheta_grid = np.vstack((theta0.flatten(), theta1.flatten())).T #numtidim\n\tnp.save('/home/data/test/theta_grid.npy', theta_grid)\n\n\tlog_r_hat, score_theta0, _ = forge.evaluate(\n\t theta0_filename='/home/data/test/theta_grid.npy',\n\t x='/home/data/test/x_test.npy',\n\t evaluate_score=inputs['evaluation']['evaluate_score']\n\t)\n\twith open('/home/data/test/log_r_hat_'+method+'.npy', \"w+\") as f: #create file\n\t\tnp.save(file='/home/data/test/log_r_hat_'+method, arr=log_r_hat)\n\t\n\twith open('/home/data/test/score_theta0_'+method+'.npy', \"w+\") as g: #create file\n\t\tnp.save(file='/home/data/test/score_theta0_'+method, arr=score_theta0)\n\t\n\n\t#plots\n\tif( bool(inputs['plots']['activate']) ):\n\t\t\n\t\tbin_size = theta_each[1] - theta_each[0]\n\t\tedges = np.linspace(theta_each[0] - bin_size/2, theta_each[-1] + bin_size/2, len(theta_each)+1)\n\n\t\tfig = plt.figure(figsize=(6,5))\n\t\tax = plt.gca()\n\n\t\texpected_llr = np.mean(log_r_hat,axis=1)\n\t\tbest_fit = theta_grid[np.argmin(-2.*expected_llr)]\n\n\t\tcmin, cmax = np.min(-2*expected_llr), np.max(-2*expected_llr)\n\t\t \n\t\tpcm = ax.pcolormesh(edges, edges, -2. * expected_llr.reshape((21,21)),\n\t\t norm=matplotlib.colors.Normalize(vmin=cmin, vmax=cmax),\n\t\t cmap='viridis_r')\n\t\tcbar = fig.colorbar(pcm, ax=ax, extend='both')\n\n\t\tplt.scatter(best_fit[0], best_fit[1], s=80., color='black', marker='*')\n\n\t\tplt.xlabel(r'$\\theta_0$')\n\t\tplt.ylabel(r'$\\theta_1$')\n\t\tcbar.set_label(r'$\\mathbb{E}_x [ -2\\, \\log \\,\\hat{r}(x | \\theta, \\theta_{SM}) ]$')\n\n\t\tplt.tight_layout()\n\t\tplt.savefig('/home/plots/expected_llr_'+method+'.png')\t\n\n\nif( method in ['alice2', 'alices2', 'carl2', 'rascal2', 'rolr2' ] ):\n\tprint('evaluation for this method is not yet implemented')\n\tpass \n\n\t#make and save grid\n\tevaluation = inputs['evaluation']['theta_each']\n\ttheta_each = np.linspace( float(evaluation['start']), float(evaluation['stop']), int(evaluation['num']) ) \n\ttheta0, theta1 = np.meshgrid(theta_each, theta_each)\n\ttheta_grid = np.vstack((theta0.flatten(), theta1.flatten())).T #numtidim\n\tnp.save('/home/data/test/theta_grid.npy', theta_grid)\n\n\tlog_r_hat, score_theta0, score_theta1 = forge.evaluate(\n\t theta0_filename='/home/data/test/theta_grid.npy',\n\t theta1_filename='/home/data/test/theta_grid.npy', #TO DO !\n\t x='/home/data/test/x_test.npy',\n\t evaluate_score=False\n\t)\n\twith open('/home/data/test/log_r_hat_'+method+'.npy', \"w+\") as f: #create file\n\t\tnp.save(file='/home/data/test/log_r_hat_'+method, arr=log_r_hat)\t\t\n\n\nif( method in ['sally', 'sallino'] ):\n\tt_hat = forge.evaluate(\n \tx='/home/data/samples/x_test.npy'\n\t)\n\twith open('/home/data/test/t_hat_'+method+'.npy', \"w+\") as f: #create file\n\t\tnp.save(file='/home/data/test/t_hat_'+method, arr=t_hat)\n\n\t#plots\n\tif( bool(inputs['plots']['activate']) ):\n\t\tx = np.load('data/samples/x_test.npy')\n\t\tfig = plt.figure(figsize=(10,4))\n\n\t\tfor i in range(2):\n\t\t\tax = plt.subplot(1,2,i+1)\n\t\t\tsc = plt.scatter(x[::10,0], x[::10,1], c=t_hat[::10,i], s=10., cmap='viridis', vmin=-0.8, vmax=0.4)\n\t\t\tcbar = plt.colorbar(sc)\n\t\t\tcbar.set_label(r'$\\hat{t}_' + str(i) + r'(x | \\theta_{ref})$')\n\t\t\tplt.xlabel(r'$p_{T,j1}$ [GeV]')\n\t\t\tplt.ylabel(r'$\\Delta \\phi_{jj}$')\n\t\t\tplt.xlim(10.,400.)\n\t\t\tplt.ylim(-3.15,3.15)\n\t\t\tplt.tight_layout()\n\t\t\tplt.savefig('/home/plots/t_hat_'+method+'.png')\t\n\n\n#Fisher ifnormation\nif( bool(inputs['fisher_information']['activate']) and method in ['sally'] ):\n\tfisher = inputs['fisher_information']\n\tfisher = FisherInformation(h5_file)\n\n\tfisher_information, _ = fisher.calculate_fisher_information_full_detector(\n\t theta=fisher['theta'],\n\t model_file=eval_folder_path+'/sally',\n\t unweighted_x_sample_file='/home/data/samples/x_test.npy',\n\t luminosity=float(fisher['luminosity'])\n\t)\n\tprint('Kinematic Fisher information after {} ifb:\\n{}'.format(float(fisher['luminosity']), fisher_information))\n\n\t#plots\n\tif( bool(inputs['plots']['activate']) ):\n\t\t#1\n\t\tplot_fisher_contour = plot_fisher_information_contours_2d(\n\t\t [fisher_information],\n\t\t xrange=(-1,1),\n\t\t yrange=(-1,1)\n\t\t)\n\t\tplot_fisher_contour.savefig('/home/plots/plot_fisher_contour.png')\n\t\t\n\t\t#2\n\t\tprint('plot_distribution_of_information yer to be implemented')\n\t\tpass\n\t\tplot_fisher_distr = plot_distribution_of_information(\n\t\t\t[fisher_information_matrices],\n\t\t\txbins=None, \n\t\t\txsecs=None,\n\t\t)\n\t\t\n\t\tplot_fisher_distr.savefig('/home/plots/plot_fisher_distr.png')","sub_path":"docker-madminer-ml/code/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":6164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"502747711","text":"from .models import Project, Issue, WikiPage\nfrom .widgets import CustomDateInput\nfrom pagedown.widgets import PagedownWidget\nfrom django.forms import ModelForm\nfrom django.contrib.auth import get_user_model\n\nUser = get_user_model()\n\nclass ProjectForm(ModelForm):\n class Meta(object):\n model = Project\n fields = ['name', 'description', 'organisation']\n widgets = {\n 'description': PagedownWidget(),\n }\n\n def __init__(self, *args, **kwargs):\n super(ProjectForm, self).__init__(*args, **kwargs)\n for field in self.fields:\n self.fields[field].widget.attrs={'class':'form-control'}\n\n\nclass IssueForm(ModelForm):\n class Meta(object):\n model = Issue\n exclude = ['created_at', 'project']\n widgets = {\n 'deadline': CustomDateInput(),\n 'description': PagedownWidget(),\n }\n\n def __init__(self, *args, **kwargs):\n super(IssueForm, self).__init__(*args, **kwargs)\n for field in self.fields:\n self.fields[field].widget.attrs={'class':'form-control'}\n self.fields['assignee'].queryset = User.objects.order_by('username')\n\n\nclass WikiPageForm(ModelForm):\n class Meta(object):\n model = WikiPage\n exclude = ['project']\n widgets = {\n 'content': PagedownWidget(),\n }\n\n def __init__(self, *args, **kwargs):\n super(WikiPageForm, self).__init__(*args, **kwargs)\n for field in self.fields:\n self.fields[field].widget.attrs={'class':'form-control'}\n","sub_path":"todolist/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"633677200","text":"\nimport unittest\n\n# The Customer class\n# The Customer class represents a customer who will order from the stalls.\nclass Customer: \n # Constructor\n def __init__(self, name, wallet = 100):\n self.name = name\n self.wallet = wallet\n\n # Reload some deposit into the customer's wallet.\n def reload_money(self,deposit):\n self.wallet += deposit\n\n # The customer orders the food and there could be different cases \n def validate_order(self, cashier, stall, item_name, quantity):\n if not(cashier.has_stall(stall)):\n print(\"Sorry, we don't have that vendor stall. Please try a different one.\")\n elif not(stall.has_item(item_name, quantity)): \n print(\"Our stall has run out of \" + item_name + \" :( Please try a different stall!\")\n elif self.wallet < stall.compute_cost(quantity): \n print(\"Don't have enough money for that :( Please reload more money!\")\n else:\n bill = cashier.place_order(stall, item_name, quantity) \n self.submit_order(cashier, stall, bill) \n \n # Submit_order takes a cashier, a stall and an amount as parameters, \n # it deducts the amount from the customer’s wallet and calls the receive_payment method on the cashier object\n def submit_order(self, cashier, stall, amount): \n self.wallet -= amount\n cashier.receive_payment(stall, amount) \n\n # The __str__ method prints the customer's information. \n def __str__(self):\n return \"Hello! My name is \" + self.name + \". I have $\" + str(self.wallet) + \" in my payment card.\"\n\n\n# The Cashier class\n# The Cashier class represents a cashier at the market. \nclass Cashier:\n\n # Constructor\n def __init__(self, name, directory =[]):\n self.name = name\n self.directory = directory[:] # make a copy of the directory\n\n # Whether the stall is in the cashier's directory\n def has_stall(self, stall):\n return stall in self.directory\n\n # Adds a stall to the directory of the cashier.\n def add_stall(self, new_stall):\n self.directory.append(new_stall)\n\n # Receives payment from customer, and adds the money to the stall's earnings.\n def receive_payment(self, stall, money):\n stall.earnings += money\n\n # Places an order at the stall.\n\t# The cashier pays the stall the cost.\n\t# The stall processes the order\n\t# Function returns cost of the order, using compute_cost method\n def place_order(self, stall, item, quantity):\n stall.process_order(item, quantity)\n return stall.compute_cost(quantity) \n \n # string function.\n def __str__(self):\n\n return \"Hello, this is the \" + self.name + \" cashier. We take preloaded market payment cards only. We have \" + str(sum([len(category) for category in self.directory.values()])) + \" vendors in the farmers' market.\"\n\n## Complete the Stall class here following the instructions in HW_4_instructions_rubric\nclass Stall:\n \n def __init__(self, name, inventory, cost = 7, earnings = 0):\n self.name = name\n self.inventory = inventory\n self.cost = cost\n self.earnings = earnings\n\n def process_order(self, item_name, quantity): \n if (self.has_item(item_name, quantity)): \n self.inventory[item_name] -= quantity #Anything to add???\n\n def has_item(self, item_name, quantity):\n enough_food = False\n if(item_name in self.inventory): \n if(self.inventory[item_name] >= quantity):\n enough_food = True\n return enough_food\n\n def stock_up(self, item_name, quantity):\n if(item_name in self.inventory):\n self.inventory[item_name] += quantity\n else:\n self.inventory[item_name] = quantity\n\n def compute_cost(self, quantity):\n return self.cost * quantity\n\n def __str__(self): \n keys_list = list(self.inventory.keys())\n keys_string = \", \".join(keys_list)\n return \"Hello, we are \" + self.name + \". This is the current menu \" + keys_string + \". We charge $\" + str(self.cost) + \" per item. We have $\" + str(self.earnings) + \" in total.\"\n\n\nclass TestAllMethods(unittest.TestCase):\n \n def setUp(self):\n inventory = {\"Burger\":40, \"Taco\":50}\n self.f1 = Customer(\"Ted\")\n self.f2 = Customer(\"Morgan\", 150)\n self.s1 = Stall(\"The Grill Queen\", inventory, cost = 10)\n self.s2 = Stall(\"Tamale Train\", inventory, cost = 9)\n self.s3 = Stall(\"The Streatery\", inventory)\n self.c1 = Cashier(\"West\")\n self.c2 = Cashier(\"East\")\n #the following codes show that the two cashiers have the same directory\n for c in [self.c1, self.c2]:\n for s in [self.s1,self.s2,self.s3]:\n c.add_stall(s)\n\n\t## Check to see whether constructors work\n def test_customer_constructor(self):\n self.assertEqual(self.f1.name, \"Ted\")\n self.assertEqual(self.f2.name, \"Morgan\")\n self.assertEqual(self.f1.wallet, 100)\n self.assertEqual(self.f2.wallet, 150)\n\n\t## Check to see whether constructors work\n def test_cashier_constructor(self):\n self.assertEqual(self.c1.name, \"West\")\n #cashier holds the directory - within the directory there are three stalls\n self.assertEqual(len(self.c1.directory), 3) \n\n\t## Check to see whether constructors work\n def test_truck_constructor(self):\n self.assertEqual(self.s1.name, \"The Grill Queen\")\n self.assertEqual(self.s1.inventory, {\"Burger\":40, \"Taco\":50})\n self.assertEqual(self.s3.earnings, 0)\n self.assertEqual(self.s2.cost, 9)\n\n\t# Check that the stall can stock up properly.\n def test_stocking(self):\n inventory = {\"Burger\": 10}\n s4 = Stall(\"Misc Stall\", inventory)\n\n\t\t# Testing whether stall can stock up on items\n self.assertEqual(s4.inventory, {\"Burger\": 10})\n s4.stock_up(\"Burger\", 30)\n self.assertEqual(s4.inventory, {\"Burger\": 40})\n \n def test_make_payment(self):\n\t\t# Check to see how much money there is prior to a payment\n previous_custormer_wallet = self.f2.wallet\n previous_earnings_stall = self.s2.earnings\n \n self.f2.submit_order(self.c1, self.s2, 30)\n\n\t\t# See if money has changed hands\n self.assertEqual(self.f2.wallet, previous_custormer_wallet - 30)\n self.assertEqual(self.s2.earnings, previous_earnings_stall + 30)\n\n\n\t# Check to see that the server can serve from the different stalls\n def test_adding_and_serving_stall(self):\n c3 = Cashier(\"North\", directory = [self.s1, self.s2])\n self.assertTrue(c3.has_stall(self.s1))\n self.assertFalse(c3.has_stall(self.s3)) \n c3.add_stall(self.s3)\n self.assertTrue(c3.has_stall(self.s3))\n self.assertEqual(len(c3.directory), 3)\n\n\n\t# Test that computed cost works properly.\n def test_compute_cost(self):\n #what's wrong with the following statements?\n #can you correct them?\n self.assertEqual(self.s1.compute_cost(5), 50)\n self.assertEqual(self.s3.compute_cost(6), 42)\n\n\t# Check that the stall can properly see when it is empty\n def test_has_item(self):\n # Set up to run test cases\n inventory = {\"Chicken Nuggets\":40, \"Fries\":50, \"Salad\":25}\n s5 = Stall(\"Misc Stall #2\", inventory)\n\n # Test to see if has_item returns True when a stall has enough items left\n # Please follow the instructions below to create three different kinds of test cases \n # Test case 1: the stall does not have this food item: \n self.assertEqual(s5.has_item(\"Onion Rings\", 10), False) \n \n # Test case 2: the stall does not have enough food item: \n self.assertEqual(s5.has_item(\"Fries\", 55), False)\n \n # Test case 3: the stall has the food item of the certain quantity: \n self.assertEqual(s5.has_item(\"Chicken Nuggets\", 40), True)\n\n\t# Test validate order\n def test_validate_order(self): \n inventory = {\"Grilled Cheese Sandwich\":50, \"Onion Rings\":30, \"Bacon Fries\":10} \n f3 = Customer(\"Dahlia\")\n s6 = Stall(\"Misc Stall #3\", inventory, cost = 8)\n s7 = Stall(\"Misc Stall #4\", inventory, cost = 9)\n c4 = Cashier(\"Jack\", [s6])\n before_custormer_wallet = f3.wallet\n before_earnings_stall_1 = s6.earnings\n before_earnings_stall_2 = s7.earnings\n\n\t\t# case 1: test if a customer doesn't have enough money in their wallet to order\n f3.validate_order(c4, s6, \"Onion Rings\", 13)\n self.assertEqual(f3.wallet, before_custormer_wallet) # See if the customer's money has remained the same\n self.assertEqual(s6.earnings, before_earnings_stall_1) # See if the stall still has zero earnings\n self.assertEqual(s6.inventory, inventory) # See if the stall's inventory has remained the same \n\n\t\t# case 2: test if the stall doesn't have enough food left in stock\n f3.validate_order(c4, s6, \"Bacon Fries\", 11)\n self.assertEqual(f3.wallet, before_custormer_wallet) # See if the customer's money has remained the same\n self.assertEqual(s6.earnings, before_earnings_stall_1) # See if the stall still has zero earnings\n self.assertEqual(s6.inventory, inventory) # See if the stall's inventory has remained the same \n\n\t\t# case 3: check if the cashier can order item from that stall\n f3.validate_order(c4, s7, \"Grilled Cheese Sandwich\", 5)\n self.assertEqual(f3.wallet, before_custormer_wallet) # See if the customer's money has remained the same\n self.assertEqual(s7.earnings, before_earnings_stall_2) # See if the stall still has zero earnings\n self.assertEqual(s6.inventory, inventory) # See if the stall's inventory has remained the same \n\n # case 4: test if the customer succesfully places the order\n f3.validate_order(c4, s6, \"Grilled Cheese Sandwich\", 5)\n self.assertEqual(f3.wallet, before_custormer_wallet - 40) # See if the customer's money has decreased\n self.assertEqual(s6.earnings, before_earnings_stall_2 + 40) # See if the stall has made earnings\n self.assertEqual(s6.inventory, {\"Grilled Cheese Sandwich\":45, \"Onion Rings\":30, \"Bacon Fries\":10}) # See if the stall's inventory has decreased\n \n # Test if a customer can add money to their wallet\n def test_reload_money(self):\n f4 = Customer(\"Rachel\")\n past_custormer_wallet = f4.wallet\n f4.reload_money(100)\n self.assertEqual(f4.wallet, past_custormer_wallet + 100)\n \n### Write main function\ndef main():\n #Create different objects \n inventory_1 = {\"Corn Dog\":35, \"Elephant Ear\":40, \"Cheese Curds\": 70, \"Poutine\": 55}\n inventory_2 = {\"Cotton Candy\":65, \"Candied Apple\":30, \"Fried Oreos\": 45}\n customer_1 = Customer(\"Anna\", 125)\n customer_2 = Customer(\"Madison\", 70)\n stall_1 = Stall(\"Fair Foods #1\", inventory_1, 10, 625)\n stall_2 = Stall(\"Fair Foods #2\", inventory_2, 5, 500)\n cashier_1 = Cashier(\"Roger\", [stall_1])\n cashier_2 = Cashier(\"Greg\", [stall_2])\n\n #Try all cases in the validate_order function\n #Below you need to have *each customer instance* try the four cases\n #case 1: the cashier does not have the stall \n customer_1.validate_order(cashier_1, stall_2, \"Candied Apple\", 3)\n customer_2.validate_order(cashier_2, stall_1, \"Cheese Curds\", 10)\n \n #case 2: the casher has the stall, but not enough ordered food or the ordered food item\n customer_1.validate_order(cashier_1, stall_1, \"Corn Dog\", 40)\n customer_2.validate_order(cashier_2, stall_2, \"Fried Oreos\", 50)\n \n #case 3: the customer does not have enough money to pay for the order: \n customer_1.validate_order(cashier_1, stall_1, \"Elephant Ear\", 13)\n customer_2.validate_order(cashier_2, stall_2, \"Candied Apple\", 15)\n \n #case 4: the customer successfully places an order\n customer_1.validate_order(cashier_1, stall_1, \"Poutine\", 5)\n customer_2.validate_order(cashier_2, stall_2, \"Cotton Candy\", 10)\n\nif __name__ == \"__main__\":\n\tmain()\n\tprint(\"\\n\")\n\tunittest.main(verbosity = 2)\n","sub_path":"hw4.py","file_name":"hw4.py","file_ext":"py","file_size_in_byte":12022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"483671034","text":"from django import forms\nfrom my_project.estoque.models import Equipamento\n\n\nCEANORTE= (\n (\"PEDRO\"),\n (\"RAISSA\"),\n (\"JOSUÉ\"),\n )\n\nclass CeanorteForm(forms.Form):\n pessoa = forms.ChoiceField(choices=CEANORTE, required=True, label=\"\", initial='', widget=forms.Select())","sub_path":"my_project/frentecaixaold/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"296415202","text":"import pandas as pd\r\n\r\ndummyCounter = 0\r\n'''\r\nThe list of all the teams in Turkish League and the list of excel files that stores the data about their players.\r\n'''\r\nTurkishLeague = [\"Alanyaspor\", \"Ankaragücü\", \"Antalyaspor\", \"Beşiktaş\", \"Çaykur Rizespor\", \"Denizlispor\",\r\n \"Fenerbahçe\", \"Galatasaray SK\", \"Gazişehir Gaziantep\", \"Gençlerbirliği\", \"Göztepe SK\",\r\n \"İstanbul Başakşehir\", \"Kasımpaşa\", \"Kayserispor\", \"Konyaspor\",\r\n \"Sivasspor\", \"Trabzonspor\", \"Yeni Malatyaspor\"]\r\ntslFiles = [f\"Spor Toto Super League/{i}.xlsx\" for i in TurkishLeague]\r\n\r\n\r\n'''\r\nPlayer class that keeps the information about player's abilities, ratings and statistics.\r\n'''\r\n\r\n\r\nclass Player:\r\n def __init__(self, excel, index):\r\n self.name = excel.iloc[index][0].split(\"-\")[0]\r\n self.position = excel.iloc[index][1].split(\" - \")\r\n self.nation = excel.iloc[index][2]\r\n self.club = excel.iloc[index][3]\r\n self.age = excel.iloc[index][4]\r\n self.finishing = excel.iloc[index][5]\r\n self.dribbling = excel.iloc[index][6]\r\n self.firstTouch = excel.iloc[index][7]\r\n self.heading = excel.iloc[index][8]\r\n self.corners = excel.iloc[index][9]\r\n self.marking = excel.iloc[index][10]\r\n self.crossing = excel.iloc[index][11]\r\n self.passing = excel.iloc[index][12]\r\n self.penalty = excel.iloc[index][13]\r\n self.freeKick = excel.iloc[index][14]\r\n self.technique = excel.iloc[index][15]\r\n self.tackling = excel.iloc[index][16]\r\n self.longShots = excel.iloc[index][17]\r\n self.longThrows = excel.iloc[index][18]\r\n self.aggression = excel.iloc[index][19]\r\n self.bravery = excel.iloc[index][20]\r\n self.workRate = excel.iloc[index][21]\r\n self.decisions = excel.iloc[index][22]\r\n self.determination = excel.iloc[index][23]\r\n self.concentration = excel.iloc[index][24]\r\n self.leadership = excel.iloc[index][25]\r\n self.anticipation = excel.iloc[index][26]\r\n self.flair = excel.iloc[index][27]\r\n self.positioning = excel.iloc[index][28]\r\n self.composure = excel.iloc[index][29]\r\n self.teamWork = excel.iloc[index][30]\r\n self.offTheBall = excel.iloc[index][31]\r\n self.vision = excel.iloc[index][32]\r\n self.agility = excel.iloc[index][33]\r\n self.stamina = excel.iloc[index][34]\r\n self.balance = excel.iloc[index][35]\r\n self.strength = excel.iloc[index][36]\r\n self.pace = excel.iloc[index][37]\r\n self.acceleration = excel.iloc[index][38]\r\n self.fitness = excel.iloc[index][39]\r\n self.jumping = excel.iloc[index][40]\r\n self.height = excel.iloc[index][41]\r\n self.skills = [self.finishing, self.dribbling, self.firstTouch, self.heading, self.marking, self.crossing,\r\n self.passing, self.technique, self.tackling, self.longShots, self.vision]\r\n self.mentals = [self.aggression, self.bravery, self.workRate, self.decisions, self.determination,\r\n self.anticipation, self.positioning, self.composure, self.teamWork, self.offTheBall]\r\n self.physical = [self.agility, self.balance, self.strength, self.pace,\r\n self.acceleration, self.jumping, self.stamina]\r\n self.rating = Player.positionRating(self, self.position)\r\n self.goalScored = 0\r\n self.assists = 0\r\n self.matchesPlayed = 0\r\n\r\n\r\n \"\"\"\r\n Attributes that are needed in match. \r\n \r\n lastPosition --> The last position the player has been registered.\r\n \r\n Everything else is statistical.\r\n \"\"\"\r\n\r\n\r\n\r\n\r\n\r\n # Calculates the players rating with the given position of the player and returns a dictionary which the keys are\r\n # the positions and the values are the ratings. The method of calculating is multiplying every single ability of the\r\n # player with an amount that has been chosen accordingly to its importance. Since the mental abilities are less\r\n # important than abilities that are directly about the ball, they have lower impact to player's rating.\r\n def positionRating(self, positions):\r\n recipe = pd.read_excel(\"ratingRecipe.xlsx\", engine=\"openpyxl\")\r\n ratings = {}\r\n for position in positions:\r\n if \"RB\" in position or \"LB\" in position:\r\n sumOfSkills = 0\r\n sumOfMentals = 0\r\n sumOfPhysical = 0\r\n for i in range(len(self.skills)):\r\n x = self.skills[i] * recipe.iloc[i][1]\r\n sumOfSkills += x\r\n skillRating = (sumOfSkills / recipe.iloc[11][1]) * 5\r\n for i in range(len(self.mentals)):\r\n x = self.mentals[i] * recipe.iloc[i + 19][1]\r\n sumOfMentals += x\r\n mentalRating = (sumOfMentals / recipe.iloc[29][1]) * 5\r\n for i in range(len(self.physical)):\r\n x = self.physical[i] * recipe.iloc[i + 30][1]\r\n sumOfPhysical += x\r\n physicalRating = (sumOfPhysical / recipe.iloc[37][1]) * 5\r\n rating = (skillRating * 0.43) + (mentalRating * 0.27) + (physicalRating * 0.30)\r\n if position == \"RB\":\r\n ratings[\"RB\"] = round(rating, 2)\r\n else:\r\n ratings[\"LB\"] = round(rating, 2)\r\n\r\n elif \"CB\" in position:\r\n sumOfSkills = 0\r\n sumOfMentals = 0\r\n sumOfPhysical = 0\r\n for i in range(len(self.skills)):\r\n x = self.skills[i] * recipe.iloc[i][2]\r\n sumOfSkills += x\r\n skillRating = (sumOfSkills / recipe.iloc[11][2]) * 5\r\n for i in range(len(self.mentals)):\r\n x = self.mentals[i] * recipe.iloc[i + 19][2]\r\n sumOfMentals += x\r\n mentalRating = (sumOfMentals / recipe.iloc[29][2]) * 5\r\n for i in range(len(self.physical)):\r\n x = self.physical[i] * recipe.iloc[i + 30][2]\r\n sumOfPhysical += x\r\n physicalRating = (sumOfPhysical / recipe.iloc[37][2]) * 5\r\n rating = (skillRating * 0.35) + (mentalRating * 0.30) + (physicalRating * 0.35)\r\n rating += (int(self.height[:3]) - 190) * 0.10\r\n ratings[\"CB\"] = round(rating, 2)\r\n\r\n elif \"CDM\" in position:\r\n sumOfSkills = 0\r\n sumOfMentals = 0\r\n sumOfPhysical = 0\r\n for i in range(len(self.skills)):\r\n x = self.skills[i] * recipe.iloc[i][3]\r\n sumOfSkills += x\r\n skillRating = (sumOfSkills / recipe.iloc[11][3]) * 5\r\n for i in range(len(self.mentals)):\r\n x = self.mentals[i] * recipe.iloc[i + 19][3]\r\n sumOfMentals += x\r\n mentalRating = (sumOfMentals / recipe.iloc[29][3]) * 5\r\n for i in range(len(self.physical)):\r\n x = self.physical[i] * recipe.iloc[i + 30][3]\r\n sumOfPhysical += x\r\n physicalRating = (sumOfPhysical / recipe.iloc[37][3]) * 5\r\n rating = (skillRating * 0.40) + (mentalRating * 0.26) + (physicalRating * 0.34)\r\n ratings[\"CDM\"] = round(rating, 2)\r\n\r\n elif \"CM\" in position:\r\n sumOfSkills = 0\r\n sumOfMentals = 0\r\n sumOfPhysical = 0\r\n for i in range(len(self.skills)):\r\n x = self.skills[i] * recipe.iloc[i][4]\r\n sumOfSkills += x\r\n skillRating = (sumOfSkills / recipe.iloc[11][4]) * 5\r\n for i in range(len(self.mentals)):\r\n x = self.mentals[i] * recipe.iloc[i + 19][4]\r\n sumOfMentals += x\r\n mentalRating = (sumOfMentals / recipe.iloc[29][4]) * 5\r\n for i in range(len(self.physical)):\r\n x = self.physical[i] * recipe.iloc[i + 30][4]\r\n sumOfPhysical += x\r\n physicalRating = (sumOfPhysical / recipe.iloc[37][4]) * 5\r\n rating = (skillRating * 0.45) + (mentalRating * 0.27) + (physicalRating * 0.28)\r\n ratings[\"CM\"] = round(rating, 2)\r\n\r\n elif \"RM\" in position or \"LM\" in position:\r\n sumOfSkills = 0\r\n sumOfMentals = 0\r\n sumOfPhysical = 0\r\n for i in range(len(self.skills)):\r\n x = self.skills[i] * recipe.iloc[i][5]\r\n sumOfSkills += x\r\n skillRating = (sumOfSkills / recipe.iloc[11][5]) * 5\r\n for i in range(len(self.mentals)):\r\n x = self.mentals[i] * recipe.iloc[i + 19][5]\r\n sumOfMentals += x\r\n mentalRating = (sumOfMentals / recipe.iloc[29][5]) * 5\r\n for i in range(len(self.physical)):\r\n x = self.physical[i] * recipe.iloc[i + 30][5]\r\n sumOfPhysical += x\r\n physicalRating = (sumOfPhysical / recipe.iloc[37][5]) * 5\r\n rating = (skillRating * 0.43) + (mentalRating * 0.23) + (physicalRating * 0.34)\r\n\r\n if position == \"RM\":\r\n ratings[\"RM\"] = round(rating, 2)\r\n else:\r\n ratings[\"LM\"] = round(rating, 2)\r\n\r\n elif \"CAM\" in position:\r\n sumOfSkills = 0\r\n sumOfMentals = 0\r\n sumOfPhysical = 0\r\n for i in range(len(self.skills)):\r\n x = self.skills[i] * recipe.iloc[i][6]\r\n sumOfSkills += x\r\n skillRating = (sumOfSkills / recipe.iloc[11][6]) * 5\r\n for i in range(len(self.mentals)):\r\n x = self.mentals[i] * recipe.iloc[i + 19][6]\r\n sumOfMentals += x\r\n mentalRating = (sumOfMentals / recipe.iloc[29][6]) * 5\r\n for i in range(len(self.physical)):\r\n x = self.physical[i] * recipe.iloc[i + 30][6]\r\n sumOfPhysical += x\r\n physicalRating = (sumOfPhysical / recipe.iloc[37][6]) * 5\r\n rating = (skillRating * 0.48) + (mentalRating * 0.29) + (physicalRating * 0.23)\r\n ratings[\"CAM\"] = round(rating, 2)\r\n\r\n elif \"RW\" in position or \"LW\" in position:\r\n sumOfSkills = 0\r\n sumOfMentals = 0\r\n sumOfPhysical = 0\r\n for i in range(len(self.skills)):\r\n x = self.skills[i] * recipe.iloc[i][7]\r\n sumOfSkills += x\r\n skillRating = (sumOfSkills / recipe.iloc[11][7]) * 5\r\n for i in range(len(self.mentals)):\r\n x = self.mentals[i] * recipe.iloc[i + 19][7]\r\n sumOfMentals += x\r\n mentalRating = (sumOfMentals / recipe.iloc[29][7]) * 5\r\n for i in range(len(self.physical)):\r\n x = self.physical[i] * recipe.iloc[i + 30][7]\r\n sumOfPhysical += x\r\n physicalRating = (sumOfPhysical / recipe.iloc[37][7]) * 5\r\n rating = (skillRating * 0.40) + (mentalRating * 0.20) + (physicalRating * 0.40)\r\n\r\n if position == \"RW\":\r\n ratings[\"RW\"] = round(rating, 2)\r\n else:\r\n ratings[\"LW\"] = round(rating, 2)\r\n\r\n else:\r\n sumOfSkills = 0\r\n sumOfMentals = 0\r\n sumOfPhysical = 0\r\n for i in range(len(self.skills)):\r\n x = self.skills[i] * recipe.iloc[i][8]\r\n sumOfSkills += x\r\n skillRating = (sumOfSkills / recipe.iloc[11][8]) * 5\r\n for i in range(len(self.mentals)):\r\n x = self.mentals[i] * recipe.iloc[i + 19][8]\r\n sumOfMentals += x\r\n mentalRating = (sumOfMentals / recipe.iloc[29][8]) * 5\r\n for i in range(len(self.physical)):\r\n x = self.physical[i] * recipe.iloc[i + 30][8]\r\n sumOfPhysical += x\r\n physicalRating = (sumOfPhysical / recipe.iloc[37][8]) * 5\r\n rating = (skillRating * 0.50) + (mentalRating * 0.25) + (physicalRating * 0.25)\r\n ratings[\"ST\"] = round(rating, 2)\r\n\r\n sortedRatings = {}\r\n for i in sorted(list(ratings.values()), reverse=True):\r\n for j in list(ratings.keys()):\r\n if ratings[j] == i:\r\n sortedRatings[j] = i\r\n return sortedRatings\r\n\r\n'''\r\nGoalKeeper class since the given abilities for an in field player and GK is different. Also the stats that'll be stored\r\nwill be different.\r\n'''\r\nclass GoalKeepers:\r\n def __init__(self, excel, index):\r\n self.name = excel.iloc[index][0].split(\"-\")[0]\r\n self.position = list(excel.iloc[index][1])\r\n self.nation = excel.iloc[index][2]\r\n self.club = excel.iloc[index][3]\r\n self.age = excel.iloc[index][4]\r\n self.rushingOut = excel.iloc[index][5]\r\n self.oneOnOnes = excel.iloc[index][6]\r\n self.commandOfArea = excel.iloc[index][7]\r\n self.kicking = excel.iloc[index][8]\r\n self.eccentricity = excel.iloc[index][9]\r\n self.handling = excel.iloc[index][10]\r\n self.throwing = excel.iloc[index][11]\r\n self.aerialReach = excel.iloc[index][12]\r\n self.communication = excel.iloc[index][13]\r\n self.firstTouch = excel.iloc[index][14]\r\n self.passing = excel.iloc[index][15]\r\n self.reflexes = excel.iloc[index][16]\r\n self.punchingTendency = excel.iloc[index][17]\r\n self.aggression = excel.iloc[index][18]\r\n self.bravery = excel.iloc[index][19]\r\n self.workRate = excel.iloc[index][20]\r\n self.decisions = excel.iloc[index][21]\r\n self.determination = excel.iloc[index][22]\r\n self.concentration = excel.iloc[index][23]\r\n self.leadership = excel.iloc[index][24]\r\n self.anticipation = excel.iloc[index][25]\r\n self.flair = excel.iloc[index][26]\r\n self.positioning = excel.iloc[index][27]\r\n self.composure = excel.iloc[index][28]\r\n self.teamWork = excel.iloc[index][29]\r\n self.offTheBall = excel.iloc[index][30]\r\n self.vision = excel.iloc[index][31]\r\n self.agility = excel.iloc[index][32]\r\n self.stamina = excel.iloc[index][33]\r\n self.balance = excel.iloc[index][34]\r\n self.strength = excel.iloc[index][35]\r\n self.pace = excel.iloc[index][36]\r\n self.acceleration = excel.iloc[index][37]\r\n self.fitness = excel.iloc[index][38]\r\n self.jumping = excel.iloc[index][39]\r\n self.height = excel.iloc[index][40]\r\n self.skills = [self.rushingOut, self.oneOnOnes, self.commandOfArea, self.kicking, self.eccentricity,\r\n self.handling, self.throwing, self.aerialReach, self.communication, self.firstTouch,\r\n self.passing, self.reflexes, self.punchingTendency, self.vision, self.agility, self.balance,\r\n self.strength, self.jumping]\r\n self.mental = [self.aggression, self.bravery, self.decisions, self.determination, self.anticipation,\r\n self.positioning, self.composure, self.teamWork]\r\n self.rating = GoalKeepers.gkRating(self)\r\n self.goalConceded = 0\r\n self.assists = 0\r\n\r\n # Basically the same way to calculate a player's rating.\r\n def gkRating(self):\r\n recipe = pd.read_excel(\"gkRating.xlsx\", engine=\"openpyxl\")\r\n sumOfSkills = 0\r\n sumOfMentals = 0\r\n ratings = {}\r\n for i in range(len(self.skills)):\r\n x = self.skills[i] * recipe.iloc[i][1]\r\n sumOfSkills += x\r\n skillRating = (sumOfSkills / recipe.iloc[18][1]) * 5\r\n for i in range(len(self.mental)):\r\n x = self.mental[i] * recipe.iloc[i + 19][1]\r\n sumOfMentals += x\r\n mentalRating = (sumOfMentals / recipe.iloc[27][1]) * 5\r\n rating = (skillRating * 0.65) + (mentalRating * 0.35)\r\n rating += (int(self.height[0:3]) - 185) * 0.06\r\n ratings[\"GK\"] = round(rating, 2)\r\n return ratings\r\n\r\n\r\n# Adding all the players from their excel files to a list that involves every player in whole project. Easily accessible\r\n# by using the index of the player.\r\nallPlayers = []\r\nfor team in tslFiles:\r\n df = pd.read_excel(team, engine=\"openpyxl\")\r\n for i in range(len(df)):\r\n player = Player(df, i)\r\n allPlayers.append(player)\r\n\r\n# Adding the gk's to the allPlayers list.\r\ngk = pd.read_excel(\"Spor Toto Super League/GK1.xlsx\", engine=\"openpyxl\")\r\nfor i in range(len(gk)):\r\n player = GoalKeepers(gk, i)\r\n allPlayers.append(player)\r\n","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":17058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"650045038","text":"# -*- coding: utf-8 -*-\nfrom django.conf.urls.defaults import *\nfrom django.conf import settings\nfrom django.contrib import admin\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\n\nurlpatterns = patterns('',\n url(r'^admin/', include(admin.site.urls)),\n)\n\nurlpatterns += patterns('',\n (r'^accounts/', include('accounts.urls')),\n (r'^index/', include('index.urls')),\n (r'^books/', include('books.urls')),\n (r'^$', 'index.views.index'),\n)\n","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"624133629","text":"from five import grok\nfrom zope.schema.vocabulary import SimpleVocabulary, SimpleTerm\nfrom zope.schema.interfaces import IVocabularyFactory\n\n\nclass categories(grok.GlobalUtility):\n grok.name('sinar.pardocs.categories')\n grok.implements(IVocabularyFactory)\n\n # this should be written to automatically be generated from csv\n _terms = [{\n 'value': 'agriculture',\n 'title': 'Agriculture',\n },\n {\n 'value': 'citizenship',\n 'title': 'Citizenship',\n },\n {\n 'value': 'civilservice',\n 'title': 'Civil Service',\n },\n {\n 'value': 'consumers',\n 'title': 'Consumers',\n },\n {\n 'value': 'constitution',\n 'title': 'Constitutional',\n },\n {\n 'value': 'corruption',\n 'title': 'Corruption and Transparency',\n },\n {\n 'value': 'defence',\n 'title': 'Defence',\n },\n {\n 'value': 'economy',\n 'title': 'Economy',\n },\n {\n 'value': 'education',\n 'title': 'Education',\n },\n {\n 'value': 'employment',\n 'title': 'Employment',\n },\n {\n 'value': 'energy',\n 'title': 'Energy',\n },\n {\n 'value': 'environment',\n 'title': 'Environment',\n },\n {\n 'value': 'finance',\n 'title': 'Finance',\n },\n {\n 'value': 'fishery',\n 'title': 'Fishery',\n },\n {\n 'value': 'foodsecurity',\n 'title': 'Food Security',\n },\n {\n 'value': 'foreignaffairs',\n 'title': 'Foreign Affairs',\n },\n {\n 'value': 'gender',\n 'title': 'Women and Gender',\n },\n {\n 'value': 'glc',\n 'title': 'GLC',\n },\n {\n 'value': 'health',\n 'title': 'Health',\n },\n {\n 'value': 'homeaffairs',\n 'title': 'Home Affairs',\n },\n {\n 'value': 'housing',\n 'title': 'Housing',\n },\n {\n 'value': 'humanresources',\n 'title': 'Human Resources',\n },\n {\n 'value': 'humanrights',\n 'title': 'Human Rights',\n },\n {\n 'value': 'indigenous',\n 'title': 'Indigenous Affairs',\n },\n {\n 'value': 'labour',\n 'title': 'Labour Rights',\n },\n {\n 'value': 'localgov',\n 'title': 'Local Government',\n },\n {\n 'value': 'migrants',\n 'title': 'Migrants and Refugees',\n },\n {\n 'value': 'naturaldisasters',\n 'title': 'Natural Disasters',\n },\n {\n 'value': 'sports',\n 'title': 'Sports and Recreation',\n },\n {\n 'value': 'tariffsubsidy',\n 'title': 'Tariffs and Subsidies',\n },\n {\n 'value': 'tax',\n 'title': 'Taxation',\n },\n {\n 'value': 'trade',\n 'title': 'Trade',\n },\n {\n 'value': 'transportation',\n 'title': 'Transportation',\n },\n {\n 'value': 'tourism',\n 'title': 'Tourism',\n }, ]\n\n def __call__(self, context):\n terms = []\n for i in self._terms:\n terms.append(SimpleTerm(**i))\n return SimpleVocabulary(terms)\n","sub_path":"sinar/pardocs/vocabulary/categories.py","file_name":"categories.py","file_ext":"py","file_size_in_byte":3363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"256179441","text":"# Before running this code you MUST edit /home/symons/anaconda3/lib/python3.7/site-packages/astrobase/services/trilegal.py\r\n# ADD to TRILEGAL_FILTER_SYSTEMS dict:\r\n# 'gaiaDR2': {\r\n# 'desc': \"Gaia's DR2 G, G_BP, G_RP (Vegamags, Gaia passbands from Evans et al. 2018)\",\r\n# 'table': 'tab_mag_odfnew/tab_mag_gaiaDR2.dat'\r\n# },\r\n# COMMENT OUT extinction_info and Av_infinity lines w/ try/except ect. in query_galcoords function and replace them with:\r\n# #instead, use website default\r\n# Av_infinity = 0.0378\r\n# inputparams['extinction_infty'] = '%.5f' % Av_infinity\r\n\r\nimport os\r\nimport gzip\r\nimport shutil\r\nimport astrobase.services.trilegal\r\n\r\ndir_base = '/data/symons/nh_data_lauer/trilegal/gaia' #base directory for outputs\r\n\r\n# lauer fields\r\nfield_DEC = [-17.7780, -41.6360, -50.7529, -0.5183, 0.2915, 36.2331, 35.2979] #DEC values\r\nfield_RA = [1.7790, 348.0611, 33.4069, 358.2428, 0.8066, 224.9875, 226.4865] #RA values\r\nfield_fieldNums = [i for i in range(1,len(field_DEC)+1)] #field num array, make a list if not going 1 to lenDEC\r\nfield_numPerField = 10 #num times to run the same field\r\n\r\nfield_numFields = len(field_DEC) #get len now\r\nif( (len(field_DEC) != len(field_RA)) | (len(field_DEC) != len(field_fieldNums)) ):\r\n print('ERROR: Len field_DEC is '+str(len(field_DEC))+', len field_RA is '+str(len(field_RA))+', len field_fieldNum is '+str(len(field_fieldNums))+' and at least one of them doesn\\'t match.')\r\n import sys\r\n sys.crash() #not a real call\r\n#END IF\r\nfor i in range(0,field_numFields):\r\n dir_curr = os.path.join(dir_base,str(field_fieldNums[i]).zfill(2)) #create current path\r\n if os.path.isdir(dir_curr) == False:\r\n os.makedirs(dir_curr) #create dir if not a dir\r\n #END IF\r\n\r\n for j in range(0,field_numPerField):\r\n return_dict = astrobase.services.trilegal.query_radecl(field_RA[i], field_DEC[i], filtersystem='gaiaDR2', field_deg2=0.0841,\r\n usebinaries=True, extinction_sigma=0, magnitude_limit=32.0, maglim_filtercol=1, trilegal_version=1.6,\r\n extraparams=None, forcefetch=True, cachedir=dir_curr, verbose=True,\r\n timeout=60.0, refresh=60.0, maxtimeout=1500.0) #read trilegal file, it is zipped\r\n\r\n with gzip.open(return_dict['tablefile'], 'rb') as f_in:\r\n with open(return_dict['tablefile'][:return_dict['tablefile'].find('.')]+str(j)+'.dat', 'wb') as f_out:\r\n shutil.copyfileobj(f_in, f_out) #un gzips and saves file, inspired by https://stackoverflow.com/a/44712152\r\n #END WITH\r\n #END WITH\r\n #END FOR j\r\n os.remove(return_dict['tablefile']) #cleanup (.gz file name is same for all FOR j runs, so only 1 .gz to cleanup at the end)\r\n#END FOR i\r\n\r\nprint('done')","sub_path":"py/trilegal/get_trilegal.py","file_name":"get_trilegal.py","file_ext":"py","file_size_in_byte":2771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"168316317","text":"# Spell fragment card data\n\n# Text -> ASCII Art: http://patorjk.com/software/taag/#p=display&f=Rectangles&t=Monster\n\nspell_card_revision = 8\n\nspell_card_categories = [\n 'blank',\n 'starter',\n\n #'attack-charge',\n #'attack-tapestry',\n\n 'eye-create',\n 'eye-move',\n 'eye-defend', # Protect eyes from being destroyed\n 'eye-other-attack',\n 'eye-other-move',\n\n 'defend-charge',\n 'defend-tapestry',\n\n 'mage-move',\n #'mage-move-astral',\n 'mage-defend', # Shields to prevent HP damage\n 'mage-defend-move', # Prevent mage from being moved\n 'mage-other-move',\n 'mage-other-attack', # Damage mage HP\n\n 'tapestry-thread',\n \n #'modify-tapestry',\n #'add-action',\n 'terrain',\n]\n\n# Basic abilities\n# Create eye in current location\n# Small move self\n# Recover Thread\n# Expand tapestry\n\n# Required spell types\n# Move self/target\n# using river\n# using forest\n# using dense forest\n# using rough terrain\n# ignoring rough terrain\n# through unobstructed terrain\n# to location at same elevation\n# Create eye distant\n# anywhere in connected forest/rough/river\n# in same location as existing eye\n# follow another's eye back to mage\n# Move eye\n# single eye\n# multiple eyes\n# n spaces split between eyes\n# to another mage when eye overlaps\n# n spaces along matching terrain\n# Attack eye\n# Remove eye in same location\n# Remove eyes adjacent\n# Move other eye\n# Defend eye against attack\n# Sacrifice charge to defend eye\n# Defend eye from being consumed\n# Defend eye move - Anchor eye\n# Attack creature\n# at eye\n# at eye in a forest/mountain\n# by targeting one of their eyes\n# Defend self against attack\n# Defend target against attack\n# Reflect attack back at attacker\n# Deflect attack to adjacent\n# shield if in same location as eye\n# shield that also recovers Thread when attacked\n\n# Hide from detection\n# Push adjacent creature/mage\n# Anchor (to counter push)\n# Teleport to eye\n# Exchange locations with an eye\n# Levitate/fly\n# + move while levitated\n# Charges\n# extra action\n# copy charge on another's spell\n\n# Terraform\n# add/remove forest\n# add/remove rough terrain\n# area around an eye changes type: forest, water\n# change elevation\n# Attack tapestry\n# cover an element\n# cover a space\n# Defend tapestry\n\n# Spell combos:\n# Move + create eye\n\n# Artifact abilities\n# Recover Thread\n# Move Threads\n# Concealment\n# Ignore terrain penalty\n\n\n# Core abilities:\n# * Map\n# * Move Self\n# * Create eye (in current location)\n# * Tapestry\n# * Recover thread (= mental rest to recover)\n# * Gain Tapestry card (= focus on spell casting - new patterns)\n# * Spell deck\n# * Trash spell card (= focus spell deck - reduce spells)\n# * Interaction with Spell deck\n\n# Element opposites\n# Air <-> Earth\n# Fire <-> Water\n\n# Spell affinity\n# Air Fire Earth Water\n# +-------------+-------------+-------------+-------------+\n# Move Self + + + + + + +\n# Move Other + + + + + + + +\n# Defend Move Self\n#\n# Create Eye + + + + + + +\n# Move Eye + + + + + + + +\n# Move Other Eye\n# Defend Move Eye\n# Attack Eye + + + + + + +\n# Defend Eye\n#\n# Create Anchor + + + + + + +\n# Attack Anchor\n# Defend Anchor\n#\n# Attack HP + + + + + + + +\n# Defend HP + + + + + + + +\n# Recover HP + + + + + + + +\n#\n# Tapestry + + +\n# Other Tapestry\n# Defend Tapestry\n#\n# Spell\n# Other Spell\n#\n# Astral\n\n# TODO:\n# Triggers - spell effects for current turn\n# On , do X\n# On push mage into another location, do cause 1 damage\n# On enter location with mage, do push mage out\n# Reactions - spell effects in response to another mage's spell\n# If attacked, cast spell to deflect\n# If eye moves onto you, cast spell to dispel, reflect, push away\n# If eye moves next to you, do X\n\n# Data Format:\n# spell_card_data:\n# List of s\n#\n# :\n# , <attributes>, <info>\n#\n# <attribute>:\n# 'element': 'air', 'fire', 'earth', 'water' or 'none'\n# 'pattern': name of pattern\n# 'op': alternate action at bottom of card\n# 'category': <string> to group spells by general category\n# 'flavor': flavor text for spell\n#\n# <info>:\n# 'cast': Description when spell is cast.\n# 'charged': Description when spell is charged.\n# 'notes': Additional notes\n# 'sacrifice': Description when charge is sacrificed.\n\nspell_card_data = [\n\n # _____ _ _ \n # | | |___ _ _| |_ ___ ___| |\n # | | | | -_| | | _| _| .'| |\n # |_|___|___|___|_| |_| |__,|_|\n #\n # Neutral spells are basic spells that are always worse than corresponding\n # elemental spells.\n \n # _____ _ _ \n # | __| |_ ___ ___| |_ ___ ___ \n # |__ | _| .'| _| _| -_| _|\n # |_____|_| |__,|_| |_| |___|_| \n #\n # Representative spells for each element.\n\n [\"Haste\",\n {'element': 'air', 'pattern': 'E1-1', 'op': 'eye', 'vp': 0,\n 'category': 'starter,mage-move',\n }, {\n 'cast': \"Move 4\",\n } ],\n\n [\"Endurance\",\n {'element': 'earth', 'pattern': 'E1-1', 'op': 'tapestry-eye', 'vp': 0,\n 'category': 'starter,terrain,mage-move',\n }, {\n 'cast': \"{{ADD_ACTION}}\",\n 'active': \"You may ignore the movement penalty for rough terrain or changing elevation.\",\n } ],\n\n [\"Fire Shards\",\n {'element': 'fire', 'pattern': 'E1-2', 'op': 'eye-thread', 'vp': 0,\n 'category': 'starter,mage-other-attack',\n }, {\n 'cast': \"Consume one of your Eyes to Attack 1 at that location.\",\n } ],\n\n [\"Extend\",\n {'element': 'water', 'pattern': 'E1-2', 'op': 'eye-mmove', 'vp': 0,\n 'category': 'starter,eye-move',\n }, {\n 'cast': \"Move one of your Eyes 2 spaces.\",\n } ],\n\n # _____ _____ _ ___ \n # | |___ _ _ ___ | __|___| | _|\n # | | | | . | | | -_| |__ | -_| | _|\n # |_|_|_|___|\\_/|___| |_____|___|_|_|\n #\n # Move mage N spaces\n # Move mage N spaces, create eye\n # Move into adjacent location via land (w/o crossing water)\n # Cross over river\n # Ignore movement penalty: rough terrain, elevation, cross rivers\n # Move through connected terrain type (forest, dense forest, river, plain)\n # Dense forest teleport within 5 spaces\n # React: when attacked, move to adjacent location\n # Air walk: move along same or lower terrain. must end at same level.\n # Teleport link: within forest, swap positions with an Eye.\n # Levitate/Fly - ignore terrain cost, easier to detect\n # Move into location and push others\n \n [\"Airwalk\",\n {'element': 'air', 'pattern': 'E2-7', 'op': 'eye-thread', 'vp': 1,\n 'category': 'terrain,mage-move',\n }, {\n 'cast': \"If at mid or high-elevation, move 5 spaces over same of lower elevation. You must end at the same elevation as your start.\",\n } ],\n\n [\"Plainswalker\",\n {'element': 'earth', 'pattern': 'E2-2', 'op': 'tapestry-eye', 'vp': 1,\n 'category': 'terrain,mage-move',\n }, {\n 'cast': \"If in low-elevation, move 7 spaces through low-elevation, ignoring terrain cost.\",\n } ],\n\n [\"Waterwalk\",\n {'element': 'water', 'pattern': 'E2-34', 'op': 'eye-thread', 'vp': 1,\n 'category': 'terrain,mage-move',\n #'flavor': \"Rising columns of mud form a temporary bridge.\",\n }, {\n 'cast': \"If adjacent to a river, move 5 spaces along that river, switching sides at will.\",\n } ],\n\n # Pattern is Doubled form of Haste\n [\"Blur\",\n {'element': 'air', 'pattern': 'E2-1', 'op': 'tapestry-eye', 'vp': 1,\n 'category': 'mage-move',\n }, {\n 'cast': \"Move 8\",\n } ],\n\n [\"Forest Blink\",\n {'element': 'air', 'pattern': 'E2-59', 'op': 'eye-thread', 'vp': 1,\n 'category': 'terrain,mage-move',\n }, {\n 'cast': \"If you are in a forest location, you may move to any connected forest location, ignoring any terrain costs and crossing rivers.\",\n } ],\n\n [\"Dense Passage\",\n {'element': 'air', 'pattern': 'E2-60', 'op': 'eye-thread', 'vp': 1,\n 'category': 'terrain,mage-move',\n }, {\n 'cast': \"If in a Dense Forest location, jump to another Dense Forest location no more than 5 spaces away.\",\n 'react': \"If attacked while in a Dense Forest, jump to the nearest Dense Forest\",\n } ],\n\n [\"Dodge\",\n {'element': 'air', 'pattern': 'E1-3', 'op': 'eye-thread', 'vp': 1,\n 'category': 'mage-move',\n }, {\n 'cast': \"Move 6\",\n 'react': \"When attacked, cast to move into any valid adjacent location.\",\n } ],\n\n # _____ _____ _ _ \n # | |___ _ _ ___ | | |_| |_ ___ ___ \n # | | | | . | | | -_| | | | _| | -_| _|\n # |_|_|_|___|\\_/|___| |_____|_| |_|_|___|_|\n #\n # Attack another mage's position on the map\n # Locations next to eyes are barriers that others cannot move into\n # Teleport other\n # Target is prevented from moving out of current location\n # Move into adjacent location, pushing any mage there into another location\n # moving them to one of your Eye locations\n \n # ____ ___ _ _____ _____ _ ___ \n # | \\ ___| _|___ ___ _| | | |___ _ _ ___ | __|___| | _|\n # | | | -_| _| -_| | . | | | | | . | | | -_| |__ | -_| | _|\n # |____/|___|_| |___|_|_|___| |_|_|_|___|\\_/|___| |_____|___|_|_|\n #\n # Defend against being moved by another mage\n\n # _____ _ _____ \n # | |___ ___ ___| |_ ___ | __|_ _ ___ \n # | --| _| -_| .'| _| -_| | __| | | -_|\n # |_____|_| |___|__,|_| |___| |_____|_ |___|\n # |___|\n #\n # Convert mana into an Eye on the map\n # Duplicate Eye - double number of eyes\n # When in location of opponent's Eye, create Eye in their location\n # When in location of opponent's Eye, create Eye in one of their Eye's location\n # When in forest/water, create Eye in same terrain within N spaces\n\n [\"Water Target\",\n {'element': 'water', 'pattern': 'E1-5', 'op': 'mmove-thread', 'vp': 1,\n 'category': 'eye-create',\n }, {\n 'cast': \"If next to a river, place an Eye in any location along that river within 5 spaces.\",\n } ],\n\n [\"Woodland Target\",\n {'element': 'earth', 'pattern': 'E2-10', 'op': 'tapestry-mmove', 'vp': 1,\n 'category': 'eye-create',\n }, {\n 'cast': \"If in a forest, place an Eye in any connected forest location.\",\n } ],\n\n [\"Duplicate\",\n {'element': 'water', 'pattern': 'E2-27', 'op': 'eye-mmove', 'vp': 1,\n 'category': 'eye-create',\n }, {\n 'cast': \"In a location where you have at least one Eye, split each of your Eyes into two separate Eyes.\",\n } ],\n\n [\"Traceback\",\n {'element': 'water', 'pattern': 'E2-36', 'op': 'tapestry-thread', 'vp': 1,\n 'category': 'eye-create',\n }, {\n 'cast': \"If in a location with another mage's Eye, you may place an Eye at that Mage's location.\",\n 'react': \"You may cast this when an opponent's Eye is moved into your location.\",\n } ],\n \n # _____ _____ \n # | |___ _ _ ___ | __|_ _ ___ \n # | | | | . | | | -_| | __| | | -_|\n # |_|_|_|___|\\_/|___| |_____|_ |___|\n # |___|\n #\n # Move your Eyes on the map\n # Move one 1 Eye N spaces\n # Move all Eyes N spaces each\n # Move N spaces, split among M Eyes\n # Move N spaces, split among any number of Eyes\n # Duplicate an Eye and then move it N spaces\n # Create Eye, then move Eyes\n # Move Eye N spaces, if Eye in same location as another mage's Eye,\n # move Eye to that mage's location\n # Move Eye in plain/water/forest N spaces within that terrain\n # Move Eye in plain/water/forest to another within N spaces\n \n [\"Eyedrop\",\n {'element': 'air', 'pattern': 'E2-14', 'op': 'mmove-thread', 'vp': 1,\n 'category': 'eye-move',\n }, {\n 'cast': \"Create an Eye and then move it 4.\",\n } ],\n \n [\"Seek\",\n {'element': 'air', 'pattern': 'E2-15', 'op': 'eye-mmove', 'vp': 1,\n 'category': 'eye-move',\n }, {\n 'cast': \"Move one of your Eyes 4 spaces. If it ends in the same location as another Mage's Eye, then move your Eye to that Mage's location.\",\n } ],\n \n [\"Gust\",\n {'element': 'air', 'pattern': 'E1-6', 'op': 'eye-mmove', 'vp': 1,\n 'category': 'eye-move',\n }, {\n 'cast': \"Move your Eyes 6 spaces, split among any number of Eyes.\",\n } ],\n \n [\"Spread\",\n {'element': 'water', 'pattern': 'E2-31', 'op': 'eye-thread', 'vp': 1,\n 'category': 'eye-move',\n }, {\n 'cast': \"Move all your Eyes 3 spaces.\",\n } ],\n\n [\"Expand\",\n {'element': 'water', 'pattern': 'E2-35', 'op': 'mmove-thread', 'vp': 1,\n 'category': 'eye-create,eye-move',\n 'flavor': \"The air crackles as the Eye splits and one half shoots away. \",\n }, {\n 'cast': \"Duplicate an existing Eye and then move it 6 spaces.\",\n } ],\n\n [\"Bolt\",\n {'element': 'fire', 'pattern': 'E1-8', 'op': 'eye-mmove', 'vp': 1,\n 'category': 'eye-move',\n }, {\n 'cast': \"Move a single Eye 8 spaces.\",\n } ],\n\n # _____ _____ _ _ _____ \n # | |___ _ _ ___ | | |_| |_ ___ ___ | __|_ _ ___ \n # | | | | . | | | -_| | | | _| | -_| _| | __| | | -_|\n # |_|_|_|___|\\_/|___| |_____|_| |_|_|___|_| |_____|_ |___|\n # |___|\n #\n # Move an opponent's Eye\n # Move all eyes in your location N spaces\n # Move all eyes from adjacent spaces\n # Move self N spaces, for each space entered move all Eyes 1 space\n # Move Eye N spaces, for each space entered move all Eyes 1 space\n\n [\"Disperse\",\n {'element': 'air', 'pattern': 'E2-53', 'op': 'eye-mmove', 'vp': 1,\n 'category': 'eye-move',\n }, {\n 'cast': \"Move one of your Eyes 3 spaces, pushing any existing Eyes into an adjacent space.\",\n } ],\n\n [\"Control\",\n {'element': 'water', 'pattern': 'E2-78', 'op': 'eye-mmove', 'vp': 1,\n 'category': 'eye-move',\n }, {\n 'cast': \"If you have an Eye in the same location as another Eye, then you may move that other Eye 4 spaces.\",\n } ],\n\n [\"Control Burst\",\n {'element': 'water', 'pattern': 'E2-79', 'op': 'mmove-thread', 'vp': 1,\n 'category': 'eye-move',\n }, {\n 'cast': \"If you have an Eye in the same location as other Eyes, then you may move all other Eyes 2 spaces each.\",\n } ],\n\n # ____ ___ _ _____ _____ \n # | \\ ___| _|___ ___ _| | | |___ _ _ ___ | __|_ _ ___ \n # | | | -_| _| -_| | . | | | | | . | | | -_| | __| | | -_|\n # |____/|___|_| |___|_|_|___| |_|_|_|___|\\_/|___| |_____|_ |___|\n # |___|\n #\n # Defend against an opponent moving your Eyes\n # Create Anchored Eye\n # Anchor remote eye\n \n [\"Anchor\",\n {'element': 'earth', 'pattern': 'E1-6', 'op': 'tapestry-thread', 'vp': 1,\n 'category': 'eye-defend',\n }, {\n 'cast': \"Create a new Eye and then Anchor it.\",\n } ],\n\n [\"Remote Anchor\",\n {'element': 'earth', 'pattern': 'E2-15', 'op': 'mmove-thread', 'vp': 1,\n 'category': 'eye-defend',\n }, {\n 'cast': \"Anchor one of your Eyes.\",\n } ],\n\n # _____ _ _ _ _____ \n # | _ | |_| |_ ___ ___| |_ | __|_ _ ___ \n # | | _| _| .'| _| '_| | __| | | -_|\n # |__|__|_| |_| |__,|___|_,_| |_____|_ |___|\n # |___|\n #\n # Move or destroy an opponent's Eye\n # Cast: Remove all Eyes at location\n # Charge: When opponent's eye moves into your location, destroy Eye\n # Remove all Eyes from 1 location adjacent to Eye (or all locations adjacent)\n # Cast: Move 3 spaces, removing 1 Eye from each location you enter.\n # Cast: If in location with other Eye, remove 1 of that mage's Eyes\n # Charge: At end of turn, move co-located Eye 1 space.\n # Sacrifice charge to move 4 spaces.\n # Remove Eye from adjacent location and move into that space\n\n [\"Dispel\",\n {'element': 'fire', 'pattern': 'E1-5', 'op': 'tapestry-eye', 'vp': 1,\n 'category': 'eye-other-attack',\n }, {\n 'cast': \"Consume one of your Eyes to remove all Eyes at that location.\",\n } ],\n\n [\"Ground\",\n {'element': 'earth', 'pattern': 'E2-60', 'op': 'tapestry-mmove', 'vp': 1,\n 'category': 'eye-other-attack',\n }, {\n 'cast': \"Remove all Eyes from your location and all adjacent locations.\",\n } ],\n\n [\"Scorch\",\n {'element': 'fire', 'pattern': 'E2-36', 'op': 'eye-thread', 'vp': 1,\n 'category': 'eye-move,eye-other-attack',\n }, {\n 'cast': \"Move one of your Eyes 3 spaces, removing one opponent Eye from each location it moves into this turn. Consume this Eye.\",\n } ],\n\n [\"Repel\",\n {'element': 'fire', 'pattern': 'E2-35', 'op': 'tapestry-thread', 'vp': 1,\n 'category': 'eye-move,eye-other-attack',\n }, {\n 'cast': \"{{ADD_CHARGE}}\",\n 'react': \"You may cast this when an Eye move into your location.\",\n 'sacrifice': \"When an Eye moves into your location, you may spend a Charge to destroy that Eye.\",\n } ],\n\n # ____ ___ _ _____ \n # | \\ ___| _|___ ___ _| | | __|_ _ ___ \n # | | | -_| _| -_| | . | | __| | | -_|\n # |____/|___|_| |___|_|_|___| |_____|_ |___|\n # |___|\n #\n # Defend against an opponent removing one of your eyes\n # Charge: Sacrifice charge to substitute one Eye for another being removed\n # Charge: Sacrifice charge to prevent Eye from being removed\n # N charges protects N Eyes on map\n # Anchor Eye\n # Charge: all Eyes become anchors\n\n [\"Sacrificium\",\n {'element': 'earth', 'pattern': 'E2-8', 'op': 'eye-mmove', 'vp': 1,\n 'category': 'mage-defend',\n }, {\n 'cast': \"{{ADD_CHARGE}}\",\n 'react': \"You may cast this when one of your Eyes is attacked.\",\n 'sacrifice': \"When you need to remove an Eye, you may instead remove a Charge from this spell.\",\n } ],\n\n [\"Switch\",\n {'element': 'earth', 'pattern': 'E2-11', 'op': 'eye-thread', 'vp': 1,\n 'category': 'mage-defend',\n }, {\n 'cast': \"{{ADD_CHARGE}}\",\n 'react': \"You may cast this when one of your Eyes is attacked.\",\n 'sacrifice': \"When you need to remove an Eye, you may instead remove one of your other Eyes.\",\n } ],\n\n # _____ _ _ _ _____ _____ \n # | _ | |_| |_ ___ ___| |_ | | | _ |\n # | | _| _| .'| _| '_| | | __|\n # |__|__|_| |_| |__,|___|_,_| |__|__|__|\n #\n # Attack another mage/creature\n # Attack at Eye\n # Attack adjacent to Eye\n # React: Redirect attack to one of your Eyes\n # Charge: When opponent's eye moves into your location, attack 1 at mage\n # Attack 1 at all Eyes\n # Attack 2 in all Eyes in Forest/Rough/next to water\n # Attack 3 in neighboring location to Eye in mountain\n # Move 1 and then attack 1 adjacent to new location\n # Charge: Sacrifice to boost power of attack by 1\n # Groups of 3 Eyes are Wall of Flame. Charge lost if group broken\n # Extra damage against shield spell\n\n [\"Ignis\",\n {'element': 'fire', 'pattern': 'E2-27', 'op': 'eye-thread', 'vp': 1,\n 'category': 'mage-other-attack',\n }, {\n 'cast': \"Consume one of your Eyes to Attack 1 at location adjacent to that Eye.\",\n } ],\n\n [\"Redirect\",\n {'element': 'fire', 'pattern': 'E2-32', 'op': 'eye-mmove', 'vp': 1,\n 'category': 'mage-other-attack',\n }, {\n 'cast': \"Attack 1 at one of your Eyes.\",\n 'react': \"When attacked, cast to redirect the attack to one of your Eyes.\",\n } ],\n\n [\"Lavastone\",\n {'element': 'fire', 'pattern': 'E2-31', 'op': 'eye-thread', 'vp': 1,\n 'category': 'mage-other-attack',\n }, {\n 'cast': \"Attack 2 at one of your Eyes. Attack 3 if targeting rough terrain or high elevation.\",\n } ],\n\n [\"Boost\",\n {'element': 'fire', 'pattern': 'E2-28', 'op': 'tapestry-thread', 'vp': 1,\n 'category': 'mage-other-attack',\n }, {\n 'cast': \"{{ADD_CHARGE}}\",\n 'sacrifice': \"Spend a Charge to increase Attack strength by 1.\",\n } ],\n\n [\"Geyser\",\n {'element': 'water', 'pattern': 'E1-8', 'op': 'eye-thread', 'vp': 1,\n 'category': 'mage-other-attack',\n }, {\n 'cast': \"Attack 1 at two of your Eyes.\",\n } ],\n\n # ____ ___ _ _____ _____ \n # | \\ ___| _|___ ___ _| | | | | _ |\n # | | | -_| _| -_| | . | | | __|\n # |____/|___|_| |___|_|_|___| |__|__|__|\n #\n # Defend against being attacked\n # Charge: Defend 1 damage\n # React: Cast to defend\n # Charge: Defend from attack, but attack reflected back at attacker\n # Charge: If in same location as Eye, that Eye acts as shield 2\n # Charge: Deflect attack into adjacent location\n # Charge: Boost defense power by 1\n\n [\"Shield\",\n {'element': 'earth', 'pattern': 'E1-3', 'op': 'eye-mmove', 'vp': 1,\n 'category': 'mage-defend',\n }, {\n 'cast': \"{{ADD_CHARGE}}\",\n 'sacrifice': \"Remove a charge to cancel an attack of 1 damage.\",\n } ],\n\n [\"Deflect\",\n {'element': 'earth', 'pattern': 'E2-5', 'op': 'tapestry-eye', 'vp': 1,\n 'category': 'mage-defend',\n }, {\n 'cast': \"Deflect an attack of 1\",\n 'react': \"When attacked, cast to deflect attack.\",\n } ],\n\n [\"Reflect\",\n {'element': 'fire', 'pattern': 'E2-44', 'op': 'eye-thread', 'vp': 1,\n 'category': 'mage-defend',\n }, {\n 'cast': \"{{ADD_CHARGE}}\",\n 'sacrifice': \"Remove a charge to reduce damage to 1/2 (round down) and reflect full damage back at the attacker.\",\n } ],\n\n # _____ _ \n # |_ _|___ ___ ___ ___| |_ ___ _ _ \n # | | | .'| . | -_|_ -| _| _| | |\n # |_| |__,| _|___|___|_| |_| |_ |\n # |_| |___|\n # Tapestry modification\n # Remove thread from tapestry. Take another action.\n # Recovery shield - Protection shield 1, but:\n # Charge may be sacrificed to recover 2 threads\n # If attacked, recover 2 threads\n\n # _____ _ _ _____ _ \n # | | |_| |_ ___ ___ |_ _|___ ___ ___ ___| |_ ___ _ _ \n # | | | _| | -_| _| | | | .'| . | -_|_ -| _| _| | |\n # |_____|_| |_|_|___|_| |_| |__,| _|___|___|_| |_| |_ |\n # |_| |___|\n # Attack an opponent's tapestry\n # Attack: Cover a element spot in another mage's tapestry.\n # Attack: Cover a normal space in opponent's tapestry\n # Attack: Opponent is forced to add mana to their tapestry\n # New mana must be placed adjacent to existing mana\n\n # ____ ___ _ _____ _ \n # | \\ ___| _|___ ___ _| | |_ _|___ ___ ___ ___| |_ ___ _ _ \n # | | | -_| _| -_| | . | | | | .'| . | -_|_ -| _| _| | |\n # |____/|___|_| |___|_|_|___| |_| |__,| _|___|___|_| |_| |_ |\n # |_| |___|\n # Defend tapestry from attack\n\n # _____ _ \n # |_ _|___ ___ ___ ___|_|___ \n # | | | -_| _| _| .'| | |\n # |_| |___|_| |_| |__,|_|_|_|\n #\n # Change terrain type: -> water, forest, rough\n # While charges, Eyes represent terrain type\n\n # _____ _ _ \n # | __|___ ___| | |\n # |__ | . | -_| | |\n # |_____| _|___|_|_|\n # |_|\n # Interact with your spells\n # Duplicate Charge on one of your spells\n\n # _____ _ _ _____ _ _ \n # | | |_| |_ ___ ___ | __|___ ___| | |\n # | | | _| | -_| _| |__ | . | -_| | |\n # |_____|_| |_|_|___|_| |_____| _|___|_|_|\n # |_|\n # Remove a charge from an opponent's spell\n # Copy effect of another's spell\n # Copy charge - if Eye adjacent to mage, add charge to one of their spells\n\n # _____ _ _ \n # | _ |___| |_|_|___ ___ \n # | | _| _| | . | |\n # |__|__|___|_| |_|___|_|_|\n #\n # Gain an extra action\n # Store an action for later - sacrifice charge\n\n # _____ _ _ \n # | _ |___| |_ ___ ___| |\n # | |_ -| _| _| .'| |\n # |__|__|___|_| |_| |__,|_|\n #\n # Teleport self - go to astral plane\n # Teleport return - return from astral to an Eye\n # Teleport other - move other mage at Eye to astral\n # Teleport return other - move other mage from astral to Eye\n\n # _____ _ \n # | |_|___ ___ \n # | | | | |_ -| _|\n # |_|_|_|_|___|___|\n #\n # Hide from detection\n \n # Blank card (for TTS)\n #[\"???\",\n # {'element': 'none', 'pattern': 'blank',\n # 'category': 'blank'},\n # {\n # 'cast': \"???\",\n # } ],\n\n]\n","sub_path":"components/data_spell_cards.py","file_name":"data_spell_cards.py","file_ext":"py","file_size_in_byte":26822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"614225292","text":"# Imports: standard library\nimport os\nfrom typing import List, Optional\n\n# Imports: third party\nimport pandas as pd\nimport pytest\n\n# Imports: first party\n# pylint: disable=no-member\nfrom tensorize.bedmaster.match_patient_bedmaster import PatientBedmasterMatcher\n\n\ndef get_patient_bedmaster_matcher(\n bedmaster: str,\n desired_departments: Optional[List[str]] = None,\n) -> PatientBedmasterMatcher:\n matcher = PatientBedmasterMatcher(\n bedmaster=bedmaster,\n adt=pytest.adt_path,\n desired_departments=desired_departments,\n )\n return matcher\n\n\ndef test_file_structure_and_atributes(temp_dir):\n matcher = get_patient_bedmaster_matcher(pytest.bedmaster_matching)\n matcher2 = get_patient_bedmaster_matcher(\n bedmaster=pytest.bedmaster_matching,\n desired_departments=[\"MGH BLAKE 8 CARD SICU\"],\n )\n assert not matcher.desired_departments\n assert matcher2.desired_departments == [\"MGH BLAKE 8 CARD SICU\"]\n\n # Check if columns of obtained xref table matches expected columns\n cross_ref_file_matched = os.path.join(temp_dir, \"xref_file_matched.csv\")\n matcher.match_files(pytest.bedmaster_index, cross_ref_file_matched)\n expected_df = pd.read_csv(os.path.join(pytest.datadir, \"xref_file_matched_exp.csv\"))\n obt_df = pd.read_csv(cross_ref_file_matched)\n assert set(expected_df.keys()) == set(obt_df.keys())\n\n\ndef test_xref_file_generation(temp_dir):\n def test_xref_file_results(\n temp_dir,\n bedmaster_dir,\n ):\n matcher = get_patient_bedmaster_matcher(\n bedmaster=bedmaster_dir,\n )\n expected_df = pd.read_csv(\n os.path.join(pytest.datadir, \"xref_file_matched_exp.csv\"),\n )\n cross_ref_file_matched = os.path.join(temp_dir, \"xref_file_matched.csv\")\n\n matcher.match_files(pytest.bedmaster_index, cross_ref_file_matched)\n obt_df = pd.read_csv(cross_ref_file_matched)\n\n # Remove the path prefix to leave just the file name\n assert (expected_df == obt_df).all().all()\n\n matcher2 = get_patient_bedmaster_matcher(\n bedmaster=bedmaster_dir,\n desired_departments=[\"MGH BLAKE 8 CARD SICU\"],\n )\n matcher2.match_files(pytest.bedmaster_index, cross_ref_file_matched)\n obt_df2 = pd.read_csv(cross_ref_file_matched)\n\n assert (\n (\n expected_df[\n expected_df[\"DepartmentDSC\"] == \"MGH BLAKE 8 CARD SICU\"\n ].reset_index(drop=True)\n == obt_df2\n )\n .all()\n .all()\n )\n\n folder = pytest.bedmaster_matching\n test_xref_file_results(temp_dir, folder)\n","sub_path":"tests/icu_ingest/test_match_patient_bedmaster.py","file_name":"test_match_patient_bedmaster.py","file_ext":"py","file_size_in_byte":2674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"58944204","text":"import ftplib\n#import config\nimport log\nimport tarfile\nfrom datetime import datetime\nimport db\n\ndef getRemoteTars():\n\ttry:\n\t\tml_db = db.connect(config.get('db_host','medialib_live'),config.get('db_user','medialib_live'),config.get('db_password','medialib_live'),config.get('db_name','medialib_live'))\n\t\tlog.logger.debug('Succesfully connected to database ' + config.get('db_host','medialib_live') )\n\texcept Exception as e:\n\t\tlog.logger.critical('Could not connect to database '+ config.get('db_host','medialib_live'))\n\t\tlog.logger.debug(e)\n\t\texit(1)\n\n\t#q = 'SELECT name,remote_dir FROM tar_file WHERE name LIKE \"%_HERBARIUMWAG_%\" AND backup_created BETWEEN \"' + date + ' 00:00:00\" AND \"' + date + ' 23:59:59\"'\n\tq = 'SELECT name,remote_dir FROM tar_file WHERE name LIKE \"%_HERBARIUMWAG_%\" AND backup_created < \"2013-08-01\"'\n\ttry:\n\t\ttars = db.query(ml_db,q)\n\t\tlog.logger.debug('Succesfully queried to database ' + config.get('db_host','medialib_live') )\n\t\treturn tars\n\texcept Exception as e:\n\t\tlog.logger.critical('Could not query to database '+ config.get('db_host','medialib_live'))\n\t\tlog.logger.debug(e)\n\t\texit(1)\n\ndef indexRemoteTars(tar_list):\n\n\ttry:\n\t\ttar_db = db.connect(config.get('db_host'),config.get('db_user'),config.get('db_password'),config.get('db_name'))\n\t\tlog.logger.debug('Succesfully connected to database on: ' + config.get('db_host'))\n\texcept Exception as e:\n\t\tlog.logger.critical('Could not connect database to :' + config.get('db_host'))\n\t\tlog.logger.debug(e)\n\n\n\tfor tar in tar_list:\n\t\ttry:\n\t\t\tif int(tar['name'].split('_')[2][:8]) < 20130924:\n\t\t\t\tremote_dir = tar['name'].split('_')[2][:8]\n\t\t\telif tar['remote_dir'] is None:\n\t\t\t\tremote_dir = ''\n\t\t\telse:\n\t\t\t\tremote_dir = tar['remote_dir']\n\n\t\t\tq = 'INSERT INTO ftp_index (tar,remote_dir) VALUES (\"'+tar['name']+'\",\"'+str(remote_dir)+'\")'\n\t\t\tdb.update(tar_db,q)\n\t\t\tlog.logger.debug('Succesfully added this record to the database: ' + tar['name'])\n\t\texcept Exception as e:\n\t\t\tlog.logger.critical('Could not add record ' + tar['name'] + ' this is a CRITICAL -> EXITING')\n\t\t\texit(1)\n\ndef getTar(setsize):\n\ttry:\n\t\tftp_db = db.connect(config.get('db_host'),config.get('db_user'),config.get('db_password'),config.get('db_name'))\n\t\tlog.logger.debug('Succesfully connected to database on: ' + config.get('db_host'))\n\texcept Exception as e:\n\t\tlog.logger.critical('Could not connect database to :' + config.get('db_host'))\n\t\tlog.logger.debug(e)\n\n\tq = 'SELECT * FROM ftp_index WHERE downloaded = 0 ORDER BY id DESC limit ' + str(setsize)\n\ttry:\n\t\ttars = db.query(ftp_db,q)\n\t\tlog.logger.debug('Succesfully queried to database ' + config.get('db_host') )\n\t\treturn tars\n\texcept Exception as e:\n\t\tlog.logger.critical('Could not query to database '+ config.get('db_host'))\n\t\tlog.logger.debug(e)\n\t\texit(1)\n\n\t#for tar in tars:\n\t#\tprint tar\n\n\ndef openFTP():\n\tftp = ftplib.FTP(config.get('ftp_host'))\n\ttry:\n\t\tftp.login(config.get('ftp_username'),config.get('ftp_password'))\n\t\tftp.set_pasv(True)\n\t\tlog.logger.debug('FTP connection to ' + config.get('ftp_host') + ' succesfull')\n\t\treturn ftp\n\texcept Exception as e:\n\t\tlog.logger.critical('Fail during setup of ftp connection to ' + config.get('ftp_host') )\n\t\tlog.logger.debug(e)\n\t\traise Exception\n\ndef closeFTP(ftp):\n\ttry:\n\t\tftp.close()\n\t\tlog.logger.debug('FTP connection close of ' + config.get('ftp_host') + ' succesfull')\n\texcept Exception as e:\n\t\tlog.logger.critical('Fail during closing of ftp connection to ' + config.get('ftp_host') )\n\t\tlog.logger.debug(e)\n\t\traise Exception\n\ndef checkRemoteFile(ftp,path,tarfile):\n\ttry:\n\t\tftp.cwd('/'+path)\n\t\tlog.logger.debug('Succesfully changed dir to /' + path)\n\texcept Exception as e:\n\t\tlog.logger.critical('Fail during directory change of /' + path )\n\t\tlog.logger.debug(e)\n\t\traise Exception\n\n\ttry:\n\t\tsize = ftp.size(tarfile)\n\t\tlog.logger.debug('Succesfully checked size of ' + tarfile )\n\texcept Exception as e:\n\t\tlog.logger.critical('Fail checked size of ' + tarfile )\n\t\tlog.logger.debug(e)\n\t\traise Exception\n\n\ttry:\n\t\tif size is None:\n\t\t\treturn False\n\t\telse:\n\t\t\treturn size\n\texcept Exception as e:\n\t\tlog.logger.critical('Could not return size of ' + tarfile )\n\t\tlog.logger.debug(e)\n\t\traise Exception\n\ndef downloadTar(ftp,path,tarfile):\n\ttry:\n\t\tftp.cwd('/'+path)\n\t\tlog.logger.debug('Succesfully changed dir to /' + path)\n\texcept Exception as e:\n\t\tlog.logger.critical('Fail during directory change of /' + path )\n\t\tlog.logger.debug(e)\n\t\traise Exception\n\n\ttry:\n\t\tftp.retrbinary('RETR ' + tarfile,open(tarfile, 'wb').write)\n\t\tlog.logger.debug('Succesfully downloaded ' + tarfile)\n\texcept Exception as e:\n\t\tlog.logger.critical('Fail retriefing file ' + tarfile )\n\t\tlog.logger.debug(e)\n\t\traise Exception\n\n\tftp_db = db.connect(config.get('db_host'),config.get('db_user'),config.get('db_password'),config.get('db_name'))\n\n\tq = 'UPDATE ftp_index SET downloaded = 1, download_date = \"' +str(datetime.now()) + '\" WHERE tar = \"'+tarfile+'\"'\n\n\ttry:\n\t\tdb.update(ftp_db,q)\n\t\tlog.logger.debug('Succesfully updated ftp_index database with downloaded file')\n\texcept Exception as e:\n\t\tlog.logger.critical('Could not update ftp_index database')\n\t\tlog.logger.debug(e)\n\ndef extractTar(id):\n\ttar_db = db.connect(config.get('db_host'),config.get('db_user'),config.get('db_password'),config.get('db_name'))\n\tq = 'SELECT tar,filename FROM tar_index WHERE id = ' + str(id)\n\t#tar_info = {}\n\ttry:\n\t\ttar_info = db.query(tar_db,q)\n\t\t#print tar_info[0]\n\t\t#tar_info = db.query(tar_db,q)[0]\n\texcept Exception as e:\n\t\tlog.logger.critical('Could not query tar_index table')\n\t\tlog.logger.debug(e)\n\tif len(tar_info) == 0:\n\t\tlog.logger.error('Could not find this id in tar_index. ID:' + str(id))\n\t\traise Exception\n\telse:\n\t\ttry:\n\t\t\ttar = tarfile.open(tar_info[0]['tar'])\n\t\t\tlog.logger.debug('Succesfully opened ' + tar_info[0]['tar'])\n\t\texcept Exception as e:\n\t\t\tlog.logger.critical('Fail during opening ' + tar_info[0]['tar'] )\n\t\t\tlog.logger.debug(e)\n\t\t\traise Exception\n\t\ttry:\n\t\t\ttar.extract(tar_info[0]['filename'])\n\t\t\t#tar.extract(14)\n\t\t\tlog.logger.debug('Succesfully extracted ' + tar_info[0]['filename'])\n\t\t\treturn tar_info[0]['filename']\n\t\texcept Exception as e:\n\t\t\tlog.logger.critical('Could not extact' + tar_info[0]['filename'] + ' from ' + tar_info[0]['tar'])\n\t\t\tlog.logger.debug(e)\n\ndef indexTar(tarfilename):\n\n\t__MIME__ = ['tif','tiff','jpg','jpeg']\n\n\ttar_db = db.connect(config.get('db_host'),config.get('db_user'),config.get('db_password'),config.get('db_name'))\n\n\ttry:\n\t\ttar = tarfile.open(tarfilename)\n\t\tlog.logger.debug('Succesfully opened ' + tarfilename)\n\texcept Exception as e:\n\t\tlog.logger.critical('Fail during opening ' + tarfilename )\n\t\tlog.logger.debug(e)\n\t\traise Exception\n\n\ttry:\n\t\tmembers = tar.getnames()\n\t\tlog.logger.debug('Succesfully indexed tar file ' + tarfilename)\n\texcept Exception as e:\n\t\tlog.logger.critical('Fail during opening ' + tarfilename )\n\t\tlog.logger.debug(e)\n\t\traise Exception\n\ttotaller = 0\n\tfor i in range(len(members)):\n\t\tmember = members[i]\n\t\tif member.split('/')[-1].split('.')[-1] in __MIME__:\n\t\t\ttotaller = totaller + 1\n\t\t\tfullpath = member\n\t\t\ttar_index = i\n\t\t\tfilename = member.split('/')[-1]\n\t\t\tname = filename[0:-len(filename.split('.')[-1])-1]\n\t\t\tt = tarfilename.split('.')[0].split('_')[-1]\n\t\t\ttar_date = datetime(int(t[:4]),int(t[4:6]),int(t[6:8]),int(t[8:10]),int(t[10:12]),int(t[12:]))\n\t\t\tindex_date = datetime.now()\n\t\t\tif '-2013-' in name:\n\t\t\t\tproccessed_2013 = 0\n\t\t\telse:\n\t\t\t\tproccessed_2013 = 1\n\n\t\t\tq = 'INSERT INTO tar_index (tar,filename,tar_index,name,index_date,tar_date,processed_2013) VALUES (\\\n\t\t\t\"' + tarfilename + '\",\\\n\t\t\t\"' + fullpath + '\",\\\n\t\t\t\"' + str(tar_index) + '\",\\\n\t\t\t\"' + name + '\",\\\n\t\t\t\"' + str(index_date) + '\",\\\n\t\t\t\"' + str(tar_date) + '\",\\\n\t\t\t\"' + str(proccessed_2013) + '\"\\\n\t\t\t)'\n\t\t\ttry:\n\t\t\t\tdb.update(tar_db,q)\n\t\t\texcept Exception as e:\n\t\t\t\tlog.logger.critical('Could not add record ' + fullpath + ' from ' + tarfilename + ' this is a CRITICAL -> EXITING')\n\t\t\t\texit(1)\n\t\tlog.logger.info('Indexed ' + str(totaller) + ' files from tar: ' + tarfilename)\n","sub_path":"lib/restore.py","file_name":"restore.py","file_ext":"py","file_size_in_byte":7943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"289452417","text":"import argparse\nfrom os.path import abspath\nimport json\nfrom logging.config import dictConfig\n\nfrom sm.engine.util import sm_log_config, SMConfig\nfrom sm.engine import ESIndexManager\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Create ElasticSearch indices')\n parser.add_argument('--conf', default='conf/config.json', help=\"SM config path\")\n parser.add_argument('--drop', action='store_true', help='Delete index if exists')\n args = parser.parse_args()\n\n dictConfig(sm_log_config)\n SMConfig.set_path(args.conf)\n\n es_config = SMConfig.get_conf()['elasticsearch']\n es_man = ESIndexManager(es_config)\n alias = es_config['index']\n index = es_man.internal_index_name(alias)\n\n if args.drop:\n es_man.delete_index(index)\n es_man.create_index(index)\n es_man.remap_alias(index, alias)\n","sub_path":"scripts/create_es_index.py","file_name":"create_es_index.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"539403243","text":"import requests\nimport json\nfrom config import *\n\nclass tvdbApi:\n\tdef __init__(self, key):\n\t\tdataJson = {\"apikey\" : key}\n\t\tr = requests.post(\"https://api.thetvdb.com/login\", headers={\"content-type\":\"application/json\", \"accept\":\"application/json\"}, data=json.dumps(dataJson))\n\t\tself.token = r.json()['token']\n\tdef searchID(self, que):\n\t\tr = requests.get(\"https://api.thetvdb.com/search/series\", headers={\"accept\":\"application/json\", \"authorization\":\"Bearer \"+self.token}, params = {\"name\":que})\n\t\ttry:\n\t\t\tID = r.json()['data'][0]['id']\n\t\texcept:\n\t\t\tID = False\n\t\treturn ID\n\tdef getIList(self, ID):\n\t\tr = requests.get(\"https://api.thetvdb.com/series/{}/images/query/params\".format(ID), headers={\"accept\":\"application/json\", \"authorization\":\"Bearer \"+self.token})\n\t\tprint(json.dumps(r.json(), indent=4, sort_keys=True))\n\tdef getPosters(self, ID):\n\t\tr = requests.get(\"https://api.thetvdb.com/series/{}/images/query\".format(ID), headers={\"accept\":\"application/json\", \"authorization\":\"Bearer \"+self.token}, params = {\"keyType\":\"poster\"})\n\t\tdata = r.json()['data']\n\t\tret = []\n\t\tfor images in data:\n\t\t\tret.append(images[\"fileName\"])\n\t\treturn ret\n\tdef getBanners(self, ID):\n\t\tr = requests.get(\"https://api.thetvdb.com/series/{}/images/query\".format(ID), headers={\"accept\":\"application/json\", \"authorization\":\"Bearer \"+self.token}, params = {\"keyType\":\"series\"})\n\t\tdata = r.json()['data']\n\t\tret = []\n\t\tfor images in data:\n\t\t\tret.append(images[\"fileName\"])\n\t\treturn ret\n\tdef getImage(self, link):\n\t\tif link:\n\t\t\tr = requests.get(\"https://www.thetvdb.com/banners/\"+link, headers={\"authorization\":\"Bearer \"+self.token})\n\t\t\tif r.status_code == 200:\n\t\t\t\timage = r.content\n\t\t\t\treturn image\n\t\t\treturn False\n\t\treturn False\n\tdef getFromString(self, tip, ID):\n\t\tif tip == \"banner\":\n\t\t\treturn self.getBanners(ID)\n\t\tif tip == \"poster\":\n\t\t\treturn self.getPosters(ID)\n\n# api = tvdbApi(tvdb_key)\n# ID = api.searchID(\"Lucifer\")\n# print(api.getBanners(ID))\n# print(api.getPosters(ID))\n# api.getIList(ID)","sub_path":"tvdbApi.py","file_name":"tvdbApi.py","file_ext":"py","file_size_in_byte":1974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"485167795","text":"class Node:\n\tdef __init__(self, parent, value):\n\t\tself.values = [value]\n\t\tself.parent = parent\n\t\tself.children = []\n\t\t\n\t\t\n\tdef __repr__(self):\n\t\treturnstr = \"Node: \"\n\t\t\n\t\tfor i in range(len(self.values)):\n\t\t\treturnstr += str(self.values[i]) + \" \"\n\t\t\t\n\t\treturnstr += \" (has \" + str(len(self.children)) + \" children)\"\n\t\t\t\n\t\treturn returnstr\n\t\t\n\t\t\n\tdef is_leaf(self):\n\t\treturn len(self.children) == 0\n\t\t\n\t\t\n\tdef is_full(self):\n\t\treturn len(self.values) >= 3\n\n\tdef is_full2(self):\n\t\treturn len(self.values) >= 2 \n\t\t\n\t\t\n\tdef is_root(self):\n\t\treturn self.parent == None\n\n\t\t\t\n\n\n\n\tdef split(self):\n\t\t\"\"\"Splits a node with 3 values into 3 nodes, with the middle value being the parent of the other two.\"\"\"\n\t\tself.values.append(6)\n\t\tself.values.append(7)\n\t\tprint(self.values)\n\t\tif self.is_root():\n\t\t\tlchild = Node(self, self.values[0])\n\t\t\trchild = Node(self, self.values[2])\n\t\t\tlchild.children = []\n\t\t\trchild.children = []\n\n\t\t\tfor i in range(len(self.children)):\n\t\t\t\tif self.children[i] < self.values[1]:\n\t\t\t\t\tlchild.children.append(self.children[i])\n\t\t\t\telse:\n\t\t\t\t\trchild.children.append(self.children[i])\n\t\t\tfor i in range(len(lchild.children)):\n\t\t\t\tlchild.children[i].parent = lchild\n\t\t\tfor j in range(len(rchild.children)):\n\t\t\t\trchild.children[j].parent = rchild\n\t\t\t\n\t\t\tself.values = [self.values[1]]\n\t\t\t\n\t\t\tself.children = [lchild,rchild]\n\t\t\t\n\t\t\treturn self\n\t\telse:\n\t\t\tself.mergesplit()\n\t\t\t\n\t\t\treturn self.parent\n\n\tdef mergesplit(self):\n\t\t\"\"\"\"Splits a node with 3 by merging the middle value to the parent, and having the two outer values become children of said parent.\"\"\"\n\t\t\n\t\t# Parent has one value\n\t\tif len(self.parent.values) == 1:\n\t\t\tif self.values[1] < self.parent.values[0]: # Node is left child\n\t\t\t\tself.parent.values.insert(0, self.values[1])\n\t\t\t\t\t\n\t\t\t\t# New node\n\t\t\t\tnewnode = Node(self.parent, self.values[2])\n\t\t\t\tself.parent.children.insert(1, newnode)\n\t\t\t\t\n\t\t\t\tif not self.is_leaf():\n\t\t\t\t\tnewnode.children = [self.children[2], self.children[3]]\n\t\t\t\t\tnewnode.children[0].parent = newnode\n\t\t\t\t\tnewnode.children[1].parent = newnode\n\t\t\t\t\n\t\t\t\t# Old (reused) node\n\t\t\t\t\tself.children = [self.children[0], self.children[1]]\n\t\t\t\tself.values = [self.values[0]]\n\t\t\t\t\n\t\t\t\treturn\n\t\t\telse: # Node is right child\n\t\t\t\tself.parent.values.insert(1, self.values[1])\n\t\t\t\t\t\n\t\t\t\t# New node\n\t\t\t\tnewnode = Node(self.parent, self.values[0])\n\t\t\t\tself.parent.children.insert(1, newnode)\n\t\t\t\t\n\t\t\t\tif not self.is_leaf():\n\t\t\t\t\tnewnode.children = [self.children[0], self.children[1]]\n\t\t\t\t\tnewnode.children[0].parent = newnode\n\t\t\t\t\tnewnode.children[1].parent = newnode\n\t\t\t\t\n\t\t\t\t# Old (reused) node\n\t\t\t\t\tself.children = [self.children[2], self.children[3]]\n\t\t\t\tself.values = [self.values[2]]\n\t\t\t\t\n\t\t\t\treturn\n\t\t\t\n\t\t# Parent has two values\n\t\tif len(self.parent.values) == 2:\n\t\t\tif self.values[1] < self.parent.values[0]: # Node is left child\n\t\t\t\tself.parent.values.insert(0, self.values[1])\n\t\t\t\t\n\t\t\t\t# New node\n\t\t\t\tnewnode = Node(self.parent, self.values[2])\n\t\t\t\tself.parent.children.insert(1, newnode)\n\t\t\t\t\n\t\t\t\tif not self.is_leaf():\n\t\t\t\t\tnewnode.children = [self.children[2], self.children[3]]\n\t\t\t\t\tnewnode.children[0].parent = newnode\n\t\t\t\t\tnewnode.children[1].parent = newnode\n\t\t\t\t\n\t\t\t\t# Old (reused) node\n\t\t\t\t\tself.children = [self.children[0], self.children[1]]\n\t\t\t\tself.values = [self.values[0]]\n\n\t\t\t\treturn\n\t\t\telif self.values[1] < self.parent.values[1]: # Node is middle child\n\t\t\t\tself.parent.values.insert(1, self.values[1])\n\t\t\t\t\n\t\t\t\t# New node\n\t\t\t\tnewnode = Node(self.parent, self.values[2])\n\t\t\t\tself.parent.children.insert(2, newnode)\n\t\t\t\t\n\t\t\t\tif not self.is_leaf():\n\t\t\t\t\tnewnode.children = [self.children[2], self.children[3]]\n\t\t\t\t\tnewnode.children[0].parent = newnode\n\t\t\t\t\tnewnode.children[1].parent = newnode\n\t\t\t\t\n\t\t\t\t# Old (reused) node\n\t\t\t\t\tself.children = [self.children[0], self.children[1]]\n\t\t\t\tself.values = [self.values[0]]\n\n\t\t\t\treturn\n\t\t\telse:\n\t\t\t\tself.parent.values.insert(2, self.values[1])\n\t\t\t\t\n\t\t\t\t# New node\n\t\t\t\tnewnode = Node(self.parent, self.values[0])\n\t\t\t\tself.parent.children.insert(2, newnode)\n\t\t\t\t\n\t\t\t\tif not self.is_leaf():\n\t\t\t\t\tnewnode.children = [self.children[0], self.children[1]]\n\t\t\t\t\tnewnode.children[0].parent = newnode\n\t\t\t\t\tnewnode.children[1].parent = newnode\n\t\t\t\t\n\t\t\t\t# Old (reused) node\n\t\t\t\t\tself.children = [self.children[2], self.children[3]]\n\t\t\t\tself.values = [self.values[2]]\n\n\t\t\t\treturn\n\t\t\t\n\t\t\t\n\tdef add_value(self, value):\n\t\tif not self.is_full2():\n\t\t\tself.values.append(value)\n\t\t\tself.values.sort()\n\t\telse:\n\t\t\tprint(\"ERROR: Node already has 2 values.\\n(tried to insert \" + str(value) + \")\")\n\n\tdef goto_subtree(self, value):\n\t\t\"\"\"Returns the subtree/child where the value needs to be inserted\"\"\"\n\t\tif self.is_leaf():\n\t\t\tprint(\"ERROR: This node is a leaf.\\n(tried to insert \" + str(value) + \")\")\n\t\t\treturn\n\t\t\t\n\t\tfor i in range(len(self.values)):\n\t\t\tif self.values[i] > value:\n\t\t\t\treturn self.children[i]\n\t\t\t\n\t\treturn self.children[-1]\n\n\tdef child_index(self):\n\t\t# Returns which location the Node has in its parent's children list.\n\t\tif self.is_root():\n\t\t\tprint(\"The root has no parent!\")\n\t\t\treturn False\n\t\t\n\t\tfor i in range(len(self.parent.children)):\n\t\t\tif self.parent.children[i] == self:\n\t\t\t\treturn i\n\n\t\t\nclass TwoThreeTree:\n\tdef __init__(self):\n\t\tself.root = None\n\t\tself.traverselist = []\n\t\t\n\t\t\n\tdef inorder(self, subtree):\n\t\tcurnode = subtree\n\n\t\tif curnode.is_leaf():\n\t\t\tfor i in range(len(curnode.values)):\n\t\t\t\tself.traverselist.append(curnode.values[i])\n\t\t\treturn\n\t\t\n\t\tself.inorder(curnode.children[0])\n\t\tfor i in range(len(curnode.values)):\n\t\t\tself.traverselist.append(curnode.values[i])\n\t\t\tself.inorder(curnode.children[i+1])\n\t\t\n\t\t\n\tdef d_rebuild(self, value):\n\t\tself.traverselist = []\n\t\tself.inorder(self.root)\n\t\tself.traverselist.remove(value)\n\t\tself.root = None\n\t\tfor i in range(len(self.traverselist)):\n\t\t\tself.insert(\"\", self.traverselist[i])\n\n\tdef insert(self, searchkey, value):\n\t\tif self.root == None: # Empty Tree\n\t\t\tself.root = Node(None, value)\n\t\t\treturn\n\t\telse:\n\t\t\tself.insert_subtree(self.root, value) # Tree is not empty\n\n\n\tdef insert_subtree(self, subtree, value):\n\t\tcurnode = subtree\n\n\t\tif curnode.is_leaf(): # current node is a leaf\n\t\t\tif not curnode.is_full2(): # current node is not full\n\t\t\t\tcurnode.add_value(value)\n\t\t\t\treturn\n\n\t\t\telse:\n\t\t\t\tcurnode.add_value(value)\n\t\t\t\t# # print(\"Splitting node: \" + str(curnode))\n\t\t\t\tcurnode = curnode.split()\n\t\t\t\t# # print(\"Current node is now: \" + str(curnode))\n\t\t\t\t\n\t\t\t\t# Curnode is now the parent of a leaf\n\n\t\t\t\tif len(curnode.values) == 3:\n\n\t\t\t\t\tcurnode = curnode.split()\n\n\n\n\t\telse:\n\t\t\tself.insert_subtree(curnode.goto_subtree(value), value)\n\n\tdef __repr__(self):\n\t\treturnstr = \"\\nTTFTree:\\n\\nRoot: \" + str(self.root)\n\t\t\n\t\treturn returnstr\n\t\t\n\t\n\tdef get(self, value):\n\t\tif self.root != None:\n\t\t\tnode = self.find_node(value, self.root)\n\t\telse:\n\t\t\treturn False\n\n\t\tif node != False:\n\t\t\tfor i in range(3):\n\t\t\t\tif node.values[i] == value:\n\t\t\t\t\treturn node.values[i]\n\t\telse:\n\t\t\treturn False\n\n\tdef get_all(self):\n\t\tself.traverselist = []\n\t\tself.inorder(self.root)\n\t\t\n\t\treturn self.traverselist\n\n\n\tdef find_node(self, value, subtree):\n\t\tcurnode = subtree\n\t\t\n\t\tif value in curnode.values:\n\t\t\treturn curnode\n\t\t\n\t\t\t\n\t\telse:\n\t\t\treturn self.find_node(value, curnode.goto_subtree(value))\n\n\tdef delete(self, value):\n\t\tto_delete = self.find_node(value, self.root)\n\t\t\n\t\tif to_delete == False:\n\t\t\treturn False\n\t\tif to_delete.is_root():\n\t\t\tif len(to_delete.values == 1):\n\t\t\t\tto_delete.values.pop()\n\t\t\t\treturn\n\t\tif to_delete.is_leaf():\n\t\t\tif len(to_delete.values) > 1:\n\t\t\t\tfor i in range(len(to_delete.values)):\n\t\t\t\t\tif to_delete.values[i] == value:\n\t\t\t\t\t\tto_delete.values.pop(i)\n\t\t\t\t\t\treturn\n\t\t\telse:\n\t\t\t\tself.d_rebuild(value)\n\t\t\t\treturn\n\t\telse:\n\t\t\ttakeClosest = lambda num, collection:min(collection,key=lambda x:abs(x-num))\n\t\t\tswap = takeClosest(value, to_delete.children)\n\t\t\tvalue1 = value\n\t\t\tvalue2 = swap\n\t\t\tto_delete.values.remove(value)\n\t\t\tto_delete.values.append(value2)\n\t\t\tto_delete.values.sort()\n\t\t\tto_delete.children.remove(swap)\n\t\t\tto_delete.children.append(value1)\n\t\t\tto_delete.children.sort()\n\t\t\tdelete(self, value)\n","sub_path":"TTTree.py","file_name":"TTTree.py","file_ext":"py","file_size_in_byte":8010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"196722471","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.7-x86_64/egg/gorgou/iciba.py\n# Compiled at: 2018-02-10 05:05:41\n# Size of source mod 2**32: 783 bytes\nimport os, requests, json\ndire = os.path.dirname(os.path.abspath(__file__))\n\ndef get_mp3(db_word, pen_dir=dire):\n purl = 'http://fy.iciba.com/ajax.php?a=fy&w=' + db_word\n ptext = requests.get(purl).text\n obj = json.loads(ptext)\n pstatus = obj['status']\n pcontent = obj['content']\n if pstatus == 0:\n cn_mean = pcontent['word_mean']\n br_vo = pcontent['ph_en']\n am_vo = pcontent['ph_am']\n en_mp3 = pcontent['ph_en_mp3']\n am_mp3 = pcontent['ph_am_mp3']\n pcontent = requests.get(en_mp3).content\n pen_mp3 = os.path.join(pen_dir + '/', db_word + '.mp3')\n with open(pen_mp3, 'wb') as (f):\n f.write(pcontent)\n return cn_mean","sub_path":"pycfiles/gorgou-1.1.3-py3.6/iciba.cpython-36.py","file_name":"iciba.cpython-36.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"253841256","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n# \n# Add a new user to the current samba4 domain\n# make sure all needed parameters are given and force the use of \n# Unix IDs and OTP\n#\n\nimport sys, argparse\nimport subprocess\nimport unicodedata\n\ndef main():\n\n parser = argparse.ArgumentParser(description = 'Ajouter un utilisateur Samba4')\n parser.add_argument('-u', '--username', nargs = '+', help = 'username')\n parser.add_argument('-s', '--sambaid', nargs = '+', help = 'sambaid')\n parser.add_argument('-gn', '--givenName', nargs = '+', help = 'givenname')\n parser.add_argument('-sn', '--surname', nargs = '+', help = 'surname')\n parser.add_argument('-gp', '--groupname', nargs = '+', help = 'groupname')\n args = parser.parse_args(sys.argv[1:])\n\n username = args.username[0]\n sambaid = args.sambaid[0]\n surname = args.surname[0].decode('utf-8')\n givenName = args.givenName[0].decode('utf-8')\n groupname = args.groupname[0]\n\n\n # delete non ascii\n surname = unicodedata.normalize('NFKD', surname).encode('ascii', 'ignore')\n givenName = unicodedata.normalize('NFKD', givenName).encode('ascii', 'ignore')\n\n subprocess.call([\"samba-tool\", \"user\", \"add\", \\\n username,\"pass\", \\\n \"--surname=\"+surname, \\\n \"--given-name=\"+givenName, \\\n \"--uid-number=\"+sambaid, \\\n \"--gid-number=100\", \\\n \"--must-change-at-next-login\" \\\n ])\n\n subprocess.call([\"samba-tool\", \"group\", \"addmembers\", groupname, username])\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"adduser.py","file_name":"adduser.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"627874744","text":"square1 = [ [23, 28, 21], [22, 24, 26], [27, 20, 25] ]\n\ndef row_check(square):\n \n row_check = True\n\n for row in square:\n \n if sum(row) == sum(square[0]):\n row_check = True\n else:\n row_check = False\n break\n\n return row_check\n\n# print(row_check(square1))\n\ndef col_check(square):\n\n col_check = True\n\n for index in range(0, len(square[0])):\n sum_col = 0\n for row in square:\n\n sum_col += row[index]\n\n if sum_col == sum(square[0]):\n col_check = True\n else:\n col_check = False\n break\n\n return col_check\n\n# print(col_check(square1))\n\ndef main_diag_check(square):\n\n main_diag_check = True\n\n index = 0\n sum_main_diag = 0\n\n for row in square:\n sum_main_diag += row[index]\n\n index += 1\n\n if sum_main_diag == sum(square[0]):\n main_diag_check = True\n else:\n main_diag_check = False\n\n return main_diag_check\n\n# print(main_diag_check(square1))\n\ndef second_diag_check(square):\n \n second_diag_check = True\n\n index = len(square) - 1\n sum_second_diag = 0\n\n for row in square:\n sum_second_diag += row[index]\n index -= 1\n\n if sum_second_diag == sum(square[0]):\n second_diag_check = True\n else:\n second_diag_check = False\n\n return second_diag_check\n\n# print(second_diag_check(square1))\n\ndef magic_square(square):\n magic_square = True\n if row_check(square) and col_check(square) and main_diag_check(square) and second_diag_check(square) == True:\n magic_square = True\n else:\n magic_square = False\n\n return magic_square\n\nprint(magic_square(square1))\n","sub_path":"Programming0-1/week5/4-Magic-Square/magic.py","file_name":"magic.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"366170682","text":"#关于concurrent的案例\nfrom concurrent.futures import ThreadPoolExecutor\nimport time\n\ndef return_future(msg):\n time.sleep(3)\n return msg\n\n# 创建一个线程池\npool = ThreadPoolExecutor(max_workers=2) # 制定2个线程\n\n# 往线程池加入2个task\nf1 = pool.submit(return_future,\"hello\")\nf2 = pool.submit(return_future,\"world\")\n\n# 等待执行完毕\nprint(f1.done())\ntime.sleep(3)\nprint(f2.done())\n\n# 结果\nprint(f1.result())\nprint(f2.result())\n","sub_path":"协程/07.py","file_name":"07.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"371807181","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 21 16:11:41 2017\n\n@author: subum\n\"\"\"\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 21 11:28:15 2017\n\n@author: subum\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 19 12:52:23 2017\n\n@author: subum\n\"\"\"\nimport numpy as np\nfrom scipy.ndimage.filters import gaussian_filter\nfrom scipy import ndimage\nimport scipy.ndimage\n\n\n\ndef gs_filter(img, sigma):\n if type(img) != np.ndarray:\n raise TypeError('Input image must be of type ndarray.')\n else:\n return gaussian_filter(img, sigma)\n\n\ndef gradient_intensity(img):\n preSobel = np.array([[[2, 4, 2], [0, 0, 0], [-2, -4, -2]],\n [[4, 8, 4], [0, 0, 0], [-4, -8, -4]],\n [[2, 4, 2], [0, 0, 0], [-2, -4, -2]]], np.int32)\n # Kernel for Gradient in y-direction\n dx = ndimage.sobel(preSobel, 0) # x derivative\n dy = ndimage.sobel(preSobel, 1) # y derivative\n dz = ndimage.sobel(preSobel, 2) # z derivative\n # Apply kernels to the image\n Ix = ndimage.filters.convolve(img, dx)\n Iy = ndimage.filters.convolve(img, dy)\n Iz = ndimage.filters.convolve(img, dz)\n\n G = abs(Ix) + abs(Iy) + abs(Iz)\n\n D2 = np.arctan2(Iz, Iy)\n print(D2)\n return (G, D2)\n\n\ndef round_angle(angle):\n angle = np.rad2deg(angle) % 180\n if (0 <= angle < 22.5) or (157.5 <= angle < 180):\n angle = 0\n elif (22.5 <= angle < 67.5):\n angle = 45\n elif (67.5 <= angle < 112.5):\n angle = 90\n elif (112.5 <= angle < 157.5):\n angle = 135\n return angle\n\n\ndef suppression(img, D):\n M, N, O = img.shape\n Z = np.zeros((M, N, O), dtype=np.int32)\n\n for i in range(M):\n for j in range(N):\n for k in range(O):\n # find neighbour pixels to visit from the gradient directions\n where = round_angle(D[i, j, k])\n try:\n if where == 0:\n if (img[i, j, k] >= img[i, j - 1, k]) and (img[i, j, k] >= img[i, j + 1, k]):\n Z[i, j, k] = img[i, j, k]\n elif where == 90:\n if ((img[i, j, k] >= img[i - 1, j, k]) and (img[i, j, k] >= img[i + 1, j, k])\n and (img[i, j, k] >= img[i, j, k - 1]) and (img[i, j, k] >= img[i, j, k + 1])):\n Z[i, j, k] = img[i, j, k]\n elif where == 135:\n if ((img[i, j, k] >= img[i, j + 1, k + 1]) and (img[i, j, k] >= img[i, j - 1, k + 1])\n and (img[i, j, k] >= img[i + 1, j, k + 1]) and (img[i, j, k] >= img[i - 1, j, k + 1])\n and (img[i, j, k] >= img[i, j + 1, k - 1]) and (img[i, j, k] >= img[i, j - 1, k - 1])\n and (img[i, j, k] >= img[i + 1, j, k - 1]) and (img[i, j, k] >= img[i - 1, j, k - 1])):\n Z[i, j, k] = img[i, j, k]\n elif where == 45:\n if ((img[i, j, k] >= img[i + 1, j + 1, k + 1]) and (img[i, j, k] >= img[i + 1, j - 1, k - 1])\n and (img[i, j, k] >= img[i + 1, j - 1, k + 1]) and (img[i, j, k] >= img[i - 1, j + 1, k + 1])\n and (img[i, j, k] >= img[i - 1, j - 1, k + 1]) and (img[i, j, k] >= img[i + 1, j + 1, k - 1])\n and (img[i, j, k] >= img[i - 1, j + 1, k - 1]) and (img[i, j, k] >= img[i + 1, j, k - 1])\n and (img[i, j, k] >= img[i - 1, j - 1, k]) and (img[i, j, k] >= img[i + 1, j + 1, k])\n and (img[i, j, k] >= img[i - 1, j + 1, k]) and (img[i, j, k] >= img[i + 1, j - 1, k])):\n Z[i, j, k] = img[i, j, k]\n except IndexError as e:\n \"\"\" Todo: Deal with pixels at the image boundaries. \"\"\"\n pass\n return Z\n\n\ndef threshold(img, t, T):\n cf = {'WEAK': np.int32(50), 'STRONG': np.int32(255), }\n\n # get strong pixel indices\n strong_i, strong_j, strong_k = np.where(img > T)\n\n # get weak pixel indices\n weak_i, weak_j, weak_k = np.where((img >= t) & (img <= T))\n\n # get pixel indices set to be zero\n zero_i, zero_j, zero_k = np.where(img < t)\n\n # set values\n img[strong_i, strong_j, strong_k] = cf.get('STRONG')\n img[weak_i, weak_j, weak_k] = cf.get('WEAK')\n img[zero_i, zero_j, zero_k] = np.int32(0)\n\n return (img, cf.get('WEAK'))\n\n\ndef tracking(img, weak, strong=255):\n M, N, O = img.shape\n for i in range(M):\n for j in range(N):\n for k in range(O):\n if img[i, j, k] == weak:\n # check if one of the neighbours is strong (=255 by default)\n try:\n if ((img[i, j + 1, k] == strong) or (img[i, j + 1, k + 1] == strong)\n or (img[i, j + 1, k - 1] == strong) or (img[i, j - 1, k] == strong)\n or (img[i, j - 1, k + 1] == strong) or (img[i, j - 1, k - 1] == strong)\n or (img[i + 1, j, k] == strong) or (img[i, j, k + 1] == strong)\n or (img[i, j, k - 1] == strong) or (img[i - 1, j, k] == strong)\n or (img[i - 1, j, k + 1] == strong) or (img[i - 1, j, k - 1] == strong)\n or (img[i - 1, j - 1, k] == strong) or (img[i - 1, j, k + 1] == strong)\n or (img[i - 1, j - 1, k - 1] == strong) or (img[i - 1, j + 1, k] == strong)\n or (img[i - 1, j + 1, k + 1] == strong) or (img[i - 1, j + 1, k - 1] == strong)\n or (img[i + 1, j, k + 1] == strong) or (img[i + 1, j, k - 1] == strong)\n or (img[i + 1, j + 1, k] == strong) or (img[i + 1, j + 1, k + 1] == strong)\n or (img[i + 1, j + 1, k - 1] == strong) or (img[i + 1, j - 1, k] == strong)\n or (img[i + 1, j - 1, k - 1] == strong) or (img[i + 1, j - 1, k + 1] == strong)):\n img[i, j, k] = strong\n else:\n img[i, j, k] = 0\n except IndexError as e:\n pass\n return img\n\n\n","sub_path":"Canny1.py","file_name":"Canny1.py","file_ext":"py","file_size_in_byte":6233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"180303425","text":"import matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\ndef plot_grid_1d(grid_search_cv, ax=None):\r\n if ax is None:\r\n ax = plt.gca()\r\n if len(grid_search_cv.param_grid.keys()) > 1:\r\n raise ValueError(\"More then one parameter found. Can't do 1d plot.\")\r\n \r\n score_means, score_stds = zip(*[(np.mean(score.cv_validation_scores), np.std(score.cv_validation_scores))\r\n for score in grid_search_cv.grid_scores_])\r\n score_means, score_stds = np.array(score_means), np.array(score_stds)\r\n parameters = grid_search_cv.param_grid.values()[0]\r\n artists = []\r\n artists.extend(ax.plot(score_means))\r\n artists.append(ax.fill_between(range(len(parameters)), score_means - score_stds,\r\n score_means + score_stds, alpha=0.2, color=\"b\"))\r\n ax.set_xticklabels(parameters)\r\n return artists","sub_path":"notebooks/scikit/Advanced-Machine-Learning-with-scikit-learn-Working-Files/Chapter-7/figures.py","file_name":"figures.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"228862528","text":"import sqlite3\nfrom datetime import datetime\n\nfrom Database import User, Repository, Order, Product\nfrom Response import Response\n\n\nclass UserController:\n def __init__(self):\n self.repo = Repository(User)\n self.repo_orders = Repository(Order)\n self.repo_products = Repository(Product)\n\n # GET ########################\n\n def get(self, id=None):\n if id is None:\n users = self.repo.get()\n return Response(True, users)\n\n user = self.repo.get(id)\n if user is None:\n return Response(False, \"Not found\", 404)\n return Response(True, user)\n\n def get_order(self, id, order_id=None):\n user = self.get(id)\n if not user.success:\n return user\n user = user.data\n if order_id is None:\n return Response(True, user.orders)\n order = list(filter(lambda o: o.id == int(order_id), user.orders))\n if len(order) == 0:\n return Response(False, \"Not found\", 404)\n return Response(True, order[0])\n\n def get_products(self, id, order_id, product_id=None):\n order = self.get_order(id, order_id)\n if not order.success:\n return order\n order = order.data\n if product_id is None:\n return Response(True, order.products)\n products = list(filter(lambda p: p.id == int(product_id), order.products))\n if len(products) == 0:\n return Response(False, \"Not found\", 404)\n return Response(True, products[0])\n\n # DELETE ########################\n\n def delete(self, id):\n user = self.repo.delete(id)\n if not user:\n return Response(False, \"Not found\", 404)\n return Response(True, '')\n\n # POST ########################\n\n def post(self, user, id=None):\n try:\n new_user = User._from_json(user)\n except Exception as e:\n return Response(False, \"Invalid data: \" + str(e), 400)\n if id is not None:\n new_user.id = id\n try:\n self.repo.create(new_user)\n except Exception as e:\n print(str(e))\n return Response(False, \"Conflict\", 409)\n return Response(True, new_user)\n\n def post_order(self, id, order, order_id=None):\n user = self.get(id)\n if not user.success:\n return user\n user = user.data\n try:\n new_order = Order._from_json(order)\n except Exception as e:\n return Response(False, \"Invalid data: \" + str(e), 400)\n place_date = datetime.strptime(new_order.place_date, \"%Y-%m-%d\").date()\n recv_date = datetime.strptime(new_order.recv_date, \"%Y-%m-%d\").date()\n if recv_date < place_date:\n return Response(False, \"Unprocessable Entity\", 422)\n if order_id is not None:\n new_order.id = order_id\n try:\n self.repo_orders.create(new_order)\n except Exception as e:\n print(str(e))\n return Response(False, \"Conflict\", 409)\n user.orders.append(new_order)\n self.repo.update()\n return Response(True, new_order)\n\n def post_product(self, id, order_id, product, product_id=None):\n order = self.get_order(id, order_id)\n if not order.success:\n return order\n order = order.data\n try:\n new_product = Product._from_json(product)\n except Exception as e:\n return Response(False, \"Invalid data: \" + str(e), 400)\n if product_id is not None:\n new_product.id = product_id\n try:\n self.repo_products.create(new_product)\n except Exception as e:\n print(str(e))\n return Response(False, \"Conflict\", 409)\n order.products.append(new_product)\n self.repo.update()\n return Response(True, new_product)\n\n # PUT ########################\n\n def put(self, user_data, id):\n user = self.get(id)\n if not user.success:\n return user\n old_user = user.data\n new_user = User._from_json(user_data)\n old_user.username = new_user.username\n old_user.address = new_user.address\n old_user.fullname = new_user.fullname\n self.repo.update()\n return Response(True, '')\n\n def put_order(self, id, order_data, order_id):\n order = self.get_order(id, order_id)\n if not order.success:\n return order\n old_order = order.data\n new_order = Order._from_json(order_data)\n old_order.recv_date = new_order.recv_date\n old_order.place_date = new_order.place_date\n old_order.cost = new_order.cost\n place_date = datetime.strptime(new_order.place_date, \"%Y-%m-%d\").date()\n recv_date = datetime.strptime(new_order.recv_date, \"%Y-%m-%d\").date()\n if recv_date < place_date:\n return Response(False, \"Unprocessable Entity\", 422)\n self.repo_orders.update()\n return Response(True, '')\n\n def put_product(self, id, order_id, product_data, product_id):\n product = self.get_products(id, order_id, product_id)\n if not product.success:\n return product\n old_product = product.data\n new_product = Product._from_json(product_data)\n old_product.name = new_product.name\n old_product.price = new_product.price\n self.repo_products.update()\n return Response(True, '')\n","sub_path":"Tema 2/UserController.py","file_name":"UserController.py","file_ext":"py","file_size_in_byte":5422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"386796442","text":"# Enter your code here. Read input from STDIN. Print output to STDOUT\r\n\r\n\r\nimport math\r\nfrom math import e\r\nwt = float(input())\r\nn = float(input())\r\nmu = float(input())\r\nsigma = float(input())\r\nmu = n * mu\r\nsigma = (n**0.5)*sigma\r\nx = 0\r\n\r\ndef cumdistri(wt, mu, sigma):\r\n x = (1/2)*(1 + math.erf((wt-mu)/(math.sqrt(2)*sigma)))\r\n return round(x,4)\r\n\r\nprint(cumdistri(wt, mu, sigma))","sub_path":"Day6_TheCentralLimitTheorem_I.py","file_name":"Day6_TheCentralLimitTheorem_I.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"615503398","text":"#!/usr/bin/python3\n\"\"\"Main program for crappy_websites project\"\"\"\nfrom urllib.parse import urlparse\nfrom urllib.error import HTTPError\nfrom args import arguments\nimport webbrowser\nfrom termcolor import colored, cprint\nfrom googlesearch import search\nfrom TestBrowser import TestBrowser\n\ndef reduceUrlToBases(urls):\n \"\"\"Return list of unique base urls\"\"\"\n returnArray =[]\n for url in urls:\n base = urlparse(url).netloc\n returnArray.append(base)\n return list(set(returnArray))\n\ndef getUrls(args):\n \"\"\"Return list of urls dependent on arguments provided\"\"\"\n TEST_SUBS = bool(args.test_subs)\n urls = []\n if args.url:\n urls.append(args.url)\n elif args.search:\n try:\n urls = list(\n search(args.search,\n stop=20,\n tld='co.uk',\n pause=7.0,\n start=args.start\n )\n )\n if not TEST_SUBS:\n oLen = len(urls)\n urls = reduceUrlToBases(urls)\n cprint(('Found %d unique bases out of %d' % (len(urls), oLen)), 'yellow')\n except HTTPError as err:\n webbrowser.open(err.url)\n print('The Google overlords have likely blocked you, you\\'ll have to wait a little while :( Try increasing the pause parameter above')\n \n return urls\n\ndef testUrl(args, url):\n \"\"\"Test a url and display appropriate results\"\"\"\n THRESHOLD_TIME = float(args.min_time)\n THRESHOLD_SIZE = float(args.min_size)\n VERBOSE = bool(args.verbose)\n cprint(('Opening %s:') % url, 'blue')\n browser = TestBrowser(url)\n browser.setUpBrowser()\n data = browser.getPageInfo()\n browser.killBrowser()\n totalTime = data['backendTime'] + data['frontendTime']\n size = data['size']\n secure = ('https:' in data['protocol'])\n outString = (' %s : Total Time = %2.3f (%2.3f + %2.3f), Size = %2.3f, secure = %s' % (data['url'], totalTime, data['backendTime'], data['frontendTime'], size, str(secure)))\n if (size >= THRESHOLD_SIZE or totalTime >= THRESHOLD_TIME or not secure):\n cprint(outString, 'red')\n elif(args.url):\n cprint(outString, 'blue')\n elif(VERBOSE):\n cprint(outString, 'green')\n \n \n\ndef main():\n \"\"\"Main function\"\"\"\n args = arguments()\n urls = getUrls(args)\n\n for url in urls:\n testUrl(args=args, url=url)\n \nif __name__ == \"__main__\":\n main()","sub_path":"crappy_sites.py","file_name":"crappy_sites.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"510719713","text":"\nmenu = 'Choose the action: ' \\\n '\\n 1. All the info by ID' \\\n '\\n 2. All the info by ISBN' \\\n '\\n 3. The number of books by the publishing date' \\\n '\\n 4. The average price for each publisher' \\\n '\\n 5. The most expansive book by the publisher and the release date' \\\n '\\n 6. Exit' \\\n '\\n'\n\nid_search_inp = 'Type in the book\\'s ID: '\nid_search_lst = ['EAN: ', 'ISBN: ', 'Author: ', 'Title: ', 'Publisher: ', 'Printing: ', 'Year of publishing: ',\n 'Format: ', 'Price: ']\n\nisbn_search_inp = 'Type in the book\\'s ISBN: '\nisbn_search_lst = ['ID: ', 'EAN: ', 'Author: ', 'Title: ', 'Publisher: ', 'Printing: ', 'Year of publishing: ',\n 'Format: ', 'Price: ']\n\nbk_qt_inp = 'Type in the year of publishing: '\nbk_qt_prt = 'The number of books of the {} year is: '\n\navg_price = 'The average price for each publisher: '\n\nm_exp_pub = 'Type in the Publisher: '\nm_exp_year = 'Type in the year of publishing: '\nm_exp_prt = 'All the info about {} publisher\\'s book of {} year:'\nm_exp_lst = ['ID: ', 'EAN: ', 'ISBN: ', 'Author: ', 'Title: ', 'Printing: ',\n 'Format: ', 'Price: ']\n","sub_path":"loceng.py","file_name":"loceng.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"155204584","text":"#!/usr/bin/env python3\n# Nexrad dataset class\n# Author: Yuping Lu <yupinglu89@gmail.com>\n# Last Update: 12/19/2018\n\n# load libs\nimport os\nimport random\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom torch.utils.data import Dataset\n\n__all__ = [\"NexradDataset\", \"RandomHorizontalFlip\", \"RandomVerticalFlip\", \"ToTensor\", \"Normalize\", \"RandomCrop\"]\n\nclass NexradDataset(Dataset):\n \"\"\" NEXRAD dataset. \"\"\"\n \n def __init__(self, root, transform=None):\n \"\"\"\n Args:\n root (string): Directory with all the nexrad data.\n transform (callable, optional): Optional transform to be applied on a sample.\n \"\"\"\n self.root = root\n self.categories = sorted(os.listdir(root))\n self.cat2idx = dict(zip(self.categories, range(len(self.categories))))\n self.idx2cat = dict(zip(self.cat2idx.values(), self.cat2idx.keys()))\n self.files = []\n \n for (dirpath, dirnames, filenames) in os.walk(self.root):\n for f in filenames:\n if f.endswith('.csv'):\n o = {}\n o['radar_path'] = dirpath + '/' + f\n o['category'] = self.cat2idx[dirpath[dirpath.rfind('/')+1:]]\n self.files.append(o)\n \n self.transform = transform\n \n def __len__(self):\n return len(self.files)\n\n def __getitem__(self, idx):\n radar_path = self.files[idx]['radar_path']\n category = self.files[idx]['category']\n radar = np.loadtxt(radar_path, delimiter=',')\n radar = radar.reshape((4, 60, 60))\n sample = {'radar': radar, 'category': category}\n \n if self.transform:\n sample = self.transform(sample)\n\t\t\t\n return sample\n\nclass RandomHorizontalFlip(object):\n \"\"\"Horizontally flip the given dataset randomly with a given probability.\n Args:\n p (float): probability of the dataset being flipped. Default value is 0.5\n \"\"\"\n\n def __init__(self, p=0.5):\n self.p = p\n\n def __call__(self, sample):\n if random.random() < self.p:\n sample['radar'] = np.copy(np.flip(sample['radar'], 2))\n return sample\n\nclass RandomVerticalFlip(object):\n \"\"\"Vertically flip the given dataset randomly with a given probability.\n Args:\n p (float): probability of the dataset being flipped. Default value is 0.5\n \"\"\"\n\n def __init__(self, p=0.5):\n self.p = p\n\n def __call__(self, sample):\n if random.random() < self.p:\n sample['radar'] = np.copy(np.flip(sample['radar'], 1))\n return sample\n\n \nclass ToTensor(object):\n \"\"\"Convert ndarrays in sample to Tensors.\"\"\"\n\n def __call__(self, sample):\n radar, category = sample['radar'], sample['category']\n return {'radar': torch.from_numpy(radar).to(torch.float),\n 'category': torch.from_numpy(np.array(category, dtype=int))}\n\nclass Normalize(object):\n \"\"\"Normalize a tensor radar with mean and standard deviation.\"\"\"\n\n def __init__(self, mean, std):\n self.mean = mean\n self.std = std\n \n def __call__(self, sample):\n for t, m, s in zip(sample['radar'], self.mean, self.std):\n t.sub_(m).div_(s)\n return sample\n\nclass RandomCrop(object):\n \"\"\"Crop the given dataset at a random location.\"\"\"\n\n def __init__(self, padding=0):\n self.padding = padding\n\n def __call__(self, sample):\n \"\"\"\n Args: Dataset to be cropped.\n Returns: Cropped dataset.\n \"\"\"\n radar = sample['radar']\n if self.padding > 0:\n radar = np.pad(radar, ((0,),(self.padding,),(self.padding,)), 'mean')\n\n i = random.randint(0, self.padding*2-1)\n j = random.randint(0, self.padding*2-1)\n\n sample['radar'] = radar[:, i:i+60, j:j+60]\n\n return sample\n","sub_path":"datasets/nexraddataset.py","file_name":"nexraddataset.py","file_ext":"py","file_size_in_byte":3861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"318562267","text":"import json\nimport copy\nimport sys\nfrom sys import argv\nfrom collections import Counter\nfrom program_synthesis.algolisp.dataset import executor\n\n# could be slightly optimized by using dicts to maintain which tokens are present\n\nvocab_size = 200\n\nsketches = []\n\nprograms = []\nprogram_tokens = []\ncommand_cnt = Counter()\ncommand_pair_cnt = Counter()\n\ndef deep_equals(l1, l2):\n if not type(l1) == type(l2):\n return False\n if type(l1) is list:\n if len(l1) != len(l2):\n return False\n for a, b in zip(l1, l2):\n if not deep_equals(a, b):\n return False\n return True\n else:\n return l1 == l2\n\ndef index_of_sketch(sketch):\n for i, possibility in enumerate(sketches):\n if deep_equals(sketch, possibility):\n return i\n return -1\n\ndef encode(program):\n token_set = set()\n if type(program) is list:\n sketch = [program[0]] + ['<HOLE>'] * (len(program) - 1)\n program[0] = index_of_sketch(sketch)\n if program[0] == -1:\n sketches.append(sketch)\n program[0] = len(sketches) - 1\n token_set.add(program[0])\n\n for i in range(1, len(program)):\n program[i], ts = encode(program[i])\n token_set = token_set.union(ts)\n else:\n if program not in sketches:\n sketches.append(program)\n program = sketches.index(program)\n token_set.add(program)\n return program, token_set\n\ndef combine(par_sketch, child_sketch, child_idx):\n if par_sketch == '<HOLE>':\n if child_idx == 0:\n return child_sketch\n else:\n return child_idx - 1\n elif type(par_sketch) is not list:\n return child_idx\n else:\n for i in range(1, len(par_sketch)):\n rec = combine(par_sketch[i], child_sketch, child_idx)\n if type(rec) is int:\n child_idx = rec\n else:\n res = [par_sketch[j] if j != i else rec for j in range(len(par_sketch))]\n return res\n return child_idx\n\ndef add_programs(file_name):\n print('processing %s ... ' % file_name, end='\\r', flush=True)\n line_cnt = 0\n with open(file_name, 'r') as f:\n for line in f:\n line_cnt += 1\n data = json.loads(line)\n program = data['short_tree']\n program, token_set = encode(program)\n programs.append(program)\n program_tokens.append(token_set)\n if line_cnt % 1 == 0:\n print('processing %s ... %d' % (file_name, line_cnt), end='\\r', flush=True)\n print('processing %s ... DONE ' % file_name, flush=True)\n\ndef add_cnt(program):\n if type(program) is not list:\n command_cnt[program] += 1\n return\n command_cnt[program[0]] += 1\n for i, a in enumerate(program[1:]):\n child_command = a[0] if type(a) is list else a\n command_pair_cnt[(program[0], i, child_command)] += 1 \n add_cnt(a)\n\ndef remove_cnt(program):\n if type(program) is not list:\n command_cnt[program] -= 1\n return\n command_cnt[program[0]] -= 1\n for i, a in enumerate(program[1:]):\n child_command = a[0] if type(a) is list else a\n command_pair_cnt[(program[0], i, child_command)] -= 1\n remove_cnt(a)\n\ndef upd(program, par_sketch, child_sketch, child_idx, new_sketch):\n def recur(prog):\n return upd(prog, par_sketch, child_sketch, child_idx, new_sketch)\n\n if type(program) is not list:\n token_set = set()\n token_set.add(program)\n return program, token_set\n\n if program[0] == par_sketch and child_idx + 1 < len(program):\n x = program[child_idx + 1]\n if type(x) is list and x[0] == child_sketch:\n program = [new_sketch] + program[1:child_idx + 1] + x[1:] + program[child_idx + 2:]\n elif type(x) is not list and x == child_sketch:\n program = [new_sketch] + program[1:child_idx + 1] + program[child_idx + 2:]\n \n if len(program) is 1:\n return recur(program[0])\n res = [recur(x) for x in program]\n program_res = [a[0] for a in res]\n token_set = set()\n for a in res:\n token_set = token_set.union(a[1])\n return program_res, token_set\n\ndef init():\n for program in programs:\n add_cnt(program)\n\ndef main():\n global vocab_size\n if len(sys.argv) > 1:\n vocab_size = int(sys.argv[1])\n for t in 'train dev test'.split():\n add_programs('metaset3.' + t + '.jsonl')\n init()\n\n with open('sketches.jsonl', 'w') as f:\n for i, s in enumerate(sketches):\n json.dump({'id':i, 'tree':s, 'frequency':command_cnt[i]}, f)\n f.write('\\n')\n\n combinations = []\n while len(sketches) < vocab_size:\n (par_sketch, child_idx, child_sketch), freq = command_pair_cnt.most_common(1)[0]\n print(freq)\n print('combining %s and %s at index %d' % (str(sketches[par_sketch]), str(sketches[child_sketch]), child_idx), flush=True)\n sketches.append(combine(sketches[par_sketch], sketches[child_sketch], child_idx))\n for i in range(len(programs)):\n if par_sketch in program_tokens[i] and child_sketch in program_tokens[i]:\n remove_cnt(programs[i])\n programs[i], program_tokens[i] = upd(programs[i], par_sketch, child_sketch, child_idx, len(sketches) - 1)\n add_cnt(programs[i])\n if (i + 1) % 100 == 0:\n print('%d/%d' % (i + 1, len(programs)), end='\\r', flush=True)\n print('%d/%d'%(len(programs), len(programs)))\n combinations.append({'id':len(sketches) - 1, 'tree':sketches[-1], 'par_sketch':par_sketch, 'child_sketch':child_sketch, 'child_idx':child_idx, 'frequency':freq})\n\n with open('sketches.jsonl', 'a') as f:\n for c in combinations:\n json.dump(c, f)\n f.write('\\n')\n\nif __name__ == '__main__':\n exit(main())\n","sub_path":"data/sketchgen.py","file_name":"sketchgen.py","file_ext":"py","file_size_in_byte":5911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"299121922","text":"import json\nimport hashlib\nimport logging\nimport random\nfrom time import time\n\nfrom util.http import make_request\n\n\nclass BotApiError(Exception):\n def __init__(self, code, message):\n super().__init__(message)\n self.code = code\n self.message = message\n\n\nclass BotApi:\n def __init__(self, token):\n self.api_url = 'https://api.telegram.org/'\n self.token = token\n self.logger = logging.getLogger('telegram_bot_api')\n\n def __request(self, api_method, **kwargs):\n url = '{base_url}bot{token}/{api_method}'.format(\n base_url=self.api_url,\n token=self.token,\n api_method=api_method\n )\n request_params = {}\n for k, v in kwargs.items():\n if v is None:\n continue\n request_params.update({k: v})\n h = hashlib.md5()\n h.update('{0}_{1}_{2}'.format(time(), url, random.random()).encode())\n request_id = h.hexdigest()\n self.logger.debug('REQUEST {hash} - {method} {url}, params: {params}'.format(\n hash=request_id,\n method='POST',\n url=url,\n params=str(request_params)\n ))\n raw_response = make_request(url, method='POST', params=request_params)\n self.logger.debug('RESPONSE {hash} - {response}'.format(\n hash=request_id,\n response=raw_response\n ))\n response = json.loads(raw_response.decode())\n if not response['ok']:\n raise BotApiError(response['error_code'], response['description'])\n return response['result']\n\n def setWebhook(self, url, certificate=None, max_connections=40, allowed_updates=None):\n if allowed_updates is None:\n allowed_updates = []\n kwargs = {\n 'url': url,\n 'certificate': certificate,\n 'max_connections': max_connections,\n 'allowed_updates': allowed_updates,\n }\n return self.__request('setWebhook', **kwargs)\n\n def sendMessage(self, chat_id, text, reply_markup=None, parse_mode=None):\n return self.__request(\n 'sendMessage',\n chat_id=chat_id,\n text=text,\n reply_markup=reply_markup,\n parse_mode=parse_mode\n )\n\n def editMessageReplyMarkup(self, chat_id, message_id, reply_markup):\n return self.__request(\n 'editMessageReplyMarkup',\n chat_id=chat_id,\n message_id=message_id,\n reply_markup=reply_markup\n )\n\n def editMessageText(self, chat_id, message_id, text, reply_markup=None):\n return self.__request(\n 'editMessageText',\n chat_id=chat_id,\n message_id=message_id,\n text=text,\n reply_markup=reply_markup\n )\n\n def getFile(self, file_id):\n file = self.__request('getFile', file_id=file_id)\n download_url = '{base_url}file/bot{token}/{path}'.format(\n base_url=self.api_url,\n token=self.token,\n path=file['file_path']\n )\n return download_url\n","sub_path":"src/util/telegram/bot_api.py","file_name":"bot_api.py","file_ext":"py","file_size_in_byte":3100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"367234852","text":"import numpy as np\nimport os\n\n# log_path = \"/home/ziqi/Desktop/deeprm-env/logs/\"\n# file_name = \"test_job_record_rate_{}.npy\".format(0.3)\nlog_path = \"/home/prquan/Github/PPO-PyTorch/logs/\"\nfile_name = \"test_job_record_rate_{}.npy\".format(0.4)\n\nlog_filename = os.path.join(log_path, file_name)\nsaved_log = np.load(log_filename, allow_pickle=True)\n\navg_slowdown = []\nfor exp_cnt in range(len(saved_log)):\n info = saved_log[exp_cnt]\n\n all_discount_rews = []\n jobs_slow_down = []\n work_complete = []\n work_remain = []\n job_len_remain = []\n num_job_remain = []\n\n enter_time = np.array([info.record[i].enter_time for i in range(len(info.record))])\n finish_time = np.array([info.record[i].finish_time for i in range(len(info.record))])\n job_len = np.array([info.record[i].len for i in range(len(info.record))])\n job_total_size = np.array([np.sum(info.record[i].res_vec) for i in range(len(info.record))])\n\n finished_idx = (finish_time >= 0)\n unfinished_idx = (finish_time < 0)\n\n jobs_slow_down.append(\n (finish_time[finished_idx] - enter_time[finished_idx]) / job_len[finished_idx]\n )\n work_complete.append(\n np.sum(job_len[finished_idx] * job_total_size[finished_idx])\n )\n work_remain.append(\n np.sum(job_len[unfinished_idx] * job_total_size[unfinished_idx])\n )\n job_len_remain.append(\n np.sum(job_len[unfinished_idx])\n )\n num_job_remain.append(\n len(job_len[unfinished_idx])\n )\n avg_slowdown.append(np.mean(jobs_slow_down))\nprint(np.mean(avg_slowdown))\n\n\n","sub_path":"deeprm_log_processing.py","file_name":"deeprm_log_processing.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"301498989","text":"#! /usr/bin/env python3\nimport math\n\nfor column in ('1', '2', '3', '4', '5', '6'):\n print('* check column ' + column + ' data *')\n fc = open ('../../StreamToColumns3/StreamToColumns3.sim/sim_1/behav/c' + column + '.txt', 'r')\n ref_fc = open('ref_c' + column + '.txt', 'r')\n ok = True\n line_no = 1\n line = fc.readline()\n while line:\n # シミュレーション結果を読み込む\n results = line[:-1].split(' ')\n d = int(results[0], 16)\n tlast = results[1]\n # 比較値を読み込む\n lref = ref_fc.readline()\n if not lref:\n print(\"Error: too much data\")\n raise Exception()\n results = lref[:-1].split(' ')\n ref_d = int(results[0], 16)\n ref_tlast = results[1]\n \n if d != ref_d:\n print('Error: line {line} is {sim}, expected {ref}'.\n format(line=line_no, sim=d, ref=ref_d))\n ok = False\n \n if tlast != ref_tlast:\n print('Error: line {line} tlast {sim}, expected {ref}'.\n format(line=line_no, sim=tlast, ref=ref_tlast))\n ok = False\n\n # 次の結果の行を読み込む\n line = fc.readline()\n line_no += 1\n\n # まだ行が残っていたらエラー\n if ref_fc.readline():\n print(\"Error: less data\")\n ok = False\n\n if ok:\n print(\"All data is good\")\n\n fc.close()\n ref_fc.close()\n print();\n","sub_path":"vivado/2017.2/module/StreamToColumns3/sim/test/checkData.py","file_name":"checkData.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"205143726","text":"#!/usr/bin/env python3\n\n\"\"\"Form 1099-INT HTML\n\nExtract Payer Name, Box 3 data, and Box 4 data from a Treasury Direct Form 1099-INT HTML file\nand write the data to the console in Tax Exchange Format (TXF).\n\"\"\"\n\nfrom argparse import ArgumentParser\nfrom html.parser import HTMLParser\nimport sys\nimport taxexchangeformat\n\nclass TreasuryDirectHtmlParser(HTMLParser):\n \"\"\"HTML parser for Treasury Direct Form 1099-INT.\"\"\"\n box_3 = None\n box_4 = None\n done = False\n found_1099_int = False\n found_payer_info = False\n found_1099_int_totals = False\n payer_name = None\n\n def _handle_payer(self, data: str) -> bool:\n if data == \"Payer Information:\":\n self.found_payer_info = True\n return True\n if self.payer_name is None and self.found_payer_info:\n self.payer_name = data.strip()\n return True\n return False\n\n def _handle_totals(self, data: str) -> None:\n if data == \"Totals:\" and self.found_1099_int:\n self.found_1099_int_totals = True\n return\n if self.found_1099_int_totals:\n if self.box_3 is None:\n if data.startswith('$'):\n self.box_3 = data\n return\n if self.box_4 is None:\n if data.startswith('$'):\n self.box_4 = data\n self.done = True\n return\n return\n\n def handle_data(self, data: str) -> None:\n \"\"\"Cache relevant data.\"\"\"\n if self.done:\n return\n if self._handle_payer(data):\n return\n if data.startswith('Form 1099-INT'):\n self.found_1099_int = True\n return\n self._handle_totals(data)\n return\n\n def get_payer_name(self) -> str:\n \"\"\"Return the payer of the interest.\"\"\"\n return self.payer_name\n\n def get_savings_bonds_interest(self) -> str:\n \"\"\"Return the savings bonds interest from box 3.\"\"\"\n return self.box_3\n\n def get_federal_tax_withheld(self) -> str:\n \"\"\"Return the federal tax withheld from box 4.\"\"\"\n return self.box_4\n\ndef parse_file(filename: str, parser: TreasuryDirectHtmlParser) -> None:\n \"\"\"Parse the HTML file and cache extracted within the parser.\"\"\"\n with open(filename, mode='r', encoding='windows-1252') as html_file:\n data = html_file.read()\n parser.feed(data)\n return\n\ndef html_to_txf(filename: str, omit_header: bool) -> None:\n \"\"\"Read interest income data from an HTML file and write TXF records to the console.\"\"\"\n html_parser = TreasuryDirectHtmlParser()\n parse_file(filename, html_parser)\n if not omit_header:\n taxexchangeformat.write_header('usincometax 2020.0.0')\n taxexchangeformat.write_1099int(\n payer=html_parser.get_payer_name(),\n box_3=html_parser.get_savings_bonds_interest(),\n box_4=html_parser.get_federal_tax_withheld())\n return\n\ndef main() -> None:\n \"\"\"Parse command line arguments and run.\"\"\"\n parser = ArgumentParser(\n description='Generate Tax Exchange Format (TXF) records from a 1099-INT HTML file')\n parser.add_argument('infile', nargs=1, help='a 1099-INT HTML file from TreasuryDirect')\n parser.add_argument(\n '-o', '--omit-header',\n action='store_true',\n help='omit the header record from the TXF output')\n args = parser.parse_args()\n html_to_txf(args.infile[0], args.omit_header)\n return\n\nif __name__ == '__main__':\n main()\n sys.exit()\n","sub_path":"usincometax/form1099inthtml.py","file_name":"form1099inthtml.py","file_ext":"py","file_size_in_byte":3529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"153067257","text":"from collections import namedtuple\nfrom typing import Optional\n\nimport redis\n\nfrom modules.settings import config\n\nCoordinates = namedtuple('Coordinates', ['latitude', 'longitude'])\n\npool = redis.ConnectionPool(host=config['host'], port=config['port'], db=config['db'])\nredis_storage = redis.Redis(connection_pool=pool)\n\n\nclass UserDataStorage:\n \"\"\"\n Storage class to work with user details\n \"\"\"\n STORAGE_USER_PREFIX = 'user'\n\n def get_storage_user_prefix(self, username: str) -> str:\n return f'{self.STORAGE_USER_PREFIX}_{username}'\n\n def save_user_location_to_store(self, username: str, coords: Coordinates) -> None:\n key = self.get_storage_user_prefix(username)\n redis_storage.hmset(\n key,\n {\n 'latitude': coords.latitude,\n 'longitude': coords.longitude\n }\n )\n\n def get_user_location_from_store(self, username: str) -> Optional[Coordinates]:\n key = self.get_storage_user_prefix(username)\n stored_data = redis_storage.hgetall(key)\n if not stored_data:\n return None\n coordinates = Coordinates(float(stored_data[b'latitude']), float(stored_data[b'longitude']))\n return coordinates\n\n\nclass CityNameToGeoIdMappingStorage:\n \"\"\"\n Storage class to work with mapping of city names to their geonameids\n \"\"\"\n\n MAPPING_KEY = 'cities_name_geoid_mapping'\n\n def add_city(self, name: str, geoid: str) -> None:\n redis_storage.hmset(self.MAPPING_KEY, {name: geoid})\n\n def get_city_geoid(self, name: str) -> Optional[str]:\n city_geoid = redis_storage.hget(self.MAPPING_KEY, name)\n if not city_geoid:\n return None\n return int(city_geoid)\n\n def is_mapping_exists(self) -> bool:\n return redis_storage.hlen(self.MAPPING_KEY) > 0\n\n\ncity_to_geoid_mapping = CityNameToGeoIdMappingStorage()\nuser_data_storage = UserDataStorage()\n","sub_path":"matrosskin/modules/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"196792935","text":"import logging\nimport os\nfrom datetime import datetime\nfrom ..utils.html_utils import threadedDownload, getHREF, updateThreads, urlBase\nBASEURL = 'http://atmos.tamucc.edu/trmm/data/gpm'\nDATEFMT = '%Y%m'\n\ndef getGPM_PF(outRoot, level = 2, startDate = None, endDate = None, **kwargs):\n log = logging.getLogger(__name__)\n updateThreads( kwargs.pop('threads', 4) )\n\n level = 'level_{}'.format(level)\n URL = '{}/{}'.format(BASEURL, level)\n outDir = os.path.join( outRoot, 'PF', level )\n\n for url in getHREF(URL):\n if url:\n try:\n date = urlBase(url).split('_')[1].split('.')[0]\n date = datetime.strptime( date, DATEFMT )\n except:\n continue\n else:\n ref = url.split('/')\n if startDate and date < startDate:\n continue\n if endDate and date > endDate:\n continue\n kwargs['fPath'] = os.path.join( outDir, *ref[-2:] )\n threadedDownload(url, **kwargs)\n","sub_path":"data_downloading/trmm/getGPM_PF.py","file_name":"getGPM_PF.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"285220340","text":"import dlite\n\n\n# Storage plugins can be loaded\ndlite.Storage.load_plugins()\n\n# Now plugins are loaded\nplugins = set(dlite.StoragePluginIter())\nassert plugins\nassert \"json\" in plugins\n\n# Plugins can be iterated over\nprint(\"Storage plugins\")\nplugins2 = set()\nfor name in dlite.StoragePluginIter():\n print(\" -\", name)\n plugins2.add(name)\nassert plugins2 == plugins\n\n# Unload json plugin\ndlite.Storage.unload_plugin(\"json\")\nassert \"json\" not in set(dlite.StoragePluginIter())\n","sub_path":"bindings/python/tests/test_storage_plugins.py","file_name":"test_storage_plugins.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"386924543","text":"from __future__ import division\nfrom __future__ import absolute_import\nfrom six.moves import range\n\n__copyright__ = \"Copyright (C) 2012 Andreas Kloeckner\"\n\n__license__ = \"\"\"\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\"\n\n\nimport numpy as np\n\n\ndef separate_by_real_and_imag(data, real_only):\n for name, field in data:\n from pytools.obj_array import log_shape\n ls = log_shape(field)\n\n if ls != () and ls[0] > 1:\n assert len(ls) == 1\n from pytools.obj_array import (\n oarray_real_copy, oarray_imag_copy,\n with_object_array_or_scalar)\n\n if field[0].dtype.kind == \"c\":\n if real_only:\n yield (name,\n with_object_array_or_scalar(oarray_real_copy, field))\n else:\n yield (name+\"_r\",\n with_object_array_or_scalar(oarray_real_copy, field))\n yield (name+\"_i\",\n with_object_array_or_scalar(oarray_imag_copy, field))\n else:\n yield (name, field)\n else:\n # ls == ()\n if field.dtype.kind == \"c\":\n yield (name+\"_r\", field.real.copy())\n yield (name+\"_i\", field.imag.copy())\n else:\n yield (name, field)\n\n\nclass FieldPlotter:\n def __init__(self, center, extent=1, npoints=1000):\n center = np.asarray(center)\n self.dimensions, = dim, = center.shape\n self.a = a = center-extent*0.5\n self.b = b = center+extent*0.5\n\n if not isinstance(npoints, tuple):\n npoints = dim*(npoints,)\n else:\n if len(npoints) != dim:\n raise ValueError(\"length of npoints must match dimension\")\n\n for i in range(dim):\n if npoints[i] == 1:\n a[i] = center[i]\n\n mgrid_index = tuple(\n slice(a[i], b[i], 1j*npoints[i])\n for i in range(dim))\n\n mgrid = np.mgrid[mgrid_index]\n\n # (axis, point x idx, point y idx, ...)\n self.nd_points = mgrid\n\n self.points = self.nd_points.reshape(dim, -1).copy()\n\n from pytools import product\n self.npoints = product(npoints)\n\n def show_scalar_in_matplotlib(self, fld, max_val=None,\n func_name=\"imshow\", **kwargs):\n if len(self.a) != 2:\n raise RuntimeError(\n \"matplotlib plotting requires 2D geometry\")\n\n if len(fld.shape) == 1:\n fld = fld.reshape(self.nd_points.shape[1:])\n\n if max_val is not None:\n fld[fld > max_val] = max_val\n fld[fld < -max_val] = -max_val\n\n fld = fld[..., ::-1]\n\n kwargs[\"extent\"] = (\n # (left, right, bottom, top)\n self.a[0], self.b[0],\n self.a[1], self.b[1])\n\n import matplotlib.pyplot as pt\n return getattr(pt, func_name)(fld.T, **kwargs)\n\n def set_matplotlib_limits(self):\n import matplotlib.pyplot as pt\n pt.xlim((self.a[0], self.b[0]))\n pt.ylim((self.a[1], self.b[1]))\n\n def show_vector_in_mayavi(self, fld, do_show=True, **kwargs):\n c = self.points\n\n from mayavi import mlab\n mlab.quiver3d(c[0], c[1], c[2], fld[0], fld[1], fld[2],\n **kwargs)\n\n if do_show:\n mlab.show()\n\n def write_vtk_file(self, file_name, data, real_only=False):\n from pyvisfile.vtk import write_structured_grid\n write_structured_grid(file_name, self.nd_points,\n point_data=list(separate_by_real_and_imag(data, real_only)))\n\n def show_scalar_in_mayavi(self, fld, max_val=None, **kwargs):\n if max_val is not None:\n fld[fld > max_val] = max_val\n fld[fld < -max_val] = -max_val\n\n if len(fld.shape) == 1:\n fld = fld.reshape(self.nd_points.shape[1:])\n\n from mayavi import mlab\n mlab.surf(self.nd_points[0], self.nd_points[1], fld, **kwargs)\n\n\n\n# vim: foldmethod=marker\n","sub_path":"sumpy/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":5037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"346381727","text":"def partioning(arr,start,end):\n pivot = arr[end]\n pindex = start # partion index\n for i in range(start,end):\n if arr[i] <= pivot:\n arr[i],arr[pindex] = arr[pindex],arr[i]\n pindex+=1\n\n arr[end], arr[pindex] = arr[pindex],arr[end]\n return pindex\n\n\n\n\n\ndef quickSort(arr,start,end):\n if start< end:\n pindex = partioning(arr,start,end)\n quickSort(arr,start,pindex-1)\n quickSort(arr,pindex+1,end)\n\n\n\narr = [ 5, 7, 8, 9, 1, 10 ]\nn = len(arr)\n\nquickSort(arr,0,n-1)\nprint(arr)","sub_path":"SEARCHING AND SORTING/SORTING/Quick_Sort.py","file_name":"Quick_Sort.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"23142740","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function\n\"\"\"\nCreated on Fri Sep 8 20:52:41 2017\n\n@author: josef\n\"\"\"\n\n#Python is amazing\n#Create ASCII-Char HTML Table\n \nstrTable = \"<html><table><tr><th>Char</th><th>ASCII</th></tr>\"\n \nfor num in range(33,48):\n symb = chr(num)\n strRW = \"<tr><td>\"+str(symb)+ \"</td><td>\"+str(num)+\"</td></tr>\"\n strTable = strTable+strRW\n \nstrTable = strTable+\"</table></html>\"\n \nhs = open(\"asciiCharHTMLTable.html\", 'w')\nhs.write(strTable)\n \nprint (strTable)","sub_path":"2017/create_ascii_table_html.py","file_name":"create_ascii_table_html.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"494643931","text":"\"\"\"\r\nDescription: Script to annotate breakpoints with repeat regions and poor mappability regions\r\nAuthor: Riccha Sethi\r\n\"\"\"\r\n\r\nimport argparse\r\nimport pandas as pd\r\nimport numpy as np\r\nimport multiprocessing\r\nimport pysam\r\nfrom Tree_Rep import *\r\nimport os\r\n\r\ndef pileup_pos(Line, samfile, STRING):\r\n ### calculates pileup in a window of 200bp having atleast 10 as base quality\r\n if STRING==\"breakpoint1\":\r\n chrom=Line['chrom1']\r\n pos=Line['pos1']\r\n else:\r\n chrom=Line['chrom2']\r\n pos=Line['pos2']\r\n a=[pileupcolumn.n for pileupcolumn in samfile.pileup(chrom, int(pos)-200, int(pos)+200, stepper='all', min_base_quality=10)]\r\n allreads=sum(a)\r\n return float(allreads)/400.0\r\n\r\ndef check_mappability(Line, mappabilityTrack, STRING):\r\n if STRING==\"breakpoint1\":\r\n chromo=Line['chrom1']\r\n pos=Line['pos1']\r\n else:\r\n chromo=Line['chrom2']\r\n pos=Line['pos2']\r\n NewDF= mappabilityTrack[(mappabilityTrack['chrom']==chromo) & (mappabilityTrack['pos1']<=pos) & (mappabilityTrack['pos2']>=pos)]\r\n if NewDF.shape[0]!=0:\r\n return \"Unique\"\r\n else:\r\n return \"Not-unique\"\r\n\r\ndef repeatAnnotation(bt, Line, STRING):\r\n if STRING==\"breakpoint1\":\r\n rep=bt.overlap(Line['chrom1'], Line['pos1'], 2, \"+\")\r\n else:\r\n rep=bt.overlap(Line['chrom2'], Line['pos2'], 2, \"+\")\r\n if rep:\r\n return rep[0][0]\r\n else:\r\n return \"NA\"\r\n\r\ndef getOverlap(a,b):\r\n return max(0,min(a[1],b[1])-max(a[0],b[0])+1)\r\n\r\ndef RepeatClass(chromo, reppos, RepMasker):\r\n tmpRep=RepMasker[(RepMasker['genoName']==chromo) & (RepMasker['repName']==reppos)]\r\n if tmpRep.shape[0]==0:\r\n return 'NA'\r\n else:\r\n return tmpRep['repClass'].values.tolist()[0]\r\n\r\ndef annotate(DF, RepMasker, MapFile,BAMT, BAML, bt):\r\n if BAMT:\r\n BAM=pysam.AlignmentFile(BAMT, 'rb')\r\n DF['LocalCoverage_Pos1_SR'], DF['LocalCoverage_Pos2_SR'] = 'NA','NA'\r\n if BAML:\r\n BAMLinked=pysam.AlignmentFile(BAML, 'rb')\r\n DF['LocalCoverage_Pos1_LR'], DF['LocalCoverage_Pos2_LR'] = 'NA','NA'\r\n\r\n if RepMasker:\r\n DF['RepPos1'], DF['RepPos2'],DF['RepPos1_Class'], DF['RepPos2_Class']= 'NA','NA','NA','NA'\r\n if MapFile:\r\n DF['Mappable_Pos1'],DF['Mappable_Pos2'] = 'NA','NA'\r\n\r\n NewDF= DF.copy(deep=True)\r\n NewDF['chrom2']=NewDF['chrom2:pos2'].apply(lambda x: x.split(\":\")[0])\r\n NewDF['pos2']=NewDF['chrom2:pos2'].apply(lambda x: int(x.split(\":\")[1]))\r\n for index,rows in NewDF.iterrows():\r\n if BAMT:\r\n tmp_a=pileup_pos(rows, BAM, \"breakpoint1\")\r\n tmp_c=pileup_pos(rows, BAM, \"breakpoint2\")\r\n NewDF.at[index, 'LocalCoverage_Pos1_SR']=tmp_a\r\n NewDF.at[index, 'LocalCoverage_Pos2_SR']=tmp_c\r\n if BAML:\r\n tmp_b=pileup_pos(rows, BAMLinked, \"breakpoint1\")\r\n tmp_d=pileup_pos(rows, BAMLinked, \"breakpoint2\")\r\n NewDF.at[index, 'LocalCoverage_Pos1_LR']=tmp_b\r\n NewDF.at[index, 'LocalCoverage_Pos2_LR']=tmp_d\r\n if RepMasker:\r\n tmp_e=repeatAnnotation(bt, rows, \"breakpoint1\")\r\n tmp_f=repeatAnnotation(bt, rows, \"breakpoint2\")\r\n NewDF.at[index, 'RepPos1']=tmp_e\r\n NewDF.at[index, 'RepPos2']=tmp_f\r\n NewDF.at[index,'RepPos1_Class']= RepeatClass(rows['chrom1'], tmp_e, RepMasker)\r\n NewDF.at[index,'RepPos2_Class']= RepeatClass(rows['chrom2'], tmp_f, RepMasker)\r\n if MapFile:\r\n tmp_g=check_mappability(rows, MapFile, \"breakpoint1\")\r\n tmp_h=check_mappability(rows, MapFile, \"breakpoint2\")\r\n NewDF.at[index, 'Mappable_Pos1']=tmp_g\r\n NewDF.at[index, 'Mappable_Pos2']=tmp_h\r\n if BAMT:\r\n BAM.close()\r\n if BAML:\r\n BAMLinked.close()\r\n return NewDF\r\n\r\ndef split(dfm, chunk_size):\r\n# divides dfm pandas dataframe into chunk_size\r\n rows=dfm.shape[0]\r\n CHUNK=[]\r\n for i in range(chunk_size):\r\n if i != chunk_size-1:\r\n CHUNK.append(dfm.iloc[int(rows/chunk_size)*i : int(rows/chunk_size)*(i+1), : ])\r\n else:\r\n CHUNK.append(dfm.iloc[int(rows/chunk_size)*i :, : ])\r\n return CHUNK\r\n\r\nif __name__=='__main__':\r\n parser=argparse.ArgumentParser(description=\"Calculates local coverage around breakpoints from cWGS and 10XWGS aligned reads (required feature) and annotate breakpoints with repetitive regions and poor mappability regions\")\r\n parser.add_argument('-Annotate','--Annotate', help=\"Annotattion of breakpoints with repetitive and poor mappability regions (Yes or No, deafult=Yes)\", default=\"Yes\", type=str)\r\n parser.add_argument('-repeatMasker','--repeats', help=\"enter repeatMasker file (default=None)\", default=None)\r\n parser.add_argument('-mappability','--mappability', help=\"enter mappability track file (default=None)\", default=None)\r\n parser.add_argument('-File','--File', help=\"enter .tsv file with structural variations from GEM quantification (Required)\")\r\n parser.add_argument('-BAM','--BAMshort',help=\"enter BAM file with aligned short-reads (Required)\", default=None)\r\n parser.add_argument('-BAMLinked','--BAMLinked', help=\"enter BAM file with aligned linked-reads (Default=None)\", default=None)\r\n parser.add_argument('-Threads','--processes', help=\"Enter number of cores (default=1)\", default=1, type=int)\r\n parser.add_argument('-outdir','--outdir', help=\"Enter output directory (Default=current directory)\", default=\".\")\r\n args=parser.parse_args()\r\n CombinedFile= pd.read_csv(args.File, sep='\\t')\r\n if not os.path.exists(args.outdir):\r\n os.makedirs(args.outdir)\r\n\r\n if args.Annotate in [\"Yes\",\"yes\"]:\r\n RepMasker= pd.read_csv(args.repeats, sep='\\t')\r\n RepMasker=RepMasker.sort_values(by=['genoName', 'genoStart', 'genoEnd'])\r\n RepFile = RepMasker[['genoName', 'genoStart', 'genoEnd', 'repName', 'swScore', 'strand']]\r\n MapFile= pd.read_csv(args.mappability, sep='\\t', header=None, skiprows=1, names=[\"chrom\",\"pos1\",\"pos2\",\"kmer\",\"unique\",\"strand\"])\r\n bt=bed_tree(RepFile, 2)\r\n else:\r\n RepFile, MapFile, bt = 'NA','NA','NA'\r\n nthreads= int(args.processes)\r\n p= multiprocessing.Pool(nthreads)\r\n chunks=split(CombinedFile, nthreads)\r\n workers=[p.apply_async(annotate, args=(i, RepMasker, MapFile, args.BAMshort, args.BAMLinked, bt,)) for i in chunks]\r\n final_result=[worker.get() for worker in workers]\r\n p.close()\r\n p.join()\r\n FinalCombinedFile= pd.concat(results for results in final_result)\r\n FinalCombinedFile.to_csv(args.outdir+ '/Annotated.tsv', sep='\\t', index=False)\r\n","sub_path":"Include_annotations.py","file_name":"Include_annotations.py","file_ext":"py","file_size_in_byte":6614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"441494272","text":"from keras.preprocessing import image\nfrom keras.preprocessing.image import img_to_array\nimport numpy as np\n\n\ndef path_to_tensor(img):\n # loads RGB image as PIL.Image.Image type\n # if the image mode is not RGB, convert it\n if img.mode != \"RGB\":\n img = image.convert(\"RGB\")\n\n # resize the input image\n target = (224, 224)\n img = img.resize(target)\n\n # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)\n x = img_to_array(img)\n\n # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor\n return np.expand_dims(x, axis=0)","sub_path":"backend/app/modules/classifier/utils/path_to_tensor.py","file_name":"path_to_tensor.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"366475596","text":"#!/home/eanderson/Virtual_Envs/General3/bin/python3\nfrom pathlib import Path\nimport matplotlib.pyplot as plt\nimport subprocess as sbp\nimport pandas as pd\nimport seaborn as sns\nimport argparse\nimport sys, os\nimport errno\n\n\ndef get_arguments():\n parser = argparse.ArgumentParser(description=\"Stratify SV calls across ga4gh regions\")\n parser.add_argument('VCF_Dir', type=str,\n help=\"Path to Truvari VCFs\")\n parser.add_argument('-t', '--tsv', type=str, help=\"path to ga4gh tsv file\",\n default=\"/home-02/eanderson/Sentieon_Binning_and_Stratification/ga4gh_all_coordonly_2.tsv\")\n parser.add_argument('-b', '--bed', type=str, help=\"path to stratification bed dir\",\n default=\"/home-02/eanderson/Sentieon_Binning_and_Stratification/stratification_regions\")\n parser.add_argument('-o', '--outdir', type=str, help=\"output path\",\n default=\"Stratification_Results/\")\n args = parser.parse_args()\n return args\n\n# get various arguments as Path objects\nargs = get_arguments()\nprint(args.VCF_Dir, type(args.VCF_Dir))\nvcf_base_path = Path(args.VCF_Dir)\nstrat_bed_dir = Path(args.bed)\nstrat_tsv = Path(args.tsv)\noutdir = Path(args.outdir)\n\n# Paths of truvari output fp, tp and fn VCFs\nVCFs = [vcf_base_path / \"fp.vcf\", vcf_base_path / 'tp-call.vcf', vcf_base_path / \"fn.vcf\"]\nstratification_map = {}\n# map the names and paths of the various stratification bed files\nwith open(strat_tsv, \"r\") as fh:\n for line in fh:\n name, strat_bed = line.rstrip().split('\\t')\n stratification_map[name] = strat_bed_dir / strat_bed\n\n# This just counts lines in a file\ndef count_lines(file_object):\n counter = 0\n for line in file_object:\n if not line.startswith(\"#\"):\n counter += 1\n\n return counter\n\n\n# iterate through fp, fn and tp VCFs\nresults_list = []\nfor vcf in VCFs:\n\n results_dict = {}\n\n # use bcftools to get the vcf results within the bed regions\n for name, strat_path in stratification_map.items():\n output = sbp.run(['bcftools', 'view', '-O', 'v', '-T', strat_path, vcf], stdout=sbp.PIPE)\n print(output.args, file=sys.stderr)\n # count results\n results_dict[name] = count_lines(output.stdout.decode('utf-8').split(\"\\n\"))\n\n # get total count of entries in the vcf\n with open(vcf, \"r\") as vcf_all:\n results_dict['All'] = count_lines(vcf_all)\n results_list.append(results_dict)\n\n# Create a dataframe of results, transpose it and get totals and fp/fn rates\ndf = pd.DataFrame(results_list, index=['FP', 'TP', 'FN'])\ndf2 = df.T\ndf2['Total_Vars'] = df2['TP'] + df2['FN']\ndf2['FP_Rate'] = df2['FP'] / df2['Total_Vars']\ndf2['FN_Rate'] = df2['FN'] /df2['Total_Vars']\n\n# Attempt to make output dir\ntry:\n os.makedirs(outdir)\nexcept OSError as e:\n if e.errno != errno.EEXIST:\n raise\n\ndf2.to_pickle(outdir / \"sv_var_results.pkl\")\n\n# Plot Totals\nfig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True, figsize=(18,12))\n\nsns.barplot(x=df2.index, y=df2['Total_Vars'], data = df2, ax = ax3)\nax3.set_xticklabels(ax3.get_xticklabels(), rotation=40, ha=\"right\", fontsize='medium', fontweight='normal')\n\n# Plot the FN rate\nsns.barplot(x=df2.index, y=df2[\"FN_Rate\"], data=df2, ax = ax2)\n\n# Plot the FP rate\nsns.barplot(x=df2.index, y=df2[\"FP_Rate\"], data=df2, ax = ax1)\n\nplt.tight_layout()\nplt.savefig(outdir / \"results.png\")\n","sub_path":"stratification_test.py","file_name":"stratification_test.py","file_ext":"py","file_size_in_byte":3397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"520701270","text":"#!/usr/bin/python\nimport feedparser\nfrom flask import Flask , render_template\n#Tue Jul 12 05:01:21 IST 2016\napp = Flask(__name__)\n\n#ndtv.com top stories\nndtv_rss = \"http://feeds.feedburner.com/ndtvnews-top-stories?format=xml\"\nindianex_rss = \"http://indianexpress.com/section/india/feed/\"\ntoi_rss = \"http://timesofindia.indiatimes.com/rssfeedstopstories.cms\"\n\nRSS_FEEDS = {'ndtv': \"http://feeds.feedburner.com/ndtvnews-top-stories?format=xml\",\n 'indianex':\"http://indianexpress.com/section/india/feed/\",\n 'toi':\"http://timesofindia.indiatimes.com/rssfeedstopstories.cms\"\n }\n\n\n\n'''\nndtv_rss_parsed = feedparser.parse(ndtv_rss)\n\n#store the the new article titles in a list\nndtv_news = []\n\nfor post in ndtv_rss_parsed.entries:\n ndtv_news.append(post.title)\n\n@app.route('/')\ndef ndtv():\n return render_template('ndtv.html',ndtv_news = ndtv_news)\n\n'''\n\n@app.route('/')\n@app.route('/ndtv')\ndef ndtv():\n return get_news('ndtv')\n\n@app.route('/indianex')\ndef indianex():\n return get_news('indianex')\n\n@app.route('/toi')\ndef toi():\n get_news('toi')\n\n\ndef get_news(publication):\n feed = feedparser.parse(RSS_FEEDS[publication])\n first_article = feed['entries'][0]\n return \"\"\"<html>\n <body>\n <h1>Headlines</h1>\n <b>{0}</b> </br>\n <i>{1}</i> </br>\n <p>{2}</p> </br>\n </body>\n </html>\"\"\".format(first_article.get(\"title\"),first_article.get(\"published\"),first_article.get('summary'))\n\nif __name__ == \"__main__\":\n app.run(debug = True)\n","sub_path":"headlinesRSS.py","file_name":"headlinesRSS.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"292400751","text":"import numpy as np\nfrom proteus.defaults import (Physics_base,\n Numerics_base,\n System_base)\nfrom proteus import (Domain,\n TimeIntegration,\n StepControl,\n FemTools,\n Quadrature,\n NonlinearSolvers,\n LinearAlgebraTools,\n LinearSolvers,\n MeshTools,\n Context,\n AnalyticalSolutions)\nfrom proteus.default_so import *\nfrom proteus.mprans import RANS2P\nimport os\n\nopts = Context.Options([\n (\"nd\", 2, \"Number of space dimensions\"),\n (\"grid\", True, \"Use a regular grid\"),\n (\"triangles\", True, \"Use triangular or tetrahedral elements\"),\n (\"spaceOrder\", 1, \"Use (bi-)linear or (bi-)quadratic spaces\"),\n (\"useTaylorHood\", False, \"Use Taylor-Hood element\"),\n (\"timeOrder\", 1, \"Use bdf1 or bdf2\"),\n (\"periodic\", False, \"Use periodic boundary conditions\"),\n (\"weak\", True, \"Use weak boundary conditions\"),\n (\"coord\", False, \"Use coordinates for setting boundary conditions\"),\n (\"Re\", 1.0, \"Reynolds number for non-periodic problem\"),\n #(\"nnx\", 21, \"Number of grid nodes in x-direction\"),\n (\"nnx\", 11, \"Number of grid nodes in x-direction\"),\n (\"pc_type\", 'LU', \"Specify preconditioner type\"),\n (\"A_block_AMG\", False, \"Specify whether a block-AMG should be used to solve A-block\")])\n\n#########\n#Physics#\n#########\np = Physics_base(nd = opts.nd,\n name=\"duct_physics\")\n\np.L=(4.0, 1.0, 1.0)\nif p.nd == 2:\n p.L=(4.0, 1.0)\np.domain = Domain.RectangularDomain(p.L)\nboundaryTags = p.domain.boundaryTags\nif not opts.grid:\n p.domain.writePoly(\"duct\")\n if p.nd == 3:\n p.domain = Domain.PiecewiseLinearComplexDomain()\n elif p.nd == 2:\n p.domain = Domain.PlanarStraightLineGraphDomain()\n p.domain.readPoly(\"duct\")\n\nnu = 1.004e-6\nrho = 998.2\n\nif p.nd == 3:\n h = p.L[2]\n umax = opts.Re*nu/p.L[2]\nelse:\n h = p.L[1]\n umax = opts.Re*nu/p.L[1]\np.T = 5.0*(p.L[0]/umax)\nmu = nu*rho\nG = (umax*8.0*mu)/(h**2)\n\nif opts.periodic:\n gravity = [G/rho, 0., 0.]\nelse:\n gravity = [0., 0., 0.]\n\np.LevelModelType = RANS2P.LevelModel\n\nif opts.periodic:\n nullSpace=\"NavierStokesConstantPressure\"\nelse:\n nullSpace=\"NoNullSpace\"\n\n\n\neps=1.0e-8\nif opts.periodic:\n if opts.nd == 2:\n def getPDBC(x,tag):\n if (x[0] < eps or x[0] > p.L[0] - eps) and (x[1] < eps or x[1] > p.L[1] - eps):\n return np.array([0.0,0.0,0.0])\n elif x[0] < eps or x[0] > p.L[0] - eps:\n return np.array([0.0,round(x[1],5),0.0])\n else:\n def getPDBC(x,flag):\n if (x[0] < eps or x[0] > p.L[0] - eps) and (x[1] < eps or x[1] > p.L[1] - eps) and (x[2] < eps or x[2] > p.L[2] - eps):#x,y,z corner\n return np.array([0.0,0.0,0.0])\n elif (x[0] < eps or x[0] > p.L[0] - eps) and (x[2] < eps or x[2] > p.L[2] - eps):#x-z edge\n return np.array([0.0,round(x[1],5),0.0])\n elif (x[0] < eps or x[0] > p.L[0] - eps) and (x[1] < eps or x[1] > p.L[1] - eps):#x-y edge\n return np.array([0.0,0.0,round(x[2],5)])\n elif (x[1] < eps) or (x[1] > p.L[1]-eps):#on front or back\n return np.array([round(x[0],5),0.0,round(x[2],5)])\n elif (x[0] < eps) or (x[0] > p.L[0]-eps):#on inflow or outflow (left/right)\n return np.array([0.0,round(x[1],5),round(x[2],5)])\n p.periodicDirichletConditions = {0:getPDBC,\n 1:getPDBC,\n 2:getPDBC,\n 3:getPDBC}\n\npSol2 = AnalyticalSolutions.PlanePoiseuilleFlow_p(plateSeperation=h,\n mu = mu,\n grad_p = -G)\nuSol2 = AnalyticalSolutions.PlanePoiseuilleFlow_u(plateSeperation=h,\n mu = mu,\n grad_p = -G)\nvSol2 = AnalyticalSolutions.PlanePoiseuilleFlow_v(plateSeperation=h,\n mu = mu,\n grad_p = -G)\nclass pRot(AnalyticalSolutions.SteadyState):\n def __init__(self):\n pass\n def uOfX(self, x):\n if p.nd==3:\n return pSol2.uOfX([x[0],x[2],x[1]])\n else:\n return pSol2.uOfX(x)\n\nclass uRot(AnalyticalSolutions.SteadyState):\n def __init__(self):\n pass\n def uOfX(self, x):\n if p.nd==3:\n return uSol2.uOfX([x[0],x[2],x[1]])\n else:\n return uSol2.uOfX(x)\n\nclass vRot(AnalyticalSolutions.SteadyState):\n def __init__(self):\n pass\n def uOfX(self, x):\n if p.nd==3:\n return vSol2.uOfX([x[0],x[2],x[1]])\n else:\n return vSol2.uOfX(x)\n\npSol = pRot()\nuSol = uRot()\nvSol = vRot()\n\nif p.nd == 2:\n p.analyticalSolution = {0:pSol, 1:uSol, 2: vSol}\nelif p.nd == 3:\n p.analyticalSolution = {0:pSol, 1:uSol, 2: vSol, 3: vRot()}\n\ninitialConditions = p.analyticalSolution\n\np.coefficients = RANS2P.Coefficients(epsFact=1.5,\n sigma=0.0,\n rho_0=rho,nu_0=nu,\n rho_1=rho,nu_1=nu,\n g=gravity,\n nd=p.nd,\n ME_model=0,\n VF_model=None,\n LS_model=None,\n Closure_0_model=None,\n Closure_1_model=None,\n epsFact_density=1.5,\n stokes=False,\n useVF=0.0,\n useRBLES=0.0,\n useMetrics=1.0,\n eb_adjoint_sigma=1.0,\n eb_penalty_constant=100.0,\n forceStrongDirichlet=not opts.weak,\n turbulenceClosureModel=0,\n NONCONSERVATIVE_FORM=1.0,\n MOMENTUM_SGE=0.0 if opts.useTaylorHood else 1.0,\n PRESSURE_SGE=0.0 if opts.useTaylorHood else 1.0,\n VELOCITY_SGE=0.0 if opts.useTaylorHood else 1.0,\n nullSpace=nullSpace)\n #analyticalSolution=p.analyticalSolution)\n\nnsave=25\ndt_init = 1.0e-3\nDT = (p.T-dt_init)/float(nsave-1)\np.tnList = [0.0,dt_init]+[dt_init+i*DT for i in range(nsave)]\n\nif opts.coord:\n if p.nd == 3:\n def onLeft(x):\n return x[0] < eps and x[2] > eps and x[2] < p.L[2] - eps\n def onRight(x):\n return x[0] > p.L[0] - eps and x[2] > eps and x[2] < p.L[2] - eps\n def onFront(x):\n return x[1] < eps and x[2] > eps and x[2] < p.L[2] - eps and x[0] > eps and x[0] < p.L[0] - eps\n def onBack(x):\n return x[1] > p.L[1] - eps and x[2] > eps and x[2] < p.L[2] - eps and x[0] > eps and x[0] < p.L[0] - eps\n def onBottom(x):\n return x[2] < eps\n def onTop(x):\n return x[2] > p.L[2] - eps\n elif p.nd == 2:\n def onLeft(x):\n return x[0] < eps and x[1] > eps and x[1] < p.L[1] - eps\n def onRight(x):\n return x[0] > p.L[0] - eps and x[1] > eps and x[1] < p.L[1] - eps\n def onBottom(x):\n return x[1] < eps\n def onTop(x):\n return x[1] > p.L[1] - eps\n\nif opts.periodic:\n def getDBC_pressure_duct(x,flag):\n pass\n\n def getDBC_u_duct(x,flag):\n if onTop(x) or onBottom(x):\n return lambda x,t: 0.0\n\n def getDBC_v_duct(x,flag):\n if onTop(x) or onBottom(x):\n return lambda x,t: 0.0\n\n def getDBC_w_duct(x,flag):\n if onTop(x) or onBottom(x):\n return lambda x,t: 0.0\n\n p.dirichletConditions = {0:getDBC_pressure_duct,\n 1:getDBC_u_duct,\n 2:getDBC_v_duct}\n if opts.nd==3:\n p.dirichletConditions[3] = getDBC_w_duct\n \n\n def getAFBC_p_duct(x,flag):\n if onTop(x) or onBottom(x):\n return lambda x,t: 0.0\n else:\n return lambda x,t: 0.0\n\n def getAFBC_u_duct(x,flag):\n if onTop(x) or onBottom(x):\n return lambda x,t: 0.0\n else:\n return lambda x,t: 0.0\n\n def getAFBC_v_duct(x,flag):\n if onTop(x) or onBottom(x):\n return lambda x,t: 0.0\n else:\n return lambda x,t: 0.0\n\n def getAFBC_w_duct(x,flag):\n if onTop(x) or onBottom(x):\n return lambda x,t: 0.0\n else:\n return lambda x,t: 0.0\n\n p.advectiveFluxBoundaryConditions = {0:getAFBC_p_duct,\n 1:getAFBC_u_duct,\n 2:getAFBC_v_duct}\n\n if opts.nd==3:\n p.advectiveFluxBoundaryConditions[3] = getAFBC_w_duct\n\n def getDFBC_duct(x,flag):\n if onTop(x) or onBottom(x):\n return None\n else:\n return lambda x,t: 0.0\n\n p.diffusiveFluxBoundaryConditions = {0:{},\n 1:{1:getDFBC_duct},\n 2:{2:getDFBC_duct}}\n\n if opts.nd==3:\n p.diffusiveFluxBoundaryConditions[3] = {3:getDFBC_duct}\n\nelse:\n if opts.coord:\n def getDBC_pressure_duct(x,flag):\n if onRight(x):\n return lambda x,t: pSol.uOfX(x)\n \n def getDBC_u_duct(x,flag):\n if onLeft(x):\n return lambda x,t: uSol.uOfX(x)\n if opts.weak and onRight(x):\n return lambda x,t: uSol.uOfX(x)\n if onTop(x) or onBottom(x):\n return lambda x,t: uSol.uOfX(x)\n \n def getDBC_v_duct(x,flag):\n if onLeft(x) or onTop(x) or onBottom(x):\n return lambda x,t: 0.0\n if onRight(x):\n return lambda x,t: 0.0\n\n def getDBC_w_duct(x,flag):\n if onLeft(x) or onTop(x) or onBottom(x):\n return lambda x,t: 0.0\n if onRight(x):\n return lambda x,t: 0.0\n\n p.dirichletConditions = {0:getDBC_pressure_duct,\n 1:getDBC_u_duct,\n 2:getDBC_v_duct}\n if p.nd == 3:\n p.dirichletConditions[3] = getDBC_w_duct\n\n\n def getAFBC_p_duct(x,flag):\n if onLeft(x):\n return lambda x,t: -uSol.uOfX(x)\n if onTop(x) or onBottom(x):\n return lambda x,t: 0.0\n if p.nd == 3:\n if onFront(x) or onBack(x):\n return lambda x,t: 0.0\n\n def getAFBC_u_duct(x,flag):\n if p.nd == 3:\n if onFront(x) or onBack(x):\n return lambda x,t: 0.0\n\n def getAFBC_v_duct(x,flag):\n if p.nd == 3:\n if onFront(x) or onBack(x):\n return lambda x,t: 0.0\n\n p.advectiveFluxBoundaryConditions = {0:getAFBC_p_duct,\n 1:getAFBC_u_duct,\n 2:getAFBC_v_duct}\n if p.nd == 3:\n def getAFBC_w_duct(x,flag):\n if onFront(x) or onBack(x):\n return lambda x,t: 0.0\n p.advectiveFluxBoundaryConditions[3] = getAFBC_w_duct\n\n def getDFBC_u_duct(x,flag):\n if onRight(x):\n return lambda x,t: 0.0\n elif p.nd == 3:\n if onFront(x) or onBack(x):\n return lambda x,t: 0.0\n\n def getDFBC_vw_duct(x,flag):\n if p.nd == 3:\n if onFront(x) or onBack(x):\n return lambda x,t: 0.0\n\n p.diffusiveFluxBoundaryConditions = {0:{},\n 1:{1:getDFBC_u_duct},\n 2:{2:getDFBC_vw_duct}}\n if p.nd == 3:\n p.diffusiveFluxBoundaryConditions[3] = {3:getDFBC_vw_duct}\n else:\n def getDBC_pressure_duct(x,flag):\n if flag == boundaryTags['right']:\n return lambda x,t: pSol.uOfX(x)\n\n def getDBC_u_duct(x,flag):\n if flag == boundaryTags['left']:\n return lambda x,t: uSol.uOfX(x)\n if opts.weak and flag == boundaryTags['right']:\n return lambda x,t: 0.0\n if flag in [boundaryTags['top'], boundaryTags['bottom']]:\n return lambda x,t: 0.0\n def getDBC_v_duct(x,flag):\n if flag in [boundaryTags['left'],\n boundaryTags['top'],\n boundaryTags['bottom']]:\n return lambda x,t: 0.0\n elif opts.weak and flag == boundaryTags['right']:\n return lambda x,t: 0.0\n def getDBC_w_duct(x,flag):\n if flag in [boundaryTags['left'],\n boundaryTags['top'],\n boundaryTags['bottom']]:\n return lambda x,t: 0.0\n elif opts.weak and flag == boundaryTags['right']:\n return lambda x,t: 0.0\n\n p.dirichletConditions = {0:getDBC_pressure_duct,\n 1:getDBC_u_duct,\n 2:getDBC_v_duct}\n if p.nd == 3:\n p.dirichletConditions[3] = getDBC_w_duct\n\n\n def getAFBC_p_duct(x,flag):\n if flag == boundaryTags['left']:\n return lambda x,t: -uSol.uOfX(x)\n if flag in [boundaryTags['top'],\n boundaryTags['bottom']]:\n return lambda x,t: 0.0\n if p.nd == 3 and flag in [boundaryTags['front'],\n boundaryTags['back'],\n 0]:\n return lambda x,t: 0.0\n elif p.nd == 2 and flag == 0:\n return lambda x,t: 0.0\n\n def getAFBC_u_duct(x,flag):\n if p.nd == 3 and flag in [boundaryTags['front'],\n boundaryTags['back'],\n 0]:\n return lambda x,t: 0.0\n elif p.nd == 2 and flag == 0:\n return lambda x,t: 0.0\n\n def getAFBC_v_duct(x,flag):\n if p.nd == 3 and flag in [boundaryTags['front'],\n boundaryTags['back'],\n 0]:\n return lambda x,t: 0.0\n elif p.nd == 2 and flag == 0:\n return lambda x,t: 0.0\n def getAFBC_w_duct(x,flag):\n if flag in [boundaryTags['front'],\n boundaryTags['back'],\n 0]:\n return lambda x,t: 0.0\n\n p.advectiveFluxBoundaryConditions = {0:getAFBC_p_duct,\n 1:getAFBC_u_duct,\n 2:getAFBC_v_duct}\n if p.nd == 3:\n p.advectiveFluxBoundaryConditions[3] = getAFBC_w_duct\n\n def getDFBC_duct(x,flag):\n if flag == boundaryTags['right']:#outflow\n return lambda x,t: 0.0\n if p.nd == 3 and flag in [boundaryTags['front'],\n boundaryTags['back'],\n 0]:\n return lambda x,t: 0.0\n elif p.nd == 2 and flag == 0:\n return lambda x,t: 0.0\n p.diffusiveFluxBoundaryConditions = {0:{},\n 1:{1:getDFBC_duct},\n 2:{2:getDFBC_duct}}\n if p.nd == 3:\n p.diffusiveFluxBoundaryConditions[3] = {3:getDFBC_duct}\n\n##########\n#Numerics#\n##########\n\nn = Numerics_base()\n\n#time stepping\nn.runCFL = 0.9\nif opts.timeOrder == 2:\n n.timeIntegration = TimeIntegration.VBDF\n n.timeOrder = 2\nelif opts.timeOrder == 1:\n n.timeIntegration = TimeIntegration.BackwardEuler\n n.timeOrder = 1\nelif opts.timeOrder == 0:\n n.timeIntegration = TimeIntegration.NoIntegration\n\nn.stepController = StepControl.Min_dt_cfl_controller\nn.systemStepExact = True\n\nif opts.spaceOrder == 1:\n if opts.triangles:\n if opts.useTaylorHood:\n n.femSpaces = {0:FemTools.C0_AffineLinearOnSimplexWithNodalBasis,\n 1:FemTools.C0_AffineQuadraticOnSimplexWithNodalBasis,\n 2:FemTools.C0_AffineQuadraticOnSimplexWithNodalBasis}\n if p.nd == 3:\n n.femSpaces[3] = FemTools.C0_AffineQuadraticOnSimplexWithNodalBasis\n n.elementQuadrature = Quadrature.SimplexGaussQuadrature(p.nd,5)\n n.elementBoundaryQuadrature = Quadrature.SimplexGaussQuadrature(p.nd-1,5)\n else:\n n.femSpaces = {0:FemTools.C0_AffineLinearOnSimplexWithNodalBasis,\n 1:FemTools.C0_AffineLinearOnSimplexWithNodalBasis,\n 2:FemTools.C0_AffineLinearOnSimplexWithNodalBasis}\n if p.nd == 3:\n n.femSpaces[3] = FemTools.C0_AffineLinearOnSimplexWithNodalBasis\n n.elementQuadrature = Quadrature.SimplexGaussQuadrature(p.nd,5)\n n.elementBoundaryQuadrature = Quadrature.SimplexGaussQuadrature(p.nd-1,5)\n else:\n if opts.useTaylorHood:\n n.femSpaces = {0:FemTools.C0_AffineLinearOnCubeWithNodalBasis,\n 1:FemTools.C0_AffineQuadraticOnCubeWithNodalBasis,\n 2:FemTools.C0_AffineQuadraticOnCubeWithNodalBasis}\n if p.nd == 3:\n n.hex = True\n n.femSpaces[3] = FemTools.C0_AffineQuadraticOnCubeWithNodalBasis\n else:\n n.quad = True\n n.elementQuadrature = Quadrature.CubeGaussQuadrature(p.nd,2)\n n.elementBoundaryQuadrature = Quadrature.CubeGaussQuadrature(p.nd-1,2)\n else:\n n.femSpaces = {0:FemTools.C0_AffineLinearOnCubeWithNodalBasis,\n 1:FemTools.C0_AffineLinearOnCubeWithNodalBasis,\n 2:FemTools.C0_AffineLinearOnCubeWithNodalBasis}\n if p.nd == 3:\n n.hex = True\n n.femSpaces[3] = FemTools.C0_AffineLinearOnCubeWithNodalBasis\n else:\n n.quad = True\n n.elementQuadrature = Quadrature.CubeGaussQuadrature(p.nd,5)\n n.elementBoundaryQuadrature = Quadrature.CubeGaussQuadrature(p.nd-1,5)\n\nelif opts.spaceOrder == 2: \n if opts.triangles:\n n.femSpaces = {0:FemTools.C0_AffineQuadraticOnSimplexWithNodalBasis,\n 1:FemTools.C0_AffineQuadraticOnSimplexWithNodalBasis,\n 2:FemTools.C0_AffineQuadraticOnSimplexWithNodalBasis}\n if p.nd == 3:\n n.femSpaces[3] = FemTools.C0_AffineQuadraticOnSimplexWithNodalBasis\n n.elementQuadrature = Quadrature.SimplexGaussQuadrature(p.nd,5)\n n.elementBoundaryQuadrature = Quadrature.SimplexGaussQuadrature(p.nd-1,5)\n else:\n n.femSpaces = {0:FemTools.C0_AffineQuadraticOnCubeWithNodalBasis,\n 1:FemTools.C0_AffineQuadraticOnCubeWithNodalBasis,\n 2:FemTools.C0_AffineQuadraticOnCubeWithNodalBasis}\n if p.nd == 3:\n n.femSpaces[3] = FemTools.C0_AffineQuadraticOnCubeWithNodalBasis\n n.elementQuadrature = Quadrature.SimplexGaussQuadrature(p.nd,5)\n n.elementBoundaryQuadrature = Quadrature.SimplexGaussQuadrature(p.nd-1,5)\n\nn.nnx=opts.nnx\nn.nny=(n.nnx-1)//4\nif p.nd == 3:\n n.nnz=n.nny\n\np.domain.MeshOptions.nnx = n.nnx\np.domain.MeshOptions.nny = n.nny\np.domain.MeshOptions.nnz = n.nnz\n#p.domain.MeshOptions.hex = n.hex\np.domain.MeshOptions.quad = n.quad\n\nhe = p.L[0]/float(n.nnx-1)\nif p.nd == 3:\n p.domain.MeshOptions.triangleOptions=\"VApq1.25q12feena%e\" % ((he**3)/6.0,)\nelse:\n p.domain.MeshOptions.triangleFlag = 0#if regular triangulatio then alternate diagonals\n p.domain.MeshOptions.triangleOptions=\"pAq30.0Dena%f\" % ((he**2)/4.0,)\n\nn.numericalFluxType = RANS2P.NumericalFlux\n\nif opts.periodic:\n n.periodicDirichletConditions = p.periodicDirichletConditions\n n.parallelPeriodic=True\n\nn.subgridError = RANS2P.SubgridError(coefficients=p.coefficients,\n nd=p.nd,\n lag=True,\n hFactor=1.0)\n\nn.shockCapturing = RANS2P.ShockCapturing(coefficients=p.coefficients,\n nd=p.nd,\n shockCapturingFactor=0.0,\n lag=True)\n\nn.multilevelNonlinearSolver = NonlinearSolvers.Newton\n\nn.levelNonlinearSolver = NonlinearSolvers.Newton\n\nn.fullNewtonFlag = True\nn.maxNonlinearIts = 50\nn.maxLineSearches = 0\n\nn.tolFac = 0.0\n\nn.nl_atol_res = 1.0e-8\n\nn.matrix = LinearAlgebraTools.SparseMatrix\n\nn.multilevelLinearSolver = LinearSolvers.KSP_petsc4py\nn.levelLinearSolver = LinearSolvers.KSP_petsc4py\n\nif opts.pc_type == 'LU':\n n.multilevelLinearSolver = LinearSolvers.LU\n n.levelLinearSolver = LinearSolvers.LU\n n.linearSmoother = None\nelif opts.pc_type == 'selfp_petsc':\n if p.nd==3:\n n.linearSmoother = LinearSolvers.SimpleNavierStokes3D\n n.linearSmootherOptions = (opts.A_block_AMG,)\n elif p.nd==2:\n n.linearSmoother = LinearSolvers.SimpleNavierStokes2D\n n.linearSmootherOptions = (opts.A_block_AMG,)\nelif opts.pc_type == 'two_phase_PCD':\n n.linearSmoother = LinearSolvers.NavierStokes_TwoPhasePCD\n n.linearSmootherOptions = (False,\n True,\n 1,\n 0,\n 1,\n False)\n #(density_scaling, numerical_viscosity, pcd_lumped, chebyshev_its, laplace_null_space)\n\nn.linear_solver_options_prefix = 'rans2p_'\n\nn.linTolFac = 0.0\nn.l_atol_res = 0.01*n.nl_atol_res\n\nn.conservativeFlux = None\n\nif opts.periodic:\n n.parallelPartitioningType = MeshTools.MeshParallelPartitioningTypes.element\nelse:\n n.parallelPartitioningType = MeshTools.MeshParallelPartitioningTypes.node\nn.nLayersOfOverlapForParallel = 0\n\n##############\n#System input#\n##############\nfrom proteus.default_so import *\nsystemStepExact=n.systemStepExact\ntnList = p.tnList\npnList=[(p,n)]\nif opts.periodic:\n mesh_name = \"pg\"\n p.domain.MeshOptions.genMesh=False\n p.domain.polyfile=os.path.dirname(os.path.abspath(__file__))+\"/\"+\"tetgen\"\nelse:\n if opts.grid:\n mesh_name = \"rg\"\n else:\n mesh_name = \"ug\"\nif opts.triangles:\n space_name=\"p{0}\".format(opts.spaceOrder)\nelse:\n space_name=\"q{0}\".format(opts.spaceOrder)\n\nif opts.useTaylorHood:\n space_name+=\"TH\"\n \nname = \"duct{0}t{1}{2}d{3}he{4}\".format(space_name,\n opts.timeOrder,\n opts.nd,\n mesh_name,\n he)\n","sub_path":"proteus/tests/periodic/duct.py","file_name":"duct.py","file_ext":"py","file_size_in_byte":23331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"449328856","text":"#!/usr/bin/env python\n\nimport os\nimport numpy as np\nfrom subprocess import call\n\n'''\n\tAnchoHash:\n if (argc < 6) {\n\t\tcout << \"Usage Error:\\n\";\n\t\tcout << \"argv[1]: int AcnhorSet\\n\";\n\t\tcout << \"argv[2]: int WorkingSet\\n\";\n\t\tcout << \"argv[3]: int NumRemovals\\n\";\n\t\tcout << \"argv[4]: int NumKeys\\n\";\n\t\tcout << \"argv[5]: int ResFileName\\n\";\n\t\treturn 1;\n\t}\n\t\n'''\n\ntry:\n\t\n\tdir_name = \"./\"\n\ttest = os.listdir(dir_name)\n\n\tfor item in test:\n\t\tif item.endswith(\".txt\"):\n\t\t\tos.remove(os.path.join(dir_name, item))\n\t\n\t\nexcept OSError:\n pass\n\nup = 6\n \nworkingset = [np.ceil(1.0*(10**i)) for i in range(1,up)] \n\nacnhorset_0 = [np.ceil(1.0*(10**i)) for i in range(1,up)]\nacnhorset_10 = [np.ceil(1.1*(10**i)) for i in range(1,up)]\nacnhorset_100 = [np.ceil(2.0*(10**i)) for i in range(1,up)]\nacnhorset_1000 = [np.ceil(10.0*(10**i)) for i in range(1,up)]\nacnhorset_10000 = [np.ceil(100.0*(10**i)) for i in range(1,up)]\n\n\n\nnumkeys = 100000000\nnumremovals = 0\n\nfor i in range(len(workingset)):\n\n\tcall([\"./speed_test\", str(acnhorset_0[i]), str(acnhorset_0[i]), str(acnhorset_0[i]-workingset[i]), str(numkeys), 'anchor_0.txt'])\n\tcall([\"./speed_test\", str(acnhorset_10[i]), str(acnhorset_10[i]), str(acnhorset_10[i]-workingset[i]), str(numkeys), 'anchor_10.txt'])\n\tcall([\"./speed_test\", str(acnhorset_100[i]), str(acnhorset_100[i]), str(acnhorset_100[i]-workingset[i]), str(numkeys), 'anchor_100.txt'])\n\tcall([\"./speed_test\", str(acnhorset_1000[i]), str(acnhorset_1000[i]), str(acnhorset_1000[i]-workingset[i]), str(numkeys), 'anchor_1000.txt'])\n\tcall([\"./speed_test\", str(acnhorset_10000[i]), str(acnhorset_10000[i]), str(acnhorset_10000[i]-workingset[i]), str(numkeys), 'anchor_10000.txt'])\n\n\n\t\n\t\n\t\n\t\n\t\n\n","sub_path":"tests/speed/speed_test.py","file_name":"speed_test.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"266045761","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport jsonfield.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('lightr', '0003_attachment_issue'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='connection',\n name='issue_labels',\n field=jsonfield.fields.JSONField(default=[]),\n preserve_default=True,\n ),\n ]\n","sub_path":"lightr/migrations/0004_connection_issue_labels.py","file_name":"0004_connection_issue_labels.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"114143642","text":"#!/usr/bin/env python3\n# extract features from xml file for IAM dataset\n\nimport xml.etree.ElementTree as ET\nimport glob\nimport os\n\ndef main():\n flist = glob.glob('../data/iam/xml/*.xml')\n for fname in flist:\n print('fname:', fname)\n tree = ET.parse(fname)\n line_info = []\n word_info = []\n for line in tree.findall('.//line'):\n li = \"%s: %s\" % (line.attrib['id'], line.attrib['text'])\n line_info.append(li)\n # print(\" %s\" % li)\n for word in line.iter('word'):\n wi = \"%s: %s\" % (word.attrib['id'], word.attrib['text'])\n word_info.append(wi)\n # print(\" %s\" % wi)\n\n ftarget = os.path.splitext(fname)[0] + '.txt'\n print('ftarget:', ftarget)\n with open(ftarget, 'w') as fout:\n fout.write('\\n'.join(line_info) + '\\n')\n fout.write('\\n'.join(word_info) + '\\n')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/mklabel.py","file_name":"mklabel.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"351074111","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sqlite3\n\nclass SaveToSqlite():\n def __init__(self, dbfile, logging):\n self.dbfile = dbfile\n self.logging = logging\n self.conn = sqlite3.connect(dbfile, check_same_thread = False)\n #设置支持中文存储\n self.conn.text_factory = str\n self.cmd = self.conn.cursor()\n self.cmd.execute('''\n create table if not exists data(\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n url text,\n url_hash text,\n deep INTEGER,\n html text\n )\n ''')\n self.conn.commit()\n\n def save(self, url, url_hash, deep, html):\n try:\n self.cmd.execute(\"insert into data (url, url_hash, deep, html) values (?,?,?,?)\", (url, url_hash, deep, html))\n self.conn.commit()\n except Exception as e:\n self.logging.error(\"Unexpected error:{0}\".format(str(e)))\n\n def close(self):\n self.conn.close()\n\n","sub_path":"utils/save.py","file_name":"save.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"21206485","text":"#!/usr/bin/python3\n\"\"\"\nUtils for files\n\"\"\"\nimport os\n\n\ndef get_dir_from_path(path):\n \"\"\"\n Extract and return the directory from the file path\n :param path: full file path (must end with file, not dir)\n :return: directory, ending without '/'\n usage:\n get_dir_from_path(\"/home/user/.vimrc\") -> \"/home/user\"\n \"\"\"\n return \"/\".join(path.split(\"/\")[0:-1])\n\n\ndef create_file(path, clean=False):\n \"\"\"\n Create a file at 'path', optionally removing any existing file beforehand.\n :param path: full path to file. Will be created if doesn't exist.\n :param clean: if True, will remove any existing file at path. If False,\n will not create file if exists.\n \"\"\"\n directory = get_dir_from_path(path)\n if directory is not '' and not os.path.exists(directory):\n os.makedirs(directory)\n if clean:\n os.remove(path)\n with open(path, \"a\"):\n pass\n\n\ndef get_filenames_in(directory, extension_filter=None, get_full_path=False):\n \"\"\"\n Get a list of filenames in 'directory'\n :param directory: the directory to enumerate files from\n :param extension_filter: Optional filter for filetype extensions\n :param get_full_path: Optional boolean to include the full path for each file\n (e.g. json, txt, log, etc.)\n :return: set() of filename strings\n usage:\n get_filenames_in(\"/home/users/\") -> [\".vimrc\", \"config.json\", \"test.log\"]\n get_filenames_in(\"/home/user/\", \"json\") -> [\"config.json\"]\n get_filenames_in(\"/home/user/\", \"json\", True) -> [\"/home/user/config.json\"]\n \"\"\"\n s = set()\n files_only = [f for f in os.listdir(directory)\n if os.path.isfile(os.path.join(directory, f))]\n if extension_filter is not None:\n files_only = [f for f in files_only\n if f.endswith(\".{extension}\".format(\n extension=extension_filter))]\n if get_full_path:\n files_only = [os.path.join(directory, f) for f in files_only]\n\n # add the files to the set\n for f in files_only:\n s.add(f)\n return s\n","sub_path":"utils/python/utils/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"154667455","text":"import numpy as np\nfrom snoRNA.hsic_kernel_weights_norm import hsic_kernel_weights_norm\n\n\nnames = ['CKSNAP', 'DNC', 'Kmer4', 'Kmer1234', 'NAC', 'RCKmer', 'TNC']\n\nK1 = np.loadtxt('D:/Study/Bioinformatics/snoRNA/tanimoto_kernel/KM_tanimoto_' + names[0] + '_train.csv', delimiter=',')\nK2 = np.loadtxt('D:/Study/Bioinformatics/snoRNA/tanimoto_kernel/KM_tanimoto_' + names[1] + '_train.csv', delimiter=',')\nK3 = np.loadtxt('D:/Study/Bioinformatics/snoRNA/tanimoto_kernel/KM_tanimoto_' + names[2] + '_train.csv', delimiter=',')\nK4 = np.loadtxt('D:/Study/Bioinformatics/snoRNA/tanimoto_kernel/KM_tanimoto_' + names[3] + '_train.csv', delimiter=',')\nK5 = np.loadtxt('D:/Study/Bioinformatics/snoRNA/tanimoto_kernel/KM_tanimoto_' + names[4] + '_train.csv', delimiter=',')\nK6 = np.loadtxt('D:/Study/Bioinformatics/snoRNA/tanimoto_kernel/KM_tanimoto_' + names[5] + '_train.csv', delimiter=',')\nK7 = np.loadtxt('D:/Study/Bioinformatics/snoRNA/tanimoto_kernel/KM_tanimoto_' + names[6] + '_train.csv', delimiter=',')\nlabel = np.loadtxt('D:/Study/Bioinformatics/snoRNA/snoRNA_label.csv', delimiter=',', skiprows=1)\n\nK_train = np.array([K1, K2, K3, K4, K5, K6, K7])\n\nkernel_weights = hsic_kernel_weights_norm(K_train, label, 1, 0.1, 0.01)\nprint(kernel_weights)\n","sub_path":"snoRNA/computeWeight.py","file_name":"computeWeight.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"546924534","text":"from flask import Flask, render_template, request\napp = Flask(__name__)\n\nresults_title = [\"戦いに破れ机の上で爆睡\", \"逃げてPythonかたかた。\", \"お布団に包まれ...。\", \"踊り狂ってふらっふらふら フラミンゴ\", \"逆立ちっ!できないっ!\", \"ぬこぬこぬこぬこ\"]\nresults_sentence = [\"あーるんは無理して戦ったので机の上で爆睡しました。3時間後に目が覚めて絶望してそのまま寝ました。\",\n \"楽しかったので眠気には負けず、PythonかたかたしてたらこのWebアプリが完成しました。宿題は終わっていません。\",\n \"大人しくそのまま寝たあーるんは、心地の良い夢の世界へ旅立ちました。ついでに朝まで目覚めることはありませんでした。ちゃんちゃん。\",\n \"バレエのくるくる回るのがしたくてやってみましたが、目が回りました。ついでに捻挫もしました。あーるんに運動をさせてはいけません。\",\n \"昔どっかの本で逆立ちしたら落ち着くって聞いたので逆立ちしました。できませんでした。頭に血が回ってふらっふらふら フラミンゴ\",\n \"にゃーにゃにゃにゃ、にゃーにゃーふにゃにゃ。にゃーごにゃ、にゃにゃにゃーーーーーにゃ。にゃっにゃ。\"]\nkey_list = [\"fight\", \"escape\", \"sleep\", \"dance\", \"handstand\", \"cat\"]\n\n@app.route(\"/\")\ndef index():\n title = None\n sentence = None\n\n key = request.args.get(\"action_key\",\"\")\n if key in key_list:\n title = results_title[key_list.index(key)]\n sentence = results_sentence[key_list.index(key)]\n\n return render_template(\"index.html\", methods=['POST','GET'], title=title, sentence=sentence)\n\nif __name__ == '__main__':\n app.debug = True\n app.run(host='0.0.0.0')","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"381198943","text":"# -*- coding: utf-8 -*-\nfrom apollo.frontend import route\nfrom apollo import services\nfrom apollo.core import csrf\nfrom apollo.messaging.forms import KannelForm, TelerivetForm\nfrom apollo.messaging.helpers import parse_message\nfrom apollo.messaging.utils import parse_text\nfrom flask import Blueprint, make_response, request, g, current_app\nimport json\nimport re\nfrom unidecode import unidecode\n\n\nbp = Blueprint('messaging', __name__)\n\n\ndef lookup_participant(msg, event=None):\n participant = None\n unused, participant_id, unused, unused, unused = parse_text(msg.text)\n\n evt = getattr(g, 'event', None) or event\n\n if participant_id:\n participant = services.participants.get(\n event=evt,\n participant_id=participant_id\n )\n\n if not participant:\n try:\n clean_number = msg.sender.replace('+', '')\n participant = services.participants.get(\n event=evt,\n phones__number__contains=clean_number\n )\n except services.participants.__model__.MultipleObjectsReturned:\n participant = None\n\n return participant\n\n\ndef update_datastore(inbound, outbound, submission, had_errors):\n if submission:\n participant = submission.contributor\n else:\n participant = lookup_participant(inbound)\n\n if participant:\n inbound.update(\n set__participant=participant,\n set__submission=submission\n )\n outbound.update(\n set__participant=participant,\n set__submission=submission\n )\n\n if not had_errors:\n participant.update(inc__accurate_message_count=1)\n\n participant.update(inc__message_count=1)\n\n\n@route(bp, '/messaging/kannel', methods=['GET'])\ndef kannel_view():\n secret = request.args.get('secret')\n\n # only allow requests that contain the gateway secret\n if secret != current_app.config.get('MESSAGING_SECRET'):\n return ''\n\n form = KannelForm(request.args)\n if form.validate():\n msg = form.get_message()\n incoming = services.messages.log_message(\n event=g.event, sender=msg.get('sender'), text=msg.get('text'),\n direction='IN', timestamp=msg.get('timestamp'))\n\n response, submission, had_errors = parse_message(form)\n\n if current_app.config.get(u'TRANSLITERATE_OUTPUT'):\n response = unidecode(response)\n\n outgoing = services.messages.log_message(\n event=g.event, recipient=msg.get('sender'), text=response,\n direction='OUT', timestamp=msg.get('timestamp'))\n\n update_datastore(incoming, outgoing, submission, had_errors)\n\n return response\n return \"\"\n\n\n@csrf.exempt\n@route(bp, '/messaging/telerivet', methods=['POST'])\ndef telerivet_view():\n secret = request.form.get('secret')\n\n if secret != current_app.config.get('MESSAGING_SECRET'):\n return ''\n\n # if the sender is the same as the recipient, then don't respond\n if re.sub(r'[^\\d]', '', request.form.get('from_number')) == re.sub(r'[^\\d]', '', request.form.get('to_number')):\n return ''\n\n form = TelerivetForm(request.form)\n if form.validate():\n msg = form.get_message()\n incoming = services.messages.log_message(\n event=g.event, sender=msg.get('sender'), text=msg.get('text'),\n direction='IN', timestamp=msg.get('timestamp'))\n\n response_text, submission, had_errors = parse_message(form)\n if current_app.config.get(u'TRANSLITERATE_OUTPUT'):\n response_text = unidecode(response_text)\n response = {'messages': [{'content': response_text}]}\n http_response = make_response(json.dumps(response))\n http_response.headers['Content-Type'] = 'application/json'\n\n outgoing = services.messages.log_message(\n event=g.event, recipient=msg.get('sender'), text=response_text,\n direction='OUT', timestamp=msg.get('timestamp'))\n\n update_datastore(incoming, outgoing, submission, had_errors)\n\n return http_response\n return \"\"\n","sub_path":"apollo/messaging/views_messaging.py","file_name":"views_messaging.py","file_ext":"py","file_size_in_byte":4077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"615983146","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2016-11-21 21:07:17\n# @Author : Ying Sun\n# @Link : Ying.example.com\n# @Version : 0.1\n\nimport os\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.utils import formataddr\n\n\ndef email(message):\n msg = MIMEText(message, 'plain', 'utf-8')\n msg['From'] = formataddr([\"孙大喜\", 'sunying2861732@126.com'])\n msg['To'] = formataddr([\"孙小喜\", '782670246@qq.com'])\n msg['Subject'] = \"报警了\"\n\n server = smtplib.SMTP(\"smtp.126.com\", 25)\n server.login(\"sunying2861732@126.com\", \"2861732\")\n server.sendmail('sunying2861732@126.com', [\n '782670246@qq.com', ], msg.as_string())\n server.quit()\n\n\nif __name__ == '__main__':\n cpu = 60\n disk = 500\n ram = 50\n for i in range(1):\n if cpu > 90:\n alert = u\"CPU出问题\"\n email(alert)\n if ram > 60:\n alert = u\"RAM挂了\"\n email(alert)\n if disk > 400:\n alert = u\"磁盘崩溃了...\"\n email(alert)\n","sub_path":"day3/alarm_system.py","file_name":"alarm_system.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"511142078","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.linalg import eig, eigh\nfrom scipy.constants import e, k\n\nk_B = k / e # Boltzmann constant [eV/K] 8.6173303e-05\n\ndef fd(energy, ef, temp):\n return 1.0 / (1.0 + np.exp((energy - ef) / (k_B * temp)))\n\n\ndef approximant(energy, poles, residues):\n\n arg = np.array(energy)\n ans = np.zeros(arg.shape) + 0.5\n\n for j in range(len(poles)):\n if poles[j] > 0:\n ans = ans - residues[j] / (arg - 1j / poles[j]) - residues[j] / (arg + 1j / poles[j])\n\n return ans\n\n\ndef approximant_diff(energy, poles, residues):\n\n arg = np.array(energy)\n ans = np.zeros(arg.shape) + 0.5 * 0\n\n for j in range(len(poles)):\n if poles[j] > 0:\n ans = ans - residues[j] / (arg - 1j / poles[j]) ** 2 - residues[j] / (arg + 1j / poles[j]) ** 2\n\n return ans\n\n\ndef poles_and_residues(cutoff=2):\n\n b_mat = [1 / (2.0 * np.sqrt((2*(j+1) - 1)*(2*(j+1) + 1))) for j in range(0, cutoff-1)]\n b_mat = np.matrix(np.diag(b_mat, -1)) + np.matrix(np.diag(b_mat, 1))\n\n poles, residues = eig(b_mat)\n\n residues = np.array(np.matrix(residues))\n # arg = np.argmax(np.abs(residues), axis=0)\n\n residues = 0.25 * np.array([np.abs(residues[0, j])**2 / (poles[j] ** 2) for j in range(residues.shape[0])])\n\n return poles, residues\n\n\ndef zero_fermi(nzp):\n '''Compute poles (zp) and residues (Rp) of fermi function.'''\n N = nzp\n M = 2*N\n\n A = np.zeros((2*M,2*M))\n B = np.zeros((2*M,2*M))\n\n zp = np.zeros(2+M)\n Rp = np.zeros(2+M)\n\n for i in range(1,M+1):\n B[i,i] = (2*i-1)\n\n for i in range(1,M):\n A[i,i+1] = -0.5;\n A[i+1,i] = -0.5;\n\n a = np.zeros(M*M)\n b = np.zeros(M*M)\n\n for i in range(M):\n for j in range(M):\n a[j*M+i] = A[i+1,j+1]\n b[j*M+i] = B[i+1,j+1]\n\n a.shape = (M,M)\n b.shape = (M,M)\n\n eigvas, eigvecs = eigh(a,b)\n\n zp[:M] = eigvas\n\n for i in range(M,0,-1):\n zp[i] = zp[i-1]\n\n for i in range(1,M+1):\n zp[i] = 1.0/zp[i];\n\n a = eigvecs.T.flatten()\n\n for i in range(0,M):\n Rp[i+1] = -a[i*M]*a[i*M]*zp[i+1]*zp[i+1]*0.250;\n\n zp = -zp[1:N+1]\n Rp = Rp[1:N+1]\n\n return zp, Rp\n\ndef integrate_pdos(G, zp, Rp, mu=0, T=300):#nzp=100, R=1e10):\n\n # zp, Rp = zero_fermi(nzp)\n N = len(zp)#nzp\n\n beta = 1/(k_B*T)\n a_p = mu + 1j*zp/beta\n\n eta = G.eta\n G.eta = complex(0.)\n\n R = 1e10\n mu_0 = 1j*R*G.apply_retarded(1j*R, G.S).diagonal()\n\n mu_1 = np.zeros(len(G.H), complex)\n for i in range(N):\n mu_1 += G.apply_retarded(a_p[i], G.S).diagonal() * Rp[i]\n mu_1 *= -1j*4/beta\n\n rho = np.real(mu_0) + np.imag(mu_1)\n\n G.eta = eta\n\n return rho\n\nif __name__=='__main__':\n\n a1, b1 = poles_and_residues(cutoff=2)\n a2, b2 = poles_and_residues(cutoff=10)\n a3, b3 = poles_and_residues(cutoff=30)\n a4, b4 = poles_and_residues(cutoff=50)\n a5, b5 = poles_and_residues(cutoff=100)\n\n energy = np.linspace(-5.7, 5.7, 3000)\n\n temp = 100\n fd0 = fd(energy, 0, temp)\n\n k_B = 8.61733e-5 # Boltzmann constant in eV\n energy = energy / (k_B * temp)\n\n ans1 = approximant(energy, a1, b1)\n ans2 = approximant(energy, a2, b2)\n ans3 = approximant(energy, a3, b3)\n ans4 = approximant(energy, a4, b4)\n ans5 = approximant(energy, a5, b5)\n\n plt.plot(fd0)\n plt.plot(ans1)\n plt.plot(ans2)\n plt.plot(ans3)\n plt.plot(ans4)\n plt.plot(ans5)\n plt.show()\n","sub_path":"transport/continued_fraction_representation.py","file_name":"continued_fraction_representation.py","file_ext":"py","file_size_in_byte":3434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"308423430","text":"from ward import test, fixture\n\nfrom darkseer.informants import OpenDotaClient\n\n\n@fixture\nasync def client():\n opendota_client = OpenDotaClient()\n yield opendota_client\n await opendota_client.aclose()\n\n\n@test('OpenDota.explorer returns JSON results', tags=['opendota', 'integration'])\nasync def _(client=client):\n q = \"\"\"\n SELECT match_id\n FROM player_matches\n GROUP BY match_id\n ORDER BY match_id\n LIMIT 50\n \"\"\"\n r = await client.explorer(q)\n assert isinstance(r, list)\n assert isinstance(r[0], dict)\n","sub_path":"tests/informants/opendota/test_response_output.py","file_name":"test_response_output.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"21925179","text":"'''\nhttps://docs.python.org/3.4/library/tkinter.html\nhttp://www.tkdocs.com/tutorial/firstexample.html\nhttp://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html\n'''\nfrom tkinter import *\nfrom tkinter import ttk\n\nroot = Tk()\nroot.title(\"Pyrom\")\nroot.eval(\"set tk_library\")\n\nmainframe = ttk.Frame(root, padding=\"3 3 3 3\")\nmainframe.grid(column=0, row=0, sticky=(N, W, E, S))\nmainframe.columnconfigure(0, weight=1)\nmainframe.rowconfigure(0, weight=1)\n\nheadframe = ttk.Frame(mainframe, padding=\"0 0 0 0\")\nheadframe.grid(column=0, row=0)\n\nfootframe = ttk.Frame(mainframe, padding=\"0 0 0 0\")\nfootframe.grid(column=0, row=1)\n\nttk.Button(headframe, text=\"Calculate 1\").grid(column=0, row=0, sticky=W)\nttk.Button(headframe, text=\"Calculate 2\").grid(column=1, row=1, sticky=W)\n\nselectedModuleOption = StringVar()\noptionList = [\"opção 1\", 'opção 2', 'opção 3', 'opção 4']\nModuleOpMenu = ttk.OptionMenu(headframe, selectedModuleOption)\nModuleOpMenu.set_menu(*optionList)\nModuleOpMenu.grid(column=0, row=2, sticky=W)\n\nroot.mainloop()\n","sub_path":"view/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"350640032","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 2 10:30:40 2018\n\n@author: sandi\n\"\"\"\n\nimport numpy as np \nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import roc_auc_score\n\ndataset = pd.read_csv('Training_dataset_Original.csv')\n\ndataset.replace('missing', np.nan, inplace=True)\ndataset.replace('na', np.nan, inplace=True)\n\ndataset = dataset.replace('L',1)\ndataset = dataset.replace('C',0)\n\n\n# from sklearn.preprocessing import Imputer\n# imputer = Imputer(missing_values = 'NaN', strategy = 'median', axis = 0)\n# imputer = imputer.fit(X[:, :47])\n# X[:, :47] = imputer.transform(X[:, :47])\n# dataset.interpolate(method='linear', inplace=True)\ndataset = dataset.apply(lambda x: x.fillna(x.median()),axis=0)\n\nX = dataset.iloc[:, :48].values\ny = dataset.iloc[:,48].values\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\n\n# =============================================================================\n# from sklearn.preprocessing import StandardScaler\n# sc = StandardScaler()\n# X_train_std = sc.fit_transform(X_train)\n# X_test_std = sc.fit_transform(X_test)\n# \n# =============================================================================\n#seeing the eigen values(PCA)\n# =============================================================================\n# cov_mat = np.cov(X_train_std.T)\n# eigen_vals, eigen_vecs = np.linalg.eig(cov_mat)\n# print('\\nEigenValues\\n%s' %eigen_vals)\n# \n# tot = sum(eigen_vals)\n# var_exp = [(i/tot) for i in sorted(eigen_vals, reverse=True)]\n# cum_var_exp = np.cumsum(var_exp)\n# =============================================================================\n\n# =============================================================================\n# import matplotlib.pyplot as plt\n# plt.bar(range(1,49), var_exp, alpha=0.5, align='center',label='individual explained variance')\n# plt.step(range(1,49), cum_var_exp, where='mid',label='cumulative explained variance')\n# plt.ylabel('Explained variance ratio')\n# plt.xlabel('Principal components')\n# plt.legend(loc='best')\n# plt.show()\n# =============================================================================\n\n#Stratified K-fold\n# =============================================================================\n# from sklearn.model_selection import StratifiedKFold\n# kfold = StratifiedKFold(\n# n_splits=10\n# )\n# for train_index, test_index in kfold.split(X,y): \n# print(\"Train:\", train_index, \"Validation:\", test_index) \n# X_train, X_test = X[train_index], X[test_index] \n# y_train, y_test = y[train_index], y[test_index]\n# \n# =============================================================================\n\n\n\n\n\n\n\nfrom xgboost import XGBClassifier\nclassifier = XGBClassifier(n_estimators=600,\n \n max_depth=7,\n learning_rate=0.05,\n subsample=0.8,\n colsample_bytree=0.4,\n gamma=0.05 \n )\nclassifier.fit(X_train, y_train)\n\ny_pred = classifier.predict_proba(X_train)\nroc_auc_score(y_train, y_pred[:,1])\n\ny_pred = classifier.predict(X_test)\n\n# Making the Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_test, y_pred)\n\n(cm[0][0]+cm[1][1])/(cm[0][0]+cm[0][1]+cm[1][0]+cm[1][1])\n\n# Applying Grid Search to find the best model and the best parameters\nfrom sklearn.model_selection import GridSearchCV\nparameters = [{\n 'max_depth':[4,5,6,7,8],\n 'learning_rate':[0.03,0.001,0.005,0.007,0.05],\n 'n_estimators':[100,200,300,400,500,600,700,800] \n }]\ngrid_search = GridSearchCV(estimator = classifier,\n param_grid = parameters,\n scoring = 'accuracy',\n cv = 10,\n n_jobs = -1)\ngrid_search = grid_search.fit(X_train, y_train)\nbest_accuracy = grid_search.best_score_\nbest_parameters = grid_search.best_params_\n","sub_path":"Analyze this/xgboostanalyze.py","file_name":"xgboostanalyze.py","file_ext":"py","file_size_in_byte":4073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"619458741","text":"#!/usr/bin/env python\nimport rospy\nfrom std_msgs.msg import String\nimport http.client\n\n\n\ndef callback(data):\n print( data.data)\n\n if data.data == \"1\":\t\n\t conn = http.client.HTTPSConnection(\"box-6748659.us-east-1.bonsaisearch.net\")\n\n\t payload = \"{\\\"dispense\\\":\\\"\" + data.data + \"\\\"}\"\n\n\t headers = {\n\t\t'authorization': \"Basic NTh5NWNrNmU6djdvY3c3NWY3MjlxYXp3NQ==\",\n\t\t'cache-control': \"no-cache\",\n\t\t'postman-token': \"fe0ea64d-4096-c09b-579c-c8299a44caf9\"\n\t\t}\n\n\t conn.request(\"POST\", \"/try/try/dispense\", payload, headers)\n\n\t res = conn.getresponse()\n\t data = res.read()\n\n\t print(data.decode(\"utf-8\"))\n\n\ndef listener():\n\n # In ROS, nodes are uniquely named. If two nodes with the same\n # node are launched, the previous one is kicked off. The\n # anonymous=True flag means that rospy will choose a unique\n # name for our 'listener' node so that multiple listeners can\n # run simultaneously.\n rospy.init_node('listener', anonymous=True)\n\n rospy.Subscriber(\"dispense_pills_now\", String, callback)\n\n # spin() simply keeps python from exiting until this node is stopped\n rospy.spin()\n\nif __name__ == '__main__':\n listener()\n","sub_path":"src/push_to_web/src/sub_dispense.py","file_name":"sub_dispense.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"478199839","text":"from src.utils.all_utils import read_yaml, create_directory\nimport argparse\nimport logging\nimport os\nfrom tqdm import tqdm\nimport shutil\n\nlogging_str = \"[%(asctime)s: %(levelname)s: %(module)s: %(message)s]\"\nlog_dir = \"logs\"\nos.makedirs(log_dir, exist_ok=True)\nlogging.basicConfig(filename=os.path.join(log_dir,\"running_logs.log\"), level=logging.INFO, \n format=logging_str, filemode=\"a\")\n\nStage = \"One\"\n\ndef copy_data(source_dir, target_dir):\n list_of_files = os.listdir(source_dir)\n N = len(list_of_files)\n for file in tqdm(list_of_files, total=N, desc=f\"coppying file from {source_dir} to {target_dir}\", colour=\"green\"):\n src = os.path.join(source_dir, file)\n dest = os.path.join(target_dir, file)\n shutil.copy(src,dest)\n\n\ndef get_data(config_path):\n config = read_yaml(config_path)\n source_download_dirs = config[\"source_download_dirs\"]\n local_data_dirs = config[\"local_data_dirs\"]\n\n for source_download_dir, local_data_dir in tqdm(zip(source_download_dirs, local_data_dirs), total=2, desc= \"list of folders\", colour=\"red\"):\n create_directory([local_data_dir])\n copy_data(source_download_dir, local_data_dir)\n\nif __name__ == \"__main__\":\n args = argparse.ArgumentParser()\n args.add_argument(\"--config\", \"-c\", default=\"config/config.yaml\")\n parsed_args = args.parse_args()\n try:\n logging.info(\">>>>> Stage {Stage} started \")\n get_data(config_path=parsed_args.config)\n logging.info(\"Stage {Stage} completed! All the data is saved in local >>>>>\")\n except Exception as e:\n logging.exception(e)\n raise e","sub_path":"src/stage_01_load_save.py","file_name":"stage_01_load_save.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"526589465","text":"#Autor: Alondra Miranda Aguilera A01746742\n#Misión 5: Menú\n\nfrom PIL import Image, ImageDraw\nfrom random import randint\nimport turtle\n\ndef menu():\n print('''\n 1. Dibujar Cuadros y Círculos\n 2. Dibujar Estrella\n 3. Dibujar Espiral\n 4. Dibujar Red\n 5. Contar divisibles entre 17\n 6. Pirámides de Números\n 0. Salir\n ''')\n o = int(input(\"Hola Profe, eliga la opción que guste: \"))\n return o\n\n\n#-------------------------CUADROS CÍRCULOS-----------------------\ndef cuaCir(canvas):\n a=600\n for x in range (0,601,10):\n pa=(x,x)\n pb=(x+a,x+a)\n canvas.line(pa+(x+a,x)+pb+(x,x+a)+(x,x), \"white\")\n canvas.ellipse(pa+pb, \"black\", \"white\")\n a = a-20\n\n\n#---------------------------------ESTRELLA----------------------\ndef dibujarEstrella(imagen):\n for y in range (0, 301, 10):\n a = 300,y\n b = 300+y,300\n rojo = randint(0,255)\n verde = randint(0,255)\n azul = randint(0,255)\n imagen.line(a+b, (rojo, verde, azul))\n \n a = 300,y\n b = 300-y, 300\n rojo = randint(0,255)\n verde = randint(0,255)\n azul = randint(0,255)\n imagen.line(a+b, (rojo, verde, azul))\n \n a = 300,600-y\n b= 300+y,300\n rojo = randint(0,255)\n verde = randint(0,255)\n azul = randint(0,255)\n imagen.line(a+b, (rojo, verde, azul))\n \n a = 300,600-y\n b= 300-y,300\n rojo = randint(0,255)\n verde = randint(0,255)\n azul = randint(0,255)\n imagen.line(a+b, (rojo, verde, azul))\n\n\n#---------------------------------ESPIRAL----------------------\ndef dibujarEspiral():\n for x in range (5,500, 20):\n turtle.forward(x)\n turtle.left(90)\n turtle.forward(x+10)\n turtle.left(90)\n turtle.forward(x+10)\n turtle.left(90)\n turtle.forward(x+20)\n turtle.left(90)\n\n\n#------------------------------------RED------------------------\ndef dibujarRed(imagen):\n for y in range (0, 600, 20):\n a = 20+y, 0\n b = 0, 20+y\n imagen.line(a+b, \"blue\")\n \n for y in range (0, 600, 20):\n a = y-20, 600\n b = 600, y-20\n imagen.line(a+b, \"blue\")\n \n for y in range (0, 600, 20):\n a = 0+y, 0\n b = 600, 600-y\n imagen.line(a+b, \"red\")\n \n for y in range (0, 600, 20):\n a = 0+y, 600\n b = 0, 600-y\n imagen.line(a+b, \"red\")\n\n\n#---------------------------------DIVISIBLES-------------------------\ndef calcularDivisibles():\n cont= 0\n for x in range (1000,10000):\n if x %17 == 0:\n cont=cont+1\n return cont\n\n\n#--------------------------------------PIRÁMIDES--------------------\ndef piramideUno():\n b=0\n for x in range (1,10):\n b = b*10+x\n a=b*8+x\n print(b, \"* 8 +\", x,\"=\", a)\n \ndef piramideDos():\n c=0\n x=0\n for x in range (1,11):\n x=x+1\n if x<11:\n c= c*10+1\n d= c*c\n print (c ,\"*\", c, \"=\", d)\n\n\n\n#--------------------------------------------------------------------\ndef main():\n img = Image.new(\"RGB\", (600,600), \"black\")\n canvas=ImageDraw.Draw(img)\n \n o = menu()\n \n while o != 0:\n \n if o == 1: #Cuadros Círculos\n img = Image.new(\"RGB\", (600,600), \"black\")\n canvas=ImageDraw.Draw(img)\n cuaCir(canvas)\n img.show()\n \n elif o == 2: #Estrella\n imgEstrella = Image.new(\"RGB\", (600,600), \"black\")\n canvas = ImageDraw.Draw(imgEstrella)\n dibujarEstrella(canvas)\n imgEstrella.show()\n \n elif o == 3: #Espiral\n dibujarEspiral()\n \n elif o == 4: #Red\n imgRed = Image.new(\"RGB\", (600,600), \"black\")\n canvas = ImageDraw.Draw(imgRed)\n dibujarRed(canvas)\n imgRed.show()\n \n elif o == 5: #Divisibles\n divisibles = calcularDivisibles()\n print(divisibles)\n \n elif o == 6: #Pirámides\n piramideUno()\n piramideDos()\n \n else:\n print(\"Ese número no es válido, ponga otro\")\n \n o = menu()\n \n print(\"Si saqué 100 verdad profe? :D \")\n \nmain()","sub_path":"MisionCinco.py","file_name":"MisionCinco.py","file_ext":"py","file_size_in_byte":4402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"468093199","text":"\"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\n\" ACCESS-Pipeline SNV workflow operator\n\" http://www.github.com/mskcc/access-pipeline/workflows/snps_and_indels.cwl\n\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\n\nimport os\nimport json\nimport logging\n\nfrom django.conf import settings\nfrom jinja2 import Template\nfrom django.db.models import Q\n\nfrom file_system.models import File\nfrom runner.models import Port, RunStatus\nfrom file_system.models import FileMetadata\nfrom runner.operator.operator import Operator\nfrom runner.run.objects.run_creator_object import RunCreator\nfrom file_system.repository.file_repository import FileRepository\nfrom runner.operator.access import get_request_id_runs, get_unfiltered_matched_normal, get_request_id\n\n\nlogger = logging.getLogger(__name__)\n\nWORKDIR = os.path.dirname(os.path.abspath(__file__))\n\nACCESS_CURATED_BAMS_FILE_GROUP_SLUG = \"access_curated_normals\"\nACCESS_DEFAULT_NORMAL_ID = \"DONOR22-TP\"\nACCESS_DEFAULT_NORMAL_FILENAME = \"DONOR22-TP_cl_aln_srt_MD_IR_FX_BR__aln_srt_IR_FX-duplex.bam\"\nNORMAL_SAMPLE_SEARCH = \"-N0\"\nTUMOR_SAMPLE_SEARCH = \"-L0\"\nDUPLEX_BAM_SEARCH = \"__aln_srt_IR_FX-duplex.bam\"\nSIMPLEX_BAM_SEARCH = \"__aln_srt_IR_FX-simplex.bam\"\nUNFILTERED_BAM_SEARCH = \"__aln_srt_IR_FX.bam\"\nDMP_DUPLEX_REGEX = \"-duplex.bam\"\nDMP_SIMPLEX_REGEX = \"-simplex.bam\"\n\n\nclass AccessLegacySNVOperator(Operator):\n\n fillout_duplex_tumors = None\n fillout_simplex_tumors = None\n fillout_unfiltered_normals = None\n curated_normal_bams = None\n curated_normal_ids = None\n\n @staticmethod\n def is_tumor_bam(file):\n if not file.file_name.endswith(\".bam\"):\n return False\n t_n_timepoint = file.file_name.split(\"-\")[2]\n return not t_n_timepoint[0] == \"N\"\n\n def get_sample_inputs(self):\n \"\"\"\n Create all sample inputs for all runs triggered in this instance of the operator\n\n :return: list of json_objects\n \"\"\"\n run_ids = self.run_ids if self.run_ids else [r.id for r in get_request_id_runs(self.request_id)]\n\n # Get all duplex / simplex bam ports for these runs\n duplex_output_ports = Port.objects.filter(\n name__in=[\"duplex_bams\", \"fgbio_filter_consensus_reads_duplex_bam\"],\n run__id__in=run_ids,\n run__status=RunStatus.COMPLETED,\n )\n simplex_output_ports = Port.objects.filter(\n name__in=[\"simplex_bams\", \"fgbio_postprocessing_simplex_bam\"],\n run__id__in=run_ids,\n run__status=RunStatus.COMPLETED,\n )\n\n duplex_tumor_bams = [f for p in duplex_output_ports for f in p.files.all() if self.is_tumor_bam(f)]\n simplex_tumor_bams = [f for p in simplex_output_ports for f in p.files.all() if self.is_tumor_bam(f)]\n\n def make_pairs(d, s):\n paired = []\n for di in d:\n for si in s:\n if di.file_name.rstrip(\"-duplex.bam\") == si.file_name.rstrip(\"-simplex.bam\"):\n paired.append((di, si))\n return paired\n\n # Make sure simplex bams are paired with duplex of same sample ID\n tumor_bams = make_pairs(duplex_tumor_bams, simplex_tumor_bams)\n\n # Todo: how to know which sequencer's default normal to use?\n normal_bam = File.objects.filter(file_name=ACCESS_DEFAULT_NORMAL_FILENAME)[0]\n\n # Cache a set of fillout bams from this request for genotyping (we only need to do this query once)\n curated_normals_metadata = FileMetadata.objects.filter(\n file__file_group__slug=ACCESS_CURATED_BAMS_FILE_GROUP_SLUG\n )\n curated_normal_bams = [f for f in curated_normals_metadata]\n self.curated_normal_ids = [f.metadata[\"snv_pipeline_id\"] for f in curated_normals_metadata]\n self.curated_normal_bams = [self._create_cwl_bam_object(b.file) for b in curated_normal_bams]\n\n if self.request_id:\n # Todo: need to limit these to just Nucleo bams?\n self.fillout_unfiltered_normals = (\n File.objects.filter(\n file_name__contains=NORMAL_SAMPLE_SEARCH,\n file_name__endswith=UNFILTERED_BAM_SEARCH,\n port__run__tags__igoRequestId__startswith=self.request_id.split(\"_\")[0],\n )\n .distinct(\"file_name\")\n .order_by(\"file_name\", \"-created_date\")\n )\n\n self.fillout_duplex_tumors = (\n File.objects.filter(\n file_name__contains=TUMOR_SAMPLE_SEARCH,\n file_name__endswith=DUPLEX_BAM_SEARCH,\n port__run__tags__igoRequestId=self.request_id,\n )\n .distinct(\"file_name\")\n .order_by(\"file_name\", \"-created_date\")\n )\n\n self.fillout_simplex_tumors = (\n File.objects.filter(\n file_name__contains=TUMOR_SAMPLE_SEARCH,\n file_name__endswith=SIMPLEX_BAM_SEARCH,\n port__run__tags__igoRequestId=self.request_id,\n )\n .distinct(\"file_name\")\n .order_by(\"file_name\", \"-created_date\")\n )\n\n # Evaluate the queryset so that the cache is populated for later queries which use slicing / LIMIT\n # https://docs.djangoproject.com/en/3.1/topics/db/queries/#when-querysets-are-not-cached\n list(self.fillout_unfiltered_normals)\n list(self.fillout_duplex_tumors)\n list(self.fillout_simplex_tumors)\n\n # Gather input Files / Metadata\n sample_infos = []\n for d, s in tumor_bams:\n sample_info = self.create_sample_info(d, s)\n sample_info[\"normal_bam\"] = normal_bam\n sample_infos.append(sample_info)\n\n # Format input templates\n sample_inputs = []\n for sample_info in sample_infos:\n sample_input = self.construct_sample_inputs(**sample_info)\n sample_inputs.append(sample_input)\n\n return sample_inputs\n\n def create_sample_info(self, tumor_duplex_bam, tumor_simplex_bam):\n \"\"\"\n Query DB for all relevant files / metadata necessary for SNV pipeline input:\n\n - Tumor Duplex Bam\n - Tumor Simplex Bam\n - Matched Normal Unfiltered bam (from IGO / DMP or None) (external code)\n - Other Tumor Duplex bams from same patient or capture (for genotyping)\n - Other Tumor Simplex bams from same patient or capture (for genotyping)\n\n :return:\n \"\"\"\n tumor_sample_id = self.extract_sample_id(tumor_duplex_bam)\n patient_id = \"-\".join(tumor_sample_id.split(\"-\")[0:2])\n\n # Get the Matched, Unfiltered, Normal BAM\n matched_normal_unfiltered_bam, matched_normal_unfiltered_id = get_unfiltered_matched_normal(\n patient_id, self.request_id\n )\n\n # Get genotyping bams for Unfiltered Normal samples from the same Study\n geno_samples_normal_unfiltered, geno_samples_normal_unfiltered_sample_ids = self.get_normal_geno_samples(\n tumor_sample_id, matched_normal_unfiltered_id\n )\n\n # Get genotyping bams for Simplex and Duplex Tumor samples from the same Patient or in the same Capture\n geno_samples_duplex, geno_samples_simplex = self.get_geno_samples(\n tumor_sample_id, tumor_duplex_bam, tumor_simplex_bam, matched_normal_unfiltered_id\n )\n\n capture_samples_duplex_sample_ids = [self.extract_sample_id(s) for s in geno_samples_duplex]\n capture_samples_simplex_sample_ids = [self.extract_sample_id(s) for s in geno_samples_simplex]\n\n # Use sample IDs to remove duplicates from normal geno samples\n geno_samples_normal_unfiltered, geno_samples_normal_unfiltered_sample_ids = self._remove_normal_dups(\n geno_samples_normal_unfiltered, geno_samples_normal_unfiltered_sample_ids, capture_samples_duplex_sample_ids\n )\n\n # SNV pipeline requires that all samples have simplex and duplex bams\n if set(capture_samples_duplex_sample_ids) != set(capture_samples_simplex_sample_ids):\n msg = \"ACCESS SNV Operator Error: Duplex sample IDs not matched to Simplex sample IDs\"\n raise Exception(msg)\n\n # Add in any DMP ACCESS samples\n (\n dmp_matched_duplex_tumors,\n dmp_matched_simplex_tumors,\n dmp_matched_duplex_sample_ids,\n dmp_matched_simplex_sample_ids,\n ) = self.get_dmp_matched_patient_geno_samples(patient_id)\n\n geno_samples_duplex = geno_samples_duplex + dmp_matched_duplex_tumors\n geno_samples_simplex = geno_samples_simplex + dmp_matched_simplex_tumors\n geno_samples_duplex_sample_ids = capture_samples_duplex_sample_ids + dmp_matched_duplex_sample_ids\n geno_samples_simplex_sample_ids = capture_samples_simplex_sample_ids + dmp_matched_simplex_sample_ids\n\n sample_info = {\n \"tumor_sample_id\": tumor_sample_id,\n \"tumor_duplex_bam\": tumor_duplex_bam,\n \"tumor_simplex_bam\": tumor_simplex_bam,\n \"matched_normal_unfiltered\": matched_normal_unfiltered_bam,\n \"matched_normal_unfiltered_id\": matched_normal_unfiltered_id,\n \"geno_samples_duplex\": geno_samples_duplex,\n \"geno_samples_simplex\": geno_samples_simplex,\n \"geno_samples_normal_unfiltered\": geno_samples_normal_unfiltered,\n \"geno_samples_normal_unfiltered_sample_ids\": geno_samples_normal_unfiltered_sample_ids,\n \"geno_samples_duplex_sample_ids\": geno_samples_duplex_sample_ids,\n \"geno_samples_simplex_sample_ids\": geno_samples_simplex_sample_ids,\n }\n\n return sample_info\n\n @staticmethod\n def extract_sample_id(s):\n if \"_cl_aln_srt\" in s.file_name:\n ret = s.file_name.split(\"_cl_aln_srt\")[0]\n else:\n ret = s.filemetadata_set.first().metadata[settings.CMO_SAMPLE_NAME_METADATA_KEY]\n return ret\n\n def _remove_normal_dups(\n self,\n geno_samples_normal_unfiltered,\n geno_samples_normal_unfiltered_sample_ids,\n capture_samples_duplex_sample_ids,\n ):\n \"\"\"\n Make sure none of the normals are already present in duplex genotyping samples (GBCMS can not have\n duplicate sample IDs)\n\n :param geno_samples_normal_unfiltered:\n :param geno_samples_normal_unfiltered_sample_ids:\n :param capture_samples_duplex_sample_ids:\n :return:\n \"\"\"\n deduped = []\n deduped_ids = []\n for i, s in enumerate(geno_samples_normal_unfiltered_sample_ids):\n if not any([sid in s for sid in capture_samples_duplex_sample_ids]):\n deduped_ids.append(s)\n deduped.append(geno_samples_normal_unfiltered[i])\n return deduped, deduped_ids\n\n def get_normal_geno_samples(self, tumor_sample_id, matched_normal_unfiltered_id):\n \"\"\"\n 20 first Normal fillout samples\n\n :return:\n \"\"\"\n geno_samples_normal_unfiltered = self.fillout_unfiltered_normals[:20]\n logger.info(\n \"Adding {} fillout samples to SNV run for sample {}:\".format(\n len(geno_samples_normal_unfiltered), tumor_sample_id\n )\n )\n logger.info([s.file_name for s in geno_samples_normal_unfiltered])\n\n # Exclude matched normal bam\n if matched_normal_unfiltered_id:\n geno_samples_normal_unfiltered = [\n s for s in geno_samples_normal_unfiltered if not s.file_name.startswith(matched_normal_unfiltered_id)\n ]\n\n geno_samples_normal_unfiltered_sample_ids = [self.extract_sample_id(s) for s in geno_samples_normal_unfiltered]\n return geno_samples_normal_unfiltered, geno_samples_normal_unfiltered_sample_ids\n\n def get_geno_samples(self, tumor_sample_id, tumor_duplex_bam, tumor_simplex_bam, matched_normal_id):\n \"\"\"\n Use the initial fastq metadata to get the capture of the sample,\n then, based on this capture ID, find tumor and matched normal simplex and duplex bams for genotyping\n\n Also include any tumor samples from the same patient\n\n Limits to 40 samples (or 80 bams, because each has Simplex and Duplex)\n\n Todo: put metadata on the Bams themselves\n\n :param tumor_sample_id: str\n :return:\n \"\"\"\n # Get capture ID\n capture_id = None\n sample_ids = []\n sample_fastq = FileRepository.filter(\n file_type=\"fastq\", metadata={settings.CMO_SAMPLE_NAME_METADATA_KEY: tumor_sample_id}, filter_redact=True\n )\n if len(sample_fastq) >= 1:\n capture_id = sample_fastq[0].metadata[\"captureName\"]\n\n if capture_id:\n # Get samples IDs from this capture from fastqs with this capture ID\n sample_id_fastqs = FileRepository.filter(\n file_type=\"fastq\", metadata={\"captureName\": capture_id}, filter_redact=True\n )\n sample_ids = list(set([f.metadata[settings.CMO_SAMPLE_NAME_METADATA_KEY] for f in sample_id_fastqs]))\n # Don't double-genotype the main sample\n sample_ids.remove(tumor_sample_id)\n\n if len(sample_ids) == 0 or not capture_id:\n duplex_capture_samples = []\n simplex_capture_samples = []\n else:\n capture_q = Q(*[(\"file_name__startswith\", id) for id in sample_ids], _connector=Q.OR)\n\n duplex_capture_q = Q(file_name__endswith=DUPLEX_BAM_SEARCH) & capture_q\n simplex_capture_q = Q(file_name__endswith=SIMPLEX_BAM_SEARCH) & capture_q\n\n duplex_capture_samples = (\n File.objects.filter(duplex_capture_q)\n .distinct(\"file_name\")\n .order_by(\"file_name\", \"-created_date\")\n .exclude(file_name=tumor_duplex_bam.file_name)\n .exclude(file_name__startswith=matched_normal_id)\n )\n simplex_capture_samples = (\n File.objects.filter(simplex_capture_q)\n .distinct(\"file_name\")\n .order_by(\"file_name\", \"-created_date\")\n .exclude(file_name=tumor_simplex_bam.file_name)\n .exclude(file_name__startswith=matched_normal_id)\n )\n\n duplex_capture_samples = list(duplex_capture_samples)\n simplex_capture_samples = list(simplex_capture_samples)\n\n # Add patient matched Tumors samples\n patient_id = \"-\".join(tumor_sample_id.split(\"-\")[0:2])\n matched_tumor_search = patient_id + TUMOR_SAMPLE_SEARCH\n duplex_matched_q = Q(file_name__endswith=DUPLEX_BAM_SEARCH) & Q(file_name__startswith=matched_tumor_search)\n simplex_matched_q = Q(file_name__endswith=SIMPLEX_BAM_SEARCH) & Q(file_name__startswith=matched_tumor_search)\n\n duplex_matched_samples = (\n File.objects.filter(duplex_matched_q)\n .distinct(\"file_name\")\n .order_by(\"file_name\", \"-created_date\")\n .exclude(file_name=tumor_duplex_bam.file_name)\n .exclude(file_name__startswith=matched_normal_id)\n )\n simplex_matched_samples = (\n File.objects.filter(simplex_matched_q)\n .distinct(\"file_name\")\n .order_by(\"file_name\", \"-created_date\")\n .exclude(file_name=tumor_simplex_bam.file_name)\n .exclude(file_name__startswith=matched_normal_id)\n )\n\n duplex_geno_samples = list(duplex_matched_samples) + list(duplex_capture_samples)\n simplex_geno_samples = list(simplex_matched_samples) + list(simplex_capture_samples)\n\n if len(duplex_geno_samples) < 20:\n num_geno_samples_to_add = 20 - len(duplex_geno_samples)\n duplex_geno_samples_to_add = self.fillout_duplex_tumors[:num_geno_samples_to_add]\n simplex_geno_samples_to_add = self.fillout_simplex_tumors[:num_geno_samples_to_add]\n # Remove the main tumor sample\n duplex_geno_samples_to_add = [\n s for s in duplex_geno_samples_to_add if s.file_name != tumor_duplex_bam.file_name\n ]\n simplex_geno_samples_to_add = [\n s for s in simplex_geno_samples_to_add if s.file_name != tumor_simplex_bam.file_name\n ]\n duplex_geno_samples += duplex_geno_samples_to_add\n simplex_geno_samples += simplex_geno_samples_to_add\n\n # Deduplicate based on PK\n duplex_geno_samples = list(set(duplex_geno_samples))\n simplex_geno_samples = list(set(simplex_geno_samples))\n # Deduplicate based on file name\n duplex_geno_samples, simplex_geno_samples = self._remove_dups_by_file_name(\n duplex_geno_samples, simplex_geno_samples\n )\n\n return duplex_geno_samples, simplex_geno_samples\n\n def _remove_dups_by_file_name(self, duplex_geno_samples, simplex_geno_samples):\n \"\"\"\n Simple util to avoid Genotyping same sample twice\n (when bams come from different runs and can't be\n de-duplicated based on PK)\n\n :return:\n \"\"\"\n duplex_geno_samples_dedup_ids = set()\n duplex_geno_samples_dedup = []\n for s in duplex_geno_samples:\n if not s.file_name in duplex_geno_samples_dedup_ids:\n duplex_geno_samples_dedup_ids.add(s.file_name)\n duplex_geno_samples_dedup.append(s)\n simplex_geno_samples_dedup_ids = set()\n simplex_geno_samples_dedup = []\n for s in simplex_geno_samples:\n if not s.file_name in simplex_geno_samples_dedup_ids:\n simplex_geno_samples_dedup_ids.add(s.file_name)\n simplex_geno_samples_dedup.append(s)\n return duplex_geno_samples_dedup, simplex_geno_samples_dedup\n\n def get_dmp_matched_patient_geno_samples(self, patient_id):\n \"\"\"\n Find DMP ACCESS samples for genotyping\n\n :param patient_id: str - CMO sample ID (C-123ABC)\n :return: (QuerySet<File> - Duplex Bams, QuerySet<File> - Simplex Bams, str[] duplex samples IDs,\n str[] simplex sample IDs)\n \"\"\"\n matched_duplex_tumors_dmp = FileMetadata.objects.filter(\n metadata__cmo_assay=\"ACCESS_V1_0\",\n metadata__patient__cmo=patient_id.replace(\"C-\", \"\"),\n metadata__type=\"T\",\n file__path__endswith=DMP_DUPLEX_REGEX,\n )\n matched_duplex_tumors_dmp = [b.file for b in matched_duplex_tumors_dmp]\n matched_duplex_sample_ids_dmp = [b.file_name.replace(\"-duplex.bam\", \"\") for b in matched_duplex_tumors_dmp]\n\n matched_simplex_tumors_dmp = FileMetadata.objects.filter(\n metadata__cmo_assay=\"ACCESS_V1_0\",\n metadata__patient__cmo=patient_id.replace(\"C-\", \"\"),\n metadata__type=\"T\",\n file__path__endswith=DMP_SIMPLEX_REGEX,\n )\n matched_simplex_tumors_dmp = [b.file for b in matched_simplex_tumors_dmp]\n matched_simplex_sample_ids_dmp = [b.file_name.replace(\"-simplex.bam\", \"\") for b in matched_simplex_tumors_dmp]\n\n return (\n matched_duplex_tumors_dmp,\n matched_simplex_tumors_dmp,\n matched_duplex_sample_ids_dmp,\n matched_simplex_sample_ids_dmp,\n )\n\n def get_jobs(self):\n \"\"\"\n Convert job inputs into serialized jobs\n\n :return: list[(serialized job info, Job)]\n \"\"\"\n self.request_id = get_request_id(self.run_ids, self.request_id)\n sample_inputs = self.get_sample_inputs()\n\n return [\n RunCreator(\n **{\n \"name\": \"ACCESS LEGACY SNV M1: %s, %i of %i\" % (self.request_id, i + 1, len(sample_inputs)),\n \"app\": self.get_pipeline_id(),\n \"inputs\": job,\n \"tags\": {\n settings.REQUEST_ID_METADATA_KEY: self.request_id,\n \"cmoSampleIds\": job[\"tumor_sample_names\"],\n settings.PATIENT_ID_METADATA_KEY: \"-\".join(job[\"tumor_sample_names\"][0].split(\"-\")[0:2]),\n },\n }\n )\n for i, job in enumerate(sample_inputs)\n ]\n\n def construct_sample_inputs(\n self,\n normal_bam,\n tumor_sample_id,\n tumor_duplex_bam,\n tumor_simplex_bam,\n matched_normal_unfiltered,\n matched_normal_unfiltered_id,\n geno_samples_duplex,\n geno_samples_simplex,\n geno_samples_duplex_sample_ids,\n geno_samples_simplex_sample_ids,\n geno_samples_normal_unfiltered,\n geno_samples_normal_unfiltered_sample_ids,\n ):\n \"\"\"\n Use sample metadata and json template to create inputs for the CWL run\n\n :return: JSON format sample inputs\n \"\"\"\n with open(os.path.join(WORKDIR, \"input_template.json.jinja2\")) as file:\n template = Template(file.read())\n\n tumor_sample_names = [tumor_sample_id]\n tumor_bams = [self._create_cwl_bam_object(tumor_duplex_bam)]\n\n matched_normal_ids = [matched_normal_unfiltered_id]\n normal_bams = [self._create_cwl_bam_object(normal_bam)]\n normal_sample_names = [ACCESS_DEFAULT_NORMAL_ID]\n\n genotyping_bams = [\n self._create_cwl_bam_object(tumor_duplex_bam),\n self._create_cwl_bam_object(tumor_simplex_bam),\n ]\n genotyping_bams_ids = [tumor_sample_id, tumor_sample_id + \"-SIMPLEX\"]\n\n # Matched Normal may or may not be available for genotyping\n if matched_normal_unfiltered:\n genotyping_bams += [self._create_cwl_bam_object(matched_normal_unfiltered)]\n genotyping_bams_ids += [matched_normal_unfiltered_id]\n\n # Additional matched Tumors may be available\n if len(geno_samples_duplex) > 0:\n genotyping_bams += [self._create_cwl_bam_object(b) for b in geno_samples_duplex]\n genotyping_bams += [self._create_cwl_bam_object(b) for b in geno_samples_simplex]\n genotyping_bams_ids += geno_samples_duplex_sample_ids\n genotyping_bams_ids += [i + \"-SIMPLEX\" for i in geno_samples_simplex_sample_ids]\n\n # Additional unfiltered normals may be available\n if len(geno_samples_normal_unfiltered) > 0:\n genotyping_bams += [self._create_cwl_bam_object(b) for b in geno_samples_normal_unfiltered]\n genotyping_bams_ids += geno_samples_normal_unfiltered_sample_ids\n\n genotyping_bams += self.curated_normal_bams\n genotyping_bams_ids += self.curated_normal_ids\n\n input_file = template.render(\n tumor_bams=json.dumps(tumor_bams),\n normal_bams=json.dumps(normal_bams),\n tumor_sample_names=json.dumps(tumor_sample_names),\n normal_sample_names=json.dumps(normal_sample_names),\n matched_normal_ids=json.dumps(matched_normal_ids),\n genotyping_bams=json.dumps(genotyping_bams),\n genotyping_bams_ids=json.dumps(genotyping_bams_ids),\n )\n\n sample_input = json.loads(input_file)\n return sample_input\n\n @staticmethod\n def _create_cwl_bam_object(bam):\n \"\"\"\n Util function to create a simple CWL File object from a bam with a path attribute\n\n :param bam:\n :return:\n \"\"\"\n return {\"class\": \"File\", \"location\": \"juno://\" + bam.path}\n","sub_path":"runner/operator/access/v1_0_0/snps_and_indels/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":23477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"1930856","text":"\"\"\"\nFull model: with weight sharing + fully-connected small\n\n\"\"\"\n\nimport torch as t\n###############################################################################\n # - IMPORT - #\n###############################################################################\nfrom torch.autograd import Variable\nfrom torch import nn\nfrom torch.nn import functional as F\nimport dlc_practical_prologue as prologue\n\nimport numpy as np\nimport time\n\n###############################################################################\n # - CONSTANTS - #\n###############################################################################\n \nt.manual_seed(0)\n \nNB_PAIRS = 1000\nNB_EPOCHS = 25\nMINI_BATCH_SIZE = 100 # seems to be quite optimal (see lesson 5.2)\nNB_RUN = 10\n\n\ntrain_input,train_target,train_classes,test_input,test_target,test_classes \\\n= prologue.generate_pair_sets(NB_PAIRS)\n\nprint(train_input.size())\nprint(train_input[:,1].size())\nblablabla = train_input[:,1].view(NB_PAIRS,1,14,14)\nprint(blablabla.size())\n\ntrain_input = Variable(train_input.float(),requires_grad=True)\ntest_input = Variable(test_input.float(),requires_grad=True)\n\n\n\n###############################################################################\n # - NETWORKS - #\n###############################################################################\n\nclass Classification(nn.Module):\n def __init__(self):\n super(Classification, self).__init__()\n #1x14x14\n self.conv1 = nn.Conv2d(1, 32, kernel_size=5)\n self.conv2 = nn.Conv2d(32, 64, kernel_size=5)\n self.fc1 = nn.Linear(64, 128)\n self.fc3 = nn.Linear(128,256)\n self.fc2 = nn.Linear(256,10)\n self.b1 = nn.BatchNorm1d(128)\n self.m = nn.Softmax()\n\n def forward(self, x):\n x = F.relu(F.max_pool2d(self.conv1(x), kernel_size=2, stride=2))\n x = F.relu(F.max_pool2d(self.conv2(x), kernel_size=2, stride=2))\n x = F.relu(self.fc1(x.view(-1, 64)))\n x = self.b1(x)\n x = F.relu(self.fc3(x))\n #batchnorm here does not change much\n #dropout neither\n x = self.fc2(x)\n x = self.m(x)\n return x\n#\nclass Comparison_fc_large(nn.Module):\n def __init__(self):\n super(Comparison, self).__init__()\n self.fc1 = nn.Linear(20, 40)\n self.fc2 = nn.Linear(40, 80)\n self.fc3 = nn.Linear(80, 160)\n self.fc4 = nn.Linear(160, 80)\n self.fc5 = nn.Linear(80, 2)\n self.m = nn.Softplus()\n \n def forward(self, x):\n x = F.relu(x.view(-1,20))\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = F.relu(self.fc3(x))\n x = F.relu(self.fc4(x))\n x = self.m(self.fc5(x))\n return x\n \nclass Comparison_fc_small(nn.Module):\n def __init__(self): \n super(Comparison,self).__init__()\n self.fc1 = nn.Linear(20,40)\n self.fc2 = nn.Linear(40,80)\n self.fc3 = nn.Linear(80,2)\n self.m = nn.Softplus()\n \n def forward(self,x):\n x = F.relu(x.view(-1,20))\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.m(self.fc3(x))\n return x\n\n###############################################################################\n # - ERROR COMPUTATION - #\n###############################################################################\n \ndef compute_error_classification (input, class_target):\n # input of size Nx2x10\n # target of size Nx2\n # max error N*2 = 2N\n error = 0\n \n for k in range(input.size(0)):\n for i in range(2):\n _,n = t.max(input[k,i],0)\n if n != class_target[k,i]:\n error = error + 1\n return error\n\ndef compute_error_comparison (input,target):\n # input of size Nx2\n # target of size N\n \n error = 0\n for k in range(input.size(0)):\n _,n = t.max(input[k],0)\n if n != target[k]:\n error = error + 1\n return error\n\n###############################################################################\n # - TRAINING & TESTING- #\n###############################################################################\n \ndef training_ws(model_classification,model_comparison):\n lr_ = 1e-3\n criterion = nn.CrossEntropyLoss()\n optimizer_cl = t.optim.Adam(model_classification.parameters(),lr=lr_)\n optimizer_co = t.optim.Adam(model_comparison.parameters(),lr=lr_)\n input = train_input\n target_cl = train_classes\n target_co = train_target\n \n for e in range(NB_EPOCHS):\n sum_loss_classification = 0\n sum_loss_comparison = 0\n model_comparison.zero_grad()\n model_classification.zero_grad()\n for b in range(0,input.size(0),MINI_BATCH_SIZE):\n sum_loss = 0\n input_co = t.empty(MINI_BATCH_SIZE,2,10)\n #model_comparison.zero_grad()\n #model_classification.zero_grad()\n for i in range(2):\n # using 100 samples to train our model (fast and accurate and enough i guess )\n output_cl = model_classification(input[b:b+MINI_BATCH_SIZE,i].view(100,1,14,14)) \n loss_cl = criterion (output_cl,target_cl[b:b+MINI_BATCH_SIZE,i].long())\n input_co[:,i,:] = output_cl\n sum_loss = sum_loss + loss_cl\n \n \n # Update parameters after backward pass\n sum_loss_classification = sum_loss_classification + sum_loss.item()\n output_co = model_comparison(input_co)\n loss_co = criterion(output_co,target_co[b:b+MINI_BATCH_SIZE].long())\n sum_loss = sum_loss * 0.8 + loss_co * 0.2\n #model_comparison.zero_grad()\n #model_classification.zero_grad()\n sum_loss_comparison = sum_loss_comparison + loss_co.item()\n sum_loss.backward()\n optimizer_co.step()\n optimizer_cl.step()\n print(\"Epoch no {} : \\nClassification loss = {:0.4f}\\nComparison loss = {:0.4f}\".format(e+1,sum_loss_classification,sum_loss_comparison))\n\ndef test_models(model_cl, model_co, input, classes, target, train=True):\n output_cl = t.empty(NB_PAIRS,2,10)\n for i in range(2):\n output_cl[:,i,:] = model_cl(input[:,i].view(NB_PAIRS,1,14,14)) \n \n output_co = model_co(output_cl) #1000x2\n\n if (train):\n s = \"training\"\n else:\n s = \"testing\"\n err1 = compute_error_classification(output_cl,classes)/2/NB_PAIRS\n err2 = compute_error_comparison(output_co, target)/NB_PAIRS\n print('\\x1b[3;37;41m'+\"Error in {}: \\nClassification = {:0.3f}% \\nComparison = {:0.3f}%\".format(\n s,err1*100\n ,err2*100)+'\\x1b[0m')\n return err1, err2\n###############################################################################\n # - MAIN - #\n###############################################################################\ntrain_class = t.empty(NB_RUN)\ntrain_comp = t.empty(NB_RUN)\ntest_class = t.empty(NB_RUN)\ntest_comp = t.empty(NB_RUN)\n\ntraining_time = []\n\nfor i in range(NB_RUN):\n model_cl = Classification()\n model_co= Comparison()\n print(\"RUN NO {}\".format(i+1))\n \n #Compute training time\n start_time = time.perf_counter()\n training(model_cl,model_co)\n stop_time = time.perf_counter()\n \n training_time.append(stop_time - start_time)\n\n e1, e2 = test_models(model_cl, model_co, train_input, train_classes, train_target)\n e3, e4 = test_models(model_cl, model_co, test_input, test_classes, test_target, False)\n train_class[i] = (e1)\n train_comp[i] = (e2)\n test_class[i] = (e3)\n test_comp[i] = (e4)\n\n\nprint(\"Final error for train batch : {:0.2f}\\u00B1{:0.4f}%\".format(t.mean(train_comp)*100,t.std(train_comp)*100))\nprint(\"Final error for test batch : {:0.2f}\\u00B1{:0.4f}%\".format(t.mean(test_comp)*100,t.std(test_comp)*100))\n\nprint('Average training time: {:f}s'.format(np.mean(training_time)))\n","sub_path":"Project1/final_models/model_ws_fc_large.py","file_name":"model_ws_fc_large.py","file_ext":"py","file_size_in_byte":8062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"254515217","text":"from hivemind_chatroom import get_connection\nfrom hivemind_chatroom import MessageHandler\nfrom flask import Flask, render_template, request, redirect, url_for, \\\n jsonify, Response\n\napp = Flask(__name__)\n\nhivemind = None\n\n\n@app.route('/', methods=['GET'])\ndef general():\n room = \"general\"\n return redirect(url_for(\"chatroom\", room=room))\n\n\n@app.route('/<room>', methods=['GET'])\ndef chatroom(room):\n return render_template('room.html', room=room)\n\n\n@app.route('/messages/<room>', methods=['GET'])\ndef messages(room):\n return jsonify(MessageHandler.get_messages(room))\n\n\n@app.route('/send_message/<room>', methods=['POST'])\ndef send_message(room):\n hivemind.say(request.form['message'], request.form['username'], room)\n return redirect(url_for(\"chatroom\", room=room))\n\n\ndef main():\n global hivemind\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--access_key\", help=\"access key\",\n default=\"RESISTENCEisFUTILE\")\n parser.add_argument(\"--crypto_key\", help=\"payload encryption key\",\n default=\"resistanceISfutile\")\n parser.add_argument(\"--name\", help=\"human readable device name\",\n default=\"JarbasChatRoomTerminal\")\n parser.add_argument(\"--host\", help=\"HiveMind host\",\n default=\"wss://127.0.0.1\")\n parser.add_argument(\"--port\", help=\"HiveMind port number\", default=5678)\n parser.add_argument(\"--flask-port\", help=\"Chatroom port number\",\n default=8081)\n parser.add_argument(\"--flask-host\", help=\"Chatroom host\",\n default=\"0.0.0.0\")\n args = parser.parse_args()\n hivemind = get_connection(args.host, args.port, args.name,\n args.access_key, args.crypto_key)\n hivemind.run_threaded()\n app.run(args.flask_host, args.flask_port)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"hivemind_chatroom/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"592675553","text":"import re\n# 1将给定字符串的PHP替换为Python\n# best_language = \"PHP is the best programming language in the world! \"\n\na = \"PHP is the best programming language in the world!\"\nprint(a.replace(\"PHP\",\"Python\"))\n\n# 运行结果\n# Python is the best programming language in the world!\n\n# 2\n# 编写代码,提示用户输入1 - 7\n# 七个数字,分别代表周一到周日,打印输出“今天是周几”\nweek = input(\"请输入数字1-7:\")\nprint(\"今天是周{}\".format(week))\n\n# 运行结果\n# 请输入数字1-7:1\n# 今天是周1\n#\n# Process finished with exit code 0\n\n\n\n# 3\n# 给定一个字符串: Python is the\n# BEST\n# Programming\n# Language!\n# 编写一个正则表达式用来判断该字符串是否全部为小写。\n\n\na = \"Python is the BEST Programming Language!\"\nb = r'^[a-z\\s]*$'\nif re.match(b, a):\n print('全为小写字母')\nelse:\n print(\"不全为小写字母\")\n# 运行结果\n# 不全为小写字母\n#\n# Process finished with exit code 0\n\n\n\n# 4\n# 读取一个字符串,要求使用正则表达式来读取其中的电话号码,电话号码的格式假定为:\n# (xxx) xxx - xxxx或xxx - xxx - xxxx。\n# str=input(\"请输入一个(含电话号码)字符串:\")\n# # [ ]?表示区号可以跟“ ”,?表示也可能什么都没1有\na = \"我的学号是1720390电话是187-8887-6669\"\nnum = re.findall(r'(\\d{3}-\\d{4}-\\d{4})', a)\nfor i in range(len(num)):\n print(num[i], end=\" \")\n # 运行结果\n# 187-8887-6669\n\n\n\n# 5\n# 利用正则表达式从下列不同的字符串中获取指定格式的日期。日期的格式为yyyy - mm - dd。\n#\n# '今天是2022/9/24', '今天是2017/09/25', '今天是2012-07-25', '今天是2020年04月25',\na = '今天是2022/9/24,今天是2017/09/25,今天是2012-07-25,今天是2020年04月25'\nday = re.findall(r'\\d{4}-\\d{2}-\\d{2}', a)\nfor i in range(len(day)):\n print(\"今天是\", day[i], end=\"\")\n# 运行结果\n# 今天是 2012-07-25\n# Process finished with exit code 0\n\n# 全部运行结果\n# E:\\untitled\\Scripts\\python.exe E:/PythonWork/untitled/1.py\n# Python is the best programming language in the world!\n# 请输入数字1-7:1\n# 今天是周1\n# 不全为小写字母\n# 187-8887-6669 今天是 2012-07-25\n# Process finished with exit code 0","sub_path":"homework6/Group8/hw6_1720390.py","file_name":"hw6_1720390.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"571846645","text":"\nfrom oop2 import Kutya, Macska\n\n\ndef read_file(filename):\n data = []\n with open(filename, \"r\") as ofile:\n for sor in ofile:\n a=sor.split(\",\")\n if (a[0] == \"kutya\"):\n ujkuyta=Kutya()\n data.append(ujkuyta)\n elif (a[0] == \"macska\"):\n ujmacska=Macska()\n data.append(ujmacska)\n ofile.close()\n return data\n\n\nx=read_file(\"randomfile.csv\")\nprint(*x,sep=\"\\n\")\n","sub_path":"python/11_19/gyakorlás.py","file_name":"gyakorlás.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"521509650","text":"# -*- coding: utf-8 -*-\n\"\"\"\nthis is a script that builds a daily weather dataframe with the darksky api and saves it as 'weather.csv' \n\"\"\"\n\n#packages\nimport requests # to make calls\nimport pandas as pd #to make dataframe once calls are done\nfrom datetime import timedelta, date # to formate dates for calls\nimport time as ti #for introducing delay in script\n#base api url\nurl = 'https://api.darksky.net/forecast/'\n#key \napi = '0afa37ac1d3b32df4539e21c51e9eae8'\n\n#location of chicago \nlat = '41.8781'\nlong = '-87.6298'\n\nstart_date = date(2011,1,1) #inclusive\nend_date = date(2012,1,1) #exclusive\ntime='T12:00:00' #required for call set to midday\n#length\ndays = [start_date + timedelta(n) for n in range((end_date-start_date).days)]\ndata = []\n\nfor day in days:\n call = f'{url}{api}/{lat},{long},{day.isoformat()}{time}?exclude=hourly,minutely,currently'\n re = requests.get(call)\n record = re.json()['daily']['data']\n record[0]['date'] = day\n data.append(record[0])\n ti.sleep(.25)\n\ndf = pd.DataFrame(data)\ndf.to_csv(f'weather.csv{start_date.year}-{end_date.year}', index = False )","sub_path":"weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"387781224","text":"import pymongo\nimport json\nimport config\n\nimport os,sys\nglobal mongo_cli\nmongo_cli = pymongo.MongoClient('mongodb://%s:%s@47.94.128.239:27613' % (config.dbuser,config.dbpwd))\n\ndef main():\n\tglobal mongo_cli\n\tfor filename in os.listdir('../result'):\n\t\tfile = open('../result/'+filename,'r')\n\t\tdata = None\n\t\tfor line in file:\n\t\t\tdata = json.loads(line)\n\t\t\tbreak\n\t\tfile.close()\n\t\tif len(filename) == 6:\n\t\t\tmongo_cli['fund-similar'][filename].update({'_id':data['_id']},{'$set':data},upsert=True)\n\t\telse:\n\t\t\tmongo_cli['fund-info']['similar-top'].update({'_id':data['_id']},{'$set':data},upsert=True)\n\nif __name__ == '__main__':\n\tmain()","sub_path":"src/result2db.py","file_name":"result2db.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"15850668","text":"\nimport BreezyBarb.Stocks.folder as crsf\nimport BreezyBarb.Utilities.filters as crtf\nimport BreezyBarb.Utilities.pkgstdy as crup\nimport BreezyBarb.Utilities.shrink as crts\n\nfrom multiprocessing import Pool\nimport numpy as np\n\nd_comb = crsf.cr_comb\nd_cor_st = crsf.cr_cor_st\nd_cor_dy = crsf.cr_cor_dy\nd_res = crsf.cr_res\nd_bt_pp = crsf.cr_bt_pp\nd_bt_bs = crsf.cr_bt_bs\nd_bt_ft = crsf.cr_bt_ft\n\n# _dt_st = '20031224'\n_dt_st = '20040616'\n\n\ndef _reduce_data(x):\n # x = fvol.copy()\n xdt = crup.pd_dt_to_str(x['Date', list])\n xidx = [i for i, j in enumerate(xdt) if j >= _dt_st]\n x = x[xidx, :]\n return x\n\n\nclus = 7\n_d_bt_bs = d_bt_bs[clus]\n_d_bt_ft = d_bt_ft[clus]\n_d_comb = d_comb[clus]\n_d_cor_st = d_cor_st[clus]\n_d_cor_dy = d_cor_dy[clus]\n\n\ndef _refresh_base_data(x):\n _d_bt_bs, _d_bt_ft, _d_comb, _d_cor_st, _d_cor_dy = x\n\n # read the characteristics\n fvol = _reduce_data(_d_comb.retrieve('Vol_CC_240D'))\n fadv = _reduce_data(_d_comb.retrieve('Adv'))\n fun = _reduce_data(_d_comb.retrieve('Univ'))\n frt = _reduce_data(_d_comb.retrieve('Returns'))\n\n # read the betas\n fpc0_dy = _reduce_data(_d_comb.retrieve('PCA0_Dy'))\n fpc0_st = _reduce_data(_d_comb.retrieve('PCA0_St'))\n fpc1_dy = _reduce_data(_d_comb.retrieve('PCA1_Dy'))\n fpc1_st = _reduce_data(_d_comb.retrieve('PCA1_St'))\n fpc2_dy = _reduce_data(_d_comb.retrieve('PCA2_Dy'))\n fpc2_st = _reduce_data(_d_comb.retrieve('PCA2_St'))\n fpc3_dy = _reduce_data(_d_comb.retrieve('PCA3_Dy'))\n fpc3_st = _reduce_data(_d_comb.retrieve('PCA3_St'))\n fpc4_dy = _reduce_data(_d_comb.retrieve('PCA4_Dy'))\n fpc4_st = _reduce_data(_d_comb.retrieve('PCA4_St'))\n fpc5_dy = _reduce_data(_d_comb.retrieve('PCA5_Dy'))\n fpc5_st = _reduce_data(_d_comb.retrieve('PCA5_St'))\n\n fsp03 = _reduce_data(_d_comb.retrieve('SPY_Beta_3m'))\n fsp06 = _reduce_data(_d_comb.retrieve('SPY_Beta_6m'))\n fsp09 = _reduce_data(_d_comb.retrieve('SPY_Beta_9m'))\n fsp12 = _reduce_data(_d_comb.retrieve('SPY_Beta_12m'))\n\n fmd03 = _reduce_data(_d_comb.retrieve('MDY_Beta_3m'))\n fmd06 = _reduce_data(_d_comb.retrieve('MDY_Beta_6m'))\n fmd09 = _reduce_data(_d_comb.retrieve('MDY_Beta_9m'))\n fmd12 = _reduce_data(_d_comb.retrieve('MDY_Beta_12m'))\n\n fmom03 = _reduce_data(_d_comb.retrieve('MOM_Beta_3m'))\n fmom06 = _reduce_data(_d_comb.retrieve('MOM_Beta_6m'))\n fmom09 = _reduce_data(_d_comb.retrieve('MOM_Beta_9m'))\n fmom12 = _reduce_data(_d_comb.retrieve('MOM_Beta_12m'))\n\n flvl03 = _reduce_data(_d_comb.retrieve('LVOL_Beta_3m'))\n flvl06 = _reduce_data(_d_comb.retrieve('LVOL_Beta_6m'))\n flvl09 = _reduce_data(_d_comb.retrieve('LVOL_Beta_9m'))\n flvl12 = _reduce_data(_d_comb.retrieve('LVOL_Beta_12m'))\n\n fsig = _reduce_data(_d_comb.retrieve('CompSig1'))\n\n n = fvol.shape[0]\n tc = fvol.tick_cols()\n\n for i in range(0, n):\n # i = 0\n _dt = crup.pd_dt_to_str([fvol[i, 'Date', list]])[0]\n funi = [k for k, j in enumerate(fun[i, tc].values.astype('bool')) if j]\n tci = [j for k, j in enumerate(tc) if k in funi]\n\n xi = np.vstack((fvol[i, tci].values.astype('float32'), # 0\n fadv[i, tci].values.astype('float32'), # 1\n fpc0_dy[i, tci].values.astype('float32'), # 2\n fpc0_st[i, tci].values.astype('float32'), # 3\n fpc1_dy[i, tci].values.astype('float32'), # 4\n fpc1_st[i, tci].values.astype('float32'), # 5\n fpc2_dy[i, tci].values.astype('float32'), # 6\n fpc2_st[i, tci].values.astype('float32'), # 7\n fpc3_dy[i, tci].values.astype('float32'), # 8\n fpc3_st[i, tci].values.astype('float32'), # 9\n fpc4_dy[i, tci].values.astype('float32'), # 10\n fpc4_st[i, tci].values.astype('float32'), # 11\n fpc5_dy[i, tci].values.astype('float32'), # 12\n fpc5_st[i, tci].values.astype('float32'), # 13\n fsp03[i, tci].values.astype('float32'), # 14\n fsp06[i, tci].values.astype('float32'), # 15\n fsp09[i, tci].values.astype('float32'), # 16\n fsp12[i, tci].values.astype('float32'), # 17\n fmd03[i, tci].values.astype('float32'), # 18\n fmd06[i, tci].values.astype('float32'), # 19\n fmd09[i, tci].values.astype('float32'), # 20\n fmd12[i, tci].values.astype('float32'), # 21\n fmom03[i, tci].values.astype('float32'), # 22\n fmom06[i, tci].values.astype('float32'), # 23\n fmom09[i, tci].values.astype('float32'), # 24\n fmom12[i, tci].values.astype('float32'), # 25\n flvl03[i, tci].values.astype('float32'), # 26\n flvl06[i, tci].values.astype('float32'), # 27\n flvl09[i, tci].values.astype('float32'), # 28\n flvl12[i, tci].values.astype('float32'), # 29\n fsig[i, tci].values.astype('float32')\n ))\n\n if i < n-2:\n yi = frt[i+2, tci].values.astype('float64')\n\n ci1 = _d_cor_st.load(_dt)\n ci1 = ci1[:, funi]\n ci1 = ci1[funi, :]\n\n ci2 = _d_cor_dy.load(_dt)\n ci2 = ci2[:, funi]\n ci2 = ci2[funi, :]\n\n # remove stocks with missing data\n v_idx = np.sum(~np.isnan(xi), axis=0)/xi.shape[0]\n v_idx = [k for k, j in enumerate(v_idx) if j > 0.999999]\n xi = xi[:, v_idx]\n ci1 = ci1[:, v_idx]\n ci1 = ci1[v_idx, :]\n ci2 = ci2[:, v_idx]\n ci2 = ci2[v_idx, :]\n tci = [j for i, j in enumerate(tci) if i in v_idx]\n if i < n-2:\n yi = yi[v_idx]\n\n # remove stocks with no correlation values\n n_ = ci1.shape[0]\n c_idx = []\n for j in range(0, n_):\n cor1_r = np.all(np.isnan(np.array([l for k, l in enumerate(ci1[j, :]) if k != j])))\n cor1_c = np.all(np.isnan(np.array([l for k, l in enumerate(ci1[:, j]) if k != j])))\n cor2_r = np.all(np.isnan(np.array([l for k, l in enumerate(ci2[j, :]) if k != j])))\n cor2_c = np.all(np.isnan(np.array([l for k, l in enumerate(ci2[:, j]) if k != j])))\n if ~cor1_r or ~cor1_c or ~cor2_c or ~cor2_r:\n c_idx.append(j)\n\n if len(c_idx) != n_:\n xi = xi[:, c_idx]\n ci1 = ci1[:, c_idx]\n ci1 = ci1[c_idx, :]\n ci2 = ci2[:, c_idx]\n ci2 = ci2[c_idx, :]\n tci = [j for i, j in enumerate(tci) if i in c_idx]\n if i < n-2:\n yi = yi[c_idx]\n # n_ = len(c_idx)\n\n ei = np.ones(n_, dtype='float64')\n bi1 = 1/np.dot(np.abs(ci1), ei)\n bi1 /= np.sum(bi1)\n\n bi2 = 1/np.dot(np.abs(ci2), ei)\n bi2 /= np.sum(bi2)\n\n sci1 = np.linalg.inv(crts.shrink_correl_fast(bi1)).astype('float32')\n sci2 = np.linalg.inv(crts.shrink_correl_fast(bi2)).astype('float32')\n\n xi = np.vstack((xi, bi1.astype('float32'), bi2.astype('float32')))\n _d_bt_bs.save(_dt, xi, ci1, ci2, sci1, sci2, np.array(tci))\n if i < n-2:\n _d_bt_ft.save(_dt, yi)\n return None\n\n\ndef refresh_base_data():\n with Pool(processes=4) as p:\n p.map(_refresh_base_data, zip(d_bt_bs, d_bt_ft, d_comb, d_cor_st, d_cor_dy))\n return None\n\nif __name__ == '__main__':\n refresh_base_data()\n","sub_path":"BreezyBarb/Stocks/Backtest/prepare2.py","file_name":"prepare2.py","file_ext":"py","file_size_in_byte":7637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"566482569","text":"import logging\nimport os\nimport time\n\nimport requests\nimport telegram\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nPRAKTIKUM_TOKEN = os.getenv('PRAKTIKUM_TOKEN')\nTELEGRAM_TOKEN = os.getenv('TELEGRAM_TOKEN')\nCHAT_ID = os.getenv('TELEGRAM_CHAT_ID')\nPRAKTIKUM_API_URL = 'https://praktikum.yandex.ru/api/user_api/homework_statuses/'\nheaders = {\n 'Authorization': f'OAuth {PRAKTIKUM_TOKEN}',\n}\navailable_statuses_verdicts = {\n 'reviewing': None,\n 'approved': 'Ревьюеру всё понравилось, можно приступать к следующему уроку.',\n 'rejected': 'К сожалению в работе нашлись ошибки.',\n}\n\nlogging.basicConfig(format='%(asctime)s; %(levelname)s; %(message)s',\n filename='log.log',\n filemode='a')\nlogger = logging.getLogger('__name__')\nlogger.setLevel(logging.DEBUG)\n\n\nclass UndefinedStatusError(Exception):\n pass\n\n\ndef parse_homework_status(homework):\n homework_name = homework.get('homework_name')\n status = homework.get('status')\n if status is None or status not in available_statuses_verdicts:\n raise UndefinedStatusError(\n f'В ответе пришел неизвестный статус {status}')\n verdict = available_statuses_verdicts[status]\n if not verdict:\n return f'Работа \"{homework_name}\" взята в ревью'\n return f'У вас проверили работу \"{homework_name}\"!\\n\\n{verdict}'\n\n\ndef get_homework_statuses(current_timestamp):\n params = {\n 'from_date': current_timestamp\n }\n homework_statuses = requests.get(PRAKTIKUM_API_URL,\n headers=headers,\n params=params)\n return homework_statuses.json()\n\n\ndef send_message(message, bot_client):\n return bot_client.send_message(chat_id=CHAT_ID, text=message)\n\n\ndef main():\n bot_client = telegram.Bot(token=TELEGRAM_TOKEN)\n logger.debug('Бот запущен')\n current_timestamp = int(time.time())\n\n while True:\n try:\n new_homework = get_homework_statuses(current_timestamp)\n if new_homework.get('homeworks'):\n send_message(\n parse_homework_status(new_homework.get('homeworks')[0]),\n bot_client)\n logger.info('Отправлено сообщение')\n current_timestamp = new_homework.get('current_date',\n current_timestamp)\n time.sleep(300)\n\n except Exception as e:\n logger.error(e, exc_info=True)\n send_message(\n f'Бот столкнулся с ошибкой: {e}',\n bot_client)\n time.sleep(5)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"homework.py","file_name":"homework.py","file_ext":"py","file_size_in_byte":2827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"592510110","text":"# -*- coding: utf-8 -*-\n\"\"\"Module providing widget setting constants\"\"\"\n\nPKG_WIDGETS = {\n \"bfa-teaser-news\": {\n \"pkg\": \"bfa.sitecontent\",\n \"id\": \"bfa-teaser-news\",\n \"name\": \"Brechtfestival Teaser News\",\n \"title\": \"Teaser News\",\n \"category\": \"more\",\n \"type\": \"content-item\",\n \"schema\": \"bfa.sitecontent.widgets.teaser.interfaces.IBFAWidgetTeaserNews\", # noqa\n \"node\": {}\n },\n \"bfa-teaser-events\": {\n \"pkg\": \"bfa.sitecontent\",\n \"id\": \"bfa-teaser-events\",\n \"name\": \"Brechtfestival Teaser Events\",\n \"title\": \"Teaser Events\",\n \"category\": \"more\",\n \"type\": \"content-item\",\n \"schema\": \"bfa.sitecontent.widgets.teaser.interfaces.IBFAWidgetTeaserEvents\", # noqa\n \"node\": {}\n },\n \"bfa-slider\": {\n \"pkg\": \"bfa.sitecontent\",\n \"id\": \"bfa-slider\",\n \"name\": \"Brechtfestival Slider\",\n \"title\": \"Slider\",\n \"category\": \"more\",\n \"type\": \"collection\",\n \"schema\": \"bfa.sitecontent.widgets.slider.interfaces.IBFAWidgetSlider\", # noqa\n \"node\": {\n \"title\": \"Slide\",\n \"schema\": \"bfa.sitecontent.widgets.slider.interfaces.IBFAWidgetSliderItem\" # noqa\n }\n }\n}\n","sub_path":"src/bfa.sitecontent/bfa/sitecontent/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"430667477","text":"import urllib.request\nfrom bs4 import BeautifulSoup as BS\n\ndef fetch_poem():\n\t'''Fetch Shakespeare poems from MIT site (http://shakespeare.mit.edu/) \n\tand writes them into a file poem_name.txt for example The Sonnets.txt\n\tAlso return a dictionary with poem name as key and the poem as value'''\n\n\tpoems = { \"A Lover's Complaint\" : 'LoversComplaint',\n\t\t\t 'The Rape of Lucrece' : 'RapeOfLucrece',\n\t\t\t 'Venus and Adonis' : 'VenusAndAdonis'}\t\t\t \n\tpoem_dicts = {}\n\turl = \"http://shakespeare.mit.edu/Poetry/\"\n\n\tfor poem in poems:\n\t\tpoem_url = url + poems[poem] + '.html'\n\t\tresponse = urllib.request.urlopen(poem_url)\n\t\thtml_doc = response.read().decode('utf-8')\n\t\thtml_string = BS(html_doc, 'html.parser')\n\t\tpoem_lines = ''\n\t\tfor block in html_string.find_all('blockquote'):\n\t\t\tfor line in block.strings:\n\t\t\t\tpoem_lines += line\n\n\t\t# with open(poem+'.txt', 'w') as f:\n\t\t# \tf.write(poem_lines)\n\n\t\tpoem_dicts[poem] = poem_lines\n\n\treturn poem_dicts ","sub_path":"Markov_Chain/fetch_data.py","file_name":"fetch_data.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"197746809","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('polls', '0002_category_image'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='NegativeVote',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('pub_date', models.DateTimeField(verbose_name=b'date published')),\n ('choice', models.ForeignKey(to='polls.Choice')),\n ('poll', models.ForeignKey(to='polls.Poll')),\n ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='vote',\n name='old',\n field=models.BooleanField(default=False),\n preserve_default=True,\n ),\n ]\n","sub_path":"polls/migrations/0003_auto_20150407_1238.py","file_name":"0003_auto_20150407_1238.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"119332160","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import optimize\nfrom scipy.interpolate import interp1d\nimport copy\n# MLDC packages\nimport LISAConstants as LC\nfrom LISAhdf5 import LISAhdf5,ParsUnits,Str\nimport Cosmology\nimport GenerateFD_SignalTDIs as GenTDIFD\nfrom waveforms_mldc import ComputeXYZ_FD,GenerateFastGB,ComputeSNR_MBHB#,ComputeTD\nimport LISANoise\nimport tdi\nimport MainChooseSources\n\nimport h5py\n\n\n#import time\n#import datetime\n\n\nclass simuoptions:\n\n def __init__(self,source_type):\n\n #now = datetime.datetime.now()\n #prefix = now.strftime(\"%Y-%m-%d_%Hh%M-%S_\")\n\n # Source parameter file and hdf5 file name definitions\n if (source_type is 'SB'):\n self.par_file = 'ParamGal.txt'\n self.hdf5_name = 'MySim_ParamGal.hdf5'\n elif (source_type is 'MBHB'):\n self.par_file = 'ParamMBH.txt'\n self.hdf5_name = 'MySim_ParamMBH.hdf5'\n elif (source_type is 'EMRI'):\n raise NotImplementedError(\"EMRI source not implemented yet.\")\n else:\n raise ValueError(\"Unknown source type!\")\n\n\n # Configuration of simulation\n self.debug = False\n self.verbose = False\n self.seed = 1234\n self.NoGW = False\n self.NoNoise = True\n\n # Congiguration of instrument\n self.TDI = \"X,Y,Z\"\n self.duration = 31457280 #LC.year\n self.timeStep = 20.0\n self.orbits = \"LISACode_Orbits\"\n\n\n\ndef logfrequency(fmin,fmax,J):\n \"\"\"\n Returns a logarithmic frequency grid\n \"\"\"\n\n return fmin*(fmax/fmin)**(np.arange(0,J)/(J-1.))\n\n\ndef ComputeSNR(x, S, fr):\n\n df = fr[1]-fr[0]\n SNR2 = (4.0*df) * np.sum(np.absolute(x)**2/S)\n\n return(np.sqrt(SNR2))\n\n\n\ndef calculate_noise_psd(f,CSVFile = \"./LISA_NoiseParameters_ESACallv1-2.csv\",TDI='X1'):\n\n \"\"\"\n Computes the PSD of the TDI noise at Fourier frequencies.\n Assumes that the function LISANoise.LISAModel.Sn is giving the one-sided PSD.\n\n \"\"\"\n lisa = LISANoise.LISAModel(Name=\"ESAcall1\",CSVFile=CSVFile)\n # f = np.fft.fftfreq(N)*fs\n # fpos = f[f>0]\n Sn = lisa.Sn(f, TDI=TDI, AllOutput=False, rf=True, TDIOscil=True)\n\n return Sn\n\n\n\n\n\ndef param_dic2p(params_dic,constants_dic,options,verbose = False):\n \"\"\"\n Functions that writes the information on the source contained in the\n dictionary param_dic and the information on the simulation options contained\n in the simuoption instance \"options\" into the LISAhdf5 SourceParameters\n instance p\n\n\n Parameters\n ----------\n params_dic : dictionary\n dictionary of source parameter values as specified by CLST tool\n constant_dic : Dictionary\n dictionary of fixed constants of the problem giving their values\n options : simuoption class instance\n defines simulation parameters such that observation time, sampling time,\n catalog paths...\n\n Returns\n -------\n p : ParsUnits instance\n MLDC's source parameter object\n\n\n\n\n \"\"\"\n\n\n # Source parameters Here we assume SI units !! G and c are NOT equal to one\n m1 = params_dic[\"m1\"]\n m2 = params_dic[\"m2\"]\n f_start = 2/params_dic[\"Torb\"]\n sourcetype = params_dic[\"sourcetype\"]\n skyloc = params_dic[\"skyloc\"]\n z = params_dic[\"z\"]\n\n # Constants of the problem\n Omega_m = constants_dic[\"Omega_m\"]\n H0 = constants_dic[\"H0\"]\n Tobs = constants_dic[\"Tobs\"]\n\n # Compute lunimosity distance from redshift\n Dl = z2Dl(z,Omega_m=Omega_m, H0=H0)\n\n ### Calculate relevant mass parameters\n # redshift the source frame masses in SI units\n m1 *= (1. + z)*LC.MsunKG\n m2 *= (1. + z)*LC.MsunKG\n M = m1 + m2 # total mass\n M_chirp = (m1*m2)**(3./5.)/M**(1./5.) # chirp mass\n eta = (m1*m2)/M**2 # symmetric mass ratio\n\n ### Compute Approximate frequency derivative\n f_dot = 96/5.*np.pi**(8/3.)*(LC.G*M_chirp/LC.c**3)**(5/3.)*f_start**(11/3.)\n\n # Compute strain amplitude\n Dl_SI = Dl*LC.Mpc\n Amp = 4*(LC.G*M_chirp)**(5/3.) * (np.pi*f_start)**(2/3.) / (LC.c**4 * Dl_SI)\n\n # Compute time to merger\n T_merger = 5.*LC.c**5*(LC.G*M_chirp)**(-5/3.)/(8.*np.pi*f_start)**(8./3.)\n\n\n ### Create MLDC source parameter instance\n MainChooseSources.main(options)\n #fr_hf5 = options.hdf5_name[:-5]+\"_FD.hdf5\"\n #os.system(\"cp \" + options.hdf5_name + \" \" + fr_hf5 )\n #print(fr_hf5)\n #FD5 = LISAhdf5(fr_hf5)\n FD5 = LISAhdf5(options.hdf5_name)\n GWs = FD5.getSourcesName()\n # Load parameter\n p = FD5.getSourceParameters(GWs[0])\n if verbose: p.display();\n\n if (skyloc == \"random\") |( skyloc == \"favorable\") | ( skyloc == \"unfavorable\" ):\n\n if verbose:\n print(\"Randomly drawn sky location:\")\n print(\"EclipticLatitude:\" + str(p.get(\"EclipticLatitude\")))\n print(\"EclipticLongitude:\" + str(p.get(\"EclipticLongitude\")))\n\n\n elif (len(skyloc)== 2):\n # p.pars[\"EclipticLatitude\"] = skyloc[0]*LC.convAngle['deg']\n # p.pars[\"EclipticLongitude\"] = skyloc[1]*LC.convAngle['deg']\n # p.pars[\"Polarization\"] = 0\n #p = ParsUnits()\n p.addPar(\"EclipticLatitude\",skyloc[0]*LC.convAngle['deg'],'Radian')\n p.addPar(\"EclipticLongitude\",skyloc[1]*LC.convAngle['deg'],'Radian')\n p.addPar(\"Polarization\",0,'Radian')\n\n elif (len(skyloc)== 3):\n #p = ParsUnits()\n # p.pars[\"EclipticLatitude\"] = skyloc[0]*LC.convAngle['deg']\n # p.pars[\"EclipticLongitude\"] = skyloc[1]*LC.convAngle['deg']\n # p.pars[\"Polarization\"] = skyloc[2]*LC.convAngle['deg']\n\n p.addPar('EclipticLatitude',skyloc[0]*LC.convAngle['deg'],'Radian')\n p.addPar('EclipticLongitude',skyloc[1]*LC.convAngle['deg'],'Radian')\n p.addPar('Polarization',skyloc[2]*LC.convAngle['deg'],'Radian')\n\n\n\n # Sampling frequency and observation duration\n p.addPar('ObservationDuration',options.duration,'Second')\n p.addPar('Cadence',options.timeStep,'Second')\n\n if verbose:\n print(\"The chosen sampling time is: \" + str(options.timeStep))\n\n # Load parameters values into p\n if sourcetype == 'SB':\n p.addPar('Amplitude',Amp,'strain')\n p.addPar('Frequency',f_start,'Hertz')\n p.addPar('FrequencyDerivative',f_dot,'Hertz^2')\n p.addPar('Inclination',0,'Radian')\n p.addPar('InitialPhase',0,'Radian')\n\n # p.pars[\"Amplitude\"] = Amp\n # p.pars[\"Frequency\"] = f_start\n # p.pars[\"FrequencyDerivative\"] = f_dot\n # p.pars[\"Inclination\"] = 0\n # p.pars[\"InitialPhase\"] = 0\n if verbose:\n print(\"f_dot = \" + str(f_dot) + \"Hz/s\")\n print(\"The amplitude is \" + str(Amp))\n print(\"The frequency is \" + str(f_start) + \" Hz\")\n print(\"The observation duration is \" + str(p.get(\"ObservationDuration\")))\n\n elif sourcetype == 'MBHB':\n\n\n\n # p.pars['Distance'] = Dl*LC.Mpc\n # p.addPar('Distance',Dl,'mpc')\n # p.pars['Redshift'] = z\n # p.pars['Mass1'] = params_dic[\"m1\"]\n # p.pars['Mass2'] = params_dic[\"m2\"]\n # p.pars['CoalescenceTime'] = T_merger\n # p.pars['PhaseAtCoalescence'] = 0\n # p.pars['InitialAzimuthalAngleL'] = z\n # p.pars['InitialPolarAngleL'] = 0\n # p.pars['PolarAngleOfSpin1'] = 0\n # p.pars['PolarAngleOfSpin2'] = 0\n # p.pars['Spin1'] = 0\n # p.pars['Spin2'] = 0\n if verbose:\n print(\"The distance of the black hole is \" + str(p.get('Distance')) + ' MPC')\n # Set other parameter values\n #p.addPar('Approximant','IMRPhenomD','dimensionless')\n #p.addPar('Distance',Dl*LC.Mpc,'Meter')\n p.addPar('Distance',Dl,'mpc')\n p.addPar('Redshift',z,'dimensionless')\n p.addPar('Mass1',params_dic[\"m1\"],'SolarMass')\n p.addPar('Mass2',params_dic[\"m2\"],'SolarMass')\n p.addPar('CoalescenceTime',T_merger,'Second')\n p.addPar('PhaseAtCoalescence',0,'Radian')\n p.addPar('InitialAzimuthalAngleL',0,'Radian')\n p.addPar('InitialPolarAngleL',0,'Radian')\n p.addPar('PolarAngleOfSpin1',0,'Radian')\n p.addPar('PolarAngleOfSpin2',0,'Radian')\n p.addPar('Spin1',0,'MassSquared')\n p.addPar('Spin2',0,'MassSquared')\n\n if verbose:\n print(\"------------------\")\n print(\"Source parameters:\")\n print(\"------------------\")\n p.display()\n\n return p\n\n\ndef get_Dl(z, Omega_m, H0):\n \"\"\" calculate luminosity distance in geometrized units \"\"\"\n # see http://arxiv.org/pdf/1111.6396v1.pdf\n x0 = (1. - Omega_m)/Omega_m\n xZ = x0/(1. + z)**3\n\n Phi0 = (1. + 1.320*x0 + 0.4415*x0**2 + 0.02656*x0**3)\n Phi0 /= (1. + 1.392*x0 + 0.5121*x0**2 + 0.03944*x0**3)\n PhiZ = (1. + 1.320*xZ + 0.4415*xZ**2 + 0.02656*xZ**3)\n PhiZ /= (1. + 1.392*xZ + 0.5121*xZ**2 + 0.03944*xZ**3)\n\n return 2.*LC.c/H0*(1.0e-3*LC.Mpc)*(1. + z)/np.sqrt(Omega_m)*(Phi0 - PhiZ/np.sqrt(1. + z))\n\n\n\n\ndef get_z(z, Dl, Omega_m, H0):\n \"\"\" calculate redishift uisng root finder \"\"\"\n\n\n\n return get_Dl(z, Omega_m, H0) - Dl\n\n\ndef Dl2z(Dl,Omega_m=0.286, H0=69.6):\n \"\"\"\n Function converting lumisonity distance [in MPC] to redshift\n\n Parameters\n ----------\n Dl : scalar float\n \tluminosity distance in MPC\n Omega_m : scalar float\n \tdensity parameter of matter (should always be fixed)\n H0 : scalar float\n \tHubble parameter\n\n Returns\n -------\n z : scalar float\n \tredshift [no dimension]\n\n \"\"\"\n\n #z = Cosmology.zofDl(Dl,w=0, tolerance=1e-3)[0]\n z = Cosmology.zofDl(Dl,w=0, tolerance=1e-3)[0]\n #z = optimize.root(get_z, 1., args=(Dl*LC.Mpc, Omega_m, H0)).x[0]\n\n return z\n\ndef z2Dl(z,Omega_m=0.286, H0=69.6):\n \"\"\"\n Function converting redshift to lumisonity distance [in MPC]\n\n Parameters\n ----------\n z : scalar float\n \tredshift [no dimension]\n Omega_m : scalar float\n \tdensity parameter of matter (should always be fixed)\n H0 : scalar float\n \tHubble parameter\n\n Returns\n -------\n Dl : scalar float\n \tluminosity distance in MPC\n\n Reference\n ---------\n\n see http://arxiv.org/pdf/1111.6396v1.pdf\n\n\n \"\"\"\n\n # x0 = (1. - Omega_m)/Omega_m\n # xZ = x0/(1. + z)**3\n #\n # Phi0 = (1. + 1.320*x0 + 0.4415*x0**2 + 0.02656*x0**3)\n # Phi0 /= (1. + 1.392*x0 + 0.5121*x0**2 + 0.03944*x0**3)\n # PhiZ = (1. + 1.320*xZ + 0.4415*xZ**2 + 0.02656*xZ**3)\n # PhiZ /= (1. + 1.392*xZ + 0.5121*xZ**2 + 0.03944*xZ**3)\n #\n # Dl = 2.*LC.c/H0*(1.0e-3*LC.Mpc)*(1. + z)/np.sqrt(Omega_m)*(Phi0 - PhiZ/np.sqrt(1. + z))\n\n Dl = Cosmology.DL(z, w=0)\n\n return Dl[0]\n\n #return Dl/LC.Mpc\n\n\ndef tune_sampling_time(Tobs,f_start,f_dot,tmax = 1000,margin = 0.5):\n\n # We want a sampling time smaller than\n ts_min = np.min([tmax,margin/(f_start + 0.5*Tobs*f_dot)])\n\n q = np.int(np.log(Tobs/ts_min)/np.log(2)) + 1\n\n return Tobs/(2**q)\n\n\ndef period2sep(Torb,m1,m2):\n \"\"\"\n Translates the orbital period of the source into to binary separation\n\n Parameters\n ----------\n Torb : scalar float\n orbital period of the binary in seconds\n m1 : scalar float\n mass of object 1 in SOLAR MASSES\n m2 : scalar float\n mass of object 2 in SOLAR MASSES\n\n Returns\n -------\n d : scalar float\n orbital separation of the binary in KM\n\n \"\"\"\n\n M = (m1+m2)*LC.MsunKG\n d = ( LC.G*M*Torb**2/(4*np.pi**2) )**(1/3.)\n\n return d/1e3\n\ndef sep2period(d,m1,m2):\n \"\"\"\n Translates the binary separation into orbital period\n\n Parameters\n ----------\n d : scalar float\n orbital separation of the binary in KM\n m1 : scalar float\n mass of object 1 in SOLAR MASSES\n m2 : scalar float\n mass of object 2 in SOLAR MASSES\n\n Returns\n -------\n Torb : scalar float\n orbital period of the binary in seconds\n\n\n\n \"\"\"\n M = (m1+m2)*LC.MsunKG\n Torb = 2*np.pi*np.sqrt( (d*1e3)**3/(LC.G*M) )\n\n return Torb\n\n\n\n\n\ndef compute_crude_snr_vs_time(source,pGW,f_start,Npts = 100):\n \"\"\"\n\n Crude computation of the SNR of a source with respect to integration time.\n\n\n Parameters\n ----------\n p : ParsUnits instance\n object containing the source parameters\n\n\n \"\"\"\n\n\n\n\n # Source parameters Here we assume SI units !! G and c are NOT equal to one\n m1 = pGW.get(\"Mass1\")\n m2 = pGW.get(\"Mass2\")\n z = params_dic[\"z\"]\n\n # Constants of the problem\n Omega_m = constants_dic[\"Omega_m\"]\n H0 = constants_dic[\"H0\"]\n Tobs = constants_dic[\"Tobs\"]\n\n # Compute lunimosity distance from redshift\n Dl = z2Dl(z,Omega_m=Omega_m, H0=H0)\n\n ### Calculate relevant mass parameters\n # redshift the source frame masses in SI units\n m1 *= (1. + z)*LC.MsunKG\n m2 *= (1. + z)*LC.MsunKG\n M = m1 + m2 # total mass\n M_chirp = (m1*m2)**(3./5.)/M**(1./5.) # chirp mass\n eta = (m1*m2)/M**2 # symmetric mass ratio\n\n # Compute Approximate frequency derivative\n f_dot = 96/5.*np.pi**(8/3.)*(LC.G*M_chirp/LC.c**3)**(5/3.)*f_start**(11/3.)\n\n # Compute strain amplitude\n Dl_SI = Dl*LC.Mpc\n Amp = 4*(LC.G*M_chirp)**(5/3.) * (np.pi*f_start)**(2/3.) / (LC.c**4 * Dl_SI)\n\n\n # Create template for parameter object\n options = simuoptions('SB')\n options.timeStep = pGW.get('Cadence')\n options.duration = pGW.get('ObservationDuration')\n MainChooseSources.main(options)\n FD5 = LISAhdf5(options.hdf5_name)\n GWs = FD5.getSourcesName()\n # Load parameter\n p = FD5.getSourceParameters(GWs[0])\n\n # Create a new parameter for equivalent \"abiabatic binary\" source\n p_eq = copy.deepcopy(p)\n p_eq.addPar('EclipticLatitude',p.get('EclipticLatitude'),'Radian')\n p_eq.addPar('EclipticLongitude',p.get('EclipticLongitude'),'Radian')\n p_eq.addPar('Polarization',p.get('Polarization'),'Radian')\n\n #p_eq.addPar('ObservationDuration',Tobs,'Second')\n #p_eq.addPar('Cadence',p.get('Cadence'),'Second')\n p_eq.addPar('Amplitude',Amp,'strain')\n p_eq.addPar('Frequency',f_start,'Hertz')\n p_eq.addPar('FrequencyDerivative',f_dot,'Hertz^2')\n p_eq.addPar('Inclination',p.get('Inclination'),'Radian')\n p_eq.addPar('InitialPhase',p.get('InitialPhase'),'Radian')\n\n\n if source == 'SB':\n day = 3600*24\n t_snr = np.linspace(day,Tobs,Npts)\n\n\n elif source == 'MBHB':\n t_snr = logfrequency(100,Tobs,Npts)\n\n SNR = np.zeros(Npts+1,dtype = np.float64)\n f_t = f_start\n t_snr = np.concatenate(([0],t_snr))\n\n for j in range(Npts):\n\n # Create new source parameter instance\n p_snr = copy.deepcopy(p_eq)\n\n T = t_snr[j+1]-t_snr[j]\n # Update frequency\n f_t = f_t + 0.5 * f_dot * T\n p_snr.addPar('Frequency',f_t,'Hertz')\n\n # Update amplitude\n p_snr.addPar('Amplitude',Amp,'strain')\n Amp = 4*(LC.G*M_chirp)**(5/3.) * (np.pi*f_t)**(2/3.) / (LC.c**4 * Dl_SI)\n\n # Update frequency derivative\n f_dot = 96/5.*np.pi**(8/3.)*(LC.G*M_chirp/LC.c**3)**(5/3.)*f_start**(11/3.)\n p_snr.addPar('FrequencyDerivative',f_dot,'Hertz^2')\n\n p_snr.addPar('ObservationDuration',T,'Second')\n # Compute TDI response to GW\n fr,Xf,Yf,Zf = GenerateFastGB(p_snr)\n # Compute A,E,T channels\n Af,Ef,Tf = tdi.AET(Xf,Yf,Zf)\n\n ix = np.where(fr>0)\n SnX = np.exp(logSnX_func(np.log(fr[ix])))\n SnA = np.exp(logSnA_func(np.log(fr[ix])))\n SnE = SnA[:]\n SnT = 3*(SnX + 0.5*(SnA+SnE))\n\n # Compute SNR\n SNR_new = np.sqrt( ComputeSNR(Af[ix], SnA, fr[ix])**2 \\\n + ComputeSNR(Ef[ix], SnE, fr[ix])**2 \\\n + ComputeSNR(Tf[ix], SnT, fr[ix])**2 )*t_snr[j+1]*np.sqrt(2)\n\n #SNR[j] = SNR_new\n SNR[j+1] = SNR[j] + SNR_new\n\n\n\n\n return t_snr[1:],SNR[1:]\n\n\n\ndef compute_snr_vs_time(p,respfunc,logSnA_func,logSnT_func,sourcetype,f0=1e-3,Npts = 15):\n \"\"\"\n\n \"Exact\" computation of the SNR of a source with respect to integration time.\n The LISA response is recomputed for each value of integration time.\n\n\n Parameters\n ----------\n p : ParsUnits instance\n object containing the source parameters\n respfunc : callable\n function of p giving the TDI X,Y,Z response to incoming GW\n logSnA_func : callable\n function of giving the noise log-PSD of the TDI channel A as a function\n of log-frequency\n logSnT_func : callable\n function of giving the noise log-PSD of the TDI channel T as a function\n of log-frequency\n Npts : scalar integer\n number of time points where to compute the SNR\n source_type : string\n type of source among {'SB','MBHB','EMRI'}\n\n Returns\n -------\n t_snr : numpy array\n time vector (Seconds, on logarithmic scale)\n snr : numpy array\n vector giving SNR as a function of t_snr\n\n \"\"\"\n\n # Xf_array = np.zeros((len(Xf),Npts),dtype = np.complex128)\n # Yf_array = np.zeros((len(Yf),Npts),dtype = np.complex128)\n # Zf_array = np.zeros((len(Zf),Npts),dtype = np.complex128)\n\n # Observation duration\n Tobs = p.get(\"ObservationDuration\")\n\n\n day = 3600*24\n\n\n\n if sourcetype == 'SB':\n\n SNR = np.zeros(Npts,dtype = np.float64)\n t_snr = np.linspace(day,Tobs,Npts)\n\n for j in range(Npts):\n p_snr = copy.deepcopy(p)\n p_snr.addPar('ObservationDuration',t_snr[j],'Second')\n # Compute TDI response to GW\n fr,Xf,Yf,Zf = respfunc(p_snr)\n # Compute A,E,T channels\n Af,Ef,Tf = tdi.AET(Xf,Yf,Zf)\n\n ix = np.where(fr>0)\n SnA = np.exp(logSnA_func(np.log(fr[ix])))\n SnT = np.exp(logSnT_func(np.log(fr[ix])))\n SnE = SnA[:]\n #SnT = 3*(SnX + 0.5*(SnA+SnE))\n\n # Compute SNR\n SNR[j] = np.sqrt( ComputeSNR(Af[ix], SnA, fr[ix])**2 \\\n + ComputeSNR(Ef[ix], SnE, fr[ix])**2 \\\n + ComputeSNR(Tf[ix], SnT, fr[ix])**2 )\n\n SNR = SNR*t_snr*np.sqrt(2)\n\n elif sourcetype == 'MBHB':\n # Time vector on logarithmic scale\n #\n #t_snr = np.linspace(100,Tobs,Npts)\n t_snr = logfrequency(100,Tobs,Npts)\n SNR = np.zeros(Npts,dtype = np.float64)\n\n for j in range(Npts):\n p_snr = copy.deepcopy(p)\n p_snr.addPar('ObservationDuration',t_snr[j],'Second')\n # Compute TDI response to GW\n fr,Xf,Yf,Zf = respfunc(p_snr)\n # Compute A,E,T channels\n Af,Ef,Tf = tdi.AET(Xf,Yf,Zf)\n\n ix = np.where(fr>0)\n SnA = np.exp(logSnA_func(np.log(fr[ix])))\n SnT = np.exp(logSnT_func(np.log(fr[ix])))\n SnE = SnA[:]\n\n # Compute SNR\n SNR[j] = np.sqrt( ComputeSNR(Af[ix], SnA, fr[ix])**2 \\\n + ComputeSNR(Ef[ix], SnE, fr[ix])**2 \\\n + ComputeSNR(Tf[ix], SnT, fr[ix])**2 )\n #results_list = [GenerateFastGB(pt) for pt in p_list]\n\n # For the SNR estimation\n #SnX = lisa.Sn(fr[ix], TDI='X1', AllOutput=False, rf=True, TDIOscil=True)\n #SnA = lisa.Sn(fr[ix], TDI='A1', AllOutput=False, rf=True, TDIOscil=True)\n return t_snr,SNR\n\n\n\n\n# ==============================================================================\n# Main function to be used in \"Can LISA See This\" Tool\n# ==============================================================================\n\ndef calculate_plot_source(constants_dic,params_dic,figsavename = 'sensitivity',\nusetex = False,verbose = True,recompute_psd = False,snr_vs_time=True, disp = True):\n \"\"\"\n Determine the appropriate way to plot the source, calculate its characteristic strain\n and print the correpsonding SNR.\n\n\n Calculate the Characteristic strain of the source.\n\n Units of parameters are given in brackets.\n\n Parameters in constants_dic\n ---------------------------\n\n H0 : scalar float\n the Hubble parameter [km/sec/MPC]\n Omega_m : scalar float\n the density of matter in the universe today [no dimension]\n L : positive scalar float\n the LISA armlength [meters]\n f_star : positive scalar float\n the transfer frequency of the sensitivty PSD\n Tobs : positive scalar float\n the observation time of the source [seconds]\n NC : positive integer scalar\n the Number of Michelson Data Channels [no dimension]\n\n\n Parameters in params_dic\n ------------------------\n\n m1 : scalar float\n component mass 1 in the source frame [solar masses]\n m2 : scalar float\n component mass 2 in the source frame [solar masses]\n f_start : positive scalar float or None\n start frequency for source [Hz]\n z : positive scalar float or None\n redshift [no dimension]\n source_type : string\n type of source among {'SB','MBHB','EMRI'}\n SB stands for stellar-origin binary, and include galactic binaries\n MBHB stands for massive black hole binaries.\n EMRI stands for extreme mass ratio inspirals: these are binary system\n for which the mass ratio is larger than 100\n skyloc : 1d array or string\n vector containing [ecliptic longitude, ecliptic latitude] or\n [ecliptic longitude, ecliptic latitude, polarization] or\n 'random' : the sky location and polarization angles of the source are\n drawn randomly from the catalogue\n 'favorable': the sky location is chosen so that the wave vector is perpendicular\n to the constellation close to merger time\n 'unfavorable' the sky location is chosen so that the wave vector is parallel\n to the constellation triangle close to merger time\n\n\n\n Optional parameters\n -------------------\n figsavename : string\n the file name to save the output figure. Default is 'sensitivity.png'\n usetex : boolean\n if True, enable the latex font and math capabilities when plotting the\n figure\n\n\n Returns\n -------\n\n SNR : scalar float\n signal-to-noise ratio of the source [no dimension]\n\n \"\"\"\n\n ### Get observation time, sampling time, and source type\n Tobs = constants_dic[\"Tobs\"]\n del_t = constants_dic[\"del_t\"]\n source_type = params_dic[\"sourcetype\"]\n\n\n ### Simulation options\n options = simuoptions(source_type)\n options.timeStep = del_t\n\n ### Convert parameter discionary to MLDC parameter instance\n p = param_dic2p(params_dic,constants_dic,options,verbose = verbose)\n\n ### Number of data points assumed\n N = np.int(Tobs/p.get('Cadence'))\n f_start = 2/params_dic[\"Torb\"]\n\n\n # ==========================================================================\n ### Computation of the response to incoming wave\n # ==========================================================================\n # if chosen source is stellar-origin binary\n if (source_type == 'SB'):\n\n # Use Auxiliary function GenerateFastGB of the notebook ProduceGB_exmpl\n fr, Xf, Yf, Zf = GenerateFastGB(p)\n if verbose: print(\"The length of the data is \" + str(len(Xf)));\n\n # Response function\n respfunc = lambda x: GenerateFastGB(x)\n\n # Warning: normalizations are different for GenerateFastGB outputs and\n # ComputeMBHBXYZ_FD outputs\n norm_SNR = Tobs*np.sqrt(2)\n # To convert from Xf to physical amplitude\n coeff_amp = 2.\n\n # if chosen source is massive black hole binary\n elif (source_type == 'MBHB'):\n\n fr, Xf, Yf, Zf = GenTDIFD.ComputeMBHBXYZ_FD(p)\n\n #fr, Xf, Yf, Zf = ComputeXYZ_FD(p)\n norm_SNR = 1.\n # To convert from Xf to physical amplitude\n coeff_amp = np.sqrt(2)/(Tobs)\n\n # Response function used afterwards\n respfunc = lambda x: GenTDIFD.ComputeMBHBXYZ_FD(x)\n\n\n\n # Convert the TDI channels into A,E,T\n #AET_f = tdi.AET(Xf,Yf,Zf)\n Af,Ef,Tf = tdi.AET(Xf,Yf,Zf)\n AET_f = [Af,Ef,Tf]\n\n # ==========================================================================\n # PSD plots\n # ==========================================================================\n CSVFile = \"./noiseconfig/LISA_NoiseParameters_ESACallv1-2.csv\"\n lisa = LISANoise.LISAModel(Name=\"ESAcall1\",CSVFile=CSVFile)\n ix = np.where(fr>0)\n\n # Compute the noise PSD of TDI channels (see ComputeSNR module)\n #ix = np.argwhere(np.absolute(fr) > 0.0)[0][0]\n\n #SnX = tdi.noisepsd_X(fr[ix], model='Proposal', includewd=Tobs/LC.year)\n SnA = tdi.noisepsd_AE(fr[ix], model='Proposal', includewd=Tobs/LC.year)\n SnE = SnA[:]\n SnT = tdi.noisepsd_T(fr[ix], model='Proposal')\n\n fn = logfrequency(1/Tobs,1,1000)\n #SnX_plot = tdi.noisepsd_X(fn, model='Proposal', includewd=Tobs/LC.year)\n SnA_plot = tdi.noisepsd_AE(fn, model='Proposal', includewd=Tobs/LC.year)\n SnE_plot = SnA_plot[:]\n # #SnT_plot = SnX_plot + SnA_plot\n SnT_plot = tdi.noisepsd_T(fn, model='Proposal')\n\n # # For the PSD plot\n # if recompute_psd:\n # fn = logfrequency(1/Tobs,1,1000)\n # SnX_plot = lisa.Sn(fn, TDI='X1', AllOutput=False, rf=True, TDIOscil=True)\n # SnA_plot = lisa.Sn(fn, TDI='A1', AllOutput=False, rf=True, TDIOscil=True)\n # SnE_plot = SnA_plot[:] #lisa.Sn(fn, TDI='E', AllOutput=False, rf=True, TDIOscil=True) # SnA_plot[:]\n # SnT_plot = 3*(SnX_plot + 0.5*(SnA_plot+SnE_plot))\n # # hfile = h5py.File('./noiseconfig/noisePSDs.hdf5','a')\n # # hfile.create_dataset(\"frequencies\", data = fn)\n # # hfile.create_dataset(\"PSD_X1\", data = SnX_plot)\n # # hfile.create_dataset(\"PSD_A1\", data = SnA_plot)\n # # hfile.close()\n # else:\n # hfile = h5py.File('./noiseconfig/noisePSDs.hdf5','r')\n # fn = hfile.get('frequencies').value\n # SnX_plot = hfile.get('PSD_X1').value\n # SnA_plot = hfile.get('PSD_A1').value\n # SnE_plot = SnA_plot[:]\n # SnT_plot = 3*(SnX_plot + 0.5*(SnA_plot+SnE_plot))\n\n # For the SNR estimation\n logSnA_func = interp1d(np.log(fn),np.log(SnA_plot))\n logSnT_func = interp1d(np.log(fn),np.log(SnT_plot))\n # #SnX = lisa.Sn(fr[ix], TDI='X1', AllOutput=False, rf=True, TDIOscil=True)\n # #SnA = lisa.Sn(fr[ix], TDI='A1', AllOutput=False, rf=True, TDIOscil=True)\n #\n # SnX = np.exp(logSnX_func(np.log(fr[ix])))\n # SnA = np.exp(logSnA_func(np.log(fr[ix])))\n # SnE = SnA[:]\n # SnT = 3*(SnX + 0.5*(SnA+SnE))\n\n\n\n\n # Gather noise PSDs in a list\n Sn_AET = [SnA,SnE,SnT]\n Sn_AET_plot = [SnA_plot,SnE_plot,SnT_plot]\n\n\n\n if verbose:\n print(\"Length of fr:\" + str(len(fr)))\n print(\"Length of data_plot:\" + str(len(Xf)))\n\n if snr_vs_time:\n print(\"SNR wrt time is ON\")\n #t_snr_fast,SNR_t_fast = compute_crude_snr_vs_time(source_type,p,f_start,Npts = 15)\n t_snr,SNR_t = compute_snr_vs_time(p,respfunc,logSnA_func,logSnT_func,\n source_type,f0 = f_start,Npts = 15)\n\n #t_snr,SNR_t = compute_crude_snr_vs_time(p,Npts = 100)\n #print(\"SNR vs time calculation complete.\")\n\n # ==========================================================================\n # Plot the results and compute total SNR\n # ==========================================================================\n #plt.ion()\n plt.rcParams['text.usetex'] = usetex\n plt.rc('text', usetex=usetex)\n plt.rc('font', family='calibri')\n\n # SNR VS TIME\n if snr_vs_time:\n title = \"Signal-to-noise ratio vs time\"\n\n fig_snr = plt.figure(figsize=(8,6))\n\n plt.xlabel('Time [Seconds]', fontsize=20, labelpad=10)\n plt.ylabel('Cumulated SNR', fontsize=20, labelpad=10)\n plt.tick_params(axis='both', which='major', labelsize=20)\n plt.loglog(t_snr, np.abs(SNR_t),'k',label = 'Exact')\n #plt.loglog(t_snr, np.abs(SNR_t_fast),'k',label = 'Exact')\n plt.title(title, fontsize=20)\n #%config InlineBackend.figure_format = 'retina'\n # plt.xlim(1.0e-5, 1.0e0)\n # plt.ylim(1.0e-26, 1.0e-20)\n plt.tight_layout()\n plt.tick_params(labelsize=20)\n plt.savefig(figsavename + '_SNR_vs_time.png')\n\n plt.draw()\n\n # SIGNAL AND SENSITIVITY CURVES FOR THE ENTIRE OBSERVATION TIME\n # Compute SNR\n SNR2 = [ComputeSNR(norm_SNR*AET_f[j][ix], Sn_AET[j], fr[ix])**2 for j in range(3)]\n\n # Display the quadratic sum of amplitudes of each channel\n Amp_f = np.sqrt( sum([AET_f[j]**2 for j in range(3)]) )\n Sn_AET_sum = SnA_plot + SnE_plot + SnT_plot\n\n title = r\"Time delay interferometry spectrum A + E + T\"\n\n fig = plt.figure(figsize=(8,6))\n\n if usetex:\n plt.xlabel(r'Frequency [Hz]', fontsize=20, labelpad=10)\n plt.ylabel(r'Fractional frequency [$\\frac{d\\nu}{\\nu}$]', fontsize=20, labelpad=10)\n else:\n plt.xlabel('Frequency [Hz]', fontsize=20, labelpad=10)\n plt.ylabel('Fractional frequency', fontsize=20, labelpad=10)\n\n\n plt.tick_params(axis='both', which='major', labelsize=20)\n plt.loglog(fr[ix], coeff_amp*np.absolute(Amp_f[ix]),'r',label = 'Wave response signal')\n #plt.loglog(fr[ix], np.abs(data_plot[ix]),'r',label = 'Wave response signal')\n plt.title(title, fontsize=20)\n plt.loglog(fn, 2*np.sqrt(Sn_AET_sum/Tobs),'b',label = 'Noise PSD') # plot the characteristic strain of noise\n #%config InlineBackend.figure_format = 'retina'\n plt.legend()\n plt.xlim(1.0e-5, 1.0e0)\n plt.ylim(1.0e-26, 1.0e-20)\n plt.tight_layout()\n plt.tick_params(labelsize=20)\n plt.savefig(figsavename + '_AET.png')\n\n plt.draw()\n\n if disp:\n plt.show()\n\n # Adopt MLDC convention for the SNR (square root of power)\n SNR = np.sqrt(sum(SNR2))\n\n if verbose: print(\"SNR = \" + \"%.4g\" % SNR);\n \n Lat = p.get('EclipticLatitude')/LC.convAngle['deg']\n Long = p.get('EclipticLongitude')/LC.convAngle['deg']\n\n return SNR,Lat,Long,t_snr,SNR_t\n\n\n\n\n\n\n\nif __name__ == '__main__':\n\n # # Typical number for MBHB\n # Dl = 1000\n # z = Dl2z(Dl)\n # sourcetype = \"MBHB\"\n # m1 = 1e6\n # m2 = 2e6\n # Torb = 1e3\n\n # Typical number for SB\n # Type of source\n sourcetype = \"SB\"\n # Masses\n m1 = 0.45\n m2 = 0.7\n # Distance\n Dl = 0.0001 #MPC\n z = Dl2z(Dl)\n # Orbital period\n Torb = 1e3\n\n\n # Sky location\n #skyloc = \"random\"\n skyloc = np.array([40.,20.])\n\n\n params_dic={\"m1\":m1,\"m2\":m2,\"Torb\":Torb,\"z\":z,\"sourcetype\":sourcetype,\n \"skyloc\":skyloc}\n\n constants_dic={\"H0\":70.,\"Omega_m\":0.2,\"L\":2.5e9,\"Tobs\":4*LC.year,\"del_t\":15.}\n\n SNR,Lat,Long,t_snr,SNR_t = calculate_plot_source(constants_dic,params_dic,\n figsavename = 'sensitivity',usetex=True,verbose = True,snr_vs_time=True, disp=True)\n","sub_path":"clst/clst_mldc.py","file_name":"clst_mldc.py","file_ext":"py","file_size_in_byte":30353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"311902397","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2020/9/19 7:45 下午\n# @Author : guohua08\n# @File : playground.py\nfrom typing import List\nimport copy\nimport collections\nimport string\n\nfrom src.linked_list.ListNode import ListNode\nfrom src.linked_list.LinkedList import LinkedList\n\n\nclass Solution:\n def numDecodings(self, s: str) -> int:\n length = len(s)\n if length == 0:\n return 0\n nums = [str(value) for value in list(range(1, 27))]\n dp = [0 for _ in range(length)]\n if s[0] in nums:\n dp[0] = 1\n if s[0] == \"*\":\n dp[0] = 9\n if length>1:\n for idx in range(1, length):\n if idx == 1:\n if dp[idx-1] != 0:\n if s[idx] in nums:\n dp[idx] += 1\n elif s[idx] == \"*\":\n dp[idx] += 9\n if s[:2] in nums:\n dp[idx] += 1\n else:\n if dp[idx-1] != 0:\n if s[idx] in nums:\n dp[idx] += dp[idx-1]\n elif s[idx] == \"*\":\n dp[idx] = dp[idx] + dp[idx-1] + 9\n if dp[idx-2] != 0 and s[idx-1:idx+1] in nums:\n dp[idx] += dp[idx-2]\n print(dp)\n return dp[-1]\n\n# s = \"*\" # 9\ns = \"1*\" #18\nres = Solution().numDecodings(s)\nprint(res)","sub_path":"problems/unsolved/639.py","file_name":"639.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"475697410","text":"\nfrom skimage import io, feature, img_as_float\nfrom skimage import color\nfrom skimage.transform import hough_circle, hough_circle_peaks\nfrom skimage.draw import circle_perimeter\nimport matplotlib.pyplot as plt\n\nimport numpy as np\nimport os\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\nimage = img_as_float(color.rgb2gray(io.imread(dir_path+'/media/IRIS3.jpg')))\nedges = feature.canny(image, sigma=3)\n\nhough_radii = np.arange(80, 100, 2)\nhough_radii_inner = np.arange(20, 35, 2)\n\nhough_res = hough_circle(edges, hough_radii)\nhough_res_inner = hough_circle(edges, hough_radii_inner)\n\n\naccums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii, total_num_peaks=1)\naccums_i, cx_i, cy_i, radii_i = hough_circle_peaks(hough_res_inner, hough_radii_inner, total_num_peaks=1)\n\n\nfig, ax = plt.subplots(ncols=1, nrows=1, figsize=(10, 4))\nimage = color.gray2rgb(image)\n\nfor center_y, center_x, radius in zip(cy, cx, radii):\n circy, circx = circle_perimeter(center_y, center_x, radius)\n image[circy, circx] = (220, 20, 20)\n\nfor center_y, center_x, radius in zip(cy_i, cx_i, radii_i):\n circy, circx = circle_perimeter(center_y, center_x, radius)\n image[circy, circx] = (220, 20, 20)\n\nax.imshow(image, cmap=plt.cm.gray)\nplt.show()","sub_path":"OpenCV/sci_eye.py","file_name":"sci_eye.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"276209954","text":"import time\nimport os\nimport glob\nimport tensorflow as tf\nimport numpy as np\n\n# path = 'by_class'\npath = 'test'\n\nt1 = time.time()\nfile_names=glob.glob(os.path.join(path,'*','train_*','*.[pP][nN][gG]'))\nfilename_queue = tf.train.string_input_producer(file_names)\nt2 = time.time()\nprint('Time to list files: ', t2-t1)\n\nfile_classes=[int(ele.split('/')[1], base=16) for ele in file_names]\ntry:\n file_labels = [str(chr(i)) for i in file_classes] #python 3\nexcept:\n file_labels = [str(unichr(i)) for i in file_classes] #python 2.7 \n\n# file_labels=np.array(file_labels)\n# tf.convert_to_tensor(file_labels.eval())\nt3 = time.time()\nprint('Time to list labels: ', t3-t2)\n\nreader = tf.WholeFileReader()\nkey, value = reader.read(filename_queue)\nmy_img = tf.image.decode_png(value) # use png or jpg decoder based on your files.\n\ninit_op = tf.initialize_all_variables()\n\nsess = tf.Session()\nsess.run(init_op)\n\n# Start populating the filename queue.\n\ncoord = tf.train.Coordinator()\nthreads = tf.train.start_queue_runners(coord=coord, sess=sess)\n\nfor i in range(len(file_classes)): #length of your filename list\n image = my_img.eval(session = sess).ravel() #here is your image Tensor :)\n\ncoord.request_stop()\ncoord.join(threads)\nt4 = time.time()\nprint('Time to read images: ',t4-t3)\n# Takes about seconds to read test folder on my 4GB PC :-D\n# And the code works!!\n#Input the images from mnist to tensorflow\n\nfile_labels = np.zeros((len(file_labels),10))\n\nx = tf.placeholder(tf.float32, [None, 128*128*3],name=\"x\")\nW = tf.Variable(tf.zeros([128*128*3, 10]))\nb = tf.Variable(tf.zeros([10]))\ny = tf.nn.softmax(tf.matmul(x, W) + b)\ny_ = tf.placeholder(tf.float32, [None, 10])\n\ncross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))\n\ntrain_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\n\ninit = tf.initialize_all_variables()\n\nsess = tf.Session()\nsess.run(init)\n\n#Training the NN\nsess.run(train_step, feed_dict={x: image.reshape(1,image.shape[0]), y_: file_labels})\n\ncorrect_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))\n\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\nprint(correct_prediction)\n# print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))","sub_path":"read_images.py","file_name":"read_images.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"45317202","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jul 21 16:41:44 2020\r\n\r\nQuestion 6\r\nWrite a short Python program to open the video file myVideo.mp4 . \r\nUse the program to play the video. \r\nConvert the video to grayscale and save it as myVideo_gray.mp4. \r\nRepeat the same problem using video from your webcam.\r\n Use the opencv cv2 module for video processing.\r\n\r\n---------\r\nConvert to grayscale and save it\r\n\r\n@author: user\r\n\"\"\"\r\n\r\n#%% Import\r\n\r\nimport cv2\r\nimport numpy as np\r\nimport os\r\nimport matplotlib.pyplot as plt\r\n\r\n#%% Read Video File\r\n\r\nfilename = './media_files/myVideo.mp4' # ok\r\nfilenameOut = './media_files/myVideo_gray.mp4'\r\n\r\n# Create a video reader \r\ncap = cv2.VideoCapture(filename) # video object\r\n\r\n# get video parameter\r\nframe_width = int(cap.get(3))\r\nframe_height = int(cap.get(4))\r\nfourcc = cv2.VideoWriter_fourcc(*'MP4V') # use mpeg4 encoder\r\nfps = round( cap.get(cv2.CAP_PROP_FPS) ) # frame rate\r\n\r\nout = cv2.VideoWriter(filenameOut, fourcc, fps, (frame_width,frame_height) , isColor=False )\r\n\r\n# check for error in opening the video\r\nif (cap.isOpened()== False): \r\n print(\"Error opening video stream or file\")\r\n \r\n#%% Write to another video\r\nframeIdx=0\r\nwhile (cap.isOpened()):\r\n ret,frame = cap.read()\r\n \r\n if (ret == True):\r\n frameIdx += 1\r\n frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n out.write(frame_gray)\r\n\r\n if (ret == False):\r\n break\r\n\r\nprint(\" Total frames = {}\".format(frameIdx)) \r\n\r\n#%%\r\ncap.release() \r\nout.release()\r\n \r\n# Closes all the frames \r\ncv2.destroyAllWindows() \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"tutorial_1/tut1_Q6_part2.py","file_name":"tut1_Q6_part2.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"629117899","text":"from behave import step\n\nfrom time import time\nfrom time import sleep\n\nfrom .utils import safe_get_element_text\n\nfrom .buttons import clicketi_click\n\nfrom .forms import clear_input_and_send_keys\n\n\ndef get_tag_modals(context):\n return context.browser.find_elements_by_css_selector('paper-dialog#tagsModal')\n\n\ndef get_open_tag_modal(context, wait_to_open=True):\n tag_modals = get_tag_modals(context)\n open_tag_modal = None\n # then wait until the modal is displayed\n timeout = time() + 10\n while time() < timeout:\n open_tag_modal = filter(lambda el: el.is_displayed(), tag_modals)\n if open_tag_modal:\n open_tag_modal = open_tag_modal[0]\n break\n sleep(1)\n\n if open_tag_modal and wait_to_open:\n timeout = time() + 10\n dimensions = open_tag_modal.size\n sleep(1)\n while time() < timeout:\n if dimensions['width'] == open_tag_modal.size['width'] and \\\n dimensions['height'] == open_tag_modal.size['height']:\n break\n else:\n dimensions = open_tag_modal.size\n sleep(1)\n return open_tag_modal\n\n\ndef get_tags_list(tag_modal):\n return tag_modal.find_elements_by_tag_name('tag-item')\n\n\ndef get_empty_tag(tag_modal):\n tags = get_tags_list(tag_modal)\n for tag in tags:\n inputs = tag.find_elements_by_tag_name('input')\n if not inputs[0].get_attribute('value').strip():\n return tag\n return None\n\n\ndef get_tag_with_key(tag_modal, key):\n key = key.lower()\n tags = get_tags_list(tag_modal)\n for tag in tags:\n inputs = tag.find_elements_by_tag_name('input')\n if inputs[0].get_attribute('value').strip().lower() == key:\n return tag\n return None\n\n\ndef set_key_and_value(tag, key, value):\n inputs = tag.find_elements_by_tag_name('input')\n clear_input_and_send_keys(inputs[0], key)\n clear_input_and_send_keys(inputs[1], value)\n\n\ndef close_tag(context, tag):\n clicketi_click(context, tag.find_element_by_tag_name('paper-icon-button'))\n\n\n@step(u'I remove all the previous tags')\ndef delete_previous_tags(context):\n for tag in get_tags_list(get_open_tag_modal(context, False)):\n close_tag(context, tag)\n\n\n@step(u'I add a tag with key \"{key}\" and value \"{value}\"')\ndef add_a_new_tag(context, key, value):\n tag_modal = get_open_tag_modal(context, False)\n tag = get_empty_tag(tag_modal)\n if not tag:\n context.execute_steps(u'When I click the button \"Add Tag\" in the tag menu')\n tag = get_empty_tag(tag_modal)\n set_key_and_value(tag, key, value)\n\n\n@step(u'I remove the tag with key \"{key}\"')\ndef close_some_tag(context, key):\n tag_modal = get_open_tag_modal(context, False)\n tag = get_tag_with_key(tag_modal, key)\n close_tag(context, tag)\n\n\n@step(u'I expect for the tag popup to {action} within {seconds} seconds')\ndef wait_for_tag_dialog(context, action, seconds):\n action = action.lower()\n if action not in ['open', 'close']:\n raise Exception('Unknown action')\n if action == 'open':\n if get_open_tag_modal(context):\n return True\n else:\n assert False, \"Tag modal is not open yet\"\n else:\n timeout = time() + 10\n while time() < timeout:\n if not filter(lambda el: el.is_displayed(), get_tag_modals(context)):\n return True\n sleep(1)\n assert False, \"Tag modal is not closed yet\"\n\n\n@step(u'I ensure that the \"{type_of_item}\" has the tags \"{tags}\" within {seconds} seconds')\ndef ensure_tags_are_present(context, type_of_item, tags, seconds):\n from .forms import get_edit_form\n form = get_edit_form(context, type_of_item)\n end_time = time() + int(seconds)\n while time() < end_time:\n existing_tags = form.find_elements_by_class_name('tag')\n expected_tags = dict(map(lambda t: (t.split(':')[0], t.split(':')[1]), tags.strip().lower().split(',')))\n for existing_tag in existing_tags:\n key = safe_get_element_text(existing_tag).lower().split('=')[0].strip()\n if key.endswith('\\n'):\n key = key[:-1]\n if key in expected_tags:\n del expected_tags[key]\n if len(expected_tags) == 0:\n return\n sleep(2)\n assert len(expected_tags) == 0, \"These keys are not available: %s\" % expected_tags.keys()\n","sub_path":"misttests/integration/gui/steps/tags.py","file_name":"tags.py","file_ext":"py","file_size_in_byte":4397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"152175747","text":"import numpy as np\nimport matplotlib.image as image\nimport matplotlib.pyplot as plt\nplt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签\nplt.rcParams['axes.unicode_minus']=False #用来正常显示负号\nimport matplotlib.colors as colors\n\n\ndef get_steps_range(line):\n num = len(line)\n max_nstep = 0\n\n #首先获得line中各段的起始坐标和长度\n start_list = [0]\n lenght_list = []\n n = 0\n for k in range(1,num):\n n += 1\n if line[k] != line[k-1]:\n lenght_list.append(n)\n start_list.append(k)\n n = 0\n lenght_list.append(n)\n\n #统计长度序列中保持不变的部分\n start_list_length = [0]\n lenght_list_lenght = []\n n = 0\n for k in range(1,len(lenght_list)):\n n += 1\n if abs(lenght_list[k] - lenght_list[k-1]) > 1:\n lenght_list_lenght.append(n)\n start_list_length.append(k)\n n = 0\n lenght_list_lenght.append(n)\n\n #计算总共有多少个color等级\n step_num = np.max(np.array(lenght_list_lenght))\n #计算等长序列最大个数在lenght_list_lenght对应的起始位置\n k = np.argmax(np.array(lenght_list_lenght))\n\n # 计算lenght_list_lenght起始坐标在lenght_list中的位置\n j = start_list_length[k]\n\n # lenght_list中的位置在整个line中的位置\n i_start_list = []\n for i in range(step_num + 1):\n i_start_list.append(start_list[j + i])\n\n return step_num,i_start_list\n\ndef get_color_map_from_picture(path,show = False):\n #im的第一维是y方向,第二维是x方向,第三维是rgb\n im = image.imread(path)\n #首先沿着x方向寻找\n rgb_to_1d = np.zeros((im.shape[0],im.shape[1]))\n rgb_to_1d = im[:,:,0] * 256* 256 + im[:,:,1] * 256 + im[:,:,2]\n\n color_type_num_y = np.zeros(im.shape[0])\n for y in range(im.shape[0]):\n line = rgb_to_1d[y,:] #line 是一条沿着x方向的线\n rgb_list = line.tolist()\n color_set = set(rgb_list)\n color_type_num_y[y] = len(color_set)\n\n color_type_num_x = np.zeros(im.shape[1])\n for x in range(im.shape[1]):\n line = rgb_to_1d[:,x] #line_x 是一条沿着y方向的线\n rgb_list = line.tolist()\n color_set = set(rgb_list)\n color_type_num_x[x] = len(color_set)\n\n #plt.plot(color_type_num_x)\n #plt.show()\n max_color_type_y = np.max(color_type_num_y)\n max_color_type_x = np.max(color_type_num_x)\n max_color_type = max(max_color_type_x,max_color_type_y)\n\n\n max_step_num = 0\n i_start = 0\n i_end = 0\n j_start = 0\n j_end = 0\n color_list = []\n\n ij_list = np.where(color_type_num_x == max_color_type)[0]\n if(len(ij_list) > 0):\n k_list_list = []\n k_list = [0]\n for k in range(1,len(ij_list)):\n if ij_list[k] - ij_list[k-1] == 1:\n k_list.append(k)\n else:\n k_list_list.append(k_list)\n k_list = [k]\n k_list_list.append(k_list)\n\n for k in range(len(k_list_list)):\n k_list =k_list_list[k]\n mid = int((ij_list[0] + ij_list[-1])/2)\n line = rgb_to_1d[:,mid]\n step_num,start_list = get_steps_range(line)\n if step_num > max_step_num:\n max_step_num = step_num\n i_start = ij_list[0]\n i_end = ij_list[-1]\n j_start = start_list[0]\n j_end = start_list[-1]\n color_list = []\n for i in range(step_num):\n start = start_list[-i-2]\n color_list.append(im[start,mid,:])\n\n\n #\n ij_list = np.where(color_type_num_y == max_color_type)[0]\n if len(ij_list) >0:\n k_list_list = []\n k_list = [0]\n for k in range(1,len(ij_list)):\n if ij_list[k] - ij_list[k-1] == 1:\n k_list.append(k)\n else:\n k_list_list.append(k_list)\n k_list = [k]\n k_list_list.append(k_list)\n\n for k in range(len(k_list_list)):\n k_list =k_list_list[k]\n mid = int((ij_list[0] + ij_list[-1])/2)\n line = rgb_to_1d[mid,:]\n step_num,start_list = get_steps_range(line)\n if step_num > max_step_num:\n max_step_num = step_num\n j_start = ij_list[0]\n j_end = ij_list[-1]\n i_start = start_list[0]\n i_end = start_list[-1]\n color_list = []\n for i in range(step_num):\n start = start_list[i]\n color_list.append(im[mid,start,:])\n\n if show:\n color_bar = im[j_start:j_end,i_start:i_end,:]\n plt.imshow(color_bar)\n plt.xticks([])\n plt.yticks([])\n plt.show()\n cmap = colors.ListedColormap(color_list, 'indexed')\n return cmap\n\n","sub_path":"nmc_verification/nmc_vf_base/tool/color_tools.py","file_name":"color_tools.py","file_ext":"py","file_size_in_byte":4872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"316294645","text":"'''\nhttps://www.interviewbit.com/problems/vertical-order-traversal-of-binary-tree/\nVertical Order traversal of Binary Tree\n\nGiven a binary tree, print a vertical order traversal of it.\n\nExample :\nGiven binary tree:\n\n 6\n / \\\n 3 7\n / \\ \\\n 2 5 9\nreturns\n\n[\n [2],\n [3],\n [6 5],\n [7],\n [9]\n]\n\n\nNote : If 2 Tree Nodes shares the same vertical level then the one with lesser depth will come first.\n'''\n\n# Definition for a binary tree node\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nfrom collections import defaultdict\n\n\nclass Solution:\n # @param A : root node of tree\n # @return a list of list of integers\n def verticalOrderTraversal(self, A):\n if not A:\n return []\n li = [(A, 0)]\n dic = defaultdict(list)\n while li: # level-order traversal\n n, l = li.pop(0)\n dic[l].append(n.val)\n if n.left:\n li.append((n.left, l - 1))\n if n.right:\n li.append((n.right, l + 1))\n return [dic[k] for k in sorted(dic)]\n\n\n","sub_path":"vertical_order_traversal_of_binary_tree.py","file_name":"vertical_order_traversal_of_binary_tree.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"43182509","text":"import unittest\nimport requests\nimport json\nfrom Global_base import global_base\nfrom parameterized import parameterized\n\n\nclass Init(unittest.TestCase):\n \"\"\"初始化接口\"\"\"\n\n def setUp(self):\n self.url = global_base.DefTool.url(self, '/usercenter/sys/init')\n\n @parameterized.expand([\n ('参数正确,初始化成功', \"000000\", \"\", \"7f8af6d4b932a77e\", \"90:2B:D2:C6:2C:8F\", \"HONOR\", \"5860656\", \"56910413824\",\n \"38484373504\",\n \"2.5.1\", \"14\", \"868777047018746\", \"1\", \"1003\", \"cpjz002\", \"\", \"cjhj\"),\n ])\n def test_init(self, name, imsi, serialnumber, androidid, mac, brand, memory, totalspace, availablespace, ver,\n verno, deviceId, deviceType, productId, channelId, deviceToken, mjbname):\n \"\"\"初始化接口\"\"\"\n pa = {\"imsi\": imsi, \"serialnumber\": serialnumber, \"androidid\": androidid, \"mac\": mac, \"brand\": brand,\n \"memory\": memory, \"totalspace\": totalspace, \"availablespace\": availablespace, \"ver\": ver,\n \"verno\": verno, \"deviceId\": deviceId, \"deviceType\": deviceType, \"productId\": productId,\n \"channelId\": channelId, \"deviceToken\": deviceToken, \"mjbname\": mjbname}\n self.params = global_base.DefTool().payload(**pa)\n self.result = requests.post(url=self.url, data=self.params).json()\n self.assertEqual(self.result[\"msg\"], \"ok\")\n self.assertEqual(self.result[\"code\"], 200)\n\n def tearDown(self):\n print(\"请求地址为{}\".format(self.url))\n print(\"请求参数为{}\".format(json.dumps(self.params, indent=2, sort_keys=False, ensure_ascii=False)))\n print(\"请求结果为:{}\".format(json.dumps(self.result, indent=2, sort_keys=False, ensure_ascii=False)))\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"interface/app/init_test_test.py","file_name":"init_test_test.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"479366027","text":"def fun():\n result = 0\n words = [x.replace('\"', '') for x in\n open(\"//home//liam//Desktop//Python//Euler//Data files//Problem42_words.txt\", \"r\").read().split(',')]\n alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n for word in words:\n value = sum([alphabet.index(y) + 1 for y in word])\n if (((value * 8) + 1) ** 0.5) % 1.0 == 0: result += 1\n return result\n\n\nif __name__ == '__main__':\n print(fun())\n","sub_path":"Euler/Problems 41 - 50/Problem_42.py","file_name":"Problem_42.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"252730546","text":"\"\"\"Module defining sets of FileParsers to be used by the VaspParser\"\"\"\n\nfrom aiida_vasp.io.doscar import DosParser\nfrom aiida_vasp.io.eigenval import EigParser\nfrom aiida_vasp.io.kpoints import KpParser\nfrom aiida_vasp.io.outcar import OutcarParser\nfrom aiida_vasp.io.vasprun import VasprunParser\nfrom aiida_vasp.io.chgcar import ChgcarParser\nfrom aiida_vasp.io.wavecar import WavecarParser\nfrom aiida_vasp.io.poscar import PoscarParser\n\nFILE_PARSER_SETS = {\n 'default': {\n 'DOSCAR': {\n 'parser_class': DosParser,\n 'is_critical': False,\n 'status': 'Unknown'\n },\n 'EIGENVAL': {\n 'parser_class': EigParser,\n 'is_critical': False,\n 'status': 'Unknown'\n },\n 'IBZKPT': {\n 'parser_class': KpParser,\n 'is_critical': False,\n 'status': 'Unknown'\n },\n 'OUTCAR': {\n 'parser_class': OutcarParser,\n 'is_critical': False,\n 'status': 'Unknown'\n },\n 'vasprun.xml': {\n 'parser_class': VasprunParser,\n 'is_critical': True,\n 'status': 'Unknown'\n },\n 'CHGCAR': {\n 'parser_class': ChgcarParser,\n 'is_critical': False,\n 'status': 'Unknown'\n },\n 'WAVECAR': {\n 'parser_class': WavecarParser,\n 'is_critical': False,\n 'status': 'Unknown'\n },\n 'CONTCAR': {\n 'parser_class': PoscarParser,\n 'is_critical': False,\n 'status': 'Unknown'\n },\n },\n}\n\n\nclass ParserSettings(object):\n \"\"\"\n Settings object for the VaspParser.\n\n :param settings: Dict with the 'parser_settings'.\n :param default_settings: Dict with default settings.\n\n This provides the following properties to other components of the VaspParser:\n\n * nodes: A list with all requested output nodes.\n\n * parser_definitions: A Dict with the FileParser definitions.\n \"\"\"\n\n def __init__(self, settings, default_settings=None):\n\n if settings is None:\n settings = {}\n self._settings = settings\n if default_settings:\n self.update_with(default_settings)\n\n self.nodes = []\n self.set_nodes()\n\n self.parser_definitions = {}\n self.set_parser_definitions(self._settings.get('file_parser_set'))\n\n def set_nodes(self):\n \"\"\"Set the 'nodes' card of a settings object.\"\"\"\n # Find all the nodes, that should be added.\n nodes = []\n for key, value in self._settings.items():\n if not key.startswith('add_'):\n # only keys starting with 'add_' are relevant as nodes.\n continue\n if not value:\n # The quantity should not be added.\n continue\n nodes.append(key[4:])\n\n self.nodes = nodes\n\n def update_with(self, update_dict):\n \"\"\"Selectively update keys from one Dictionary to another.\"\"\"\n for key, value in update_dict.items():\n if key not in self._settings:\n self._settings[key] = value\n\n def get(self, item, default=None):\n return self._settings.get(item, default)\n\n def set_parser_definitions(self, file_parser_set='default'):\n \"\"\"Load the parser definitions.\"\"\"\n from copy import deepcopy\n\n if file_parser_set not in FILE_PARSER_SETS:\n return\n for file_name, parser_dict in FILE_PARSER_SETS.get(file_parser_set).items():\n self.parser_definitions[file_name] = deepcopy(parser_dict)\n","sub_path":"aiida_vasp/parsers/parser_settings.py","file_name":"parser_settings.py","file_ext":"py","file_size_in_byte":3609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"260700454","text":"\n# @Title: 分隔链表 (Partition List)\n# @Author: 18015528893\n# @Date: 2021-02-13 11:56:58\n# @Runtime: 44 ms\n# @Memory: 15 MB\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def partition(self, head: ListNode, x: int) -> ListNode:\n dummy_left = ListNode(next=head)\n dummy_right = ListNode()\n p = dummy_right\n\n pre = dummy_left\n cur = dummy_left.next\n while cur:\n if cur.val >= x:\n pre.next = cur.next\n cur.next = None\n p.next = cur\n p = p.next\n else:\n pre = pre.next\n cur = pre.next\n pre.next = dummy_right.next\n return dummy_left.next\n\n","sub_path":"Problemset/partition-list/partition-list.py","file_name":"partition-list.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"156116051","text":"from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, orm, DateTime, inspect\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker, relationship\nfrom datetime import datetime, timedelta\nfrom sqlalchemy.schema import Table\nfrom sqlalchemy.schema import MetaData\n\n# inclusao de classe geral de personal data\nfrom sqlalchemy.ext.declarative import declared_attr\n\n\nengine = create_engine('sqlite:///user.db', echo=False) # ('sqlite:///:memory:', echo=True) --- coloca a BD em memoria se mudar para algo tipo user.db cria em file na dir\n\nmeta = MetaData()\n\n\n\n\n\n\n\n#ve as tabelas que tao na BD APAGAR\nprint(\"\\n\\n\\n\\nTABELAS NA BD\\n\")\nprint (engine.table_names())\nprint(\"\\n\\n\\n\\nFIM TABELAS NA BD\\n\")\n\n\n\ndef func(t):\n person_table = Table(t, meta, autoload=True, autoload_with=engine)\n print(\"------------------\")\n print(person_table)\n for fkey in person_table.foreign_keys:\n #chama func de grafo func(aux)\n print(fkey)\n fkey=str(fkey).split(\".\")[0]\n aux=(fkey[13:])\n print(aux.capitalize())\n\n\n\n\n\n################################################################################\n#FUNCAO DE CREACAO DE GRAFOS\n################################################################################\n\ngrafo={}\ndef creategraph(t):\n table = Table(t, meta, autoload=True, autoload_with=engine)\n print(\"------------------\")\n print(\"Entrou na funcao com \"+str(table))\n print(\"------------------\")\n neighbors=[]\n for fkey in table.foreign_keys:\n fkey=str(fkey).split(\".\")[0]\n aux=(fkey[13:])\n print(\"foreign key \"+aux)\n neighbors.append(aux)\n print(\"\\n\\n-----neighbours-----\")\n print(neighbors)\n grafo[str(table)]=neighbors\n\n\n\n\ndef find_path(graph, start, end, path=[]):\n path = path + [start]\n if start == end:\n return path\n if not graph.has_key(start):\n return None\n for node in graph[start]:\n if node not in path:\n newpath = find_path(graph, node, end, path)\n if newpath: return newpath\n return None\n\ndef find_all_paths(graph, start, end, path=[]):\n path = path + [start]\n if start == end:\n return [path]\n if not graph.has_key(start):\n return []\n paths = []\n for node in graph[start]:\n if node not in path:\n newpaths = find_all_paths(graph, node, end, path)\n for newpath in newpaths:\n paths.append(newpath)\n return paths\n\n\ndef find_shortest_path(graph, start, end, path=[]):\n path = path + [start]\n if start == end:\n return path\n if not graph.has_key(start):\n return None\n shortest = None\n for node in graph[start]:\n if node not in path:\n newpath = find_shortest_path(graph, node, end, path)\n if newpath:\n if not shortest or len(newpath) < len(shortest):\n shortest = newpath\n return shortest\n\n\nfor t in engine.table_names():\n #print(\"TABELA - \"+t)\n #func(t)\n creategraph(t)\nprint(\"\\n\\n--------Grafo---------\")\nprint (grafo)\nprint(\"\\n\\n--------TODOS CAMINHOS---------\")\nprint(find_all_paths(grafo, 'checkin', 'person'))\nprint(\"\\n\\n--------CAMINHO MAIS PEQUENO---------\")\nprint(find_shortest_path(grafo, 'checkin', 'restaurant'))\nprint(\"\\n\\n--------UM CAMINHO---------\")\nprint(find_path(grafo, 'checkin', 'person'))\n\n\n################################################################################\n#TESTES\n###############################################################################\n# levels=0\n# etc=\"alo\"\n# results={}\n# results[levels]=etc\n# for x, y in results.items():\n# print(x,y)\n","sub_path":"check_tables.py","file_name":"check_tables.py","file_ext":"py","file_size_in_byte":3708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"266235523","text":"import os\nimport argparse\nimport shutil\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport numpy as np\nimport math\nimport sys\nimport datetime\nnp.set_printoptions(threshold=sys.maxsize)\n\nfrom lib import Constant\nfrom lib.utils import codeword_threshold, find_index\n\nparser = argparse.ArgumentParser()\n\n# learning parameters\nparser.add_argument('-learning_rate', type = float, default=0.001)\nparser.add_argument('-momentum', type=float, default=0.9)\nparser.add_argument('-num_epoch', type=int, default=4000)\nparser.add_argument('-epoch_start', type=int, default=0)\nparser.add_argument('-num_batch', type=int, default=200)\nparser.add_argument('-weight_decay', type=float, default=0.0001)\nparser.add_argument('-eval_freq', type=int, default=50)\nparser.add_argument('-eval_start', type=int, default=2000)\nparser.add_argument('-print_freq_ep', type=int, default=50)\n\nparser.add_argument('-batch_size_snr_train', type=int, default=30)\nparser.add_argument('-batch_size_snr_validate', type=int, default=600)\n\nparser.add_argument('-prob_start', type=float, default=0.1)\nparser.add_argument('-prob_up', type=float, default=0.01)\nparser.add_argument('-prob_step_ep', type=int, default=50)\n\n# storing path\nparser.add_argument('-result', type=str, default='result.txt')\nparser.add_argument('-checkpoint', type=str, default='./checkpoint.pth.tar')\nparser.add_argument('-resume', default='', type=str, metavar='PATH', \n help='path to latest checkpoint (default:none)')\n\n# PR-NN parameters\nparser.add_argument('-eval_info_length', type=int, default=1000000)\nparser.add_argument('-dummy_length_start', type=int, default=5)\nparser.add_argument('-dummy_length_end', type=int, default=5)\nparser.add_argument('-eval_length', type=int, default=10)\nparser.add_argument('-overlap_length', type=int, default=20)\n\n# RNN parameters\nparser.add_argument('-input_size', type=int, default=5)\nparser.add_argument('-rnn_input_size', type=int, default=5)\nparser.add_argument('-rnn_hidden_size', type=int, default=50)\nparser.add_argument('-output_size', type=int, default=1)\nparser.add_argument('-rnn_layer', type=int, default=4)\nparser.add_argument('-rnn_dropout_ratio', type=float, default=0)\n\n# channel parameters\nparser.add_argument('-snr_start', type=float, default=8.5)\nparser.add_argument('-snr_stop', type=float, default=10.5)\nparser.add_argument('-snr_step', type=float, default=0.5)\n\ndef main():\n global args\n args = parser.parse_known_args()[0]\n \n # cuda device\n os.environ['CUDA_VISIBLE_DEVICES'] = \"0\"\n if torch.cuda.is_available():\n device = torch.device(\"cuda\")\n \n # write the results\n dir_name = './output_' + datetime.datetime.strftime(datetime.datetime.now(), \n '%Y-%m-%d_%H:%M:%S') + '/'\n os.mkdir(dir_name)\n result_path = dir_name + args.result\n result = open(result_path, 'w+')\n \n # data loader\n (encoder_dict, channel_dict, dummy_dict_start, \n dummy_dict_end, dummy_dict_end_eval) = Constant()\n data_class = Dataset(args, device, encoder_dict, channel_dict, \n dummy_dict_start, dummy_dict_end)\n \n snr_point = int((args.snr_stop-args.snr_start)/args.snr_step+1)\n \n # model\n model = Model(args, device).to(device)\n \n # criterion and optimizer\n optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), \n lr=args.learning_rate, \n eps=1e-08, \n weight_decay=args.weight_decay)\n \n # optionally resume from a checkpoint\n if args.resume:\n if os.path.isfile(args.resume):\n print(\"=> loading checkpoint '{}'\".format(args.resume))\n checkpoint = torch.load(args.resume)\n args.epoch_start = checkpoint['epoch']\n model.load_state_dict(checkpoint['state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n print(\"=> loaded checkpoint '{}' (epoch {})\"\n .format(args.resume, checkpoint['epoch']))\n else:\n print(\"=> no checkpoint found at '{}'\".format(args.resume))\n\n \n # train and validation\n \n prob_start_ori = 0.1\n if args.epoch_start > args.eval_start:\n prob_start = 0.5\n else:\n prob_start = prob_start_ori + (args.prob_up * \n (args.epoch_start // args.prob_step_ep))\n \n prob_end = 0.5\n prob_step = int((prob_end - prob_start_ori) / args.prob_up)\n prob_ep_list = list(range(prob_step*args.prob_step_ep, 0, -args.prob_step_ep))\n prob = prob_start\n for epoch in range(args.epoch_start, args.num_epoch):\n \n # increase the probability each 10 epochs\n if epoch in prob_ep_list:\n prob += args.prob_up\n \n # train and validate\n train_loss = train(data_class, prob, model, optimizer, epoch, device)\n valid_loss, ber = validate(data_class, prob, channel_dict, dummy_dict_start, \n dummy_dict_end_eval, model, epoch, device)\n \n result.write('epoch %d \\n' % epoch)\n result.write('information prob.'+str(prob)+'\\n')\n result.write('Train loss:'+ str(train_loss)+'\\n')\n result.write('Validation loss:'+ str(valid_loss)+'\\n')\n if (epoch >= args.eval_start and epoch % args.eval_freq == 0):\n result.write('-----SNR[dB]:'+str(ber)+'\\n')\n else:\n result.write('-----:no evaluation'+'\\n')\n result.write('\\n')\n \n torch.save({\n 'epoch': epoch+1,\n 'arch': 'rnn',\n 'state_dict': model.state_dict(),\n 'optimizer': optimizer.state_dict(),\n }, args.checkpoint)\n\n## Dataset: generate dataset for neural network\nclass Dataset(object):\n def __init__(self, args, device, encoder_machine, channel_machine, \n dummy_dict_start, dummy_dict_end):\n self.args = args\n self.device = device\n \n self.encoder_machine = encoder_machine\n self.num_state = len(self.encoder_machine)\n self.num_input_sym_enc = self.encoder_machine[1]['input'].shape[1]\n self.num_out_sym = self.encoder_machine[1]['output'].shape[1]\n self.code_rate = self.num_input_sym_enc / self.num_out_sym\n \n self.channel_machine = channel_machine\n self.ini_state_channel = self.channel_machine['ini_state']\n self.num_input_sym_channel = int(self.channel_machine['in_out'].shape[1]/2)\n \n self.dummy_dict_start = dummy_dict_start\n self.dummy_dict_end = dummy_dict_end\n\n def data_generation_train(self, prob, batch_size_snr):\n '''\n training/testing data(with sliding window) and label\n output: float torch tensor (device)\n '''\n \n batch_size = int(((args.snr_stop-args.snr_start)/\n args.snr_step+1)*batch_size_snr)\n block_length = (args.dummy_length_start + args.eval_length + \n args.overlap_length + args.dummy_length_end)\n info_length = math.ceil((block_length - args.dummy_length_end)\n /self.num_out_sym)*self.num_input_sym_enc\n \n info = np.random.choice(np.arange(0, 2), size = (batch_size_snr, info_length), \n p=[1-prob, prob])\n \n data_bt, label_bt = (np.zeros((batch_size, block_length)), \n np.zeros((batch_size, args.eval_length+args.overlap_length)))\n \n for i in range(batch_size_snr):\n codeword = (self.precoding(self.encoder_constrain(info[i : i+1, :]))\n [:, :block_length - args.dummy_length_end])\n codeword_isi, state = self.e2pr4_channel(codeword)\n codeword_isi_end = np.concatenate((codeword_isi, \n self.dummy_dict_end[state]), axis=1)\n \n for idx in np.arange(0, (args.snr_stop-args.snr_start)/args.snr_step+1):\n label_bt[int(idx*batch_size_snr+i) : \n int(idx*batch_size_snr+i+1), \n :] = (codeword[:, args.dummy_length_start:\n block_length-args.dummy_length_end])\n \n codeword_noisy = self.awgn(codeword_isi_end[:, args.dummy_length_start:], \n args.snr_start+idx*args.snr_step)\n \n data_bt[int(idx*batch_size_snr+i) : int(idx*batch_size_snr+i+1), \n :args.dummy_length_start] = codeword_isi_end[:, :args.dummy_length_start]\n data_bt[int(idx*batch_size_snr+i) : int(idx*batch_size_snr+i+1), \n args.dummy_length_start:] = codeword_noisy\n \n data_bt = self.sliding_shape(torch.from_numpy(data_bt).float().to(self.device))\n label_bt = (torch.from_numpy(label_bt).float()).to(self.device)\n \n return data_bt, label_bt\n \n def data_generation_eval(self, snr):\n '''\n evaluation data(without sliding window) and label\n output: float torch tensor data_eval, numpy array label_eval\n '''\n \n info = np.random.randint(2, size = (1, args.eval_info_length))\n codeword = self.precoding(self.encoder_constrain(info))\n codeword_isi, _ = self.e2pr4_channel(codeword)\n codeword_noisy = self.awgn(codeword_isi, snr)\n \n data_eval = torch.from_numpy(codeword_noisy).float().to(self.device)\n label_eval = codeword\n \n return data_eval, label_eval\n \n def sliding_shape(self, x):\n '''\n Input: (1, length) torch tensor\n Output: (input_size, length) torch tensor\n Mapping: sliding window for each time step\n '''\n \n batch_size, time_step = x.shape\n zero_padding_len = args.input_size - 1\n x = torch.cat(((torch.zeros((batch_size, zero_padding_len))).to(self.device), x), 1)\n y = torch.zeros(batch_size, time_step, args.input_size)\n for bt in range(batch_size):\n for time in range(time_step):\n y[bt, time, :] = x[bt, time:time+args.input_size]\n return y.float().to(self.device)\n \n def encoder_constrain(self, info):\n '''\n Input: (1, length) array\n Output: (1, length / rate) array\n Mapping: Encoder (Markov Chain)\n '''\n \n info_len = np.size(info, 1)\n codeword = np.zeros((1, int(info_len/self.code_rate)))\n \n state = np.random.randint(low=1, high=self.num_state+1, size=1)[0]\n for i in range(0, info_len, self.num_input_sym_enc):\n # start symbol and state\n idx = int(i / self.num_input_sym_enc)\n input_sym = info[:, i:i+self.num_input_sym_enc][0]\n # input idx\n idx_in = find_index(self.encoder_machine[state]['input'], input_sym)\n # output sym and next state\n output_sym = self.encoder_machine[state]['output'][idx_in, :]\n state = self.encoder_machine[state]['next_state'][idx_in, 0]\n codeword[:, self.num_out_sym*idx : self.num_out_sym*(idx+1)] = output_sym\n \n return codeword.astype(int)\n \n def precoding(self, z):\n '''\n Input: (1, length) array\n Output: (1, length) array\n Mapping: x = (1 / 1 + D) z (mod 2)\n x_{-1} = 0\n '''\n \n length = np.size(z, 1)\n x = np.zeros((1, length))\n x[0, 0] = z[0, 0]\n for i in range(1, length):\n x[0, i] = x[0, i-1] + z[0, i]\n return x % 2\n \n def e2pr4_channel(self, x):\n '''\n Input: (1, length) array\n Output: (1, length) array, ending state\n Mapping: channel state machine\n '''\n \n length = x.shape[1]\n y = np.zeros((1, length))\n \n # Memory channel\n state = self.ini_state_channel\n for i in range(0, length, self.num_input_sym_channel):\n set_in = np.where(self.channel_machine['state_machine'][:, 0]==state)[0]\n idx_in = set_in[np.where(self.channel_machine['in_out'][set_in, 0]==x[:, i])[0]]\n y[:, i] = self.channel_machine['in_out'][idx_in, 1]\n state = self.channel_machine['state_machine'][idx_in, 1]\n \n return y, state[0]\n \n def awgn(self, x, snr):\n '''\n AWGN channel\n '''\n scaling_para = 0.25\n sigma = np.sqrt(scaling_para * 10 ** (- snr * 1.0 / 10))\n return x + sigma * np.random.normal(0, 1, x.shape)\n \nclass Model(nn.Module):\n def __init__(self, args, device):\n super(Model, self).__init__()\n \n '''\n time_step: total number of time steps in RNN\n fc_length: input length to linear layer\n dec_input: input linear network\n dec_rnn: rnn network\n dec_output: output linear network\n '''\n \n self.args = args\n self.device = device\n self.time_step = (args.dummy_length_start + args.eval_length \n + args.overlap_length + args.dummy_length_end)\n self.fc_length = args.eval_length + args.overlap_length\n self.dec_input = torch.nn.Linear(args.input_size, \n args.rnn_input_size)\n self.dec_rnn = torch.nn.GRU(args.rnn_input_size, \n args.rnn_hidden_size, \n args.rnn_layer, \n bias=True, \n batch_first=True,\n dropout=args.rnn_dropout_ratio, \n bidirectional=True)\n \n self.dec_output = torch.nn.Linear(2*args.rnn_hidden_size, args.output_size)\n \n def forward(self, x):\n batch_size = x.size(0)\n dec = torch.zeros(batch_size, self.fc_length, \n args.output_size).to(self.device)\n \n x = self.dec_input(x)\n y, _ = self.dec_rnn(x)\n y_dec = y[:, args.dummy_length_start : \n self.time_step-args.dummy_length_end, :]\n\n dec = torch.sigmoid(self.dec_output(y_dec))\n \n return torch.squeeze(dec, 2)\n \ndef train(data_class, prob, model, optimizer, epoch, device):\n\n # switch to train mode\n model.train()\n \n train_loss = 0\n for batch_idx in range(args.num_batch):\n # data\n data_train, label_train = (data_class.data_generation_train\n (prob, args.batch_size_snr_train))\n \n # network\n optimizer.zero_grad()\n output = model(data_train)\n loss = loss_func(output, label_train)\n \n # compute gradient and do gradient step\n loss.backward()\n optimizer.step()\n train_loss += loss.item()\n \n # print\n if (epoch % args.print_freq_ep == 0 and \n (batch_idx+1) % args.num_batch == 0):\n avg_loss = train_loss / args.num_batch\n print('Train Epoch: {} (w.p. {:.2f}) - Loss: {:.6f}, Avg Loss: {:.6f}'\n .format(epoch+1, prob, train_loss, avg_loss))\n \n return loss.item()\n \ndef validate(data_class, prob, channel_dict, dummy_dict_start, \n dummy_dict_end_eval, model, epoch, device):\n \n np.random.seed(12345)\n # switch to evaluate mode\n model.eval()\n \n # data\n data_val, label_val = (data_class.data_generation_train\n (prob, args.batch_size_snr_validate))\n \n # network\n with torch.no_grad():\n output = model(data_val)\n valid_loss = loss_func(output, label_val)\n \n if epoch % args.print_freq_ep == 0:\n print('Validation Epoch: {} - Loss: {:.6f}'.\n format(epoch+1, valid_loss.item()))\n \n # evaluation for a very long sequence\n ber = np.ones((1, int((args.snr_stop-args.snr_start)/args.snr_step+1)))\n \n if (epoch >= args.eval_start) & (epoch % args.eval_freq == 0):\n for idx in np.arange(0, int((args.snr_stop-args.snr_start)/args.snr_step+1)):\n data_eval, label_eval = (data_class.data_generation_eval\n (args.snr_start+idx*args.snr_step))\n dec = evaluation(data_eval, dummy_dict_start, dummy_dict_end_eval, \n channel_dict, data_class, model, device)\n ber[0, idx] = (np.sum(np.abs(dec.cpu().numpy() - label_eval))\n /label_eval.shape[1])\n print('Validation Epoch: {} ber: {}'.format(epoch+1, ber))\n \n return valid_loss.item(), ber\n \ndef evaluation(x, dummy_dict_start, dummy_dict_end_eval,\n channel_dict, data_class, model, device):\n # paras\n truncation_len = args.eval_length + args.overlap_length\n state_num = channel_dict['state_label'].shape[1]\n x_len = x.shape[1]\n \n # add dummy bits to x\n tail_bit = (torch.zeros((1, args.overlap_length))).to(device)\n x = torch.cat((x, tail_bit), 1)\n \n # dummy ending values for evaluation\n dummy_dict_end_eval = dummy_dict_end_eval.to(device)\n \n state = 0\n dec = torch.zeros((1, 0)).float().to(device)\n \n for idx in range(0, x_len, args.eval_length):\n # decode one truncation block\n truncation = x[:, idx : idx+truncation_len]\n truncation_block = torch.cat((torch.cat((dummy_dict_start[state].\n to(device), truncation), 1), \n dummy_dict_end_eval), 1)\n truncation_in = data_class.sliding_shape(truncation_block)\n with torch.no_grad():\n dec_block = codeword_threshold(model(truncation_in)\n [:, :args.eval_length])\n # concatenate the decoding codeword\n dec = torch.cat((dec, dec_block), 1)\n \n # find the initial state in block\n state_label = dec[:, -state_num:]\n state = find_index(channel_dict['state_label'], state_label[0])\n\n if state == None:\n state = 0\n \n return dec\n\ndef loss_func(output, label):\n \n return F.binary_cross_entropy(output, label).cuda()\n\ndef save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):\n torch.save(state, filename)\n\nif __name__ == '__main__':\n main()\n","sub_path":"individual/main_awgn.py","file_name":"main_awgn.py","file_ext":"py","file_size_in_byte":18549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"236602302","text":"class Solution:\n def findMaxConsecutiveOnes(self, nums: List[int]) -> int:\n maxOnes, c = 0, 0 \n for num in nums:\n if num == 1:\n c += 1\n maxOnes = max(maxOnes, c)\n else:\n c = 0\n return maxOnes\n","sub_path":"leetcode/485. Max Consecutive Ones/soln.py","file_name":"soln.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"159774478","text":"#!/usr/bin/env python3\n#FOODY_SCRAPY\nimport webbrowser\nfrom bs4 import BeautifulSoup as bs\nimport urllib.request\nimport json\nimport mysql.connector\nimport re\nimport time\nimport sys\n\ncnx = mysql.connector.connect(user='root',\n password='London!2019',\n host='localhost',\n database='dulcisinfundo_database')\ncursor = cnx.cursor()\n\ndef get_recipes_data(page):\n raw_soup = urllib.request.urlopen(page).read().decode(\"utf8\")\n time.sleep(5)\n soup = bs(raw_soup, \"html.parser\")\n i=0\n for article in soup.find_all('article'):\n # if div.get('class') != None:\n # if div.attrs['class'] == ['gz-image-recipe', 'gz-video']:#\n recipe_page_soup = bs(urllib.request.urlopen(article.a.attrs['href']).read().decode(\"utf8\"), \"html.parser\")\n time.sleep(3)\n for script in recipe_page_soup.find_all('script'):\n if script.get('type') != None:\n if script.attrs['type'] == 'application/ld+json':\n json_text = json.loads(script.string)\n json_keys = json_text.keys()\n keys = []\n for key in json_keys:\n key = key.replace('@', '')\n keys.append(key)\n json_values = json_text.values()\n values = []\n for value in json_values:\n if type(value) is list or type(value) is dict:\n value = str(value)\n value = value.replace('\\'', '\\\\\\'')\n value = value.replace('\\\"', '\\\\\\\"')\n values.append(value)\n else:\n value = str(value)\n value = value.replace('\\'', '\\\\\\'')\n value = value.replace('\\\"', '\\\\\\\"')\n values.append(value)\n\n #IMPORT JSON_DATA TO DATABASE\n # text_file = open( r'C:\\Users\\Pats\\Desktop\\My Python Programs\\Work in progress\\Webscrape\\Data extracted\\raw_data.txt', 'w')\n # text_file.write(str(json_text))\n # text_file.write('\\n\\n')\n # text_file.close()\n\n # regex = re.compile(r'\\\"name\\\":\\\"(.*?)\\\",\\\"author\\\":')\n # recipe_name = re.findall(regex, str(json_text))\n #\n # text_file = open( r'C:\\Users\\Pats\\Desktop\\My Python Programs\\Work in progress\\Webscrape\\Data extracted\\recipe_names.txt', 'w')\n # text_file.write(','.join(recipe_name)+'\\n\\n')\n # text_file.close()\n # print(str(recipe_name))\n try:\n cursor.execute(\"INSERT INTO recipes_data (\"+\", \".join(keys)+\")\"\n \"VALUES (\\\"\"+\"\\\", \\\"\".join(values)+\"\\\");\")\n cnx.commit()\n time.sleep(2)\n i+=1\n print(i)\n except mysql.connector.errors.ProgrammingError as e:\n e = str(e)\n regex=re.compile(r'\\'(.*?)\\' in')\n new_column = re.findall(regex, e)\n cursor.execute(\"ALTER TABLE recipes_data \"\n \"ADD \"+str(new_column[0])+\" varchar(500);\")\n cnx.commit()\n time.sleep(3)\n\nmain_page='https://www.giallozafferano.it/ricette-cat/page1/Dolci-e-Desserts/'\nraw_soup=urllib.request.urlopen(main_page).read().decode('utf8')\nsoup=bs(raw_soup,'html.parser')\nfor span in soup.find_all('span'):\n if span.get('class') != None:\n if span.attrs['class'] == ['disabled', 'total-pages']:\n total_pages = span.string\ni=1\nfor x in range(int(total_pages)):\n if i == 1:\n # regex=re.compile(r'/page(.*?)/')\n # page=regex.sub('/', main_page)\n # print('___________START___________\\n'+page)\n # get_recipes_data(page)\n # print('___________END___________\\n')\n i+=1\n if i > 70:\n regex=re.compile(r'/page(.*?)/')\n page=regex.sub('/page'+str(i)+'/', main_page)\n print('___________START___________\\n'+page)\n get_recipes_data(page)\n print('___________END___________\\n')\n i+=1\n\n else:\n # regex=re.compile(r'/page(.*?)/')\n # page=regex.sub('/page'+str(i)+'/', main_page)\n # print('___________START___________\\n'+page)\n # get_recipes_data(page)\n # print('___________END___________\\n')\n i+=1\n","sub_path":"Webscrape_v2.py","file_name":"Webscrape_v2.py","file_ext":"py","file_size_in_byte":5126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"222948379","text":"from cassandra.auth import PlainTextAuthProvider\nimport config as cfg\nfrom cassandra.query import BatchStatement, SimpleStatement\nfrom prettytable import PrettyTable\nimport time\nimport ssl\nimport cassandra\nfrom cassandra.cluster import Cluster, BatchStatement\nfrom cassandra.policies import *\nfrom ssl import PROTOCOL_TLSv1_2, SSLContext, CERT_NONE\nfrom requests.utils import DEFAULT_CA_BUNDLE_PATH\nimport uuid\nfrom json import dumps\n\ndef PrintTable(rows):\n t = PrettyTable(['player_id', 'event', 'country', 'session_id', 'ts'])\n for r in rows:\n t.add_row([r.player_id, r.event, r.country, r.session_id, r.ts])\n print (t)\n\n#<authenticateAndConnect>\nssl_context = SSLContext(PROTOCOL_TLSv1_2)\nssl_context.verify_mode = CERT_NONE\nauth_provider = PlainTextAuthProvider(username=cfg.config['username'], password=cfg.config['password'])\ncluster = Cluster([cfg.config['contactPoint']], port = cfg.config['port'], auth_provider=auth_provider,ssl_context=ssl_context)\nsession = cluster.connect()\n#</authenticateAndConnect>\n\n#<createKeyspace>\nprint (\"\\nCreating Keyspace\")\nsession.execute('CREATE KEYSPACE IF NOT EXISTS uprofile WITH replication = {\\'class\\': \\'NetworkTopologyStrategy\\', \\'datacenter\\' : \\'1\\' }')\n#</createKeyspace>\n\n#<createTable>\nprint (\"\\nCreating Table\")\nsession.execute(\n 'CREATE TABLE IF NOT EXISTS uprofile.events_by_user(player_id text, ts timestamp, country text, event text, session_id uuid, PRIMARY KEY((player_id, session_id), ts, event)) WITH CLUSTERING ORDER BY (\"ts\" DESC, \"event\" ASC)')\n#</createTable>\n\n#<insertData>\nsession.execute(\"INSERT INTO uprofile.events_by_user (player_id, event, country, session_id, ts) VALUES (%s,%s,%s,%s,%s)\", [\n \"0a2d12a1a7e145de8bae44c0c6e06629\", 'start', 'FI', '4a0c43c9-c43a-42ff-ba55-67563dfa35d4', '2016-12-02T12:48:05.520022'])\nsession.execute(\"INSERT INTO uprofile.events_by_user (player_id, event, session_id, ts) VALUES (%s,%s,%s,%s)\", [\n \"0a2d12a1a7e145de8bae44c0c6e06629\", 'end', '4a0c43c9-c43a-42ff-ba55-67563dfa35d4', '2016-12-02T12:49:05.520022'])\nsession.execute(\"INSERT INTO uprofile.events_by_user (player_id, event , country, session_id, ts) VALUES (%s,%s,%s,%s,%s)\", [\n \"0a2d12a1a7e145de8bae44c0c6e06630\", 'start', 'xx', '4a0c43c9-c43a-42ff-ba55-67563dfa35d5', '2016-12-02T12:50:05.520022'])\nsession.execute(\"INSERT INTO uprofile.events_by_user (player_id, event , country, session_id, ts) VALUES (%s,%s,%s,%s,%s)\", [\n \"0a2d12a1a7e145de8bae44c0c6e06631\", 'start', 'YY', '4a0c43c9-c43a-42ff-ba55-67563dfa35d6', '2016-12-02T12:59:05.520022'])\nsession.execute(\"INSERT INTO uprofile.events_by_user (player_id, event , country, session_id, ts) VALUES (%s,%s,%s,%s,%s)\", [\n \"0a2d12a1a7e145de8bae44c0c6e06632\", 'start', 'XZ', '4a0c43c9-c43a-42ff-ba55-67563dfa35d7', '2016-12-02T12:56:05.520022'])\nsession.execute(\"INSERT INTO uprofile.events_by_user (player_id, event , country, session_id, ts) VALUES (%s,%s,%s,%s,%s)\", [\n \"0a2d12a1a7e145de8bae44c0c6e06633\", 'start', 'MM', '4a0c43c9-c43a-42ff-ba55-67563dfa35d8', '2016-12-02T12:55:05.520022'])\nsession.execute(\"INSERT INTO uprofile.events_by_user (player_id, event , country, session_id, ts) VALUES (%s,%s,%s,%s,%s)\", [\n \"0a2d12a1a7e145de8bae44c0c6e06634\", 'start', 'NN', '4a0c43c9-c43a-42ff-ba55-67563dfa35d9', '2016-12-02T12:54:05.520022'])\n#</insertData>\n\n#<queryAllItems>\nprint (\"\\nSelecting All\")\nrows = session.execute('SELECT * FROM uprofile.events_by_user')\nPrintTable(rows)\n#</queryAllItems>\n\n#<queryByID>\n# print (\"\\nSelecting Id=1\")\n# rows = session.execute(\n# 'SELECT * FROM uprofile.events_by_user where player_id=\"0a2d12a1a7e145de8bae44c0c6e06629\"')\n# PrintTable(rows)\n#</queryByID>\n\ncluster.shutdown()\n","sub_path":"pyquickstart.py","file_name":"pyquickstart.py","file_ext":"py","file_size_in_byte":3781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"121674448","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 16 15:31:19 2022\n\n@author: molierenguile-makao\n\"\"\"\n\nclass facequadri:\n def __init__(self,larg,long,haut=None):\n self.lrg=larg\n self.log=long\n self.hat=haut\n \n def perimetre(self):\n if self.hat is None:\n return 2*(self.log+self.lrg)\n else:\n return 2*(self.log+self.lrg+self.hat)\n \n def volume(self):\n if self.hat is None :\n return self.lrg*self.log\n else:\n return self.lrg*self.log*self.hat","sub_path":"pakg_com/pakg_com/modultest.py","file_name":"modultest.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"305455621","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"Command Line Interface.\"\"\"\nfrom argparse import ArgumentParser\nfrom sys import stderr\n\nfrom project_name.definitions.error import PackageException\nfrom project_name.project_name import run\n\n\ndef get_parser():\n \"\"\"Add required fields to parser.\n\n Returns:\n ArgumentParser: Argeparse object.\n \"\"\"\n package_description = 'Description'\n parser = ArgumentParser(description=package_description)\n\n arg1_help = 'Description'\n parser.add_argument('-f', '--first-arg', nargs='+', help=arg1_help)\n\n arg2_help = 'Description'\n parser.add_argument('-s', '--second-arg', nargs='+', help=arg2_help)\n\n out_help = ('Path to save output file. If not present, same directory of'\n 'any input files passed will be used.')\n parser.add_argument('-o', '--outpath', help=out_help)\n\n return parser\n\n\ndef cli():\n \"\"\"Command line interface for package.\n\n Side Effects: Executes program.\n\n Command Syntax:\n\n Examples:\n\n \"\"\"\n parser = get_parser()\n kwargs = parser.parse_args()\n\n try:\n run(arg1=kwargs.arg1,\n arg2=kwargs.arg1,\n outpath=kwargs.outpath)\n except PackageException as err:\n err = 'An error occurred.\\n\\n' + str(err)\n print(err, file=stderr)\n\n\nif __name__ == '__main__':\n cli()\n","sub_path":"project_name/interfaces/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"162132355","text":"import scipy.io\nimport numpy as np\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import KFold\nfrom sklearn import preprocessing\nfrom sklearn.decomposition import PCA\nfrom sklearn.linear_model import LinearRegression\nimport os\nfrom sklearn.metrics import classification_report,confusion_matrix,precision_score\n\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nimport pickle\n\n\ndef concat_channels(eeg_events):#channels*EEG_value*img \n #for putting all channels in a single vector. return is n_img x 17600\n n_channels,n_samples,n_img = np.shape(eeg_events)\n concat_all = np.zeros((n_img,n_channels*n_samples))\n for i in range(n_img): #for each image\n concat_row = []\n for j in range(n_channels): #for each channel of channels\n #concat_data[i] = np.concatenate((concat_data[i],eeg_events[j,:,i]),axis=1)\n concat_row = np.concatenate((concat_row,eeg_events[j,:,i]))\n concat_all[i] = concat_row\n return concat_all #[n_img*17600]\n\n#\n#def is_animal(class_vector):#creates vector of 1 if animal and 0 if not\n# n = np.size(class_vector)\n# bin_vector = np.zeros(n)\n# for i in range(n):\n# if class_vector[i] == 'animal':\n# bin_vector[i] = 1\n# else:\n# bin_vector[i] = 0\n# return bin_vector\n\n\n\nos.chdir('C:/Users/Bruger/Documents/Uni/Advanche machine learning/Projekt/new_data/data')\n\n\nn_experiments = 4\n\n\nfull_data_matrix = []\nfull_superClass_array = []\nfull_subClass_array = []\nfull_semantics_matrix = []\n\nfor i in range(n_experiments):\n eeg_events = scipy.io.loadmat('exp' + str(i+1) + '\\eeg_events.mat')\n image_order = np.genfromtxt('exp' + str(i+1) + '\\image_order.txt', delimiter=\"\\t\", skip_header = True, dtype=(str))#\n data = eeg_events[\"eeg_events\"]\n concat_data = concat_channels(data)\n #load sematics\n image_semantics_mat = scipy.io.loadmat('exp' + str(i+1) + '\\image_semantics.mat')\n image_semantics = image_semantics_mat[\"image_semantics\"]#semantics_vector x n_images\n \n if i == 0:\n full_data_matrix = concat_data\n full_superClass_array = image_order[:,0]\n full_subClass_array = image_order[:,1]\n full_semantics_matrix = np.transpose(image_semantics)\n\n else:\n full_data_matrix = np.concatenate((full_data_matrix,concat_data),axis=0)\n full_superClass_array = np.concatenate((full_superClass_array,image_order[:,0]),axis=0)\n full_subClass_array = np.concatenate((full_subClass_array,image_order[:,1]),axis=0)\n full_semantics_matrix = np.concatenate((full_semantics_matrix,np.transpose(image_semantics)))\n \n#Normalize data\n \nnormal_data_all = preprocessing.scale(full_data_matrix)#normalize\n\n\n\n#Change superclass toAnimal or not:\n#full_isAnimal_array = is_animal(full_superClass_array)\n\n\n\"\"\"\nPCA stuff method 1\n\"\"\"\npca = PCA(2160, svd_solver='auto')\npca.fit(normal_data_all)\nnormal_data_pca = pca.transform(normal_data_all)#transform data to xx components\n\n\n\nn_observations =2160\nX_train, X_test, y_train_index, y_test_index = train_test_split(normal_data_pca[range(n_observations),:],range(n_observations),test_size=0.2) #The reason why y-labels are not sorte least to largest is because this funktion mix things arround in order to get a mo\n\ny_train_string=full_subClass_array[y_train_index]\n\ny_test_string=full_subClass_array[y_test_index]\n\n\n\n\"\"\"\nBinary\n\"\"\"\ny_train=np.zeros(len(y_train_string))\ny_test=np.ceil(np.zeros(len(y_test_string)))\n\nfor i in range(len(y_train_string)):\n if y_train_string[i]=='airplane':\n y_train[i]=1\n if y_train_string[i]=='elephant':\n y_train[i]=0\n if y_train_string[i]=='pizza':\n y_train[i]=1\n if y_train_string[i]=='sheep':\n y_train[i]=0\n if y_train_string[i]=='train':\n y_train[i]=1\n if y_train_string[i]=='zebra':\n y_train[i]=0\n\nfor i in range(len(y_test_string)):\n if y_test_string[i]=='airplane':\n y_test[i]=1\n if y_test_string[i]=='elephant':\n y_test[i]=0\n if y_test_string[i]=='pizza':\n y_test[i]=1\n if y_test_string[i]=='sheep':\n y_test[i]=0\n if y_test_string[i]=='train':\n y_test[i]=1\n if y_test_string[i]=='zebra':\n y_test[i]=0\n\n\n\n\nfrom tpot import TPOTClassifier\nclf=TPOTClassifier(verbosity=2,n_jobs=1)\nclf.fit(X_train,y_train)\n\nprint('test score=',clf.score(X_test,y_test))\npredictions = clf.predict(X_test)\nprint(confusion_matrix(y_test,predictions))\n\nos.chdir('C:/Users/Bruger/Documents/Uni/Advanche machine learning/Projekt/Code/thor_final_scripts_for_report')\nclf.export('TPOT_export_autoML_newData_FULL_PCA_Binary.py')\nerror_rate=clf.score(X_test,y_test)\nnumber_observations=len(X_test)\nprint('uncertanty=',np.sqrt((error_rate*(1-error_rate))/(number_observations)))\ndef f(error_rate,number_observations):\n return np.sqrt((error_rate*(1-error_rate))/(number_observations))\n","sub_path":"thor_final_scripts_for_report/autoML_newData_FULL_PCA_Binary.py","file_name":"autoML_newData_FULL_PCA_Binary.py","file_ext":"py","file_size_in_byte":4916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"580751368","text":"__author__ = 'spaweska'\n\n\"\"\"\nQuestion:\nWrite a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a.\nSuppose the following input is supplied to the program:\n9\nThen, the output should be:\n11106\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\n\"\"\"\nuser_input = input(\"Enter a digit: \")\n\nif len(user_input) != 1:\n print(\"Wrong input!\")\nelif not user_input.isdigit():\n print(\"Not a digit!\")\nelse:\n input_list = [user_input]\n for number in range(1, 4):\n input_list.append(input_list[number-1] + user_input)\n sum_d = 0\n for value in input_list:\n sum_d += int(value)\n print(sum_d)\n","sub_path":"015.py","file_name":"015.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"432391622","text":"# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport os\nimport sys\nimport paddle\nimport logging\nimport paddle.fluid as fluid\nimport paddle.fluid.incubate.fleet.collective as fleet\n\n\nlogging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s')\nlogger = logging.getLogger(\"fluid\")\nlogger.setLevel(logging.INFO)\n\nos.environ[\"NCCL_SOCKET_IFNAME\"] = \"xgbe0\"\nos.environ[\"NCCL_P2P_DISABLE\"] = \"1\"\nos.environ[\"NCCL_IB_CUDA_SUPPORT\"] = \"1\"\nos.environ[\"NCCL_IB_DISABLE\"] = \"0\"\n\ndef load_vocab(filename):\n vocab = {}\n with open(filename) as f:\n wid = 0\n for line in f:\n vocab[line.strip()] = wid\n wid += 1\n vocab[\"<unk>\"] = len(vocab)\n return vocab\n\nfleet.init()\n\nif __name__ == \"__main__\":\n vocab = load_vocab('imdb.vocab')\n dict_dim = len(vocab)\n\n data = fluid.layers.data(name=\"words\", shape=[1], dtype=\"int64\", lod_level=1)\n label = fluid.layers.data(name=\"label\", shape=[1], dtype=\"int64\")\n\n dataset = fluid.DatasetFactory().create_dataset(\"InMemoryDataset\")\n filelist = [\"train_data/%s\" % x for x in os.listdir(\"train_data\")]\n dataset.set_use_var([data, label])\n pipe_command = \"python imdb_reader.py\"\n dataset.set_pipe_command(pipe_command)\n dataset.set_batch_size(64)\n dataset.set_filelist(filelist)\n dataset.set_thread(1)\n dataset.load_into_memory()\n from nets import lstm_net\n avg_cost, acc, prediction = lstm_net(data, label, dict_dim)\n sgd = fluid.optimizer.SGD(learning_rate=0.01)\n sgd = fleet.DistributedOptimizer(sgd)\n sgd.minimize(avg_cost)\n fleet.init_worker(fluid.default_main_program())\n exe = fluid.Executor(fluid.CUDAPlace(fleet.worker_index()))\n exe.run(fluid.default_startup_program())\n epochs = 30\n save_dirname = \"lstm_model\"\n for i in range(epochs):\n exe.train_from_dataset(program=fluid.default_main_program(),\n fetch_list=[avg_cost],\n fetch_info=[\"avg_cost\"],\n dataset=dataset, debug=False)\n logger.info(\"TRAIN --> pass: {}\".format(i))\n fluid.io.save_inference_model(\"%s/epoch%d.model\" % (save_dirname, i),\n [data.name, label.name], [acc], exe)\n","sub_path":"pipeline_io_example/text_classification_gpu/local_train_gpu.py","file_name":"local_train_gpu.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"373237929","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Time : 2018/5/31 21:36\n# @Author : chen\n# @File : 服务端.py\n\nimport socket\n\n# 服务端需要两个套接字,一个用来发送,另一个用来接收bind,recv\n#客户端只有一个套接字,connect\n\n# 1. 买手机\nphone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n# print(phone)\n\n# 2. 绑定手机卡\nphone.bind(('127.0.0.1', 8081)) # 0-65535; 0-1024给操作系统使用\n\n# 3.开机\nphone.listen(5)\n\n# 4.等待电话\nprint('starting...')\nconn, client = phone.accept()\n\n# 收、发消息\ndata = conn.recv(1024) # 1、单位:bytes 2、1024代表最大接收1024个bytes\nprint('客户端的数据', data)\n\nconn.send(data.upper())\n\n# 6.挂电话\nconn.close()\n","sub_path":"类与网络编程/网络编程/01.简单套接字通信/服务端.py","file_name":"服务端.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"141538769","text":"import gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\n\nscope = [\"https://spreadsheets.google.com/feeds\", 'https://www.googleapis.com/auth/spreadsheets',\n 'https://www.googleapis.com/auth/drive.file', \"https://www.googleapis.com/auth/drive\"]\n\ncredentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)\n\nclient = gspread.authorize(credentials)\n\nsheet = client.open(\"players\").sheet1\n\n# retrieving data\n\ndata = sheet.get_all_records()\n\nrow = sheet.row_values(3)\ncolumn = sheet.col_values(3)\n\ncell = sheet.cell(2, 2).value\n\nprint(cell)\n\n# inserting data\n\ninsert_row = [\"6\", \"Manchester United\", \"Paul Pogba\"]\nsheet.insert_row(insert_row, 7)\n\n# deleting data\n\nsheet.delete_row(6)\n\n# update data\n\nsheet.update_cell(4, 3, \"Eric Bailly\")\n\n# stats\n\nnum_rows = sheet.row_count\nprint(len(data))\n","sub_path":"sheets.py","file_name":"sheets.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"643712479","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 31 13:00:51 2020\n\n@author: jbyoung\n\"\"\"\n\nimport sys\nimport csv\nfrom argparse import ArgumentParser\nimport numpy\nfrom cigar import Cigar\n\n\ndef parse_command(command):\n \"\"\"Sets up and parses input arguemnts\"\"\"\n parser = ArgumentParser(description='Counts number of unique start sites for each fusion \\n'\n 'in star fusion results, takes a list of star fusion \\n'\n 'results folders as input, usage:\\n'\n 'get_uniq_starts_final.py -f *star_fusion_results -o output_name.txt')\n parser.add_argument('-f', '--fusionresults', nargs='+', required=True, help='folder(s) containing star-fusion results')\n parser.add_argument('-o', '--outname', required=True, help='output for combined results file')\n\n try:\n args = parser.parse_args(command)\n except:\n parser.error('Invalid options provided')\n return args\n\ndef chomp_cigar_list(table, gene):\n \"\"\"Reads cigar string for supporting read pairs and calculates start/end points\"\"\"\n coord = []\n if gene == \"A\":\n aln_start = 0\n splice_junc = 1\n strand_ind = 2\n cigar_ind = 3\n if gene == \"B\":\n aln_start = 4\n splice_junc = 5\n strand_ind = 6\n cigar_ind = 7\n for row in table:\n frag_type = row[9]\n #print(\"fragtype = \" + frag_type)\n c_string = Cigar(row[cigar_ind].replace(\"-\", \"\"))\n c_list = list(c_string.items())\n c_ar = numpy.array(c_list)\n p_ind = numpy.where(c_ar == 'p')\n\n if p_ind[0].size > 0:\n c_ar = c_ar[:int(p_ind[0])]\n\n clipped = numpy.where(c_ar == 'S')\n if clipped[0].size > 0:\n c_ar = numpy.delete(c_ar, clipped[0], 0)\n deletions = numpy.where(c_ar == 'D')\n if deletions[0].size > 0:\n c_ar = numpy.delete(c_ar, deletions[0], 0)\n\n mapped_len = numpy.sum(c_ar[:, 0].astype(numpy.int))\n\n if gene == \"A\" and row[strand_ind] == '+':\n if frag_type == \"spanningfrag\":\n coord.append(int(row[aln_start]))\n else:\n coord.append(int(row[splice_junc]) - int(mapped_len))\n\n if gene == \"A\" and row[strand_ind] == '-':\n if frag_type == \"spanningfrag\":\n coord.append(int(row[aln_start]) + int(mapped_len))\n else:\n coord.append(int(row[splice_junc]) + int(mapped_len))\n\n if gene == \"B\" and row[strand_ind] == '+':\n if frag_type == \"spanningfrag\":\n coord.append(int(row[aln_start]) + int(mapped_len))\n else:\n coord.append(int(row[splice_junc]) + int(mapped_len))\n\n if gene == \"B\" and row[strand_ind] == '-':\n if frag_type == \"spanningfrag\":\n coord.append(int(row[aln_start]))\n else:\n coord.append(int(row[splice_junc]) - int(mapped_len))\n return coord\n\n\ndef decomment(csvfile):\n \"\"\"strip comment lines from csv\"\"\"\n for row in csvfile:\n raw = row.split('#')[0].strip()\n if raw:\n yield raw\n\ndef cluster_ends(coords, dist):\n \"\"\"groups read ends < dist bp apart as same primer\"\"\"\n ref = 0\n cnt = 0\n out = []\n for pos in coords:\n if abs(pos[1]-ref) > dist:\n cnt += 1\n ref = pos[1]\n out.append((str(pos[0]), 'primer%d'%cnt))\n return out\n\n\ndef main():\n \"\"\"main function for counting unique starts from star fusion supporting reads\"\"\"\n input_command = parse_command(sys.argv[1:])\n csv.field_size_limit(sys.maxsize)\n\n with open(input_command.outname, \"w+\") as out:\n #with open(\"test_out\", \"w+\") as out:\n writer = csv.writer(out, delimiter='\\t', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n writer.writerow(['Sample', 'Fusion', 'JunctionReads', 'SpanningFragments', 'UniqueStarts'])\n for path in input_command.fusionresults:\n #for path in [\"S1568-00245-CP1Lib1_S23_Resampled_uniq.R1.fusions\"]:\n fusions_file = str(path) + \"/star-fusion.fusion_predictions.tsv\"\n coding_eff_file = str(path) + \"/star-fusion.fusion_predictions.abridged.coding_effect.tsv\"\n chimeric_reads_file = str(path) + \"/Chimeric.out.junction\"\n print(\"starting: \" + path)\n # need fields\n # 0: fusion name,\n # 1: junction reads\n # 2: spanning frags\n # 8: junction readnames\n # 9: spanningfragnames\n\n # dictionary:\n # readname: s_start, a_junction, a_strand, a cigar, b_start, b_junction, b_strand, b_cigar\n\n junc_dict = {}\n with open(chimeric_reads_file, newline='') as chim_in:\n next(chim_in)\n reader = csv.reader(decomment(chim_in), delimiter='\\t')\n for row in reader:\n read = row[9]\n stats = [row[10], row[1], row[2], row[11], row[12], row[4], row[5], row[13], row[9]]\n junc_dict[read] = stats\n\n with open(fusions_file, newline='') as fus_in, open(coding_eff_file, newline='') as eff_in:\n next(fus_in)\n next(eff_in)\n results = [x for x in csv.reader(fus_in, delimiter='\\t')]\n eff = [x for x in csv.reader(eff_in, delimiter='\\t')]\n for k in range(0, (len(results))):\n line=results[k]\n #for line in results:\n splitfrags = line[8].split(',')\n spanningfrags = line[9].split(',')\n reads = (splitfrags + spanningfrags)\n reads = list(filter(lambda a: a != '.', reads))\n read_pos = list((junc_dict[k]) for k in tuple(reads))\n for i in read_pos:\n if i[8] in spanningfrags:\n i.append(\"spanningfrag\")\n else:\n i.append(\"splitfrag\")\n a_coords = chomp_cigar_list(read_pos, \"A\")\n b_coords = chomp_cigar_list(read_pos, \"B\")\n res = list(zip(a_coords, b_coords))\n comb_list2 = sorted(res, key=lambda x: x[1])\n out = cluster_ends(comb_list2, 10)\n clus = len(set(out))\n coding_effect = eff[k][19]\n writer.writerow([path.replace(\"_uniq.R1.fusions\", \"\"), line[0], line[1], line[2], clus, coding_effect])\n print(\"finished: \" + path + \" \" + line[0])\n\nmain()\n\n","sub_path":"misc/uniq_counts_codeff.py","file_name":"uniq_counts_codeff.py","file_ext":"py","file_size_in_byte":6642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"498903284","text":"import Database\nfrom Camera import Camera\nfrom Client import Client\n\nfile = 'database.txt'\n\n# Main \nif __name__ == '__main__':\n\n camera = Camera(0)\n db = Database(file)\n\n while (True):\n try:\n response = input('New client? (y/n) ')\n\n if response == 'y':\n\n # Create client\n client = Client()\n\n # Scan QR code for each suitcase\n print('Scan QR codes')\n check_ = 'n'\n while (check_ != 'y'):\n qr_codes = camera.get_qr(int(client.n_suitcases))\n check_ = input(\"Is OK? (y/n) \")\n camera.release()\n\n # Associate client with QR codes\n db.save(qr_codes, client)\n\n except KeyboardInterrupt:\n print(\"..\")\n print(\"Closing..\")\n camera.release()\n db.to_file(file)\n break\n print(\"Bye\")\n","sub_path":"QR/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"516740644","text":"# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.\n# Lean CLI v1.0. Copyright 2021 QuantConnect Corporation.\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 http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport zipfile\nfrom pathlib import Path\nfrom typing import Any, List\n\nimport click\n\nfrom lean.components.api.api_client import APIClient\nfrom lean.components.config.lean_config_manager import LeanConfigManager\nfrom lean.components.util.logger import Logger\nfrom lean.models.errors import RequestFailedError\nfrom lean.models.map_file import MapFile\n\n\nclass DataDownloader:\n \"\"\"The DataDownloader is responsible for downloading data from the QuantConnect Data Library.\"\"\"\n\n def __init__(self, logger: Logger, api_client: APIClient, lean_config_manager: LeanConfigManager):\n \"\"\"Creates a new CloudBacktestRunner instance.\n\n :param logger: the logger to use to log messages with\n :param api_client: the APIClient instance to use when communicating with the QuantConnect API\n :param lean_config_manager: the LeanConfigManager instance to retrieve the data directory from\n \"\"\"\n self._logger = logger\n self._api_client = api_client\n self._lean_config_manager = lean_config_manager\n self._force_overwrite = None\n self._map_files_cache = None\n\n def download_files(self,\n data_files: List[Any],\n overwrite_flag: bool,\n is_interactive: bool,\n organization_id: str) -> None:\n \"\"\"Downloads files from the QuantConnect Data Library to the local data directory.\n\n :param data_files: the list of data files to download\n :param overwrite_flag: whether the user has given permission to overwrite existing files\n :param is_interactive: whether the CLI is allowed to prompt for input\n :param organization_id: the id of the organization that should be billed\n \"\"\"\n data_dir = self._lean_config_manager.get_data_directory()\n\n if not is_interactive:\n self._force_overwrite = overwrite_flag\n\n for index, data_file in enumerate(data_files):\n self._logger.info(\n f\"[{index + 1}/{len(data_files)}] Downloading {data_file.file} ({data_file.vendor.price:,.0f} QCC)\")\n self._download_file(data_file.file, overwrite_flag, data_dir, organization_id)\n\n def download_map_files(self, organization_id: str) -> List[MapFile]:\n \"\"\"Downloads and parses all available map files.\n\n :param organization_id: the id of the organization that should be used for downloads\n :return: the list of available map files\n \"\"\"\n if self._map_files_cache is not None:\n return self._map_files_cache\n\n map_files_zip = self._api_client.data.list_files(\"equity/usa/map_files/map_files_\")[-1]\n\n data_directory = self._lean_config_manager.get_data_directory()\n map_files_zip_path = data_directory / map_files_zip\n\n if not map_files_zip_path.is_file():\n self._logger.info(\"Downloading the latest map files (free)\")\n self._download_file(map_files_zip, True, data_directory, organization_id)\n\n map_files = []\n with zipfile.ZipFile(map_files_zip_path) as zip_file:\n for file_info in zip_file.filelist:\n map_files.append(MapFile.parse(zip_file.read(file_info.filename).decode(\"utf-8\")))\n\n self._map_files_cache = map_files\n\n return map_files\n\n def _download_file(self,\n relative_file: str,\n overwrite_flag: bool,\n data_directory: Path,\n organization_id: str) -> None:\n \"\"\"Downloads a single file from the QuantConnect Data Library to the local data directory.\n\n If this method downloads a map or factor files zip file,\n it also updates the Lean config file to ensure LEAN uses those files instead of the csv files.\n\n :param relative_file: the relative path to the file in the data directory\n :param overwrite_flag: whether the user has given permission to overwrite existing files\n :param data_directory: the path to the local data directory\n :param organization_id: the id of the organization that should be billed\n \"\"\"\n local_path = data_directory / relative_file\n\n if local_path.exists() and not self._should_overwrite(overwrite_flag, local_path):\n return\n\n try:\n file_content = self._api_client.data.download_file(relative_file, organization_id)\n except RequestFailedError as error:\n self._logger.warn(str(error))\n self._logger.warn(\"You have not been charged for this file\")\n return\n\n local_path.parent.mkdir(parents=True, exist_ok=True)\n with local_path.open(\"wb+\") as f:\n f.write(file_content)\n\n if relative_file.startswith(\"equity/usa/map_files/map_files_\") and relative_file.endswith(\".zip\"):\n self._lean_config_manager.set_properties({\n \"map-file-provider\": \"QuantConnect.Data.Auxiliary.LocalZipMapFileProvider\"\n })\n\n if relative_file.startswith(\"equity/usa/factor_files/factor_files_\") and relative_file.endswith(\".zip\"):\n self._lean_config_manager.set_properties({\n \"factor-file-provider\": \"QuantConnect.Data.Auxiliary.LocalZipFactorFileProvider\"\n })\n\n def _should_overwrite(self, overwrite_flag: bool, path: Path) -> bool:\n \"\"\"Returns whether we should overwrite existing files.\n\n :param overwrite_flag: whether the user has given permission to overwrite existing files\n :param path: the path to the file that already exists\n :return: True if existing files may be overwritten, False if not\n \"\"\"\n if overwrite_flag or self._force_overwrite:\n return True\n\n self._logger.warn(f\"{path} already exists, use --overwrite to overwrite it\")\n\n if self._force_overwrite is None:\n self._force_overwrite = click.confirm(\n \"Do you want to temporarily enable overwriting for the previously selected items?\",\n default=False)\n\n if not self._force_overwrite:\n self._logger.warn(\"You have not been charged for this file\")\n\n return self._force_overwrite\n","sub_path":"lean/components/cloud/data_downloader.py","file_name":"data_downloader.py","file_ext":"py","file_size_in_byte":6856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"74072365","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def swapNodes(self, head: ListNode, k: int) -> ListNode:\n curr=start=end=head\n while curr:\n k-=1\n if k==0: start=curr\n if k<0: end=end.next\n curr=curr.next\n \n start.val, end.val=end.val, start.val\n return head\n\n","sub_path":"python/swapping-nodes-in-a-linked-list.py","file_name":"swapping-nodes-in-a-linked-list.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"373752946","text":"from playground.network.common import StackingProtocolFactory, StackingProtocol, StackingTransport\nfrom playground.network.packet import PacketType\nfrom playground.network.packet.fieldtypes import STRING, BUFFER, UINT8, UINT16, UINT32, BOOL\nfrom playground.network.packet.fieldtypes.attributes import Optional\nimport logging\nimport random\nimport asyncio\nimport binascii\nimport time\n\nlogger = logging.getLogger(\"playground.__connector__.\"+__name__)\n\nclass PoopPacketType(PacketType):\n DEFINITION_IDENTIFIER = \"poop\"\n DEFINITION_VERSION = \"1.0\"\n\nclass DataPacket(PoopPacketType):\n DEFINITION_IDENTIFIER = \"poop.datapacket\"\n DEFINITION_VERSION = \"1.0\"\n\n FIELDS = [\n (\"seq\", UINT32({Optional: True})),\n (\"hash\", UINT32),\n (\"data\", BUFFER({Optional: True})),\n (\"ACK\", UINT32({Optional: True})),\n ]\n\nclass HandshakePacket(PoopPacketType):\n DEFINITION_IDENTIFIER = \"poop.handshakepacket\"\n DEFINITION_VERSION = \"1.0\"\n\n NOT_STARTED = 0\n SUCCESS = 1\n ERROR = 2\n\n FIELDS = [\n (\"SYN\", UINT32({Optional: True})),\n (\"ACK\", UINT32({Optional: True})),\n (\"error\", STRING({Optional: True})),\n (\"hash\", UINT32)\n ]\n \nclass ShutdownPacket(PoopPacketType):\n DEFINITION_IDENTIFIER = \"poop.shutdownpacket\"\n DEFINITION_VERSION = \"1.0\"\n\n SUCCESS = 0\n ERROR = 1\n\n FIELDS = [\n (\"FIN\", UINT32),\n (\"hash\", UINT32)\n ]\n\n\n#Hash function and checkHash function\ndef hashPacket(packet):\n packet.hash = 0\n packet.hash = binascii.crc32(packet.__serialize__()) & 0xffffffff\n\ndef checkHash(packet):\n h = packet.hash\n packet.hash = 0\n result = (h == binascii.crc32(packet.__serialize__()) & 0xffffffff)\n packet.hash = h\n return result\n\n#--------------------- higher transport part -----------------------------\nclass POOPTransport(StackingTransport):\n \n def __init__(self, protocol, transport, seq):\n print(\"higher transport begin\")\n \n super().__init__(transport)\n self.protocol = protocol\n self.seq = seq\n #use dictionary to record the state of a data packet corresponding to a sequence number\n self.confirmed_seqs = {}\n\n def write(self, data):\n #The maximum size of any DataPacket shall be 15000 bytes.\n for i in range(0, len(data), 5000):\n asyncio.ensure_future(self.myWrite(data[i:i+5000]))\n\n def close(self):\n asyncio.ensure_future(self._close())\n\n#------------------------- called functions ------------------------------------------\n async def myWrite(self, data):\n \n seq = self.seq\n self.seq = (self.seq + 1)%(2**32)\n self.confirmed_seqs[seq] = 1\n \n while self.protocol.stage != \"closing\" and self.confirmed_seqs[seq] >= 1 and self.confirmed_seqs[seq] <= 3:\n p = DataPacket(seq=seq, data=data) \n hashPacket(p) \n print(\"send data, MyProtocoLog: \",\"length of data: \", len(data), \"seq number: \", seq, \"times of sending: \", self.confirmed_seqs[seq], \"ack: \",p.ACK ) \n \n self.lowerTransport().write(p.__serialize__())\n\n self.confirmed_seqs[seq] += 1\n await asyncio.sleep(1)\n \n async def _close(self):\n print(\"begin close\")\n self.protocol.stage = \"closing\"\n self.protocol.connection_lost()\n seq = self.seq\n self.FIN = seq\n self.seq (self.seq + 1)%(2**32)\n self.confirmed_seqs[seq] = 1\n while self.confirmed_seqs[seq] >= 1 and self.confirmed_seqs[seq] <= 3:\n p = ShutdownPacket(FIN=seq)\n hashPacket(p)\n self.lowerTransport().write(p.__serialize__())\n\n self.confirmed_seqs[seq] += 1\n await asyncio.sleep(1)\n \n #TODO: check\n self.lowerTransport().close()\n #self.lowerTransport().connection_lost()\n \n# ------------------------------ lower transport part ------------------------------ \n#Fot handshake, NOT_STARTED = 0 SUCCESS = 1 ERROR = 2\n#For shutdown, SUCCESS = 0 ERROR = 1\n#set the timeout for every step to be 1 second \n#If not receives the acknowledgement from the other side after timeout or receive a wrong acknowledgement packet, it will try to resend TWO more times. \nclass PassthroughProtocol(StackingProtocol):\n def __init__(self, mode):\n super().__init__()\n \n self.mode = mode\n #four stages: handshake_1, handshake_2, connected, closing\n self.stage = \"handshake_1\"\n #records if the data packet of a sequence number is received before\n self.received_seqs = {}\n \n self.deserializer = PoopPacketType.Deserializer()\n \n #generate random integers X and Y\n if self.mode == \"client\":\n self.x = random.randint(0,2**32)\n self.seq = self.x\n print(\"x: \",self.x)\n elif self.mode == \"server\":\n self.y = random.randint(0,2**32)\n self.seq = self.y\n print(\"y: \",self.y)\n \n def connection_made(self, transport):\n #logger.debug(\"{} passthrough connection made. Calling connection made higher.\".format(self.mode))\n\n self.transport = transport\n \n if self.mode == \"client\":\n asyncio.ensure_future(self.client_handshake_packet1())\n print(\"client sends the first handshake packet\")\n \n def data_received(self, buffer):\n #logger.debug(\"{} passthrough received a buffer of size {}\".format(self.mode, len(buffer)))\n \n print(\"data_received begin\")\n \n self.deserializer.update(buffer)\n for packet in self.deserializer.nextPackets():\n \n packet_type = packet.DEFINITION_IDENTIFIER\n if not packet_type or not packet.DEFINITION_VERSION: \n print(\"The received packet does not have a DEFINITION_IDENTIFIER or DEFINITION_VERSION\")\n continue\n \n if self.stage == \"handshake\":\n if isinstance(packet, HandshakePacket):\n if self.mode == \"server\":\n self.handshake_received_server(packet)\n continue\n elif self.mode == \"client\":\n self.handshake_received_client(packet)\n continue\n \n if self.stage == \"connected\": \n #normal data transmission\n if isinstance(packet, DataPacket):\n self.data_received_duplex(packet)\n continue\n #get a shutdown packet from another side \n if isinstance(packet,ShutdownPacket):\n self.shutdown_received(packet)\n continue\n \n if self.stage == \"closing\":\n #simultaneous shutdown\n if isinstance(packet, ShutdownPacket):\n self.shutdown_received(packet)\n continue\n \n #get the ACK of shutdown packet\n if isinstance(packet, DataPacket):\n self.shutdown_received(packet)\n continue\n \n def connection_lost(self, exc):\n #logger.debug(\"{} passthrough connection lost. Shutting down higher layer.\".format(self.mode))\n self.higherProtocol().connection_lost(exc)\n \n # ------------------- called functions --------------------------------------------- \n \n # --------------------- process handshake received packet --------------------------------- \n def handshake_received_server(self, packet):\n print(\"handshake_received_server\", self.stage)\n \n if packet.DEFINITION_IDENTIFIER != \"poop.handshakepacket\" or packet.DEFINITION_VERSION != \"1.0\":\n print(\"it is a wrong packet\")\n return\n \n if packet.status == 2: \n print(\"error packet\")\n \n if not checkHash(packet):\n print(\"hash wrong\")\n self.handshake_error()\n \n if not packet.SYN:\n print(\"missing SYN\")\n self.handshake_error()\n \n if self.stage == \"handshake_1\":\n #get the first handshake packet from client\n if packet.status == 0:\n if packet.ACK:\n self.handshake_error()\n else:\n asyncio.ensure_future(self.server_handshake_packet1(packet))\n self.stage = \"handshake_2\"\n print(\"server sends the first handshake packet\")\n else:\n self.handshake_error()\n \n #get the second handshake packet from client \n if self.stage == \"handshake_2\": \n if packet.status == 1:\n if packet.ACK == ((self.y+1)%(2**32)):\n self.stage = \"connected\"\n \n #stop sending client_handshake_packet1\n self.server_handshake_packet1_confirmed = -1\n \n self.higher_transport = POOPTransport(self, self.transport, self.seq)\n self.higherProtocol().connection_made(self.higher_transport)\n else:\n self.handshake_error()\n else:\n self.handshake_error()\n \n def handshake_received_client(self, packet):\n print(\"data_received_client\", self.stage)\n \n #stop sending client_handshake_packet1\n self.client_handshake_packet1_confirmed = -1\n \n if packet.DEFINITION_IDENTIFIER != \"poop.handshakepacket\" or packet.DEFINITION_VERSION != \"1.0\":\n print(\"it is a wrong packet\")\n return\n \n if packet.status == 2: \n print(\"error packet\")\n \n if not checkHash(packet):\n print(\"hash wrong\")\n # asyncio.ensure_future(self.client_handshake_packet1())\n self.handshake_error()\n \n if packet.status == 1 and packet.ACK == ((self.x+1)%(2**32)):\n asyncio.ensure_future(self.client_handshake_packet2(packet)) \n self.stage = \"connected\" \n print(\"client sends the second handshake packet\")\n \n self.higher_transport = POOPTransport(self, self.transport, self.seq)\n self.higherProtocol().connection_made(self.higher_transport)\n \n else:\n self.handshake_error()\n \n #------------------------ send handshake packet part ------------------------------\n async def client_handshake_packet1(self): \n self.client_handshake_packet1_confirmed = 0\n while self.stage == \"handshake\" and self.client_handshake_packet1_confirmed >= 0 and self.client_handshake_packet1_confirmed <= 2:\n p = HandshakePacket(SYN=self.x, status=0)\n hashPacket(p)\n self.transport.write(p.__serialize__())\n self.client_handshake_packet1_confirmed += 1\n await asyncio.sleep(1)\n \n async def server_handshake_packet1(self, packet):\n self.server_handshake_packet1_confirmed = 0\n while self.stage == \"handshake\" and self.server_handshake_packet1_confirmed >= 0 and self.server_handshake_packet1_confirmed <= 2:\n p = HandshakePacket(SYN=self.y, ACK=((packet.SYN+1)%(2**32)), status=1)\n hashPacket(p)\n self.transport.write(p.__serialize__())\n self.server_handshake_packet1_confirmed += 1\n await asyncio.sleep(1)\n \n async def client_handshake_packet2(self, packet):\n self.client_handshake_packet2_confirmed = 0\n while self.stage == \"handshake\" and self.client_handshake_packet2_confirmed >= 0 and self.client_handshake_packet2_confirmed <= 2:\n p = HandshakePacket(SYN=((self.x+1)%(2**32)), ACK=((packet.SYN+1)%(2**32)), status=1)\n hashPacket(p)\n self.transport.write(p.__serialize__())\n self.client_handshake_packet2_confirmed += 1\n await asyncio.sleep(1)\n \n #--------------------------- data transmission received part ----------------------------- \n def data_received_duplex(self, packet):\n print(\"data_received_duplex\")\n \n #stop sending client_handshake_packet2\n self.client_handshake_packet2_confirmed = -1\n \n if packet.DEFINITION_IDENTIFIER != \"poop.datapacket\" or packet.DEFINITION_VERSION != \"1.0\":\n print(\"it is a wrong packet\")\n return\n \n if packet.status == 2:\n print(\"get error packet\")\n \n if not checkHash(packet):\n print(\"hash wrong\")\n self.data_error()\n \n if not packet.seq or not packet.data or not packet.hash:\n print(\"Wrong data packet.\")\n return\n \n if packet.ACK:\n if packet.seq or packet.data:\n print(\"wrong ACK packet.\")\n return\n #when this ACK packet is not corresponding to a data packet sent before\n if packet.ACK not in self.higher_transport.confirmed_seqs:\n print(\"wrong ACK data packet\") \n #when this ACK packet is corresponding to a data packet sent before\n else:\n print(\"get an ACK of send data hhhhhhhhhhhhhhhhhhhhh\") \n # mark this sent data packet has been received and stop sending it any more \n self.higher_transport.confirmed_seqs[packet.ACK] = -1\n \n else:\n if packet.seq in self.received_seqs:\n print(\"MyProtocoLog: Received Old DataPacket\", packet.seq, \"\\n\")\n else:\n print(\"MyProtocoLog: Received Correct DataPacket\", packet.seq, \"\\n\")\n #mark this data packet is received\n self.received_seqs[packet.seq] = True\n self.higherProtocol().data_received(packet.data)\n \n p = DataPacket(ACK=packet.seq)\n print(\"ACK: \",p.ACK)\n hashPacket(p)\n print(\"MyProtocoLog: send ACK DataPacket\", packet.seq, '\\n')\n self.transport.write(p.__serialize__())\n \n #-------------------------------- shut down process ----------------------------------\n #get a shutdown packet during data transmission\n def shutdown_received(self,packet):\n \n if not checkHash(packet):\n print(\"hash wrong\")\n \n self.stage = \"closing\"\n \n p = DataPacket(ACK=packet.FIN)\n hashPacket(p)\n print(\"send FACK KKKKKKKKKKKKKK\")\n self.transport.write(p.__serialize__())\n self.connection_lost()\n self.transport.close()\n \n #get a ACK of a sent shutdown packet\n def ack_received(self,packet):\n if not checkHash(packet):\n print(\"hash wrong\")\n \n if packet.ACK == self.higher_transport.FIN:\n # fin has been ACKed by other agent. Teardown connection.\n print(\"shutdown packet has been acked.\")\n self.higher_transport.confirmed_seqs[packet.ACK] = -1\n self.connection_lost()\n self.transport.close()\n \n #---------------------------------- send error packet ---------------------------------------- \n def handshake_error(self):\n print(\"handshake error!\")\n packet = HandshakePacket(status=2)\n self.transport.write(packet.__serialize__())\n \n def data_error(self):\n print(\"data transimission error!\")\n packet = DataPacket(status=2)\n self.transport.write(packet.__serialize__())\n\n\nPassthroughClientFactory = StackingProtocolFactory.CreateFactoryType(\n lambda: PassthroughProtocol(mode=\"client\")\n)\n\nPassthroughServerFactory = StackingProtocolFactory.CreateFactoryType(\n lambda: PassthroughProtocol(mode=\"server\")\n)","sub_path":"lab1/protocol_shan_m3.py","file_name":"protocol_shan_m3.py","file_ext":"py","file_size_in_byte":16163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"303683191","text":"# Copyright (c) 2014 Cisco Systems\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n\"\"\" Main ACI Toolkit module\n This is the main module that comprises the ACI Toolkit.\n\"\"\"\nfrom acibaseobject import BaseACIObject, BaseRelation, Stats\nfrom acisession import Session\n# from aciphysobject import Linecard\nimport json\nimport logging\nimport re\n\n\nclass Tenant(BaseACIObject):\n \"\"\"\n The Tenant class is used to represent the tenants within the acitoolkit\n object model. In the APIC model, this class is roughly equivalent to\n the fvTenant class.\n \"\"\"\n def get_json(self):\n \"\"\"\n Returns json representation of the fvTenant object\n\n :returns: A json dictionary of fvTenant\n \"\"\"\n attr = self._generate_attributes()\n return super(Tenant, self).get_json('fvTenant', attributes=attr)\n\n @classmethod\n def get(cls, session):\n \"\"\"\n Gets all of the tenants from the APIC.\n\n :param session: the instance of Session used for APIC communication\n :returns: a list of Tenant objects\n \"\"\"\n return BaseACIObject.get(session, cls, 'fvTenant')\n\n @classmethod\n def exists(cls, session, tenant):\n \"\"\"\n Check if a tenant exists on the APIC.\n\n :param session: the instance of Session used for APIC communication\n :param tenant: the instance of Tenant to check if exists on the APIC\n :returns: True or False\n \"\"\"\n apic_tenants = cls.get(session)\n for apic_tenant in apic_tenants:\n if tenant == apic_tenant:\n return True\n return False\n\n @staticmethod\n def get_url(fmt='json'):\n \"\"\"\n Get the URL used to push the configuration to the APIC\n if no format parameter is specified, the format will be 'json'\n otherwise it will return '/api/mo/uni.' with the format string\n appended.\n\n :param fmt: optional format string, default is 'json'\n :returns: URL string\n \"\"\"\n return '/api/mo/uni.' + fmt\n\n\nclass AppProfile(BaseACIObject):\n \"\"\"\n The AppProfile class is used to represent the Application Profiles within\n the acitoolkit object model. In the APIC model, this class is roughly\n equivalent to the fvAp class.\n \"\"\"\n def __init__(self, name, parent):\n \"\"\"\n :param name: String containing the Application Profile name\n :param parent: An instance of Tenant class representing the Tenant\\\n which contains this Application Profile.\n \"\"\"\n if not isinstance(parent, Tenant):\n raise TypeError('Parent must be of Tenant class')\n super(AppProfile, self).__init__(name, parent)\n\n def get_json(self):\n \"\"\"\n Returns json representation of the AppProfile object.\n\n :returns: json dictionary of fvAp\n \"\"\"\n attr = self._generate_attributes()\n return super(AppProfile, self).get_json('fvAp', attributes=attr)\n\n @classmethod\n def get(cls, session, tenant):\n \"\"\"Gets all of the Application Profiles from the APIC.\n\n :param session: the instance of Session used for APIC communication\n :param tenant: the instance of Tenant used to limit the Application\\\n Profiles retreived from the APIC\n :returns: List of AppProfile objects\n \"\"\"\n return BaseACIObject.get(session, cls, 'fvAp', parent=tenant,\n tenant=tenant)\n\n def _get_url_extension(self):\n return '/ap-%s' % self.name\n\n\nclass L2Interface(BaseACIObject):\n \"\"\" The L2Interface class creates an logical L2 interface that can be\\\n attached to a physical interface. This interface defines the L2\\\n encapsulation i.e. VLAN, VXLAN, or NVGRE\n \"\"\"\n def __init__(self, name, encap_type, encap_id):\n \"\"\"\n :param name: String containing the L2Interface instance name\n :param encap_type: String containing the encapsulation type.\\\n Valid values are 'VLAN', 'VXLAN', or 'NVGRE'.\n :param encap_id: String containing the encapsulation specific\\\n identifier representing the virtual L2 network (i.e. for VXLAN,\\\n this is the numeric value of the VNID).\n \"\"\"\n super(L2Interface, self).__init__(name)\n if encap_type not in ('vlan', 'vxlan', 'nvgre'):\n raise ValueError(\"Encap type must be one of 'vlan',\"\n \" 'vxlan', or 'nvgre'\")\n self.encap_type = encap_type\n self.encap_id = encap_id\n\n def is_interface(self):\n \"\"\"\n Returns whether this instance is considered an interface.\n\n :returns: True\n \"\"\"\n return True\n\n def get_encap_type(self):\n \"\"\"\n Get the encap_type of the L2 interface.\n Valid values are 'vlan', 'vxlan', and 'nvgre'\n\n :returns: String containing encap_type value.\n \"\"\"\n return self.encap_type\n\n def get_encap_id(self):\n \"\"\"\n Get the encap_id of the L2 interface.\n The value is returned as a string and depends on the encap_type\n (i.e. VLAN VID, VXLAN VNID, or NVGRE VSID)\n\n :returns: String containing encapsulation identifier value.\n \"\"\"\n return self.encap_id\n\n def _get_path(self):\n \"\"\"\n Get the path of this interface used when communicating with\\\n the APIC object model.\n\n :returns: String containing the path\n \"\"\"\n for relation in self._relations:\n if relation.item.is_interface():\n return relation.item._get_path()\n\n\nclass CommonEPG(BaseACIObject):\n \"\"\"\n Base class for EPG and OutsideEPG.\n Not meant to be instantiated directly\n \"\"\"\n def __init__(self, epg_name, parent=None):\n \"\"\"\n :param epg_name: String containing the name of this EPG\n :param parent: Instance of the AppProfile class representing\\\n the Application Profile where this EPG is contained.\n \"\"\"\n super(CommonEPG, self).__init__(epg_name, parent)\n\n # Contract references\n def provide(self, contract):\n \"\"\"\n Make this EPG provide a Contract\n\n :param contract: Instance of Contract class to be provided by this EPG.\n :returns: True\n \"\"\"\n if self.does_provide(contract):\n return True\n self._add_relation(contract, 'provided')\n return True\n\n def does_provide(self, contract):\n \"\"\"\n Check if this EPG provides a specific Contract.\n\n :param contract: Instance of Contract class to check if it is\\\n provided by this EPG.\n :returns: True or False. True if the EPG does provide the Contract.\n \"\"\"\n return self._has_relation(contract, 'provided')\n\n def dont_provide(self, contract):\n \"\"\"\n Make this EPG not provide a Contract\n\n :param contract: Instance of Contract class to be no longer provided\\\n by this EPG.\n :returns: True\n \"\"\"\n self._remove_relation(contract, 'provided')\n\n def get_all_provided(self):\n \"\"\"\n Get all of the Contracts provided by this EPG\n\n :returns: List of Contract objects that are provided by the EPG.\n \"\"\"\n return self._get_all_relation(Contract, 'provided')\n\n def consume(self, contract):\n \"\"\"\n Make this EPG consume a Contract\n\n :param contract: Contract class instance to be consumed by this EPG.\n :returns: True\n \"\"\"\n\n if self.does_consume(contract):\n return True\n self._add_relation(contract, 'consumed')\n return True\n\n def does_consume(self, contract):\n \"\"\"\n Check if this EPG consumes a specific Contract\n\n :param contract: Instance of Contract class to check if it is\\\n consumed by this EPG.\n :returns: True or False. True if the EPG does consume the Contract.\n \"\"\"\n return self._has_relation(contract, 'consumed')\n\n def dont_consume(self, contract):\n \"\"\"\n Make this EPG not consume a Contract. It does not check to see\n if the Contract was already consumed\n\n :param contract: Instance of Contract class to be no longer consumed\\\n by this EPG.\n :returns: True\n \"\"\"\n self._remove_relation(contract, 'consumed')\n return True\n\n def get_all_consumed(self):\n \"\"\"\n Get all of the Contracts consumed by this EPG\n\n :returns: List of Contract objects that are consumed by the EPG.\n \"\"\"\n return self._get_all_relation(Contract, 'consumed')\n\n def get_interfaces(self, status='attached'):\n \"\"\"\n Get all of the interfaces that this EPG is attached.\n The default is to get list of 'attached' interfaces.\n If 'status' is set to 'detached' it will return the list of\n detached Interface objects (Those EPGs which are no longer\n attached to an Interface, but the configuration is not yet\n pushed to the APIC.)\n\n :param status: 'attached' or 'detached'. Defaults to 'attached'.\n :returns: List of Interface objects\n \"\"\"\n\n resp = []\n for relation in self._relations:\n if relation.item.is_interface() and relation.status == status:\n resp.append(relation.item)\n return resp\n\n def _get_common_json(self):\n \"\"\"Internal routine to generate JSON common to EPGs and Outside EPGs\"\"\"\n children = []\n for contract in self.get_all_provided():\n text = {'fvRsProv': {'attributes': {'tnVzBrCPName':\n contract.name}}}\n children.append(text)\n for contract in self.get_all_consumed():\n text = {'fvRsCons': {'attributes': {'tnVzBrCPName':\n contract.name}}}\n children.append(text)\n return children\n\n @classmethod\n def get(cls, session, parent, tenant):\n \"\"\"Gets all of the EPGs from the APIC.\n\n :param session: the instance of Session used for APIC communication\n :param parent: Instance of the AppProfile class used to limit the EPGs\\\n retreived from the APIC.\n :param tenant: Instance of Tenant class used to limit the EPGs\\\n retreived from the APIC.\n :returns: List of CommonEPG instances (or EPG instances if called\\\n from EPG class)\n \"\"\"\n return BaseACIObject.get(session, cls, 'fvAEPg', parent, tenant)\n\n\nclass EPG(CommonEPG):\n \"\"\" EPG : roughly equivalent to fvAEPg \"\"\"\n def __init__(self, epg_name, parent=None):\n \"\"\"\n Initializes the EPG with a name and, optionally,\n an AppProfile parent.\n If the parent is specified and is not an AppProfile,\n an error will occur.\n\n :param epg_name: String containing the name of the EPG.\n :param parent: Instance of the AppProfile class representing\\\n the Application Profile where this EPG is contained.\n \"\"\"\n if not isinstance(parent, AppProfile):\n raise TypeError('Parent must be instance of AppProfile')\n super(EPG, self).__init__(epg_name, parent)\n\n # Bridge Domain references\n def add_bd(self, bridgedomain):\n \"\"\"\n Add BridgeDomain to the EPG, roughly equivalent to fvRsBd\n\n :param bridgedomain: Instance of BridgeDomain class. Represents\\\n the BridgeDomain that this EPG will be assigned.\\\n An EPG can only be assigned to a single\\\n BridgeDomain.\n \"\"\"\n if not isinstance(bridgedomain, BridgeDomain):\n raise TypeError('add_bd not called with BridgeDomain')\n self._remove_all_relation(BridgeDomain)\n self._add_relation(bridgedomain)\n\n def remove_bd(self):\n \"\"\"\n Remove BridgeDomain from the EPG.\n Note that there should only be one BridgeDomain attached to the EPG.\n \"\"\"\n self._remove_all_relation(BridgeDomain)\n\n def get_bd(self):\n \"\"\"\n Return the assigned BridgeDomain.\n There should only be one item in the returned list.\n\n :returns: List of BridgeDomain objects\n \"\"\"\n return self._get_any_relation(BridgeDomain)\n\n def has_bd(self):\n \"\"\"\n Check if a BridgeDomain has been assigned to the EPG\n\n :returns: True or False. True if the EPG has been assigned\\\n a BridgeDomain.\n \"\"\"\n return self._has_any_relation(BridgeDomain)\n\n # Output\n def get_json(self):\n \"\"\"\n Returns json representation of the EPG\n\n :returns: json dictionary of the EPG\n \"\"\"\n children = super(EPG, self)._get_common_json()\n if self.has_bd():\n text = {'fvRsBd': {'attributes': {'tnFvBDName':\n self.get_bd().name}}}\n children.append(text)\n is_interfaces = False\n for interface in self.get_interfaces():\n is_interfaces = True\n text = {'fvRsPathAtt': {'attributes':\n {'encap': '%s-%s' % (interface.encap_type,\n interface.encap_id),\n 'tDn': interface._get_path()}}}\n children.append(text)\n if is_interfaces:\n text = {'fvRsDomAtt': {'attributes': {'tDn': 'uni/phys-allvlans'}}}\n children.append(text)\n\n is_vmms = False\n for vmm in self.get_all_attached(VMM):\n is_vmms = True\n text = {'fvRsDomAtt': {'attributes':\n {'tDn': vmm._get_path(),\n 'resImedcy': 'immediate'}}}\n children.append(text)\n\n for interface in self.get_interfaces('detached'):\n text = {'fvRsPathAtt': {'attributes':\n {'encap': '%s-%s' % (interface.encap_type,\n interface.encap_id),\n 'status': 'deleted',\n 'tDn': interface._get_path()}}}\n children.append(text)\n attr = self._generate_attributes()\n return super(EPG, self).get_json('fvAEPg',\n attributes=attr,\n children=children)\n\n\nclass OutsideEPG(CommonEPG):\n \"\"\"Represents the EPG for external connectivity\n \"\"\"\n def __init__(self, epg_name, parent=None):\n \"\"\"\n :param epg_name: String containing the name of this OutsideEPG\n :param parent: Instance of the Tenant class representing\\\n the tenant owning this OutsideEPG.\n \"\"\"\n if not isinstance(parent, Tenant):\n raise TypeError('Parent is not set to Tenant')\n super(OutsideEPG, self).__init__(epg_name, parent)\n\n def get_json(self):\n \"\"\"\n Returns json representation of OutsideEPG\n\n :returns: json dictionary of OutsideEPG\n \"\"\"\n children = []\n for interface in self.get_interfaces():\n if interface.is_ospf():\n ospf_if = interface\n text = {'ospfExtP': {'attributes': {'areaId': ospf_if.area_id},\n 'children': []}}\n children.append(text)\n text = {'l3extInstP': {'attributes': {'name': self.name},\n 'children': []}}\n for network in ospf_if.networks:\n subnet = {'l3extSubnet': {'attributes': {'ip': network},\n 'children': []}}\n contracts = super(OutsideEPG, self)._get_common_json()\n text['l3extInstP']['children'].append(subnet)\n for contract in contracts:\n text['l3extInstP']['children'].append(contract)\n children.append(text)\n for interface in self.get_interfaces():\n text = interface.get_json()\n children.append(text)\n attr = self._generate_attributes()\n return super(OutsideEPG, self).get_json('l3extOut',\n attributes=attr,\n children=children)\n\n\nclass L3Interface(BaseACIObject):\n \"\"\"\n Creates an L3 interface that can be attached to an L2 interface.\n This interface defines the L3 address i.e. IPv4\n \"\"\"\n def __init__(self, name):\n \"\"\"\n :param name: String containing the name of this L3Interface object.\n \"\"\"\n super(L3Interface, self).__init__(name)\n self._addr = None\n self._l3if_type = None\n\n def is_interface(self):\n \"\"\"\n Check if this is an interface object.\n\n :returns: True\n \"\"\"\n\n return True\n\n def get_addr(self):\n \"\"\"\n Get the L3 address assigned to this interface.\n The address is set via the L3Interface.set_addr() method\n\n :returns: String containing the L3 address in dotted decimal notation.\n \"\"\"\n return self._addr\n\n def set_addr(self, addr):\n \"\"\"\n Set the L3 address assigned to this interface\n\n :param addr: String containing the L3 address in dotted decimal\\\n notation.\n \"\"\"\n self._addr = addr\n\n def get_l3if_type(self):\n \"\"\"\n Get the l3if_type of this L3 interface.\n\n :returns: L3 interface type. Valid values are 'sub-interface',\\\n 'l3-port', and 'ext-svi'\n \"\"\"\n return self._l3if_type\n\n def set_l3if_type(self, l3if_type):\n \"\"\"\n Set the l3if_type of this L3 interface.\n\n :param l3if_type: L3 interface type. Valid values are 'sub-interface',\\\n 'l3-port', and 'ext-svi'\n \"\"\"\n if l3if_type not in ('sub-interface', 'l3-port', 'ext-svi'):\n raise ValueError(\"l3if_type is not one of 'sub-interface', \"\n \"'l3-port', or 'ext-svi'\")\n self._l3if_type = l3if_type\n\n # Context references\n def add_context(self, context):\n \"\"\"\n Add context to the EPG\n\n :param context: Instance of Context class to assign to this\\\n L3Interface.\n \"\"\"\n if self.has_context():\n self.remove_context()\n self._add_relation(context)\n\n def remove_context(self):\n \"\"\"\n Remove context from the EPG\n \"\"\"\n self._remove_all_relation(Context)\n\n def get_context(self):\n \"\"\"\n Return the assigned context\n\n :returns: Instance of Context class that this L3Interface is assigned.\\\n If no Context is assigned, None is returned.\n \"\"\"\n return self._get_any_relation(Context)\n\n def has_context(self):\n \"\"\"\n Check if the context has been assigned\n\n :returns: True or False. True if a Context has been assigned to this\\\n L3Interface.\n \"\"\"\n return self._has_any_relation(Context)\n\n def get_json(self):\n \"\"\"\n Returns json representation of L3Interface\n\n :returns: json dictionary of L3Interface\n \"\"\"\n text = {'l3extRsPathL3OutAtt':\n {'attributes':\n {'encap': '%s-%s' % (self.get_interfaces()[0].encap_type,\n self.get_interfaces()[0].encap_id),\n 'ifInstT': self.get_l3if_type(),\n 'addr': self.get_addr(),\n 'tDn': self.get_interfaces()[0]._get_path()},\n 'children': []}}\n return text\n\n\nclass OSPFInterface(BaseACIObject):\n \"\"\"\n Creates an OSPF router interface that can be attached to a L3 interface.\n This interface defines the OSPF area, authentication, etc.\n \"\"\"\n def __init__(self, name, area_id=None):\n \"\"\"\n :param name: String containing the name of this OSPFInterface object.\n :param area_id: String containing the OSPF area id of this interface.\\\n Default is None.\n \"\"\"\n super(OSPFInterface, self).__init__(name)\n self.area_id = area_id\n self.auth_key = None\n self.auth_type = None\n self.auth_keyid = None\n self.networks = []\n\n def is_interface(self):\n \"\"\"\n Returns whether this instance is considered an interface.\n\n :returns: True\n \"\"\"\n return True\n\n @staticmethod\n def is_ospf():\n \"\"\"\n :returns: True if this interface is an OSPF interface. In the case\\\n of OSPFInterface instances, this is always True.\n \"\"\"\n return True\n\n def get_json(self):\n \"\"\"\n Returns json representation of OSPFInterface\n\n :returns: json dictionary of OSPFInterface\n \"\"\"\n text = {'ospfIfP': {'attributes': {'authKey': self.auth_key,\n 'authKeyId': self.auth_keyid,\n 'authType': self.auth_type,\n 'name': self.name},\n 'children': []}}\n text = [text, self.get_interfaces()[0].get_json()]\n text = {'l3extLIfP': {'attributes': {'name': self.name},\n 'children': text}}\n text = {'l3extLNodeP': {'attributes': {'name': self.name},\n 'children': [text]}}\n return text\n\n\nclass OSPFRouter(BaseACIObject):\n \"\"\"\n Represents the global settings of the OSPF Router\n \"\"\"\n def __init__(self, name):\n \"\"\"\n :param name: String containing the name of this OSPFRouter object.\n \"\"\"\n super(OSPFRouter, self).__init__(name)\n self._router_id = None\n self._node = None\n\n\nclass BridgeDomain(BaseACIObject):\n \"\"\"\n BridgeDomain : roughly equivalent to fvBD\n \"\"\"\n def __init__(self, bd_name, parent=None):\n \"\"\"\n :param bd_name: String containing the name of this BridgeDomain\\\n object.\n :param parent: An instance of Tenant class representing the Tenant\\\n which contains this BridgeDomain.\n \"\"\"\n if parent is None or not isinstance(parent, Tenant):\n raise TypeError\n super(BridgeDomain, self).__init__(bd_name, parent)\n\n def get_json(self):\n \"\"\"\n Returns json representation of the bridge domain\n\n :returns: json dictionary of bridge domain\n \"\"\"\n children = []\n if self.has_context():\n text = {'fvRsCtx': {'attributes':\n {'tnFvCtxName': self.get_context().name}}}\n children.append(text)\n attr = self._generate_attributes()\n return super(BridgeDomain, self).get_json('fvBD',\n attributes=attr,\n children=children)\n\n # Context references\n def add_context(self, context):\n \"\"\"\n Set the Context for this BD\n\n :param context: Context to assign this BridgeDomain\n \"\"\"\n self._add_relation(context)\n\n def remove_context(self):\n \"\"\"\n Remove the assigned Context from this BD\n \"\"\"\n self._remove_all_relation(Context)\n\n def get_context(self):\n \"\"\"\n Get the Context for this BD\n\n :returns: Instance of Context class that this BridgeDomain is assigned.\n \"\"\"\n return self._get_any_relation(Context)\n\n def has_context(self):\n \"\"\"\n Check if the Context has been set for this BD\n\n :returns: True or False. True if this BridgeDomain is assigned to a\\\n Context.\n \"\"\"\n return self._has_any_relation(Context)\n\n # Subnet\n def add_subnet(self, subnet):\n \"\"\"\n Add a subnet to this BD.\n\n :param subnet: Instance of Subnet class to add to this BridgeDomain.\n \"\"\"\n if not isinstance(subnet, Subnet):\n raise TypeError('add_subnet requires a Subnet instance')\n if subnet.get_addr() is None:\n raise ValueError('Subnet address is not set')\n if subnet in self.get_subnets():\n return\n self.add_child(subnet)\n\n def remove_subnet(self, subnet):\n \"\"\"\n Remove a subnet from this BD\n\n :param subnet: Instance of Subnet class to remove from this\\\n BridgeDomain.\n \"\"\"\n if not isinstance(subnet, Subnet):\n raise TypeError('remove_subnet requires a Subnet instance')\n self.remove_child(subnet)\n\n def get_subnets(self):\n \"\"\"\n Get all of the subnets on this BD.\n\n :returns: List of Subnet instances assigned to this BridgeDomain.\n \"\"\"\n resp = []\n children = self.get_children()\n for child in children:\n if isinstance(child, Subnet):\n resp.append(child)\n return resp\n\n def has_subnet(self, subnet):\n \"\"\"\n Check if the BD has this particular subnet.\n\n :returns: True or False. True if this BridgeDomain has this\\\n particular Subnet.\n \"\"\"\n if not isinstance(subnet, Subnet):\n raise TypeError('has_subnet requires a Subnet instance')\n if subnet.get_addr() is None:\n raise ValueError('Subnet address is not set')\n return self.has_child(subnet)\n\n @classmethod\n def get(cls, session, tenant):\n \"\"\"\n Gets all of the Bridge Domains from the APIC.\n\n :param session: the instance of Session used for APIC communication\n :param tenant: the instance of Tenant used to limit the BridgeDomain\\\n instances retreived from the APIC\n :returns: List of BridgeDomain objects\n \"\"\"\n return BaseACIObject.get(session, cls, 'fvBD', tenant, tenant)\n\n def _get_url_extension(self):\n return '/BD-%s' % self.name\n\n\nclass Subnet(BaseACIObject):\n \"\"\" Subnet : roughly equivalent to fvSubnet \"\"\"\n def __init__(self, subnet_name, parent=None):\n \"\"\"\n :param subnet_name: String containing the name of this Subnet instance.\n :param parent: An instance of BridgeDomain class representing the\\\n BridgeDomain which contains this Subnet.\n \"\"\"\n if not isinstance(parent, BridgeDomain):\n raise TypeError('Parent of Subnet class must be BridgeDomain')\n super(Subnet, self).__init__(subnet_name, parent)\n self._addr = None\n\n def get_addr(self):\n \"\"\"\n Get the subnet address\n\n :returns: The subnet address as a string in the form of <ipaddr>/<mask>\n \"\"\"\n return self._addr\n\n def set_addr(self, addr):\n \"\"\"\n Set the subnet address\n\n :param addr: The subnet address as a string in the form\\\n of <ipaddr>/<mask>\n \"\"\"\n if addr is None:\n raise TypeError('Address can not be set to None')\n self._addr = addr\n\n def get_json(self):\n \"\"\"\n Returns json representation of the subnet\n\n :returns: json dictionary of subnet\n \"\"\"\n attributes = self._generate_attributes()\n if self.get_addr() is None:\n raise ValueError('Subnet address is not set')\n attributes['ip'] = self.get_addr()\n return super(Subnet, self).get_json('fvSubnet', attributes=attributes)\n\n def _populate_from_attributes(self, attributes):\n \"\"\"\n Sets the attributes when creating objects from the APIC.\n Called from the base object when calling the classmethod get()\n \"\"\"\n self.set_addr(attributes['ip'])\n\n @classmethod\n def get(cls, session, bridgedomain, tenant):\n \"\"\"\n Gets all of the Subnets from the APIC for a particular tenant and\n bridgedomain.\n\n :param session: the instance of Session used for APIC communication\n :param bridgedomain: the instance of BridgeDomain used to limit the\\\n Subnet instances retreived from the APIC\n :param tenant: the instance of Tenant used to limit the Subnet\\\n instances retreived from the APIC\n :returns: List of Subnet objects\n\n \"\"\"\n return BaseACIObject.get(session, cls, 'fvSubnet',\n parent=bridgedomain, tenant=tenant)\n\n\nclass Context(BaseACIObject):\n \"\"\" Context : roughly equivalent to fvCtx \"\"\"\n def __init__(self, context_name, parent=None):\n \"\"\"\n :param context_name: String containing the Context name\n :param parent: An instance of Tenant class representing the Tenant\\\n which contains this Context.\n\n \"\"\"\n super(Context, self).__init__(context_name, parent)\n self._allow_all = False\n\n def set_allow_all(self, value=True):\n \"\"\"\n Set the allow_all value. When set, contracts will not be enforced\\\n in this context.\n\n :param value: True or False. Default is True.\n \"\"\"\n self._allow_all = value\n\n def get_allow_all(self):\n \"\"\"\n Returns the allow_all value from this Context. When set, contracts\\\n will not be enforced in this context.\n\n :returns: True or False.\n \"\"\"\n return self._allow_all\n\n def get_json(self):\n \"\"\"\n Returns json representation of fvCtx object\n\n :returns: json dictionary of fvCtx object\n \"\"\"\n attributes = self._generate_attributes()\n if self.get_allow_all():\n attributes['pcEnfPref'] = 'unenforced'\n else:\n attributes['pcEnfPref'] = 'enforced'\n return super(Context, self).get_json('fvCtx', attributes=attributes)\n\n @classmethod\n def get(cls, session, tenant):\n \"\"\"\n Gets all of the Contexts from the APIC.\n\n :param session: the instance of Session used for APIC communication\n :param tenant: the instance of Tenant used to limit the Contexts\\\n retreived from the APIC\n :returns: List of Context objects\n \"\"\"\n return BaseACIObject.get(session, cls, 'fvCtx', tenant, tenant)\n\n\nclass BaseContract(BaseACIObject):\n \"\"\" BaseContract : Base class for Contracts and Taboos \"\"\"\n def __init__(self, contract_name, contract_type='vzBrCP', parent=None):\n super(BaseContract, self).__init__(contract_name, parent)\n self._scope = 'context'\n\n @staticmethod\n def _get_contract_code():\n raise NotImplementedError\n\n @staticmethod\n def _get_subject_code():\n raise NotImplementedError\n\n @staticmethod\n def _get_subject_relation_code():\n raise NotImplementedError\n\n def set_scope(self, scope):\n \"\"\"Set the scope of this contract.\n Valid values are 'context', 'global', 'tenant', and\n 'application-profile'\n \"\"\"\n if scope not in ('context', 'global', 'tenant', 'application-profile'):\n raise ValueError\n self._scope = scope\n\n def get_scope(self):\n \"\"\"Get the scope of this contract.\n Valid values are 'context', 'global', 'tenant', and\n 'application-profile'\n \"\"\"\n return self._scope\n\n def get_json(self):\n \"\"\"\n Returns json representation of the contract\n\n :returns: json dictionary of the contract\n \"\"\"\n resp_json = []\n subj_code = self._get_subject_code()\n subj_relation_code = self._get_subject_relation_code()\n attributes = self._generate_attributes()\n\n contract_code = self._get_contract_code()\n contract = super(BaseContract, self).get_json(contract_code,\n attributes=attributes,\n get_children=False)\n # Create a subject for every entry with a relation to the filter\n subjects = []\n for entry in self.get_children():\n subject_name = self.name + entry.name\n subject = {subj_code: {'attributes': {'name': subject_name}}}\n filt_name = subject_name\n filt = {subj_relation_code:\n {'attributes': {'tnVzFilterName': filt_name}}}\n subject[subj_code]['children'] = [filt]\n subjects.append(subject)\n contract[self._get_contract_code()]['children'] = subjects\n resp_json.append(contract)\n for entry in self.get_children():\n entry_json = entry.get_json()\n if entry_json is not None:\n resp_json.append(entry_json)\n return resp_json\n\n\nclass Contract(BaseContract):\n \"\"\" Contract : Class for Contracts \"\"\"\n def __init__(self, contract_name, parent=None):\n super(Contract, self).__init__(contract_name, 'vzBrCP', parent)\n\n @staticmethod\n def _get_contract_code():\n return 'vzBrCP'\n\n @staticmethod\n def _get_subject_code():\n return 'vzSubj'\n\n @staticmethod\n def _get_subject_relation_code():\n return 'vzRsSubjFiltAtt'\n\n def _generate_attributes(self):\n attributes = super(Contract, self)._generate_attributes()\n attributes['scope'] = self.get_scope()\n return attributes\n\n @classmethod\n def get(cls, session, tenant):\n \"\"\"Gets all of the Contracts from the APIC for a particular tenant.\n \"\"\"\n return BaseACIObject.get(session, cls, cls._get_contract_code(),\n tenant, tenant)\n\n\nclass Taboo(BaseContract):\n \"\"\" Taboo : Class for Taboos \"\"\"\n def __init__(self, contract_name, parent=None):\n super(Taboo, self).__init__(contract_name, self._get_contract_code(),\n parent)\n\n @staticmethod\n def _get_contract_code():\n return 'vzTaboo'\n\n @staticmethod\n def _get_subject_code():\n return 'vzTSubj'\n\n @staticmethod\n def _get_subject_relation_code():\n return 'vzRsDenyRule'\n\n\nclass FilterEntry(BaseACIObject):\n \"\"\" FilterEntry : roughly equivalent to vzEntry \"\"\"\n def __init__(self, name, applyToFrag, arpOpc, dFromPort, dToPort,\n etherT, prot, sFromPort, sToPort, tcpRules, parent):\n \"\"\"\n :param name: String containing the name of this FilterEntry instance.\n :param applyToFrag: True or False. True indicates that this\\\n FilterEntry should be applied to IP fragments.\n :param arpOpc: 'req' or 'reply'. Indicates that this FilterEntry\\\n should be applied to ARP Requests or ARP replies.\n :param dFromPort: String containing the lower L4 destination port\\\n number of the L4 destination port number range.\n :param dToPort: String containing the upper L4 destination port\\\n number of the L4 destination port number range.\n :param etherT: String containing the EtherType of the frame to be\\\n matched by this FilterEntry.\n :param prot: String containing the L4 protocol number to be\\\n matched by this FilterEntry.\n :param sFromPort: String containing the lower L4 source port\\\n number of the L4 source port number range.\n :param sToPort: String containing the upper L4 source port\\\n number of the L4 source port number range.\n :param tcpRules: Bit mask consisting of the TCP flags to be matched\\\n by this FilterEntry.\n \"\"\"\n self.applyToFrag = applyToFrag\n self.arpOpc = arpOpc\n self.dFromPort = dFromPort\n self.dToPort = dToPort\n self.etherT = etherT\n self.prot = prot\n self.sFromPort = sFromPort\n self.sToPort = sToPort\n self.tcpRules = tcpRules\n super(FilterEntry, self).__init__(name, parent)\n\n def _generate_attributes(self):\n attributes = super(FilterEntry, self)._generate_attributes()\n attributes['applyToFrag'] = self.applyToFrag\n attributes['arpOpc'] = self.arpOpc\n attributes['dFromPort'] = self.dFromPort\n attributes['dToPort'] = self.dToPort\n attributes['etherT'] = self.etherT\n attributes['prot'] = self.prot\n attributes['sFromPort'] = self.sFromPort\n attributes['sToPort'] = self.sToPort\n attributes['tcpRules'] = self.tcpRules\n return attributes\n\n def get_json(self):\n \"\"\"\n Returns json representation of the FilterEntry\n\n :returns: json dictionary of the FilterEntry\n \"\"\"\n attr = self._generate_attributes()\n text = super(FilterEntry, self).get_json('vzEntry',\n attributes=attr)\n filter_name = self.get_parent().name + self.name\n text = {'vzFilter': {'attributes': {'name': filter_name},\n 'children': [text]}}\n return text\n\n\nclass BaseInterface(BaseACIObject):\n \"\"\"Abstract class used to provide base functionality to other Interface\n classes.\n \"\"\"\n def _get_port_selector_json(self, port_type, port_name):\n \"\"\"Returns the json used for selecting the specified interfaces\n \"\"\"\n name = self._get_name_for_json()\n port_blk = {'name': name,\n 'fromCard': self.module,\n 'toCard': self.module,\n 'fromPort': self.port,\n 'toPort': self.port}\n port_blk = {'infraPortBlk': {'attributes': port_blk,\n 'children': []}}\n pc_url = 'uni/infra/funcprof/%s-%s' % (port_type, port_name)\n accbasegrp = {'infraRsAccBaseGrp': {'attributes': {'tDn': pc_url},\n 'children': []}}\n portselect = {'infraHPortS': {'attributes': {'name': name,\n 'type': 'range'},\n 'children': [port_blk, accbasegrp]}}\n accport_selector = {'infraAccPortP': {'attributes': {'name': name},\n 'children': [portselect]}}\n node_blk = {'name': name,\n 'from_': self.node, 'to_': self.node}\n node_blk = {'infraNodeBlk': {'attributes': node_blk, 'children': []}}\n leaf_selector = {'infraLeafS': {'attributes': {'name': name,\n 'type': 'range'},\n 'children': [node_blk]}}\n accport = {'infraRsAccPortP':\n {'attributes': {'tDn': 'uni/infra/accportprof-%s' % name},\n 'children': []}}\n node_profile = {'infraNodeP': {'attributes': {'name': name},\n 'children': [leaf_selector,\n accport]}}\n return node_profile, accport_selector\n\n def get_port_selector_json(self):\n return self._get_port_selector_json('accportgrp',\n self._get_name_for_json())\n\n def get_port_channel_selector_json(self, port_name):\n return self._get_port_selector_json('accbundle', port_name)\n\n\nclass Interface(BaseInterface):\n \"\"\"This class defines a physical interface.\n \"\"\"\n def __init__(self, interface_type, pod, node, module, port, parent=None, session=None):\n# if parent :\n# if not isinstance(parent, Linecard):\n# raise TypeError('An instance of Linecard class is required as the parent')\n self._session = session\n self.interface_type = str(interface_type)\n self.pod = str(pod)\n self.node = str(node)\n self.module = str(module)\n self.port = str(port)\n self.if_name = self.interface_type + ' ' + self.pod + '/'\n self.if_name += self.node + '/' + self.module + '/' + self.port\n super(Interface, self).__init__(self.if_name, None)\n self.porttype = ''\n self.adminstatus = '' # up or down\n self.speed = '10G' # 100M, 1G, 10G or 40G\n self.mtu = ''\n self._cdp_config = None\n self._lldp_config = None\n self.type = 'interface'\n self.id = interface_type+module+'/'+port\n self._parent = parent\n if parent:\n self._parent.add_child(self)\n self.stats = Stats(self._session, counters=self._initStats())\n\n def is_interface(self):\n \"\"\"\n Returns whether this instance is considered an interface.\n\n :returns: True\n \"\"\"\n return True\n\n def is_cdp_enabled(self):\n \"\"\"\n Returns whether this interface has CDP configured as enabled.\n\n :returns: True or False\n \"\"\"\n return self._cdp_config == 'enabled'\n\n def enable_cdp(self):\n \"\"\"\n Enables CDP on this interface.\n \"\"\"\n self._cdp_config = 'enabled'\n\n def disable_cdp(self):\n \"\"\"\n Disables CDP on this interface.\n \"\"\"\n self._cdp_config = 'disabled'\n\n def is_lldp_enabled(self):\n \"\"\"\n Returns whether this interface has LLDP configured as enabled.\n\n :returns: True or False\n \"\"\"\n return self._lldp_config == 'enabled'\n\n def enable_lldp(self):\n \"\"\"\n Enables LLDP on this interface.\n \"\"\"\n self._lldp_config = 'enabled'\n\n def disable_lldp(self):\n \"\"\"\n Disables LLDP on this interface.\n \"\"\"\n self._lldp_config = 'disabled'\n\n def get_type(self):\n return self.type\n\n def get_serial(self):\n return None\n\n def get_url(self):\n phys_domain_url = '/api/mo/uni.json'\n fabric_url = '/api/mo/uni/fabric.json'\n infra_url = '/api/mo/uni.json'\n return phys_domain_url, fabric_url, infra_url\n\n def _get_name_for_json(self):\n return '%s-%s-%s-%s' % (self.pod, self.node,\n self.module, self.port)\n\n def get_json(self):\n \"\"\" Get the json for an interface. Returns a tuple since the json is\n required to be sent in 2 posts.\n \"\"\"\n fabric = None\n # Physical Domain json\n vlan_ns_dn = 'uni/infra/vlanns-allvlans-static'\n vlan_ns_ref = {'infraRsVlanNs': {'attributes':\n {'tDn': vlan_ns_dn},\n 'children': []}}\n phys_domain = {'physDomP': {'attributes': {'name': 'allvlans'},\n 'children': [vlan_ns_ref]}}\n\n # Infra json\n infra = {'infraInfra': {'children': []}}\n node_profile, accport_selector = self.get_port_selector_json()\n infra['infraInfra']['children'].append(node_profile)\n infra['infraInfra']['children'].append(accport_selector)\n speed_name = 'speed%s' % self.speed\n hifpol_dn = 'uni/infra/hintfpol-%s' % speed_name\n speed = {'fabricHIfPol': {'attributes': {'autoNeg': 'on',\n 'dn': hifpol_dn,\n 'name': speed_name,\n 'speed': self.speed},\n 'children': []}}\n infra['infraInfra']['children'].append(speed)\n name = self._get_name_for_json()\n accportgrp_dn = 'uni/infra/funcprof/accportgrp-%s' % name\n speed_attr = {'tnFabricHIfPolName': speed_name}\n speed_children = {'infraRsHIfPol': {'attributes': speed_attr,\n 'children': []}}\n cdp_children = None\n if self._cdp_config is not None:\n cdp_data = {'tnCdpIfPolName': 'CDP_%s' % self._cdp_config}\n cdp_children = {'infraRsCdpIfPol': {'attributes': cdp_data}}\n lldp_children = None\n if self._lldp_config is not None:\n lldp_data = {'tnLldpIfPolName': 'LLDP_%s' % self._lldp_config}\n lldp_children = {'infraRsLldpIfPol': {'attributes': lldp_data}}\n att_ent_dn = 'uni/infra/attentp-allvlans'\n att_ent_p = {'infraRsAttEntP': {'attributes': {'tDn': att_ent_dn},\n 'children': []}}\n speed_ref = {'infraAccPortGrp': {'attributes': {'dn': accportgrp_dn,\n 'name': name},\n 'children': [speed_children,\n att_ent_p]}}\n if cdp_children is not None:\n speed_ref['infraAccPortGrp']['children'].append(cdp_children)\n if lldp_children is not None:\n speed_ref['infraAccPortGrp']['children'].append(lldp_children)\n speed_ref = {'infraFuncP': {'attributes': {}, 'children': [speed_ref]}}\n infra['infraInfra']['children'].append(speed_ref)\n\n phys_dom_dn = 'uni/phys-allvlans'\n rs_dom_p = {'infraRsDomP': {'attributes': {'tDn': phys_dom_dn}}}\n infra_att_entity_p = {'infraAttEntityP': {'attributes':\n {'name': 'allvlans'},\n 'children': [rs_dom_p]}}\n infra['infraInfra']['children'].append(infra_att_entity_p)\n\n if self._cdp_config is not None:\n cdp_if_pol = {'cdpIfPol': {'attributes': {'adminSt': self._cdp_config,\n 'name': 'CDP_%s' % self._cdp_config}}}\n infra['infraInfra']['children'].append(cdp_if_pol)\n\n if self._lldp_config is not None:\n lldp_if_pol = {'lldpIfPol': {'attributes': {'adminRxSt': self._lldp_config,\n 'adminTxSt': self._lldp_config,\n 'name': 'LLDP_%s' % self._lldp_config}}}\n infra['infraInfra']['children'].append(lldp_if_pol)\n\n if self.adminstatus != '':\n adminstatus_attributes = {}\n adminstatus_attributes['tDn'] = self._get_path()\n if self.adminstatus == 'up':\n admin_dn = 'uni/fabric/outofsvc/rsoosPath-['\n admin_dn = admin_dn + self._get_path() + ']'\n adminstatus_attributes['dn'] = admin_dn\n adminstatus_attributes['status'] = 'deleted'\n else:\n adminstatus_attributes['lc'] = 'blacklist'\n adminstatus_json = {'fabricRsOosPath':\n {'attributes': adminstatus_attributes,\n 'children': []}}\n fabric = {'fabricOOServicePol': {'children': [adminstatus_json]}}\n\n fvns_encap_blk = {'fvnsEncapBlk': {'attributes': {'name': 'encap',\n 'from': 'vlan-1',\n 'to': 'vlan-4092'}}}\n fvns_vlan_inst_p = {'fvnsVlanInstP': {'attributes':\n {'name': 'allvlans',\n 'allocMode': 'static'},\n 'children': [fvns_encap_blk]}}\n infra['infraInfra']['children'].append(fvns_vlan_inst_p)\n\n return phys_domain, fabric, infra\n\n def _get_path(self):\n \"\"\"Get the path of this interface used when communicating with\n the APIC object model.\n \"\"\"\n return 'topology/pod-%s/paths-%s/pathep-[eth%s/%s]' % (self.pod,\n self.node,\n self.module,\n self.port)\n\n @staticmethod\n def parse_name(name):\n \"\"\"Parses a name that is of the form:\n <type> <pod>/<mod>/<port>\n \"\"\"\n interface_type = name.split()[0]\n name = name.split()[1]\n (pod, node, module, port) = name.split('/')\n return interface_type, pod, node, module, port\n\n @staticmethod\n def _parse_physical_dn(dn):\n \"\"\"\n Handles DNs that look like the following:\n topology/pod-1/node-103/sys/phys-[eth1/12]\n \"\"\"\n name = dn.split('/')\n pod = name[1].split('-')[1]\n node = name[2].split('-')[1]\n module = name[4].split('[')[1]\n interface_type = module[:3]\n module = module[3:]\n port = name[5].split(']')[0]\n #id = re.search('\\[(.+)\\]',dn).group(1)\n return interface_type, pod, node, module, port\n\n @staticmethod\n def _parse_path_dn(dn):\n \"\"\"\n Handles DNs that look like the following:\n topology/pod-1/paths-102/pathep-[eth1/12]\n \"\"\"\n name = dn.split('/')\n pod = name[1].split('-')[1]\n node = name[2].split('-')[1]\n module = name[3].split('[')[1]\n interface_type = module[:3]\n module = module[3:]\n port = name[4].split(']')[0]\n #id = re.search('\\[(.+)\\]',dn).group(1)\n return interface_type, pod, node, module, port\n\n @classmethod\n def parse_dn(cls, dn):\n \"\"\"\n Parses the pod, node, module, port from a distinguished name\n of the interface.\n\n :param dn: String containing the interface distinguished name\n :returns: interface_type, pod, node, module, port\n \"\"\"\n if 'sys' in dn.split('/'):\n return cls._parse_physical_dn(dn)\n else:\n return cls._parse_path_dn(dn)\n\n @staticmethod\n def get(session, parent=None):\n \"\"\"\n Gets all of the physical interfaces from the APIC if no parent is specified.\n If a parent, of type Linecard is specified, then only those interfaces on\n that linecard are returned and they are also added as children to that linecard.\n\n :param session: the instance of Session used for APIC communication\n :param parent: Linecard instance to limit interfaces (optional)\n\n :returns: list of Interface instances\n \"\"\"\n if not isinstance(session, Session):\n raise TypeError('An instance of Session class is required')\n\n interface_query_url = '/api/node/class/l1PhysIf.json?query-target=self'\n ret = session.get(interface_query_url)\n resp = []\n interface_data = ret.json()['imdata']\n for interface in interface_data:\n dist_name = str(interface['l1PhysIf']['attributes']['dn'])\n porttype = str(interface['l1PhysIf']['attributes']['portT'])\n adminstatus = str(interface['l1PhysIf']['attributes']['adminSt'])\n speed = str(interface['l1PhysIf']['attributes']['speed'])\n mtu = str(interface['l1PhysIf']['attributes']['mtu'])\n id = str(interface['l1PhysIf']['attributes']['id'])\n (interface_type, pod, node,\n module, port) = Interface.parse_dn(dist_name)\n interface_obj = Interface(interface_type, pod, node, module, port, parent=None, session=session)\n interface_obj.porttype = porttype\n interface_obj.adminstatus = adminstatus\n interface_obj.speed = speed\n interface_obj.mtu = mtu\n\n if parent:\n if interface_obj.pod == parent.pod and interface_obj.node == parent.node and interface_obj.module == parent.slot:\n resp.append(interface_obj)\n else:\n resp.append(interface_obj)\n return resp\n\n def __str__(self):\n items = [self.if_name, '\\t', self.porttype, '\\t',\n self.adminstatus, '\\t', self.speed, '\\t',\n self.mtu]\n ret = ''.join(items)\n return ret\n\n def _initStats(self):\n \"\"\"This method will create the data structure for the statistics.\n The format is [(dn,[attribute,name]),...] where 'dn' is the dn of\n the managed object that contains the counter. 'attribute' is the\n name of the attribute that is the counter. 'name' is the name used\n by the toolkit to access the counter value.\n\n :returns: list of counters\n \"\"\"\n\n result = []\n counters = [('dropEvents', 'drops'),\n ('multicastPkts', 'multicastPkts'),\n ('octets', 'octets'),\n ('rXNoErrors', 'rxPackets'),\n ('tXNoErrors', 'txPackets'),\n ]\n dn = 'topology/pod-'+self.pod+'/node-'+self.node+'/sys/phys-['+self.id+']/dbgEtherStats'\n result.append((dn, counters))\n return result\n\n\nclass PortChannel(BaseInterface):\n \"\"\"\n This class defines a port channel interface.\n \"\"\"\n def __init__(self, name):\n super(PortChannel, self).__init__(name)\n self._interfaces = []\n self._nodes = []\n\n def attach(self, interface):\n \"\"\"Attach an interface to this PortChannel\"\"\"\n if interface not in self._interfaces:\n self._interfaces.append(interface)\n self._update_nodes()\n\n def detach(self, interface):\n \"\"\"Detach an interface from this PortChannel\"\"\"\n if interface in self._interfaces:\n self._interfaces.remove(interface)\n self._update_nodes()\n\n def _update_nodes(self):\n \"\"\"Updates the nodes that are participating in this PortChannel\"\"\"\n nodes = []\n for interface in self._interfaces:\n nodes.append(interface.node)\n self._nodes = set(nodes)\n\n def is_vpc(self):\n \"\"\"Returns True if the PortChannel is a VPC\"\"\"\n return len(self._nodes) > 1\n\n def is_interface(self):\n \"\"\"Returns True since a PortChannel is an interface\"\"\"\n return True\n\n def _get_nodes(self):\n \"\"\" Returns a single node id or multiple node ids in the\n case that this is a VPC\n \"\"\"\n return self._nodes\n\n def _get_path(self):\n \"\"\"Get the path of this interface used when communicating with\n the APIC object model.\n \"\"\"\n assert len(self._interfaces)\n pod = self._interfaces[0].pod\n if self.is_vpc():\n (node1, node2) = self._get_nodes()\n path = 'topology/pod-%s/protpaths-%s-%s/pathep-[%s]' % (pod,\n node1,\n node2,\n self.name)\n else:\n node = self._interfaces[0].node\n path = 'topology/pod-%s/paths-%s/pathep-%s' % (pod,\n node,\n self.name)\n\n return path\n\n def get_json(self):\n \"\"\"\n Returns json representation of the PortChannel\n\n :returns: json dictionary of the PortChannel\n \"\"\"\n vpc = self.is_vpc()\n pc_mode = 'link'\n if vpc:\n pc_mode = 'node'\n infra = {'infraInfra': {'children': []}}\n # Add the node and port selectors\n for interface in self._interfaces:\n node_profile, accport_selector = interface.get_port_channel_selector_json(self.name)\n infra['infraInfra']['children'].append(node_profile)\n infra['infraInfra']['children'].append(accport_selector)\n # Add the actual port-channel\n accbndlgrp = {'infraAccBndlGrp':\n {'attributes':\n {'name': self.name, 'lagT': pc_mode},\n 'children': []}}\n infrafuncp = {'infraFuncP': {'attributes': {},\n 'children': [accbndlgrp]}}\n infra['infraInfra']['children'].append(infrafuncp)\n\n if not vpc:\n return None, infra\n\n # VPC add Fabric Protocol Policy\n # Pick the lowest node as the unique id for the vpc group\n nodes = []\n for interface in self._interfaces:\n nodes.append(str(interface.node))\n unique_nodes = sorted(set(nodes))\n unique_id = unique_nodes[0]\n\n fabric_nodes = []\n for node in unique_nodes:\n fabric_node = {'fabricNodePEp': {'attributes': {'id': node}}}\n fabric_nodes.append(fabric_node)\n fabric_group = {'fabricExplicitGEp':\n {'attributes':\n {'name': 'vpc' + unique_id, 'id': unique_id},\n 'children': fabric_nodes}}\n fabric_prot_pol = {'fabricProtPol': {'attributes':\n {'name': 'vpc' + unique_id},\n 'children': [fabric_group]}}\n\n return fabric_prot_pol, infra\n\n @staticmethod\n def get(session):\n \"\"\"Gets all of the port channel interfaces from the APIC\n \"\"\"\n if not isinstance(session, Session):\n raise TypeError('An instance of Session class is required')\n interface_query_url = ('/api/node/class/infraAccBndlGrp.json?'\n 'query-target=self')\n portchannels = []\n ret = session.get(interface_query_url)\n pc_data = ret.json()['imdata']\n for pc in pc_data:\n portchannel_name = str(pc['infraAccBndlGrp']['attributes']['name'])\n portchannel = PortChannel(portchannel_name)\n portchannels.append(portchannel)\n return portchannels\n\n\nclass Endpoint(BaseACIObject):\n @staticmethod\n def get(session):\n \"\"\"Gets all of the endpoints connected to the fabric from the APIC\n \"\"\"\n if not isinstance(session, Session):\n raise TypeError('An instance of Session class is required')\n\n # Get all of the interfaces\n interface_query_url = ('/api/node/class/fabricPathEp.json?'\n 'query-target=self')\n ret = session.get(interface_query_url)\n interfaces = ret.json()['imdata']\n\n # Get all of the Endpoints\n endpoint_query_url = ('/api/node/class/fvCEp.json?'\n 'query-target=self&rsp-subtree=full')\n endpoints = []\n ret = session.get(endpoint_query_url)\n ep_data = ret.json()['imdata']\n for ep in ep_data:\n children = ep['fvCEp']['children']\n ep = ep['fvCEp']['attributes']\n endpoint = Endpoint(str(ep['name']))\n endpoint.mac = str(ep['mac'])\n endpoint.ip = str(ep['ip'])\n endpoint.encap = str(ep['encap'])\n endpoint.epg = str(ep['dn']).split('/')[3][4:]\n endpoint.tenant = str(ep['dn']).split('/')[1][3:]\n endpoint.app_profile = str(ep['dn']).split('/')[2][3:]\n for child in children:\n if 'fvRsCEpToPathEp' in child:\n endpoint.if_name = str(child['fvRsCEpToPathEp']['attributes']['tDn'])\n for interface in interfaces:\n interface = interface['fabricPathEp']['attributes']\n interface_dn = str(interface['dn'])\n if endpoint.if_name == interface_dn:\n if str(interface['lagT']) == 'not-aggregated':\n endpoint.if_name = Interface(*Interface.parse_dn(interface_dn)).if_name\n else:\n endpoint.if_name = interface['name']\n endpoint_query_url = '/api/mo/' + endpoint.if_name + '.json'\n ret = session.get(endpoint_query_url)\n endpoints.append(endpoint)\n return endpoints\n\n\nclass NetworkPool(BaseACIObject):\n \"\"\"This class defines a pool of network ids\n \"\"\"\n def __init__(self, name, encap_type, start_id, end_id, mode):\n super(NetworkPool, self).__init__(name)\n valid_encap_types = ['vlan', 'vxlan']\n if encap_type not in valid_encap_types:\n raise ValueError('Encap type specified is not a valid encap type')\n self.encap_type = encap_type\n self.start_id = start_id\n self.end_id = end_id\n valid_modes = ['static', 'dynamic']\n if mode not in valid_modes:\n raise ValueError('Mode specified is not a valid mode')\n self.mode = mode\n\n def get_json(self):\n from_id = self.encap_type + '-' + self.start_id\n to_id = self.encap_type + '-' + self.end_id\n fvnsEncapBlk = {'fvnsEncapBlk': {'attributes': {'name': 'encap',\n 'from': from_id,\n 'to': to_id},\n 'children': []}}\n if self.encap_type == 'vlan':\n fvnsEncapInstP_string = 'fvnsVlanInstP'\n elif self.encap_type == 'vxlan':\n fvnsEncapInstP_string = 'fvnsVxlanInstP'\n fvnsEncapInstP = {fvnsEncapInstP_string: {'attributes': {'name': self.name,\n 'allocMode': self.mode},\n 'children': [fvnsEncapBlk]}}\n infra = {'infraInfra': {'attributes': {},\n 'children': [fvnsEncapInstP]}}\n return infra\n\n\nclass VMMCredentials(BaseACIObject):\n \"\"\"This class defines the credentials used to login to a Virtual\n Machine Manager\n \"\"\"\n def __init__(self, name, uid, pwd):\n super(VMMCredentials, self).__init__(name)\n self.uid = uid\n self.pwd = pwd\n\n def get_json(self):\n vmmUsrAccP = {'vmmUsrAccP': {'attributes': {'name': self.name,\n 'usr': self.uid,\n 'pwd': self.pwd},\n 'children': []}}\n return vmmUsrAccP\n\n\nclass VMMvSwitchInfo(object):\n \"\"\"This class contains the information necessary for creating the\n vSwitch on the Virtual Machine Manager\n \"\"\"\n def __init__(self, vendor, container_name, vswitch_name):\n valid_vendors = ['VMware', 'Microsoft']\n if vendor not in valid_vendors:\n raise ValueError('Vendor specified is not in valid vendor list')\n self.vendor = vendor\n self.container_name = container_name\n self.vswitch_name = vswitch_name\n\n\nclass VMM(BaseACIObject):\n \"\"\"This class defines an instance of connectivity to a\n Virtual Machine Manager (such as VMware vCenter)\n \"\"\"\n def __init__(self, name, ipaddr, credentials, vswitch_info, network_pool):\n super(VMM, self).__init__(name)\n self.ipaddr = ipaddr\n self.credentials = credentials\n self.vswitch_info = vswitch_info\n self.network_pool = network_pool\n\n def _get_path(self):\n return 'uni/vmmp-%s/dom-%s' % (self.vswitch_info.vendor,\n self.vswitch_info.vswitch_name)\n\n def get_json(self):\n vmmUsrAccP = self.credentials.get_json()\n vmmUsrAccDn = 'uni/vmmp-%s/dom-%s/usracc-%s' % (self.vswitch_info.vendor,\n self.vswitch_info.vswitch_name,\n self.credentials.name)\n vmmRsAcc = {'vmmRsAcc': {'attributes': {'tDn': vmmUsrAccDn},\n 'children': []}}\n vmmCtrlrP = {'vmmCtrlrP': {'attributes': {'name': self.name,\n 'hostOrIp': self.ipaddr,\n 'rootContName': self.vswitch_info.container_name},\n 'children': [vmmRsAcc]}}\n infraNsDn = 'uni/infra/%sns-%s-%s' % (self.network_pool.encap_type,\n self.network_pool.name,\n self.network_pool.mode)\n\n if self.network_pool.encap_type == 'vlan':\n infraNsType = 'infraRsVlanNs'\n elif self.network_pool.encap_type == 'vxlan':\n infraNsType = 'infraRsVxlanNs'\n infraRsNs = {infraNsType: {'attributes': {'tDn': infraNsDn},\n 'children': []}}\n vmmDomP = {'vmmDomP': {'attributes': {'name': self.vswitch_info.vswitch_name},\n 'children': [vmmUsrAccP, vmmCtrlrP, infraRsNs]}}\n vmmProvP = {'vmmProvP': {'attributes': {'vendor': self.vswitch_info.vendor},\n 'children': [vmmDomP]}}\n\n return vmmProvP\n\n\nclass Search(BaseACIObject):\n \"\"\"This is an empty class used to create a search object for use with the \"find\" method.\n\n Attaching attributes to this class and then invoking find will return all objects with matching attributes\n in the object hierarchy at and below where the find is invoked.\n \"\"\"\n def __init__(self):\n pass\n","sub_path":"acitoolkit/acitoolkit.py","file_name":"acitoolkit.py","file_ext":"py","file_size_in_byte":65762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"110212520","text":"'''***************************************************************************\r\n*\r\n* FILE NAME:\r\n* bta_ext_if_genif_commandline.py\r\n*\r\n* DESCRIPTION:\r\n* This module will provide the services of command line.\r\n*\r\n*\r\n* REVISION HISTORY\r\n*\r\n* Date Author Reason\r\n* 13 Mar 2014 Rahul Goel Changes done for handling exception for PS data transfer.\r\n* 06 Dec 2009 Manish Gupta First Draft\r\n*\r\n*\r\n* Copyright 2009, ARICENT\r\n*\r\n*\r\n***************************************************************************'''\r\n\r\n# Import system modules\r\nimport time\r\nimport os\r\nimport string\r\nfrom threading import Semaphore\r\nimport re\r\n\r\n# Import user defined modules\r\nimport bta_util_constants as CONSTANTS\r\nfrom bta_ext_if_genif_oscommand import clsGenIFOSCommand\r\nfrom bta_util_common import obj_util_comm\r\n\r\n\r\nMODULE_NAME = \"bta_ext_if_genif_commandline\"\r\n\r\nTEMPFILE = \"temp.txt\"\r\nOUTPUTFILE_NAME = \"output_\"\r\nTYPE = \".log\"\r\n#OUTPUTFILE = \"\"\r\nTEMP_FILE_FOR_DIALUP = \"checkdialupconnection.txt\"\r\n\r\nCOMMAND_FILE_TRANSFER = \"DATA_TRANSFER\"\r\nCOMMAND_PING = \"SEND_PING\"\r\nCOMMAND_DIRECT = \"DIRECT_COMMAND\"\r\n\r\n# Parameters in commands dict\r\nFILE_SERVER_IP = 'file_server_ip'\r\nUSERNAME = 'username'\r\nPASSWORD = 'password'\r\nFILE_TO_BE_TRANSFERED = 'file_path'\r\nDIAL_UP_CONNECTION_NAME = 'connection_name'\r\nDIRECTION = 'direction'\r\nUPLINK = 'U'\r\nPING_SIZE = 'ping_size'\r\nPING_COUNT = 'ping_count'\r\nDEF_PING_SIZE = '256'\r\nDEF_PING_COUNT = '1'\r\nCOMMAND = 'command'\r\n\r\n\r\nDIALUP_COMMAND = ' rasdial '\r\nDELETE_COMMAND = ' del '\r\nTMP_USERNAME = ' temp '\r\nTMP_PASSWORD = ' temp '\r\nINVALID_COMMAND = 'ABCXYZ'\r\n\r\n\r\nTHROUGHPUT = 'app_thruput'\r\nSENT = 'sent'\r\nRECEIVE = 'receive'\r\nLOST = 'lost'\r\nMAXIMUM = 'maximum'\r\nMINIMUM = 'minimum'\r\nAVERAGE = 'average'\r\nRESPONSE = 'response'\r\n\r\n\r\nMESSAGE_TYPE = 'message_type'\r\nSERVER_IP = 'server_ip'\r\nLOG_TIME1 = 'MessageTimestamp'\r\nEXEC_ID = \"execution_id\"\r\nXML_CONTENT = \"xml_content\"\r\nBYTES_TAG = 'bytes_transfered'\r\nINTERFACE_TYPE_TAG = 'interface_type'\r\nTHROUGHPUT1 = 'throughput'\r\nTIME_SEC = 'time_sec'\r\nDOT = \".\"\r\nDIR_DATE_TIME_FORMAT = \"%Y-%m-%d %H:%M:%S\"\r\nFTP_FILE_NAME = \"cli_output.log\"\r\n\r\nZERO = 0\r\nclass clsGenIFCommandLine:\r\n '''\r\n Description : Provide the services of command line\r\n '''\r\n def __init__( self, logger, flt_hdlr ):\r\n '''\r\n * FUNCTION NAME:\r\n * __init__()\r\n *\r\n * DESCRIPTION:\r\n * Constructor Function of clsGenIFTime class. \r\n * \r\n *\r\n * INPUT:\r\n * logger - Logger class object, to log event in execution logs\r\n * err_handler - Object of err handler thread\r\n * \r\n * RETURNS:\r\n * Object of clsGenIFTime Class\r\n *\r\n * NOTES:\r\n * \r\n '''\r\n self.logger = logger\r\n self.err_handler = flt_hdlr\r\n self.output_file = None\r\n self.obj_semaphore = Semaphore()\r\n self.obj_os = clsGenIFOSCommand()\r\n \r\n def sendCommand( self, cmd_name, cmd_param_dict, db_hdlr=None, run_id=None, event_no=None, query_hdlr=None ):\r\n '''\r\n * FUNCTION NAME:\r\n * sendCommand()\r\n *\r\n * DESCRIPTION:\r\n * It will provide services of command prompt.\r\n *\r\n * INPUT:\r\n * \r\n * cmd_name - Command Name which needs to be executed\r\n * cmd_param_dict - Parameters of Command \r\n *\r\n * RETURNS:\r\n * Status of command execution\r\n *\r\n * NOTES:\r\n * \r\n '''\r\n try:\r\n self.obj_semaphore.acquire()\r\n response_list = []\r\n temp_dict = {}\r\n dict_response= {}\r\n result = CONSTANTS.FAIL\r\n self.logString( \"Sending Command \" + str(cmd_name) , CONSTANTS.DEBUG_LEVEL )\r\n if cmd_name and cmd_param_dict:\r\n start_time = obj_util_comm.getCurrentDateTime( CONSTANTS.DATE_TIME_FORMAT )\r\n start_time = obj_util_comm.getDateTime( start_time, CONSTANTS.DATE_TIME_FORMAT ) #returns date time instance\r\n start_time = start_time.strftime( DIR_DATE_TIME_FORMAT )\r\n #self.output_file = cmd_param_dict[CONSTANTS.PARAM_NAME_LOG_PATH] + OUTPUTFILE_NAME +\\\r\n #time.strftime(\"%Y_%m_%d %H_%M_%S\") + TYPE\r\n #output_file = OUTPUTFILE_NAME + start_time + TYPE\r\n #FTP_FILE_NAME= str(FTP_FILE_NAME + start_time + TYPE\r\n self.output_file = os.path.join(cmd_param_dict[CONSTANTS.PARAM_NAME_LOG_PATH], FTP_FILE_NAME)\r\n if COMMAND_FILE_TRANSFER == cmd_name:\r\n self.fileTransfer( cmd_param_dict )\r\n application_troughput,bytes_received = self.checkThroughput(self.output_file)\r\n throughput = re.findall(r'\\d+', application_troughput)\r\n if len(throughput) == ZERO: \r\n application_troughput =str(ZERO)\r\n else:\r\n application_troughput = throughput[0]\r\n if len(bytes_received) == ZERO:\r\n bytes_received =str(ZERO)\r\n else:\r\n bytes = re.findall(r'\\d+', bytes_received)\r\n bytes_received = bytes[0]\r\n if len(bytes) ==2 :\r\n time = bytes[1]\r\n elif len(bytes)> 2:\r\n time = bytes[1] + DOT + bytes[2]\r\n else:\r\n time = str(ZERO)\r\n temp_dict[THROUGHPUT1] = application_troughput\r\n temp_dict[BYTES_TAG] = bytes_received\r\n temp_dict[LOG_TIME1] = start_time\r\n #temp_dict[EXEC_ID] = run_id\r\n temp_dict[TIME_SEC] = time\r\n #temp_dict[INTERFACE_TYPE_TAG] = THROUGHPUT\r\n temp_dict[MESSAGE_TYPE]= cmd_name\r\n elif COMMAND_PING == cmd_name:\r\n response = self.initiatePing(cmd_param_dict, self.output_file )\r\n if (response == CONSTANTS.PASS) :\r\n sent,receive,lost,max,min,lost2 = self.checkPingDetails()\r\n temp_dict[SENT] = sent\r\n temp_dict[RECEIVE] = receive\r\n temp_dict[LOST] = lost\r\n temp_dict[MAXIMUM] = max\r\n temp_dict[MINIMUM] = min\r\n temp_dict[AVERAGE] = lost2\r\n temp_dict[MESSAGE_TYPE]= cmd_name\r\n temp_dict[SERVER_IP] = cmd_param_dict['file_server_ip']\r\n temp_dict[LOG_TIME1] = start_time\r\n temp_dict[EXEC_ID] = run_id\r\n temp_dict[INTERFACE_TYPE_TAG] = 'ping'\r\n #self.traverseResponseDict(temp_dict, cmd_param_dict, run_id, query_hdlr, db_hdlr )\r\n else:\r\n result = CONSTANTS.FAIL\r\n raise Exception(\"Invalid command name:may be error in connecting with the server\")\r\n elif COMMAND_DIRECT == cmd_name:\r\n self.sendCommandToPrompt( cmd_param_dict )\r\n temp_dict[RESPONSE] = \"Command Executed Successfully\"\r\n else:\r\n result = CONSTANTS.FAIL\r\n raise Exception(\"Invalid command name\")\r\n\r\n dict_response= {}\r\n dict_response[cmd_name] = temp_dict\r\n result = CONSTANTS.PASS\r\n except Exception as detail:\r\n result = CONSTANTS.FAIL\r\n temp_dict[RESPONSE] = str(detail)\r\n self.logString( MODULE_NAME + \".clsGenIFCommandLine.sendCommandToPrompt : Error occured in Send Command CLI\", CONSTANTS.ERROR_LEVEL )\r\n finally:\r\n response_list.append(dict_response)\r\n self.obj_semaphore.release()\r\n return result, response_list\r\n\r\n def sendCommandToPrompt( self, command_param_dict):\r\n try:\r\n if COMMAND not in command_param_dict:\r\n raise Exception(\"Invalid command parameters\")\r\n else:\r\n cmd = str(command_param_dict[COMMAND]) + ' >> \\\"' + self.output_file + '\\\"'\r\n if (self.obj_os.execute(cmd)):\r\n raise Exception(\"Invalid command or command execution failed\")\r\n except Exception as detail:\r\n raise Exception(detail)\r\n \r\n def pingServer( self, command_param_dict ):\r\n '''\r\n * FUNCTION NAME:\r\n * pingServer()\r\n * \r\n * DESCRIPTION:\r\n * Pings fileserver\r\n * \r\n * INPUT:\r\n * command_param_dict - parameter dictionary created by user using GUI \r\n * \r\n * RETURNS: \r\n * None\r\n '''\r\n try:\r\n if (CONSTANTS.FAIL == self.createDialUpConnection(command_param_dict)):\r\n raise Exception(\"Unable to create dialup connection\")\r\n if (CONSTANTS.FAIL == self.initiatePing(command_param_dict, self.output_file)):\r\n raise Exception(\"Ping Failed\")\r\n if (CONSTANTS.FAIL == self.disconnectDialUpConnection()):\r\n raise Exception(\"DialUp Connection disconnect Failed\")\r\n except Exception as details:\r\n self.disconnectDialUpConnection()\r\n raise Exception(details)\r\n \r\n def initiatePing( self, command_param_dict, output_file ):\r\n '''\r\n * FUNCTION NAME:\r\n * initiatePing()\r\n * \r\n * DESCRIPTION:\r\n * initiates PING\r\n * \r\n * INPUT:\r\n * command_param_dict - dictionary which holds command parameters\r\n * output_file - temporary output file created for temporary storing output of data transfer\r\n *\r\n * OUTPUT:\r\n * data transfer completed\r\n * \r\n * RETURNS: \r\n * None\r\n * \r\n '''\r\n response = None\r\n if PING_SIZE in command_param_dict:\r\n size = command_param_dict[PING_SIZE]\r\n else:\r\n size = DEF_PING_SIZE\r\n \r\n if PING_COUNT in command_param_dict:\r\n count = command_param_dict[PING_COUNT]\r\n else:\r\n count = DEF_PING_COUNT\r\n \r\n if FILE_SERVER_IP in command_param_dict:\r\n ip = command_param_dict[FILE_SERVER_IP]\r\n command ='ping -n ' + str(size) + ' -l ' + str(count) + ' ' + str(ip)\r\n cmd = command + ' >> \\\"' + self.output_file + '\\\"'\r\n else:\r\n command = INVALID_COMMAND\r\n cmd = command\r\n \r\n if (not self.obj_os.execute(cmd)):\r\n response = CONSTANTS.PASS\r\n else:\r\n response = CONSTANTS.FAIL\r\n\r\n return response \r\n \r\n \r\n def fileTransfer( self, command_param_dict ):\r\n '''\r\n * FUNCTION NAME:\r\n * fileTransfer()\r\n * \r\n * DESCRIPTION:\r\n * Uploads file to fileserver\r\n * Downloads file from server\r\n * \r\n * INPUT:\r\n * command_param_dict - parameter dictionary created by user using GUI \r\n * \r\n * RETURNS: \r\n * None\r\n '''\r\n\r\n try:\r\n if (CONSTANTS.FAIL == self.createTransferFile(TEMPFILE, command_param_dict )): # 0 replace with constant.Fail\r\n self.logString(\"File creation failed for file transfer\", CONSTANTS.ERROR_LEVEL)\r\n raise Exception(\"File creation failed for file transfer\")\r\n if (CONSTANTS.FAIL == self.createDialUpConnection(command_param_dict)):\r\n self.logString(\"Unable to create dialup connection\", CONSTANTS.ERROR_LEVEL)\r\n raise Exception(\"Unable to create dialup connection\")\r\n if (CONSTANTS.FAIL == self.initiateDataTransfer(TEMPFILE, self.output_file)):\r\n self.logString(\"Transfer Failed in initiating data transfer\", CONSTANTS.ERROR_LEVEL)\r\n raise Exception(\"Transfer Failed\") \r\n if (CONSTANTS.FAIL == self.readTransferStatus(self.output_file)):\r\n self.logString(\"Transfer Failed in reading data transfer status\", CONSTANTS.ERROR_LEVEL)\r\n raise Exception(\"Transfer Failed\") \r\n \r\n if (CONSTANTS.FAIL == self.disconnectDialUpConnection()):\r\n self.logString(\"DialUp Connection disconnect Failed\", CONSTANTS.ERROR_LEVEL)\r\n raise Exception(\"DialUp Connection disconnect Failed\")\r\n except Exception as details:\r\n self.disconnectDialUpConnection()\r\n raise Exception(details)\r\n\r\n def createTransferFile( self, temp_file_path, command_param_dict ):\r\n '''\r\n * FUNCTION NAME:\r\n * createTransferFile(self, temp_file_path, command_param_dict)\r\n * \r\n * DESCRIPTION:\r\n * creates temporary file, which is used for upload/download file\r\n * \r\n * INPUT:\r\n * command_param_dict - parameter dictionary created by user using GUI \r\n * temp_file_path - temporary File path for file transfer\r\n * \r\n * RETURNS: \r\n * Returns status whether file successfully created or not.\r\n * \r\n '''\r\n file_creation = None \r\n try:\r\n file_handler = open(temp_file_path, CONSTANTS.FILE_MODE_ASCII_WRITE)\r\n file_handler.write('open ' + str(command_param_dict[FILE_SERVER_IP]) + '\\n') \r\n file_handler.write(str(command_param_dict[USERNAME]).strip() + '\\n') \r\n file_handler.write(str(command_param_dict[PASSWORD]).strip() + '\\n') \r\n file_handler.write('ha\\n') \r\n file_handler.write(\"bi\\n\")\r\n file_handler.write(\"pr\\n\") \r\n if (UPLINK == str(command_param_dict[DIRECTION]).capitalize()):\r\n file_handler.write(\"put \" + str(command_param_dict[FILE_TO_BE_TRANSFERED]) + '\\n')\r\n else:\r\n file_handler.write(\"get \" + str(command_param_dict[FILE_TO_BE_TRANSFERED]) + '\\n')\r\n file_handler.write('bye\\n')\r\n file_creation = CONSTANTS.PASS # 1 replace with constant.PASS \r\n except Exception as details:\r\n file_creation = CONSTANTS.FAIL # 0 replace with constant.Fail\r\n finally:\r\n file_handler.close()\r\n return file_creation\r\n\r\n\r\n def createDialUpConnection( self, command_param_dict ):\r\n '''\r\n * FUNCTION NAME:\r\n * createDialUpConnection(self, command_param_dict)\r\n * \r\n * DESCRIPTION:\r\n * creates dialup connection for data transfer\r\n * \r\n * INPUT:\r\n * command_param_dict - parameter dictionary created by user using GUI \r\n * \r\n * RETURNS: \r\n * Returns status whether dialup connection created or not.\r\n * \r\n '''\r\n try:\r\n filename = TEMP_FILE_FOR_DIALUP\r\n dialup_complete = CONSTANTS.FAIL # 0 replace with constant.Fail\r\n\r\n dialup_file_handler = open(filename, CONSTANTS.FILE_MODE_ASCII_WRITE)\r\n dialup_file_handler.close()\r\n\r\n command = DIALUP_COMMAND + str(command_param_dict[DIAL_UP_CONNECTION_NAME]) +\\\r\n TMP_USERNAME + TMP_PASSWORD + '>> \\\"' + filename + '\\\"'\r\n del_command = DELETE_COMMAND + \"\\\"\" + filename + \"\\\"\"\r\n\r\n self.obj_os.execute(command) \r\n dialup_file_handler = open(filename, CONSTANTS.FILE_MODE_ASCII_READ)\r\n lines = dialup_file_handler.readlines()\r\n for line in lines:\r\n if (line.find('Successfully connected') > -1):\r\n self.logString(\"DialUp Connection Created\", CONSTANTS.DEBUG_LEVEL)\r\n dialup_complete = CONSTANTS.PASS # 1 replace with constant.PASS \r\n except Exception as details:\r\n dialup_complete = CONSTANTS.FAIL\r\n self.logString(\"DialUp Connection creation failed\", CONSTANTS.ERROR_LEVEL)\r\n finally:\r\n dialup_file_handler.close()\r\n self.obj_os.execute(del_command)\r\n return dialup_complete\r\n\r\n\r\n def disconnectDialUpConnection( self ):\r\n '''\r\n * FUNCTION NAME:\r\n * disconnectDialUpConnection(self, command_param_dict)\r\n * \r\n * DESCRIPTION:\r\n * disconnect dialup connection for data transfer\r\n * \r\n * INPUT:\r\n * None \r\n * \r\n * OUTPUT:\r\n * Disconnect DialUp Connection \r\n * \r\n * RETURNS: \r\n * None\r\n * GLOBAL DATA REFERENCED: \r\n * None\r\n * CALLED ROUTINES:\r\n * \r\n '''\r\n try:\r\n filename = TEMP_FILE_FOR_DIALUP\r\n disconnect_dialup_complete = CONSTANTS.FAIL \r\n\r\n disconnect_dialup_file_handler = open(filename,CONSTANTS.FILE_MODE_ASCII_WRITE)\r\n disconnect_dialup_file_handler.close()\r\n \r\n command = 'rasdial /d >> \\\"' + filename + '\\\"'\r\n del_command = \"del \\\"\" + filename + \"\\\"\"\r\n\r\n self.obj_os.execute(command) \r\n disconnect_dialup_file_handler = open(filename,CONSTANTS.FILE_MODE_ASCII_READ)\r\n lines = disconnect_dialup_file_handler.readlines()\r\n for line in lines:\r\n if (line.find('Command completed successfully.') > -1):\r\n self.logString(\"DialUp Connection disconnected sucessfully\", CONSTANTS.DEBUG_LEVEL)\r\n disconnect_dialup_complete = CONSTANTS.PASS \r\n except Exception as details:\r\n pass\r\n finally:\r\n disconnect_dialup_file_handler.close()\r\n self.obj_os.execute(del_command)\r\n return disconnect_dialup_complete \r\n\r\n def initiateDataTransfer( self, temp_file, output_file ):\r\n '''\r\n * FUNCTION NAME:\r\n * initiateDataTransfer(self, temp_file, output_file)\r\n * \r\n * DESCRIPTION:\r\n * initiates data transfer\r\n * \r\n * INPUT:\r\n * temp_file - temporary file created for providing input for data transfer\r\n * output_file - temporary output file created for temporary storing output of data transfer\r\n *\r\n * OUTPUT:\r\n * data transfer completed\r\n * \r\n * RETURNS: \r\n * None\r\n * \r\n '''\r\n response = None\r\n temp_file_handler = open( output_file, CONSTANTS.FILE_MODE_ASCII_APPEND_WRITE )\r\n temp_file_handler.close()\r\n command = \"ftp -s:\\\"\" + str(temp_file) + '\\\" >> \\\"' + str(output_file) + '\\\"'\r\n self.logString(\"Data transfer initiated\", CONSTANTS.DEBUG_LEVEL)\r\n if (not self.obj_os.execute(command)):\r\n response = CONSTANTS.PASS\r\n else:\r\n response = CONSTANTS.FAIL\r\n\r\n return response \r\n \r\n def readTransferStatus( self, output_file ):\r\n '''\r\n * FUNCTION NAME:\r\n * readTransferStatus(self, output_file)\r\n * \r\n * DESCRIPTION:\r\n * Checks whether data transfer is successful\r\n * \r\n * INPUT:\r\n * output_file - temporary output file created for temporary storing output of data transfer\r\n *\r\n * RETURNS: \r\n * returns status whether data transfer is successfully completed or not.\r\n *\r\n * \r\n '''\r\n try:\r\n transfer_complete = CONSTANTS.FAIL # 0 replace with constant.Fail \r\n output_file_handler = open(output_file, CONSTANTS.FILE_MODE_ASCII_READ)\r\n lines = output_file_handler.readlines()\r\n for line in lines:\r\n if (line.find('Transfer complete') > -1):\r\n self.logString(\"Transfer Completed sucessfully\", CONSTANTS.DEBUG_LEVEL)\r\n transfer_complete = CONSTANTS.PASS # 1 replace with constant.PASS \r\n except Exception as details:\r\n transfer_complete = CONSTANTS.FAIL\r\n self.logString(\"Transfer Unsucessful\", CONSTANTS.ERROR_LEVEL)\r\n finally:\r\n output_file_handler.close()\r\n return transfer_complete\r\n \r\n def checkThroughput( self, output_file ):\r\n '''\r\n * FUNCTION NAME:\r\n * checkThroughput(self, output_file)\r\n * \r\n * DESCRIPTION:\r\n * Checks Application Throughput of data transfer\r\n * \r\n * INPUT:\r\n * output_file - temporary output file created for temporarly storing output of data transfer\r\n *\r\n * OUTPUT: \r\n * None \r\n * \r\n * RETURNS: \r\n * returns application thruput of data transfer\r\n *\r\n * \r\n '''\r\n try:\r\n app_thruput = None\r\n output_file_handler = open(output_file, CONSTANTS.FILE_MODE_ASCII_READ)\r\n lines = output_file_handler.readlines()\r\n for line in lines:\r\n if (line.find('Kbytes/sec') > -1):\r\n a, b, app_thruput = line.rpartition(\" \")\r\n self.logString(\"Application Throughput : \" + str(app_thruput), CONSTANTS.DEBUG_LEVEL)\r\n except Exception as details:\r\n pass\r\n finally:\r\n output_file_handler.close()\r\n return app_thruput,a\r\n\r\n def checkPingDetails( self ):\r\n '''\r\n * FUNCTION NAME:\r\n * checkPingDetails(self, output_file)\r\n * \r\n * DESCRIPTION:\r\n * Checks ping details (Packet Sent, received, lost)/(Max, Min, Avg RTT) \r\n * \r\n * INPUT:\r\n * output_file - temporary output file created for temporarly storing output of data transfer\r\n *\r\n * OUTPUT: \r\n * None \r\n * \r\n * RETURNS: \r\n * returns application thruput of data transfer\r\n *\r\n * \r\n '''\r\n try:\r\n sent,receive,lost,max,min,lost2 = None,None,None,None,None,None\r\n output_file_handler = open(self.output_file, CONSTANTS.FILE_MODE_ASCII_READ)\r\n lines = output_file_handler.readlines()\r\n for line in lines:\r\n if (line.find('Packets:') > -1):\r\n list_line = line.split(\",\")\r\n list_sent = list_line[0].split(\" \")\r\n sent = list_sent[len(list_sent)-1]\r\n list_receive = list_line[1].split(\" \")\r\n receive = list_receive[len(list_receive)-1]\r\n list_lost = list_line[2].split(\" \")\r\n lost = list_lost[3]\r\n if (line.find('Minimum') > -1):\r\n list_line = line.split(\",\")\r\n list_max = list_line[0].split(\" \")\r\n max = list_max[len(list_max)-1]\r\n list_min = list_line[1].split(\" \")\r\n min = list_min[len(list_min)-1]\r\n list_avg = list_line[2].split(\" \")\r\n lost2 = list_avg[len(list_avg)-1]\r\n \r\n except Exception as details:\r\n pass\r\n finally:\r\n output_file_handler.close()\r\n return sent,receive,lost,max,min,lost \r\n\r\n def logString( self, log_string, log_level=CONSTANTS.DEBUG_LEVEL ): \r\n '''\r\n * FUNCTION NAME: \r\n * logString( self, log_string, log_level=CONSTANTS.DEBUG_LEVEL )\r\n *\r\n * DESCRIPTION: \r\n * The function does the following tasks\r\n * - Checks if logger instance is not None\r\n * - Calls logger's logString function to log into log file.\r\n *\r\n * INPUT:\r\n * log_string - The string to be written into log file\r\n * log_level - The level (DEBUG, INFO, WARN, ERROR)\r\n *\r\n * OUTPUT:\r\n * None\r\n *\r\n * RETURNS: \r\n * None\r\n * \r\n '''\r\n if self.logger:\r\n self.logger.logString( log_string, log_level )\r\n\r\n\r\n\r\n","sub_path":"kk_ADTRAN/Execution_Framework1_build25/Execution_Framework1_build25/bta_ext_if_genif_commandline.py","file_name":"bta_ext_if_genif_commandline.py","file_ext":"py","file_size_in_byte":25723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"612575420","text":"\"\"\"\nExceptions & Testing\nCreated Spring 2019\nLab 10\n@author: Ethan Walters (emw45)\n\"\"\"\n\nimport turtle\n\n\nclass Sun:\n\n def __init__(self, name, rad, m, temp, color):\n if rad < 0 or m < 0 or temp < -273.15:\n raise ValueError('Numeric properties must be greater than 0 and the temperature'\n 'must be greater than absolute zero.')\n self.name = name\n self.radius = rad\n self.mass = m\n self.temp = temp\n self.color = color\n self.x = 0\n self.y = 0\n self.pen = turtle.Turtle()\n self.pen.penup()\n self.pen.pencolor(self.color)\n self.pen.shape('circle')\n self.pen.shapesize(self.radius, self.radius)\n self.pen.goto(self.x, self.y)\n\n def getmass(self):\n return self.mass\n\n def __str__(self):\n return self.name\n\n\nif __name__ == '__main__':\n\n window = turtle.Screen()\n sun = Sun('Sun', 45, 78, 35, 'yellow')\n window.exitonclick()\n","sub_path":"lab10/sun.py","file_name":"sun.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"279388558","text":"from .baseparser import BaseParser, JSError, unify\n\n\nclass PythonicParser(BaseParser):\n \"\"\" Parser to transcompile Python to JS, allowing more Pythonic\n code, like ``self``, ``print()``, ``len()``, list methods, etc.\n \"\"\"\n \n NAME_MAP = {'self': 'this', }\n NAME_MAP.update(BaseParser.NAME_MAP)\n \n def function_isinstance(self, node):\n if len(node.args) != 2:\n raise JSError('isinstance expects two arguments.')\n \n ob = unify(self.parse(node.args[0]))\n cls = unify(self.parse(node.args[1]))\n if cls[0] in '\"\\'':\n cls = cls[1:-1] # remove quotes\n \n BASIC_TYPES = 'number', 'boolean', 'string', 'function', 'array', 'object', 'null', 'undefined'\n \n MAP = {'(int, float)': 'number', '(float, int)': 'number', 'float': 'number',\n 'str': 'string', 'basestring': 'string', 'string_types': 'string',\n 'bool': 'boolean',\n 'FunctionType': 'function', 'types.FunctionType': 'function',\n 'list': 'array', 'tuple': 'array', '(list, tuple)': 'array', '(tuple, list)': 'array',\n 'dict': 'object',\n }\n \n cmp = MAP.get(cls, cls)\n \n if cmp.lower() in BASIC_TYPES:\n # Basic type, use Object.prototype.toString \n # http://stackoverflow.com/questions/11108877\n return [\"({}).toString.call(\", \n ob, \n \").match(/\\s([a-zA-Z]+)/)[1].toLowerCase() === \", \n repr(cmp.lower())\n ]\n \n else:\n # User defined type, use instanceof\n # http://tobyho.com/2011/01/28/checking-types-in-javascript/\n cmp = unify(cls)\n if cmp[0] == '(':\n raise JSError('isinstance() can only compare to simple types')\n return ob, \" instanceof \", cmp\n \n def function_print(self, node):\n # Process keywords\n sep, end = '\" \"', ''\n for kw in node.keywords:\n if kw.arg == 'sep':\n sep = ''.join(self.parse(kw.value))\n elif kw.arg == 'end':\n end = ''.join(self.parse(kw.value))\n elif kw.arg in ('file', 'flush'):\n raise JSError('print() file and flush args not supported')\n else:\n raise JSError('Invalid argument for print(): %r' % kw.arg)\n \n # Combine args\n args = [unify(self.parse(arg)) for arg in node.args]\n end = (\" + %s\" % end) if (args and end and end != '\\n') else ''\n combiner = ' + %s + ' % sep\n args_concat = combiner.join(args)\n return 'console.log(' + args_concat + end + ')'\n \n def function_len(self, node):\n if len(node.args) == 1:\n return unify(self.parse(node.args[0])), '.length'\n else:\n return None # don't apply this feature\n \n def function_sum(self, node):\n if len(node.args) == 1:\n return (unify(self.parse(node.args[0])), \n '.reduce(function(a, b) {return a + b;})')\n else:\n raise JSError('sum() needs exactly one argument')\n \n def function_max(self, node):\n if len(node.args) == 0:\n raise JSError('max() needs at least one argument')\n elif len(node.args) == 1:\n arg = ''.join(self.parse(node.args[0]))\n return 'Math.max.apply(null, ', arg, ')'\n else:\n args = ', '.join([unify(self.parse(arg)) for arg in node.args])\n return 'Math.max(', args, ')'\n \n def function_min(self, node):\n if len(node.args) == 0:\n raise JSError('min() needs at least one argument')\n elif len(node.args) == 1:\n arg = ''.join(self.parse(node.args[0]))\n return 'Math.min.apply(null, ', arg, ')'\n else:\n args = ', '.join([unify(self.parse(arg)) for arg in node.args])\n return 'Math.min(', args, ')'\n \n \n def method_append(self, node, base):\n if len(node.args) == 1: \n code = []\n code.append('(%s.append || %s.push).apply(%s, [' % (base, base, base))\n code += self.parse(node.args[0])\n code.append('])')\n return code\n \n def method_remove(self, node, base):\n if len(node.args) == 1: \n code = []\n remove_func = 'function (x) {%s.splice(%s.indexOf(x), 1);}' % (base, base)\n code.append('(%s.remove || %s).apply(%s, [' % (base, remove_func, base))\n code += self.parse(node.args[0])\n code.append('])')\n return code\n","sub_path":"flexx/pyscript/pythonicparser.py","file_name":"pythonicparser.py","file_ext":"py","file_size_in_byte":4652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"504730911","text":"from ftw.upgrade import UpgradeStep\nfrom opengever.meeting.committee import ICommittee\nfrom plone.uuid.interfaces import IUUID\n\n\nclass SetDefaultTemplateAsAllowedTemplate(UpgradeStep):\n \"\"\"Set default template as allowed template.\n \"\"\"\n\n def __call__(self):\n self.install_upgrade_profile()\n\n query = {'object_provides': [ICommittee.__identifier__]}\n for obj in self.objects(\n query, 'Set default template as allowed template in committees'):\n container_ad_hoc_template = obj.get_ad_hoc_template()\n if container_ad_hoc_template is not None:\n obj.allowed_ad_hoc_agenda_item_templates = [IUUID(container_ad_hoc_template)]\n","sub_path":"opengever/core/upgrades/20180625151759_set_default_template_as_allowed_template/upgrade.py","file_name":"upgrade.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"411689744","text":"# -*- coding: UTF-8 -*-\n\nfrom __future__ import print_function\nimport os\nimport codecs\nimport numpy as np\nimport tensorflow as tf\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.preprocessing.text import Tokenizer\n\nclass AnswerProcessor:\n max_ans_len = 50\n max_words = 10000\n embedding_dim = 25\n \n def __init__(self, ans_texts=[], data_kind=\"train\"):\n self.ans_texts = ans_texts\n self.ans_output_texts = []\n self.ans_input_texts = []\n\n self.ans_data = []\n self.ans_input_data = []\n self.ans_output_data = []\n \n self.data_kind = data_kind\n # return true length of questions\n def readData(self):\n data_dir = '/home/xinze/project/dialogue_generate/data/'\n data_dir += self.data_kind + '/'\n ans_name = 'Computers&Internet_ans.txt'\n ans_len = []\n\n ans_f = open(os.path.join(data_dir, ans_name))\n for line in ans_f.readlines():\n self.ans_texts.append(line)\n ans_f.close()\n ans_input_f = open(os.path.join(data_dir, ans_name))\n for line in ans_input_f.readlines():\n # We use \"starttrats \" as the \"start sequence\" character\n # for the targets, and \" enddne\" as \"end sequence\" character\n input_line = \"starttrats \" + line\n output_line = line + \" enddne\"\n ans_len.append(len(input_line.split()))\n self.ans_input_texts.append(input_line)\n self.ans_output_texts.append(output_line)\n ans_input_f.close()\n return ans_len\n\n def tokenizeData(self):\n tokenizer = Tokenizer(num_words=AnswerProcessor.max_words)\n tokenizer.fit_on_texts(self.ans_texts)\n tokenizer.fit_on_texts(self.ans_input_texts)\n tokenizer.fit_on_texts(self.ans_output_texts)\n ques_sequences = tokenizer.texts_to_sequences(self.ans_texts)\n target_input_sequences = tokenizer.texts_to_sequences(self.ans_input_texts)\n target_output_sequences = tokenizer.texts_to_sequences(self.ans_output_texts)\n\n self.word_index = tokenizer.word_index\n print(\"In answer file, Found %s unique tokens.\" % len(self.word_index))\n log_dir = \"my_log_dir/\"\n fword_index = codecs.open(log_dir + \"ans_word_index.tsv\", \"w\")\n for key in self.word_index:\n fword_index.write(key + \"\\t\" + str(self.word_index[key]) + \"\\n\")\n fword_index.close()\n\n self.ans_data = pad_sequences(\n ques_sequences, \n padding='post', \n maxlen=AnswerProcessor.max_ans_len, \n )\n self.ans_input_data = pad_sequences(\n target_input_sequences, \n padding='post', \n maxlen=AnswerProcessor.max_ans_len, \n )\n self.ans_output_data = pad_sequences(\n target_output_sequences, \n padding='post', \n maxlen=AnswerProcessor.max_ans_len, \n )\n return self.ans_data, self.ans_input_data, self.ans_output_data\n \n # must after tokenizeData()\n def getWordIndex(self):\n return self.word_index","sub_path":"process_answers.py","file_name":"process_answers.py","file_ext":"py","file_size_in_byte":3099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"506173319","text":"import os\nimport sqlite3\n\nimport pytest\n\nfrom GooglePlayAdvancedSearch.DBUtils import AppAccessor\nfrom GooglePlayAdvancedSearch.Models import AppItem\n\n\ndef test_getCompleteAppInfoPartial():\n\tapp = AppItem()\n\tapp['name'] = 'test app'\n\tapp['id'] = 'testid'\n\tapp['rating'] = 1\n\tapp['install_fee'] = 0\n\tapp['app_icon'] = ''\n\n\tappAccessor = AppAccessor(10)\n\tappAccessor.insertOrUpdateApp(app, 0)\n\n\tassert appAccessor.getCompleteAppInfo('testid') is None, \"Database only has partial info.\"\n\n\ndef test_getCompleteAppInfoStale(dbFilePath):\n\tif os.path.exists(dbFilePath):\n\t\ttry:\n\t\t\tos.remove(dbFilePath)\n\t\texcept PermissionError as e:\n\t\t\tpytest.skip(str(e))\n\n\tconnection = sqlite3.connect(dbFilePath)\n\tcursor = connection.cursor()\n\ttry:\n\t\tapp = AppItem()\n\t\tapp['name'] = 'test app'\n\t\tapp['id'] = 'testid'\n\t\tapp['rating'] = 1\n\t\tapp['install_fee'] = 0\n\t\tapp['app_icon'] = ''\n\t\tapp['inAppPurchases'] = True\n\t\tapp['containsAds'] = False\n\t\tapp['num_reviews'] = 1000\n\t\tapp['install_fee'] = 0\n\t\tapp['permissions'] = []\n\t\tapp['categories'] = []\n\n\t\tappAccessor = AppAccessor(10)\n\t\tappAccessor.insertOrUpdateApp(app, 0)\n\n\t\tassert appAccessor.getCompleteAppInfo('testid')['rating'] == 1\n\n\t\tcursor.execute(\"update app set updateDate='2000-01-01' where id='testid'\")\n\t\tconnection.commit()\n\t\tassert appAccessor.getCompleteAppInfo('testid') is None, \"App data are stale, getCompleteAppInfo should return null.\"\n\tfinally:\n\t\tcursor.execute(\"delete from app where id='testid'\")\n\n\ndef test_searchAppsStale(dbFilePath):\n\tconnection = sqlite3.connect(dbFilePath)\n\tcursor = connection.cursor()\n\n\ttry:\n\t\tapp = AppItem()\n\t\tapp['name'] = 'test app'\n\t\tapp['id'] = 'testid'\n\t\tapp['rating'] = 1\n\t\tapp['install_fee'] = 0\n\t\tapp['app_icon'] = ''\n\n\t\tappAccessor = AppAccessor(10)\n\t\tappAccessor.insertOrUpdateApp(app, 0)\n\n\t\tcursor.execute(\"update app set updateDate='2000-01-01' where id='testid'\")\n\t\tconnection.commit()\n\t\tassert next((a for a in appAccessor.searchApps('test app') if a['id'] == 'testid'), None) is None, \"test app was updated on 2000-01-01, it should appear in search result.\"\n\tfinally:\n\t\tcursor.execute(\"delete from app where id='testid'\")\n","sub_path":"src/GooglePlayAdvancedSearch/tests/test_AppAccessor.py","file_name":"test_AppAccessor.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"24396044","text":"from __future__ import print_function, division\n\nimport abc\nfrom collections import namedtuple\n\nimport numpy as np\n\n\nclass Element:\n __metaclass__ = abc.ABCMeta\n gauss_points = None\n gauss_weights = None\n dofs = None\n strains_components = None\n \n def __init__(self, nodes):\n self.xe = np.zeros((len(nodes), 3))\n for i in range(3):\n self.xe[:, i] = [n.coordinates[i] for n in nodes]\n self.node_labels = [n.label for n in nodes]\n\n def J(self, xi, eta, zeta):\n return np.dot(self.d(xi, eta, zeta), self.xe)\n\n def volume(self):\n return np.sum([np.linalg.det(self.J(*gp)*w) for gp, w in zip(self.gauss_points, self.gauss_weights)])\n\n @abc.abstractmethod\n def d(self, xi, eta, zeta):\n pass\n\n @abc.abstractmethod\n def B(self, xi, eta, zeta):\n pass\n\n def gp_volume(self, i):\n gp = self.gauss_points[i, :]\n return np.linalg.det(self.J(*gp))*self.gauss_weights[i]\n\n\nclass C3D8(Element):\n dofs = 24\n strains_components = 6*8\n local_nodal_pos = np.array([[-1, -1, -1],\n [1, -1, -1],\n [1, 1, -1],\n [-1, 1, -1],\n [-1, -1, 1],\n [1, -1, 1],\n [1, 1, 1],\n [-1, 1, 1]])\n gauss_points = np.zeros((8, 3))\n counter = 0\n gauss_weights = np.ones(8)\n for i in [-1, 1]:\n for j in [-1, 1]:\n for k in [-1, 1]:\n gauss_points[counter, :] = k/np.sqrt(3), j/np.sqrt(3), i/np.sqrt(3)\n counter += 1\n\n def __init__(self, nodes):\n super(C3D8, self).__init__(nodes)\n\n def d(self, xi, eta, zeta):\n \"\"\"\n Returns the a matrix 3x8 matrix with derivatives of the shape functions with respect to x y and z\n :param xi: xi-coordinate\n :param eta: eta-coordinate\n :param zeta: zeta-coordinate\n :return: 3x8 matrix with derivatives\n \"\"\"\n\n d_matrix = np.zeros((3, 8))\n for i in range(8):\n d_matrix[0, i] = (1. + eta*self.local_nodal_pos[i, 1]) * \\\n (1. + zeta*self.local_nodal_pos[i, 2])*self.local_nodal_pos[i, 0]/8\n d_matrix[1, i] = (1. + xi*self.local_nodal_pos[i, 0]) * \\\n (1. + zeta*self.local_nodal_pos[i, 2])*self.local_nodal_pos[i, 1]/8\n d_matrix[2, i] = (1. + xi*self.local_nodal_pos[i, 0]) * \\\n (1. + eta*self.local_nodal_pos[i, 1])*self.local_nodal_pos[i, 2]/8\n return d_matrix\n\n def B(self, xi, eta, zeta):\n B = np.zeros((6, 24))\n jacobian = self.J(xi, eta, zeta)\n d = self.d(xi, eta, zeta)\n for i in range(8):\n dx_avg = [np.linalg.solve(self.J(*gp), self.d(*gp)[:, i])*np.linalg.det(self.J(*gp))\n for gp in self.gauss_points]\n dx_avg = sum(dx_avg)/self.volume()\n\n for j in range(3):\n for k in range(3):\n B[j, 3*i + k] += dx_avg[k]/3\n\n dx = np.linalg.solve(jacobian, d[:, i])\n for j in range(3):\n for k in range(3):\n if j == k:\n B[j, 3*i + k] += 2*dx[k]/3\n else:\n B[j, 3*i + k] += -dx[k]/3\n\n B[3, 3*i] += dx[1]\n B[3, 3*i + 1] += dx[0]\n\n B[4, 3*i] += dx[2]\n B[4, 3*i + 2] += dx[0]\n\n B[5, 3*i + 1] += dx[2]\n B[5, 3*i + 2] += dx[1]\n return B\n\n\nclass C3D20(Element):\n dofs = 60\n strains_components = 27*6\n local_nodal_pos = np.array([[-1, -1, -1], # 1\n [1, -1, -1], # 2\n [1, 1, -1], # 3\n [-1, 1, -1], # 4\n [-1, -1, 1], # 5\n [1, -1, 1], # 6\n [1, 1, 1], # 7\n [-1, 1, 1], # 8\n [0, -1, -1], # 9\n [1, 0, -1], # 10\n [0, 1, -1], # 11\n [-1, 0, -1], # 12\n [0, -1, 1], # 13\n [1, 0, 1], # 14\n [0, 1, 1], # 15\n [-1, 0, 1], # 16\n [-1, -1, 0], # 17\n [1, -1, 0], # 18\n [1, 1, 0], # 19\n [-1, 1, 0], # 20\n ])\n\n gauss_points = np.zeros((27, 3))\n counter = 0\n gauss_weights = 5/9*np.ones(27)\n gauss_weights[1::3] = 8/9\n for i in [-1, 0, 1]:\n for j in [-1, 0, 1]:\n for k in [-1, 0, 1]:\n gauss_points[counter, :] = k*np.sqrt(0.6), j*np.sqrt(0.6), i*np.sqrt(0.6)\n counter += 1\n\n def __init__(self, nodes):\n super(C3D20, self).__init__(nodes)\n\n def d(self, xi, eta, zeta):\n d_matrix = np.zeros((3, 20))\n for i in range(20):\n x = self.local_nodal_pos[i, 0]\n y = self.local_nodal_pos[i, 1]\n z = self.local_nodal_pos[i, 2]\n if i < 8:\n d_matrix[0, i] = ((1 + eta*y)*(1 + zeta*z)*(xi*x + eta*y + zeta*z - 2)*x +\n x*(1 + x*xi)*(1 + y*eta)*(1 + z*zeta))/8\n d_matrix[1, i] = ((1 + xi*x)*(1 + zeta*z)*(xi*x + eta*y + zeta*z - 2)*y +\n y*(1 + x*xi)*(1 + y*eta)*(1 + z*zeta))/8\n d_matrix[2, i] = ((1. + xi*x)*(1 + eta*y)*(xi*x + eta*y + zeta*z - 2)*z +\n z*(1 + x*xi)*(1 + y*eta)*(1 + z*zeta))/8\n\n elif i in [8, 10, 12, 14]:\n d_matrix[0, i] = -xi*(1 + y*eta)*(1 + z*zeta)/2\n d_matrix[1, i] = y*(1 - xi**2)*(1 + z*zeta)/4\n d_matrix[2, i] = z*(1 - xi**2)*(1 + y*eta)/4\n\n elif i in [9, 11, 13, 15]:\n d_matrix[0, i] = x*(1 - eta**2)*(1 + z*zeta)/4\n d_matrix[1, i] = -eta*(1 + x*xi)*(1 + z*zeta)/2\n d_matrix[2, i] = z*(1 - eta**2)*(1 + x*xi)/4\n\n elif i > 15:\n d_matrix[0, i] = x*(1 - zeta**2)*(1 + y*eta)/4\n d_matrix[1, i] = y*(1 - zeta**2)*(1 + x*xi)/4\n d_matrix[2, i] = -zeta*(1 + x*xi)*(1 + y*eta)/2\n return d_matrix\n\n def B(self, xi, eta, zeta):\n B = np.zeros((6, 60))\n jacobian = self.J(xi, eta, zeta)\n d = self.d(xi, eta, zeta)\n for i in range(20):\n dx = np.linalg.solve(jacobian, d[:, i])\n B[0, 3*i] = dx[0]\n B[1, 3*i + 1] = dx[1]\n B[2, 3*i + 2] = dx[2]\n\n B[3, 3*i] = dx[1]\n B[3, 3*i + 1] = dx[0]\n\n B[4, 3*i] = dx[2]\n B[4, 3*i + 2] = dx[0]\n\n B[5, 3*i + 1] = dx[2]\n B[5, 3*i + 2] = dx[1]\n return B\n\n\nif __name__ == '__main__':\n Node = namedtuple('Node', ['coordinates', 'label'])\n node_list = [Node(coordinates=[0, 0, 0], label=1),\n Node(coordinates=[2, 0, 0], label=2),\n Node(coordinates=[2, 2, 0], label=3),\n Node(coordinates=[0, 2, 0], label=4),\n Node(coordinates=[0, 0, 1], label=5),\n Node(coordinates=[2, 0, 1], label=6),\n Node(coordinates=[2, 2, 1], label=7),\n Node(coordinates=[0, 2, 1], label=8)]\n element = C3D8(node_list)\n element.B(0, 0, 0)\n print(np.linalg.solve(element.J(0, 0, 0), element.d(0, 0, 0)[:, 0])*8/element.volume())\n","sub_path":"python/FEM_functions/elements.py","file_name":"elements.py","file_ext":"py","file_size_in_byte":7833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"32982509","text":"from collections import UserDict\nfrom six import text_type\nfrom inspect import signature\nfrom urllib import parse\nfrom IPython import embed\n\nred = '\\x1b[91m{}\\x1b[0m'\n\ndef cullNone(**kwargs):\n return {k:v for k, v in kwargs.items() if v is not None}\n\nclass QueryResult:\n \"\"\" Encapsulate query results and allow for clear and clean documentation\n of how a particular service maps their result terminology onto the\n ontquery keyword api. \"\"\"\n def __init__(self,\n query_args,\n iri=None,\n curie=None,\n label=None,\n abbrev=None, # TODO\n acronym=None, # TODO\n definition=None,\n synonyms=None,\n prefix=None,\n category=None,\n predicates=None,\n upstream=None):\n self.__query_args = query_args # for debug\n self.__dict = {}\n if upstream is None:\n self.__upstream = OntTerm\n else:\n self.__upstream = upstream\n for k, v in dict(iri=iri,\n curie=curie,\n label=label,\n definition=definition,\n synonyms=synonyms,\n predicates=predicates).items():\n # this must return the empty values for all keys\n # so that users don't have to worry about hasattring\n # to make sure they aren't about to step into a typeless void\n setattr(self, k, v)\n self.__dict[k] = v\n #self.__dict__[k] = v\n\n def asTerm(self): # FIXME does not work as desired\n return self.__upstream(iri=self.iri) # TODO works best with a cache\n\n def keys(self):\n yield from self.__dict.keys()\n\n def values(self):\n yield from self.__dict.values()\n\n def items(self):\n yield from self.__dict.items()\n\n def __iter__(self):\n yield from self.__dict\n\n def __getitem__(self, key):\n try:\n return self.__dict[key]\n except KeyError as e:\n self.__missing__(key, e)\n\n def __contains__(self, key):\n return key in self.__dict\n\n def __missing__(self, key, e=None):\n raise KeyError(f'{key} {type(key)}') from e\n\n def __setitem__(self, key, value):\n raise ValueError('Cannot set results of a query.')\n\n def __repr__(self):\n return f'QueryResult({self.__dict!r})'\n\n\nclass OntCuries:\n \"\"\" A bad implementation of a singleton dictionary based namespace.\n Probably better to use metaclass= to init this so types can be tracked.\n \"\"\"\n # TODO how to set an OntCuries as the default...\n def __new__(cls, *args, **kwargs):\n if not hasattr(cls, '_' + cls.__name__ + '__dict'):\n cls.__dict = {}\n cls.__dict.update(dict(*args, **kwargs))\n return cls.__dict\n\n @classmethod\n def qname(cls, iri):\n # sort in reverse to match longest matching namespace first TODO/FIXME trie\n for prefix, namespace in sorted(cls.__dict.items(), key=lambda kv: len(kv[1]), reverse=True):\n if iri.startswith(namespace):\n suffix = iri[len(namespace):]\n return ':'.join((prefix, suffix))\n return iri\n\n\nclass OntId(text_type): # TODO all terms singletons to prevent nastyness\n _namespaces = OntCuries # overwrite when subclassing to switch curies...\n repr_arg_order = (('curie',),\n ('prefix', 'suffix'),\n ('iri',))\n __firsts = 'curie', 'iri'\n def __new__(cls, curie_or_iri=None, prefix=None, suffix=None, curie=None, iri=None, **kwargs):\n\n if not hasattr(cls, f'_{cls.__name__}__repr_level'):\n cls.__repr_level = 0\n if not hasattr(cls, 'repr_args'):\n cls.repr_args = cls.repr_arg_order[0]\n\n iri_ps, iri_ci, iri_c = None, None, None\n\n if prefix is not None and suffix is not None:\n #curie_ps = ':'.join(prefix, suffix)\n iri_ps = cls._make_iri(prefix, suffix)\n\n if curie_or_iri is not None:\n if (curie_or_iri.startswith('http://') or\n curie_or_iri.startswith('https://') or \n curie_or_iri.startswith('file://')):\n iri_ci = curie_or_iri\n curie_ci = cls._namespaces.qname(iri_ci)\n prefix, suffix = curie_ci.split(':')\n else:\n curie_ci = curie_or_iri\n try:\n prefix, suffix = curie_ci.split(':')\n except ValueError as e:\n raise ValueError(f'Could not split cuire {curie_ci!r} is it actually an identifier?') from e\n iri_ci = cls._make_iri(prefix, suffix)\n\n if curie is not None and curie != iri:\n prefix, suffix = curie.split(':')\n iri_c = cls._make_iri(prefix, suffix)\n\n if iri is not None:\n curie_i = cls._namespaces.qname(iri)\n prefix, suffix = curie_i.split(':')\n\n iris = iri_ps, iri_ci, iri_c, iri\n unique_iris = set(i for i in iris if i is not None)\n\n if len(unique_iris) > 1:\n ValueError(f'All ways of constructing iris not match! {sorted(unique_iris)}')\n else:\n iri = next(iter(unique_iris))\n\n self = super().__new__(cls, iri)\n self.prefix = prefix\n self.suffix = suffix\n return self\n\n @property\n def namespaces(self):\n return self._namespaces()\n\n @namespaces.setter\n def namespaces(self, value):\n self.__class__._namespaces = value\n # TODO recompute prefix and suffix for the new namespaces for all subclasses.\n # even though this is a property\n\n @property\n def curie(self):\n return ':'.join((self.prefix, self.suffix))\n\n @property\n def iri(self):\n return str(self) # without str we will get infinite recursion\n\n @classmethod\n def _make_iri(cls, prefix, suffix):\n namespaces = cls._namespaces()\n if prefix in namespaces:\n return namespaces[prefix] + suffix\n else:\n raise KeyError(f'Unknown curie prefix: {prefix}')\n\n @classmethod\n def repr_level(cls): # FIXME naming\n if not hasattr(cls, f'_{cls.__name__}__repr_level'):\n setattr(cls, f'_{cls.__name__}__repr_level', 0)\n #cls.__repr_level = 0 # how is this different....\n current = getattr(cls, f'_{cls.__name__}__repr_level')\n nargs = len(cls.repr_arg_order)\n next = (current + 1) % nargs\n cls.repr_args = self.repr_arg_order[next]\n print(self.__name__, 'will now repr with', cls.repr_args)\n setattr(cls, f'_{cls.__name__}__repr_level', next)\n\n @property\n def _repr_level(self):\n if not hasattr(self, f'_{self.__class__.__name__}__repr_level'):\n setattr(self, f'_{self.__class__.__name__}__repr_level', 0)\n current = getattr(self.__class__, f'_{cls.__class__.__name__}__repr_level')\n nargs = len(self.repr_arg_order)\n next = (current + 1) % nargs\n self.__class__.repr_args = self.repr_arg_order[next]\n print(self.__name__, 'will now repr with', self.repr_args)\n setattr(self.__class__, f'_{self.__class__.__name__}__repr_level', next)\n\n\n @property\n def _repr_include_args(self):\n first_done = False\n firsts = getattr(self.__class__, f'_{self.__class__.__name__}__firsts')\n for arg in self.__class__.repr_args: # always use class repr args\n if not hasattr(self, arg) or getattr(self, arg) is None: # allow repr of uninitialized classes\n continue\n is_arg = False\n if not first_done:\n if arg in firsts:\n first_done = True\n is_arg = True\n yield arg, is_arg\n\n if hasattr(self, 'unverified') and self.unverified:\n yield 'unverified', False\n\n @property\n def _repr_base(self):\n pref = self.__class__.__name__ + '('\n suf = ')'\n return pref + ', '.join(('{' + f'{kwarg}' + '}'\n if is_arg else\n f'{kwarg}={{' + f'{kwarg}' + '}')\n for kwarg, is_arg in self._repr_include_args) + suf\n\n @property\n def _repr_args(self):\n return {kwarg:repr(getattr(self, kwarg)) for kwarg, p in self._repr_include_args}\n\n def _no__str__(self): # don't use this -- we need sane serialization as the iri\n id_ = self.curie if hasattr(self, 'curie') else super().__repr__()\n return f\"{self.__class__.__name__}('{id_}')\"\n\n def __repr__(self):\n return self._repr_base.format(**self._repr_args)\n\n\nclass OntTerm(OntId):\n # TODO need a nice way to pass in the ontology query interface to the class at run time to enable dynamic repr if all information did not come back at the same time\n repr_arg_order = (('curie', 'label', 'synonyms', 'definition'),\n ('curie', 'label', 'synonyms'),\n ('curie', 'label'),\n ('label',),\n ('curie',),\n ('curie', 'label', 'definition', 'iri'),\n ('iri', 'label', 'definition', 'curie'),\n ('iri', 'label', 'definition'),)\n\n _cache = {}\n\n @staticmethod\n def query(*args, **kwargs):\n print(red.format('WARNING:'), 'no query provided to OntTerm')\n # FIXME deal with args\n return QueryResult(query_args=kwargs)\n\n __firsts = 'curie', 'iri'\n def __new__(cls, curie_or_iri=None, # cuire_or_iri first to allow creation without keyword\n label=None,\n term=None,\n search=None,\n unverified=None,\n query=None,\n **kwargs):\n kwargs['upstream'] = cls # FIXME not a good way to do this\n kwargs['curie_or_iri'] = curie_or_iri\n kwargs['label'] = label\n kwargs['term'] = term\n kwargs['search'] = search\n if not hasattr(cls, f'_{cls.__name__}__repr_level'):\n cls.__repr_level = 0\n if not hasattr(cls, 'repr_args'):\n cls.repr_args = cls.repr_arg_order[0]\n\n # FIXME not clear if we really want to do this because it can let\n # unverified terms creep in...\n fail = False\n if curie_or_iri is None and 'curie' not in kwargs and 'iri' not in kwargs and 'suffix' not in kwargs:\n fail = True\n nargs = cullNone(**kwargs)\n if query is not None:\n result = query(**nargs)\n else:\n result = cls.query(**nargs)\n\n kwargs.update(result)\n else:\n result = None\n\n self = super().__new__(cls, **kwargs)\n\n if self.iri in cls._cache: # FIXME __cache\n return cls._cache[self.iri]\n else:\n cls._cache[self.iri] = self\n\n self.kwargs = kwargs\n if query is not None:\n self.query = query\n\n if result is None:\n result = self.query(iri=self, upstream=cls)\n\n if result:\n for keyword, value in result.items():\n # TODO open vs closed world\n if unverified and keyword in kwargs and kwargs[keyword] != value:\n raise ValueError(f'Unverified value {keyword}=\\'{kwargs[keyword]}\\' '\n 'does not match ontology value {value} for {results[\"iri\"]}')\n #print(keyword, value)\n if keyword not in ('iri', 'curie'): # already managed by OntId\n setattr(self, keyword, value) # TODO value lists...\n self.unverified = False\n else:\n self.unverified = True\n for keyword in set(keyword\n for keywords in self.repr_arg_order\n for keyword in keywords\n if keyword not in cls.__firsts):\n if keyword in kwargs:\n value = kwargs[keyword]\n else:\n value = None\n setattr(self, keyword, value)\n\n print(red.format('WARNING:'), repr(self), '\\n')\n\n if fail:\n print(red.format(repr(self)))\n raise ValueError(f'Your term does not have a valid identifier.\\nPlease replace it with {self!r}')\n\n return self\n\n # use properties to query for various things to repr\n\n def __call__(self, *predicates, depth=1):\n qr = self.query(iri=self, predicates=predicates, depth=depth)\n return qr.predicates\n\n def __repr__(self): # TODO fun times here\n return super().__repr__()\n\n\nclass OntComplete(OntTerm):\n \"\"\" EXPERIMENTAL OntTerm that populates properties from OntQuery \"\"\"\n\n class _fakeQuery:\n def __call__(self, *args, **kwargs):\n raise NotImplementedError('Set OntComplete.query = OntQuery(...)')\n\n @property\n def predicates(self):\n raise NotImplementedError('Set OntComplete.query = OntQuery(...)')\n\n query = _fakeQuery()\n\n def __new__(cls, *args, **kwargs):\n for predicate in cls.query.predicates:\n p = OntId(predicate)\n name = p.suffix if p.suffix else p.prefix # partOf:\n\n def _prop(self, *predicates, depth=1):\n return cls.__call__(self, *predicates, depth=depth)\n\n prop = property(_prop)\n setattr(cls, name, prop)\n\n return super().__new__(*args, **kwargs)\n\n\nclass OntQuery:\n def __init__(self, *services, prefix=None, category=None, upstream=OntTerm): # services from OntServices\n # check to make sure that prefix valid for ontologies\n # more config\n self.services = services\n self.upstream = upstream\n\n @property\n def predicates(self):\n unique_predicates = set()\n for service in self.services:\n for predicate in service.predicates:\n unique_predicates.add(predicate)\n\n yield from sorted(unique_predicates)\n\n def __iter__(self): # make it easier to init filtered queries\n yield from self.services\n\n def __call__(self,\n term=None, # put this first so that the happy path query('brain') can be used, matches synonyms\n prefix=None, # limit search within this prefix\n category=None, # like prefix but works on predefined categories of things like 'anatomical entity' or 'species'\n label=None, # exact matches only\n abbrev=None, # alternately `abbr` as you have\n search=None, # hits a lucene index, not very high quality\n suffix=None, # suffix is 1234567 in PREFIX:1234567\n curie=None, # if you are querying you can probably just use OntTerm directly and it will error when it tries to look up\n iri=None, # the most important one\n predicates=tuple(), # provided with an iri or a curie to extract more specific triple information\n depth=1,\n limit=10,\n upstream=None, # FIXME this is NOT a happy way to do this\n ):\n qualifiers = cullNone(prefix=prefix,\n category=category)\n queries = cullNone(abbrev=abbrev,\n label=label,\n term=term,\n search=search)\n graph_queries = cullNone(predicates=(OntId(p) for p in predicates),\n depth=depth)\n identifiers = cullNone(suffix=suffix,\n curie=curie,\n iri=iri)\n control = dict(limit=limit)\n if queries and identifiers:\n print(f'\\x1b[91mWARNING: An identifier ({list(identifiers)}) was supplied. Ignoring other query parameters {list(queries)}.\\x1b[0m')\n queries = {}\n if 'suffix' in identifiers and 'prefix' not in qualifiers:\n raise ValueError('Queries using suffix= must also include an explicit prefix.')\n if len(queries) > 1:\n raise ValueError('Queries only accept a single non-qualifier argument. Qualifiers are prefix=, category=.')\n # TODO more conditions here...\n\n # TODO? this is one place we could normalize queries as well instead of having\n # to do it for every single OntService\n kwargs = {**qualifiers, **queries, **graph_queries, **identifiers, **control}\n out = []\n for service in self.services:\n if not service.started:\n service.setup()\n service.upstream = self.upstream\n # TODO query keyword precedence if there is more than one\n #print(red.format(str(kwargs)))\n for result in service.query(**kwargs):\n #print(red.format('AAAAAAAAAA'), result)\n out.append(result)\n\n # do not use these funcs to set the return values, only the error messages\n if upstream is not None:\n def func(result): return upstream(**result)\n elif self.upstream is not None:\n def func(result): return self.upstream(**result)\n else:\n func = lambda r: r\n\n if len(out) > 1:\n terms = '\\n\\n'.join(repr(func(result)) for result in out)\n message = f'Query {kwargs} returned more than one result. Please review.\\n\\n' + terms\n if upstream is not None:\n raise ValueError(message)\n else:\n print(message)\n elif len(out) == 1:\n return out[0]\n else:\n message = f'Query {kwargs} returned no results. Please change your query.'\n if upstream is not None:\n raise ValueError(message)\n else:\n print(message)\n\n\nclass OntService:\n \"\"\" Base class for ontology wrappers that define setup, dispatch, query,\n add ontology, and list ontologies methods for a given type of endpoint. \"\"\"\n\n def __init__(self):\n self._onts = []\n self.started = False\n\n def add(self, iri): # TODO implement with setter/appender?\n self._onts.append(iri)\n raise NotImplementedError()\n\n @property\n def onts(self):\n yield from self._onts\n\n @property\n def predicates(self):\n raise NotImplementedError()\n\n def setup(self):\n self.started = True\n return self\n\n def query(self, *args, **kwargs): # needs to conform to the OntQuery __call__ signature\n yield 'Queries should return an iterable'\n raise NotImplementedError()\n\n\n# helpers\nclass Graph():\n \"\"\" I can be pickled! And I can be loaded from a pickle dumped from a graph loaded via rdflib. \"\"\"\n def __init__(self, triples=tuple()):\n self.store = triples\n\n def add(triple):\n self.store += triple\n\n def subjects(self, predicate, object): # this method by iteself is sufficient to build a keyword based query interface via query(predicate='object')\n for s, p, o in self.store:\n if (predicate is None or predicate == p) and (object == None or object == o):\n yield s\n\n def predicates(self, subject, object):\n for s, p, o in self.store:\n if (subject is None or subject == s) and (object == None or object == o):\n yield p\n\n def predicate_objects(subject): # this is sufficient to let OntTerm work as desired\n for s, p, o in self.store:\n if subject == None or subject == s:\n yield p, o\n\n\n# services\nclass BasicService(OntService):\n \"\"\" A very simple services for local use only \"\"\"\n graph = Graph()\n predicate_mapping = {'label':'http://www.w3.org/2000/01/rdf-schema#label'} # more... from OntQuery.__call__ and can have more than one...\n\n @property\n def predicates(self):\n yield from sorted(set(self.graph.predicates(None, None)))\n\n def add(self, triples):\n for triple in triples:\n self.graph.add(triple)\n\n def setup(self): # inherit this as `class BasicLocalOntService(ontquery.BasicOntService): pass` and load the default graph during setup\n pass\n\n def query(self, iri=None, label=None, term=None, search=None): # right now we only support exact matches to labels\n if iri is not None:\n yield from self.graph.predicate_objects(iri)\n else:\n for keyword, object in kwargs.items():\n predicate = self.predicate_mapping(keyword)\n yield from self.graph.subjects(predicate, object)\n\n # Dispatching as describe previously is dispatch on type where the type is the set of query\n # features supported by a given OntService. The dispatch method can be dropped from OntQuery\n # and managed with python TypeErrors on kwarg mismatches to the service `query` method\n # like the one implemented here.\n\nfrom pyontutils import scigraph_client\nclass SciGraphRemote(OntService): # incomplete and not configureable yet\n cache = True\n verbose = False\n upstream = OntTerm\n known_inverses = ('partOf:', 'hasPart:'),\n def __init__(self, api_key=None, apiEndpoint='https://scicrunch.org/api/1/scigraph'):\n self.basePath = apiEndpoint\n self.api_key = api_key\n self.inverses = {OntId(k):OntId(v)\n for _k, _v in self.known_inverses\n for k, v in ((_k, _v), (_v, _k))}\n super().__init__()\n\n def add(self, iri): # TODO implement with setter/appender?\n raise TypeError('Cannot add ontology to remote service.')\n\n @property\n def predicates(self):\n yield from self._predicates\n\n def setup(self):\n # TODO make it possible to set these properties dynamically\n # one way is just to do scigraph = SciGraphRemote \\\\ OntQuery(scigraph)\n self.sgv = scigraph_client.Vocabulary(cache=self.cache, verbose=self.verbose, key=self.api_key)\n self.sgg = scigraph_client.Graph(cache=self.cache, verbose=self.verbose, key=self.api_key)\n self.sgc = scigraph_client.Cypher(cache=self.cache, verbose=self.verbose, key=self.api_key)\n self.curies = self.sgc.getCuries() # TODO can be used to provide curies...\n self.categories = self.sgv.getCategories()\n self._predicates = sorted(set(self.sgg.getRelationships()))\n self._onts = self.sgg.getEdges('owl:Ontology') # TODO incomplete and not sure if this works...\n super().setup()\n\n def _graphQuery(self, subject, predicate, depth=1, inverse=False):\n # TODO need predicate mapping... also subClassOf inverse?? hasSubClass??\n # TODO how to handle depth? this is not an obvious or friendly way to do this\n if predicate.prefix in ('owl', 'rdfs'):\n p = predicate.suffix\n else:\n p = predicate\n d_nodes_edges = self.sgg.getNeighbors(subject, relationshipType=p, depth=depth) # TODO\n if d_nodes_edges:\n edges = d_nodes_edges['edges']\n else:\n if inverse:\n predicate = self.inverses[predicate]\n print(f'{subject.curie} has no edges with predicate {predicate.curie} ')\n raise StopIteration\n s, o = 'sub', 'obj'\n if inverse:\n s, o = o, s\n if depth > 1:\n subjects = set(subject.curie)\n for e in edges:\n # FIXME need to actually get the transitive closure, this doesn't actually work\n #if e[s] in subjects:\n #subjects.add(object.curie)\n object = e[o]\n yield object\n continue # FIXME TODO this is _very_ inefficient for multiple lookups...\n u = self.upstream(object)\n print(repr(u))\n yield u\n else:\n #objects = (self.upstream(e[o]) for e in edges if e[s] == subject.curie) # TODO efficiency\n objects = (e[o] for e in edges if e[s] == subject.curie)\n yield from objects\n\n def query(self, iri=None, curie=None,\n label=None, term=None, search=None, abbrev=None, # FIXME abbrev -> any?\n prefix=None, category=None,\n predicates=tuple(), depth=1,\n limit=10):\n # use explicit keyword arguments to dispatch on type\n if prefix is not None and prefix not in self.curies:\n raise ValueError(f'{prefix} not in {self.__class__.__name__}.prefixes')\n if category is not None and category not in self.categories:\n raise ValueError(f'{category} not in {self.__class__.__name__}.categories')\n\n qualifiers = cullNone(prefix=prefix, category=category, limit=limit)\n identifiers = cullNone(iri=iri, curie=curie)\n predicates = tuple(OntId(p) for p in predicates)\n if identifiers:\n identifier = OntId(next(iter(identifiers.values()))) # WARNING: only takes the first if there is more than one...\n result = self.sgv.findById(identifier) # this does not accept qualifiers\n if result is None:\n yield result\n raise StopIteration\n\n if predicates: # TODO incoming/outgoing\n for predicate in predicates:\n values = tuple(sorted(self._graphQuery(identifier, predicate, depth=depth)))\n result[predicate] = values\n if predicate in self.inverses:\n p = self.inverses[predicate]\n values = tuple(sorted(self._graphQuery(identifier, p, depth=depth, inverse=True)))\n result[predicate] += values\n\n results = result,\n elif term:\n results = self.sgv.findByTerm(term, searchSynonyms=True, **qualifiers)\n elif label:\n results = self.sgv.findByTerm(label, searchSynonyms=False, **qualifiers)\n elif search:\n results = self.sgv.searchByTerm(search, **qualifiers)\n elif abbrev:\n results = self.sgv.findByTerm(abbrev, searchSynonyms=True,\n searchAbbreviations=True,\n searchAcronyms=True,\n **qualifiers)\n else:\n raise ValueError('No query prarmeters provided!')\n\n # TODO deprecated handling\n\n # TODO transform result to expected\n for result in results:\n if result['deprecated'] and not identifiers:\n continue\n ni = lambda i: next(iter(i)) if i else None\n predicate_results = {OntId(predicate).curie:result[predicate] for predicate in predicates}\n qr = QueryResult(query_args={**qualifiers, **identifiers, predicates:predicates},\n iri=result['iri'],\n curie=result['curie'] if 'curie' in result else result['iri'], # FIXME...\n label=ni(result['labels']),\n definition=ni(result['definitions']),\n synonyms=result['synonyms'],\n acronym=result['acronyms'],\n abbrev=result['abbreviations'],\n prefix=result['curie'].split(':')[0] if 'curie' in result else None,\n category=ni(result['categories']),\n predicates=predicate_results,\n upstream=self.upstream)\n yield qr\n\n\nclass InterLexRemote(OntService): # note to self\n pass\n\n\nclass rdflibLocal(OntService): # reccomended for local default implementation\n #graph = rdflib.Graph() # TODO pull this out into ../plugins? package as ontquery-plugins?\n # if loading if the default set of ontologies is too slow, it is possible to\n # dump loaded graphs to a pickle gzip and distribute that with a release...\n\n def add(self, iri, format):\n pass\n\n def setup(self):\n pass # graph added at class level\n\n def dispatch(self, prefix=None, category=None): # return True if the filters pass\n # TODO\n raise NotImplementedError()\n\n def query(self, *args, **kwargs): # needs to conform to the OntQuery __call__ signature\n # TODO\n pass\n\n\ndef main():\n import os\n from IPython import embed\n from pyontutils.core import get_api_key, PREFIXES as uPREFIXES\n curies = OntCuries(uPREFIXES)\n #print(curies)\n query = OntQuery(SciGraphRemote(api_key=get_api_key()))\n OntTerm.query = query\n\n # direct use of query instead of via OntTerm, users should never have to do this\n qr = query(label='brain', prefix='UBERON')\n t = qr.asTerm() # creation of a term using QueryResult.asTerm\n t1 = OntTerm(**qr) # creation of a term by passing a QueryResult instance to OntTerm as a dictionary\n\n # predicates query\n pqr = query(iri='UBERON:0000955', predicates=('hasPart:',))\n pt = pqr.asTerm()\n preds = OntTerm('UBERON:0000955')('hasPart:', 'partOf:', 'rdfs:subClassOf', 'owl:equivalentClass')\n preds1 = t('hasPart:', 'partOf:', 'rdfs:subClassOf', 'owl:equivalentClass')\n\n # query enabled OntTerm, throws a ValueError if there is no identifier\n try:\n t2 = OntTerm(term='brain', prefix='UBERON')\n except ValueError as e:\n print(red.format(e))\n try:\n t2 = OntTerm(label='brain', prefix='UBERON')\n except ValueError as e:\n print(red.format(e))\n t2 = OntTerm('UBERON:0000955', label='brain')\n\n print(repr(t))\n #*(print(repr(_)) for _ in (t, t1, t2)),\n\n def test(func):\n #expected fails\n #func(prefix='definition'),\n #func(suffix=''),\n asdf = (\n func('definition:'),\n func(prefix='definition', suffix=''),\n func(curie='definition:'),\n func('http://purl.obolibrary.org/obo/IAO_0000115'),\n func(iri='http://purl.obolibrary.org/obo/IAO_0000115'),\n )\n [print(repr(_)) for _ in asdf]\n return asdf\n\n test(OntId)\n asdf = test(OntTerm)\n\nif __name__ == '__main__':\n main()\n","sub_path":"ontquery/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":30335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"229082093","text":"import torch\r\nfrom torch import nn, optim\r\n\r\nimport nltk\r\n\r\nfrom torch.utils.data import DataLoader\r\nimport metaInfoLoader\r\nfrom main import prepare_sample\r\n\r\ndef main():\r\n \r\n print(\"start running\")\r\n daic_train, daic_test = prepare_sample()\r\n \r\n batchsz = 1\r\n \r\n daic_test = DataLoader(daic_test, batch_size=1, shuffle=True, drop_last=True)\r\n\r\n \r\n device = torch.device('cuda')\r\n model = torch.load(\"model/model.pt\").to(device)\r\n model = model.double()\r\n\r\n sm = nn.Sigmoid().to(device)\r\n\r\n print(model)\r\n\r\n model.eval() \r\n with torch.no_grad():\r\n # test\r\n total_correct = 0\r\n total_num = 0\r\n total_positive = 0\r\n total_true = 0\r\n total_true_positive = 0\r\n for x1, x2, x3, label in daic_test:\r\n x1, x2, x3, label = x1.to(device), x2.to(device), x3.to(device), label.to(device)\r\n label = torch.squeeze(label) \r\n inputs = (batchsz, x1, x2, x3) \r\n logits = model(inputs)\r\n logits = torch.squeeze(logits)\r\n \r\n pred = sm(logits)\r\n print(\"pred: \", pred, \" label: \", label)\r\n \r\n total_correct += torch.le(torch.abs(pred-label), 0.5).float().sum().item()\r\n total_num += x1.size(0)\r\n total_positive += torch.gt(pred, 0.5).float().sum().item()\r\n total_true += torch.gt(label, 0.5).float().sum().item()\r\n total_true_positive += (torch.gt(pred, 0.5) and torch.gt(label, 0.5)).float().sum().item()\r\n \r\n del inputs\r\n\r\n print(\"total_positive: \", total_positive, \"total_true: \", total_true, \"total_true_positive: \", total_true_positive)\r\n acc = total_correct / total_num\r\n if total_positive==0:\r\n precision=None\r\n F1_score=None\r\n recall = total_true_positive / total_true\r\n\r\n else:\r\n precision = total_true_positive / total_positive\r\n recall = total_true_positive / total_true\r\n F1_score = 2./(1./precision + 1./recall)\r\n print(\"test accuracy: \", acc, \"precision: \", precision, \"recall: \", recall, \"F1_score: \", F1_score)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n","sub_path":"basic_multimodal/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"163257891","text":"class StreamChecker:\n def __init__(self, words: List[str]):\n self.root = {}\n self.letters = ''\n\n for word in words:\n self.insert(word)\n\n def query(self, letter: str) -> bool:\n self.letters += letter\n node = self.root\n\n for c in self.letters[::-1]:\n if c not in node:\n return False\n node = node[c]\n if 'isWord' in node:\n return True\n\n return False\n\n def insert(self, word: str) -> None:\n node = self.root\n for c in word[::-1]:\n if c not in node:\n node[c] = {}\n node = node[c]\n node['isWord'] = True\n","sub_path":"solutions/1032. Stream of Characters/1032.py","file_name":"1032.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"513868246","text":"from tweepy.streaming import StreamListener \r\nfrom tweepy import OAuthHandler\r\nfrom tweepy import Stream\r\n\r\nimport credential\r\n\r\nclass listener(StreamListener):\r\n def on_data(self, data):\r\n print(data)\r\n return True\r\n def on_error(self, status):\r\n print(status)\r\n \r\nif __name__ == \"__main__\":\r\n listen = listener()\r\n auth = OAuthHandler(credential.CONSUMER_KEY, credential.CONSUMER_SECRET)\r\n auth.set_access_token(credential.ACCESS_TOKEN, credential.ACCESS_TOKEN_SECRET)\r\n \r\n stream = Stream(auth, listen)\r\n stream.filter(track = [\"\"]) # the keyword here\r\n","sub_path":"stream_tweets.py","file_name":"stream_tweets.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"24809875","text":"# Copyright 2019 Google LLC\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\"\"\"Runs a reinforcement learning loop to train a Go playing model.\"\"\"\n\nimport sys\nsys.path.insert(0, '.') # nopep8\n\nfrom collections import OrderedDict\nimport logging\nimport numpy as np\nimport os\nimport random\nimport re\nimport shutil\nimport subprocess\nimport tensorflow as tf\nimport utils\n\nfrom absl import app, flags\nfrom rl_loop import example_buffer, fsdb\n\nflags.DEFINE_integer('iterations', 100, 'Number of iterations of the RL loop.')\n\nflags.DEFINE_float('gating_win_rate', 0.55,\n 'Win-rate against the current best required to promote a '\n 'model to new best.')\n\nflags.DEFINE_string('flags_dir', None,\n 'Directory in which to find the flag files for each stage '\n 'of the RL loop. The directory must contain the following '\n 'files: bootstrap.flags, selfplay.flags, eval.flags, '\n 'train.flags.')\n\nflags.DEFINE_integer('max_window_size', 5,\n 'Maximum number of recent selfplay rounds to train on.')\n\nflags.DEFINE_integer('slow_window_size', 5,\n 'Window size after which the window starts growing by '\n '1 every slow_window_speed iterations of the RL loop.')\n\nflags.DEFINE_integer('slow_window_speed', 1,\n 'Speed at which the training window increases in size '\n 'once the window size passes slow_window_size.')\n\nFLAGS = flags.FLAGS\n\n\n# Models are named with the current reinforcement learning loop iteration number\n# and the model generation (how many models have passed gating). For example, a\n# model named \"000015-000007\" was trained on the 15th iteration of the loop and\n# is the 7th models that passed gating.\n# Note that we rely on the iteration number being the first part of the model\n# name so that the training chunks sort correctly.\nclass State:\n\n def __init__(self):\n self.iter_num = 0\n self.gen_num = 0\n\n # We start playing using a random model.\n # After the first round of selfplay has been completed, the engine is\n # updated to FLAGS.engine.\n self.engine = 'random'\n\n self.best_model_name = 'random'\n\n @property\n def output_model_name(self):\n return '%06d-%06d' % (self.iter_num, self.gen_num)\n\n @property\n def train_model_name(self):\n return '%06d-%06d' % (self.iter_num, self.gen_num + 1)\n\n @property\n def seed(self):\n return self.iter_num + 1\n\n\ndef checked_run(name, *cmd):\n # Read & expand any flagfiles specified on the commandline so we can know\n # exactly what's going on.\n expanded = flags.FlagValues().read_flags_from_files(cmd)\n logging.info('Running %s:\\n %s', name, ' '.join(expanded))\n\n with utils.logged_timer('%s finished' % name.capitalize()):\n completed_process = subprocess.run(\n cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n if completed_process.returncode:\n logging.error('Error running %s: %s', name,\n completed_process.stdout.decode())\n raise RuntimeError('Non-zero return code executing %s' % ' '.join(cmd))\n return completed_process\n\n\ndef get_lines(completed_process, slice):\n return '\\n'.join(completed_process.stdout.decode()[:-1].split('\\n')[slice])\n\n\nclass MakeSlice(object):\n\n def __getitem__(self, item):\n return item\n\n\nmake_slice = MakeSlice()\n\n\n# Return up to num_records of golden chunks to train on.\ndef get_golden_chunk_records(num_records):\n # Sort the list of chunks so that the most recent ones are first and return\n # the requested prefix.\n pattern = os.path.join(fsdb.golden_chunk_dir(), '*.zz')\n return sorted(tf.gfile.Glob(pattern), reverse=True)[:num_records]\n\n\n# Self-play a number of games.\ndef selfplay(state, flagfile='selfplay'):\n output_dir = os.path.join(fsdb.selfplay_dir(), state.output_model_name)\n holdout_dir = os.path.join(fsdb.holdout_dir(), state.output_model_name)\n model_path = os.path.join(fsdb.models_dir(), state.best_model_name)\n\n result = checked_run('selfplay',\n 'bazel-bin/cc/selfplay',\n '--flagfile={}.flags'.format(os.path.join(FLAGS.flags_dir, flagfile)),\n '--model={}.pb'.format(model_path),\n '--output_dir={}'.format(output_dir),\n '--holdout_dir={}'.format(holdout_dir),\n '--seed={}'.format(state.seed))\n logging.info(get_lines(result, make_slice[-2:]))\n\n # Write examples to a single record.\n pattern = os.path.join(output_dir, '*', '*.zz')\n random.seed(state.seed)\n tf.set_random_seed(state.seed)\n np.random.seed(state.seed)\n # TODO(tommadams): This method of generating one golden chunk per generation\n # is sub-optimal because each chunk gets reused multiple times for training,\n # introducing bias. Instead, a fresh dataset should be uniformly sampled out\n # of *all* games in the training window before the start of each training run.\n buffer = example_buffer.ExampleBuffer(sampling_frac=1.0)\n\n # TODO(tommadams): parallel_fill is currently non-deterministic. Make it not\n # so.\n logging.info('Writing golden chunk from \"{}\"'.format(pattern))\n buffer.parallel_fill(tf.gfile.Glob(pattern))\n buffer.flush(os.path.join(fsdb.golden_chunk_dir(),\n state.output_model_name + '.tfrecord.zz'))\n\n\n# Train a new model.\ndef train(state, tf_records):\n model_path = os.path.join(fsdb.models_dir(), state.train_model_name)\n checked_run('training',\n 'python3', 'train.py', *tf_records,\n '--flagfile={}'.format(os.path.join(FLAGS.flags_dir, 'train.flags')),\n '--work_dir={}'.format(fsdb.working_dir()),\n '--export_path={}'.format(model_path),\n '--training_seed={}'.format(state.seed),\n '--freeze=true')\n\n\n# Validate the trained model against holdout games.\ndef validate(state, holdout_glob):\n checked_run('validation',\n 'python3', 'validate.py', holdout_glob,\n '--flagfile={}'.format(os.path.join(FLAGS.flags_dir, 'validate.flags')),\n '--work_dir={}'.format(fsdb.working_dir()))\n\n\n# Evaluate the trained model against the current best model.\ndef evaluate(state):\n eval_model = state.train_model_name\n best_model = state.best_model_name\n eval_model_path = os.path.join(fsdb.models_dir(), eval_model)\n best_model_path = os.path.join(fsdb.models_dir(), best_model)\n sgf_dir = os.path.join(fsdb.eval_dir(), eval_model)\n result = checked_run('evaluation',\n 'bazel-bin/cc/eval',\n '--flagfile={}'.format(os.path.join(FLAGS.flags_dir, 'eval.flags')),\n '--model={}.pb'.format(eval_model_path),\n '--model_two={}.pb'.format(best_model_path),\n '--sgf_dir={}'.format(sgf_dir),\n '--seed={}'.format(state.seed))\n result = get_lines(result, make_slice[-7:])\n logging.info(result)\n pattern = '{}\\s+\\d+\\s+(\\d+\\.\\d+)%'.format(eval_model)\n win_rate = float(re.search(pattern, result).group(1)) * 0.01\n logging.info('Win rate %s vs %s: %.3f', eval_model, best_model, win_rate)\n return win_rate\n\n\ndef rl_loop():\n state = State()\n\n # Play the first round of selfplay games with a fake model that returns\n # random noise. We do this instead of playing multiple games using a single\n # model bootstrapped with random noise to avoid any initial bias.\n selfplay(state, 'bootstrap')\n\n # Train a real model from the random selfplay games.\n tf_records = get_golden_chunk_records(1)\n state.iter_num += 1\n train(state, tf_records)\n\n # Select the newly trained model as the best.\n state.best_model_name = state.train_model_name\n state.gen_num += 1\n\n # Run selfplay using the new model.\n selfplay(state)\n\n # Now start the full training loop.\n while state.iter_num <= FLAGS.iterations:\n # Build holdout glob before incrementing the iteration number because we\n # want to run validation on the previous generation.\n holdout_glob = os.path.join(fsdb.holdout_dir(), '%06d-*' % state.iter_num,\n '*')\n\n # Calculate the window size from which we'll select training chunks.\n window = 1 + state.iter_num\n if window >= FLAGS.slow_window_size:\n window = (FLAGS.slow_window_size +\n (window - FLAGS.slow_window_size) // FLAGS.slow_window_speed)\n window = min(window, FLAGS.max_window_size)\n\n # Train on shuffled game data from recent selfplay rounds.\n tf_records = get_golden_chunk_records(window)\n state.iter_num += 1\n train(state, tf_records)\n\n # These could all run in parallel.\n validate(state, holdout_glob)\n model_win_rate = evaluate(state)\n selfplay(state)\n\n # TODO(tommadams): if a model doesn't get promoted after N iterations,\n # consider deleting the most recent N training checkpoints because training\n # might have got stuck in a local minima.\n if model_win_rate >= FLAGS.gating_win_rate:\n # Promote the trained model to the best model and increment the generation\n # number.\n state.best_model_name = state.train_model_name\n state.gen_num += 1\n\n\ndef main(unused_argv):\n \"\"\"Run the reinforcement learning loop.\"\"\"\n\n print('Wiping dir %s' % FLAGS.base_dir, flush=True)\n shutil.rmtree(FLAGS.base_dir, ignore_errors=True)\n\n utils.ensure_dir_exists(fsdb.models_dir())\n utils.ensure_dir_exists(fsdb.selfplay_dir())\n utils.ensure_dir_exists(fsdb.holdout_dir())\n utils.ensure_dir_exists(fsdb.eval_dir())\n utils.ensure_dir_exists(fsdb.golden_chunk_dir())\n utils.ensure_dir_exists(fsdb.working_dir())\n\n # Copy the target model to the models directory so we can find it easily.\n shutil.copy('ml_perf/target.pb', fsdb.models_dir())\n\n logging.getLogger().addHandler(\n logging.FileHandler(os.path.join(FLAGS.base_dir, 'reinforcement.log')))\n formatter = logging.Formatter('[%(asctime)s] %(message)s',\n '%Y-%m-%d %H:%M:%S')\n for handler in logging.getLogger().handlers:\n handler.setFormatter(formatter)\n\n with utils.logged_timer('Total time'):\n rl_loop()\n\n\nif __name__ == '__main__':\n app.run(main)\n","sub_path":"ml_perf/reference_implementation.py","file_name":"reference_implementation.py","file_ext":"py","file_size_in_byte":10397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"596104019","text":"\"\"\"\n Decision Tree\n Author: Sola Gbenro\n\"\"\"\n# Importing the libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.tree import DecisionTreeRegressor\n\n# Importing the dataset\ndataset = pd.read_csv('Position_Salaries.csv')\n# Matrix of independent variable\n# Explicitily make X a matrix of 10 rows 1 column(s), otherwise default is 1d vector\nX = dataset.iloc[:, 1:2].values\n# DEPENDENT VARIABLE VECTOR (not a matrix, see above)\ny = dataset.iloc[:, 2].values\n\n# Fitting the Decision Tree Regression model to the dataset\nregressor = DecisionTreeRegressor(random_state = 0)\nregressor.fit(X, y)\n\n# Predicting a new result\n# takes a martrix\ny_pred = regressor.predict([[6.5]])\n\n# Visualizing the Decision Tree Regression results IN HIGH DEFINITION\n# create a 1d vector from min(X) to max(x) values are [1-10], increment by .1\nX_grid = np.arange(min(X), max(X), 0.01)\n# plt takes a MATRIX not a VECTOR, will require .reshape()\nX_grid = X_grid.reshape((len(X_grid), 1))\nplt.scatter(X, y, color='red')\n# predicted salaries 1-10\nplt.plot(X_grid, regressor.predict(X_grid), color='blue')\nplt.title('Truth or Bluff (Decision Tree Regression)')\nplt.xlabel('Position level')\nplt.ylabel('Salary')\nplt.show()\n","sub_path":"decision_tree.py","file_name":"decision_tree.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"471304565","text":"from pendulum_eqns.sim_eqns_ActIB_sinusoidal_activations import *\nfrom recovered_tension import *\nfrom recovered_muscle_length import *\nfrom recovered_activation import *\nfrom danpy.useful_functions import *\nfrom danpy.sb import dsb,get_terminal_width\nimport pickle\n\nX_o = np.array([r(0),dr(0)])\n# InitialTensions = return_initial_tension(\n# X_o,\n# ReturnMultipleInitialTensions=True,\n# Bounds=[[0,0.4*F_MAX1],[0,0.4*F_MAX2]],\n# InitialAngularAcceleration=0\n# ) # list of len::8\nInitialTensions = return_initial_tension(\n X_o,\n ReturnMultipleInitialTensions=True,\n Seed=1,\n Bounds = [[0,0.4*BIC.F_MAX],[0,0.4*TRI.F_MAX]],\n InitialAngularAcceleration=d2r(0),\n Return_k = False\n) # list of len::8\nInitialTensions = InitialTensions[3:6]\n# InitialTensions = [InitialTensions[3]]\nNumberOfTensionTrials = len(InitialTensions)\nInitialTensionsFromSuccessfulTrials = []\nTerminalWidth = get_terminal_width()\ncount = 0\nfor i in range(NumberOfTensionTrials):\n try:\n TensionTrialTitle = (\n \" Tension Setting \"\n + str(i+1)\n + \"/\" +str(NumberOfTensionTrials)\n + \" \\n\")\n print(\n \t\" \"*int(TerminalWidth/2 - len(TensionTrialTitle)/2)\n \t+ colored(TensionTrialTitle,'blue',attrs=[\"underline\",\"bold\"])\n \t)\n\n TotalX_temp,TotalU_temp = run_N_sim_IB_sinus_act(\n NumberOfTrials=1,\n FixedInitialTension=InitialTensions[i],\n Amp=\"Scaled\",\n Freq=1,\n InitialAngularAcceleration=0,\n InitialAngularSnap=0\n )\n plt.close('all')\n count+=1\n\n if count == 1:\n TotalX = TotalX_temp\n TotalU = TotalU_temp\n InitialTensionsFromSuccessfulTrials.append(TotalX_temp[0,2:4,0])\n else:\n TotalX = np.concatenate([TotalX,TotalX_temp],axis=0)\n TotalU = np.concatenate([TotalU,TotalU_temp],axis=0)\n InitialTensionsFromSuccessfulTrials.append(TotalX_temp[0,2:4,0])\n except:\n print(\"Trial \" + str(i+1) + \" Failed...\")\n\nprint(\"Number of Total Trials: \" + str(NumberOfTensionTrials) + \"\\n\")\nprint(\n \"Number of Successful Trials: \"\n + str(len(InitialTensionsFromSuccessfulTrials))\n )\n\nif len(InitialTensions) != 0:\n figs = plot_N_sim_IB_sinus_act(\n Time,TotalX,TotalU,\n Return=True\n )\n recoverd_tension_figs = plot_recovered_vs_simulated_tension(\n Time,TotalX\n )\n recoverd_muscle_length_figs = \\\n plot_recovered_vs_simulated_muscle_length(\n Time,TotalX\n )\n recoverd_muscle_activation_figs = \\\n plot_recovered_vs_simulated_activation(\n Time,TotalX,TotalU\n )\n # plt.show()\n\n params[\"Muscle 1\"] = BIC.__dict__\n params[\"Muscle 1\"][\"Settings\"] = BIC_Settings\n params[\"Muscle 2\"] = TRI.__dict__\n params[\"Muscle 2\"][\"Settings\"] = TRI_Settings\n\n FilePath = save_figures(\n \"output_figures/integrator_backstepping_sinusoidal_activations_fixed_lm/\",\n \"fixed_lm\",\n {**{\"X_o\": X_o, \"Initial Tensions\" : InitialTensions},**params},\n saveAsPDF=True,\n saveAsMD=True,\n addNotes=\"Fixed Muscle Length Integrator Backstepping Experiment\",\n returnPath=True\n )\n plt.close('all')\n FormatedSaveData = {\n \"States\" : TotalX,\n \"Input\" : TotalU,\n \"Initial Tensions\" : InitialTensionsFromSuccessfulTrials\n }\n pickle.dump(\n FormatedSaveData,\n open(\n FilePath/\"output.pkl\",\n \"wb\"\n )\n )\nelse:\n print(\"All Trials Unsuccessful...\")\n","sub_path":"IB_1DOF_2DOA_simulation/IB_1DOF_2DOA_Sinusoidal_Activations_Fixed_Muscle_Length.py","file_name":"IB_1DOF_2DOA_Sinusoidal_Activations_Fixed_Muscle_Length.py","file_ext":"py","file_size_in_byte":3662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"238110741","text":"from django.conf import settings\r\nfrom rest_framework.test import APIClient\r\n\r\nfrom gatekeeper.models import GateKeeper\r\nfrom newsfeeds.models import NewsFeed, HBaseNewsFeed\r\nfrom newsfeeds.services import NewsFeedService\r\nfrom testing.testcases import TestCase\r\nfrom utils.paginations import EndlessPagination\r\n\r\nNEWSFEEDS_URL = '/api/newsfeeds/'\r\nPOST_TWEETS_URL = '/api/tweets/'\r\nFOLLOW_URL = '/api/friendships/{}/follow/'\r\n\r\n\r\nclass NewsFeedApiTests(TestCase):\r\n\r\n def setUp(self):\r\n self.clear_cache()\r\n super(NewsFeedApiTests, self).setUp()\r\n self.user1 = self.create_user('user1')\r\n self.user1_client = APIClient()\r\n self.user1_client.force_authenticate(self.user1)\r\n\r\n self.user2 = self.create_user('user2')\r\n self.user2_client = APIClient()\r\n self.user2_client.force_authenticate(self.user2)\r\n\r\n # create followings and followers for user2\r\n for i in range(2):\r\n follower = self.create_user('user2_follower{}'.format(i))\r\n self.create_friendship(from_user=follower, to_user=self.user2)\r\n\r\n for i in range(3):\r\n following = self.create_user('user2_following{}'.format(i))\r\n self.create_friendship(from_user=self.user2, to_user=following)\r\n\r\n def test_user_cache(self):\r\n profile = self.user2.profile\r\n profile.nickname = 'huanglaoxie'\r\n profile.save()\r\n\r\n self.assertEqual(self.user1.username, 'user1')\r\n self.create_newsfeed(self.user2, self.create_tweet(self.user1))\r\n self.create_newsfeed(self.user2, self.create_tweet(self.user2))\r\n\r\n response = self.user2_client.get(NEWSFEEDS_URL)\r\n results = response.data['results']\r\n self.assertEqual(results[0]['tweet']['user']['username'], 'user2')\r\n self.assertEqual(results[0]['tweet']['user']['nickname'], 'huanglaoxie')\r\n self.assertEqual(results[1]['tweet']['user']['username'], 'user1')\r\n\r\n self.user1.username = 'linghuchong'\r\n self.user1.save()\r\n profile.nickname = 'huangyaoshi'\r\n profile.save()\r\n\r\n response = self.user2_client.get(NEWSFEEDS_URL)\r\n results = response.data['results']\r\n self.assertEqual(results[0]['tweet']['user']['username'], 'user2')\r\n self.assertEqual(results[0]['tweet']['user']['nickname'], 'huangyaoshi')\r\n self.assertEqual(results[1]['tweet']['user']['username'], 'linghuchong')\r\n\r\n def test_tweet_cache(self):\r\n tweet = self.create_tweet(self.user1, 'content1')\r\n self.create_newsfeed(self.user2, tweet)\r\n response = self.user2_client.get(NEWSFEEDS_URL)\r\n results = response.data['results']\r\n self.assertEqual(results[0]['tweet']['user']['username'], 'user1')\r\n self.assertEqual(results[0]['tweet']['content'], 'content1')\r\n\r\n # update username\r\n self.user1.username = 'user1'\r\n self.user1.save()\r\n response = self.user2_client.get(NEWSFEEDS_URL)\r\n results = response.data['results']\r\n self.assertEqual(results[0]['tweet']['user']['username'], 'user1')\r\n\r\n # update content\r\n tweet.content = 'content2'\r\n tweet.save()\r\n response = self.user2_client.get(NEWSFEEDS_URL)\r\n results = response.data['results']\r\n self.assertEqual(results[0]['tweet']['content'], 'content2')\r\n\r\n def test_list(self):\r\n # 需要登录\r\n response = self.anonymous_client.get(NEWSFEEDS_URL)\r\n self.assertEqual(response.status_code, 403)\r\n\r\n # 不能用 post\r\n response = self.user1_client.post(NEWSFEEDS_URL)\r\n self.assertEqual(response.status_code, 405)\r\n\r\n # 一开始啥都没有\r\n response = self.user1_client.get(NEWSFEEDS_URL)\r\n self.assertEqual(response.status_code, 200)\r\n self.assertEqual(len(response.data['results']), 0)\r\n\r\n # 自己发的信息是可以看到的\r\n self.user1_client.post(POST_TWEETS_URL, {'content': 'Hello World'})\r\n response = self.user1_client.get(NEWSFEEDS_URL)\r\n self.assertEqual(len(response.data['results']), 1)\r\n\r\n # 关注之后\r\n self.user1_client.post(FOLLOW_URL.format(self.user2.id))\r\n response = self.user2_client.post(POST_TWEETS_URL, {\r\n 'content': 'Hello Twitter',\r\n })\r\n posted_tweet_id = response.data['id']\r\n response = self.user1_client.get(NEWSFEEDS_URL)\r\n self.assertEqual(len(response.data['results']), 2)\r\n self.assertEqual(response.data['results'][0]['tweet']['id'], posted_tweet_id)\r\n\r\n def test_pagination(self):\r\n page_size = EndlessPagination.page_size\r\n followed_user = self.create_user('followed')\r\n newsfeeds = []\r\n for i in range(page_size * 2):\r\n tweet = self.create_tweet(followed_user)\r\n newsfeed = self.create_newsfeed(user=self.user1, tweet=tweet)\r\n newsfeeds.append(newsfeed)\r\n\r\n newsfeeds = newsfeeds[::-1]\r\n\r\n # pull the first page\r\n response = self.user1_client.get(NEWSFEEDS_URL)\r\n self.assertEqual(response.data['has_next_page'], True)\r\n results = response.data['results']\r\n self.assertEqual(len(results), page_size)\r\n self.assertEqual(results[0]['created_at'], newsfeeds[0].created_at)\r\n self.assertEqual(results[1]['created_at'], newsfeeds[1].created_at)\r\n self.assertEqual(results[page_size - 1]['created_at'], newsfeeds[page_size - 1].created_at)\r\n\r\n # pull the second page\r\n response = self.user1_client.get(\r\n NEWSFEEDS_URL,\r\n {'created_at__lt': newsfeeds[page_size - 1].created_at},\r\n )\r\n self.assertEqual(response.data['has_next_page'], False)\r\n results = response.data['results']\r\n self.assertEqual(len(results), page_size)\r\n self.assertEqual(results[0]['created_at'], newsfeeds[page_size].created_at)\r\n self.assertEqual(results[1]['created_at'], newsfeeds[page_size + 1].created_at)\r\n self.assertEqual(\r\n results[page_size - 1]['created_at'],\r\n newsfeeds[2 * page_size - 1].created_at,\r\n )\r\n\r\n # pull latest newsfeeds\r\n response = self.user1_client.get(\r\n NEWSFEEDS_URL,\r\n {'created_at__gt': newsfeeds[0].created_at},\r\n )\r\n self.assertEqual(response.data['has_next_page'], False)\r\n self.assertEqual(len(response.data['results']), 0)\r\n\r\n tweet = self.create_tweet(followed_user)\r\n new_newsfeed = self.create_newsfeed(user=self.user1, tweet=tweet)\r\n\r\n response = self.user1_client.get(\r\n NEWSFEEDS_URL,\r\n {'created_at__gt': newsfeeds[0].created_at},\r\n )\r\n self.assertEqual(response.data['has_next_page'], False)\r\n self.assertEqual(len(response.data['results']), 1)\r\n self.assertEqual(response.data['results'][0]['created_at'], new_newsfeed.created_at)\r\n\r\n def _paginate_to_get_newsfeeds(self, client):\r\n # paginate until the end\r\n response = client.get(NEWSFEEDS_URL)\r\n results = response.data['results']\r\n while response.data['has_next_page']:\r\n created_at__lt = response.data['results'][-1]['created_at']\r\n response = client.get(NEWSFEEDS_URL, {'created_at__lt': created_at__lt})\r\n results.extend(response.data['results'])\r\n return results\r\n\r\n def test_redis_list_limit(self):\r\n list_limit = settings.REDIS_LIST_LENGTH_LIMIT\r\n page_size = 20\r\n users = [self.create_user('user{}'.format(i)) for i in range(3, 8)]\r\n newsfeeds = []\r\n for i in range(list_limit + page_size):\r\n tweet = self.create_tweet(user=users[i % 5], content='feed{}'.format(i))\r\n feed = self.create_newsfeed(self.user1, tweet)\r\n newsfeeds.append(feed)\r\n newsfeeds = newsfeeds[::-1]\r\n\r\n # only cached list_limit objects\r\n cached_newsfeeds = NewsFeedService.get_cached_newsfeeds(self.user1.id)\r\n self.assertEqual(len(cached_newsfeeds), list_limit)\r\n\r\n if GateKeeper.is_switch_on('switch_newsfeed_to_hbase'):\r\n count = len(HBaseNewsFeed.filter(prefix=(self.user1.id, None)))\r\n else:\r\n count = NewsFeed.objects.filter(user=self.user1).count()\r\n self.assertEqual(count, list_limit + page_size)\r\n\r\n results = self._paginate_to_get_newsfeeds(self.user1_client)\r\n self.assertEqual(len(results), list_limit + page_size)\r\n for i in range(list_limit + page_size):\r\n self.assertEqual(newsfeeds[i].created_at, results[i]['created_at'])\r\n\r\n # a followed user create a new tweet\r\n self.create_friendship(self.user1, self.user2)\r\n new_tweet = self.create_tweet(self.user2, 'a new tweet')\r\n NewsFeedService.fanout_to_followers(new_tweet)\r\n\r\n def _test_newsfeeds_after_new_feed_pushed():\r\n results = self._paginate_to_get_newsfeeds(self.user1_client)\r\n self.assertEqual(len(results), list_limit + page_size + 1)\r\n self.assertEqual(results[0]['tweet']['id'], new_tweet.id)\r\n for i in range(list_limit + page_size):\r\n self.assertEqual(newsfeeds[i].created_at, results[i + 1]['created_at'])\r\n\r\n _test_newsfeeds_after_new_feed_pushed()\r\n\r\n # cache expired\r\n self.clear_cache()\r\n _test_newsfeeds_after_new_feed_pushed()\r\n","sub_path":"newsfeeds/api/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":9410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"27601637","text":"'''\nThis is learning parser. It's get weather.\n'''\n\ndef get_weather_perm():\n\n import requests\n import bs4\n\n site = requests.get(\"https://sinoptik.com.ru/погода-пермь\") #get raw site text\n\n b = bs4.BeautifulSoup(site.text, \"html.parser\") #Make tags tree\n '''\n What is tegs tree. Example.\n \n import bs4 \n text = \"<HTML><HEAD></HEAD><BODY></BODY></HTML>\" - html code in line(without sctucture.\n magic_tails = bs4.BeautifulSoup(text)\n magic_tails.prettyfy()\n #<HTML>\n # <HEAD>\n # </HEAD>\n # <BODY>\n # </BODY>\n #<HTML>\n It is true magic!\n '''\n \n #Morning temperature\n p3 = b.select('.temperature .p3') #BeautifulSoup object. It is select tags temperature and p3\n morinig_weather1 = p3[0].getText()\n p4 = b.select('.temperature .p4')\n morinig_weather2 = p4[0].getText()\n\n #Day temperature\n p5 = b.select('.temperature .p5')\n day_weather1 = p5[0].getText()\n p6 = b.select('.temperature .p6')\n day_weather2 = p6[0].getText()\n\n #Weather description\n tmp_dsc = b.select('.rSide .description')\n descript = (tmp_dsc[0].getText()).strip()\n\n #Return answer\n returned_answer = \"Погода в Перми:\\nУтром:{0} {1};\\nДнем: {2} {3};\\n{4}\".format(morinig_weather1, morinig_weather2, day_weather1, day_weather2, descript)\n print (returned_answer)\n\ndef main():\n get_weather_perm()\n\nif __name__ == '__main__':\n main()","sub_path":"parsers/weather_parser.py","file_name":"weather_parser.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"87210604","text":"import peewee\n\ndatabase = peewee.SqliteDatabase('blog.db', check_same_thread=False)\n\ndef create_tables():\n User.create_table()\n Post.create_table()\n Commemt.create_table()\n return None\n\nclass BaseModel(peewee.Model):\n class Meta:\n database = database\n\n\nclass User(BaseModel):\n\n username = peewee.CharField(max_length=25,null=False)\n email = peewee.CharField(max_length=50,null=False)\n password = peewee.CharField(max_length=25,null=False)\n join_date = peewee.DateField()\n\n def __unicode__(self):\n return \"%s : %s\" %(self.username,self.email)\n\nclass Post(BaseModel):\n \n user = peewee.ForeignKeyField(User,null=False)\n title = peewee.CharField(max_length=25,null=False)\n content = peewee.TextField()\n pub_date = peewee.DateTimeField()\n\n def __unicode__(self):\n return \"%s posted by %s\" %(self.title,self.user.username)\n \n class Meta:\n order_by = ('-pub_date',)\n \n\nclass Comment(BaseModel):\n user = peewee.ForeignKeyField(User,null=False)\n post = peewee.ForeignKeyField(Post,null=False)\n content = peewee.TextField()\n pub_date = peewee.DateTimeField()\n\n def __unicode__(self):\n return \"%s posted a comment on post %s on %s\" %(self.user,self.post,self.pub_date)\n\n class Meta:\n order_by = ('-pub_date',)\n ","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"361854017","text":"from os import makedirs\nfrom pathlib import Path\nfrom subprocess import check_call\nfrom tempfile import TemporaryDirectory\nfrom typing import Generator\n\nimport pytest\nimport requests\nimport yaml\n\nfrom tests.integration_tests import ADMIN_TOKEN\n\n\n@pytest.yield_fixture(scope=\"session\")\ndef local_grand_challenge() -> Generator[str, None, None]:\n local_api_url = \"https://gc.localhost/api/v1/\"\n\n try:\n r = requests.get(\n local_api_url,\n verify=False,\n headers={\"Authorization\": f\"TOKEN {ADMIN_TOKEN}\"},\n )\n r.raise_for_status()\n local_gc_running = True\n except requests.exceptions.ConnectionError:\n local_gc_running = False\n\n if local_gc_running:\n yield local_api_url\n else:\n # Start our own version of grand challenge\n with TemporaryDirectory() as tmp_path:\n\n for f in [\n \"docker-compose.yml\",\n \"dockerfiles/db/postgres.test.conf\",\n ]:\n get_grand_challenge_file(Path(f), Path(tmp_path))\n\n try:\n check_call([\"docker-compose\", \"pull\"], cwd=tmp_path)\n\n for command in [\n \"migrate\",\n \"check_permissions\",\n \"init_gc_demo\",\n ]:\n check_call(\n [\n \"docker-compose\",\n \"run\",\n \"--rm\",\n \"web\",\n \"python\",\n \"manage.py\",\n command,\n ],\n cwd=tmp_path,\n )\n check_call([\"docker-compose\", \"up\", \"-d\"], cwd=tmp_path)\n check_call(\n [\"docker-compose-wait\", \"-w\", \"-t\", \"2m\"], cwd=tmp_path\n )\n\n yield local_api_url\n\n finally:\n check_call([\"docker-compose\", \"down\"], cwd=tmp_path)\n\n\ndef get_grand_challenge_file(repo_path: Path, output_directory: Path) -> None:\n r = requests.get(\n (\n f\"https://raw.githubusercontent.com/comic/grand-challenge.org/\"\n f\"master/{repo_path}\"\n ),\n allow_redirects=True,\n )\n\n if str(repo_path) == \"docker-compose.yml\":\n content = rewrite_docker_compose(r.content)\n else:\n content = r.content\n\n output_file = output_directory / repo_path\n makedirs(str(output_file.parent), exist_ok=True)\n\n with open(str(output_file), \"wb\") as f:\n f.write(content)\n\n\ndef rewrite_docker_compose(content: bytes) -> bytes:\n spec = yaml.safe_load(content)\n\n for s in spec[\"services\"]:\n # Remove the non-postgres volume mounts, these are not needed for testing\n if s != \"postgres\" and \"volumes\" in spec[\"services\"][s]:\n del spec[\"services\"][s][\"volumes\"]\n\n # Replace test with production containers\n if spec[\"services\"][s][\"image\"] == \"grandchallenge/web-test:latest\":\n spec[\"services\"][s][\"image\"] = \"grandchallenge/web:latest\"\n\n # Use the production web server as the test one is not included\n spec[\"services\"][\"web\"][\n \"command\"\n ] = \"gunicorn -b 0.0.0.0 -k uvicorn.workers.UvicornWorker config.asgi:application\"\n\n return yaml.safe_dump(spec).encode(\"utf-8\")\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":3387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"330061028","text":"#!/usr/bin/python\r\nimport db\r\nimport datetime\r\nimport mylogging\r\nfrom send_sms import SendClientSms\r\n\r\ndef GetAllActiveClients():\r\n\r\n try:\r\n conn = db.DbConnect()\r\n except Exception as e:\r\n msg = \"Unable to connect to database\"\r\n mylogging.LogError(msg, e)\r\n return False\r\n\r\n cursor = conn.cursor()\r\n\r\n sql = \"SELECT C.policy_number as policy, C.balance as balance, C.extended, P.premium as premium FROM clients C LEFT JOIN policyplans P ON C.policy_plan = P.Id WHERE C.is_active = 1\"\r\n\r\n try:\r\n cursor.execute(sql)\r\n except Exception as e:\r\n msg = \"unable to fetch active clients\"\r\n mylogging.LogError(msg, e)\r\n return False\r\n\r\n db.DbDisconnect(conn)\r\n return cursor\r\n\r\ndef BillClient(smsList):\r\n\r\n try:\r\n conn = db.DbConnect()\r\n except Exception as e:\r\n msg = \"Unable to connect to database\"\r\n mylogging.LogError(msg, e)\r\n return False\r\n\r\n cursor = conn.cursor()\r\n\r\n sql = \"INSERT INTO premiums(policy_number, amount, period, run_date, status) VALUES(%s, %s, %s, %s, %s)\"\r\n\r\n try:\r\n cursor.executemany(sql, smsList)\r\n conn.commit()\r\n except Exception as e:\r\n msg = \"unable insert client bills\"\r\n mylogging.LogError(msg, e)\r\n return False\r\n\r\n db.DbDisconnect(conn)\r\n return False\r\n\r\ndef UpdateClientBalance(policy, amount, cursor):\r\n\r\n sql = \"UPDATE clients SET balance = (balance + %d) WHERE policy_number = '%s'\" % (amount,policy)\r\n\r\n try:\r\n cursor.execute(sql)\r\n except Exception as e:\r\n msg = \"unable to update client balance\"\r\n mylogging.LogError(msg, e)\r\n return False\r\n\r\n return True\r\n\r\ndef Main():\r\n # 1) Get active clients\r\n cursor = GetAllActiveClients()\r\n\r\n if not cursor:\r\n msg = \"main program failed because of error(s)\"\r\n e = \"None\"\r\n mylogging.LogError(msg, e)\r\n else:\r\n count = 0\r\n if (cursor.rowcount > 0):\r\n results = cursor.fetchall()\r\n\r\n # db connection for updating\r\n # *****************************************************\r\n try:\r\n conn = db.DbConnect()\r\n except Exception as e:\r\n msg = \"Unable to connect to database\"\r\n mylogging.LogError(msg, e)\r\n return False\r\n\r\n cursor1 = conn.cursor()\r\n # ******************************************************\r\n \r\n # dates\r\n # ******************************************************\r\n now = datetime.datetime.now()\r\n nowFormatted = now.strftime(\"%Y-%m-%d %H:%M:%S\")\r\n d = datetime.date.today()\r\n month = str(d.month)\r\n year = str(d.year)\r\n\r\n if len(month) == 1:\r\n month = \"0\"+month\r\n\r\n period = year+\"-\"+month\r\n # ******************************************************\r\n\r\n insertList = list()\r\n\r\n # loop through active clients, update balance and create insert array\r\n for row in results:\r\n count += 1\r\n premium = row[3]\r\n extended = row[2]\r\n \r\n policy = str(row[0])\r\n balance = float(row[1])\r\n\r\n if premium == None:\r\n premium = 0\r\n\r\n amount = float(premium) + float(extended)\r\n\r\n if balance < 0 and abs(balance) > amount:\r\n status = 1\r\n else:\r\n status = 0\r\n\r\n # create insert tuple and add it to list\r\n insertData = (policy,float(amount), period,nowFormatted, status)\r\n insertList.append(insertData)\r\n\r\n cursor2 = UpdateClientBalance(policy, amount, cursor1)\r\n\r\n if not cursor2:\r\n msg = \"main program failed because of error(s)\"\r\n e = \"None\"\r\n mylogging.LogError(msg, e)\r\n \r\n # commit updated values and disconnect update cursor\r\n conn.commit()\r\n db.DbDisconnect(conn)\r\n\r\n # bulk insert bills\r\n cursor3 = BillClient(insertList)\r\n if not cursor3:\r\n msg = \"main program failed because of error(s)\"\r\n e = \"None\"\r\n mylogging.LogError(msg, e)\r\n\r\n msg = \"Finished billing clients, count:\" + str(count)\r\n mylogging.LogInfo(msg)\r\n else:\r\n msg = \"No active clients, count:\" + str(count)\r\n mylogging.LogInfo(msg)\r\n\r\nif __name__ == \"__main__\":\r\n Main()","sub_path":"scripts/billing.py","file_name":"billing.py","file_ext":"py","file_size_in_byte":4679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"651231633","text":"import sys\nsys.path.append(\"..\")\n\nimport clusters\n\nmissing = [] # Indexes of countries with missing values\ndata_matrix = [] # Matrix of csv values\ndata_range = range(2, 8) # Useful sub-indexes\n\n\n# Read the input file and populate data_matrix and missing\ndef read_file(input_f):\n data = open(input_f)\n\n count = -2\n for line in data:\n count += 1\n if count == -1: # Skip headers\n continue\n\n arr = line.rstrip().split(',')\n if '' in arr:\n missing.append(count)\n\n data_matrix.append(arr)\n\n data.close()\n\n\n# Write data_matrix to an output file\ndef write_output(output_f):\n output = open(output_f, \"w\")\n\n for line in data_matrix:\n for i in range(len(line)):\n output.write(line[i] + ('\\n' if i == (len(line) - 1) else ','))\n\n output.close()\n\n\n# Return the 3 most similar countries\ndef find_similar(country, available):\n similarities = [] # List of 3 tuples of (index, score) with highest score\n country_vector = [int(country[i]) for i in available]\n\n for i in range(len(data_matrix)):\n if '' in data_matrix[i]: # Skip countries without a full set of data\n continue\n\n test_vector = [int(data_matrix[i][j]) for j in available]\n similarities = sorted(similarities + [(clusters.pearson(country_vector, test_vector), i)])[:3]\n\n return [data_matrix[i] for i in map(lambda x: x[1], similarities)]\n\n\n# Fill in missing values for a country\ndef fill(country):\n available = list(data_range)\n country_missing = []\n\n for index in data_range:\n if country[index] == '':\n available.remove(index)\n country_missing.append(index)\n\n similar_countries = find_similar(country, available)\n\n # Fill in missing values with averages\n for index in country_missing:\n country[index] = str(round(sum(map(lambda x: int(x[index]), similar_countries))/3))\n\n\n# Main function\ndef main(input_f, output_f):\n read_file(input_f)\n\n for index in missing:\n fill(data_matrix[index])\n\n write_output(output_f)\n\n\nif __name__ == \"__main__\":\n main(\"data/dataset.csv\", \"data/preprocessed.csv\")\n\n for l in data_matrix:\n print(l)\n","sub_path":"lab/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"259609536","text":"### THIS IS TEMPORARY! CAN DELETE ONCE ZACH UPDATES THE REAL SHIMON_HERO\n\nimport pygame\nimport time\nimport math\nimport numpy as np\nimport socket\nfrom copy import copy\nfrom mido import MidiFile\nimport os\nimport time\n\n\nclass GameSettings(object):\n def __init__(self):\n # SET DIMENSIONS AND STUFF\n self.SCREEN_WIDTH = 96 # pretty much scales everything else\n self.TOTAL_NUM_NOTES = 24.\n self.NOTE_WIDTH = self.SCREEN_WIDTH / self.TOTAL_NUM_NOTES\n self.NOTE_HEIGHT = self.NOTE_WIDTH * 4.\n\n self.SHIMON_RANGE = 1385. # for sending to shimon\n self.WIDTH_PROPORTION = 55. / self.SHIMON_RANGE #\n self.SEND_TO_SHIMON = False\n\n self.ARM_WIDTH = self.NOTE_WIDTH\n # math.ceil(((-1.0) * self.WIDTH_PROPORTION * self.SCREEN_WIDTH) / (((-1.0) * self.WIDTH_PROPORTION) - 1.0))\n self.ARM_HEIGHT = self.ARM_WIDTH * 4.\n self.SCREEN_HEIGHT = int(self.SCREEN_WIDTH + self.ARM_HEIGHT)\n\n self.UDP_IP = \"127.0.0.1\"\n self.UDP_PORT = 5005\n\n #self.sock = socket.socket(socket.AF_INET, # Internet\n #socket.SOCK_DGRAM) # UDP\n\n # SET ARMS STUFF\n self.NUMBER_OF_ARMS = 2\n self.ARM_SPEED = 2 # specified in pixels/frame - represents the maximum speed for the arms\n self.ACCELERATION = -1 # if acceleration is < 0 use instant velocity - specified in pixels/frame/frame\n # ** with the current setup, ARM_SPEED must be a multiple of ACCELERATION\n self.PIXELS_TO_STOP = 2 * (self.ARM_SPEED / self.ACCELERATION) # max number of pixels needed to stop\n self.NOTE_SPEED = 1\n\n # set control mode, can be either list_enumerated [1, 0, 0...], [0, 1, 0]\n # this mode only exists because it conveniently works well with the deep mind stuff.\n # the other mode is direct which takes a list which has the direction of each arm:\n # 1 being right, -1 being left and 0 being stay still\n self.CONTROL_MODE = [\"list_enumerated\", \"direct\"][1]\n\n # REWARD STUFF\n self.REWARD_CATCHING_NOTE = 1.\n self.PENALTY_MISSING_NOTE = -1.\n self.PLAYER_DIES_PENALTY = 0.\n self.ARM_COLLISION_PENALTY = 0. # punishment for arms colliding\n self.AMOUNT_TO_MISS = self.ARM_HEIGHT # this is how many pixels a note can go past the arms before it is considered missed\n self.POINT_THRESHOLD = -10\n\n # GAME SETTINGS\n self.COLLIDE_DEATH = False # if true, arms collideing causes death, else arms colliding causes arms to stay still\n self.PROB_NOTE_SPAWNED = 0.02\n self.DISPLAY_SCORE = False\n self.SOUND_WHEN_GENERATED = False # if true, notes will play sound when generated as well as hit\n\n # DIRECTORY SETTINGS\n self.USE_MIDI = True\n self.MIDI_FILES_DIRECTORY = './midi/curriculum2/level5' # if empty, defaul is random\n self.THRESHOLD_TIME = 30\n self.RANDOM_NOTES_IN_BETWEEN = False\n self.RANDOM_NOTES_RANGE = (52, 68)\n self.RANDOM_NOTES_PROB = 0.02\n self.RANDOM_NOTES_NUMS = [5,6,11,12,17,18]\n\n\n self.ARM_DIRECTION = (np.zeros(self.NUMBER_OF_ARMS)).tolist()\n self.ARM_STARTS = (np.zeros(self.NUMBER_OF_ARMS)).tolist()\n left_arms = 0\n right_arms = 0\n for i in range(self.NUMBER_OF_ARMS): # initialize arm stuff\n if i % 2 == 0: # arm is on left\n arm_start = left_arms * self.ARM_WIDTH\n arm_direction = 1 # arm will move right by default\n self.ARM_STARTS[left_arms] = arm_start\n self.ARM_DIRECTION[left_arms] = arm_direction\n left_arms += 1\n else: # arm is on right\n arm_start = self.SCREEN_WIDTH - (((1 + right_arms) * self.ARM_WIDTH))\n arm_direction = -1 # arm will move left by default\n self.ARM_STARTS[self.NUMBER_OF_ARMS - 1 - right_arms] = arm_start\n self.ARM_DIRECTION[self.NUMBER_OF_ARMS - 1 - right_arms] = arm_direction\n right_arms += 1\n\n self.GAME_TITLE = 'shimon_hero_hanoi'\n self.TPS = 100\n\n # Loose definition of a colours used in the game\n self.BLACK = (0, 0, 0)\n self.WHITE = (255, 255, 255)\n self.RED = (219, 218, 191)\n self.DARK_GREY = (50, 50, 50)\n self.NOTE = (255, 215, 64)\n self.GREY = (255, 255, 255)\n\n\ngs = GameSettings() # global singleton containing all game settings\n\n\nclass Block(pygame.sprite.Sprite):\n def __init__(self, width, height):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.Surface([width, height])\n self.rect = self.image.get_rect()\n\n\nclass Arm(Block):\n def __init__(\n self,\n index,\n arm_list,\n colour=gs.GREY,\n width=gs.ARM_WIDTH,\n start=0.0):\n\n self.start = start\n self.mult = 1.0\n self.position = start\n Block.__init__(self, width, gs.ARM_HEIGHT)\n self.image.fill(colour)\n self.arm_list = arm_list\n self.index = index\n self.rect.x = self.position\n self.rect.y = gs.SCREEN_HEIGHT - gs.ARM_HEIGHT\n self.score = 0\n self.speed = [+gs.ARM_SPEED, 0] # how fast the arm can go - should really be called max speed\n self.current_speed = 0.0 # represents how fast the arm is going (only used when working with acceleration)\n self.last_speed = 0.0\n self.direction = 0.0 # direction of intended movement (only used when working with acceleration)\n\n def move(self):\n if gs.ACCELERATION <= 0.0: # simple case: instant velocity\n right = gs.SCREEN_WIDTH - gs.ARM_WIDTH\n left = 0.0\n self.position = max(min((self.position + self.speed[0], right)), left)\n self.rect.x = self.position\n self.rect.y += self.speed[1]\n else: # use acceleration\n\n wall = [1,1]\n if self.index == 0 : # leftmost arm\n wall[0] = 0.5\n left = 0.0\n if self.index == gs.NUMBER_OF_ARMS - 1: # only one arm\n right = gs.SCREEN_WIDTH - gs.ARM_WIDTH\n else: # more than 1 arm\n right = self.arm_list[self.index + 1].position - gs.ARM_WIDTH\n elif self.index == gs.NUMBER_OF_ARMS - 1: # rightmost arm\n wall[1] = 0.5\n left = self.arm_list[self.index - 1].position + gs.ARM_WIDTH\n right = gs.SCREEN_WIDTH - gs.ARM_WIDTH\n else:\n left = self.arm_list[self.index - 1].position + gs.ARM_WIDTH\n right = self.arm_list[self.index + 1].position - gs.ARM_WIDTH\n\n output = False\n if((self.position - left) <= (gs.PIXELS_TO_STOP * wall[0])) and self.direction < 0.0:\n self.mult = math.sqrt(max(0.0, self.position - left) / (gs.PIXELS_TO_STOP * wall[0]))\n output = True\n elif((right - self.position) <= (gs.PIXELS_TO_STOP * wall[1])) and self.direction > 0.0:\n self.mult = math.sqrt(max(0.0, right - self.position) / (gs.PIXELS_TO_STOP * wall[1]))\n output = True\n else:\n self.mult = 1.0\n\n if self.direction != self.speed[0]: # arm changed direction\n self.current_speed = self.last_speed\n output = True\n if self.current_speed == 0.0:\n output = True # we want to output here because this is when we can actually update the position of arms\n\n if self.current_speed > self.speed[0]:\n self.current_speed = max(self.speed[0], self.current_speed - gs.ACCELERATION)\n elif self.current_speed < self.speed[0]:\n self.current_speed = min(self.speed[0], self.current_speed + gs.ACCELERATION)\n self.position = min(right, max(left, self.position + (self.mult * self.current_speed)))\n self.last_speed = (self.mult * self.current_speed)\n self.rect.x = self.position\n self.rect.y += self.speed[1]\n if output: # arm changed direction\n pass\n # print(\"this is where we output stuff to shimon\")\n self.direction = self.speed[0]\n\n def update(self):\n self.move()\n\n\nclass Penalty(Block):\n def __init__(self, color = gs.DARK_GREY):\n height = gs.ARM_HEIGHT\n Block.__init__(self, gs.SCREEN_WIDTH, height )\n self.image.fill(color)\n self.rect.x = 0\n self.rect.y = gs.SCREEN_HEIGHT - gs.ARM_HEIGHT + gs.AMOUNT_TO_MISS\n\n def update(self):\n pass\n\n\nclass Note(Block):\n def __init__(\n self,\n colour=gs.NOTE,\n speed=gs.NOTE_SPEED,\n note=None):\n Block.__init__(self, gs.NOTE_WIDTH, gs.NOTE_HEIGHT)\n self.image.fill(colour)\n offset = 0\n mult = (gs.SCREEN_WIDTH) / gs.TOTAL_NUM_NOTES\n\n if note != None:\n middle = gs.TOTAL_NUM_NOTES / 2\n if gs.TOTAL_NUM_NOTES % 2 == 1:\n middle = gs.TOTAL_NUM_NOTES / 2 + 1\n\n self.note = (note - 60) + middle\n while self.note >= gs.TOTAL_NUM_NOTES:\n self.note -= 12\n while self.note < 0:\n self.note += 12\n else:\n self.note = int(np.random.randint(0, gs.TOTAL_NUM_NOTES))\n\n self.sound_file = str(int(self.note)) + '.wav'\n self.rect.x = (self.note * mult) + offset\n self.rect.y = 0\n self.speed = speed\n\n def update(self):\n self.rect.y += self.speed\n\n def note_missed(self):\n return self.rect.y >= (gs.SCREEN_HEIGHT - gs.ARM_HEIGHT - gs.NOTE_HEIGHT - gs.AMOUNT_TO_MISS)\n\n\nclass Game(object):\n def __init__(self, *initial_data, **kwargs):\n\n np.random.seed(int(time.time())) # random seed\n\n for dictionary in initial_data: # allows for parameters to be loaded in as a dictionary\n for key in dictionary:\n setattr(gs, key, dictionary[key])\n for key in kwargs:\n setattr(gs, key, kwargs[key])\n\n self.start = time.time()\n\n # Launch PyGame\n pygame.init()\n pygame.mixer.init()\n pygame.display.set_caption(gs.GAME_TITLE)\n self.screen = pygame.display.set_mode([gs.SCREEN_WIDTH, gs.SCREEN_HEIGHT])\n\n # Initialize a few useful variables\n self.font = pygame.font.SysFont(\"calibri\", 20)\n self.reward = 0\n self.is_terminal = False\n self.count = +1\n self.clock = pygame.time.Clock()\n self.score = \"\"\n self.note_count = 0\n self.step_count = 0\n self.midi_notes = []\n self.tot_notes = 0\n\n\n if gs.USE_MIDI:\n if os.path.isdir(gs.MIDI_FILES_DIRECTORY):\n for file in os.listdir(gs.MIDI_FILES_DIRECTORY):\n if file.endswith('.midi') or file.endswith('.mid'):\n #print(\"reading midi file: \", file)\n midiFile = MidiFile(gs.MIDI_FILES_DIRECTORY + '/' + str(file))\n for i, track in enumerate(midiFile.tracks):\n for message in track:\n if message.type == \"note_on\":\n #print(\"note: \" + str(message.note) + \" time: \" + str(message.time))\n self.midi_notes.append((message.note, message.time/gs.NOTE_SPEED))\n self.tot_notes += 1\n\n\n self.penalty_zone = Penalty()\n\n self.penalty_list = pygame.sprite.Group()\n self.penalty_list.add(self.penalty_zone)\n self.all_items_list = pygame.sprite.Group()\n self.arm_sprite_list = pygame.sprite.Group()\n self.arm_list = []\n self.note_list = pygame.sprite.Group()\n self.arm_actions = []\n for i in range(gs.NUMBER_OF_ARMS):\n arm = Arm(i, self.arm_list, start=gs.ARM_STARTS[i])\n self.arm_sprite_list.add(arm)\n self.all_items_list.add(arm)\n self.arm_actions.append(1) # 1 means move in default direction\n self.arm_list.append(arm)\n self.last_time = time.time()\n\n def get_settings(self):\n return gs.__dict__\n\n def get_collisions(self, arms, directions):\n collisions = (np.zeros(gs.NUMBER_OF_ARMS)).tolist()\n for i in range(len(arms)):\n current_arm = arms[i]\n for j in range((i + 1), len(arms)):\n other_arm = arms[j]\n other_next_x = other_arm.rect.x + (gs.ARM_SPEED * directions[j] * gs.ARM_DIRECTION[j])\n current_next_x = current_arm.rect.x + (gs.ARM_SPEED * directions[i] * gs.ARM_DIRECTION[i])\n if((other_next_x - current_next_x) < gs.ARM_WIDTH):\n #print(i, other_arm.rect.x, current_arm.rect.x)\n collisions[i] = 1\n collisions[j] = 1\n return collisions\n\n def arm_collision(self, arms):\n for i in range(len(arms)):\n current_arm = arms[i]\n for j in range((i + 1), len(arms)):\n other_arm = arms[j]\n if((other_arm.rect.x - current_arm.rect.x) < gs.ARM_WIDTH):\n #print(i, other_arm.rect.x, current_arm.rect.x)\n return True\n return False\n\n def next_action(self, input_actions):\n if (gs.SEND_TO_SHIMON):\n this_time = time.time()\n if self.last_time != 0:\n arms_x = ''\n dt = this_time - self.last_time\n for i in range(len(self.arm_list)):\n arms_x += ' ' + str(self.arm_list[i].rect.x / float(gs.SCREEN_WIDTH - gs.ARM_WIDTH))\n speed = (gs.ARM_SPEED/float(gs.SCREEN_WIDTH - gs.ARM_WIDTH)) * float(gs.SHIMON_RANGE) / dt\n aG = 9.80665\n accel = (((gs.ACCELERATION/float(gs.SCREEN_WIDTH - gs.ARM_WIDTH))*float(gs.SHIMON_RANGE)/dt)*aG)/1000.0\n arms_x = arms_x + ' ' + str(accel) + ' ' + str(speed)\n gs.sock.sendto(arms_x, (gs.UDP_IP, gs.UDP_PORT))\n self.last_time = this_time\n\n if self.is_terminal:\n self.__init__() # If the player dies, then restart the game. HOWEVER, I need the self.is_terminal=True\n # and self.reward = -ve to be passed on to the q_learning algorithm. So reset the game when next_action\n # is called after the game that was lost.\n # Problem is that self.gave_over = True is not transferred directly to q learner immediatly.\n\n # We are using \"direct\" control mode of shimon arms in all cases\n for i in range(len(self.arm_actions)):\n self.arm_actions[i] = input_actions[i] * gs.ARM_DIRECTION[i]\n\n # penalty for colliding arms\n for i in range(len(self.arm_actions)):\n if i != gs.NUMBER_OF_ARMS - 1: # not right arm\n this_arm_x = self.arm_list[i].rect.x\n right_arm_x = self.arm_list[i+1].rect.x\n space = right_arm_x - this_arm_x\n if space <= gs.ARM_WIDTH: #arms are touching\n this_arm_dir = self.arm_actions[i] * gs.ARM_DIRECTION[i]\n right_arm_dir = self.arm_actions[i + 1] * gs.ARM_DIRECTION[i + 1]\n\n self.reward = -1 # If arms touch, then game over\n self.is_terminal = True # If arms touch, then game over\n\n if this_arm_dir != right_arm_dir: # arms moving in different directions\n if this_arm_dir == 1: # this arm collision\n self.arm_list[i+1].score += gs.ARM_COLLISION_PENALTY #punish other arm\n\n self.reward = -1 # If Shimon misses a note, give negative reward\n self.is_terminal = False # If Shimon misses a note, restart the game\n\n if right_arm_dir == -1: # right arm collision\n self.arm_list[i].score += gs.ARM_COLLISION_PENALTY\n\n\n\n # if collision is not set to terminal, then don't allow arms to move if they are collided\n if gs.ACCELERATION <= 0.0 and not gs.COLLIDE_DEATH:\n collisions = self.get_collisions(self.arm_list, self.arm_actions)\n collision = False\n total_movement = 0\n collision_start = 0\n for i in range(len(self.arm_actions)):\n if(collision):\n collision = collisions[i] == 1\n if collision: # continued collision\n total_movement += self.arm_actions[i] * gs.ARM_DIRECTION[i]\n else: # no more collision\n dir = 0\n if total_movement > 0:\n dir = 1\n elif total_movement < 0:\n dir = -1\n move = gs.ARM_DIRECTION[collision_start] * dir * gs.ARM_SPEED\n if(self.arm_list[collision_start].rect.x + move<= 0):\n dir = max(0, dir)\n print(self.arm_list[collision_start].rect.x + move)\n for j in range(collision_start, i):\n self.arm_actions[j] = gs.ARM_DIRECTION[j] * dir\n else:\n collision = collisions[i] == 1\n if collision: # new collision\n collision_start = i\n total_movement = self.arm_actions[i] * gs.ARM_DIRECTION[i]\n if collision:\n dir = 0\n if total_movement > 0:\n dir = 1\n elif total_movement < 0:\n dir = -1\n move = gs.ARM_DIRECTION[len(self.arm_list) - 1] * dir * gs.ARM_SPEED\n if (self.arm_list[len(self.arm_list) - 1].rect.x + move >= gs.SCREEN_WIDTH - gs.ARM_WIDTH - 1):\n dir = min(0, dir)\n # print(self.arm_list[len(self.arm_list) - 1].rect.x + move)\n move = gs.ARM_DIRECTION[collision_start] * dir * gs.ARM_SPEED\n if (self.arm_list[collision_start].rect.x + move <= 0):\n dir = max(0, dir)\n for j in range(collision_start, len(self.arm_actions)):\n self.arm_actions[j] = gs.ARM_DIRECTION[j] * dir\n\n # Update all items' positions and the game_count\n for i in range(len(self.arm_list)):\n self.arm_list[i].speed = [gs.ARM_SPEED * self.arm_actions[i] * gs.ARM_DIRECTION[i], 0]\n self.all_items_list.update()\n self.count += 1\n\n # Create the background, basic frame, and score line\n self.screen.fill(gs.BLACK)\n score_total = 0\n for arm in self.arm_list:\n score_total += arm.score\n\n if gs.DISPLAY_SCORE:\n self.score = self.font.render(\n str(int(score_total)), True, gs.WHITE)\n self.screen.blit(\n self.score,\n (6, 0))\n # self.reward = copy(score_total) # Need to return the overall score\n\n # Generate notes based on MIDI file input or randomly\n if gs.USE_MIDI and self.note_count <= len(self.midi_notes) - 1:\n if gs.RANDOM_NOTES_IN_BETWEEN:\n if self.midi_notes[self.note_count][1] - self.step_count > gs.THRESHOLD_TIME and self.step_count > gs.THRESHOLD_TIME:\n if (np.random.uniform() < gs.RANDOM_NOTES_PROB):\n note = Note(note = int(np.random.randint(gs.RANDOM_NOTES_RANGE[0], gs.RANDOM_NOTES_RANGE[1])))\n if gs.SOUND_WHEN_GENERATED:\n sound = pygame.mixer.Sound('piano_notes/' + str(note.sound_file))\n sound.play()\n self.note_list.add(note)\n self.all_items_list.add(note)\n self.tot_notes += 1\n while self.note_count <= len(self.midi_notes) - 1 and self.midi_notes[self.note_count][1] == self.step_count:\n note = None\n if self.note_count + 1 in gs.RANDOM_NOTES_NUMS:\n note = Note(note=int(np.random.randint(gs.RANDOM_NOTES_RANGE[0], gs.RANDOM_NOTES_RANGE[1])))\n else:\n note = Note(note=self.midi_notes[self.note_count][0])\n if gs.SOUND_WHEN_GENERATED:\n sound = pygame.mixer.Sound('piano_notes/' + str(note.sound_file))\n sound.play()\n self.note_list.add(note)\n self.all_items_list.add(note)\n self.note_count += 1\n self.step_count = 0\n self.step_count += 1\n #if self.note_count >= len(self.midi_notes) - 1:\n #print(\"Song(s) completed\")\n elif gs.USE_MIDI and self.note_list.__len__() == 0:\n self.is_terminal = True\n elif not gs.USE_MIDI:\n if (np.random.uniform() < gs.PROB_NOTE_SPAWNED):\n note = Note()\n if gs.SOUND_WHEN_GENERATED:\n sound = pygame.mixer.Sound('piano_notes/' + str(note.sound_file))\n sound.play()\n self.note_list.add(note)\n self.all_items_list.add(note)\n\n\n self.reward = 0 # reward is 0 by default\n\n for arm in self.arm_list:\n note_hit = pygame.sprite.spritecollide(arm, self.note_list, True)\n # Play corresponding note sounds when note is hit\n for note in note_hit:\n sound = pygame.mixer.Sound('piano_notes/' + str(note.sound_file))\n sound.play()\n\n if note_hit:\n arm.score += len(note_hit) * gs.REWARD_CATCHING_NOTE\n self.reward = 1 # reward is 1 when a note is hit\n\n penalty_hits = pygame.sprite.spritecollide(self.penalty_zone, self.note_list, True)\n if penalty_hits:\n arm.score += gs.PENALTY_MISSING_NOTE\n self.reward = -1 # If Shimon misses a note, give negative reward\n self.is_terminal = False # If Shimon misses a note, restart the game\n\n #self.reward = copy(score_total)\n\n # If the arm hits an obstacle or the screen's border, it's game over\n # The scores are updated and the game is reset\n if gs.COLLIDE_DEATH:\n did_arms_collide = self.arm_collision(self.arm_list)\n if (did_arms_collide):\n #print(\"ARMS COLLIDED\")\n self.last_score = self.arm_list[0].score\n\n self.all_items_list.empty()\n self.arm_sprite_list.empty()\n self.note_list.empty()\n #self.reward += gs.PLAYER_DIES_PENALTY\n self.reward = -1 #\n self.is_terminal = True\n\n #if self.reward <= gs.POINT_THRESHOLD:\n #self.is_terminal = True\n\n\n # Print all objects in the screen\n self.penalty_list.draw(self.screen)\n self.all_items_list.draw(self.screen)\n\n image_data = pygame.surfarray.array3d(pygame.display.get_surface())\n pygame.display.update()\n # self.clock.tick(gs.TPS)\n\n\n\n return image_data, self.reward, self.is_terminal, score_total\n\n def exit_game(self):\n # Save settings, reset the graph, and close the session\n pygame.display.quit()\n pygame.quit()\n","sub_path":"shimon_hero/shimon_hero_curriculum.py","file_name":"shimon_hero_curriculum.py","file_ext":"py","file_size_in_byte":23442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"395682497","text":"import base64\nimport sys\nimport datetime\nimport random\n\nfrom google.cloud import pubsub_v1\nimport json\n\nPROJECT_ID = \"sej-dev-spanner-test\"\nTOPIC_NAME = \"aggregation-by-label\"\n\n\ndef _publish(project_id, topic_name, data):\n pub_client = pubsub_v1.PublisherClient()\n topic_path = pub_client.topic_path(project_id, topic_name)\n future = pub_client.publish(topic_path, data=data)\n # print('Published {} of message ID {}.'.format(data, future.result()))\n\n\nif __name__ == \"__main__\":\n\n time_now = datetime.datetime.now()\n month = time_now.month\n year = time_now.year\n day = time_now.day\n hour = time_now.hour\n minute = time_now.minute\n second = time_now.second\n\n record_cnt = 952\n record_json_list = [] * record_cnt\n for i in range(record_cnt):\n record_json_list.append({\n \"store_cd\": \"900\"+ str(record_cnt).zfill(3),\n \"created_datetime\": str(year).zfill(4) + str(month).zfill(2) + str(day).zfill(2) + str(hour).zfill(2) + str(\n minute).zfill(2) + str(second).zfill(2),\n \"instore_label_cd\": str(i + 1).zfill(14),\n \"item_cd\": str(i).zfill(6),\n \"tyunou_yyyymmdd\": str(year).zfill(4) + str(month).zfill(2) + str(day).zfill(2),\n \"shipping_no\": \"3\",\n \"delivery_amnt\": 200,\n \"sales_amnt\": 5000,\n \"disposal_amnt\": 20,\n \"returns_amnt\": 6,\n \"move_amnt\": 10,\n \"inside_store_amnt\": 70,\n \"delivery_plans_datetime\": \"20201012222600\",\n \"out_of_freshness_datetime\": \"20201012222600\",\n \"delivery_processing_datetime\": \"20201012222600\",\n \"final_shipment_datetime\": \"20201012222600\",\n \"final_shipment_processing_type\": \"12\"\n })\n data_json = {\n \"id\": str(year).zfill(4) + str(month).zfill(2) + str(day).zfill(2) + str(hour).zfill(2) + str(minute).zfill(\n 2) + str(second).zfill(2),\n \"sendtimes\": 1,\n \"aggregate_unit\": record_json_list\n }\n _publish(PROJECT_ID, TOPIC_NAME, json.dumps(data_json).encode(\"utf-8\"))\n\n print('data_json: ' + json.dumps(data_json))\n data_b_body = base64.b64encode(json.dumps(data_json).encode('utf-8'))\n data_body = data_b_body.decode('ascii')\n data_json_message = {\n \"messages\": [\n {\n \"attributes\": {\n \"key\": \"iana.org/language_tag\",\n \"value\": \"en\"\n },\n \"data\": data_body\n }\n ]\n }\n data_pubsub_message = json.dumps(data_json_message).encode('utf-8')\n print('data pubsub message: ' + json.dumps(data_json))\n\n","sub_path":"publish_instore_label_aggregate.py","file_name":"publish_instore_label_aggregate.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"386428887","text":"from django import forms\nfrom Article.models import Post\nfrom tinymce.widgets import TinyMCE\n\n\nclass BlogForm(forms.ModelForm):\n\n class Meta:\n model=Post\n fields = ['description','content']\n widgets = {\n 'name': TinyMCE(attrs={'cols': 80, 'rows': 30,'class': 'form-control'}),\n }\n\n","sub_path":"Article/form.py","file_name":"form.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"428068605","text":"import matplotlib.pyplot as plt \nfrom numpy.random import normal\n\ngaussian_numbers = normal(size=1000)\n\nplt.hist(gaussian_numbers)\n\n#plot\nplt.title(\"Gaussian Histogram\") \nplt.xlabel(\"Value\") \nplt.ylabel(\"Frequency\") \n\nplt.show()\n","sub_path":"FOP/Prac03/histogramtest.py","file_name":"histogramtest.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"371957235","text":"import connexion\nimport six\nimport os\nimport googleapiclient.discovery\nimport json\n\nfrom swagger_server.models.vm import VM # noqa: E501\nfrom swagger_server import util\n\ncreds = os.environ['HOME'] + '/.cloudmesh/configuration_gce_419.json'\n\nos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = creds\n\nwith open(creds) as json_data:\n d = json.load(json_data)\n project = d['project_id']\n\ndef vms_get(): # noqa: E501\n \"\"\"vms_get\n\n Returns a list of VMs # noqa: E501\n\n\n :rtype: List[VM]\n \"\"\"\n vms = []\n compute = googleapiclient.discovery.build('compute', 'v1')\n\n zones = compute.zones().list(project=project).execute()\n results=[]\n \n for zone in zones['items']:\n instances = compute.instances().list(project=project, zone=zone['name']).execute()\n if 'items' in instances.keys():\n results = results + instances['items']\n \n for result in results:\n vm = VM(id=result['id'],\n creation_timestamp=result['creationTimestamp'],\n name=result['name'],\n description=result['description'],\n machine_type=result['machineType'],\n status=result['status'],\n zone=result['zone'],\n can_ip_forward=result['canIpForward'])\n vms.append(vm)\n \n return vms\n\ndef vms_id_get(id): # noqa: E501\n \"\"\"vms_id_get\n\n Returns information on a VM instance # noqa: E501\n\n :param id: ID of VM to fetch\n :type id: str\n\n :rtype: VM\n \"\"\"\n vms = vms_get()\n vm = vms['id'==id]\n \n return vm\n","sub_path":"swagger/cloudmesh/google_compute_engine/default_controller.py","file_name":"default_controller.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"507642013","text":"# -*- coding: utf-8 -*-\n# https://blog.csdn.net/lzs781/article/details/97617723\nimport socket\nimport threading\n\n# 端口映射配置信息\n# 接收数据缓存大小\nPKT_BUFF_SIZE = 16384\na_8888 = {}\nb_34444 = {}\nb_9999 = {}\na_9999 = {}\nrecent_count = 5\nlisten1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nlisten1.bind((\"0.0.0.0\", 34444))\n\n\ndef log(msg, *args, **kwargs):\n print(msg, *args, **kwargs)\n\n\ndef l1():\n global a_8888, b_34444, b_9999, listen1\n while True:\n try:\n data, source = listen1.recvfrom(PKT_BUFF_SIZE)\n # log('recv from 34444: {} B, '.format(len(data)))\n if len(a_8888) == 0 or len(b_34444) == 0:\n # 若至少有一方还未连接\n if len(data) == 1:\n b_34444[source] = recent_count\n log('b34444 found: {}'.format(source))\n else:\n a_8888[source] = recent_count\n log('a8888 found: {}'.format(source))\n else:\n # 两方都连接了 有一方更换了地址\n if (source not in a_8888) and (source not in b_34444):\n if source in a_8888:\n # b换了\n b_34444[source] = recent_count\n log('new b found: {}'.format(source))\n elif source in b_34444:\n # a 换了\n a_8888[source] = recent_count\n log('new a found: {}'.format(source))\n else:\n # 未知错误\n a_8888[source] = recent_count\n b_34444[source] = recent_count\n\n log('**new a,b found**: {}\\n\\n\\n'.format(source))\n\n if len(b_34444) != 0:\n\n minus(b_34444)\n for addr in b_34444:\n b_34444[addr] = recent_count\n listen1.sendto(data, addr)\n # log('send 34444 -> b34444: {}'.format(addr))\n\n log(\"l1: a8888{} -> b34444{}\\nall a8888:{}\".format(source, b_34444, a_8888))\n else:\n log('found no acceptor, waiting...')\n except KeyboardInterrupt:\n log('l1 stop.')\n listen1.close()\n break\n\n\nlisten2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nlisten2.bind((\"0.0.0.0\", 8888))\n\n\ndef l2():\n global b_9999, a_9999, a_8888, listen1, listen2\n while True:\n try:\n data, source = listen2.recvfrom(PKT_BUFF_SIZE)\n if source not in b_9999:\n b_9999[source] = recent_count\n log('b9999 found: {}'.format(source))\n\n # log('recv b9999 -> 8888: {} B'.format(len(data)))\n minus(a_8888)\n for addr in a_8888:\n a_8888[addr] = recent_count\n listen1.sendto(data, addr)\n # log('send 34444 -> a8888: {}'.format(addr))\n\n log(\"l2: b9999->a8888: {} -> {}\\nall b9999:{} \".format(source, a_8888, b_9999))\n\n except KeyboardInterrupt:\n log('l2 stop.')\n listen2.close()\n break\n\n\nlisten3 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nlisten3.bind((\"0.0.0.0\", 9999))\n\n\ndef l3():\n global a_9999, b_9999, listen2, listen3\n while True:\n try:\n data, source = listen3.recvfrom(PKT_BUFF_SIZE)\n if source not in a_9999:\n a_9999[source] = recent_count\n log('a9999 found: {}'.format(source))\n\n # log('recv a9999 -> 9999: {} B'.format(len(data)))\n minus(b_9999)\n for addr in b_9999:\n b_9999[addr] = recent_count\n listen2.sendto(data, addr)\n # log('send 8888 -> b9999: {}'.format(addr))\n log(\"l3: a9999->b9999: {} -> {}\\nall a9999:{} \".format(source, b_9999, a_9999))\n\n except KeyboardInterrupt:\n log('l3 stop.')\n listen3.close()\n break\n\n\ndef minus(a: dict):\n\n for key in a.keys():\n if a[key] <= 1:\n del a[key]\n continue\n a[key] -= 1\n\n\n\nprint('server start....')\nt1 = threading.Thread(target=l1)\nt2 = threading.Thread(target=l2)\nt3 = threading.Thread(target=l3)\nt1.start()\nt2.start()\nt3.start()\nprint('all server start complete')\ntry:\n t1.join()\n t2.join()\n t3.join()\nexcept KeyboardInterrupt:\n print('a8888: {}'.format(a_8888))\n print('a9999: {}'.format(a_9999))\n print('b9999: {}'.format(b_9999))\n print('b34444: {}'.format(b_34444))\n pass\nlisten1.close()\nlisten2.close()\nlisten3.close()\n\n","sub_path":"server2.py","file_name":"server2.py","file_ext":"py","file_size_in_byte":4642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"459989926","text":"# 打开文件\nimport os\nimport time\n\nimport pymysql\nimport xlrd as xlrd\n\nsuccess = 0\nfail = 0\nrootdir = r'C:\\Users\\Administrator.DESKTOP-DV7S27B\\Desktop\\IDGdemo\\IO\\IT橘子'\nlist = os.listdir(rootdir) # 列出文件夹下所有的目录与文件\nfor i in range(0, len(list)):\n path = os.path.join(rootdir, list[i])\n if os.path.isfile(\n path) and path == r'C:\\Users\\Administrator.DESKTOP-DV7S27B\\Desktop\\IDGdemo\\IO\\IT橘子\\2018年12月15日投融资信息.xlsx': # #判断路径是否为文件\n print('当前打开的是', path)\n workbook = xlrd.open_workbook(path)\n # 获取所有sheet\n # print(workbook)\n print(workbook.sheet_names())\n # 根据sheet索引或者名称获取sheet内容\n sheet2 = workbook.sheet_by_index(0) # sheet索引从0开始\n # sheet的名称,行数,列数\n print(sheet2.name, sheet2.nrows, sheet2.ncols)\n for i in range(1, sheet2.nrows):\n # 获取整行和整列的值(数组)\n rows = sheet2.row_values(i) # 获取第四行内容\n finance_time = rows[0] # 把融资时间格式化输出\n import time\n timeArray = time.strptime(finance_time, \"%Y-%m-%d\")\n finance_time = time.strftime(\"%Y-%m-%d\", timeArray)\n # print(finance_time)\n company_name = rows[2]\n legal_name = rows[3]\n city = rows[4]\n industry = rows[5]\n finance = rows[6]\n money = rows[7]\n agency = rows[8]\n brief = rows[9]\n past_financing = rows[10]\n teams = rows[11]\n localtime = time.localtime(time.time())\n str_time = time.strftime(\"%Y-%m-%d\", localtime)\n db = pymysql.connect(\"192.168.103.31\", \"root\", \"adminadmin\", \"company\")\n # 使用 cursor() 方法创建一个游标对象 cursor\n cursor = db.cursor()\n # SQL 插入语句\n sql = \"\"\"INSERT INTO ITORANGE(project_name,brief,industry,city,finance_time,finance,money,agency,legal_person,legal_name,registered_capital,competing_product,past_financing,teams,types,insert_times) VALUES (\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%d\",\"%s\")\"\"\" % (\n company_name, brief, industry, city, finance_time, finance, money, agency, '', legal_name, '', '',\n past_financing, teams, 2, str_time)\n try:\n # 执行sql语句\n cursor.execute(sql)\n # 提交到数据库执行\n db.commit()\n print('成功公司', company_name)\n success += 1\n except Exception as e:\n fail += 1\n print(e)\n # 如果发生错误则回滚\n db.rollback()\n # print(company_name, brief, industry, city, finance_time, finance, money, agency)\n\n db.close()\nprint('成功数', success)\nprint('失败数', fail)\n","sub_path":"IDGdemo/IO/python_IT_orange_csv.py","file_name":"python_IT_orange_csv.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"613498720","text":"\n## Dynamic programming solution to the sequence alignment problem.\n\ndef align(s, t, w_sub = 1, w_gap = 1):\n dist = [ [0] * (len(t) + 1) for i in range(len(s) + 1) ]\n for i in range(0, len(s) + 1):\n dist[i][0] = i * w_gap\n for j in range(0, len(t) + 1):\n dist[0][j] = j * w_gap\n print(\"with base cases:\")\n print('\\n'.join([str(row) for row in dist]))\n for i in range(1, len(s) + 1):\n for j in range(1, len(t) + 1):\n if s[i - 1] == t[j - 1]:\n d1 = dist[i - 1][j - 1]\n else:\n d1 = dist[i - 1][j - 1] + w_sub\n dist[i][j] = min(d1, dist[i - 1][j] + w_gap, dist[i][j - 1] + w_gap)\n print(\"complete:\")\n print('\\n'.join([str(row) for row in dist]))\n return dist[len(s)][len(t)]\n\n\ns1 = \"GAATTCA\"\ns2 = \"GGATCGA\"\ns3 = \"GCATGCT\"\ns4 = \"GATTACA\"\n","sub_path":"dynamic/align-dp.py","file_name":"align-dp.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"126323184","text":"# from django.db.models import fields\r\nfrom django.shortcuts import render, redirect\r\nfrom django.http import HttpResponse\r\n\r\n# from django.forms import inlineformset_factory\r\n# from django.contrib.auth.forms import UserCreationForm\r\nfrom django.views.generic import (\r\n ListView,\r\n DetailView,\r\n CreateView,\r\n UpdateView,\r\n DeleteView,\r\n)\r\nfrom django.contrib.auth import authenticate, login, logout\r\nfrom django.contrib.auth.models import User\r\nfrom django.urls import reverse_lazy\r\n\r\nfrom django.contrib import messages\r\n\r\nfrom django.contrib.auth.decorators import login_required\r\n\r\nfrom django.contrib.sites.shortcuts import get_current_site\r\nfrom django.utils.encoding import force_bytes, force_text\r\nfrom django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode\r\nfrom django.template.loader import render_to_string\r\nfrom .tokens import account_activation_token\r\nfrom django.core.mail import EmailMessage\r\nfrom django.shortcuts import get_object_or_404\r\n\r\n\r\n# Create your views here.\r\nfrom .models import *\r\nfrom .forms import RestuarantUserForm, FoodRedistributorUserForm, PostForm\r\n\r\n\r\n# @user_passes_test(res_check)\r\ndef register_restaurant(request):\r\n if request.user.is_authenticated:\r\n return redirect(\"home\")\r\n else:\r\n form = RestuarantUserForm(request.POST)\r\n if request.method == \"POST\":\r\n if form.is_valid():\r\n # WRITE TEST FROM HERE\r\n user = form.save(commit=False)\r\n user.is_active = False\r\n user.save()\r\n user_profile = Restaurant(user=user)\r\n # name = form.cleaned_data.get(\"username\")\r\n current_site = get_current_site(request)\r\n mail_subject = \"Activate your account.\"\r\n message = render_to_string(\r\n \"accounts/acc_active_email.html\",\r\n {\r\n \"user\": user,\r\n \"domain\": current_site.domain,\r\n \"uid\": urlsafe_base64_encode(force_bytes(user.pk)),\r\n \"token\": account_activation_token.make_token(user),\r\n },\r\n )\r\n\r\n # Just trying to condense some lines here\r\n\r\n # to_email = form.cleaned_data.get(\"email\")\r\n # form.clean_email()\r\n # user_profile.email = to_email\r\n user_profile.email = form.cleaned_data.get(\"email\")\r\n # nameofres = form.cleaned_data.get(\"name_of_restaurant\")\r\n # user_profile.name = name\r\n user_profile.name = form.cleaned_data.get(\"username\")\r\n # user_profile.name_of_restaurant = nameofres\r\n user_profile.name_of_restaurant = form.cleaned_data.get(\r\n \"name_of_restaurant\"\r\n )\r\n # phone_r = form.cleaned_data.get(\"phone\")\r\n # user_profile.phone = phone_r\r\n user_profile.phone = form.cleaned_data.get(\"phone\")\r\n # address_r = form.cleaned_data.get(\"address\")\r\n # user_profile.address = address_r\r\n user_profile.address = form.cleaned_data.get(\"address\")\r\n user_profile.is_res = True\r\n user_profile.save()\r\n email = EmailMessage(mail_subject, message, to=[to_email])\r\n email.send()\r\n return HttpResponse(\r\n \"Please confirm your email address to complete the registration\"\r\n )\r\n # TO HERE\r\n\r\n context = {\"form\": form}\r\n return render(request, \"accounts/restuarant_register.html\", context)\r\n\r\n\r\ndef activate(request, uidb64, token):\r\n try:\r\n uid = force_text(urlsafe_base64_decode(uidb64))\r\n user = User.objects.get(pk=uid)\r\n except (TypeError, ValueError, OverflowError, User.DoesNotExist):\r\n user = None\r\n if user is not None and account_activation_token.check_token(user, token):\r\n user.is_active = True\r\n user.save()\r\n login(request, user)\r\n # return redirect('home')\r\n return HttpResponse(\r\n \"Thank you for your email confirmation. Now you can login your account.\"\r\n )\r\n else:\r\n return HttpResponse(\"Activation link is invalid!\")\r\n\r\n\r\ndef register_foodredistributor(request):\r\n if request.user.is_authenticated and request.user.is_active:\r\n return redirect(\"home2\")\r\n else:\r\n form = FoodRedistributorUserForm(request.POST)\r\n if request.method == \"POST\":\r\n if form.is_valid():\r\n # user = form.save()\r\n user = form.save(commit=False)\r\n user.is_active = False\r\n user.save()\r\n user_profile = FoodRedistributor(user=user)\r\n # name = form.cleaned_data.get(\"username\")\r\n current_site = get_current_site(request)\r\n mail_subject = \"Activate your account.\"\r\n message = render_to_string(\r\n \"accounts/acc_active_email.html\",\r\n {\r\n \"user\": user,\r\n \"domain\": current_site.domain,\r\n \"uid\": urlsafe_base64_encode(force_bytes(user.pk)),\r\n \"token\": account_activation_token.make_token(user),\r\n },\r\n )\r\n # to_email = form.cleaned_data.get(\"email\")\r\n user_profile.email = form.cleaned_data.get(\"email\")\r\n # nameofredis = form.cleaned_data.get(\"name_of_food_redis\")\r\n # user_profile.name = name\r\n user_profile.name = form.cleaned_data.get(\"username\")\r\n user_profile.name_of_food_redis = form.cleaned_data.get(\r\n \"name_of_food_redis\"\r\n )\r\n # phone_r = form.cleaned_data.get(\"phone\")\r\n user_profile.phone = form.cleaned_data.get(\"phone\")\r\n # address_r = form.cleaned_data.get(\"address\")\r\n user_profile.address = form.cleaned_data.get(\"address\")\r\n user_profile.is_food_redis = True\r\n user_profile.save()\r\n email = EmailMessage(mail_subject, message, to=[to_email])\r\n email.send()\r\n return HttpResponse(\r\n \"Please confirm your email address to complete the registration\"\r\n )\r\n # messages.success(\r\n # request, f'Success! Account created for {name}')\r\n # user_profile.save()\r\n # return redirect('login2')\r\n\r\n context = {\"form\": form}\r\n return render(request, \"accounts/food_redistributor_register.html\", context)\r\n\r\n\r\nclass PostView(ListView):\r\n model = Post\r\n template_name = \"accounts/blogposts/blogposts.html\"\r\n ordering = [\"-id\"]\r\n\r\n\r\nclass DetailedblogView(DetailView):\r\n model = Post\r\n template_name = \"accounts/blogposts/detailedblog.html\"\r\n\r\n\r\nclass AddPostView(CreateView):\r\n model = Post\r\n form_class = PostForm\r\n template_name = \"accounts/blogposts/addpost.html\"\r\n # fields = \"__all__\"\r\n\r\n def form_valid(self, form):\r\n form.instance.author = self.request.user\r\n return super().form_valid(form)\r\n\r\n\r\nclass UpdatePostView(UpdateView):\r\n model = Post\r\n template_name = \"accounts/blogposts/update_post.html\"\r\n fields = [\"title\", \"body\"]\r\n\r\n\r\nclass DeletePostView(DeleteView):\r\n model = Post\r\n template_name = \"accounts/blogposts/delete_post.html\"\r\n success_url = reverse_lazy(\"posts\")\r\n\r\n\r\ndef res_check(user):\r\n try:\r\n get_object_or_404(Restaurant, user=user)\r\n except:\r\n return False\r\n else:\r\n return True\r\n\r\n\r\ndef login_restuarant(request):\r\n if request.user.is_authenticated:\r\n return redirect(\"home\")\r\n else:\r\n if request.method == \"POST\":\r\n username = request.POST.get(\"username\")\r\n # TEST FROM HERE\r\n password = request.POST.get(\"password\")\r\n user = authenticate(request, username=username, password=password)\r\n\r\n if user is not None and res_check(user) is True:\r\n login(request, user)\r\n return redirect(\"home\")\r\n else:\r\n messages.info(request, \"Username or password is incorrect\")\r\n\r\n context = {}\r\n # TO HERE\r\n return render(request, \"accounts/restuarantlogin.html\", context)\r\n\r\n\r\ndef login_foodredistributor(request):\r\n if request.user.is_authenticated:\r\n return redirect(\"home2\")\r\n else:\r\n # TEST FROM HERE\r\n if request.method == \"POST\":\r\n username = request.POST.get(\"username\")\r\n password = request.POST.get(\"password\")\r\n\r\n user = authenticate(request, username=username, password=password)\r\n\r\n if user is not None and res_check(user) is False:\r\n login(request, user)\r\n return redirect(\"home2\")\r\n else:\r\n messages.info(request, \"Username or password is incorrect\")\r\n # TO HERE\r\n context = {}\r\n return render(request, \"accounts/foodredislogin.html\", context)\r\n\r\n\r\ndef logout_restuarant(request):\r\n logout(request)\r\n return redirect(\"login\")\r\n\r\n\r\ndef logout_foodredistributor(request):\r\n logout(request)\r\n return redirect(\"login2\")\r\n\r\n\r\n@login_required(login_url=\"login\")\r\ndef home(request):\r\n return render(request, \"accounts/dashboard.html\")\r\n\r\n\r\n@login_required(login_url=\"login2\")\r\ndef home2(request):\r\n return render(request, \"accounts/dashboard.html\")\r\n\r\n\r\n@login_required(login_url=\"profile\")\r\ndef profile(request):\r\n return render(request, \"accounts/profile-card.html\")\r\n\r\n\r\ndef landing(request):\r\n return render(request, \"accounts/landing_page.html\")\r\n\r\n\r\ndef choose_login(request):\r\n return render(request, \"accounts/chooselogin.html\")\r\n\r\n\r\ndef about(request):\r\n return render(request, \"accounts/about.html\")\r\n","sub_path":"food_redistribution/accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"307642395","text":"\"\"\"\nThis module implements a multi-layer perceptron.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nfrom tensorflow.contrib.layers import initializers\nfrom tensorflow.contrib.layers import regularizers\n\nimport utils\n\nclass HRED(object):\n \"\"\"\n This class implements a Multilayer Perceptron in Tensorflow.\n It handles the different layers and parameters of the model.\n Once initialized an MLP object can perform inference and evaluation.\n \"\"\"\n\n def __init__(self, vocab_size, q_dim, s_dim, o_dim, num_layers, num_samples=512, is_training=True):\n \"\"\"\n Constructor for an HRED object.\n Args:\n vocab_size: The size of the vocabulary\n q_dim: The size of the query embeddings\n s_dim: The size of the session embeddings\n o_dim: The size of the output\n \"\"\"\n self.vocab_size = vocab_size\n self.q_dim = q_dim\n self.s_dim = s_dim\n self.o_dim = o_dim\n self.num_layers = num_layers\n self.num_samples = num_samples\n self.is_training = is_training\n \n self.init = tf.random_normal_initializer(stddev=1e-3)\n self.reg = regularizers.l2_regularizer(1e-2)\n self.counter = 0\n\n def inference(self, query, target, sess_enc, click_hot):\n \"\"\"\n Given a session x, this method will encode each query in x. After that it\n will encode the session given the query states. Eventually a new query will\n be decoded and returned.\n Args:\n query: a tensor of shape [num_of_query_words, 1] representing the query we need to encode\n target: a tensor of shape [num_of_target_words, 1] representing the target we need to decode to\n sess_enc: a tensor of shape [s_dim, 1] representing the previous session encoding\n Returns:\n logits: a tensor of shape [num_of_target_words, q_dim] representing the decoded query\n \"\"\"\n with tf.variable_scope('HRED'): \n E = tf.get_variable('embedding', (self.vocab_size, self.q_dim), initializer=self.init, regularizer=self.reg)\n with tf.variable_scope('QueryEncoder'):\n # Create the GRU cell(s)\n single_cell = tf.nn.rnn_cell.GRUCell(self.q_dim)\n if self.num_layers > 1:\n cell = tf.nn.rnn_cell.MultiRNNCell([single_cell] * self.num_layers)\n else:\n cell = single_cell\n # Loop over all the queries to encode them\n word_embeddings = tf.nn.embedding_lookup(E, query)\n word_embeddings = tf.split(0, word_embeddings.get_shape()[0].value, word_embeddings)#unpack_sequence(word_embeddings)\n _, Q = tf.nn.rnn(cell, word_embeddings, dtype=tf.float32)\n Q = tf.concat(1, [Q, click_hot])\n with tf.variable_scope('SessionEncoder'):\n # Create the GRU cell(s)\n single_cell = tf.nn.rnn_cell.GRUCell(self.s_dim)\n if self.num_layers > 1:\n cell = tf.nn.rnn_cell.MultiRNNCell([single_cell] * self.num_layers)\n else:\n cell = single_cell\n # When we're not training we only want to predict the last query\n _, S = cell(Q, sess_enc)\n with tf.variable_scope('Decoder') as dec:\n # Create the GRU cell(s)\n single_cell = tf.nn.rnn_cell.GRUCell(self.q_dim)\n if self.num_layers > 1:\n cell = tf.nn.rnn_cell.MultiRNNCell([single_cell] * self.num_layers)\n else:\n cell = single_cell\n # Get/create the variables\n H0 = tf.get_variable('weights', (self.s_dim, self.q_dim), initializer=self.init, regularizer=self.reg)\n b0 = tf.get_variable('bias', (1, self.q_dim), initializer=tf.constant_initializer(0.0))\n Ho = tf.get_variable('omega_Hweights', (self.q_dim, self.o_dim), initializer=self.init, regularizer=self.reg)\n Eo = tf.get_variable('omega_Eweights', (self.q_dim, self.o_dim), initializer=self.init, regularizer=self.reg)\n bo = tf.get_variable('omega_bias', (1, self.o_dim), initializer=tf.constant_initializer(0.0))\n O = tf.get_variable('embedding', (self.o_dim, self.vocab_size), initializer=self.init, regularizer=self.reg)\n # According to the paper, this is how s is used to generate the query\n state = tf.tanh(tf.matmul(S, H0) + b0)\n word_embeddings = tf.nn.embedding_lookup(E, target)\n word_embeddings = tf.split(0, word_embeddings.get_shape()[0].value, word_embeddings)\n D = []\n for word in word_embeddings: \n D.append(state) \n _, state = cell(word, state) \n dec.reuse_variables()\n # We add a final linear layer to create the output \n D = pack_sequence(D)\n W = pack_sequence(word_embeddings)\n omega = tf.matmul(D, Ho) + tf.matmul(W, Eo) + bo\n \n logits = tf.matmul(omega, O)\n\n return logits, S\n\n def loss(self, logits, labels):\n \"\"\"\n Calculates the sofmax loss using sampling. \n Args:\n logits: A list of 2D float Tensor of size [num_words, self.vocab_size].\n labels: A list of 2D int Tensor of size [num_words, 1] containing the true words of the sequence\n Returns:\n loss: scalar float Tensor, full loss = cross_entropy + reg_loss\n \"\"\"\n ########################\n # PUT YOUR CODE HERE #\n #######################\n with tf.variable_scope('loss'):\n # Calculate the length of the query (e.g. the part that is not equal to the padding)\n query_len = tf.reduce_sum(tf.cast(tf.not_equal(labels, utils.PAD_ID), tf.int32))\n # Select only the parts that correspond to the actual query\n lbls = tf.one_hot(labels[:query_len], self.vocab_size, axis=-1)\n inpts = tf.cast(logits[:query_len], tf.float32)\n softmax_loss = tf.nn.softmax_cross_entropy_with_logits(inpts, lbls)\n softmax_loss = tf.reduce_mean(softmax_loss)\n tf.summary.scalar('softmax_loss', softmax_loss)\n # Add the weight regularization loss\n reg_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)\n reg_loss = tf.reduce_sum(reg_losses)\n tf.summary.scalar('regularization_loss', reg_loss)\n \n loss = tf.add(softmax_loss, reg_loss)\n tf.summary.scalar('total_loss', loss)\n ########################\n # END OF YOUR CODE #\n #######################\n\n return loss\n \n def accuracy(self, logits, labels):\n \"\"\"\n Calculate the prediction accuracy, i.e. the average correct predictions\n of the network.\n As in self.loss above, you can use tf.scalar_summary to save\n scalar summaries of accuracy for later use with the TensorBoard.\n\n Args:\n logits: 2D float Tensor of size [num_words, self.vocab_size].\n The predictions returned through self.inference.\n labels: 2D int Tensor of size [num_words, 1]\n with one-hot encoding. Ground truth labels for\n each observation in batch.\n\n Returns:\n accuracy: scalar float Tensor, the accuracy of predictions,\n i.e. the average correct predictions over the whole batch.\n \"\"\"\n ########################\n # PUT YOUR CODE HERE #\n ########################\n with tf.name_scope('accuracy'):\n # Create the predictions by applying softmax to the logits\n preds = tf.nn.softmax(logits)\n # Count how many predictions are correct\n correct_prediction = tf.cast(tf.equal(tf.cast(tf.argmax(preds,1), tf.int32), labels), tf.float32)\n # Calculate the length of the actual query (e.g. the number of words that are not equal to padding)\n query_len = tf.reduce_sum(tf.cast(tf.not_equal(labels, utils.PAD_ID), tf.int32))\n # Calculate the accuracy over the actual query\n accuracy = tf.reduce_sum(correct_prediction[:query_len])/tf.cast(query_len, tf.float32)\n tf.summary.scalar('accuracy', accuracy)\n ########################\n # END OF YOUR CODE #\n ########################\n\n return accuracy\n \ndef unpack_sequence(tensor):\n \"\"\"Split the single tensor of a sequence into a list of frames.\"\"\"\n try:\n tensor = tf.reshape(tensor, (tensor.get_shape()[0].value, tensor.get_shape()[2].value))\n except ValueError:\n print(tensor.get_shape())\n raise\n return tf.split(0, tensor.get_shape()[0].value, tensor)\n\ndef pack_sequence(sequence):\n \"\"\"Combine a list of the frames into a single tensor of the sequence.\"\"\"\n dim = sequence[0].get_shape()[1].value\n return tf.reshape(tf.pack(sequence), (len(sequence), dim))","sub_path":"RNNTensors/TFclick_model.py","file_name":"TFclick_model.py","file_ext":"py","file_size_in_byte":8680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"652528443","text":"#!/usr/bin/python3.6\n# -*- coding:utf-8 -*-\n# https://leetcode.com/problems/merge-k-sorted-lists/\n# Approach 1:Brute Force\n# Traverse all the linked lists and collect the values of the nodes into an array.\n# Sort and iterate over this array to get the proper value of nodes.\n# Create a new sorted linked list and extend it with the new nodes.\n# Approach 2, 3, 5: recursion, Compare one by one\n# Approach 4: iteration, Compare one by one\n# Approach 6: by from operator import attrgetter\n\n\n\n\n\n\n\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution:\n def mergeKLists1(self, lists):\n self.node = []\n for li in lists:\n while li:\n self.node += [li.val]\n li = li.next\n self.node.sort()\n head = cur = ListNode(0)\n for i in self.node:\n cur.next = ListNode(i)\n cur = cur.next\n return head.next\n\n def mergeKLists2(self, lists):\n def find_min(lists, head):\n while None in lists:\n lists.remove(None)\n if len(lists) == 0:\n return\n min_node = lists[0]\n min_val = min_node.val\n for node in lists:\n print(node.val)\n if min_val > node.val:\n min_val = node.val\n min_node = node\n idx = lists.index(min_node)\n lists[idx] = lists[idx].next\n head.next = min_node\n print(min_node.val)\n find_min(lists, head.next)\n return min_node\n\n head = ListNode(0)\n find_min(lists, head)\n return head.next\n\n def mergeKLists3(self, lists):\n def find_min(lists, head):\n while None in lists:\n lists.remove(None)\n if len(lists) == 0:\n return\n min_node = lists[0]\n min_val = min_node.val\n min_index = 0\n for i in range(len(lists)):\n cur_val = lists[i].val\n if min_val > cur_val:\n min_val = cur_val\n min_node = lists[i]\n min_index = i\n lists[min_index] = lists[min_index].next\n head.next = min_node\n find_min(lists, head.next)\n return min_node\n\n head = ListNode(0)\n find_min(lists, head)\n return head.next\n\n def mergeKLists4(self, lists):\n head = cur = ListNode(0)\n while lists:\n while None in lists:\n lists.remove(None)\n if len(lists) == 0:\n return head.next\n min_node = lists[0]\n min_index = 0\n for i in range(len(lists)):\n if min_node.val > lists[i].val:\n min_node = lists[i]\n min_index = i\n cur.next = min_node\n lists[min_index] = lists[min_index].next\n cur = cur.next\n return head.next\n\n def mergeKLists5(self, lists):\n def find_min(lists):\n while None in lists:\n lists.remove(None)\n if len(lists)==0:\n return None\n min_node = lists[0]\n min_index = 0\n for i in range(len(lists)):\n if min_node.val > lists[i].val:\n min_node = lists[i]\n min_index = i\n lists[min_index] = lists[min_index].next\n min_node.next = find_min(lists)\n return min_node\n return find_min(lists)\n\n def mergeKLists6(self, lists):\n from operator import attrgetter\n sorted_list = []\n for head in lists:\n curr = head\n while curr is not None:\n sorted_list.append(curr)\n curr = curr.next\n\n sorted_list = sorted(sorted_list, key=attrgetter('val'))\n for i, node in enumerate(sorted_list):\n try:\n node.next = sorted_list[i + 1]\n except Exception:\n node.next = None\n\n if sorted_list:\n return sorted_list[0]\n else:\n return None\n\n # def mergeKLists7(self, lists):\n\n\n\ndef ListToListNode(li):\n res = tmp = ListNode(0)\n for i in li:\n tmp.next = ListNode(i)\n tmp = tmp.next\n return res.next\n\n\ndef ListNodeToList(L):\n tmp = []\n while L:\n tmp += [L.val]\n L = L.next\n return tmp\n\n\ndef main():\n l1 = [[1, 4, 5], [1, 3, 4], [2, 6]]\n l1 = [ListToListNode(i) for i in l1]\n l2 = [[], []]\n l2 = [ListToListNode(i) for i in l2]\n s = Solution()\n res = s.mergeKLists6(l1)\n res = ListNodeToList(res)\n print(res)\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"linked_list/23. Merge k Sorted Lists.py","file_name":"23. Merge k Sorted Lists.py","file_ext":"py","file_size_in_byte":4770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"438773520","text":"from tkinter import *\r\nfrom tkinter import font\r\nfrom tkinter.messagebox import *\r\nimport random\r\n\r\ndef judge():\r\n num1=input1.get()\r\n num2=input2.get()\r\n if num1.isdigit() and num2.isdigit() and num1<=num2:\r\n var.set(random.randint(int(num1),int(num2)))\r\n elif num1>num2:\r\n showinfo('Info','ValueError: empty range for randrange()')\r\n else:\r\n showinfo('Info','SyntaxError: invalid character')\r\n\r\nroot=Tk()\r\nroot.title('输出随机整数 V1.1')\r\nroot.geometry('540x540')\r\n\r\nLabel(root,text='起始数:',font=('NSimSun',15)).place(relx=0.1,rely=-0.32,relheight=0.9,relwidth=0.15)\r\ninput1=Entry(root,font=('NSimSun',15))\r\ninput1.place(relx=0.225,rely=0.1, relheight=0.05,relwidth=0.1)\r\n\r\nLabel(root,text='结束数:',font=('NSimSun',15)).place(relx=0.6,rely=-0.32,relheight=0.9,relwidth=0.15)\r\ninput2=Entry(root,font=('NSimSun',15))\r\ninput2.place(relx=0.725,rely=0.1, relheight=0.05,relwidth=0.1)\r\n\r\nvar=StringVar()\r\nEntry(root,textvariable=var,font=('NSimSun',30)).place(relx=0.4,rely=0.4,relheight=0.2,relwidth=0.2)\r\nButton(root,text='输出',font=('NSimSun',15),command=judge).place(relx=0.4,rely=0.6,relheight=0.1,relwidth=0.2)\r\n\r\nroot.mainloop()","sub_path":"输出随机整数_V1.1.py","file_name":"输出随机整数_V1.1.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"559572439","text":"from machine import Pin, I2C\nfrom ssd1306 import SSD1306_I2C\nfrom utime import sleep\n\na = [(0,0),(0,1),(1,2),(2,3),(3,3)]\nb = [(0,0),(1,0),(2,1),(3,2),(3,3)]\nc = [(3,0),(3,1),(2,2),(1,3),(0,3)]\nd = [(3,0),(2,0),(1,1),(0,2),(0,3)]\n\nlefts = [(a,0),(c,0),(d,1),(b,1)] # Snake going left, head is on left\nrights = [(c,3),(a,3),(b,2),(d,2)] # Snake going right, head is on right\nups = [(c,1),(b,1),(a,2),(d,2)] # Snake going up, head is on top\ndowns=[(d,3),(a,3),(b,0),(c,0)] # Snake going down, head is on bottom\n\nsnake = []\n\nt=.05\n\ndef plot(c,r,a,isDraw):\n for p in a:\n oled.pixel(c*3+p[0],63-r*3-p[1],1 if isDraw else 0)\n\ndef draw(c,r,a):\n plot(c,r,a,True)\n\ndef erase(c,r,a):\n plot(c,r,a,False)\n\ndef drawe(x,y,e):\n if e[1]==0: draw(x,y,e[0])\n if e[1]==1: draw(x,y-1,e[0])\n if e[1]==2: draw(x-1,y-1,e[0])\n if e[1]==3: draw(x-1,y,e[0])\n\ndef erasee(x,y,e):\n if e[1]==0: erase(x,y,e[0])\n if e[1]==1: erase(x,y-1,e[0])\n if e[1]==2: erase(x-1,y-1,e[0])\n if e[1]==3: erase(x-1,y,e[0])\n\ndef left_to_right(y):\n x=0\n for r in range(6):\n for e in lefts:\n drawe(x,y,e)\n oled.show()\n sleep(t)\n x += 1\n\ndef right_to_left(y):\n x=int(127/3)\n for r in range(6):\n for e in rights:\n drawe(x,y,e)\n oled.show()\n sleep(t)\n x -= 1\n\ndef go_up(x):\n y=int(64/3)\n for r in range(6):\n for e in ups:\n drawe(x,y,e)\n oled.show()\n sleep(t)\n y -= 1\n\ndef go_down(x):\n y=0\n for r in range(6):\n for e in downs:\n drawe(x,y,e)\n oled.show()\n sleep(t)\n y += 1\n\ndef next_right(old_head):\n for e in rights:\n if e[0]==old_head[0]:\n print(\"wow\")\n return old_head\n \ndef move_snake(dx,dy):\n # at any rate, remove tail\n print(len(snake))\n tail = snake[-1]\n erasee(tail[0],tail[1],tail[2])\n snake.pop() \n if dx==1:\n old_head = snake[0]\n new_head = next_right(old_head)\n snake.insert(0,new_head)\n \ndef main():\n sleep(0.5)\n i2c=I2C(1,sda=Pin(2), scl=Pin(3), freq=400000)\n global oled\n oled = SSD1306_I2C(128, 64, i2c)\n\n oled.fill(0)\n# go_up(1)\n# go_down(3)\n# left_to_right(1)\n# right_to_left(3)\n\n x=int(128/3/2)\n y=int(64/3/2)\n global snake\n snake = [ (x,y,rights[0]), (x-1,y,rights[1]), (x-2,y,rights[2]), (x-3,y,rights[3])]\n \n for r in range(2):\n for sn in snake:\n drawe(sn[0],sn[1],sn[2])\n oled.show()\n sleep(1)\n move_snake(1,0)\n oled.show()\n\n sleep(t)\n\n#main()\n \n","sub_path":"sn3.py","file_name":"sn3.py","file_ext":"py","file_size_in_byte":2657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"530682908","text":"# -*- coding: utf-8 -*-\n\n# Copyright 2019 Giacomo Ferretti\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport json\nimport os\n\nimport requests\nfrom mcdapi import endpoints\n\n__proxy_enabled__ = True\n__proxy_url__ = 'socks5://127.0.0.1:9050'\n__image_folder__ = 'images'\n__offers_file__ = 'offers_parsed.json'\n\n\ndef main():\n if not os.path.isdir(__image_folder__):\n os.mkdir(__image_folder__)\n\n session = requests.session()\n\n if __proxy_enabled__:\n session.proxies = {\n 'http': __proxy_url__,\n 'https': __proxy_url__\n }\n\n # Load offers\n with open(__offers_file__) as f:\n offers = json.loads(f.read())\n\n for x in offers:\n print('Getting offer {}...'.format(x))\n params = endpoints.PROMO_IMAGE['params']\n params['path'] = offers[x]['promoImagePath']\n params['imageFormat'] = 'png'\n r = session.request(endpoints.PROMO_IMAGE['method'], endpoints.PROMO_IMAGE['url'].format(size=1080),\n params=params)\n\n if r.status_code == 200:\n with open(os.path.join(__image_folder__, offers[x]['promoImagePath']), 'wb') as f:\n f.write(r.content)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"image_downloader.py","file_name":"image_downloader.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"107481533","text":"\n\n#calss header\nclass _SCOUNDREL():\n\tdef __init__(self,): \n\t\tself.name = \"SCOUNDREL\"\n\t\tself.definitions = [u'a person, especially a man, who treats other people very badly and has no moral principles: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_scoundrel.py","file_name":"_scoundrel.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"72113421","text":"from django.urls import path, include\nfrom . import views\n\napp_name = 'page'\nurlpatterns = [\n path('index/', views.index_view, name='index_view'),\n path('page_list/', views.page_list, name='get_page_list'),\n path('edit/', views.edit_page, name='edit_page'),\n path('add/', views.add_page, name='add_page'),\n path('del/', views.del_page, name='del_page'),\n path('page_tree/', views.page_tree, name='page_tree')\n]\n","sub_path":"page/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"581244849","text":"#CS231\n#Assignment 4\n\n#Write a program to lazily rewrap text from the filename passed \n#so that it fits an 80 column window without breaking any words. \n#Use a generator that yields the next lines of text, each containing \n#as many words as possible \n\nimport re\nimport sys\n\ndef wrap(s): #use regex and .join to wrap the text within 80 characters without breaking words\n linewrap = \"\\n\".join(line.strip() for line in re.findall(r'.{1,80}(?:\\s+|$)', s))\n yield linewrap\n\nf = open(sys.argv[1], 'r')\n\nfor line in f:\n result = wrap(line)\n print(next(result))\n\nf.close()\n","sub_path":"homework/homework4/peer_review_hw4/9d.py","file_name":"9d.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"586813252","text":"from __future__ import division, unicode_literals\n\nimport collections\nimport math\n\nimport time\n\nfrom magpie.misc.stemmer import stem\nfrom magpie.utils import get_documents\n\n\ndef build_global_frequency_index(trainset_dir, verbose=True):\n \"\"\"\n Build the GlobalFrequencyIndex object from the files in a given directory\n :param trainset_dir: path to the directory with files for training\n :return: GlobalFrequencyIndex object\n \"\"\"\n tick = time.clock()\n\n global_index = GlobalFrequencyIndex()\n for doc in get_documents(trainset_dir):\n global_index.add_document(doc)\n\n if verbose:\n print(\"Global index built in : {0:.2f}s\".format(time.clock() - tick))\n\n return global_index\n\n\nclass GlobalFrequencyIndex(object):\n \"\"\"\n Holds the word count (bag of words) for the whole corpus.\n Enables to calculate IDF and word occurrences.\n \"\"\"\n def __init__(self, docs=None):\n self.index = collections.defaultdict(set)\n self.total_docs = 0\n documents = docs or []\n for doc in documents:\n self.add_document(doc)\n self.total_docs += 1\n\n def add_document(self, doc):\n \"\"\"\n Add the contents of a document to the index\n :param doc: Document object\n \"\"\"\n for w in doc.get_meaningful_words():\n self.index[stem(w)].add(doc.doc_id)\n self.total_docs += 1\n\n def get_phrase_idf(self, phrase):\n \"\"\"\n Compute idf values for a list of words\n :param phrase: list of unicodes\n :return: list of floats: idfs\n \"\"\"\n return [self.get_word_idf(w) for w in phrase]\n\n def get_word_idf(self, word):\n \"\"\"\n Compute idf for a given word\n :param word: unicode\n :return: float: idf value\n \"\"\"\n return math.log(self.total_docs / (1 + len(self.index[word])))\n","sub_path":"magpie/linear_classifier/base/global_index.py","file_name":"global_index.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"249830996","text":"# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport datetime\nimport multiprocessing\nimport random\nimport time\nimport threading\nimport smtplib\n\nimport flask\nfrom jinja2 import Environment, FileSystemLoader\nfrom flask import render_template\nfrom mlm.app.config import TEMPLATE_DIR, EMAIL_TEMPLATE, EMAIL_FROM, SMTP_URL\n\n\nclass Flask(object):\n def __init__(self, api, port, name):\n self.api = api\n self.port = port\n self.name = name\n self._cache = {}\n\n def _make_table(self, data, headers, formaters=None):\n table = [\"<div class='table'>\"]\n\n def get_cls_for_cell(i, n):\n \"\"\"\n :param i: index of column\n :param n: number of columns\n \"\"\"\n if i == 0:\n return \"left_cell\"\n elif i == n:\n return \"right_cell\"\n return \"cell\"\n\n # Make header\n for i in range(len(headers)):\n cls = \"header_cell %s\" % get_cls_for_cell(i, len(headers)-1)\n table.append(\"<div class='%s'>%s</div>\" % (cls, headers[i]))\n\n for row in data:\n for i in range(len(headers)):\n key = headers[i]\n cls = get_cls_for_cell(i, len(headers)-1)\n key = key.lower()\n if key in formaters:\n value = formaters[key](row)\n else:\n value = getattr(row, key)\n table.append(\"<div class='%s'>%s</div>\" % (cls, value))\n table.append(\"</div><br/>\")\n return \"\\n\".join(table)\n\n def last_election(self):\n return \"%s\" % str(self.api.get_last_election())[1:-1]\n\n def index(self):\n election = self.api.get_last_election()\n if election:\n if election in self._cache:\n return self._cache[election]\n else:\n scores = self._make_table(\n sorted(self.api.get_members(only_active=True),\n key=lambda o: o.leader_score,\n reverse=True),\n headers=[\"Name\", \"Score\"],\n formaters={\"score\": lambda o: o.leader_score})\n\n elections = self.api.get_all_elections()\n elections.reverse()\n history = self._make_table(\n elections,\n headers=[\"Date\", \"Time\", \"Weekday\", \"Leader\"],\n formaters={\"leader\": lambda o: o.lucky_man.name,\n \"date\": lambda o: o.datetime.strftime(\n \"%y.%m.%d\"),\n \"time\":\n lambda o: \"%s UTC\" %\n o.datetime.strftime(\"%H:%M\")})\n\n return render_template(\"index.html\",\n title=self.name,\n date=election.date,\n name=election.lucky_man.name,\n scores=scores,\n history=history)\n else:\n return render_template(\"default.html\")\n\n def __call__(self):\n \"\"\"process worker\"\"\"\n f = flask.Flask(__name__,\n template_folder='templates',\n static_folder='static')\n\n f.add_url_rule(\"/last_election\", None, self.last_election)\n f.add_url_rule(\"/\", None, self.index)\n\n f.run(host='0.0.0.0', port=self.port, threaded=True)\n\n\nclass Tasks(object):\n def __init__(self, api, should_stop):\n self.api = api\n self.should_stop = should_stop\n\n def _render_html(self, template_dir, file_name, **kwargs):\n j2_env = Environment(loader=FileSystemLoader(template_dir),\n trim_blocks=True)\n\n return j2_env.get_template(file_name).render(**kwargs)\n\n def send_email_notification(self, lucky_man, date):\n \"\"\"Sends email notification to lucky man by email.\n\n :param lucky_man: mlm.app.db_models.Member object of current leader\n :param date: date of meeting\n \"\"\"\n email_message = self._render_html(TEMPLATE_DIR, EMAIL_TEMPLATE,\n username=lucky_man.name,\n date=date)\n try:\n server = smtplib.SMTP(SMTP_URL)\n server.sendmail(EMAIL_FROM, lucky_man.email, email_message)\n print(\"Successfully sent email\")\n except smtplib.SMTPException:\n print(\"Error: unable to send email\")\n\n def process_elections(self):\n while not self.should_stop.isSet():\n meeting, date = self.api.get_next_meeting()\n\n elections = self.api.get_all_elections()\n\n election = [e for e in elections\n if e.datetime == date and e.meeting.id == meeting.id]\n\n print(\"Meeting: %s\" % meeting)\n print(\"Date %s\" % date)\n\n if not election:\n members = self.api.get_members(only_active=True)\n\n if elections:\n # we should elect one person two times in a row\n previous_leader = elections[-1].lucky_man\n members = [m for m in members if m != previous_leader]\n\n choices = []\n for m in members:\n weight = len(members) - m.leader_score % len(members)\n # lets increase the difference between weights\n weight *= 10\n choices.append((m, weight))\n\n total = sum(w for c, w in choices)\n r = random.uniform(0, total)\n upto = 0\n lucky_man = None\n for c, w in choices:\n if upto + w >= r:\n lucky_man = c\n break\n upto += w\n print(\"New leader: %s\" % lucky_man)\n t = threading.Thread(target=self.send_email_notification,\n args=(lucky_man, date))\n t.start()\n self.api.save_election(meeting, date, lucky_man)\n else:\n\n # sleep until next meeting starts or should_stop event isSet.\n while (datetime.datetime.utcnow() <\n (date + datetime.timedelta(minutes=5)) and\n not self.should_stop.isSet()):\n time.sleep(1)\n\n def __call__(self):\n \"\"\"worker process\"\"\"\n # TODO: add notification thread\n elections_t = threading.Thread(target=self.process_elections)\n elections_t.start()\n elections_t.join()\n\n\ndef start(api, port, name):\n should_stop = threading.Event()\n tasks_p = multiprocessing.Process(name=\"tasks\", target=Tasks(api,\n should_stop))\n flask_p = multiprocessing.Process(name=\"flask\",\n target=Flask(api, port, name))\n\n tasks_p.start()\n flask_p.start()\n while True:\n try:\n time.sleep(0.5)\n except KeyboardInterrupt:\n should_stop.set()\n\n\nif __name__ == '__main__':\n pass\n","sub_path":"mlm/app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"507625122","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 ('userprofile', '0003_remove_userprofile_stuff'),\n ('kitbuilder_v1', '0002_remove_sample_duration'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Follower',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('date_followed', models.DateField(auto_now_add=True)),\n ('template', models.ForeignKey(to='kitbuilder_v1.KitBuilderTemplate')),\n ('user', models.ForeignKey(to='userprofile.UserProfile')),\n ],\n ),\n migrations.AddField(\n model_name='kitbuildertemplate',\n name='followers',\n field=models.ManyToManyField(related_name='templates_followed', through='kitbuilder_v1.Follower', to='userprofile.UserProfile', blank=True),\n ),\n ]\n","sub_path":"kitbuilder/kitbuilder_v1/migrations/0003_auto_20150516_0601.py","file_name":"0003_auto_20150516_0601.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"460850050","text":"\"\"\"In this module we test the `Markdown` functionality of `awesome_panel.express`\n\nThe `Markdown` functionality of Panel is limited as it does not support\n\n- One liners for using Markdown from files\n- Code blocks\n- Indented Markdown text as is often what is used in Editors like VS Code.\n\nPlease note you need to run `Code.extend()` in order to add the CODE_HILITE CSS to the app.\n\"\"\"\nimport pathlib\n\nimport panel as pn\n\nimport awesome_panel.express as pnx\nfrom awesome_panel.express.testing import TestApp\n\nTEST_MD_FILE = pathlib.Path(__file__).parent / \"data\" / \"test.md\"\n\npnx.Code.extend()\n\n\ndef test_markdown():\n \"\"\"We test that\n\n - A \"Header is shown\"\n - The background is blue\n - The sizing_mode is \"stretch_width\" by default. DOES NOT WORK CURRENTLY\n \"\"\"\n return TestApp(\n test_markdown,\n pnx.Markdown(\"# Header\", name=\"basic\", background=\"lightblue\"),\n sizing_mode=\"stretch_width\",\n background=\"lightgray\",\n max_width=600,\n )\n\n\ndef test_markdown_from_file():\n \"\"\"We test that\n\n - A path to a markdown file can used directly in one line\n \"\"\"\n return TestApp(\n test_markdown_from_file,\n pnx.Markdown(path=TEST_MD_FILE, name=\"file\", background=\"lightblue\"),\n )\n\n\ndef test_markdown_indendation():\n \"\"\"We test the Markdown pane\n\n - can handle leading spaces, i.e. this line shows as a bullited list and not in mono-space\n\"\"\"\n return TestApp(test_markdown_indendation, sizing_mode=\"stretch_width\",)\n\n\ndef test_markdown_code_block():\n \"\"\"We test that\n\n - A code blocks are supported. Sort of. BUT THE INDENTATION IS CURRENTLY LOST!\n - Indented markdown test from editors is supported. The Panel Markdown does not support this.\n \"\"\"\n code_block = \"\"\"\nThis is not indented\n\n```python\nprint(\"Hello Awesome Panel World\")\nreturn TestApp(\n test_markdown_code_block,\n pnx.Markdown(code_block, name=\"code block\", background=\"lightblue\"),\n```\n\n This is indented```\n \"\"\"\n\n return TestApp(\n test_markdown_code_block,\n pnx.Markdown(code_block, name=\"code block\", background=\"lightblue\"),\n )\n\n\ndef view() -> pn.Column:\n \"\"\"Wraps all tests in a Column that can be included in the Gallery or served independently\n\n Returns:\n pn.Column -- An Column containing all the tests\n \"\"\"\n return pn.Column(\n pnx.Markdown(__doc__),\n test_markdown,\n test_markdown_from_file,\n test_markdown_indendation,\n test_markdown_code_block,\n )\n\n\nif __name__.startswith(\"bk\"):\n view().servable(\"test_markdown\")\n","sub_path":"src/pages/gallery/awesome_panel_express_tests/test_markdown.py","file_name":"test_markdown.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"309827463","text":"def rgb(r, g, b):\n #your code here :)\n \n #check r \n _r = ''\n if r == 0:\n _r =\"00\"\n else:\n _r = getHex(r)\n #check g \n _g = ''\n if r == 0:\n _g =\"00\"\n else:\n _g = getHex(g)\n\n #check b\n _b = ''\n if b == 0:\n _b =\"00\"\n else:\n _b = getHex(b)\n \n return _r + _g + _b\n\ndef getHex(num):\n\n if num < 0 :\n return \"00\"\n \n if num > 255:\n return \"FF\"\n\n real_hex = hex(num)\n _hex = real_hex.split(\"x\")[1]\n\n if len(_hex) == 1 :\n _hex = \"0\" + _hex\n\n return _hex.upper()\n\nprint(rgb(255, 275, 234))\n\n'''\n \n'''","sub_path":"python solutions/rgbtohex.py","file_name":"rgbtohex.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"165512639","text":"import unittest\nimport rck.semver\n\nclass TestSemver(unittest.TestCase):\n\n version_valid_major = '1'\n version_valid_minor = '1'\n version_valid_patch = '1'\n valid_version = '{0}.{1}.{2}'.format(version_valid_major, version_valid_minor, version_valid_patch)\n\n invalid_version = '1a.a2.*'\n\n spec_valid_major_1 = '1'\n spec_valid_minor_1 = '*'\n spec_valid_patch_1 = '*'\n valid_spec_1 = '{0}.{1}.{2}'.format(spec_valid_major_1, spec_valid_minor_1, spec_valid_patch_1)\n valid_spec_2 = '*'\n\n invalid_spec_1 = '1a.3.1d'\n invalid_spec_2 = '1.2'\n invalid_spec_3 = 'invalid'\n\n valid_matching_version_1 = '1.1.1'\n valid_matching_spec_1 = '1.*.*'\n\n valid_unmatching_version_1 = '1.0.0'\n valid_unmatching_spec_1 = '2.0.*'\n valid_unmatching_version_2 = '2.0.0'\n valid_unmatching_spec_2 = '2.1.*'\n valid_unmatching_version_3 = '2.0.1'\n valid_unmatching_spec_3 = '2.0.0'\n\n def setUp(self):\n pass\n\n def tearDown(self):\n pass\n\n def test_ValidSemverVersion_Parsing_CorrectlyHydrate(self):\n version = rck.semver.Version(self.valid_version)\n self.assertEquals(str(version), self.valid_version)\n self.assertEquals(version.major, self.version_valid_major)\n self.assertEquals(version.minor, self.version_valid_minor)\n self.assertEquals(version.patch, self.version_valid_patch)\n\n def test_InvalidSemverVersion_Parsing_RaiseValueError(self):\n with self.assertRaises(ValueError):\n rck.semver.Version(self.invalid_version)\n\n def test_ValidSpec_Parsing_CorrectlyHydrate(self):\n spec = rck.semver.Spec(self.valid_spec_1)\n self.assertEquals(str(spec), self.valid_spec_1)\n self.assertEquals(spec.major, self.spec_valid_major_1)\n self.assertEquals(spec.minor, self.spec_valid_minor_1)\n self.assertEquals(spec.patch, self.spec_valid_patch_1)\n\n def test_ValidSpecConsistingOfOneStar_Parsing_CorrectlyHydrate(self):\n spec = rck.semver.Spec(self.valid_spec_2)\n self.assertEquals(str(spec), '*.*.*')\n self.assertEquals(spec.major, '*')\n self.assertEquals(spec.minor, '*')\n self.assertEquals(spec.patch, '*')\n\n def test_InvalidSpec_Parsing_RaiseValueError(self):\n with self.assertRaises(ValueError):\n rck.semver.Version(self.invalid_spec_1)\n rck.semver.Version(self.invalid_spec_2)\n rck.semver.Version(self.invalid_spec_3)\n\n def test_ValidSpecAndValidSpecVersion_SpecMatch_VersionIsMatching(self):\n spec = rck.semver.Spec(self.valid_matching_spec_1)\n version = rck.semver.Version(self.valid_matching_version_1)\n self.assertTrue(spec.match(version))\n\n def test_ValidSpecAndValidSpecVersion_SpecMatchOnMajorNumber_VersionIsNotMatching(self):\n spec = rck.semver.Spec(self.valid_unmatching_spec_1)\n version = rck.semver.Version(self.valid_unmatching_version_1)\n self.assertFalse(spec.match(version))\n\n def test_ValidSpecAndValidSpecVersion_SpecMatchOnMinorNumber_VersionIsNotMatching(self):\n spec = rck.semver.Spec(self.valid_unmatching_spec_2)\n version = rck.semver.Version(self.valid_unmatching_version_2)\n self.assertFalse(spec.match(version))\n\n def test_ValidSpecAndValidSpecVersion_SpecMatchOnPatchNumber_VersionIsNotMatching(self):\n spec = rck.semver.Spec(self.valid_unmatching_spec_3)\n version = rck.semver.Version(self.valid_unmatching_version_3)\n self.assertFalse(spec.match(version))\n","sub_path":"tests/test_semver.py","file_name":"test_semver.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"341893051","text":"\"\"\"A video player class.\"\"\"\nimport random\n\nfrom .video_library import VideoLibrary\nfrom .video_playlist import Playlist\n\n\nclass VideoPlayer:\n \"\"\"A class used to represent a Video Player.\"\"\"\n\n def __init__(self):\n self._video_library = VideoLibrary()\n self._current_video = \"None\"\n self._video_paused = False\n self._playlists = {}\n\n def number_of_videos(self):\n num_videos = len(self._video_library.get_all_videos())\n print(f\"{num_videos} videos in the library\")\n\n def show_all_videos(self):\n \"\"\"Returns all videos.\"\"\"\n sorted_videos = sorted(self._video_library.get_all_videos(), key=lambda video: video.title)\n\n print(\"Here's a list of all available videos:\")\n for video in sorted_videos:\n print(self.display_video(video))\n\n def display_video(self, video):\n return f\"{video.title} ({video.video_id}) [{' '.join(video.tags)}]\"\n\n def play_video(self, video_id):\n \"\"\"Plays the respective video.\n\n Args:\n video_id: The video_id to be played.\n \"\"\"\n video_to_play = self._video_library.get_video(video_id)\n if self._current_video != \"None\" and video_to_play is not None:\n self.stop_video()\n\n if video_to_play is not None:\n print(f\"Playing video: {video_to_play.title}\")\n self._current_video = video_to_play\n else:\n print(\"Cannot play video: Video does not exist\")\n\n def stop_video(self):\n \"\"\"Stops the current video.\"\"\"\n if self._current_video != \"None\":\n print(f\"Stopping video: {self._current_video.title}\")\n self._current_video = \"None\"\n self._video_paused = False\n else:\n print(\"Cannot stop video: No video is currently playing\")\n\n def play_random_video(self):\n \"\"\"Plays a random video from the video library.\"\"\"\n\n all_ids = [video.video_id for video in self._video_library.get_all_videos()]\n if all_ids is not None:\n random_id = random.choice(all_ids)\n self.play_video(random_id)\n else:\n print(\"No videos available\")\n\n def pause_video(self):\n \"\"\"Pauses the current video.\"\"\"\n\n if not self._video_paused and self._current_video != \"None\":\n print(f\"Pausing video: {self._current_video.title}\")\n self._video_paused = True\n elif self._current_video == \"None\":\n print(\"Cannot pause video: No video is currently playing\")\n elif self._video_paused:\n print(f\"Video already paused: {self._current_video.title}\")\n\n def continue_video(self):\n \"\"\"Resumes playing the current video.\"\"\"\n\n if self._video_paused and self._current_video != \"None\":\n print(f\"Continuing video: {self._current_video.title}\")\n self._video_paused = False\n elif self._current_video == \"None\":\n print(\"Cannot continue video: No video is currently playing\")\n elif not self._video_paused:\n print(\"Cannot continue video: Video is not paused\")\n\n def show_playing(self):\n \"\"\"Displays video currently playing.\"\"\"\n if self._current_video != \"None\":\n print(f\"Currently playing: {self.display_video(self._current_video)}\", end='')\n print(\" - PAUSED\" if self._video_paused else \"\")\n else:\n print(\"No video is currently playing\")\n\n def create_playlist(self, playlist_name):\n \"\"\"Creates a playlist with a given name.\n\n Args:\n playlist_name: The playlist name.\n \"\"\"\n\n if playlist_name.lower() not in self._playlists:\n new_playlist = Playlist(playlist_name)\n self._playlists[playlist_name.lower()] = new_playlist\n print(f\"Successfully created new playlist: {playlist_name}\")\n else:\n print(\"Cannot create playlist: A playlist with the same name already exists\")\n\n def add_to_playlist(self, playlist_name, video_id):\n \"\"\"Adds a video to a playlist with a given name.\n\n Args:\n playlist_name: The playlist name.\n video_id: The video_id to be added.\n \"\"\"\n if playlist_name.lower() in self._playlists:\n video_to_add = self._video_library.get_video(video_id)\n playlist_to_add = self._playlists[playlist_name.lower()]\n if video_to_add is not None:\n if not playlist_to_add.video_exists(video_to_add):\n playlist_to_add.add_video(video_to_add)\n print(f\"Added video to {playlist_name}: {video_to_add.title}\")\n else:\n print(f\"Cannot add video to {playlist_name}: Video already added\")\n else:\n print(f\"Cannot add video to {playlist_name}: Video does not exist\")\n else:\n print(f\"Cannot add video to {playlist_name}: Playlist does not exist\")\n\n def show_all_playlists(self):\n \"\"\"Display all playlists.\"\"\"\n\n if self._playlists:\n sorted_playlists = sorted(self._playlists.values(), key=lambda playlist: playlist.initial_name)\n\n print(\"Showing all playlists:\")\n for playlist in sorted_playlists:\n print(playlist.initial_name)\n else:\n print(\"No playlists exist yet\")\n\n def show_playlist(self, playlist_name):\n \"\"\"Display all videos in a playlist with a given name.\n\n Args:\n playlist_name: The playlist name.\n \"\"\"\n\n if playlist_name.lower() in self._playlists:\n print(f\"Showing playlist: {playlist_name}\")\n playlist = self._playlists[playlist_name.lower()]\n playlist_videos = playlist.get_all_videos()\n if playlist_videos:\n for video in playlist_videos:\n print(self.display_video(video))\n else:\n print(\"No videos here yet\")\n else:\n print(f\"Cannot show playlist {playlist_name}: Playlist does not exist\")\n\n def remove_from_playlist(self, playlist_name, video_id):\n \"\"\"Removes a video to a playlist with a given name.\n\n Args:\n playlist_name: The playlist name.\n video_id: The video_id to be removed.\n \"\"\"\n if playlist_name.lower() in self._playlists:\n video_to_remove = self._video_library.get_video(video_id)\n playlist_to_remove = self._playlists[playlist_name.lower()]\n if video_to_remove is not None:\n\n if playlist_to_remove.video_exists(video_to_remove):\n playlist_to_remove.remove_video(video_id)\n print(f\"Removed video from {playlist_name}: {video_to_remove.title}\")\n else:\n print(f\"Cannot remove video from {playlist_name}: Video is not in playlist\")\n else:\n print(f\"Cannot remove video from {playlist_name}: Video does not exist\")\n else:\n print(f\"Cannot remove video from {playlist_name}: Playlist does not exist\")\n\n def clear_playlist(self, playlist_name):\n \"\"\"Removes all videos from a playlist with a given name.\n\n Args:\n playlist_name: The playlist name.\n \"\"\"\n if playlist_name.lower() in self._playlists:\n playlist = self._playlists[playlist_name.lower()]\n playlist.clear()\n print(f\"Successfully removed all videos from {playlist_name}\")\n else:\n print(f\"Cannot clear playlist {playlist_name}: Playlist does not exist\")\n\n def delete_playlist(self, playlist_name):\n \"\"\"Deletes a playlist with a given name.\n\n Args:\n playlist_name: The playlist name.\n \"\"\"\n if playlist_name.lower() in self._playlists:\n self._playlists.pop(playlist_name.lower())\n print(f\"Deleted playlist: {playlist_name}\")\n else:\n print(f\"Cannot delete playlist {playlist_name}: Playlist does not exist\")\n\n def search_videos(self, search_term):\n \"\"\"Display all the videos whose titles contain the search_term.\n\n Args:\n search_term: The query to be used in search.\n \"\"\"\n matched_videos = [video for video in self._video_library.get_all_videos() if\n search_term.lower() in video.title.lower()]\n matched_videos.sort(key=lambda video: video.title)\n\n if matched_videos:\n print(f\"Here are the results for {search_term}:\")\n for i in range(len(matched_videos)):\n print(f\"{i + 1}) {self.display_video(matched_videos[i])}\")\n print(\"Would you like to play any of the above? If yes, specify the number of the video.\\n\"\n \"If your answer is not a valid number, we will assume it's a no.\")\n video_option = input()\n\n if video_option.isdigit() and 1 <= int(video_option) <= len(matched_videos):\n self.play_video(matched_videos[int(video_option) - 1].video_id)\n else:\n print(f\"No search results for {search_term}\")\n\n def search_videos_tag(self, video_tag):\n \"\"\"Display all videos whose tags contains the provided tag.\n\n Args:\n video_tag: The video tag to be used in search.\n \"\"\"\n\n matched_videos = [video for video in self._video_library.get_all_videos()\n if '#' in video_tag\n and video_tag.lower() in [tag.lower() for tag in video.tags]]\n matched_videos.sort(key=lambda video: video.title)\n\n if matched_videos:\n print(f\"Here are the results for {video_tag}:\")\n for i in range(len(matched_videos)):\n print(f\"{i + 1}) {self.display_video(matched_videos[i])}\")\n print(\"Would you like to play any of the above? If yes, specify the number of the video.\\n\"\n \"If your answer is not a valid number, we will assume it's a no.\")\n video_option = input()\n\n if video_option.isdigit() and 1 <= int(video_option) <= len(matched_videos):\n self.play_video(matched_videos[int(video_option) - 1].video_id)\n else:\n print(f\"No search results for {video_tag}\")\n\n def flag_video(self, video_id, flag_reason=\"\"):\n \"\"\"Mark a video as flagged.\n\n Args:\n video_id: The video_id to be flagged.\n flag_reason: Reason for flagging the video.\n \"\"\"\n print(\"flag_video needs implementation\")\n\n def allow_video(self, video_id):\n \"\"\"Removes a flag from a video.\n\n Args:\n video_id: The video_id to be allowed again.\n \"\"\"\n print(\"allow_video needs implementation\")\n","sub_path":"python/src/video_player.py","file_name":"video_player.py","file_ext":"py","file_size_in_byte":10730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"491981318","text":"\"\"\"\nModule containing classes for HTTP client/server interactions\n\"\"\"\n\n# Python 2.x/3.x compatibility imports\ntry:\n from urllib.error import HTTPError, URLError\n from urllib.parse import urlencode\nexcept ImportError:\n from urllib2 import HTTPError, URLError\n from urllib import urlencode\n\nimport socket\nfrom pyowm.exceptions import api_call_error, unauthorized_error, not_found_error\nfrom pyowm.webapi25.configuration25 import ROOT_API_URL\n\n\nclass WeatherHttpClient(object):\n\n API_SUBSCRIPTION_SUBDOMAINS = {\n 'free': 'api',\n 'pro': 'pro'\n }\n\n \"\"\"\n An HTTP client class for the OWM web API. The class can leverage a\n caching mechanism\n\n :param API_key: a Unicode object representing the OWM web API key\n :type API_key: Unicode\n :param cache: an *OWMCache* concrete instance that will be used to\n cache OWM web API responses.\n :type cache: an *OWMCache* concrete instance\n :param subscription_type: the type of OWM web API subscription to be wrapped.\n The value is used to pick the proper API subdomain for HTTP calls.\n Defaults to: 'free'\n :type subscription_type: str\n \"\"\"\n\n def __init__(self, API_key, cache, subscription_type='free'):\n self._API_key = API_key\n self._cache = cache\n self._subscription_type = subscription_type\n\n def _lookup_cache_or_invoke_API(self, cache, API_full_url, timeout):\n cached = cache.get(API_full_url)\n if cached:\n return cached\n else:\n try:\n try:\n from urllib.request import urlopen\n except ImportError:\n from urllib2 import urlopen\n response = urlopen(API_full_url, None, timeout)\n except HTTPError as e:\n if '401' in str(e):\n raise unauthorized_error.UnauthorizedError('Invalid API key')\n if '404' in str(e):\n raise not_found_error.NotFoundError('The resource was not found')\n if '502' in str(e):\n raise api_call_error.BadGatewayError(str(e), e)\n raise api_call_error.APICallError(str(e), e)\n except URLError as e:\n raise api_call_error.APICallError(str(e), e)\n else:\n data = response.read().decode('utf-8')\n cache.set(API_full_url, data)\n return data\n\n def call_API(self, API_endpoint_URL, params_dict,\n timeout=socket._GLOBAL_DEFAULT_TIMEOUT):\n\n \"\"\"\n Invokes a specific OWM web API endpoint URL, returning raw JSON data.\n\n :param API_endpoint_URL: the API endpoint to be invoked\n :type API_endpoint_URL: str\n :param params_dict: a dictionary containing the query parameters to be\n used in the HTTP request (given as key-value couples in the dict)\n :type params_dict: dict\n :param timeout: how many seconds to wait for connection establishment\n (defaults to ``socket._GLOBAL_DEFAULT_TIMEOUT``)\n :type timeout: int\n :returns: a string containing raw JSON data\n :raises: *APICallError*\n\n \"\"\"\n try:\n escaped = API_endpoint_URL % (self.API_SUBSCRIPTION_SUBDOMAINS[self._subscription_type],)\n except:\n escaped = API_endpoint_URL\n url = self._build_full_URL(escaped, params_dict)\n return self._lookup_cache_or_invoke_API(self._cache, url, timeout)\n\n def _build_full_URL(self, API_endpoint_URL, params_dict):\n \"\"\"\n Adds the API key and the query parameters dictionary to the specified\n API endpoint URL, returning a complete HTTP request URL.\n\n :param API_endpoint_URL: the API endpoint base URL\n :type API_endpoint_URL: str\n :param params_dict: a dictionary containing the query parameters to be\n used in the HTTP request (given as key-value couples in the dict)\n :type params_dict: dict\n :param API_key: the OWM web API key\n :type API_key: str\n :returns: a full string HTTP request URL\n\n \"\"\"\n params = params_dict.copy()\n if self._API_key is not None:\n params['APPID'] = self._API_key\n return self._build_query_parameters(API_endpoint_URL, params)\n\n def _build_query_parameters(self, base_URL, params_dict):\n \"\"\"\n Turns dictionary items into query parameters and adds them to the base\n URL\n\n :param base_URL: the base URL whom the query parameters must be added\n to\n :type base_URL: str\n :param params_dict: a dictionary containing the query parameters to be\n used in the HTTP request (given as key-value couples in the dict)\n :type params_dict: dict\n :returns: a full string HTTP request URL\n\n \"\"\"\n return base_URL + '?' + urlencode(params_dict)\n\n def __repr__(self):\n return \"<%s.%s - cache=%s>\" % \\\n (__name__, self.__class__.__name__, repr(self._cache))\n","sub_path":"pyowm/commons/weather_client.py","file_name":"weather_client.py","file_ext":"py","file_size_in_byte":5049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"596272725","text":"from tkinter import ttk\r\nimport tkinter as tk\r\nfrom tkinter.scrolledtext import ScrolledText\r\nfrom tkinter import *\r\nimport math\r\nimport random\r\nimport winsound\r\nimport pygame\r\nimport Player as p\r\nfrom PIL import ImageTk\r\nfrom PIL import Image\r\nimport Weapons as w\r\nimport Inventory as i\r\nimport threading\r\nimport time\r\n\r\n# By: James Martin\r\n# Student Number: 2019032\r\n# Teacher: Mr. Miskew\r\n# Date: 6/2/2017\r\n# Course Code: ICS3U-03\r\n\r\n\r\n# This class creates the battle screen and initiates the player. An instance of this created in main.\r\nclass Battle():\r\n # Name: __init__\r\n # Params: root, primaryWeapon, secondaryWeapon\r\n # Returns: none\r\n # Description: __init__ makes all variables for creation of GUI, Player, Weapons, Images and Key Bindings.\r\n def __init__(self, root, primary, secondary):\r\n global root1, tearlist, monsterlist, run,currentWeapon, roomc, person\r\n\r\n # Sub section of __init__ where Variables are declared.\r\n #<editor-fold desc=\"Variables\">\r\n root1 = root\r\n\r\n # These try and excepts try to equip what the player had equipped on the tile world however if it fails then\r\n # it tries to equip only a primary and if that does not work it gives the player a stick that is later removed\r\n # when the player wins the battle.\r\n try:\r\n self.primaryWeapon = i.playerinventory.itemNames[primary]\r\n self.secondaryWeapon = i.playerinventory.itemNames[secondary]\r\n self.equippedItems = [self.primaryWeapon, self.secondaryWeapon]\r\n except:\r\n try:\r\n self.primaryWeapon = i.playerinventory.itemNames[primary]\r\n self.equippedItems=[self.primaryWeapon]\r\n except:\r\n i.playerinventory.additem(i.inGameItem[\"stick\"])\r\n self.primaryWeapon = \"stick\"\r\n self.equippedItems = [self.primaryWeapon]\r\n\r\n currentWeapon = i.playerinventory.items[self.equippedItems[0]]\r\n\r\n self.currentWeaponNum = 0\r\n tearlist = []\r\n monsterlist = []\r\n run = True\r\n self.swordLen = 0\r\n self.hit = pygame.mixer.Sound('./Music/Hit.wav')\r\n self.drops = []\r\n self.shotspeed = 5\r\n self.tears = 15\r\n self.animationTimer = 0\r\n self.speed = 5\r\n self.damage = 1\r\n self.luck = 1\r\n self.knockback = 0.05\r\n self.size = 16\r\n self.anSpeed = 12\r\n self.scale = 40\r\n self.roomnum = 0\r\n self.tsize = self.scale * self.size\r\n self.timer = 0\r\n self.xspeed = 0\r\n self.yspeed = 0\r\n #self.health = 100\r\n self.damagetimer = 0\r\n self.mousex = 0\r\n self.mousey = 0\r\n\r\n # </editor-fold>\r\n\r\n # Sub section of __init__ where pictures are imported.\r\n # <editor-fold desc=\"Pictures\">\r\n self.fatBat = PhotoImage(file=\"./FatBat.png\")\r\n self.fatBatDamage = PhotoImage(file=\"./FatBatDamage.png\")\r\n self.img = Image.open(\"./PlayerTest.png\")\r\n self.img = self.img.resize((90,81))\r\n self.drawImg = ImageTk.PhotoImage(self.img)\r\n self.fatBatDamage = self.fatBatDamage.zoom(2, 2)\r\n self.fatBat = self.fatBat.zoom(2, 2)\r\n self.floorimg = PhotoImage(file=\"./floor.png\")\r\n self.floorimg = self.floorimg.zoom(2, 1)\r\n self.weaponImg = currentWeapon.img\r\n\r\n # Different rotations based on what weapon type the player is using.\r\n if currentWeapon.type == \"bow\":\r\n self.weaponImg = self.weaponImg.rotate(180)\r\n elif currentWeapon.type == \"sword\":\r\n self.swordLen = self.weaponImg.size[0]//3-5\r\n self.weaponImg = self.weaponImg.rotate(-55)\r\n\r\n self.weaponImgDraw = ImageTk.PhotoImage(self.weaponImg)\r\n\r\n # </editor-fold>\r\n\r\n # Sub section of __init__ where Root and canvas are created and configured.\r\n # <editor-fold desc=\"Root and Canvas\">\r\n root1.config(width=self.tsize * 2, height=self.tsize + 80)\r\n roomc = Canvas(root1) # Creating a new canvas\r\n roomc.pack()\r\n roomc.config(width=self.tsize * 2, height=self.tsize + 80)\r\n self.floor = roomc.create_image(self.tsize, self.tsize / 2, image=self.floorimg)\r\n person = roomc.create_image(self.tsize, self.tsize / 2, image=self.drawImg) # Making the player\r\n\r\n self.weapon = roomc.create_image(roomc.coords(person)[0],roomc.coords(person)[1]+40,image = self.weaponImgDraw) # Making the weapon\r\n roomc.create_rectangle(0 + 2, self.tsize + 2, self.tsize * 2 - 2, self.tsize + 78, fill=\"beige\",\r\n outline=\"black\")\r\n self.healthbar = roomc.create_rectangle(100, self.tsize + 25,p.player.health * 3 + 100,self.tsize + 55,fill=\"green\")\r\n self.healthLabel = Label(text=\"Health\", font=(\"papyrus\", 15))\r\n self.healthLabel.place(x=30, y=self.tsize + 25)\r\n self.hotBar()\r\n # </editor-fold>\r\n\r\n # Sub section of __init__ where keys are binded to the tkinter window.\r\n # <editor-fold desc=\"Key Bindings\">\r\n self.a = False\r\n self.d = False\r\n self.s = False\r\n self.w = False\r\n self.shoot = False\r\n\r\n root1.bind(\"<a>\", self.adef)\r\n root1.bind(\"<w>\", self.wdef)\r\n root1.bind(\"<s>\", self.sdef)\r\n root1.bind(\"<d>\", self.ddef)\r\n root1.bind(\"<KeyRelease-a>\", self.aup)\r\n root1.bind(\"<KeyRelease-d>\", self.dup)\r\n root1.bind(\"<KeyRelease-w>\", self.wup)\r\n root1.bind(\"<KeyRelease-s>\", self.sup)\r\n root1.bind(\"<Button-1>\", self.click)\r\n root1.bind(\"<ButtonRelease-1>\", self.clickUp)\r\n root1.bind(\"<B1-Motion>\", self.click)\r\n root1.bind(\"<B1-Motion>\", self.rotatePlayer,add=\"+\")\r\n root1.bind(\"<Motion>\", self.rotatePlayer)\r\n root1.bind(\"<q>\",self.switchItem)\r\n root1.bind(\"<MouseWheel>\",self.switchItem)\r\n # </editor-fold>\r\n\r\n # calls update which calls other functions every timer tick\r\n self.update()\r\n\r\n\r\n # Within this subsection of Battle all of the functions that keys are binded to are defined.\r\n #<editor-fold desc=\"Key Bind Functions\">\r\n # sets a to false when the button is lifted\r\n def aup(self, *args):\r\n self.a = False\r\n self.xspeed = 0\r\n\r\n # sets d to false when the button is lifted\r\n def dup(self, *args):\r\n self.d = False\r\n self.xspeed = 0\r\n\r\n # sets w to false when the button is lifted\r\n def wup(self, *args):\r\n self.w = False\r\n self.yspeed = 0\r\n\r\n # sets s to false when the button is lifted\r\n def sup(self, *args):\r\n self.s = False\r\n self.yspeed = 0\r\n\r\n # sets d to True when the button is pressed\r\n def ddef(self, *args):\r\n self.d = True\r\n\r\n # sets a to True when the button is pressed\r\n def adef(self, *args):\r\n self.a = True\r\n\r\n # sets w to True when the button is pressed\r\n def wdef(self, *args):\r\n self.w = True\r\n\r\n # sets s to True when the button is pressed\r\n def sdef(self, *args):\r\n self.s = True\r\n\r\n # this is called every timer tick within update. It checks what buttons are being pressed and moves the player\r\n # and weapon accordingly.\r\n def move(self, *args):\r\n if self.d == True:\r\n roomc.move(person, self.speed, 0)\r\n roomc.move(self.weapon, self.speed, 0)\r\n self.xspeed = self.speed / 5\r\n self.yspeed = 0\r\n if self.s == True:\r\n roomc.move(person, 0, self.speed)\r\n roomc.move(self.weapon, 0, self.speed)\r\n self.xspeed = 0\r\n self.yspeed = self.speed / 5\r\n if self.a == True:\r\n roomc.move(person, -self.speed, 0)\r\n roomc.move(self.weapon, -self.speed, 0)\r\n self.xspeed = -self.speed / 5\r\n self.yspeed = 0\r\n if self.w == True:\r\n roomc.move(person, 0, -self.speed)\r\n roomc.move(self.weapon, 0, -self.speed)\r\n self.xspeed = 0\r\n self.yspeed = -self.speed / 5\r\n\r\n # When mouse is clicked it recieves the x and y of the mouse and changes Bool shoot to true.\r\n def click(self, event, *args):\r\n self.mouseX, self.mouseY = event.x, event.y\r\n if currentWeapon.type==\"sword\":\r\n self.returnRotation()\r\n self.shoot = True\r\n\r\n # this is called when mouse is moved and it recieves the mouse x and y.\r\n def getXY(self, event, *args):\r\n self.mouseX, self.mouseY = event.x, event.y\r\n\r\n # this is called when the mouse button is lifted. It changes Bool shoot to False so the player no longer shoots.\r\n def clickUp(self, *args):\r\n self.shoot = False\r\n\r\n # </editor-fold>\r\n\r\n\r\n # Name: shootProjectile\r\n # Params: none\r\n # Returns: none\r\n # Description: This checks if the player should be shoot and if it is then it appends an arrow in the direction of\r\n # the mouse (only called if weapon is ranged)\r\n def shootProjectile(self):\r\n\r\n if self.shoot == True and self.timer > currentWeapon.interval:\r\n self.xDist = self.mouseX - roomc.coords(person)[0] # getting x difference between the mouse and the player\r\n self.yDist = self.mouseY - roomc.coords(person)[1] # getting y difference between the mouse and the player\r\n self.xyLength = math.sqrt((self.xDist * self.xDist) + (self.yDist * self.yDist)) # getting difference\r\n # between the mouse and the player by using Pythagorean Theorem\r\n self.xDist = self.xDist / self.xyLength\r\n self.yDist = self.yDist / self.xyLength\r\n tearlist.append(\r\n Tear(self.x - 15, self.y - 10, self.xDist * currentWeapon.shotSpeed, self.yDist *\r\n currentWeapon.shotSpeed, self.tsize,\"nargleblarg\",self.xDist,self.yDist)) # appending a new\r\n # projectile to tearlist with the speeds found with the equations * the weapons shotspeed\r\n\r\n self.timer = 0\r\n\r\n # Name: rotatePlayer\r\n # Params: event\r\n # Returns: none\r\n # Description: This function is called by the mouse moving rotating the player to face the mouse it also affect\r\n # the weapon being used by the player.\r\n def rotatePlayer(self,event):\r\n self.mousex= event.x\r\n self.mousey= event.y\r\n xDist = self.mousex - roomc.coords(person)[0]\r\n yDist = self.mousey - roomc.coords(person)[1]\r\n xyLength = math.sqrt((xDist * xDist) + (yDist * yDist))\r\n xDist = xDist / xyLength\r\n yDist = yDist / xyLength\r\n ramount = math.atan2(yDist,xDist)\r\n ramount = math.degrees(ramount)\r\n self.img = Image.open(\"./PlayerTest.png\")\r\n self.img = self.img.resize((90,81))\r\n self.img = self.img.rotate(-(ramount-90),expand = True)\r\n self.drawImg = ImageTk.PhotoImage(self.img)\r\n roomc.itemconfig(person,image = self.drawImg)\r\n roomc.delete(self.weapon)\r\n self.weaponImg = currentWeapon.img\r\n if currentWeapon.type == \"sword\":\r\n self.weaponImg = self.weaponImg.rotate(-(ramount-80), expand=True)\r\n self.weaponImgDraw = ImageTk.PhotoImage(self.weaponImg)\r\n self.weapon = roomc.create_image(\r\n roomc.coords(person)[0] - int(math.sin(math.radians(ramount) - math.pi / 2) * 35),\r\n roomc.coords(person)[1] + int(math.cos(math.radians(ramount) - math.pi / 2) * 30),\r\n image=self.weaponImgDraw)\r\n\r\n elif currentWeapon.type == \"bow\":\r\n self.weaponImg = self.weaponImg.rotate(-(ramount+90), expand=True)\r\n self.weaponImgDraw = ImageTk.PhotoImage(self.weaponImg)\r\n self.weapon = roomc.create_image(\r\n roomc.coords(person)[0] - int(math.sin(math.radians(ramount) - math.pi / 2) * 50),\r\n roomc.coords(person)[1] + int(math.cos(math.radians(ramount) - math.pi / 2) * 50),\r\n image=self.weaponImgDraw)\r\n\r\n\r\n\r\n roomc.lower(self.weapon)\r\n roomc.lower(self.floor)\r\n\r\n # Name: collision\r\n # Params: none\r\n # Returns: none\r\n # Description: This checks for collision for the walls, player, enemies and pickups.\r\n def collision(self):\r\n\r\n #<editor-fold desc=\"Wall Collision\">\r\n if roomc.coords(person)[0] < 40:\r\n roomc.move(person, self.speed, 0)\r\n roomc.move(self.weapon, self.speed, 0)\r\n if roomc.coords(person)[0] > self.tsize * 2 - 60:\r\n roomc.move(person, -self.speed, 0)\r\n roomc.move(self.weapon, -self.speed, 0)\r\n if roomc.coords(person)[1] < 40:\r\n roomc.move(person, 0, self.speed)\r\n roomc.move(self.weapon, 0, self.speed)\r\n if roomc.coords(person)[1] + 40 > self.tsize - 40:\r\n roomc.move(person, 0, -self.speed)\r\n roomc.move(self.weapon, 0, -self.speed)\r\n for i in range(len(monsterlist)):\r\n if roomc.coords(monsterlist[i].bat)[0] < 40:\r\n monsterlist[i].xspeed = 0\r\n monsterlist[i].yspeed = 0\r\n if roomc.coords(monsterlist[i].bat)[0] > self.tsize * 2 - 60:\r\n monsterlist[i].xspeed = 0\r\n monsterlist[i].yspeed = 0\r\n if roomc.coords(monsterlist[i].bat)[1] < 40:\r\n monsterlist[i].xspeed = 0\r\n monsterlist[i].yspeed = 0\r\n if roomc.coords(monsterlist[i].bat)[1] + 40 > self.tsize - 40:\r\n monsterlist[i].xspeed = 0\r\n monsterlist[i].yspeed = 0\r\n #</editor-fold>\r\n\r\n #<editor-fold desc=\"Ranged Weapon Collision\">\r\n if currentWeapon.type == \"bow\":\r\n for i in range(len(tearlist)):\r\n\r\n try:\r\n\r\n self.tearx = roomc.coords(tearlist[i].tear)[0]\r\n self.teary = roomc.coords(tearlist[i].tear)[1]\r\n except:\r\n pass\r\n if self.tearx < 20 or self.tearx > self.tsize * 2 - 55 or self.teary > self.tsize - 50 or self.teary < 30:\r\n try:\r\n\r\n roomc.delete(tearlist[i].tear)\r\n tearlist[i].alive = False\r\n del tearlist[i].size\r\n del tearlist[i].damage\r\n del tearlist[i].tsize\r\n del tearlist[i].tear\r\n del tearlist[i].xspeed\r\n del tearlist[i].yspeed\r\n\r\n\r\n except:\r\n pass\r\n for j in range(len(monsterlist)):\r\n\r\n try:\r\n self.bbox = roomc.bbox(monsterlist[j].bat)\r\n self.bbox2 = roomc.bbox(tearlist[i].tear)\r\n except:\r\n pass\r\n\r\n if (self.bbox2[0] > self.bbox[0] and self.bbox2[0] < self.bbox[2] and self.bbox2[1] > self.bbox[\r\n 1] and self.bbox2[1] < self.bbox[3]) or(self.bbox2[2] > self.bbox[0] and self.bbox2[2] < self.bbox[2] and self.bbox2[3] > self.bbox[\r\n 1] and self.bbox2[3] < self.bbox[3]) :\r\n try:\r\n\r\n monsterlist[j].xspeed = tearlist[i].xspeed * self.knockback\r\n monsterlist[j].yspeed = tearlist[i].yspeed * self.knockback\r\n roomc.delete(tearlist[i].tear)\r\n tearlist.pop(i)\r\n monsterlist[j].hit += currentWeapon.attack\r\n\r\n\r\n monsterlist[j].damagetimer = 0\r\n self.hit.play()\r\n self.enemyCheckHealth(j)\r\n\r\n\r\n\r\n except:\r\n pass\r\n #</editor-fold>\r\n\r\n #<editor-fold desc=\"Monster to Monster Collision\">\r\n for i in range(len(monsterlist) - 1):\r\n for k in range((len(monsterlist)) - 1, 0, -1):\r\n if abs(roomc.coords(monsterlist[i].bat)[0] - roomc.coords(monsterlist[k].bat)[0]) < 70 and abs(\r\n roomc.coords(monsterlist[i].bat)[1] - roomc.coords(monsterlist[k].bat)[1]) < 60:\r\n if roomc.coords(monsterlist[i].bat)[0] > roomc.coords(monsterlist[k].bat)[0]:\r\n monsterlist[i].xspeed = 1\r\n monsterlist[k].xspeed = -1\r\n if roomc.coords(monsterlist[i].bat)[0] < roomc.coords(monsterlist[k].bat)[0]:\r\n monsterlist[i].xspeed = -1\r\n monsterlist[k].xspeed = 1\r\n if roomc.coords(monsterlist[i].bat)[1] > roomc.coords(monsterlist[k].bat)[1]:\r\n monsterlist[i].yspeed = 1\r\n monsterlist[k].yspeed = -1\r\n if roomc.coords(monsterlist[i].bat)[1] < roomc.coords(monsterlist[k].bat)[1]:\r\n monsterlist[i].yspeed = -1\r\n monsterlist[k].yspeed = 1\r\n #</editor-fold>\r\n\r\n #<editor-fold desc=\"Person to Monster Collision\">\r\n\r\n for i in range(len(monsterlist)):\r\n self.x = roomc.coords(person)[0]\r\n self.y = roomc.coords(person)[1]\r\n if abs(roomc.coords(monsterlist[i].bat)[0] - self.x) < 70 and abs(\r\n roomc.coords(monsterlist[i].bat)[1] - self.y) < 60:\r\n if roomc.coords(monsterlist[i].bat)[0] > self.x:\r\n monsterlist[i].xspeed = 2\r\n roomc.move(person, -2, 0)\r\n roomc.move(self.weapon, -2, 0)\r\n if self.damagetimer > 10:\r\n self.damagetimer = 0\r\n p.player.health += -monsterlist[i].damage\r\n roomc.coords(self.healthbar, 100, self.tsize + 25, p.player.health * 3 + 100, self.tsize + 55)\r\n if roomc.coords(monsterlist[i].bat)[0] < self.x:\r\n monsterlist[i].xspeed = -2\r\n roomc.move(person, 2, 0)\r\n roomc.move(self.weapon, 2, 0)\r\n if self.damagetimer > 20:\r\n self.damagetimer = 0\r\n p.player.health += -monsterlist[i].damage\r\n roomc.coords(self.healthbar, 100, self.tsize + 25, p.player.health * 3 + 100, self.tsize + 55)\r\n if roomc.coords(monsterlist[i].bat)[1] > self.y:\r\n monsterlist[i].yspeed = 2\r\n roomc.move(person, 0, -2)\r\n roomc.move(self.weapon, 0, -2)\r\n if self.damagetimer > 20:\r\n self.damagetimer = 0\r\n p.player.health += -monsterlist[i].damage\r\n roomc.coords(self.healthbar, 100, self.tsize + 25, p.player.health * 3 + 100, self.tsize + 55)\r\n\r\n if roomc.coords(monsterlist[i].bat)[1] < self.y:\r\n monsterlist[i].yspeed = -2\r\n roomc.move(person, 0, 2)\r\n roomc.move(self.weapon, 0, 2)\r\n if self.damagetimer > 20:\r\n self.damagetimer = 0\r\n p.player.health += -monsterlist[i].damage\r\n roomc.coords(self.healthbar, 100, self.tsize + 25, p.player.health * 3 + 100, self.tsize + 55)\r\n #</editor-fold>\r\n\r\n # <editor-fold desc=\"Person to Pickup\">\r\n moreBbox = roomc.bbox(person)\r\n for i in range(len(self.drops)):\r\n if roomc.coords(self.drops[i].pos)[0] > moreBbox[0] and roomc.coords(self.drops[i].pos)[0] < moreBbox[2] and roomc.coords(self.drops[i].pos)[1] > moreBbox[1] and roomc.coords(self.drops[i].pos)[1] < moreBbox[3]:\r\n\r\n if self.drops[i].TYPE == \"gold\":\r\n p.player.goldChange(self.drops[i].value,\"give\")\r\n\r\n roomc.delete(self.drops[i].pos)\r\n self.drops.pop(i)\r\n\r\n if len(monsterlist) <= 0 and len(self.drops) <= 0:\r\n self.close(True)\r\n return\r\n None\r\n\r\n #</editor-fold>\r\n\r\n # Name: monsterAnimation\r\n # Params: none\r\n # Returns: none\r\n # Description: This function animates monsters in the battle depending on the direction the player is in.\r\n def monsterAnimation(self):\r\n for i in range(len(monsterlist)):\r\n if abs(roomc.coords(monsterlist[i].bat)[0] - self.x) > abs(roomc.coords(monsterlist[i].bat)[1] - self.y):\r\n if roomc.coords(monsterlist[i].bat)[0] - self.x > 0:\r\n monsterlist[i].dir = 3\r\n else:\r\n monsterlist[i].dir = 1\r\n else:\r\n if roomc.coords(monsterlist[i].bat)[1] - self.y > 0:\r\n monsterlist[i].dir = 0\r\n else:\r\n monsterlist[i].dir = 2\r\n if self.animationTimer >= self.anSpeed:\r\n\r\n for i in range(len(monsterlist)):\r\n\r\n monsterlist[i].img = monsterlist[i].anim[monsterlist[i].dir][monsterlist[i].animateCounter]\r\n roomc.itemconfig(monsterlist[i].bat, image=monsterlist[i].img)\r\n if monsterlist[i].animateCounter >= 2:\r\n monsterlist[i].animateCounter = 0\r\n else:\r\n monsterlist[i].animateCounter += 1\r\n self.animationTimer = 0\r\n self.animationTimer += 1\r\n\r\n # Name: blank\r\n # Params: none\r\n # Returns: none\r\n # Description: This is a function that I bind keys to when I want to disable them.\r\n def blank(self, *args):\r\n None\r\n\r\n # Name: swing\r\n # Params: none\r\n # Returns: none\r\n # Description: swing is a function that is only called when a sword is equipped. This function does no collision but\r\n # it does the animation of the sword swinging.\r\n def swing(self):\r\n split = 50\r\n amount = -170\r\n amount /= split\r\n time = currentWeapon.shotSpeed//split\r\n root1.bind(\"<B1-Motion>\",self.blank)\r\n root1.bind(\"<Motion>\",self.blank)\r\n if self.i==split//2:\r\n try:\r\n self.swordCollision()\r\n except:\r\n pass\r\n if self.i<=split:\r\n #self.weaponImg = self.weaponImg.rotate(amount / 5,expand = True)\r\n #self.weaponImgDraw = ImageTk.PhotoImage(self.weaponImg)\r\n #self.weapon = roomc.create_image(\r\n # roomc.coords(person)[0],\r\n # roomc.coords(person)[1],\r\n # image=self.weaponImgDraw)\r\n xDist = self.mousex - roomc.coords(person)[0]\r\n yDist = self.mousey - roomc.coords(person)[1]\r\n xyLength = math.sqrt((xDist * xDist) + (yDist * yDist))\r\n xDist = xDist / xyLength\r\n yDist = yDist / xyLength\r\n ramount = math.atan2(yDist, xDist)\r\n ramount = math.degrees(ramount)\r\n roomc.delete(self.weapon)\r\n self.weaponImg = currentWeapon.img\r\n self.weaponImg = self.weaponImg.rotate(-(ramount -80-(amount*self.i)), expand=True)\r\n self.weaponImgDraw = ImageTk.PhotoImage(self.weaponImg)\r\n self.weapon = roomc.create_image(\r\n roomc.coords(person)[0] - int(math.sin(math.radians(ramount) - math.pi / 2) * 35),\r\n roomc.coords(person)[1] + int(math.cos(math.radians(ramount) - math.pi / 2) * 30),\r\n image=self.weaponImgDraw)\r\n\r\n self.i+=1\r\n self.timer = 0\r\n root1.after(time,self.swing)\r\n else:\r\n\r\n self.returnRotation()\r\n self.timer=0\r\n root1.bind(\"<B1-Motion>\", self.click)\r\n root1.bind(\"<B1-Motion>\", self.rotatePlayer, add=\"+\")\r\n root1.bind(\"<Motion>\", self.rotatePlayer)\r\n\r\n # Name: enemyCheckHealth\r\n # Params: j (what enemy to check)\r\n # Returns: none\r\n # Description: This is run anytime an enemy is hit either with a sword or bow. It checks if the enemies health has\r\n # become <=0 and if it has it drops a coin and deletes the enemy. It then checks if that was the last enemy if it\r\n # was it closes the battle screen.\r\n def enemyCheckHealth(self,j):\r\n if monsterlist[j].hit >= monsterlist[j].health:\r\n self.drops.append(Drop(\"gold\", 1, roomc.coords(monsterlist[j].bat)[0], roomc.coords(monsterlist[j].bat)[1]))\r\n roomc.delete(monsterlist[j].bat)\r\n monsterlist.pop(j)\r\n\r\n if len(monsterlist) <= 0 and len(self.drops) <= 0:\r\n self.close(True)\r\n\r\n # Name: swordCollision\r\n # Params: none\r\n # Returns: none\r\n # Description:\r\n def swordCollision(self):\r\n\r\n if currentWeapon.type == \"sword\":\r\n xDist = self.mousex - roomc.coords(person)[0]\r\n yDist = self.mousey - roomc.coords(person)[1]\r\n xyLength = math.sqrt((xDist * xDist) + (yDist * yDist))\r\n xDist = xDist / xyLength\r\n yDist = yDist / xyLength\r\n ramount = math.atan2(yDist, xDist)\r\n ramount = abs(math.degrees(ramount))\r\n\r\n maxAngle = ramount + 45\r\n minAngle = ramount - 45\r\n xSizeDif = roomc.bbox(person)[2] - roomc.bbox(person)[0]\r\n ySizeDif = roomc.bbox(person)[3] - roomc.bbox(person)[1]\r\n swordLocation = [roomc.bbox(person)[0] + xSizeDif, roomc.bbox(person)[1] + ySizeDif]\r\n\r\n for i in range(len(monsterlist)):\r\n\r\n xEnemySizeDif = roomc.bbox(monsterlist[i].bat)[2] - roomc.bbox(monsterlist[i].bat)[0]\r\n yEnemySizeDif = roomc.bbox(monsterlist[i].bat)[3] - roomc.bbox(monsterlist[i].bat)[1]\r\n enemyLocation = [roomc.bbox(monsterlist[i].bat)[0] + xEnemySizeDif,\r\n roomc.bbox(monsterlist[i].bat)[1] + yEnemySizeDif]\r\n enemyRadius = math.hypot(xEnemySizeDif, yEnemySizeDif)\r\n playerEnemyDist = abs(\r\n math.hypot(swordLocation[0] - enemyLocation[0], swordLocation[1] - enemyLocation[1]))\r\n enemyXDist = (swordLocation[0] - enemyLocation[0])\r\n enemyYDist = (swordLocation[1] - enemyLocation[1])\r\n enemyXDist = enemyXDist / playerEnemyDist\r\n enemyYDist = enemyYDist / playerEnemyDist\r\n enemyRAmount = math.atan2(enemyYDist, enemyXDist)\r\n enemyRAmount = math.degrees(enemyRAmount)\r\n #if enemyRAmount < 0:\r\n # enemyRAmount += 360\r\n enemyRAmount=abs(abs(enemyRAmount)-180)\r\n if enemyRadius + self.swordLen > playerEnemyDist:\r\n if enemyRAmount > minAngle and enemyRAmount < maxAngle:\r\n\r\n monsterlist[i].xspeed += xDist*currentWeapon.knockback\r\n monsterlist[i].yspeed += yDist*currentWeapon.knockback\r\n monsterlist[i].hit += currentWeapon.attack\r\n self.enemyCheckHealth(i)\r\n\r\n # Name: returnRotation\r\n # Params: none\r\n # Returns: none\r\n # Description: This returns the weapon to its proper place according to the mouse. This is used to return the weapon\r\n # after swinging as well in other places where the weapon would not automatically correct.\r\n def returnRotation(self):\r\n xDist = self.mousex - roomc.coords(person)[0]\r\n yDist = self.mousey - roomc.coords(person)[1]\r\n xyLength = math.sqrt((xDist * xDist) + (yDist * yDist))\r\n xDist = xDist / xyLength\r\n yDist = yDist / xyLength\r\n ramount = math.atan2(yDist, xDist)\r\n ramount = math.degrees(ramount)\r\n self.img = Image.open(\"./PlayerTest.png\")\r\n self.img = self.img.resize((90, 81))\r\n self.img = self.img.rotate(-(ramount - 90), expand=True)\r\n\r\n self.drawImg = ImageTk.PhotoImage(self.img)\r\n roomc.itemconfig(person, image=self.drawImg)\r\n roomc.delete(self.weapon)\r\n self.weaponImg = currentWeapon.img\r\n\r\n\r\n if currentWeapon.type == \"sword\":\r\n self.weaponImg = self.weaponImg.rotate(-(ramount - 80), expand=True)\r\n self.weaponImgDraw = ImageTk.PhotoImage(self.weaponImg)\r\n self.weapon = roomc.create_image(\r\n roomc.coords(person)[0] - int(math.sin(math.radians(ramount) - math.pi / 2) * 35),\r\n roomc.coords(person)[1] + int(math.cos(math.radians(ramount) - math.pi / 2) * 30),\r\n image=self.weaponImgDraw)\r\n\r\n elif currentWeapon.type == \"bow\":\r\n self.weaponImg = self.weaponImg.rotate(-(ramount + 90), expand=True)\r\n self.weaponImgDraw = ImageTk.PhotoImage(self.weaponImg)\r\n self.weapon = roomc.create_image(\r\n roomc.coords(person)[0] - int(math.sin(math.radians(ramount) - math.pi / 2) * 50),\r\n roomc.coords(person)[1] + int(math.cos(math.radians(ramount) - math.pi / 2) * 50),\r\n image=self.weaponImgDraw)\r\n\r\n # Name: update\r\n # Params: none\r\n # Returns: none\r\n # Description: This function recalls itself every 17 miliseconds (60fps) and calls other functions such as collision\r\n # and enemyAnimation. Depending on what weapon is equipped it will call different functions.\r\n def update(self):\r\n\r\n if run:\r\n self.move()\r\n self.x = roomc.coords(person)[0] - 10\r\n self.y = roomc.coords(person)[1] - 10\r\n self.timer += 1\r\n self.damagetimer += 1\r\n self.monsterAnimation()\r\n self.drawImg = ImageTk.PhotoImage(self.img)\r\n roomc.itemconfig(person,image = self.drawImg)\r\n\r\n if currentWeapon.type==\"bow\":\r\n self.shootProjectile()\r\n self.collision()\r\n\r\n elif currentWeapon.type == \"sword\":\r\n self.collision()\r\n if self.shoot==True:\r\n if self.timer>currentWeapon.interval:\r\n self.i = 1\r\n self.swing()\r\n\r\n\r\n root1.after(17, self.update)\r\n\r\n\r\n # Name: switchItem\r\n # Params: event\r\n # Returns: none\r\n # Description: Based on mouse wheel movement it changes what item is equipped and highlights the current item in the\r\n # hotbar.\r\n def switchItem(self,event,*args):\r\n global currentWeapon\r\n self.lastWeaponNum = self.currentWeaponNum\r\n if event.delta >=120:\r\n self.currentWeaponNum -= 1\r\n else:\r\n self.currentWeaponNum += 1\r\n\r\n\r\n if self.currentWeaponNum>=len(self.equippedItems):\r\n self.currentWeaponNum=0\r\n elif self.currentWeaponNum<0:\r\n self.currentWeaponNum = len(self.equippedItems)-1\r\n\r\n currentWeapon = i.playerinventory.items[self.equippedItems[self.currentWeaponNum]]\r\n self.weaponImg = currentWeapon.img\r\n if currentWeapon.type == \"bow\":\r\n self.weaponImg = self.weaponImg.rotate(180)\r\n elif currentWeapon.type == \"sword\":\r\n self.swordLen = self.weaponImg.size[0] / 2 - 40\r\n self.weaponImg = self.weaponImg.rotate(-55)\r\n self.weaponImgDraw = ImageTk.PhotoImage(self.weaponImg)\r\n self.weapon = roomc.create_image(roomc.coords(person)[0], roomc.coords(person)[1] + 40,\r\n image=self.weaponImgDraw)\r\n self.returnRotation()\r\n roomc.itemconfig(self.hotBarList[self.lastWeaponNum], fill=\"white\")\r\n roomc.itemconfig(self.hotBarList[self.currentWeaponNum],fill=\"lightgreen\")\r\n\r\n\r\n\r\n\r\n self.returnRotation()\r\n\r\n # Name: close\r\n # Params: battleWon\r\n # Returns: none\r\n # Description: when the game ends this function is called and passed either True or False as eventually if you lose\r\n # or win it will do different things. The function unbinds all buttons and destroys the battle canvas (roomc).\r\n def close(self, battleWon):\r\n self.run = False\r\n try:\r\n i.playerinventory.removeItem(i.stick)\r\n except:\r\n pass\r\n roomc.destroy()\r\n root1.bind(\"<a>\",self.blank)\r\n root1.bind(\"<w>\",self.blank)\r\n root1.bind(\"<s>\",self.blank)\r\n root1.bind(\"<d>\",self.blank)\r\n root1.bind(\"<KeyRelease-a>\",self.blank)\r\n root1.bind(\"<KeyRelease-d>\",self.blank)\r\n root1.bind(\"<KeyRelease-w>\",self.blank)\r\n root1.bind(\"<KeyRelease-s>\",self.blank)\r\n root1.bind(\"<Button-1>\",self.blank)\r\n root1.bind(\"<ButtonRelease-1>\",self.blank)\r\n root1.bind(\"<B1-Motion>\",self.blank)\r\n root1.bind(\"<Motion>\",self.blank)\r\n self.killIt = True\r\n self.battleWon = battleWon\r\n\r\n # Name: hotBar\r\n # Params: none\r\n # Returns: none\r\n # Description: This function accesses the players inventory and displayes the items they have equipped in the hotbar.\r\n # Depending on the amount of items equipped it will change the size of the hotbar and will center it. This works for\r\n # amounts from 1 - infinity\r\n def hotBar(self):\r\n self.hotBarList=[]\r\n self.imageList = []\r\n self.itemList = []\r\n size = len(self.equippedItems)*25\r\n for j in range(len(self.equippedItems)):\r\n if i.playerinventory.items[self.equippedItems[j]].type==\"sword\":\r\n self.imageList.append(ImageTk.PhotoImage(\r\n i.playerinventory.items[self.equippedItems[j]].img.rotate(45,expand=True).resize((100, int(\r\n i.playerinventory.items[self.equippedItems[j]].img.rotate(45,expand=True).size[1] * 100 /\r\n i.playerinventory.items[self.equippedItems[j]].img.rotate(45,expand=True).size[0])))))\r\n self.itemList.append(\r\n roomc.create_image(self.tsize - size + (50 * j) + 105, 705, image=self.imageList[j],tags=\"weapon\"))\r\n else:\r\n self.imageList.append(ImageTk.PhotoImage(\r\n i.playerinventory.items[self.equippedItems[j]].img.rotate(45,expand=True).resize((55, int(\r\n i.playerinventory.items[self.equippedItems[j]].img.rotate(45,expand=True).size[1] * 55 /\r\n i.playerinventory.items[self.equippedItems[j]].img.rotate(45,expand=True).size[0])))))\r\n self.itemList.append(roomc.create_image(self.tsize-size+(50*j)+120, 685, image=self.imageList[j],tags=\"weapon\"))\r\n\r\n if j == self.currentWeaponNum:\r\n self.hotBarList.append(roomc.create_rectangle(self.tsize-size+(50*j)+100, 660, 50*j + self.tsize+50-size+100, 710, fill=\"lightgreen\"))\r\n else:\r\n self.hotBarList.append(roomc.create_rectangle(self.tsize - size + (50 * j) + 100, 660, 50 * j + self.tsize + 50 - size + 100, 710, fill=\"white\"))\r\n roomc.tag_raise(\"weapon\")\r\n\r\n#Name: Tear\r\n#Params: none\r\n#Returns: none\r\n#Description: This is used only when a ranged weapon is equipped. When a arrow is shot an instance of tear is created.\r\nclass Tear():\r\n\r\n # Name: __init__\r\n # Params: x (start location), y (start location), xspeed, yspeed, tsize, image1, xDist(xSpeed), yDist(ySpeed)\r\n # Returns: none\r\n # Description: Variables used later on are created here taken from both parameters and the equipped weapon. As well\r\n # as calling update() which calls other functions.\r\n def __init__(self, x, y, xspeed, yspeed, tsize,image1,xDist,yDist):\r\n self.damage = currentWeapon.attack\r\n self.size = 20\r\n self.tsize = tsize\r\n self.img = Image.open(currentWeapon.secondimage)\r\n ramount = math.atan2(yDist,xDist)\r\n ramount = math.degrees(ramount)\r\n self.img = self.img.rotate(-(ramount +90), expand=True)\r\n self.drawImg = ImageTk.PhotoImage(self.img)\r\n self.tear = roomc.create_image(x,y,image = self.drawImg)\r\n self.alive = True\r\n self.xspeed = xspeed\r\n self.yspeed = yspeed\r\n self.update()\r\n\r\n # Name: update\r\n # Params: none\r\n # Returns: none\r\n # Description: This calls move() but only if the arrow is \"alive\" meaning it has not hit anything yet. This happens\r\n # every 17 miliseconds (60fps)\r\n def update(self):\r\n try:\r\n if run:\r\n if self.alive:\r\n self.move()\r\n root1.after(17, self.update)\r\n except:\r\n pass\r\n\r\n # Name: move\r\n # Params: none\r\n # Returns: none\r\n # Description: This moves the arrow acorrding to self.xspeed and self.yspeed\r\n def move(self):\r\n roomc.move(self.tear, self.xspeed, self.yspeed)\r\n\r\n\r\n#Name: Enemy\r\n#Params: none\r\n#Returns: none\r\n#Description: This class is used when creating an enemy in battle.\r\nclass Enemy:\r\n\r\n # Name: __init__\r\n # Params: x, y (start position)\r\n # Returns: none\r\n # Description: Creates all the variables that will be later changed to create the enemy within EnemyData.py. Calls\r\n # update() which calls move() and chase().\r\n def __init__(self, x, y):\r\n\r\n self.img = PhotoImage(file=\"./FatBat.png\")\r\n self.img = self.img.zoom(2, 2)\r\n self.bat = roomc.create_image(x, y, image=self.img)\r\n self.down1 = 0\r\n self.down2 = 0\r\n self.down3 = 0\r\n self.up1 = 0\r\n self.up2 = 0\r\n self.up3 = 0\r\n self.right1 = 0\r\n self.right2 = 0\r\n self.right3 = 0\r\n self.left1 = 0\r\n self.left2 = 0\r\n self.left3 = 0\r\n self.health = 50\r\n self.healthbar = roomc.create_rectangle(100,100,200,200)\r\n self.maxhealth = 0\r\n self.speed = 2.5\r\n self.speedgain = 0.05\r\n self.xspeed = self.speed\r\n self.yspeed = self.speed\r\n self.damagetimer = 0\r\n\r\n self.hit = 0\r\n self.damage = 15\r\n self.update()\r\n self.animation = 0\r\n self.animateCounter = 0\r\n self.aLeft = [self.left1,self.left2,self.left3]\r\n self.aRight = [self.right1,self.right2,self.right3]\r\n self.aUp = [self.up1,self.up2,self.up3]\r\n self.aDown = [self.down1,self.down2,self.down3]\r\n self.anim = {\r\n 0:self.aUp,\r\n 1:self.aRight,\r\n 2:self.aDown,\r\n 3:self.aLeft\r\n }\r\n self.dir = 0\r\n\r\n # Name: update\r\n # Params: none\r\n # Returns: none\r\n # Description: Calls move() and chase() every 17 miliseconds (60fps)\r\n def update(self):\r\n\r\n if run:\r\n self.damagetimer += 1\r\n self.chase()\r\n self.move()\r\n if self.damagetimer > 4:\r\n roomc.itemconfig(self.bat, image=self.img)\r\n roomc.delete(self.healthbar)\r\n try:\r\n\r\n self.healthbar = roomc.create_rectangle(roomc.coords(self.bat)[0]-50,roomc.coords(self.bat)[1]-50,roomc.coords(self.bat)[0]+50 - int(self.hit*(100/self.health)),roomc.coords(self.bat)[1]-40,fill = \"red\")\r\n except:\r\n pass\r\n\r\n root1.after(17, self.update)\r\n\r\n # Name: move\r\n # Params: none\r\n # Returns: none\r\n # Description: actually does the moving that is calculated by chase()\r\n def move(self):\r\n roomc.move(self.bat, self.xspeed, self.yspeed)\r\n\r\n # Name: chase\r\n # Params: none\r\n # Returns: none\r\n # Description: checks where the player is and adds speed accordingly\r\n def chase(self):\r\n self.pos = roomc.coords(self.bat)[0:2]\r\n self.playerpos = roomc.coords(person)[0:2]\r\n try:\r\n if self.pos[0] > self.playerpos[0]:\r\n self.xspeed += -self.speedgain\r\n if self.pos[0] < self.playerpos[0]:\r\n self.xspeed += self.speedgain\r\n if self.pos[1] > self.playerpos[1]:\r\n self.yspeed += -self.speedgain\r\n if self.pos[1] < self.playerpos[1]:\r\n self.yspeed += self.speedgain\r\n\r\n if self.xspeed > self.speed:\r\n self.xspeed = self.speed\r\n elif self.xspeed < -self.speed:\r\n self.xspeed = -self.speed\r\n if self.yspeed > self.speed:\r\n self.yspeed = self.speed\r\n elif self.yspeed < -self.speed:\r\n self.yspeed = -self.speed\r\n\r\n except:\r\n pass\r\n\r\n#Name: Drop\r\n#Params: type(type of drop), value(value of coin), x, y (location of coin)\r\n#Returns: none\r\n#Description: Creates a drop that the player must pickup before the battle will close.\r\nclass Drop():\r\n\r\n # Name: __init__\r\n # Params: type(type of drop), value(value of coin), x, y (location of coin)\r\n # Returns: none\r\n # Description: creates the variables from parameters passed. It also gives variables values based on the type of\r\n # pickup.\r\n def __init__(self,TYPE,VALUE,x,y):\r\n self.TYPE = TYPE\r\n self.x = x\r\n self.y = y\r\n\r\n\r\n if self.TYPE == \"gold\":\r\n\r\n self.counter = 0\r\n self.img = tk.PhotoImage(file = \"./Images/Drops/Coin/Coin_\"+str(self.counter)+\".png\")\r\n self.pos = roomc.create_image(x,y,image = self.img)\r\n self.value = VALUE\r\n self.pickUpRangex = 8\r\n self.pickUpRangey = 8\r\n","sub_path":"Binding.py","file_name":"Binding.py","file_ext":"py","file_size_in_byte":41143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"44440230","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#\n# Where's Mah Intertubes?!\n#\n# A simple script that lets you know when your connection goes down or comes \n# back up with sounds. \n#\n# Depends:\n# espeak (if you don't want to use sound files)\n# pygame (if you do)\n#\n# Options:\n# -h, --help show this help message and exit\n# --speak recite a message when connection goes on or off\n# (default)\n# --off=AUDIO_OFF, --boo=AUDIO_OFF\n# set a sound played when connection is lost\n# --on=AUDIO_ON, --yay=AUDIO_ON\n# set a sound played when connection is back on\n# -t TIMEOUT, --timeout=TIMEOUT\n# set timeout for checking if connection works (default:\n# 10s)\n# -d DELAY, --delay=DELAY\n# set delay between connection checks (default: 30s)\n# -u URI, --uri=URI, --url=URI\n# ping this URI to see if connection works (default:\n# http://74.125.77.147)\n# -v, --verbose display information about things done by the program\n#\n# Examples:\n# Let's say you want to check if you can connect and you're fine with the \n# espeak dude to moan about it instead fo using a cool sound you can use one\n# of the following (let it run in the background):\n# \n# ./wheresmahintertubes.py &\n# ./wheresmahintertubes.py --speak &\n#\n# If you want some proper fun sounds then all you need is point them out:\n#\n# ./wheresmahintertubes.py --yay=file/for_on.ogg --boo=file/for_off.mp3 &\n#\n# License:\n# Copyright (C) 2010 Konrad Siek <konrad.siek@gmail.com>\n#\n# This program is free software: you can redistribute it and/or modify it \n# under the terms of the GNU General Public License version 3, as published \n# by the Free Software Foundation.\n# \n# This program is distributed in the hope that it will be useful, but \n# WITHOUT ANY WARRANTY; without even the implied warranties of \n# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR \n# PURPOSE. See the GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License along \n# with this program. If not, see <http://www.gnu.org/licenses/>.\n#\n\nimport time\nimport sys\nimport pygame\n\nquiet = False\nuri = \"http://74.125.77.147\"\n\ndef printerr(*args):\n if quiet:\n return\n from sys import argv, stderr\n from os.path import basename\n stderr.write(\"%s:\" % basename(argv[0]))\n for arg in args:\n stderr.write(\" %s\" % arg)\n stderr.write(\"\\n\")\n\ndef printout(*args):\n if quiet:\n return\n from sys import argv, stdout\n from os.path import basename\n stdout.write(\"%s:\" % basename(argv[0]))\n for arg in args:\n stdout.write(\" %s\" % arg)\n stdout.write(\"\\n\")\n\ndef can_has_connection(timeout):\n import urllib2 \n printout(\"Checking ping to\", uri)\n try:\n urllib2.urlopen(uri, timeout=timeout) # Google\n except urllib2.URLError as error:\n return False\n return True\n\nclass Speaker:\n def __init__(self):\n self.library = {}\n\n def add_to_library(self, key, path):\n self.library[key] = path\n\n def play_from_library(self, key):\n if not key in self.library:\n return False\n self.play(self.library[key])\n return True\n\n def play(self, message):\n from os import system\n system('espeak %s' % message)\n\nclass PyGamePlayer:\n def __init__(self):\n pygame.init()\n self.library = {}\n\n def add_to_library(self, key, path):\n self.library[key] = path\n\n def play_from_library(self, key):\n if not key in self.library:\n return False\n self.play(self.library[key])\n return True\n\n def play(self, path):\n pygame.mixer.Sound(path).play()\n\nclass Checker:\n def __init__(self, delay, timeout):\n self.delay = delay\n self.timeout = timeout\n\n def run(self):\n connected = can_has_connection(self.timeout)\n printout('Initially the connection is', 'on' if connected else 'off')\n while True:\n time.sleep(self.delay)\n current = can_has_connection(self.timeout)\n if connected != current:\n connected = current\n self.react(connected)\n\n def react(self, connected):\n from threading import Thread\n printout('The connection just went', 'on' if connected else 'off') \n def run():\n self.player.play_from_library(connected)\n thread = Thread()\n thread.run = run\n thread.start()\n\nif __name__ == '__main__':\n from optparse import OptionParser\n from os.path import basename\n from sys import argv\n\n usage = '\\n%s [OPTIONS] ' % basename(argv[0]) + \\\n '--on=[SOUND FILE] --off=[SOUND FILE]\\n' + \\\n '\\tplay a sound when network connection goes up or down' + \\\n '\\n%s [OPTIONS] ' % basename(argv[0]) + '--speak\\n' + \\\n '\\trecite a message when network connection goes up or down (boring...)'\n\n description = 'Wait around and periodically check if the connection ' + \\\n 'went up or down, and if that happens play an appropriate sound to ' + \\\n 'indicate it to the user. Network connectivity is check by the ' + \\\n 'the simple method of connecting a specific host address, and ' + \\\n 'assuming that the entwork is down if it takes too much time for ' + \\\n 'that host to respond.'\n\n parser = OptionParser(usage=usage, description=description)\n\n parser.add_option('--speak', action='store_true', dest='speak', \\\n help='recite a message when connection goes on or off (default)')\n parser.add_option('--off', '--boo', action='store', dest='audio_off', \\\n help='set a sound played when connection is lost')\n parser.add_option('--on', '--yay', action='store', dest='audio_on', \\\n help='set a sound played when connection is back on')\n parser.add_option('-t', '--timeout', action='store', dest='timeout', \\\n help='set timeout for checking if connection works (default: 10s)', \\\n default=10, type='int')\n parser.add_option('-d', '--delay', action='store', dest='delay', \\\n help='set delay between connection checks (default: 30s)', \\\n default=30, type='int')\n parser.add_option('-u', '--uri', '--url', action='store', dest='uri', \\\n help='ping this URI to see if connection works (default: %s)' % uri, \\\n default=uri)\n parser.add_option('-v', '--verbose', action='store_true', dest='verbose', \\\n help='display information about things done by the program')\n\n opts, args = parser.parse_args()\n\n quiet = not opts.verbose\n uri = opts.uri\n\n player = None\n\n if opts.speak or not opts.audio_on or not opts.audio_off:\n player = Speaker()\n player.add_to_library(True, \"Connection just went up\")\n player.add_to_library(False, \"Connection just went down\")\n else:\n player = PyGamePlayer()\n player.add_to_library(True, opts.audio_on)\n player.add_to_library(False, opts.audio_off)\n\n checker = Checker(delay=opts.delay, timeout=opts.timeout)\n checker.player = player\n\n try:\n checker.run()\n except (KeyboardInterrupt, SystemExit): \n printout('Exiting...')\n running = False\n","sub_path":"python/wheresmahintertubes.py","file_name":"wheresmahintertubes.py","file_ext":"py","file_size_in_byte":7421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"501016492","text":"import math\r\nimport numpy as np\r\nimport torch\r\nfrom torch import rand, log, zeros_like, cat\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom torch.autograd import Variable, Function\r\nfrom torch.autograd import Function\r\n\r\neps = 1e-12\r\n\r\n\r\nclass Gumbel(nn.Module):\r\n\r\n\tdef __init__(self, n_classes, temperature):\r\n\t\tsuper(Gumbel, self).__init__()\r\n\t\t\r\n\t\tself.n_classes\t = n_classes\r\n\t\tself.temperature = temperature\r\n\r\n\tdef sample_gumbel(self, shape, eps=1e-12):\r\n\t\tU = rand(shape).cuda()\r\n\t\treturn -Variable(log(-log(U + eps) + eps))\r\n\r\n\tdef gumbel_softmax_sample(self, logits, temperature):\r\n\t\ty = logits + self.sample_gumbel(logits.size())\r\n\t\treturn F.softmax(y / temperature, dim=-1)\r\n\r\n\tdef sample_gumbel_softmax(self, alpha, train):\r\n\r\n\t\tif train:\r\n\t\t\tunif\t = torch.rand(alpha.size())\r\n\t\t\tif alpha.is_cuda:\r\n\t\t\t\tunif = unif.cuda()\r\n\t\t\tgumbel\t = -torch.log(-torch.log(unif + eps) + eps)\r\n\t\t\tlog_alpha = torch.log(alpha + eps)\r\n\t\t\tlogit\t = (log_alpha + gumbel) / self.temperature\r\n\r\n\t\t\treturn F.softmax(logit, dim=-1)\r\n\t\telse:\r\n\t\t\t_, max_alpha = torch.max(alpha, dim=-1)\r\n\t\t\tone_hot_samples = torch.zeros(alpha.size())\r\n\t\t\tone_hot_samples.scatter_(1, max_alpha.view(-1, 1).data.cpu(), 1)\r\n\t\t\tif alpha.is_cuda:\r\n\t\t\t\treturn one_hot_samples.cuda()\r\n\t\t\telse:\t\r\n\t\t\t\treturn one_hot_samples\r\n\r\n\tdef gumbel_softmax(self, logits, train,matlab=False):\r\n\t\t\"\"\"\r\n\t\tST-gumple-softmax\r\n\t\tinput: [*, n_class]\r\n\t\treturn: flatten --> [*, n_class] an one-hot vector\r\n\t\t\"\"\"\r\n\t\tif not train and (matlab == False):\r\n\t\t\treturn self._recon_sample(logits)\r\n\t\t\r\n\t\t#if not temperature:\r\n\t\ttemperature = self.temperature\r\n\r\n\t\ty = self.gumbel_softmax_sample(logits, temperature)\r\n\t\tshape = y.size()\r\n\t\t_, ind = y.max(dim=-1)\r\n\t\ty_hard = zeros_like(y).view(-1, shape[-1])\r\n\t\ty_hard.scatter_(1, ind.view(-1, 1), 1)\r\n\t\ty_hard = y_hard.view(*shape)\r\n\t\ty_hard = (y_hard - y).detach() + y\r\n\t\treturn y_hard.view(-1, shape[-1])\r\n\r\n\tdef _recon_sample(self, alphas):\r\n\t\t\r\n\t\t_, max_alpha = torch.max(alphas, dim=-1)\r\n\t\tone_hot_sample = torch.zeros(alphas.size())\r\n\t\t#one_hot_sample.scatter_(1,max_alpha.view(-1,1).data.cpu(), 1).cuda()\r\n\t\tone_hot_sample.scatter_(1,max_alpha.view(-1,1).data.cpu(), 1)\r\n\t\tif alphas.is_cuda:\r\n\t\t\treturn one_hot_sample.cuda()\r\n\t\telse:\r\n\t\t\treturn one_hot_sample\r\n\r\n\tdef calc_kloss(self, alphas, discap, disdim, cur_iter):\r\n\t\t\r\n\t\tkl_losses = [self._kloss(alpha) for alpha in alphas]\r\n\t\t\r\n\t\tkl_loss = torch.sum(cat(kl_losses)) \r\n\t\t\r\n\t\tdisc_min, disc_max, disc_num_iters, disc_gamma = discap\r\n\t\t# Increase discrete capacity without exceeding disc_max or theoretical\r\n\t\t# maximum (i.e. sum of log of dimension of each discrete variable)\r\n\t\tdisc_cap_current = (disc_max - disc_min) * cur_iter / float(disc_num_iters) + disc_min\r\n\t\tdisc_cap_current = min(disc_cap_current, disc_max)\r\n\t\t# Require float conversion here to not end up with numpy float\r\n\t\tdisc_theoretical_max = sum([float(np.log(dim)) for dim in disdim])\r\n\t\tdisc_cap_current = min(disc_cap_current, disc_theoretical_max)\r\n\t\t# Calculate discrete capacity loss\r\n\t\tdisc_capacity_loss = disc_gamma * torch.abs(disc_cap_current - kl_loss)\r\n\t\t\r\n\t\treturn disc_capacity_loss\r\n\r\n\r\n\tdef _kloss(self, alpha):\r\n\t\tlog_dim = torch.Tensor([np.log(int(alpha.size()[-1]))])\r\n\t\t\r\n\t\tif alpha.is_cuda:\r\n\t\t\tlog_dim = log_dim.cuda()\r\n\t\t\r\n\t\tneg_entropy = torch.sum(alpha * torch.log(alpha + eps),dim=-1)\r\n\t\tmean_neg_entropy=torch.mean(neg_entropy, dim=0)\r\n\t\tkl_loss = log_dim + mean_neg_entropy\r\n\t\treturn kl_loss\r\n\r\nclass STHeaviside(Function):\r\n\t@staticmethod\r\n\tdef forward(ctx, x):\r\n\t\ty = torch.zeros(x.size()).type_as(x)\r\n\t\ty[x >= 0] = 1\r\n\t\treturn y\r\n\r\n\t@staticmethod\r\n\tdef backward(ctx, grad_output):\r\n\t\treturn grad_output\r\n\r\nclass Normal(nn.Module):\r\n\t\"\"\"Samples from a Normal distribution using the reparameterization trick.\r\n\t\"\"\"\r\n\r\n\tdef __init__(self, mu=0, sigma=1):\r\n\t\tsuper(Normal, self).__init__()\r\n\t\t# self.normalization = Variable(torch.Tensor([np.log(2 * np.pi)]))\r\n\r\n\t\t# self.mu = Variable(torch.Tensor([mu]))\r\n\t\t# self.logsigma = Variable(torch.Tensor([math.log(sigma)]))\r\n\r\n\t\tself.normalization = (torch.Tensor([np.log(2 * np.pi)]))\r\n\r\n\t\tself.mu = (torch.Tensor([mu]))\r\n\t\tself.logsigma = (torch.Tensor([math.log(sigma)]))\r\n\r\n\tdef _check_inputs(self, size, mu_logsigma):\r\n\t\tif size is None and mu_logsigma is None:\r\n\t\t\traise ValueError(\r\n\t\t\t\t'Either one of size or params should be provided.')\r\n\t\telif size is not None and mu_logsigma is not None:\r\n\r\n\t\t\tmu = mu_logsigma.select(-1, 0).expand(size)\r\n\t\t\tlogsigma = mu_logsigma.select(-1, 1).expand(size)\r\n\t\t\treturn mu, logsigma\r\n\t\telif size is not None:\r\n\t\t\tmu = self.mu.expand(size)\r\n\t\t\tlogsigma = self.logsigma.expand(size)\r\n\t\t\treturn mu, logsigma\r\n\t\telif mu_logsigma is not None:\r\n\t\t\tmu = mu_logsigma.select(-1, 0)\r\n\t\t\tlogsigma = mu_logsigma.select(-1, 1)\r\n\t\t\treturn mu, logsigma\r\n\t\telse:\r\n\t\t\traise ValueError(\r\n\t\t\t\t'Given invalid inputs: size={}, mu_logsigma={})'.format(\r\n\t\t\t\t\tsize, mu_logsigma))\r\n\r\n\tdef calc_kloss(self, params, cont_cap, cur_iter):\r\n\t\t\r\n\t\tmu, logsigma = torch.chunk(params, 2, dim=-1)\r\n\t\tkl_vals = -0.5 * (1 + logsigma - mu.pow(2) - logsigma.exp())\r\n\t\tkl_means = torch.mean(kl_vals, dim=0)\r\n\t\tkl_loss = torch.sum(kl_means)\r\n\r\n\t\tcont_min, cont_max, cont_num_iters, cont_gamma = cont_cap\r\n\t\t# Increase continuous capacity without exceeding cont_max\r\n\t\tcont_cap_current = (cont_max - cont_min) * cur_iter / float(cont_num_iters) + cont_min\r\n\t\tcont_cap_current = min(cont_cap_current, cont_max)\r\n\t\t# Calculate continuous capacity loss\r\n\t\treturn\tcont_gamma * torch.abs(cont_cap_current - kl_loss)\r\n\t\t\r\n\r\n\tdef sample_normal(self, params, train=True, heir=False):\r\n\t\t\r\n\t\tmu, logsigma = torch.chunk(params, 2, dim=-1)\r\n\r\n\t\tif train:\r\n\t\r\n\t\t\tsigma = torch.exp(0.5 * logsigma).cuda()\r\n\t\t\teps = torch.zeros(sigma.size()).normal_().cuda()\r\n\t\t\t#logsigma = torch.clamp(logsigma, min=-103., max=87.)\t\t\r\n\t\t\tsample = mu.cuda() + sigma * eps \r\n\t\t\t\r\n\t\t\tif heir == True:\r\n\t\t\t\treturn sample, mu, sigma\r\n\t\t\telse:\r\n\t\t\t\treturn sample\r\n\t\telse:\r\n\t\t\treturn mu\r\n\r\n\tdef log_density(self, sample, params=None):\r\n\t\tif params is not None:\r\n\t\t\tmu, logsigma = self._check_inputs(None, params)\r\n\t\telse:\r\n\t\t\tmu, logsigma = self._check_inputs(sample.size(), None)\r\n\t\t\tmu = mu.type_as(sample)\r\n\t\t\tlogsigma = logsigma.type_as(sample)\r\n\r\n\t\tc = self.normalization.type_as(sample.data)\r\n\t\t\r\n\t\tretval = -.5 * (sample - mu) * (sample - mu) / (torch.exp(logsigma) * torch.exp(logsigma)) - 0.5 * torch.log(c*torch.exp(logsigma) * torch.exp(logsigma))\r\n\t\t\r\n\t\treturn retval\r\n\r\n\tdef NLL(self, params, sample_params=None):\r\n\t\t\"\"\"Analytically computes\r\n\t\t\tE_N(mu_2,sigma_2^2) [ - log N(mu_1, sigma_1^2) ]\r\n\t\tIf mu_2, and sigma_2^2 are not provided, defaults to entropy.\r\n\t\t\"\"\"\r\n\t\tmu, logsigma = self._check_inputs(None, params)\r\n\t\tif sample_params is not None:\r\n\t\t\tsample_mu, sample_logsigma = self._check_inputs(None, sample_params)\r\n\t\telse:\r\n\t\t\tsample_mu, sample_logsigma = mu, logsigma\r\n\r\n\t\tc = self.normalization.type_as(sample_mu.data)\r\n\t\tnll = logsigma.mul(-2).exp() * (sample_mu - mu).pow(2) \\\r\n\t\t\t+ torch.exp(sample_logsigma.mul(2) - logsigma.mul(2)) + 2 * logsigma + c\r\n\t\treturn nll.mul(0.5)\r\n\r\n\tdef kld(self, params):\r\n\t\t\"\"\"Computes KL(q||p) where q is the given distribution and p\r\n\t\tis the standard Normal distribution.\r\n\t\t\"\"\"\r\n\t\tmu, logsigma = self._check_inputs(None, params)\r\n\t\t# see Appendix B from VAE paper:\r\n\t\t# Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014\r\n\t\t# https://arxiv.org/abs/1312.6114\r\n\t\t# 0.5 * sum(1 + log(sigma^2) - mean^2 - sigma^2)\r\n\t\tkld = logsigma.mul(2).add(1) - mu.pow(2) - logsigma.exp().pow(2)\r\n\t\tkld.mul_(-0.5)\r\n\t\treturn kld\r\n\r\n\tdef get_params(self):\r\n\t\treturn torch.cat([self.mu, self.logsigma])\r\n\r\n\t@property\r\n\tdef nparams(self):\r\n\t\treturn 2\r\n\r\n\t@property\r\n\tdef ndim(self):\r\n\t\treturn 1\r\n\r\n\t@property\r\n\tdef is_reparameterizable(self):\r\n\t\treturn True\r\n\r\n\tdef __repr__(self):\r\n\t\ttmpstr = self.__class__.__name__ + ' ({:.3f}, {:.3f})'.format(\r\n\t\t\tself.mu.data[0], self.logsigma.exp().data[0])\r\n\t\treturn tmpstr\r\n\r\n\r\nclass Laplace(nn.Module):\r\n\t\"\"\"Samples from a Laplace distribution using the reparameterization trick.\r\n\t\"\"\"\r\n\r\n\tdef __init__(self, mu=0, scale=1):\r\n\t\tsuper(Laplace, self).__init__()\r\n\t\tself.normalization = Variable(torch.Tensor([-math.log(2)]))\r\n\r\n\t\tself.mu = Variable(torch.Tensor([mu]))\r\n\t\tself.logscale = Variable(torch.Tensor([math.log(scale)]))\r\n\r\n\tdef _check_inputs(self, size, mu_logscale):\r\n\t\tif size is None and mu_logscale is None:\r\n\t\t\traise ValueError(\r\n\t\t\t\t'Either one of size or params should be provided.')\r\n\t\telif size is not None and mu_logscale is not None:\r\n\t\t\tmu = mu_logscale.select(-1, 0).expand(size)\r\n\t\t\tlogscale = mu_logscale.select(-1, 1).expand(size)\r\n\t\t\treturn mu, logscale\r\n\t\telif size is not None:\r\n\t\t\tmu = self.mu.expand(size)\r\n\t\t\tlogscale = self.logscale.expand(size)\r\n\t\t\treturn mu, logscale\r\n\t\telif mu_logscale is not None:\r\n\t\t\tmu = mu_logscale.select(-1, 0)\r\n\t\t\tlogscale = mu_logscale.select(-1, 1)\r\n\t\t\treturn mu, logscale\r\n\t\telse:\r\n\t\t\traise ValueError(\r\n\t\t\t\t'Given invalid inputs: size={}, mu_logscale={})'.format(\r\n\t\t\t\t\tsize, mu_logscale))\r\n\r\n\tdef sample(self, size=None, params=None):\r\n\t\tmu, logscale = self._check_inputs(size, params)\r\n\t\tscale = torch.exp(logscale)\r\n\t\t# Unif(-0.5, 0.5)\r\n\t\tu = Variable(torch.rand(mu.size()).type_as(mu.data)) - 0.5\r\n\t\tsample = mu - scale * torch.sign(u) * torch.log(1 - 2 * torch.abs(u) + eps)\r\n\t\treturn sample\r\n\r\n\tdef log_density(self, sample, params=None):\r\n\t\r\n\t\tif params is not None:\r\n\t\t\tmu, logscale = self._check_inputs(None, params)\r\n\t\telse:\r\n\t\t\tmu, logscale = self._check_inputs(sample.size(), None)\r\n\t\t\tmu = mu.type_as(sample)\r\n\t\t\tlogscale = logscale.type_as(sample)\r\n\r\n\t\tc = self.normalization.type_as(sample.data)\r\n\r\n\t\t\r\n\t\t\r\n\t\tinv_scale = torch.exp(-logscale)\r\n\t\t\r\n\t\tins_exp = - torch.abs(sample - mu) * inv_scale\r\n\r\n\t\t\r\n\t\tlogdn = ins_exp + c - logscale\r\n\t\t\r\n\t\t\r\n\t\treturn logdn\r\n\r\n\tdef get_params(self):\r\n\t\treturn torch.cat([self.mu, self.logscale])\r\n\r\n\t@property\r\n\tdef nparams(self):\r\n\t\treturn 2\r\n\r\n\t@property\r\n\tdef ndim(self):\r\n\t\treturn 1\r\n\r\n\t@property\r\n\tdef is_reparameterizable(self):\r\n\t\treturn True\r\n\r\n\tdef __repr__(self):\r\n\t\ttmpstr = self.__class__.__name__ + ' ({:.3f}, {:.3f})'.format(\r\n\t\t\tself.mu.data[0], self.logscale.exp().data[0])\r\n\t\treturn tmpstr\r\n\r\n\r\nclass Bernoulli(nn.Module):\r\n\t\"\"\"Samples from a Bernoulli distribution where the probability is given\r\n\tby the sigmoid of the given parameter.\r\n\t\"\"\"\r\n\r\n\tdef __init__(self, p=0.5, stgradient=False):\r\n\t\tsuper(Bernoulli, self).__init__()\r\n\t\tp = torch.Tensor([p])\r\n\t\tself.p = Variable(torch.log(p / (1 - p) + eps))\r\n\t\tself.stgradient = stgradient\r\n\r\n\tdef _check_inputs(self, size, ps):\r\n\t\t#print(size)\r\n\t\t#print(ps.shape)\r\n\t\tif size is None and ps is None:\r\n\t\t\traise ValueError(\r\n\t\t\t\t'Either one of size or params should be provided.')\r\n\t\telif size is not None and ps is not None:\r\n\t\t\tif ps.ndimension() > len(size):\r\n\t\t\t\treturn ps.squeeze(-1).expand(size)\r\n\t\t\telse:\r\n\t\t\t\treturn ps.expand(size)\r\n\t\telif size is not None:\r\n\t\t\treturn self.p.expand(size)\r\n\t\telif ps is not None:\r\n\t\t\treturn ps\r\n\t\telse:\r\n\t\t\traise ValueError(\r\n\t\t\t\t'Given invalid inputs: size={}, ps={})'.format(size, ps))\r\n\r\n\tdef _sample_logistic(self, size):\r\n\t\tu = Variable(torch.rand(size))\r\n\t\tl = torch.log(u + eps) - torch.log(1 - u + eps)\r\n\t\treturn l\r\n\r\n\tdef sample(self, size=None, params=None):\r\n\t\tpresigm_ps = self._check_inputs(size, params)\r\n\t\tlogp = F.logsigmoid(presigm_ps)\r\n\t\tlogq = F.logsigmoid(-presigm_ps)\r\n\t\tl = self._sample_logistic(logp.size()).type_as(presigm_ps)\r\n\t\tz = logp - logq + l\r\n\t\tb = STHeaviside.apply(z)\r\n\t\treturn b if self.stgradient else b.detach()\r\n\r\n\tdef log_density(self, sample, params=None):\r\n\t\t#print(sample.size())\r\n\t\tpresigm_ps = self._check_inputs(sample.size(), params).type_as(sample)\r\n\t\tp = (torch.sigmoid(presigm_ps) + eps) * (1 - 2 * eps)\r\n\t\tlogp = sample * torch.log(p + eps) + (1 - sample) * torch.log(1 - p + eps)\r\n\t\treturn logp\r\n\r\n\tdef get_params(self):\r\n\t\treturn self.p\r\n\r\n\t@property\r\n\tdef nparams(self):\r\n\t\treturn 1\r\n\r\n\t@property\r\n\tdef ndim(self):\r\n\t\treturn 1\r\n\r\n\t@property\r\n\tdef is_reparameterizable(self):\r\n\t\treturn self.stgradient\r\n\r\n\tdef __repr__(self):\r\n\t\ttmpstr = self.__class__.__name__ + ' ({:.3f})'.format(\r\n\t\t\ttorch.sigmoid(self.p.data)[0])\r\n\t\treturn tmpstr\r\n\r\nclass FactorialNormalizingFlow(nn.Module):\r\n\r\n\tdef __init__(self, dim, nsteps):\r\n\t\tsuper(FactorialNormalizingFlow, self).__init__()\r\n\t\tself.dim = dim\r\n\t\tself.nsteps = nsteps\r\n\t\tself.x_dist = Normal()\r\n\t\tself.scale = nn.Parameter(torch.Tensor(self.nsteps, self.dim))\r\n\t\tself.weight = nn.Parameter(torch.Tensor(self.nsteps, self.dim))\r\n\t\tself.bias = nn.Parameter(torch.Tensor(self.nsteps, self.dim))\r\n\t\tself.reset_parameters()\r\n\r\n\tdef reset_parameters(self):\r\n\t\t#self.scale.data.normal_(0, 0.02).cuda()\r\n\t\t#self.weight.data.normal_(0, 0.02).cuda()\r\n\t\t#self.bias.data.normal_(0, 0.02).cuda()\r\n\t\tself.scale.data.normal_(0, 0.02)\r\n\t\tself.weight.data.normal_(0, 0.02)\r\n\t\tself.bias.data.normal_(0, 0.02)\r\n\r\n\tdef sample(self, batch_size):\r\n\t\traise NotImplementedError\r\n\r\n\tdef log_density(self, y, params=None):\r\n\r\n\t\tassert(y.size(1) == self.dim)\r\n\t\tx = y\r\n\t\t#logdetgrad = Variable(torch.zeros(y.size()).type_as(y.data)).cuda()\r\n\t\tlogdetgrad = Variable(torch.zeros(y.size()).type_as(y.data))\r\n\t\tfor i in range(self.nsteps):\r\n\t\t\t#u = self.scale[i][None].cuda()\r\n\t\t\t#w = self.weight[i][None].cuda()\r\n\t\t\t#b = self.bias[i][None].cuda()\r\n\t\t\tu = self.scale[i][None]\r\n\t\t\tw = self.weight[i][None]\r\n\t\t\tb = self.bias[i][None]\t\t\t\r\n\t\t\tact = F.tanh(x * w + b)\r\n\t\t\t#x = x + u.cuda() * act\r\n\t\t\tx = x + u * act\r\n\t\t\tlogdetgrad = logdetgrad + torch.log(torch.abs(1 + u * (1 - act.pow(2)) * w) + eps)\r\n\t\tlogpx = self.x_dist.log_density(x)\r\n\t\tlogpy = logpx + logdetgrad\r\n\t\treturn logpy\r\n","sub_path":"utils/dist.py","file_name":"dist.py","file_ext":"py","file_size_in_byte":13643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"515509524","text":"# \n# Common_7_1.py\n# GUI Constant Definitions\n#\n\nSQUARE = 1\nROUND = 2\nARROW = 3\n\nPOINT_DOWN = 0\nPOINT_UP = 1\nPOINT_RIGHT = 2\nPOINT_LEFT = 3\n\nSTATUS_OFF = 1\nSTATUS_ON = 2\nSTATUS_WARN = 3\nSTATUS_ALARM = 4\nSTATUS_SET = 5\n\nclass DummyClass:\n pass\n\nColor = DummyClass()\n\nColor.PANEL = '#545454'\nColor.OFF = '#656565'\nColor.ON = '#00FF33'\nColor.WARN = '#ffcc00'\nColor.ALARM = '#ff4422'\n\n","sub_path":"Grayson/Examples/Chapter07/Common_7_1.py","file_name":"Common_7_1.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"138151053","text":"# %load q05_top_10_plotting/build.py\n# default imports\nimport matplotlib.pyplot as plt\nfrom greyatomlib.olympics_project_new.q04_find_top_10.build import q04_find_top_10, q03_better_event, q02_country_operations, q01_rename_columns\nplt.switch_backend('agg')\npath = './data/olympics.csv'\nOlympicsDF=q01_rename_columns(path) \nOlympicsDF=q02_country_operations(OlympicsDF)\nOlympicsDF=q03_better_event(OlympicsDF) \nTop10Summer,Top10Winter, Top10, Common =q04_find_top_10(OlympicsDF,'Total_Summer', 'Total_Winter','Total')\n\ndef q05_top_10_plotting(OlympicsDF,Top10Summer,Top10Winter, Top10):\n Top10Summer = OlympicsDF.loc[OlympicsDF.Country_Name.isin(Top10Summer)].loc[:,['Country_Name', 'Total']]\n Top10Summer.plot(x='Country_Name', y='Total',kind='bar')\n \n Top10Winter = OlympicsDF.loc[OlympicsDF.Country_Name.isin(Top10Winter)].loc[:,['Country_Name', 'Total']]\n Top10Winter.plot(x='Country_Name', y='Total',kind='bar')\n \n Top10 = OlympicsDF.loc[OlympicsDF.Country_Name.isin(Top10)].loc[:,['Country_Name', 'Total']]\n Top10.plot(x='Country_Name', y='Total',kind='bar')\n plt.show()\n \nq05_top_10_plotting(OlympicsDF,Top10Summer,Top10Winter, Top10)\n\n\n\n\n\n\n","sub_path":"q05_top_10_plotting/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"502820401","text":"from __future__ import print_function, division\n\nimport numpy as np\nfrom sklearn.metrics import confusion_matrix\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nimport numpy as np\nimport torchvision\nfrom torchvision import datasets, models, transforms\nimport matplotlib.pyplot as plt\nimport time\nimport os\nimport copy\nfrom tqdm import tqdm\nfrom torch.utils.data import DataLoader\nimport glob\nimport shutil\nimport sys\n\ndef plot_confusion_matrix(cm,\n target_names,\n title='Confusion matrix',\n cmap=None,\n normalize=True,\n save_file=None):\n \"\"\"\n given a sklearn confusion matrix (cm), make a nice plot\n\n Arguments\n ---------\n cm: confusion matrix from sklearn.metrics.confusion_matrix\n\n target_names: given classification classes such as [0, 1, 2]\n the class names, for example: ['high', 'medium', 'low']\n\n title: the text to display at the top of the matrix\n\n cmap: the gradient of the values displayed from matplotlib.pyplot.cm\n see http://matplotlib.org/examples/color/colormaps_reference.html\n plt.get_cmap('jet') or plt.cm.Blues\n\n normalize: If False, plot the raw numbers\n If True, plot the proportions\n save_file: Path of destination jpg, has to be a string\n\n Usage\n -----\n plot_confusion_matrix(cm = cm, # confusion matrix created by sklearn.metrics.confusion_matrix\n normalize = True, # show proportions\n target_names = y_labels_vals, # list of names of the classes\n title = best_estimator_name # title of graph\n save_file = name_of_final_file #name and path of the final file\n \"\"\"\n import matplotlib.pyplot as plt\n import numpy as np\n import itertools\n accuracy = np.trace(cm) / float(np.sum(cm))\n misclass = 1 - accuracy\n if cmap is None:\n cmap = plt.get_cmap('Blues')\n plt.figure(figsize=(8, 6))\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n if target_names is not None:\n tick_marks = np.arange(len(target_names))\n plt.xticks(tick_marks, target_names, rotation=45)\n plt.yticks(tick_marks, target_names)\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n\n thresh = cm.max() / 1.5 if normalize else cm.max() / 2\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n if normalize:\n plt.text(j, i, \"{:0.4f}\".format(cm[i, j]),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n else:\n plt.text(j, i, \"{:,}\".format(cm[i, j]),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label\\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass))\n plt.savefig(save_file)\n\n\nmodel_name=sys.argv[1]\nprint('el model_name que li has passat es:', model_name)\n\nlabels_train_file='model_output/train_labels_'+model_name+'.txt' #els labels son tots iguals independentment del model\nlabels_val_file='model_output/val_labels_'+model_name+'.txt'\n\npreds_train_file='model_output/train_preds_'+model_name+'.txt'\npreds_val_file='model_output/val_preds_'+model_name+'.txt'\n\nwith open(labels_train_file, 'r') as textFile: #ja esta be\n labels1t = textFile.readlines()\nlabels_train = [float(s.replace('\\n', '')) for s in labels1t]\nwith open(labels_val_file, 'r') as textFile:\n labels1v = textFile.readlines()\nlabels_val = [float(s.replace('\\n', '')) for s in labels1v]\n\nwith open(preds_train_file, 'r') as textFile: #ja està bé\n preds1t = textFile.readlines()\npreds_train = [float(s.replace('\\n', '')) for s in preds1t]\nwith open(preds_val_file, 'r') as textFile:\n preds1v = textFile.readlines()\npreds_val = [float(s.replace('\\n', '')) for s in preds1v]\n\n\n\nfor phase in ['train', 'val']:\n if phase == 'train':\n conf_matrix = confusion_matrix(labels_train, preds_train)\n plot_confusion_matrix(cm=conf_matrix,\n normalize=False,\n target_names=['actinic keratosis', 'basal cell \\ncarcinoma', 'dermatofibroma',\n 'melanoma', 'nevus', 'pigmented \\nbenign keratosis', 'vascular lesion'],\n title='Confusion Matrix',\n save_file='/imatge/ltarres/PycharmProjects/test/loss_acc/confusion_matrix_train_' + model_name + '.jpg')\n else:\n conf_matrix = confusion_matrix(labels_val, preds_val)\n plot_confusion_matrix(cm=conf_matrix,\n normalize=False,\n target_names=['actinic keratosis', 'basal cell \\ncarcinoma', 'dermatofibroma',\n 'melanoma', 'nevus', 'pigmented \\nbenign keratosis', 'vascular lesion'],\n title='Confusion Matrix',\n save_file='/imatge/ltarres/PycharmProjects/test/loss_acc/confusion_matrix' + '_val_' + model_name+ '.jpg')\n","sub_path":"test/main_confusion_matrix_cpu.py","file_name":"main_confusion_matrix_cpu.py","file_ext":"py","file_size_in_byte":5424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"328437513","text":"from nltk.corpus import stopwords\nimport numpy as np\nimport os\nfrom sklearn.model_selection import train_test_split\n\n\ndef create_bow(sentence, vocab_list, gram):\n word_list = tokenize(sentence, gram)\n bow = np.zeros(len(vocab_list))\n \n for word in word_list:\n if word in vocab_list:\n bow[vocab_list[word]] = 1\n return bow\n\ndef rm_stopwords(word_list):\n return [word for word in word_list if word not in stopwords.words('english')]\n\ndef tokenize(sent, grams):\n words_list = rm_stopwords(sent.split())\n sent_tok = []\n for gram in range(1, grams + 1):\n for i in range(len(words_list) + 1 - gram):\n sent_tok.append(\"-\".join(words_list[i:i + gram]))\n return sent_tok\n \n\"\"\"\nLoads the raw data \n\"\"\"\ndef build_vocab(gram):\n \n #Load data\n cwd = os.getcwd()\n # the paths of data\n data_path_training_neg = cwd + r'\\train\\neg'\n data_path_training_pos = cwd + r'\\train\\pos'\n data_path_test = cwd + r'\\test'\n File_names_neg =[];\n File_names_pos =[];\n File_names_test = []\n \n # training and test variable definition\n Training_data_text=[]\n Training_data_class=[]\n Test_data_text=[]\n \n # reading neg training data from txt files\n for root, dirs, files in os.walk(data_path_training_neg):\n for name in files:\n if name.endswith((\".txt\")):\n File_names_neg.append(name)\n File_names_sorted_neg = sorted(File_names_neg,key = lambda x: int(x.split('_')[0]))\n for i in range(len(File_names_sorted_neg)):\n txtfile_path = data_path_training_neg + '\\\\' + File_names_sorted_neg[i]\n d = open(txtfile_path, 'r', encoding=\"utf8\")\n Training_data_text.append(d.read())\n Training_data_class.append(0)\n d.close()\n \n # reading pos training data from txt files\n for root, dirs, files in os.walk(data_path_training_pos):\n for name in files:\n if name.endswith((\".txt\")):\n File_names_pos.append(name)\n File_names_sorted_pos = sorted(File_names_pos,key = lambda x: int(x.split('_')[0]))\n for i in range(len(File_names_sorted_pos)):\n txtfile_path = data_path_training_pos + '\\\\' + File_names_sorted_pos[i]\n d = open(txtfile_path, 'r', encoding=\"utf8\")\n Training_data_text.append(d.read())\n Training_data_class.append(1)\n d.close()\n \n \n # reading test data from txt files\n for root, dirs, files in os.walk(data_path_test):\n for name in files:\n if name.endswith((\".txt\")):\n File_names_test.append(name)\n File_names_sorted = sorted(File_names_test)\n for i in range(len(File_names_sorted)):\n txtfile_path = data_path_test + '\\\\' + File_names_sorted[i]\n d = open(txtfile_path, 'r', encoding=\"utf8\")\n Test_data_text.append(d.read())\n d.close()\n \n # spliting train and valid data\n X_train, X_val, Y_train, Y_val = train_test_split(Training_data_text, Training_data_class, train_size = 0.8, test_size = 0.2)\n \n # creating training data dictionary\n Training_data_dic = {}\n for i in range(len(X_train)):\n Training_data_dic.setdefault('sentence', []).append(X_train[i])\n Training_data_dic.setdefault('label', []).append(Y_train[i])\n # creating validation data dictionary\n Validation_data_dic = {}\n for i in range(len(X_val)):\n Validation_data_dic.setdefault('sentence', []).append(X_val[i])\n Validation_data_dic.setdefault('label', []).append(Y_val[i])\n # creating test data dictionary\n Test_data_dic = {}\n for i in range(len(Test_data_text)):\n Test_data_dic.setdefault('sentence', []).append(Test_data_text[i])\n \n \n # creating vocabulary dictionary\n word_count = 0\n vocab_list = {}\n \n #Create vocab set \n vocab_set = set()\n for sentence in Training_data_dic['sentence']:\n word_list = tokenize(sentence, gram)\n word_list_reduced = []\n for i in range(len(word_list)):\n # if word_list[i] not in vocab_set:\n word_list_reduced.append(word_list[i])\n vocab_set.update(word_list_reduced)\n \n #Assign each word a unique index\n for word in vocab_set:\n vocab_list[word] = word_count\n word_count += 1\n \n df_train = Training_data_dic\n df_val = Validation_data_dic\n df_test = Test_data_dic\n \n return vocab_list, df_train, df_val, df_test\n\n\n\n","sub_path":"NBSVMpreprocessing.py","file_name":"NBSVMpreprocessing.py","file_ext":"py","file_size_in_byte":4441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"632167744","text":"import unittest\nfrom pymongo import MongoClient\n\nfrom setup.mongo_init import load_data_to_mongo\nfrom endpoints.get_favorite_fruit_veg import FruitVeg\nfrom test_settings import *\n\n\nfavorite_fruit_veg_1 = {'username': 'Carmella Lambert', 'age': 61, 'fruits': ['orange', 'apple', 'banana', 'strawberry'], 'vegetables': []}\n\nclass TestFruitVeg(unittest.TestCase):\n\n def setUp(self):\n self.client = MongoClient(HOST_NAME_TEST, PORT_NAME_TEST)\n self.db = self.client[DB_NAME_TEST]\n self.collection_companies = self.db[COMPANIES_COLLECTION_NAME_TEST]\n self.collection_people = self.db[PEOPLE_COLLECTION_NAME_TEST]\n self.person_index_test = 0\n self.fruit_veg_test = FruitVeg(self.collection_people,\n self.person_index_test)\n print()\n\n def test_get_friends_details(self):\n favorite_fruit_veg = self.fruit_veg_test.get_favorite_fruit_veg(self.collection_people,\n self.person_index_test)\n self.assertEqual(favorite_fruit_veg, favorite_fruit_veg_1)\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"tests/test_endpoints/test_get_favorite_fruit_veg.py","file_name":"test_get_favorite_fruit_veg.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"397410415","text":"import cv2\nimport numpy as np\nimport tensorflow as tf\nimport os\nimport random\nfrom tensorflow import keras\nimport tensorflow.keras.layers as Layers\nfrom tensorflow.keras.models import Sequential\nimport math\nfrom google.protobuf import text_format\n\n# exit()\n# model_name = \"autoencoder_large3\"\n# model_dir = \"auto_large3\"\nmodel_name = \"RNN_AUTO\"\nmodel_dir = \"RNN_AUTO\"\nimage_size = 400\n\ndef flatten_layer(layer):\n\tlayer_shape = layer.get_shape()\t\t\n\tnum_features = layer_shape[1:4].num_elements()\n\tprint(num_features)\n\tlayer_flat = tf.reshape(layer, [-1, num_features])\n\treturn layer_flat,num_features\n\ngpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.7)\nsess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\n\nimported_meta = tf.train.import_meta_graph(\"./tmp/\"+model_dir+\"/\"+model_name+\".ckpt.meta\")\nimported_meta.restore(sess,\"./tmp/\"+model_dir+\"/\"+model_name+\".ckpt\")\ng = sess.graph\nfor i in g.get_operations():\n\tprint(i.name)\n\t# if 'conv2d_4/Relu' in i.name:\n# for i in g.get_variables():\n# \tprint(i)\n# exit()\ninput_image = g.get_tensor_by_name('input_images_array:0')\nreshapedd = g.get_tensor_by_name('Reshape:0')\n\ndeconv_out = g.get_tensor_by_name('conv2d_transpose_5/Relu:0')\nconv_out = g.get_tensor_by_name('conv2d_3/Relu:0')\nprint(dir(conv_out))\nprint(conv_out.value_index)\n# exit()\n# shape1 = conv_out.get_shape()\n# conv_out_act1 = conv_out[:0,:,:,:0]\n# conv_out_edit = tf.zeros((1,shape1[1],shape1[2],shape1[3]),dtype=tf.float32)\n# conv_out_edit = tf.concat((conv_out_act1,conv_out_edit),axis=3)\n# assign_conv_out = tf.assign(conv_out,conv_out_edit)\n# tf.assign(conv_out_edit[:,:,:,0],conv_out[:,:,:,0])\n# tf.assign(conv_out,conv_out_edit)\n\n# exit()\n# conv2d_transpose_5/Relu\n\n# graphdef = g.as_graph_def()\n# subgraph = tf.graph_util.extract_sub_graph(graphdef,['conv2d_4/Relu'])\n# const_g = tf.graph_util.convert_variables_to_constants(sess,graphdef,['conv2d_transpose_4/Relu'])\n# tf.io.write_graph(const_g,'./frozen_auto/','trained_autol4.pbtxt')\n# exit()\n\n# output = sess.run(deconv5,feed_dict={input_image:img_array})\n\n# f = open(\"./frozen_auto/trained_auto.pbtxt\",'rb')\n# data = f.read()\n# print(type(data))\n# gdef = tf.GraphDef()\n# text_format.Merge(data,gdef)\n# tf.graph_util.import_graph_def(gdef)\n# # print(graphstr)\n# g = sess.graph\n# f.close()\n\n\ndef getMapImage(conv_out):\n\t# wsz = conv_out.shape[0]\n\twsz = 100\n\tno_filters = conv_out.shape[2]\n\t# print(wsz)\n\t# print(no_filters)\n\t# print(\"++++++++====\")\n\tif no_filters == 1:\n\t\tmin_val = np.amin(conv_out[:,:,0])\n\t\tzeroes_val = conv_out[:,:,0] - min_val\n\t\tmax_val = np.amax(zeroes_val)\n\t\tnorm_val = zeroes_val/max_val\n\t\treturn norm_val\n\trows = int(no_filters/4)+1\n\tcols = int(no_filters/rows)+1\n\t# print(rows*(wsz))\n\t# print(cols*(wsz))\n\tblank_grid = np.zeros((cols*(wsz),rows*(wsz)),dtype=np.float32)\n\tfor i in range(no_filters):\n\t\tfil = conv_out[:,:,i]\n\t\trem = i%rows\n\t\tdiv = int(i/rows)\n\t\t# print(rem)\n\t\t# print(div)\n\t\tblank_grid[div*wsz:div*wsz+wsz,rem*wsz:rem*wsz+wsz] = cv2.resize(fil,(100,100))\n\t\t# blank_grid[]\n\tmin_val = np.amin(blank_grid)\n\tzeroes_val = blank_grid - min_val\n\tmax_val = np.amax(zeroes_val)\n\tnorm_val = zeroes_val/max_val\n\treturn norm_val\n\ntest_folder = \"./test_vids/\"\nfor f in os.listdir(test_folder):\n\tvidreader = cv2.VideoCapture(test_folder+f)\n\tvidreader.set(cv2.CAP_PROP_POS_FRAMES,4000)\n\ttt = True\n\twhile(tt):\n\t\ttt,ff = vidreader.read()\n\t\t# gray = cv2.cvtColor(ff,cv2.COLOR_BGR2GRAY)\n\t\t# rsz = cv2.resize(gray,(400,400))\n\t\t# rsz = rsz/255\n\t\tgray2 = cv2.cvtColor(ff[60:],cv2.COLOR_BGR2GRAY)\n\t\tmain_image_shape = gray2.shape\n\t\tgray = cv2.resize(gray2,(int(gray2.shape[1]/16),int(gray2.shape[0]/16)))\n\t\tret,thresh = cv2.threshold(gray,1,255,cv2.THRESH_BINARY)\n\t\tsum_mid_vert = np.sum(thresh[:,int(gray.shape[1]/2)])\n\t\tsum_mid_hori = np.sum(thresh[int(gray.shape[0]/2),:])\n\t\t# print(sum_mid_hori)\n\t\twsz = 0\n\t\tsplitimg_bool = False\n\t\trightsplit_bool = False\n\t\tif sum_mid_vert < 2000 and sum_mid_hori > 5000:\n\t\t\tprint(\"split\")\n\t\t\tsplitimg_bool = True\n\t\t\tout2 = gray2[:,int(gray2.shape[1]/2):]\n\t\t\tout = gray2[:,:int(gray2.shape[1]/2)]\n\t\t\t\t# print(out.shape)\n\t\t\twsz = out.shape[1]\n\t\t\t# print(out.shape)\n\t\t\tvert_gap = int((out.shape[0]-wsz)/2)\n\t\t\thori_gap = int((out.shape[1]-wsz)/2)\n\t\t\tout = out[vert_gap:vert_gap+wsz,hori_gap:hori_gap+wsz]\n\t\t\tout2 = out2[vert_gap:vert_gap+wsz,hori_gap:hori_gap+wsz]\n\t\t\tout = cv2.resize(out,(400,400))\n\t\t\tout2 = cv2.resize(out2,(400,400))\n\t\t\t# output = sess.run(conv_out,feed_dict={input_image:[out/255,out2/255]})\n\t\t\toutput = sess.run(deconv_out,feed_dict={input_image:[out/255,out2/255]})\n\t\t\toutleft = output[0]\n\t\t\toutright = output[1]\n\t\t\toutimg = getMapImage(outleft)\n\t\t\toutimg2 = getMapImage(outright)\n\t\t\tprint(outimg.shape)\n\t\t\tcv2.imshow(\"img\",out)\n\t\t\tcv2.imshow(\"img2\",out2)\n\t\t\tcv2.imshow(\"outimg\",outimg)\n\t\t\tcv2.imshow(\"outimg2\",outimg2)\n\t\t\t# cv2.imshow(\"output2\",out2)\n\t\t\tqq = cv2.waitKey(10)\n\t\telse:\n\t\t\t# print(\"single\")\n\t\t\tout = gray2\n\t\t\t# print(out.shape)\n\t\t\twsz = 600\n\t\t\tvert_gap = int((out.shape[0]-wsz)/2)\n\t\t\thori_gap = int((out.shape[1]-wsz)/2)\n\t\t\tout = out[vert_gap:vert_gap+wsz,hori_gap:hori_gap+wsz]\n\t\t\tout = cv2.resize(out,(400,400))\n\t\t\toutput = sess.run(deconv_out,feed_dict={input_image:[out/255]})\n\t\t\toutleft = output[0]\n\t\t\toutimg = getMapImage(outleft)\n\t\t\tprint(outimg.shape)\n\t\t\tcv2.imshow(\"img\",out)\n\t\t\tcv2.imshow(\"outimg\",outimg)\n\t\t\tcv2.imshow(\"img\",out)\n\t\t\tqq = cv2.waitKey(10)\n\t\tif qq == ord('q'):\n\t\t\tvidreader.release()\n\t\t\tbreak\n\t# exit()\n\n\n\n\n\t\n\t# output = sess.run(deconv5,feed_dict={input_image:[rsz]})\n\t# cv2.imshow(\"img\",gray)\n\t# cv2.imshow(\"img2\",output[0])\n\t# cv2.waitKey(0)\n\t# output = sess.run(conv5,feed_dict={input_image:[rsz]})\n\t# print(output.shape)\n\t# conv5_filtermap = np.zeros((),dtype=np.float32)\n\t# for i in range(output.shape[3]):\n\t# \tactv = output[0,:,:,i]\n\t# \tcv2.imshow(\"img\",gray)\n\t# \tcv2.imshow(\"img2\",cv2.resize(actv,(400,400)))\n\t# \tcv2.waitKey(0)\n\t# cv2.destroyAllWindows()\n\t\n\n","sub_path":"visualize_trained_models/visual_encoder2.py","file_name":"visual_encoder2.py","file_ext":"py","file_size_in_byte":5880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"233017202","text":"a=input().split(' ')\nnum=int(a[0])\npaox=int(a[1])\npaoy=int(a[2])\ntargets=[]\nfor i in range(0,num):\n x=input().split(' ')\n x=list(map(int,x))\n targets.append(x)\nif (targets[0][1]-paoy)!=0:\n temp = (targets[0][0]-paox)/(targets[0][1]-paoy)\nelse: \n temp=(targets[0][1]-paoy)/(targets[0][0]-paox)\nline = 1\nfor i in range(1,num):\n if (targets[i][1]-paoy)!=0:\n if (targets[i][0]-paox)/(targets[i][1]-paoy)==temp:\n line+=1\n else:\n if(targets[i][1]-paoy)/(targets[i][0]-paox)==temp:\n line+=1\nif(1+num-line)!=7:\n print(1+num-line)\nelse:\n print(8)\n","sub_path":"Code/CodeRecords/2890/60727/259829.py","file_name":"259829.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"551404441","text":"import argparse\nfrom time import time\nimport time\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nfrom sklearn.model_selection import train_test_split\nfrom torch.utils.data import DataLoader\nfrom model import MultiLayerPerceptron\nfrom dataset import AdultDataset\nfrom util import *\nimport matplotlib.pyplot as plt\nimport torch\n\n\nseed = 67\ntorch.manual_seed(seed)\n\n# =================================== LOAD DATASET =========================================== #\n\n\ndata = pd.read_csv('./data/adult.csv',sep='/n',delimiter=',')\n\nprint ('shape ',data.shape)\nprint ('columns ',data.columns)\nverbose_print(data.head())\nprint(data[\"income\"].value_counts())\n\n\n# =================================== DATA CLEANING =========================================== #\n\n# Missing values are indicated with the symbol \"?\" in the dataset\n\n# Count how many missing entries there are for each feature\ncol_names = data.columns\nnum_rows = data.shape[0]\nfor feature in col_names:\n\n print (feature,data[feature].isin([\"?\"]).sum())\n\n\n\n# throw out all rows (samples) with 1 or more \"?\"\n\ndata__cleaned=data[data[\"workclass\"] != \"?\"]\ndata__cleaned=data__cleaned[data__cleaned[\"occupation\"] != \"?\"]\ndata__cleaned=data__cleaned[data__cleaned[\"native-country\"] != \"?\"]\n\nprint('new shape ',data__cleaned.shape)\nprint('number left out ',data__cleaned.shape[0]-data.shape[0])\n\n\n\n\n# =================================== BALANCE DATASET =========================================== #\n\nhigh=data__cleaned[data__cleaned[\"income\"]== \">50K\"]\nlow=data__cleaned[data__cleaned[\"income\"]== \"<=50K\"]\nmin=min(high.shape[0],low.shape[0])\n#print(min)\nhigh=high.sample(n=min,random_state=seed)\nlow=low.sample(n=min,random_state=seed)\ndata_balanced=pd.concat([high,low])\n#print(data_balanced.shape)\n\n\n# =================================== DATA STATISTICS =========================================== #\n\n\nprint(\"visualizing\")\ndes=data_balanced.describe()\nverbose_print(des)\n\ncategorical_feats = ['workclass', 'race', 'education', 'marital-status', 'occupation',\n 'relationship', 'gender', 'native-country', 'income']\n\nfor feature in categorical_feats:\n print(\"feature \", feature)\n print(data_balanced[feature].value_counts())\n\n\n\n\n#rast 3 features using pie and bar graphs\n\n#pie_chart(data_balanced, 'workclass')\n#pie_chart(data_balanced, 'race')\n#pie_chart(data_balanced, 'education')\n\n#binary_bar_chart(data_balanced, 'workclass')\n#binary_bar_chart(data_balanced, 'race')\n#binary_bar_chart(data_balanced, 'education')\n#binary_bar_chart(data_balanced, 'relationship')\n\n\n# =================================== DATA PREPROCESSING =========================================== #\n\n# NORMALIZE CONTINUOUS FEATURES\n\nage=data_balanced[\"age\"].values\nfnlwgt=data_balanced[\"fnlwgt\"].values\neducational_num=data_balanced[\"educational-num\"].values\ncapital_gain=data_balanced[\"capital-gain\"].values\ncapital_loss=data_balanced[\"capital-loss\"].values\nhours_per_week=data_balanced[\"hours-per-week\"].values\n\nage=(age-age.mean())/age.std()\nfnlwgt=(fnlwgt-fnlwgt.mean())/fnlwgt.std()\neducational_num=(educational_num-educational_num.mean())/educational_num.std()\ncapital_gain=(capital_gain-capital_gain.mean())/capital_gain.std()\ncapital_loss=(capital_loss-capital_loss.mean())/capital_loss.std()\nhours_per_week=(hours_per_week-hours_per_week.mean())/hours_per_week.std()\n\ndata_balanced=data_balanced.drop(columns=[\"age\",\"fnlwgt\",\"educational-num\",\"capital-gain\",\"capital-loss\",\"hours-per-week\"])\n\n# Represent categorical features as 1-hot encodings\n\n\nlabel_encoder = LabelEncoder()\n#print(data_balanced[\"income\"])\ndata_balanced=data_balanced.apply(label_encoder.fit_transform)\n#print(data_balanced)\nincome=data_balanced[\"income\"].values\n#print('income ',income)\n#print('type of income ' ,type(income))\n#print(income.shape)\n\n#print('labeled ', data_balanced.shape)\n\n\n\ndata_balanced=data_balanced.drop(columns=[\"income\"])\n#print('income dropped ',data_balanced.shape)\noneh_encoder = OneHotEncoder()\ndata_balanced=oneh_encoder.fit_transform(data_balanced).toarray()\n\n#print('onehot ',data_balanced.shape)\n\n\ndata_balanced=pd.DataFrame(data_balanced)\ndata_balanced=pd.concat([data_balanced,pd.DataFrame(age)],axis=1)\ndata_balanced=pd.concat([data_balanced,pd.DataFrame(fnlwgt)],axis=1)\ndata_balanced=pd.concat([data_balanced,pd.DataFrame(educational_num)],axis=1)\ndata_balanced=pd.concat([data_balanced,pd.DataFrame(capital_gain)],axis=1)\ndata_balanced=pd.concat([data_balanced,pd.DataFrame(capital_loss)],axis=1)\ndata_balanced=pd.concat([data_balanced,pd.DataFrame(hours_per_week)],axis=1)\nprint(data_balanced.shape)\n#print(data_balanced)\ndata_balanced=data_balanced.values\n\nprint(type(data_balanced))\n\n\n\n# train-validastion split\n\nfeat_train,feat_val,label_train,label_val=train_test_split(data_balanced,income,test_size=0.2,random_state=seed)\nprint(feat_train.shape)\nprint(feat_val.shape)\nprint(label_train.shape)\nprint(label_val.shape)\n\n# =================================== LOAD DATA AND MODEL =========================================== #\n\ndef load_data(batch_size):\n train_dataset=AdultDataset(feat_train,label_train)\n val_dataset=AdultDataset(feat_val,label_val)\n train_loader=DataLoader(train_dataset, batch_size=batch_size,shuffle=True)\n val_loader=DataLoader(val_dataset, batch_size=batch_size,shuffle=False)\n\n return train_loader, val_loader\n\n\ndef load_model(lr,func):\n\n if func=='tanh':\n\n\n model=MultiLayerPerceptron(103,'tanh')\n\n if func=='relu':\n\n model=MultiLayerPerceptron(103,'relu')\n if func == 'sigmoid':\n model =MultiLayerPerceptron(103,'sigmoid')\n\n loss_fnc=torch.nn.BCELoss()\n optimizer=torch.optim.SGD(model.parameters(),lr=lr)\n\n\n\n return model, loss_fnc, optimizer\n\n\ndef evaluate(model, val_loader):\n total_corr = 0\n\n for i,vbatch in enumerate(val_loader):\n feats, label = vbatch\n feats = feats.float()\n prediction = model(feats)\n corr = (prediction > 0.5).squeeze().long() == label\n total_corr += int(corr.sum())\n\n\n return float(total_corr)/len(val_loader.dataset)\n\ndef plot_graph(type,x,y,name,batch,lr,epoch):\n\n plt.figure()\n type_title = \"Validation Accuracy\" if type == \"val\" else \"train Accuracy\"\n plt.title(\"{} over gradient steps\".format(type_title))\n plt.plot(x,y)\n\n plt.xlabel(\"Gradient Steps\")\n plt.ylabel(type_title)\n #plt.legend(loc='best')\n plt.savefig(\"{}_{}_batchsize{}_lr{}_epoch{}.png\".format(type, name,batch,lr,epoch))\n\n return\n\n\ndef plot_graph_2(x,y,y2,name,batch,lr,epoch):\n\n plt.figure()\n type_title = \"Train and Validation Accuracy\"\n plt.title(\"{} over gradient steps\".format(type_title))\n plt.plot(x,y,label=\"Train\")\n plt.plot(x,y2,label=\"Validation\")\n\n plt.xlabel(\"Gradient Steps\")\n plt.ylabel(\"accuracy\")\n plt.legend(loc='best')\n plt.savefig(\"{}_{}_batchsize{}_lr{}_epoch{}.png\".format(\"train&val\", name,batch,lr,epoch))\n\n return\n\ndef plot_graph_3(x,y,y2,name,batch,lr,epoch):\n\n plt.figure()\n type_title = \"Train and Validation Accuracy\"\n plt.title(\"{} vs Time\".format(type_title))\n plt.plot(x,y,label=\"Train\")\n plt.plot(x,y2,label=\"Validation\")\n\n plt.xlabel(\"time in seconds\")\n plt.ylabel(\"accuracy\")\n plt.legend(loc='best')\n plt.savefig(\"time_{}_{}_batchsize{}_lr{}_epoch{}.png\".format(\"train&val\", name,batch,lr,epoch))\n\n return\n\n\ndef main():\n\n\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--batch_size', type=int)\n parser.add_argument('--lr', type=float)\n parser.add_argument('--epochs', type=int)#, default=20\n parser.add_argument('--eval_every', type=int)#, default=10\n parser.add_argument('--function',type=str)#,default='tanh')\n\n args = parser.parse_args()\n n=0\n N=0\n n_list = []\n val_accuracy_list = []\n last_n_list = []\n train_accuracy_list = []\n new_train_accuracy_list = []\n time_list=[]\n train_loader, val_loader = load_data(args.batch_size)\n\n\n model, loss_fnc, optimizer = load_model(args.lr,args.function)\n tot = 0\n tot_corr = 0\n\n start = time.time()\n\n for epoch in range(args.epochs):\n print('epoch: ',epoch)\n\n accum_loss = 0\n tot_corr = 0\n tot = 0\n\n\n for i, batch in enumerate(train_loader):\n\n feats, label = batch\n #print(feats.shape[0], 'feat shape')\n #print(label.shape, 'label shape')\n optimizer.zero_grad()\n feats=feats.float()\n predictions = model(feats)\n batch_loss = loss_fnc(input=predictions.squeeze(),target = label.float())\n accum_loss += batch_loss\n batch_loss.backward()\n optimizer.step()\n N=N+1\n n=n+1\n\n tot = tot + feats.shape[0]\n corr = (predictions > 0.5).squeeze().long() == label\n\n tot_corr += int(corr.sum())\n\n\n if epoch==(args.epochs-1):\n\n last_n_list.append(n)\n train_accuracy_list.append(tot_corr/tot)\n\n\n\n if N == (args.eval_every):\n val_accuracy=evaluate(model,val_loader)\n print('accuracy: ',val_accuracy)\n print('loss: ',accum_loss)\n print('num of correct prediction: ',tot_corr, 'tot ',tot)\n #print('n: ', n)\n #print('N ', N)\n n_list.append(n)\n #print('n list length: ', len(n_list))\n val_accuracy_list.append(val_accuracy)\n\n ##############\n new_train_accuracy_list.append(tot_corr/tot)\n\n curr_time=time.time()\n\n time_list.append(curr_time-start)\n\n\n #print(new_train_accuracy_list)\n N=0\n\n\n last_n_list=last_n_list[-10:]\n train_accuracy_list=train_accuracy_list[-10:]\n\n print(last_n_list, 'last n list')\n\n\n\n #df = pd.DataFrame({\"last_n\": last_n_list, \"train_accuracy\": train_accuracy_list})\n #df.to_csv(\"train_accuracy_{}_{}_{}.csv\".format(args.batch_size,args.lr,args.epochs))\n\n #df = pd.DataFrame({\"n\": n_list, \"val_accuracy\": val_accuracy_list})\n #df.to_csv(\"val_accuracy_{}_{}_{}.csv\".format(args.batch_size, args.lr, args.epochs))\n\n\n\n end = time.time()\n\n #print('total time: ',end-start)\n\n df = pd.DataFrame({\"n\": n_list,\"val_accuracy\": val_accuracy_list, \"train_accuracy\": new_train_accuracy_list})\n df.to_csv(\"ac99_sigmoid_train&val_{}_{}_{}.csv\".format(args.batch_size, args.lr, args.epochs))\n\n df = pd.DataFrame({\"time\": time_list, \"val_accuracy\": val_accuracy_list, \"train_accuracy\": new_train_accuracy_list})\n df.to_csv(\"ac99_sigmoid_time_{}_{}_{}.csv\".format(args.batch_size, args.lr, args.epochs))\n\n\n highest=max(val_accuracy_list)\n print('highest val accuracy: ',highest)\n print(args.batch_size,' ', args.lr,' ', args.epochs)\n #print(train_accuracy_list,' list')\n #print(last_n_list,' last n')\n #print(n_list, \"n list\")\n\n #####################\n #plot_graph_2(n_list, new_train_accuracy_list, val_accuracy_list, 'last_q_original', args.batch_size,args.lr,args.epochs)\n plot_graph_3(time_list, new_train_accuracy_list, val_accuracy_list, 'ac99_original', args.batch_size, args.lr, args.epochs)\n\n #plot_graph('val', n_list, val_accuracy_list, 'orignal',args.batch_size,args.lr,args.epochs)\n #plot_graph('train',last_n_list,train_accuracy_list,'original',args.batch_size,args.lr,args.epochs)\n\n\nif __name__ == \"__main__\":\n\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"474613747","text":"import numpy as np\nimport ray \nfrom ray.tune.logger import pretty_print\nfrom ray.rllib.models.tf.misc import normc_initializer\nfrom ray.rllib.models import ModelCatalog\nfrom ray.rllib.agents.dqn import DQNTrainer\nfrom ray.rllib.agents.dqn import ApexTrainer\nfrom ray.rllib.models.tf.tf_modelv2 import TFModelV2\n\nimport gym\nfrom gym.spaces import Discrete, Box\nimport requests\nimport tensorflow as tf\nimport tensorflow.keras.metrics\nimport tensorflow.keras.losses\nimport pandas as pd\n# import modin.pandas as pd\nimport json\nimport numpy as np\n\nimport os \n\nurl ='34.82.238.59'\n# data = pd.read_csv('/home/rkchee/nxtopinion/rl/rheumatology_4199362_batch_results.csv')[0:5]\n\n# train test split\n# sheets_cards = pd.read_excel('../training dataset - medical.xlsx', sheet_name='Cardiology and Infectious Disea')\n# cardiology = sheets_cards.copy()\n# train_set = cardiology.sample(frac=0.001, random_state=0)\n# train_set.to_csv('train_set.csv', index=False)\n# test_set = cardiology.drop(train_set.index)\n# test_set.to_csv('test_set.csv', index=False)\n\n# set the training data \n# data = pd.read_csv('train_set.csv')\n# data = pd.DataFrame(sheets_cards)[0:10]\n\nimport dask\nimport dask.dataframe as dd\nfrom dask.delayed import delayed\nimport dask.array as da\n\n\n\n# data = dd.read_csv('training dataset - medical.xlsx', sheet_name='Cardiology and Infectious Disea')\nparts = dask.delayed(pd.read_excel)('../training_medical.xlsx', sheet_name='Cardiology and Infectious Disea')\ndata = dd.from_delayed(parts)\n\n\ndef sequence(seq):\n if not type(seq) == str:\n seq = str(seq)\n \n js = {\n \"text\":seq\n }\n\n dumps = json.dumps(js)\n payload = json.loads(dumps)\n headers = {\"content-type\": \"application/json\"}\n response = requests.post(\"http://\" + url + \":8000/electratensors\", json=payload, headers=headers)\n t = response.text \n t = json.loads(t)\n t = t['Electra_Tensors']\n return np.asarray(t)\n\n@dask.delayed\ndef form_matrix(qa_index, question):\n matrix_max_size = 10\n matrix = []\n\n mc_choices = [\"A\", \"B\", \"C\", \"D\", \"E\"]\n\n matrix = question\n for letter in mc_choices:\n answer = data['Answer.answer' + letter].loc[qa_index]\n answer = sequence(answer)\n matrix = np.concatenate((matrix, answer), axis=0)\n \n matrix = np.squeeze(matrix)\n state_matrix = np.pad(matrix, [(0, matrix_max_size - matrix.shape[0]), (0,0), (0,0)])\n state_matrix = np.moveaxis(state_matrix, 0, 2)\n return state_matrix\n\nnum_questions = len(data.index)\nprint(num_questions)\n\n\n\n# nrows, ncols = num_questions, 2\n# f = np.memmap('memmapped.dat', dtype=object,\n# mode='w+', shape=(nrows, ncols))\n\nanswers = data['Answer.image.label']\n\n\nmcq_number ={\n 'A': 0,\n 'a': 0,\n 'B': 1,\n 'b': 1,\n 'C': 2,\n 'c': 2,\n 'D': 3,\n 'd': 3,\n 'E': 4,\n 'e': 4,\n 'F': 5,\n 'f': 5,\n 'G': 6,\n 'g': 6,\n 'H': 7,\n 'h': 7,\n 'I': 8,\n 'i': 8,\n 'J': 9,\n 'j': 9, \n} \n\n# f = pd.DataFrame(columns=[0])\n# # f[0]= f[0].astype(object) \n\n\n# dask_array = dask.delayed(np.ones)((128,256,10))\n# dask_array = da.from_delayed(dask_array, (128, 256, 10), dtype=float)\n\nf =[]\n\n\nfor i in data.index:\n# def create_matrix()\n q = data['Answer.question'].loc[i]\n # obs = sequence(obs)\n # df.map_partitions(train)\n obs = dask.delayed(sequence)(q)\n # obs = q.map_partitions(sequence)\n state = dask.delayed(form_matrix)(i, obs)\n # state = obs.map_partitions(form_matrix, i)\n f.append(state)\n\nimport dask.bag as db\n\n\nif __name__ == '__main__':\n\n f = dask.persist(f[1])\n f = dask.compute(f)\n # b = db.from_sequence(f)\n # df = b.to_dataframe()\n print(f)\n c = dask.persist(f)\n c = dask.compute(f)\n print(c)\n\n\n\n","sub_path":"test/test-mmap.py","file_name":"test-mmap.py","file_ext":"py","file_size_in_byte":3722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"100050891","text":"import datetime\nimport sys\nimport threading\nimport time\n\nfrom oslo_config import cfg\nfrom oslo_log import log as logging\n\nfrom edgeservice.common import service\nfrom edgeservice.controller.auth_manager import aksk_refresh\nfrom edgeservice.tools import etcd_client\n\nCONF = cfg.CONF\nLOG = logging.getLogger(__name__)\nLOCK_NAME = \"/edge_1/auth_manager\"\niam_client_thread_event = threading.Event()\nrenew_thread_event = threading.Event()\n\n\ndef refresh_aksk_db(aksk_update):\n interval = CONF.auth_manager.ak_sk_refresh_seconds\n while True:\n if not iam_client_thread_event.is_set():\n aksk_update.refresh_aksk_db()\n iam_client_thread_event.wait(interval)\n\n\ndef main():\n service.prepare_service(sys.argv)\n\n timestamp = str(datetime.datetime.utcnow())\n LOG.info(\"Starting Auth manager at %s\", timestamp)\n\n etcd_client.get_lock(LOCK_NAME)\n LOG.info(\"Worker get auth_manager_lock, now working.\")\n\n aksk_update = aksk_refresh.AKSKRefresh()\n db_refresh_aksk_thread = threading.Thread(target=refresh_aksk_db,\n args=(aksk_update,))\n db_refresh_aksk_thread.daemon = True\n db_refresh_aksk_thread.start()\n\n renew_thread = threading.Thread(target=etcd_client.renew_lock,\n args=(LOCK_NAME, iam_client_thread_event,\n renew_thread_event, 60, 30))\n renew_thread.daemon = True\n renew_thread.start()\n\n try:\n while True:\n time.sleep(1)\n except KeyboardInterrupt:\n LOG.info(\"Attempting to gracefully terminate Auth manager.\")\n iam_client_thread_event.set()\n db_refresh_aksk_thread.join()\n LOG.info(\"Auth-manager process terminated\")\n\n # Stop renew thread before release cts proxy lock\n renew_thread_event.set()\n renew_thread.join()\n LOG.info(\"Renew thread process terminated\")\n","sub_path":"thread.py","file_name":"thread.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"167312456","text":"import httplib\nfrom slugify import slugify\nfrom flask import request\nfrom flask import abort as flask_abort\nfrom flask.json import jsonify\nfrom ..auth.roles import user_required\nfrom ..auth.models import User\nfrom .hardware_type import HardwareType\nfrom .models import Lab\nfrom .models import Object\nfrom .servers import Server\n\nclass Cluster(HardwareType):\n TYPE_VENDOR = 'builtin'\n TYPE_NAME = 'cluster'\n\n @classmethod\n def display_name(cls):\n return 'Cluster'\n\n @classmethod\n def allow_ownership(cls):\n return True\n\n @classmethod\n def register_api(cls, app_or_blueprint, url_prefix):\n @app_or_blueprint.route(url_prefix, methods=['POST'])\n @user_required\n def create_cluster():\n lab_id = request.json['lab_id']\n display_name = request.json['display_name']\n slug = slugify(display_name)\n if Lab.query.get(lab_id) is None:\n flask_abort(httplib.NOT_FOUND, 'No lab with id={!r}'.format(lab_id))\n cluster = cls.get_by_slug_and_lab(slug, lab_id)\n if cluster is not None:\n flask_abort(httplib.CONFLICT, 'Cluster slug {!r} already in use'.format(slug))\n cluster = cls.create(slug=slug, display_name=display_name, lab_id=lab_id)\n cluster.save()\n return jsonify(cluster.as_dict()), httplib.CREATED\n\n @app_or_blueprint.route(url_prefix + '/<cluster_id>', methods=['DELETE'])\n @user_required\n def delete_cluster(cluster_id):\n cluster = cls.get_by_id(cluster_id)\n if cluster is None:\n flask_abort(httplib.NOT_FOUND, 'No cluster with id {!r}'.format(cluster_id))\n if cluster.type_key != cls.type_key():\n flask_abort(httplib.NOT_FOUND, 'No cluster with id {!r}'.format(cluster_id))\n cluster.delete()\n return jsonify(cluster.as_dict()), httplib.NO_CONTENT\n\n def _get_lab(lab_slug):\n lab = Lab.get_by_slug(lab_slug)\n if lab is None:\n flask_abort(httplib.NOT_FOUND, 'Unknown lab {!r}'.format(lab_slug))\n return lab\n\n def _get_cluster(lab, cluster_slug):\n cluster = cls.get_by_slug_and_lab(cluster_slug, lab.id)\n if cluster is None:\n flask_abort(httplib.NOT_FOUND, 'Unknown cluster {!r}'.format(cluster_slug))\n return cluster\n\n @app_or_blueprint.route(url_prefix + '/<lab_slug>/<cluster_slug>/config.json')\n @user_required\n def cluster_config(lab_slug, cluster_slug):\n lab = _get_lab(lab_slug)\n cluster = _get_cluster(lab, cluster_slug)\n servers = tuple(server.as_dict() for server in Object.query.filter(\n dict(lab_id=lab.id, type_key=Server.type_key(), cluster_id=cluster.id)))\n ownerships = tuple(dict(owner_id = ownership['owner_id'],\n obtained_at = ownership['obtained_at'],\n username = User.query.get(ownership['owner_id'])['username'])\n for ownership in cluster['ownerships'])\n config = dict(\n id = cluster['id'],\n slug = cluster['slug'],\n display_name = cluster['display_name'],\n servers = servers,\n ownerships = ownerships,\n lab = dict(\n id = lab['id'],\n slug = lab['slug'],\n display_name = lab['display_name'],\n ),\n )\n return jsonify(config)\n","sub_path":"src/labsome/backend/hardware/clusters.py","file_name":"clusters.py","file_ext":"py","file_size_in_byte":3664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"594897712","text":"import json\n\nfrom datetime import datetime\n\nimport requests\n\nfrom dadd.master import app\nfrom dadd.master.utils import get_session\n\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom sqlalchemy.dialects.postgresql import JSON\nfrom sqlalchemy.schema import UniqueConstraint\nfrom sqlalchemy.orm import relationship, backref\n\n\ndb = SQLAlchemy(app)\n\n\nclass Process(db.Model):\n\n __tablename__ = 'processes'\n\n id = db.Column(db.Integer, primary_key=True)\n pid = db.Column(db.Integer)\n spec = db.Column(JSON, nullable=False)\n host_id = db.Column(db.Integer, db.ForeignKey('hosts.id'))\n host = relationship('Host', backref=backref('procs'),\n cascade='all, delete')\n\n logfile_id = db.Column(db.Integer, db.ForeignKey('logfiles.id'))\n logfile = relationship('Logfile', backref=backref('process'))\n\n start_time = db.Column(db.DateTime, default=datetime.now)\n end_time = db.Column(db.DateTime)\n\n state = db.Column(db.Enum(\n 'init', 'setup', 'running', 'failed', 'success',\n name='proc_state'\n ))\n\n def as_dict(self):\n return {\n 'id': self.id,\n 'pid': self.pid,\n 'spec': self.spec,\n 'host': self.host.as_dict() if self.host else '',\n # TODO: Use flask url generation\n 'logfile': '/api/procs/%s/logfile/' % self.id,\n 'start_time': self.start_time,\n 'end_time': self.end_time,\n 'state': self.state,\n 'update_state_uri': '/api/procs/%s/<state>/' % self.id\n }\n\n @classmethod\n def create(cls, spec):\n \"\"\"\n Create a new process on a host.\n\n This will keep trying to start the process on a host until\n there are no hosts left to try. The Host.find_available SHOULD\n remove bad hosts that have shutdown or died so that this\n doesn't loop forever.\n \"\"\"\n try:\n host = Host.find_available()\n except Exception as e:\n app.logger.error(e.message)\n return None\n\n # Create our process in the DB\n proc = cls(spec=spec, host=host)\n db.session.add(proc)\n db.session.commit()\n\n # Add the ID to the spec\n spec['process_id'] = proc.id\n\n try:\n sess = get_session()\n # Try creating the process via the host\n url = 'http://%s/run/' % str(host)\n app.logger.debug('Creating app on host: %s' % url)\n resp = sess.post(url, data=json.dumps(spec),\n allow_redirects=False)\n resp.raise_for_status()\n\n # Save the pid\n result = resp.json()\n except requests.exceptions.HTTPError:\n return cls.create(spec)\n except requests.exceptions.ConnectionError as e:\n app.logger.error(e)\n return None\n\n # Add our process id returned from the worker and re-save our\n # spec. Re-saving the spec ensures we passed the DB id to the\n # worker when starting the process.\n proc.pid = result['pid']\n proc.spec = spec\n db.session.add(proc)\n db.session.commit()\n\n return proc\n\n\nclass Host(db.Model):\n __tablename__ = 'hosts'\n __table_args__ = (\n UniqueConstraint('host', 'port'),\n )\n\n id = db.Column(db.Integer, primary_key=True)\n host = db.Column(db.String, nullable=False)\n port = db.Column(db.Integer, nullable=False)\n\n def __str__(self):\n return '%s:%s' % (self.host, self.port)\n\n def as_dict(self):\n return {\n 'id': self.id,\n 'host': self.host,\n 'port': self.port\n }\n\n @classmethod\n def find_available(cls):\n procs = 0\n current_host = None\n for host in db.session.query(cls).all():\n if not current_host:\n current_host = host\n\n num_procs = len(host.procs)\n\n # If we have a host without any proces we'll use that right\n # off the back.\n if num_procs == 0:\n break\n\n if num_procs >= procs:\n current_host = host\n\n if not current_host:\n raise Exception('No workers available!')\n\n # See if the host is up and running. If not let's delete it.\n try:\n resp = requests.get('http://%s/up/' % str(current_host),\n allow_redirects=False)\n\n # Check explicitly for a specific message in order to\n # easily filter out hosts that might have been taken over\n # by some other process at that port.\n assert resp.json()['worker_status'] == 'available'\n return current_host\n except Exception:\n db.session.delete(host)\n db.session.commit()\n return cls.find_available()\n\n\nclass Logfile(db.Model):\n __tablename__ = 'logfiles'\n\n id = db.Column(db.Integer, primary_key=True)\n content = db.Column(db.Text)\n added_time = db.Column(db.DateTime, default=datetime.now)\n","sub_path":"dadd/master/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"245730715","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Apr 10 23:28:59 2021\r\n\r\n@author: ntuse\r\n\r\n\"\"\"\r\n\"\"\"Task:1 Importing the required packages\"\"\"\r\n\r\n# importing the required packages for the simple classification\r\n\r\n# to work with dataframes we import pandas\r\nimport pandas as pd\r\n\r\n# to work with matrices we import numpy\r\nimport numpy as np\r\n\r\n#to work with visualiztion plots we import seaborn\r\nimport seaborn as sns\r\n\r\n#to partition the data\r\nfrom sklearn.model_selection import train_test_split\r\n\r\n# to get the Logistic Regression\r\nfrom sklearn.linear_model import LogisticRegression\r\n\r\n#importing the perfomance metrices,accuracyscore\r\nfrom sklearn.metrics import accuracy_score,confusion_matrix\r\n\r\n\"\"\"Step:2 - Importing the Data\"\"\"\r\ndata_income = pd.read_csv(\"D:\\study&work\\income(1).csv\")\r\n\r\n# creating a copy of data\r\ndata=data_income.copy()\r\n\r\n\"\"\"Task2: \r\n #Exploring the data analysis:\r\n ->1.Getting to know the data\r\n ->2.Data preprocessing(Missing values)\r\n ->3.Cross tables and data visualization\r\n\r\n\"\"\"\r\n## getting to know the data\r\n# To chech the variable datatypes\r\n\r\nprint(data.info())\r\n\r\n\r\n# To check the missing values we use the method isnull() or isna()\r\n\r\ndata.isnull()\r\n\r\n# to get the no. of missing values in the attribute or column\r\n\r\nprint(\"Data columns with null values:'n\",data.isnull().sum())\r\n\r\n# @@@@ no missing values!\r\n\r\n#!!!!! Summary of numerical variables\r\n\r\nsummary_num = data.describe()\r\nprint(summary_num)\r\n\r\n# Summary of categorical values\r\nsummary_cat=data.describe(include=\"O\")\r\nprint(summary_cat)\r\n\r\n#Frequency of each categories\r\n\r\ndata['JobType'].value_counts()\r\ndata['occupation'].value_counts()\r\n\r\n# checking for unique classes and unique is a numpy method\r\nprint(np.unique(data['JobType']))\r\nprint(np.unique(data['occupation']))\r\n\r\n\"\"\"\r\nGo back and read the data by including \"na_values['?']\r\n\"\"\"\r\ndata =pd.read_csv(\"D:\\study&work\\income(1).csv\",na_values=[\" ?\"])\r\n\r\n######################################################\r\n# Data preprocessing\r\n######################################################\r\nprint(data.isnull().sum())\r\n\r\nmissing =data[data.isnull().any(axis=1)]\r\n#axis => to consider atleast one column value is missing\r\n\r\n\"\"\"\r\nPoints to note:\r\n 1.missing values in Job type =1809\r\n 2.Missing values in Occupation=1816\r\n 3.There are 1809 rows where two specific columns i.e., occupation & jobtype have missing values\r\n 4.(1816-1809) =7 => You still have occupation unfilled for these 7 rows.because jobtype is never worked\r\n \"\"\"\r\ndata1=data.dropna(axis=0)\r\n\r\n# to see the relationship of independent variables\r\ncorrelation_val=data1.corr()\r\n\r\n######################################################\r\n# Cross tables & Data Visualization\r\n#####################################################\r\n\r\n# Exctracting the column names:\r\ndata1.columns\r\n\r\n\r\n#####################3\r\n# Gender Proportion table\r\ngender=pd.crosstab(index=data1['gender'],columns='count',normalize=True)\r\nprint(gender) \r\n\r\n#####checking gender to salary relationship\r\n\r\ngender_sal=pd.crosstab(index=data1['gender'],columns=data1['SalStat'],margins=True,normalize='index')\r\nprint(gender_sal)\r\n\r\n##################################################################\r\n#Frequency distribution of Salary status'\r\n#################################################################\r\nSalStat=sns.countplot(data1['SalStat'])\r\n\r\n\r\n\"\"\"\r\n75% of people's salary status is <-50,000\r\n& 25% of people's salary status is >50,000\r\n\"\"\"\r\n\r\n###############################################################\r\nsns.distplot(data1['age'],bins=10,kde=False)\r\n## it seems that people with age group 20-40 are in more\r\nsns.boxplot('SalStat','age',data=data1)\r\ndata1.groupby('SalStat')['age'].median()\r\n##### people with age group 35-50 are likely to earn >50000\r\n#####people with age group 25-45 are likely to earn<= 50000\r\n\r\n#########################################################################3\r\n##LOGISTIC REGRESSION\r\n##########################################################################33\r\n\r\n#Reindexing the salary status names to 0,1\r\n\r\ndata1=data.dropna(axis=0)\r\ndata1['SalStat']=data1['SalStat'].map({' less than or equal to 50,000':0,' greater than 50,000':1})\r\nprint(data1['SalStat'])\r\n\r\nnew_data=pd.get_dummies(data1,drop_first=True)\r\n\r\n# storting the columnn values\r\ncolumn_list=list(new_data.columns)\r\nprint(column_list)\r\n\r\n#Seperating the input names from data\r\nfeatures=list(set(column_list)-set(['SalStat']))\r\nprint(features)\r\n\r\n#Storing the output values iun y\r\ny=new_data['SalStat'].values\r\nprint(y)\r\n\r\n\r\n# storing the values from input features\r\nx=new_data[features].values\r\nprint(x)\r\n\r\n# Splitting the data into train and test\r\ntrain_x,test_x,train_y,test_y=train_test_split(x,y,test_size=0.3,random_state=0)\r\n\r\n# make an instance of the model\r\nlogistic=LogisticRegression()\r\n\r\n# Fitting the values for x and y\r\nlogistic.fit(train_x,train_y)\r\nlogistic.coef_\r\nlogistic.intercept_\r\n\r\n# prediction from test data\r\nprediction = logistic.predict(test_x)\r\nprint(prediction)\r\n\r\n# Evaluating the model through confusion matrix\r\n\r\nconfusion_matrix=confusion_matrix(test_y,prediction)\r\nprint(confusion_matrix)\r\n\r\n# calculating the accuracy\r\nfrom sklearn.metrics import accuracy_score,confusion_matrix\r\n\r\naccuracy_score=accuracy_score(test_y, prediction)\r\nprint(accuracy_score)\r\n\r\n#Printing the misclassified values from prediction\r\n\r\nprint('Misclassified samples:%d' % (test_y != prediction).sum())\r\n\r\n#########################################################\r\n#LOGISTIC REGRESSION - REMOVING INSIGNIFICANT VARIABLES\r\n###########################################################3\r\n\r\n# Reindexing the salary status names to 0,1\r\ndata1=data.dropna(axis=0)\r\n\r\ndata1['SalStat']=data1['SalStat'].map({' less than or equal to 50,000':0,' greater than 50,000':1})\r\nprint(data1['SalStat'])\r\n\r\ncols = ['gender','nativecountry','race','JobType']\r\nnew_data=data1.drop(cols,axis=1)\r\n\r\nnew_data=pd.get_dummies(new_data,drop_first=True)\r\nprint(new_data.isnull().sum())\r\n#storing the column names\r\ncolumn_list=list(new_data.columns)\r\nprint(column_list)\r\n\r\n#seperating the input names from data\r\nfeatures=list(set(column_list)-set(['SalStat']))\r\nprint(features)\r\n#storing the output values in y\r\ny=new_data['SalStat'].values\r\nprint(y)\r\n\r\n# storing the values from input features\r\nx=new_data[features].values\r\nprint(x)\r\n\r\n#Splitting the data into train and test\r\ntrain_x,test_x,train_y,test_y = train_test_split(x,y,test_size=0.3,random_state=0)\r\n\r\n#make an instance of the model\r\nlogistic=LogisticRegression()\r\n\r\nlogistic.fit(train_x,train_y)\r\n\r\n#Prediction from test data\r\nprediction=logistic.predict(test_x)\r\nprint(prediction)\r\n\r\nfrom sklearn.metrics import accuracy_score,confusion_matrix\r\n\r\naccuracy_score=accuracy_score(test_y,prediction)\r\nprint(accuracy_score)\r\n\r\n# printing the misclassified values from prediction\r\nprint('Misclassified samples:%d'%(test_y != prediction).sum())\r\n\r\n#############################################################33\r\n#################################################\r\n#######################################\r\n##KNN\r\n\r\nfrom sklearn.metrics import accuracy_score,confusion_matrix\r\n\r\n#importing the library of KNN\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\n\r\n#import library for plotting\r\nimport matplotlib.pyplot as plt\r\n\r\n#Storing the k neaserest neighbors classifier\r\nKNN_classifier=KNeighborsClassifier(n_neighbors=5)\r\n\r\n#fitting the knearest neighbors classifier\r\nKNN_classifier.fit(train_x,train_y)\r\n\r\n#Prediciting the test values with model\r\nprediction =KNN_classifier.predict(test_x)\r\n\r\n#performance metric check\r\nconfusion_matrix=confusion_matrix(test_y,prediction)\r\nprint(\"\\t\",\"Predicted values\")\r\nprint(\"Original values\",\"\\n\",confusion_matrix)\r\n\r\n\r\n#calculating the accuracy\r\nfrom sklearn.metrics import accuracy_score,confusion_matrix\r\n\r\naccuracy_score=accuracy_score(test_y,prediction)\r\nprint(accuracy_score)\r\n\r\nprint('Misclassified samples:%d'%(test_y!=prediction).sum())\r\n\r\n\"\"\"\r\nEffect of k value on classifier\r\n\"\"\"\r\nMisclassified_sample=[]\r\n# calculating the error for k values\r\nfor i in range(1,20):\r\n knn=KNeighborsClassifier(n_neighbors=i)\r\n knn.fit(train_x,train_y)\r\n pred_i=knn.predict(test_x)\r\n Misclassified_sample.append((test_y!=pred_i).sum())\r\n \r\nprint(Misclassified_sample)\r\n \r\n####END SCRIPT","sub_path":"classificationcase.py","file_name":"classificationcase.py","file_ext":"py","file_size_in_byte":8292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"543104201","text":"import random\nimport timeit\n\n\ndef bubble_sort(lst):\n \"\"\"\n (O(n**2))\n \"\"\"\n n = 1\n while n < len(lst):\n for i in range(len(lst) - n):\n if lst[i] > lst[i+1]:\n lst[i], lst[i + 1] = lst[i + 1], lst[i]\n n += 1\n return lst\n\n\ndef short_bubble_sort(lst):\n \"\"\"\n (O(n**2))\n \"\"\"\n exchanges = True\n num = len(lst) - 1\n while num > 0 and exchanges:\n exchanges = False\n for i in range(num):\n if lst[i] > lst[i + 1]:\n exchanges = True\n temp = lst[i]\n lst[i] = lst[i + 1]\n lst[i + 1] = temp\n num = num - 1\n return lst\n\n\ndef insertion_sort(lst):\n \"\"\"\n (O(n**2))\n \"\"\"\n for index in range(1, len(lst)):\n\n current_value = lst[index]\n position = index\n\n while position > 0 and lst[position - 1] > current_value:\n lst[position] = lst[position - 1]\n position = position - 1\n\n lst[position] = current_value\n\n return lst\n\n\ndef merge_sort(alist):\n \"\"\"\n (O(n log n))\n \"\"\"\n if len(alist) > 1:\n mid = len(alist) // 2\n lefthalf = alist[:mid]\n righthalf = alist[mid:]\n\n merge_sort(lefthalf)\n merge_sort(righthalf)\n\n i = 0\n j = 0\n k = 0\n while i < len(lefthalf) and j < len(righthalf):\n if lefthalf[i] < righthalf[j]:\n alist[k] = lefthalf[i]\n i = i + 1\n else:\n alist[k] = righthalf[j]\n j = j + 1\n k = k + 1\n\n while i < len(lefthalf):\n alist[k] = lefthalf[i]\n i = i + 1\n k = k + 1\n\n while j < len(righthalf):\n alist[k] = righthalf[j]\n j = j + 1\n k = k + 1\n\n return alist\n\n\ndef quick_sort(alist):\n \"\"\"\n (O(n log n)), но может деградировать до (O(n**2))\n \"\"\"\n quick_sort_helper(alist, 0, len(alist) - 1)\n\n return alist\n\n\ndef quick_sort_helper(alist, first, last):\n if first < last:\n splitpoint = partition(alist, first, last)\n\n quick_sort_helper(alist, first, splitpoint - 1)\n quick_sort_helper(alist, splitpoint + 1, last)\n\n\ndef partition(alist, first, last):\n pivotvalue = alist[first]\n\n leftmark = first + 1\n rightmark = last\n\n done = False\n while not done:\n\n while leftmark <= rightmark and \\\n alist[leftmark] <= pivotvalue:\n leftmark = leftmark + 1\n\n while alist[rightmark] >= pivotvalue and \\\n rightmark >= leftmark:\n rightmark = rightmark - 1\n\n if rightmark < leftmark:\n done = True\n else:\n temp = alist[leftmark]\n alist[leftmark] = alist[rightmark]\n alist[rightmark] = temp\n\n temp = alist[first]\n alist[first] = alist[rightmark]\n alist[rightmark] = temp\n\n return rightmark\n\n\ndef selection_sort(lst):\n \"\"\"\n (O(n**2))\n \"\"\"\n for fillslot in range(len(lst) - 1, 0, -1):\n position_of_max = 0\n for location in range(1, fillslot + 1):\n if lst[location] > lst[position_of_max]:\n position_of_max = location\n\n temp = lst[fillslot]\n lst[fillslot] = lst[position_of_max]\n lst[position_of_max] = temp\n\n return lst\n\n\ndef shell_sort(alist):\n \"\"\"\n Производительность колеблется между (O(n)) и (O(n^2))\n \"\"\"\n sublistcount = len(alist) // 2\n\n while sublistcount > 0:\n\n for startposition in range(sublistcount):\n gap_insertion_sort(alist, startposition, sublistcount)\n\n sublistcount = sublistcount // 2\n\n return alist\n\n\ndef gap_insertion_sort(alist, start, gap):\n\n for i in range(start + gap, len(alist), gap):\n\n currentvalue = alist[i]\n position = i\n\n while position >= gap and alist[position - gap] > currentvalue:\n alist[position] = alist[position - gap]\n position = position - gap\n\n alist[position] = currentvalue\n\n\ndef shaker_sort(lst):\n \"\"\"\n (O(n^2))\n \"\"\"\n left = 0\n right = len(lst) - 1\n while left <= right:\n for i in range(left, right):\n if lst[i] > lst[i + 1]:\n lst[i], lst[i + 1] = lst[i + 1], lst[i]\n right -= 1\n for i in range(right, left, -1):\n if lst[i - 1] > lst[i]:\n lst[i], lst[i - 1] = lst[i - 1], lst[i]\n left += 1\n return lst\n\n\ndef gen_list(len_lst):\n \"\"\"\n генерирует список заданной длины\n \"\"\"\n lst = [random.randint(-100, 100) for _ in range(len_lst)]\n return lst\n\n\ndef get_sorts_time_table():\n sorts = ('bubble_sort', 'short_bubble_sort', 'insertion_sort', 'merge_sort', 'quick_sort',\n 'selection_sort', 'shell_sort', 'shaker_sort')\n list_lens = (10, 100, 300)\n\n print(f\"{'Sort Name':30s}\"\n f\"{f'{list_lens[0]} el':13s}{f'{list_lens[1]} el':13s}{f'{list_lens[2]} el'} \\n{'-' * 63}\")\n\n for sort in sorts:\n print(f\"{sort:25s}\", end='')\n for list_len in list_lens:\n test_list = (gen_list(list_len))\n print(f\"{timeit.timeit(f'{sort}({test_list})', setup=f'from __main__ import {sort}', number=1000):12f}\",\n end=' ')\n print()\n\n\nget_sorts_time_table()\n","sub_path":"Lesson_7/sorts.py","file_name":"sorts.py","file_ext":"py","file_size_in_byte":5366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"30158000","text":"\"\"\"\nCopyright (c) 2017, Jairus Martin.\n\nDistributed under the terms of the MIT License.\n\nThe full license is in the file LICENSE, distributed with this software.\n\nCreated on June 7, 2017\n\n@author: jrm\n\"\"\"\nfrom atom.api import Typed, set_default\n\nfrom enamlnative.widgets.switch import ProxySwitch\n\nfrom .android_compound_button import AndroidCompoundButton, CompoundButton\nfrom .bridge import JavaMethod\n\n\nclass Switch(CompoundButton):\n __nativeclass__ = set_default('android.widget.Switch')\n setShowText = JavaMethod('boolean')\n setSplitTrack = JavaMethod('boolean')\n setTextOff = JavaMethod('java.lang.CharSequence')\n setTextOn = JavaMethod('java.lang.CharSequence')\n\n\nclass AndroidSwitch(AndroidCompoundButton, ProxySwitch):\n \"\"\" An Android implementation of an Enaml ProxySwitch.\n\n \"\"\"\n #: A reference to the widget created by the proxy.\n widget = Typed(Switch)\n\n # -------------------------------------------------------------------------\n # Initialization API\n # -------------------------------------------------------------------------\n def create_widget(self):\n \"\"\" Create the underlying widget.\n\n \"\"\"\n d = self.declaration\n self.widget = Switch(self.get_context(), None,\n d.style or '@attr/switchStyle')\n\n def init_widget(self):\n \"\"\" Initialize the underlying widget.\n\n \"\"\"\n super(AndroidSwitch, self).init_widget()\n d = self.declaration\n self.set_show_text(d.show_text)\n if d.split_track:\n self.set_split_track(d.split_track)\n if d.text_off:\n self.set_text_off(d.text_off)\n if d.text_on:\n self.set_text_on(d.text_on)\n\n # -------------------------------------------------------------------------\n # ProxySwitch API\n # -------------------------------------------------------------------------\n def set_show_text(self, show):\n api = self.get_context().api_level\n if api >= 21:\n self.widget.setShowText(show)\n\n def set_split_track(self, split):\n self.widget.setSplitTrack(split)\n\n def set_text_off(self, text):\n self.widget.setTextOff(text)\n\n def set_text_on(self, text):\n self.widget.setTextOn(text)\n","sub_path":"src/enamlnative/android/android_switch.py","file_name":"android_switch.py","file_ext":"py","file_size_in_byte":2261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"309631790","text":"\"\"\"\nciteseerx_get_docs.py\nAuthor: Theodore LaGrow and Jacob Bieker\nLanguage: Python 2.7x\nPackages Needed: \n\n\"\"\"\n\nimport sys\nimport urllib\nimport urllib2\nfrom urllib2 import urlopen\nimport httplib\nimport feedparser\nimport wget\nimport re\nimport os\nimport requests\nimport time\nfrom bs4 import BeautifulSoup\n\n\n# Gett the topic from user\n#print(\"Without spaces or strange characters -\")\n#search_topic = raw_input(\"What topic are you interested in? :\")\n#search_topic = \"nlp\"\nsearch_topic = sys.argv[1]\n\n# To help with the query\npdf_array = []\npage_number = 0\nurl = \"http://citeseerx.ist.psu.edu/search?q=\"\nq = \"text%3A{0}&t=doc&sort=cite&start={1}\"\nurl += q.format(search_topic, page_number)\n\n#print url\n\n#this is get the amount of articles in each listing\nresponse = urllib2.urlopen(url)\nhtml_doc = response.read()\nsoup = BeautifulSoup(html_doc, 'html.parser')\n\nnumOfArticles = soup.find('strong').nextSibling.nextSibling.string\nnumOfArticles = re.sub(',', '', numOfArticles)\nnumOfArticles = int(numOfArticles)\ntop = numOfArticles\nprint(numOfArticles)\n\n\nlinks_file = open('citeseerx_texts.txt', 'a+')\nwhile page_number < numOfArticles:\n links_file = open('citeseerx_texts.txt', 'a+')\n\n url = \"http://citeseerx.ist.psu.edu/search?q=\"\n q = \"text%3A{0}&t=doc&sort=cite&start={1}\"\n url += q.format(search_topic, page_number)\n response = urllib2.urlopen(url)\n html_doc = response.read()\n soup = BeautifulSoup(html_doc, 'html.parser')\n numOfLinks = (soup.find('strong').string.strip())[-2:]\n numOfLinks = int(numOfLinks)\n\n i=0\n links_array = []\n url_start = \"http://citeseerx.ist.psu.edu\"\n if numOfLinks%10 != 0:\n break\n else:\n while i < 10:\n page_link = soup('a', {'class' : 'remove doc_details'})[i]['href']\n page_link = url_start + page_link\n links_array.append(page_link)\n i += 1\n #print(\"links_array: \", links_array)\n\n\n #get the number\n for page in links_array:\n #print page\n links_for_downloads = []\n\n response1 = urllib2.urlopen(page)\n html_doc1 = response1.read()\n soup1 = BeautifulSoup(html_doc1, 'html.parser')\n page_link1 = soup1.find('ul', id=\"dlinks\")\n page_link2 = page_link1.find_all('a')\n i = 0\n while i < len(page_link2):\n pl = page_link2[i]['href']\n #print(pl)\n pl = pl.strip()\n if pl[:5] == \"http:\" and pl[-3:] == \"pdf\":\n links_for_downloads.append(pl)\n\n i += 1\n print(links_for_downloads)\n found = False\n for link in links_for_downloads:\n #print(link)\n try:\n status = urllib2.urlopen(link).getcode()\n except urllib2.HTTPError as e:\n print(e.code)\n except urllib2.URLError as err:\n print(err)\n except httplib.BadStatusLine:\n pass\n\n if status == 200:\n the_true_link = link\n print(link)\n found = True\n elif status == 404: #if status is equal to 404 (NOT FOUND)\n print('The file: ', link, 'could not be opened. Does not exist!!') #display error\n else: #Any other message then display error and the status code\n print('Unknown Error:', status)\n if found == True:\n print(\"Keep GOING!!!\")\n links_file.write(\"{}{}\".format(the_true_link, \"\\n\")) #to get our pdf links\n print('pdf link: %s' % the_true_link)\n break\n print\n print\n print\n\n\n\n page_number += 10\n\n links_file.close()\n\n\nprint(\"\\nDONE WITH THE DOWNLOADS FOOL!! \\n\")\nlinks.close()\n\n\n\n\n ","sub_path":"data_collection/citeseerx_get_docs.py","file_name":"citeseerx_get_docs.py","file_ext":"py","file_size_in_byte":4410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"229935803","text":"# -*- coding: utf-8 -*-\nimport random\nfrom conjugation import mongo\n\nclass Verbs():\n @classmethod\n def total(cls):\n return mongo.db.verbs.count()\n\n @classmethod\n def get_random_verb(cls, temp, mode):\n total_verbs = cls.total()\n random_verbs = random.randrange(total_verbs - 1)\n return mongo.db.verbs.find({'temps.temp': temp, 'temps.mode' : mode }).skip(random_verbs).limit(1)[0]\n\n @classmethod\n def get_verb_pronouns(cls, verb):\n # Subject pronouns: http://en.wikipedia.org/wiki/French_personal_pronouns\n PRONOUNS = ['Je', 'Tu', 'Il/Elle', 'Nous', 'Vous', 'Ils/Elles'] \n PRONOUNS_CONTRACTED = ['J\\'', 'Tu', 'Il/Elle', 'Nous', 'Vous', 'Ils/Elles'] \n\n first_letter = verb[0]\n return PRONOUNS_CONTRACTED if first_letter in u'aeiuohé' else PRONOUNS\n\n @classmethod\n def is_conjugation_correct(cls, temp, mode, verb, inflections):\n verb_db = mongo.db.verbs.find({'_id' : verb, 'temps.temp' : temp, 'temps.mode': mode })[0]\n inflections_db = cls.get_verb_inflections(verb_db, temp, mode)\n is_correct = True\n corrections = [None] * len(inflections)\n pronouns = cls.get_verb_pronouns(verb)\n for i in range(len(inflections)):\n # je parle -> jeparle != jeparle <- je + ParLe\n if(inflections_db[i].replace(' ', '') != u'{0}{1}'.format(pronouns[i], inflections[i]).lower()):\n is_correct = False\n corrections[i] = inflections_db[i]\n\n return (is_correct, corrections)\n\n @classmethod\n def get_verb_inflections(cls, verb, temp, mode):\n for item in verb['temps']:\n if item['temp'] == temp and item['mode'] == mode:\n return item['inflections']\n\n return None\n","sub_path":"web/conjugation/verbs.py","file_name":"verbs.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"184716486","text":"# max arr if arr[mid] in it\ndef MaxCrossing(arr,l,m,r):\n #element on the left side\n sm=0\n SumLeft=-1000\n for i in range (m,l-1,-1):\n sm+=arr[i]\n if (sm>SumLeft):\n SumLeft=sm\n # elements on the right side\n sm=0\n SumRight=-1000\n for i in range (m-1,r+1):\n sm+=arr[i]\n if (sm>SumRight):\n SumRight=sm\n return SumLeft+SumRight\n# return the max sum of the sub arr\ndef MaxSubArrSum(arr,l,r):\n if (l==r):\n return arr[l]\n else:\n m=(l+r)//2\n return max(MaxSubArrSum(arr,0,m), MaxSubArrSum(arr,m+1,r),MaxCrossing(arr,l,m,r))\narr=[-10,9,-5,6,-8,12,-4,-3]\nprint (MaxSubArrSum(arr,0,len(arr)-1))","sub_path":"python code/MaximumSubArrSum.py","file_name":"MaximumSubArrSum.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"119268074","text":"import os\nimport django\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"lcc.settings\")\ndjango.setup()\nimport urllib.request\nfrom icalendar import Calendar, vDatetime\nfrom lcc.apps.events.models import CalendarEvent\nfrom django.core.cache import cache\n\ndef CacheEvents():\n # Download iCal\n calendar_events = []\n calendar_file = urllib.request.URLopener()\n calendar_file.retrieve(\"http://www.calendarwiz.com/CalendarWiz_iCal.php?crd=longview_community_calendar\", \"calendar.ics\")\n g = open(\"calendar.ics\")\n gcal = Calendar.from_ical(g.read())\n for component in gcal.walk():\n start_time = None\n end_time = None\n if component.get('summary'):\n summary = component.get('summary')\n start = component.get('dtstart')\n end = component.get('dtend')\n stamp = component.get('dtstamp')\n location = component.get('location')\n desc = component.get('description')\n\n if start:\n start_time = start.dt\n if end:\n end_time = end.dt\n\n calendar_events.append(\n CalendarEvent(\n title=summary,\n description=desc,\n start_time=start_time,\n end_time=end_time\n )\n )\n g.close()\n cache.set('lcc.cevents.calendarwiz', calendar_events, 400)\n \n\nif __name__ == \"__main__\":\n CacheEvents()","sub_path":"bin/import_events.py","file_name":"import_events.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"147815267","text":"import config as cf\nfrom libs.image_processing import get_edge, crop_image, apply_threshold_bgr\nimport sys\nimport os\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef process(image):\n image = crop_image(image, (500, 0), (image.shape[0], image.shape[1]))\n image = apply_threshold_bgr(image, (175, 195), (142, 155), (120, 133))\n #image = get_edge(image)\n\n return image\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) == 2:\n img_dir = str(sys.argv[1])\n if os.path.isfile(img_dir):\n video = cv2.VideoCapture(img_dir)\n while video.isOpened():\n is_capturing, frame = video.read()\n if is_capturing:\n frame = cv2.resize(frame, cf.WINDOW_SIZE)\n cv2.imshow(\"original\", frame)\n\n frame = process(frame)\n\n cv2.imshow(cf.WINDOW_NAME, frame)\n\n if cv2.waitKey(25) & 0xFF == 27: # Press ESC\n break\n elif cv2.getWindowProperty(cf.WINDOW_NAME, cv2.WND_PROP_VISIBLE) < 1: # Close window\n break\n else:\n break\n video.release()\n cv2.destroyAllWindows()\n else:\n sys.exit(\"File does not exits.\")\n else:\n sys.exit(\"Please define video directory.\")\n","sub_path":"sample_on_video.py","file_name":"sample_on_video.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"630054444","text":"from functools import lru_cache\nimport subprocess\n\nfrom typecheck import typecheck\n\nimport networkx as nx\n\n\n@typecheck\ndef shorten(mod_name: str, length: int=2) -> str:\n return \".\".join(mod_name.split(\".\")[:length])\n\n\n@lru_cache(maxsize=4095)\n@typecheck\ndef levenshtein_distance(s: str, t: str) -> int:\n if not s:\n return len(t)\n if not t:\n return len(s)\n if s[0] == t[0]:\n return levenshtein_distance(s[1:], t[1:])\n l1 = levenshtein_distance(s, t[1:])\n l2 = levenshtein_distance(s[1:], t)\n l3 = levenshtein_distance(s[1:], t[1:])\n return 1 + min(l1, l2, l3)\n\n\n@typecheck\ndef make_colors(graph: nx.Graph) -> map:\n names = graph.nodes()\n longest = max(names)\n raw = [levenshtein_distance(x, longest) for x in names]\n largest_raw = max(raw)\n degrees = [graph.degree(x) for x in graph]\n largest_degrees = max(degrees)\n return map(lambda x, y: x + y,\n [int(10 * x/largest_degrees) for x in degrees],\n [10 * x/largest_raw for x in raw])\n\n\n@typecheck\ndef has_excluded(item: str) -> bool:\n exclude = [\".dylibs\", \"__pycache__\", \".so\", \"__.py\", \".nib\", \".\", \"..\"]\n if True in [item.endswith(x) for x in exclude]:\n return True\n return False\n\n\n@typecheck\ndef output_filter(results: list) -> str:\n return \"\\n\".join([x for x in results if not has_excluded(x)])\n\n\n@typecheck\ndef run_cmd(*command):\n return subprocess.check_output(\n \" \".join(command),\n shell=True,\n universal_newlines=True).splitlines()\n\n\n@typecheck\ndef ls(*args):\n command = [\"ls -al\"] + list(args)\n print(output_filter(run_cmd(*command)))\n\n\n@typecheck\ndef rm(*args):\n command = [\"rm\"] + list(args)\n run_cmd(*command)\n\n\n__all__ = [\"shorten\", \"make_colors\", \"ls\", \"rm\"]\ndel lru_cache, typecheck, nx\n","sub_path":"Mastering matplotlib/SF_MM/02-architecture/lib/modutil.py","file_name":"modutil.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"419860246","text":"import os\nimport requests\nfrom flask import g, current_app\nfrom verification_ui.main import app\n\n\ndir_ = os.path.dirname(os.path.abspath(__file__))\npersonal_item_json = open(os.path.join(dir_, 'data/personal_item.json'), 'r').read()\n\n\ndef create_personal_worklist_item():\n with app.app_context() as ac:\n ac.g.requests = requests.Session()\n base_url = current_app.config['VERIFICATION_API_URL']\n headers = {\"Accept\": \"application/json\", \"Content-Type\": \"application/json\"}\n\n with app.test_request_context():\n post_url = \"{}/case\".format(base_url)\n post_response = g.requests.post(post_url, data=personal_item_json, headers=headers)\n data = post_response.json()\n item_id = data['case_id']\n\n get_url = '{}/case/{}'.format(base_url, item_id)\n get_response = g.requests.get(get_url, headers=headers)\n return get_response.json()\n","sub_path":"integration_tests/utility/test_data.py","file_name":"test_data.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"91420476","text":"from grafo_adj_nao_dir import *\n\ndef grau(grafo, vertice):\n indiceVertice = 0\n\n for i in range(len(grafo.N)):\n if grafo.N[i] == vertice:\n indiceVertice = i\n break\n\n contGrau = 0\n\n for i in range(len(grafo.M[indiceVertice])):\n if grafo.M[indiceVertice][i] == \"-\":\n if grafo.M[i][indiceVertice] == 1:\n contGrau += 1\n elif grafo.M[i][indiceVertice] == 2:\n contGrau += 2\n if grafo.M[indiceVertice][i] == 1:\n contGrau += 1\n elif grafo.M[indiceVertice][i] == 2:\n contGrau += 2\n\n return contGrau\n\n\n\ndef caminho_euleriano(grafo):\n vertices = grafo.N\n\n cont_impar = 0\n\n for vertice in vertices:\n if grau(grafo, vertice) % 2 != 0:\n cont_impar += 1\n if cont_impar == 0 or cont_impar == 2:\n return True\n\n return False","sub_path":"Roteiro3/euler.py","file_name":"euler.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"47281083","text":"#!/usr/bin/env python3\n\n\"\"\" try:\n print(5/0)\nexcept ZeroDivisionError:\n print('illeagle to have zero divided') \"\"\"\n\nprint('Divide two Given num')\nprint('Enter q to exit')\n\n#file operation exception\ntry:\n with open('alice.txt') as f_obj:\n contents = f_obj.read()\nexcept FileNotFoundError:\n print('file not found')\n\n#zero divide exception\nwhile True:\n num1 = input('first num\\n')\n if num1 == 'q':\n break\n num2 = input('second num\\n')\n try:\n ans = int(num1)/int(num2)\n except ZeroDivisionError:\n print(\"You can't divide by 0!\")\n except ValueError:\n print(\"Input value is illeagle\")\n else:\n print(ans)","sub_path":"exception.py","file_name":"exception.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"63534014","text":"import sys\nimport random\n\ndef cmdlinearg(name, default=None):\n for arg in sys.argv:\n if arg.startswith(name + \"=\"):\n return arg.split(\"=\")[1]\n assert default is not None, name\n return default\n\nrandom.seed(int(cmdlinearg('seed', sys.argv[-1])))\nN = int(cmdlinearg('N', 10))\nQ = int(cmdlinearg('Q', 10))\nH = int(cmdlinearg('H', 20))\nW = int(cmdlinearg('W', 100))\nN1 = int(cmdlinearg('N1', -1))\nN2 = int(cmdlinearg('N2', -1))\n\nif N1 >= 0:\n N2 = N-N1\nelif N2 >= 0:\n N1 = N-N2\nelse:\n N1 = int(N/2)\n N2 = N-N1\n\n\nprint(*(N,Q,H,W))\n\nused_x = {0}\n\ndef get_unique_x():\n x = random.randint(1,W-1)\n while (x in used_x):\n x = random.randint(1,W-1)\n used_x.add(x)\n return x\n\n\n\ncave = []\nfor i in range(0,N1):\n y = random.randint(1,H-1)\n x = get_unique_x()\n cave.append((1,x,y))\n\nfor i in range(0,N2):\n y = random.randint(1,H-1)\n x = get_unique_x()\n cave.append((2,x,y))\n\nassert(len(cave) == N)\n\nrandom.shuffle(cave)\nfor a in cave:\n print(*a)\n\nfor i in range(0,Q):\n x1 = get_unique_x()\n y1 = random.randint(1,H-1)\n x2 = get_unique_x()\n y2 = random.randint(1,H-1)\n print(*(x1,y1,x2,y2))\n","sub_path":"lager/fladdermusen/data/gen_random.py","file_name":"gen_random.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"204392290","text":"from count_patterns import count\n\n\ndef frequent_words(text, k):\n freq_dict = {}\n for i in range(0, len(text) - k):\n pattern = text[i: i + k]\n if not pattern in freq_dict:\n n = count(text, pattern)\n freq_dict[pattern] = n\n\n counts = freq_dict.values()\n m = max(counts)\n words = []\n for w, c in freq_dict.items():\n if c == m:\n words.append(w)\n return words\n\n\ndef read_input(filename):\n f = open(filename, 'r')\n text = f.readline().rstrip('\\n')\n k = int(f.readline().rstrip('\\n'))\n ans = f.readline().rstrip('\\n').split()\n return text, k, ans\n\n\ndef check_answers(words, ans):\n words.sort()\n ans.sort()\n if words == ans:\n print('Correct')\n else:\n print('Wrong')\n print(words)\n\n\ndef run_test(file_name):\n text, k, ans = read_input(file_name)\n words = frequent_words(text, k)\n print('Test: ', end='')\n check_answers(words, ans)\n\n\nif __name__ == '__main__':\n run_test('P1_short.txt')\n print()\n run_test('P1_long.txt')","sub_path":"6/frequent_words_inefficient.py","file_name":"frequent_words_inefficient.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"242789244","text":"import trafaret as t\n\nfrom datarobot.errors import ClientError\nfrom datarobot.models.api_object import APIObject\nfrom datarobot.models.residuals import ResidualsTrafaret\nfrom datarobot.utils import encode_utf8_if_py2\nfrom datarobot.utils.pagination import unpaginate\n\nfrom .external_scores import DEFAULT_BATCH_SIZE\n\n\nclass ExternalResidualsChart(APIObject):\n \"\"\" Residual analysis dataset chart data for model .\n This data is calculated over a randomly downsampled subset of the source data\n (capped at 1000 rows).\n\n versionadded:: v2.21\n\n Notes\n -----\n\n ``ResidualsChartRow`` is a list of floats and ints containing the following:\n * Element 0 (float) is the actual target value for the source data row.\n * Element 1 (float) is the predicted target value for that row.\n * Element 2 (float) is the error rate of predicted - actual and is optional.\n * Element 3 (int) is the row number in the source dataset from which the values\n were selected and is optional.\n\n Attributes\n ----------\n data : list\n List of lists with schema described as ``ResidualsChartRow`` above.\n coefficient_of_determination : float\n The r-squared value for the downsampled dataset\n residual_mean : float\n The arithmetic mean of the residual (predicted value minus actual value)\n dataset_id : str\n ID of the dataset this chart belongs\n standard_deviation : float\n standard deviation of residual values\n \"\"\"\n\n _converter = (\n t.Dict(\n {\n t.Key(\"dataset_id\"): t.String,\n t.Key(\"data\"): t.List(t.Tuple(t.Float, t.Float, t.Float, t.Int | t.Null)),\n }\n )\n .merge(ResidualsTrafaret)\n .ignore_extra(\"*\")\n )\n\n _path = \"projects/{}/models/{}/datasetResidualsCharts/\"\n\n def __init__(\n self, dataset_id, residual_mean, coefficient_of_determination, standard_deviation, data\n ):\n self.dataset_id = dataset_id\n self.residual_mean = residual_mean\n self.coefficient_of_determination = coefficient_of_determination\n self.standard_deviation = standard_deviation\n self.data = data\n\n @classmethod\n def list(cls, project_id, model_id, dataset_id=None, offset=0, limit=100):\n \"\"\" Retrieve list of residual charts for the model.\n\n Parameters\n ----------\n project_id: str\n id of the project\n model_id: str\n if specified, only lift chart for this model will be retrieved\n dataset_id: str, optional\n if specified, only lift chart for this dataset will be retrieved\n offset: int, optional\n this many results will be skipped, default: 0\n limit: int, optional\n at most this many results are returned, default: 100, max 1000.\n To return all results, specify 0\n\n Returns\n -------\n A list of :py:class:`ExternalResidualsChart <datarobot.ExternalResidualsChart>` objects\n \"\"\"\n url = cls._path.format(project_id, model_id)\n params = {\"offset\": offset, \"limit\": limit}\n if dataset_id:\n params[\"datasetId\"] = dataset_id\n if limit == 0: # unlimited results\n params[\"limit\"] = DEFAULT_BATCH_SIZE\n return [cls.from_server_data(entry) for entry in unpaginate(url, params, cls._client)]\n return [cls.from_server_data(i) for i in cls._client.get(url, params=params).json()[\"data\"]]\n\n @classmethod\n def get(cls, project_id, model_id, dataset_id):\n \"\"\" Retrieve residual chart for the model and prediction dataset.\n\n Parameters\n ----------\n project_id: str\n project id\n model_id: str\n model id\n dataset_id: str\n prediction dataset id\n\n Returns\n -------\n :py:class:`ExternalResidualsChart <datarobot.ExternalResidualsChart>` object\n\n \"\"\"\n resp = cls.list(project_id, model_id, dataset_id=dataset_id, offset=0, limit=1)\n if not resp:\n raise ClientError(\"Requested residual chart does not exist.\", 404)\n return resp[0]\n\n def __repr__(self):\n return encode_utf8_if_py2(u\"ExternalResidualChart({})\".format(self.dataset_id))\n","sub_path":"datarobot/models/external_dataset_scores_insights/external_dataset_residuals.py","file_name":"external_dataset_residuals.py","file_ext":"py","file_size_in_byte":4288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"203136025","text":"def check_primo(N):\n if N > 1:\n if N == 2:\n return True\n if N % 3 == 0:\n return False\n if N % 5 == 0:\n return False\n if N % 7 == 0:\n return False\n for i in range(2, N // 2):\n if (N % i) == 0:\n return False\n else:\n return True\n else:\n return False\n\n\ndef maior_primo_menor_que(n):\n lista_primos = []\n for i in range(2, n + 1):\n if check_primo(i) == True:\n lista_primos.append(i)\n if len(lista_primos) > 0:\n return lista_primos[len(lista_primos) - 1]\n else:\n return -1","sub_path":"backup/user_180/ch5_2019_09_28_14_13_38_531928.py","file_name":"ch5_2019_09_28_14_13_38_531928.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"104282572","text":"from __future__ import print_function, absolute_import, division, unicode_literals\n\nfrom rubicon.objc import objc_method\n\nfrom ..libs import *\nfrom .base import Widget\n\n\nclass ButtonImpl(UIButton):\n @objc_method('v@')\n def onPress_(self, obj):\n print (\"in on_press handler\")\n if self.__dict__['interface'].on_press:\n self.__dict__['interface'].on_press(self.__dict__['interface'])\n\n\nclass Button(Widget):\n def __init__(self, label, on_press=None):\n super(Button, self).__init__()\n\n self.on_press = on_press\n self.label = label\n\n self.startup()\n\n def startup(self):\n self._impl = ButtonImpl.alloc().init()\n self._impl.__dict__['interface'] = self\n\n self._impl.setTitle_forState_(self.label, UIControlStateNormal)\n self._impl.setTitleColor_forState_(UIColor.blackColor(), UIControlStateNormal)\n self._impl.addTarget_action_forControlEvents_(self._impl, get_selector('onPress:'), UIControlEventTouchDown)\n\n self._impl.setTranslatesAutoresizingMaskIntoConstraints_(False)\n","sub_path":"toga_iOS/widgets/button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"579679469","text":"#!/usr/bin/env python\n\"\"\"\nA scatter graph of grid count vs grid area.\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# extract data from csv\n# CAUTION! column locations differ from filtered.\n# file_name = \"../data/Hori_area_weight.csv\"\n\n# uncomment when using filtered data\nfile_name = \"../data/Hori_area_weight_filtered.csv\"\n\n# columns:\n# 11 - star_infs\n# 14, 12, 13 = horimgrid, quartergrid, X1grid\n# 18, 16, 17 - mgr_totalland, mainisl, smallisl\n# 22, 20, 21 - qgr_totalland, mainisl, smallisl\n# 25, 23, 24 - X1gr_totalland, mainisl, smallisl\nstar_infs = np.genfromtxt(file_name, delimiter=',', dtype=None, skip_header=1, usecols=11)\ngrid_count = np.genfromtxt(file_name, delimiter=',', dtype=None, skip_header=1, usecols=[14,12,13])\ngrid_land = np.genfromtxt(file_name, delimiter=',', dtype=None, skip_header=1, usecols=[18,22,25])\ngrid_main = np.genfromtxt(file_name, delimiter=',', dtype=None, skip_header=1, usecols=[16,20,23])\ngrid_small = np.genfromtxt(file_name, delimiter=',', dtype=None, skip_header=1, usecols=[17,21,24])\n# remove \"\" from the text string\nstars = [star[1:-1] for star in star_infs]\n\ncolours = map(lambda star_colour: 'k' if star_colour == 'BK' else 'y' if star_colour == 'GD' else 'b' if star_colour == 'BU' else 'g' if star_colour == 'GN' else 'w', stars)\n\nresolutions = (\n '0.1 lat. by 0.15 long. geoquadrat',\n '0.2 lat by 0.3 long. grid',\n '1 lat. by 1 long. grid',\n)\n\nfig = plt.figure()\nfig.suptitle('Comparison of Species Within-Japan Range Size Between Area and Count Measured at 3 Resolutions Using Horikawa Maps', fontsize=12)\n\ndef plot_scatter(index):\n ax = fig.add_subplot(131 + index)\n # grid_land/10000 to rescale the range\n ax.scatter(grid_land[:,index]/10000, grid_main[:,index]/10000, c=colours, alpha=0.5)\n ax.scatter(grid_land[:,index]/10000, grid_small[:,index]/10000, c=colours, alpha=0.5)\n ax.set_aspect(1)\n ax.set_xlim(0, 38.1)\n ax.set_ylim(0, 38.1)\n # uncomment to manually set ticks\n # xtix = np.arange(0, 380000.1, 100000)\n # ytix = np.arange(0, 1000.1, 200)\n # ax.xaxis.set_ticks(xtix)\n # ax.yaxis.set_ticks(ytix)\n ax.set_xlabel('Grid area at ' + resolutions[index], fontsize=10)\n ax.set_ylabel('Grid count at ' + resolutions[index], fontsize=8)\n #ax.set_title('Comparison of range size between area and count at ' + resolutions[index], fontsize=12)\n ax.grid(True)\n\nfor index in range(0,3):\n plot_scatter(index)\n\nplt.show()\n","sub_path":"graphing/horigrid_landtype_scatters.py","file_name":"horigrid_landtype_scatters.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"279152405","text":"# -*- coding: utf-8 -*-\n\"\"\"This file is a TMPJobsDisneyCareers spider created on top of the TMPJobs\nscrapy crawl tmp_jobs_disneycareers -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"https://jobs.disneycareers.com/search-jobs\"\n\nsample url:\n https://jobs.disneycareers.com/search-jobs\n\"\"\"\n\nfrom json import loads\nfrom urlparse import urljoin\nfrom scrapy.http import Request\nfrom urlparse import urljoin, urlparse\nfrom scrapy.selector import Selector\nfrom urllib import urlencode\nfrom brightcorp.spiders.tmp_jobs import TMP_Jobs\n\n\nclass TMPJobsDisneyCareers(TMP_Jobs):\n\n name = 'tmp_jobs_disneycareers'\n company_xpath = ['//span[b[contains(text(), \"Posting Company\")]]/span/text()']\n\n def parse(self, response):\n sel = Selector(response)\n cats = sel.xpath('//select[contains(@id, \"advanced-search-category\")]/option')\n for cat in cats:\n cat_name = cat.xpath('./text()').extract()\n # SCRP-3970 as asked to pick up only this category\n if cat_name and 'interns' in cat_name[0].lower():\n cat_id = cat.xpath('./@value').extract()[0]\n cat_url = self.start_urls[0] + '?orgIds=391&ac=%s' % cat_id\n yield Request(\n cat_url, callback=self.parse_jobslist, meta={'cat_id': cat_id}\n )\n\n def parse_jobslist(self, response):\n try:\n jsonResponse = loads(response.body.decode('utf-8'))\n sel = Selector(text=jsonResponse.get('results'), type='html')\n except:\n sel = Selector(response)\n\n if not self.expected_job_count_set:\n expected_count = sel.xpath(\n '//section/h1[@role=\"status\"]/text()'\n ).extract()\n if expected_count:\n self.expected_job_count = expected_count\n\n max_page = sel.xpath(\n '//div[@class=\"pagination-page-count\"]/input[@id=\"pagination-current-bottom\"]/@max'\n ).extract()\n if max_page:\n self.max_page = int(max_page[0])\n\n if not self.logo_url:\n self.logo_url = sel.xpath(\n '//a[@class=\"logo\"]/img/@src |'\n '//h1/a/img[contains(@src, \"logo\")]/@src'\n ).extract()\n if self.logo_url:\n if not urlparse(self.logo_url[0]).scheme:\n self.logo_url = 'http:%s' % self.logo_url[0]\n\n jobs = sel.xpath(\n '//section[@id=\"search-results-list\"]//ul/li |'\n '//section[@id=\"search-results\"]//ul/li'\n )\n for li in jobs:\n href = li.xpath('./a/@href').extract()\n if href:\n yield Request(\n callback=self.parse_job_callback(),\n meta={\n 'location': li.xpath(\n './a/*[@class=\"job-location\"]/text() |'\n './span[@class=\"job-location\"]/text()'\n ).extract(),\n },\n url=urljoin(response.url, href[0]),\n )\n\n # pagination\n next_url = sel.xpath('//a[@class=\"next\"]/@href').extract()\n if next_url:\n self.page += 1\n next_api_url = \"/search-jobs/results?ActiveFacetID=0&CurrentPage=%s&RecordsPerPage=15&Distance=50&RadiusUnitType=0&Keywords=&Location=&Latitude=&Longitude=&ShowRadius=False&FacetTerm=&FacetType=0\" % self.page + \"&FacetFilters%5B0%5D.ID=\" + response.meta.get('cat_id') + \"&FacetFilters%5B0%5D.FacetType=1&FacetFilters%5B0%5D.Count=405&FacetFilters%5B0%5D.Display=Disney+Interns&FacetFilters%5B0%5D.IsApplied=true&FacetFilters%5B0%5D.FieldName=&SearchResultsModuleName=Search+Results&SearchFiltersModuleName=Search+Filters&SortCriteria=0&SortDirection=1&SearchType=6&CategoryFacetTerm=&CategoryFacetType=&LocationFacetTerm=&LocationFacetType=&KeywordType=&LocationType=&LocationPath=&OrganizationIds=391\"\n yield Request(\n urljoin(response.url, next_api_url), callback=self.parse_jobslist,\n headers={'X-Requested-With': 'XMLHttpRequest'}, meta={'cat_id': response.meta.get('cat_id')}\n )\n","sub_path":"brightcorp/brightcorp/spiders/tmp_jobs_disneycareers.py","file_name":"tmp_jobs_disneycareers.py","file_ext":"py","file_size_in_byte":4172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"41846007","text":"#!/usr/bin/env python\n\nfrom twx.botapi import TelegramBot, send_message\nimport signal\nimport time\nimport sys\nimport os.path\n\ntry:\n import config\nexcept:\n print(\"Config not found! Please copy config.py.dist to config.py and edit the values as necessary.\")\n exit(1)\n\nUPDATE_CACHE = 'updatecache'\n\nif not os.path.isfile(UPDATE_CACHE):\n\twith open(UPDATE_CACHE, 'w') as f:\n\t\tf.write('0\\n')\n\t\tf.close()\n \nlast_update = 0\n\nwith open(UPDATE_CACHE) as f:\n last_update = int(f.readlines()[0])\n\nbot = TelegramBot(config.BOT_API_KEY)\nbot.update_bot_info().wait()\nprint(\"Running as %s \" % bot.username)\n\n\ndef exit_gracefully(signum, frame):\n\tf = open(UPDATE_CACHE,'w')\n\tf.write(str(last_update) + '\\n')\n\tf.close()\n\texit(0)\n\ndef loop():\n\tglobal last_update\n\tglobal bot\n\tupdates = bot.get_updates().wait()\n\tfor update in updates:\n\t\tif update.update_id > last_update:\n\t\t\tlast_update = update.update_id\n\t\t\tprint(update)\n\t\t\tif update.message.text == '/start':\n\t\t\t\tbot.send_message(update.message.chat.id, 'Ola, sou apenas um bot em desenvolvimento').wait()\n\t\t\tif update.message.text == '/pong':\n\t\t\t\tbot.send_message(update.message.chat.id, 'Ping!').wait()\n\nif __name__ == '__main__':\n signal.signal(signal.SIGINT, exit_gracefully)\n while True:\n loop()\n","sub_path":"bot_tg.py","file_name":"bot_tg.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"553538213","text":"# Time: O(n)\n# Space: O(n)\n#\n# There are N children standing in a line. Each child is assigned a rating value.\n# \n# You are giving candies to these children subjected to the following requirements:\n# \n# Each child must have at least one candy.\n# Children with a higher rating get more candies than their neighbors.\n# What is the minimum candies you must give?\n#\n\nclass Solution(object):\n def candy(self, ratings):\n \"\"\"\n :type ratings: List[int]\n :rtype: int\n \"\"\"\n def candy(self, ratings):\n candynum = [1 for i in range(len(ratings))]\n for i in range(1, len(ratings)):\n if ratings[i] > ratings[i-1]:\n candynum[i] = candynum[i-1] + 1\n for i in reversed(range(len(ratings)-1)):\n if ratings[i+1] < ratings[i] and candynum[i+1] >= candynum[i]:\n candynum[i] = candynum[i+1] + 1\n return sum(candynum)\n \n# http://www.cnblogs.com/zuoyuan/p/3760890.html\n# http://www.cnblogs.com/byrhuangqiang/p/4315858.html\n\n# 基本思路:先进行2次扫描,一次从左往右,一次从右往左。最后一次扫描累加出结果。\n# 第一次扫描:维护对于每一个小孩左边所需要最少的糖果数量,存入数组对应元素中。\n# 第二次扫描:维护右边所需的最少糖果数。\n# 第三次扫描:将左边和右边大的糖果数量累加到result,从而累加得出结果。\n# example: ratings = [3,4,5,1,2,3]\n \n# ratings\t3\t4\t5\t1\t2\t3\n# lefts\t1\t2\t3\t1\t2\t3\n# rights\t1\t1\t2\t1\t1\t1\n# 两者最大值\t1\t2\t3\t1\t2\t3\n# result = sum(1,2,3,1,2,3) = 12\n","sub_path":"candy-(H)-(135).py","file_name":"candy-(H)-(135).py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"99743745","text":"import socket\r\nimport protocol\r\n\r\nHEAD = protocol.HEAD\r\nTAIL = protocol.TAIL\r\nDISCONNECT_MESSAGE = '!DISCONNECT'\r\n\r\nclient = protocol.Client()\r\nclient.connect()\r\n\r\ntry:\r\n PKT_BUFFER = int(input(\"Enter packet buffer size: \"))\r\nexcept:\r\n PKT_BUFFER = 10\r\nfirst_acknowledgement = str(PKT_BUFFER)\r\nclient.send(first_acknowledgement)\r\n\r\npacket = protocol.Packet(PKT_BUFFER)\r\n\r\nmessage = \"Hello, I am a client. I am sending this message. Happy coding!\"\r\npacket.append_msg(message)\r\n\r\nactive = True\r\nwhile active:\r\n # input()\r\n buffer = protocol.from_network_layer(packet)\r\n if buffer == None:\r\n print(f\"[NOTE] No more message left.\")\r\n more_msg = input(\"Enter new message to send OR press ENTER to DISCONNECT: \")\r\n if more_msg:\r\n packet.append_msg(more_msg)\r\n continue\r\n active = False\r\n continue\r\n frame = protocol.Frame(frame_kind='data', head=HEAD, tail=TAIL, packet=buffer)\r\n protocol.to_physical_layer(frame, client)\r\n protocol.wait_for_event(event=client, t=2)\r\n print()\r\n\r\nclient.send(DISCONNECT_MESSAGE)","sub_path":"simplex-stop-and-wait-protocol/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"272784058","text":"import sys\nimport numpy as np\nimport pickle\nfrom keras.models import Model, Sequential\nfrom keras.layers import Input, Dense\nfrom keras.optimizers import Adam\nfrom keras.utils.vis_utils import plot_model\nfrom sklearn.model_selection import train_test_split\nfrom keras.layers import LSTM, Concatenate\nfrom keras.layers.embeddings import Embedding\nfrom keras.preprocessing import sequence\nfrom utilities import get_min_duration, dbclustermin, ngrams, extractFeatures, extractSignatures, multiply_durations, concat_all, get_max_packet_size, get_max_duration, extract_packet_sizes, extract_packet_size_ranges, token_frequency_features_and_labels, packet_size_features, generate_traffic_rate_features, splitAllFeatures, extract_durations, normalize_packet_sizes\nimport warnings\nfrom sklearn.metrics import confusion_matrix\nimport seaborn as sn\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import accuracy_score\nimport os\nimport random\nimport csv\nfrom statistics import multimode\nimport random\nimport statistics\n\ndef durationsToTimestamp(all_durations, max_duration=1.0):\n all_timestamps = []\n for durations in all_durations:\n timestamps = []\n float_durations = [float(x) for x in durations]\n for i in range(len(float_durations)):\n timestamps.append(sum(float_durations[0:i+1]) * max_duration)\n all_timestamps.append(timestamps)\n return all_timestamps\n\ndef flatten(features):\n flattened = []\n for feature in features:\n for f in feature:\n flattened.append(f)\n return flattened\n\ndef extractSequences(fn):\n seqs = []\n with open(fn, newline='\\n') as csvf:\n csv_reader = csv.reader(csvf, delimiter=' ')\n for row in csv_reader:\n if len(row) > 0:\n seqs.append(row)\n return seqs\n\niotg_generated_packets = extractSequences(\"final_generated_packet_sizes.txt\")\n\nwith open(\"generated_durations.pkl\", mode='rb') as tokenFile:\n iotg_flat_durations = pickle.load(tokenFile)\n\nwith open(\"syntheticPreprocessed.pkl\", mode='rb') as featuresFile:\n dg_synthetic_features = pickle.load(featuresFile)\n\nfeaturesFilePath = sys.argv[1]\ntarget_device = \"captures_master/Withings//*.pcap\"\n\nwith open(featuresFilePath, mode='rb') as featuresFile:\n raw_features = pickle.load(featuresFile)\n\ntarget_packet_sizes = extract_packet_sizes(raw_features[target_device])\ntarget_durations = extract_durations(raw_features[target_device])\nmax_packet_size_for_target = get_max_packet_size(target_packet_sizes)\nmax_duration_for_target = get_max_duration(target_durations)\n\nraw_features = splitAllFeatures(raw_features)\n\ndevice_to_packet_sizes_reals = dict()\ndevice_to_durations = dict()\ndevice_to_timestamps_reals = dict()\ndevice_to_traffic_feats_reals = dict()\n\nall_keys = []\nmax_packet_size = 0\nmax_duration = 0\nmin_duration = 1000\n\nfor key, value in raw_features.items():\n all_keys.append(key)\n device_to_packet_sizes_reals[key] = extract_packet_sizes(value)\n max_packet_size = max(get_max_packet_size(device_to_packet_sizes_reals[key]), max_packet_size)\n print(key)\n print(\"max packet size\")\n print(max_packet_size)\n current_durations = extract_durations(value)\n max_duration = max(get_max_duration(current_durations), max_duration)\n min_duration = min(get_min_duration(current_durations), min_duration)\n print(\"max duration\")\n print(max_duration)\n print(\"min duration\")\n print(min_duration)\n device_to_durations[key] = current_durations\n device_to_timestamps_reals[key] = durationsToTimestamp(current_durations)\n device_to_traffic_feats_reals[key] = generate_traffic_rate_features(concat_all(device_to_packet_sizes_reals[key], device_to_timestamps_reals[key]))\n # if key == target_device:\n # max_packet_size_for_target = max(get_max_packet_size(device_to_packet_sizes_reals[key]), max_packet_size_for_target)\n # max_duration_for_target = max(get_max_duration(current_durations), max_duration_for_target)\n\nprint(\"max size\")\nprint(get_max_packet_size(iotg_generated_packets))\nnormalized_iotg_packets = normalize_packet_sizes(iotg_generated_packets, max_packet_size=0)[0]\n\nprint(\"iotg packet size max\")\nprint(get_max_packet_size(normalized_iotg_packets))\n\ncurrentIdx = 0\niotg_durations = []\nfor gen_packet_seq in normalized_iotg_packets:\n iotg_durations.append(iotg_flat_durations[currentIdx:currentIdx+len(gen_packet_seq)])\n currentIdx += len(gen_packet_seq)\n\nnormalized_iotg_durations = multiply_durations(iotg_durations, max_duration=max_duration_for_target)\niotg_timestamps = durationsToTimestamp(normalized_iotg_durations)\niotg_traffic_rate_feats = generate_traffic_rate_features(concat_all(normalized_iotg_packets, iotg_timestamps))\n\nDG_packet_sizes = extract_packet_sizes(dg_synthetic_features[target_device])\nDG_durations = multiply_durations(extract_durations(dg_synthetic_features[target_device]), max_duration=max_duration)\nDG_timestamps = durationsToTimestamp(DG_durations)\ndg_traffic_rate_feats = generate_traffic_rate_features(concat_all(DG_packet_sizes, DG_timestamps))\n\nreal_packet_sizes = device_to_packet_sizes_reals[target_device]\nreal_timestamps = device_to_timestamps_reals[target_device]\nreal_traffic_rate_feats = device_to_traffic_feats_reals[target_device]\n\nabs_packet_length_real = []\nabs_packet_length_iotg = []\ndurations_real = list(np.array(device_to_durations[target_device]).flatten())\ndurations_iotg = list(np.array(normalized_iotg_durations).flatten())\n\nfor packets in real_packet_sizes:\n for packet in packets:\n abs_packet_length_real.append(abs(packet))\n\nfor packets in normalized_iotg_packets:\n for packet in packets:\n abs_packet_length_iotg.append(abs(packet))\n\nprint(\"average packet length real\")\nprint(statistics.mean(abs_packet_length_real))\n\nprint(\"average packet length iotg\")\nprint(statistics.mean(abs_packet_length_iotg))\n\nprint(\"average packet length standard deviation real\")\nprint(statistics.stdev(abs_packet_length_real))\n\nprint(\"average packet length standard deviation iotg\")\nprint(statistics.stdev(abs_packet_length_iotg))\n\nprint(\"average duration real\")\nprint(statistics.mean(durations_real))\n\nprint(\"average duration iotg\")\nprint(statistics.mean(durations_iotg))\n\nprint(\"average duration standard deviation real\")\nprint(statistics.stdev(durations_real))\n\nprint(\"average duration standard deviation iotg\")\nprint(statistics.stdev(durations_iotg))\n\nresults_file = \"average_packet_lengths_dg.pkl\"\nif os.path.isfile(results_file):\n with open(results_file, mode='rb') as tokenFile:\n results_dict = pickle.load(tokenFile)\nelse:\n results_dict = dict()\n\nresults_dict[target_device] = statistics.mean(abs_packet_length_iotg)\n\nwith open(results_file, mode='wb') as featureOutputFile:\n pickle.dump(results_dict, featureOutputFile)\n\nresults_file = \"stdev_packet_lengths_dg.pkl\"\nif os.path.isfile(results_file):\n with open(results_file, mode='rb') as tokenFile:\n results_dict = pickle.load(tokenFile)\nelse:\n results_dict = dict()\n\nresults_dict[target_device] = statistics.stdev(abs_packet_length_iotg)\n\nwith open(results_file, mode='wb') as featureOutputFile:\n pickle.dump(results_dict, featureOutputFile)\n\nresults_file = \"average_duration_dg.pkl\"\nif os.path.isfile(results_file):\n with open(results_file, mode='rb') as tokenFile:\n results_dict = pickle.load(tokenFile)\nelse:\n results_dict = dict()\n\nresults_dict[target_device] = statistics.mean(durations_iotg)\n\nwith open(results_file, mode='wb') as featureOutputFile:\n pickle.dump(results_dict, featureOutputFile)\n\nresults_file = \"stdev_duration_dg.pkl\"\nif os.path.isfile(results_file):\n with open(results_file, mode='rb') as tokenFile:\n results_dict = pickle.load(tokenFile)\nelse:\n results_dict = dict()\n\nresults_dict[target_device] = statistics.stdev(durations_iotg)\n\nwith open(results_file, mode='wb') as featureOutputFile:\n pickle.dump(results_dict, featureOutputFile)\n\nresults_file = \"average_duration_real.pkl\"\nif os.path.isfile(results_file):\n with open(results_file, mode='rb') as tokenFile:\n results_dict = pickle.load(tokenFile)\nelse:\n results_dict = dict()\n\nresults_dict[target_device] = statistics.mean(durations_real)\n\nwith open(results_file, mode='wb') as featureOutputFile:\n pickle.dump(results_dict, featureOutputFile)\n\nresults_file = \"stdev_duration_real.pkl\"\nif os.path.isfile(results_file):\n with open(results_file, mode='rb') as tokenFile:\n results_dict = pickle.load(tokenFile)\nelse:\n results_dict = dict()\n\nresults_dict[target_device] = statistics.stdev(durations_real)\n\nwith open(results_file, mode='wb') as featureOutputFile:\n pickle.dump(results_dict, featureOutputFile)","sub_path":"experiment10.py","file_name":"experiment10.py","file_ext":"py","file_size_in_byte":8738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"302548424","text":"#-*- coding: utf-8 -*-\nfrom django.shortcuts import render\nfrom Semestre.models import Semestre, InstanceSemestre\nfrom Semestre.forms import SemestreForm, SelectSem, RenseignerSem,InstanceSemestreForm,SelectInstanceSemestre,EvolutionSemestreForm\nfrom UE.models import UE\nfrom Matiere.models import Matiere\nfrom django.shortcuts import render, get_object_or_404\nfrom Etudiant.models import Appartient, Etu\nfrom Note.models import Resultat_Semestre\nfrom Diplome.models import Diplome\n# Create your views here.\n\n\"\"\"Cette vue permet d'ajouter un semestre\"\"\"\ndef ajouterSemestre(request):\n\tif request.method == 'POST': \n\t\tform = SemestreForm(request.POST)\n\t\tif form.is_valid():\n\n\t\t\tcode_ppn = form.cleaned_data['code_ppn']\n\t\t\tcode_apogee = form.cleaned_data['code_apogee']\n\t\t\tdip = form.cleaned_data['diplome']\n\t\t\tintitule = form.cleaned_data['intitule']\n\t\t\tsem = Semestre(\n\t\t\t\t\tcode_ppn=code_ppn,\n\t\t\t\t\tcode_apogee=code_apogee,\n\t\t\t\t\tintitule=intitule,\n\t\t\t\t\tdiplome = dip,\t\t\t\t\t\n\t )\n\t\t\tsem.save()\n\t\t\tres = True\n\t\telse :\n\t\t\tprint(\"ERREUR : AJOUTER Semestre : VIEW ajouterUE : formulaire\")\n\telse :\n\t\tdiplomes = Diplome.objects.all()\n\t\tform = SemestreForm(diplomes=diplomes) \n\treturn render(request, 'contenu_html/ajouterSemestre.html', locals())\n\n\"\"\"Cette vue permet de lister les semestres\"\"\"\ndef listerSemestre(request):\n\tsemestre = Semestre.objects.all()\n\treturn render(request, 'contenu_html/listerSemestre.html',{'semestre': semestre})\n\n\"\"\"Cette vue permet de supprimer un semestre\"\"\"\ndef supprsem(request, id):\n\tsemestre = Semestre.objects.filter(id=id)\n\tue = UE.objects.filter(semestre_id=id)\n\n\tif ue :\n\t\tue.delete()\n\n\tmatiere = Matiere.objects.filter(ue_id=id)\n\n\tif matiere :\n\t\tmatiere.delete()\n\n\tsemestre.delete()\n\treturn render(request, 'contenu_html/supprsem.html', locals())\n\n\"\"\"Cette vue permet de modifier un semestre\"\"\"\ndef modifierSemestre(request):\n\tif request.method == 'POST':\n\t\tif not request.session['sem']:\n\t\t\tSemestres = Semestre.objects.all()\n\t\t\tform = SelectSem(request.POST, semestres=Semestres)\n\t\t\tif form.is_valid() :\n\t\t\t\tid_sem = form.cleaned_data['select']\n\t\t\t\trequest.session['id_sem'] = id_sem\n\t\t\t\trequest.session['sem'] = True\n\t\t\tres = True\n\t\t\ts = get_object_or_404(Semestre, id=request.session['id_sem'])\n\t\t\tform = RenseignerSem(semestre=s)\n\t\telse:\n\t\t\ts = get_object_or_404(Semestre, id=request.session['id_sem'])\n\t\t\tform = RenseignerSem(request.POST, semestre=s)\n\t\t\tif form.is_valid() :\n\t\t\t\tsemestre = get_object_or_404(Semestre, id=request.session['id_sem'])\n\t\t\t\tif form.cleaned_data['intitule']:\n\t\t\t\t\tsemestre.intitule = form.cleaned_data['intitule']\n\t\t\t\tif form.cleaned_data['code']:\n\t\t\t\t\tsemestre.code = form.cleaned_data['code']\n\t\t\t\tif form.cleaned_data['diplome']:\n\t\t\t\t\tsemestre.diplome = form.cleaned_data['diplome']\n\t\t\t\tsemestre.save()\t\n\t\t\t\t#request.session['mat'] = False\n\t\t\t\tres2=True\n\t\t\telse :\n\t\t\t\tprint(\"ERREUR : MODIFIER Semestre : VIEW modifierSemestre : formulaire\")\t\n\telse :\n\t\tSemestres = Semestre.objects.all()\n\t\trequest.session['sem'] = False\n\t\tform = SelectSem(semestres=Semestres)\n\treturn render(request, 'contenu_html/modifierSemestre.html', locals())\n\n\ndef ajouter_instance_semestre(request):\n\tif request.method == 'POST': \n\t\tform = InstanceSemestreForm(request.POST)\n\t\tif form.is_valid():\n\n\t\t\tannee = form.cleaned_data['annee']\n\t\t\tsemestre = form.cleaned_data['semestre']\n\t\t\t\n\t\t\t# L'instance du semestre\n\t\t\tIS = InstanceSemestre(\n\t\t\t\t\tannee=annee,\n\t\t\t\t\tsemestre = semestre,\t\t\t\t\t\n\t\t\t)\n\n\t\t\tIS.save()\n\t\t\tres = True\n\t\telse :\n\t\t\tprint(\"ERREUR : AJOUTER IS : VIEW ajouter_instance_semestre : formulaire\")\n\telse :\n\t\tform = InstanceSemestreForm()\n\treturn render(request, 'contenu_html/ajouterInstanceSemestre.html', locals())\n\n\n\"\"\"Cette vue permet de faire afficher les étudiants d'une Instance de semestre\"\"\"\ndef afficherInstanceSemestre(request):\n\tif request.method == 'POST':\n\t\tinstanceSemestres = InstanceSemestre.objects.all()\n\t\tform = SelectInstanceSemestre(request.POST, instanceSemestres=instanceSemestres)\n\t\tif form.is_valid() :\n\t\t\tid_inst = form.cleaned_data['select']\n\t\t\tinstanceSemestre = get_object_or_404(InstanceSemestre, id=id_inst)\n\t\t\tlisteEtu = Appartient.objects.filter(instance_semestre=instanceSemestre)\n\t\t\tres = True\n\t\telse:\n\t\t\tprint(\"ERREUR : Afficher promotion: VIEW afficher Promotion : formulaire\")\t\n\telse:\n\t\tinstanceSemestres = InstanceSemestre.objects.all()\n\t\tform = SelectInstanceSemestre(instanceSemestres=instanceSemestres)\n\treturn render(request, 'contenu_html/afficherInstanceSemestre.html', locals())\n\n\"\"\"Cette vue permet de faire evoluer les semestres instanciées\"\"\"\ndef faireEvoluerInstanceSemestre(request): \n\tif request.method == 'POST':\n\t\tif not request.session['inst']:\n\t\t\tinstances = InstanceSemestre.objects.all()\n\t\t\tform = SelectInstanceSemestre(request.POST, instanceSemestres=instances)\n\t\t\tif form.is_valid() :\n\t\t\t\tid_instance = form.cleaned_data['select']\n\t\t\t\trequest.session['id_instance'] = id_instance\n\t\t\t\trequest.session['inst']=True\n\t\t\tinstance = get_object_or_404(InstanceSemestre, id=request.session['id_instance'])\n\t\t\tlignes= Appartient.objects.filter(instance_semestre=instance).count() + 1\n\t\t\tlisteEvolution=[[\"\"]* 4 for _ in range(lignes)]\n\t\t\tlisteEvolution[0][0]= \"Nom\"\n\t\t\tlisteEvolution[0][1]= \"Prénom\"\n\t\t\tlisteEvolution[0][2]= \"Résultat du Semestre\"\n\n\t\t\tlisteAppartient=Appartient.objects.filter(instance_semestre=instance)\n\t\t\tprint(listeAppartient)\n\t\t\ti=1\n\t\t\tfor ligne in listeAppartient:\n\t\t\t\tprint(ligne)\n\t\t\t\ttry:\n\t\t\t\t\tresSemestre= Resultat_Semestre.objects.get(etudiant=ligne.etudiant,instance_semestre=instance)\n\t\t\t\t\tlisteEvolution[i][0]=ligne.etudiant.nom\n\t\t\t\t\tlisteEvolution[i][1]=ligne.etudiant.prenom\n\t\t\t\t\tlisteEvolution[i][2]=resSemestre.resultat\n\t\t\t\t\tlisteEvolution[i][3]=ligne.etudiant.apogee\n\t\t\t\t\ti+=1\n\t\t\t\texcept Resultat_Semestre.DoesNotExist:\n\t\t\t\t\tlisteEvolution[i][0]=ligne.etudiant.nom\n\t\t\t\t\tlisteEvolution[i][1]=ligne.etudiant.prenom\n\t\t\t\t\tlisteEvolution[i][2]='Résultat inexistant'\n\t\t\t\t\tlisteEvolution[i][3]=ligne.etudiant.apogee\t\n\t\t\t\t\ti+=1\n\t\t\t\t\tprint('Erreur, cet etudiant n\\'a pas de Resultat_Semestre')\t\n\t\t\tres = True\n\t\t\trequest.session['listeEvolution'] = listeEvolution\n\t\t\tinstances = InstanceSemestre.objects.all()\n\t\t\tform = EvolutionSemestreForm(listeAppartient=listeAppartient,instanceSemestres=instances)\n\t\t\ti=1\n\t\t\tfor ligne in listeAppartient:\n\t\t\t\tlisteEvolution[i][3] = str(form[str(ligne.etudiant.apogee)])\n\t\t\t\ti +=1\t\n\t\telse:\n\t\t\tinstances = InstanceSemestre.objects.all()\n\t\t\tinstance = get_object_or_404(InstanceSemestre, id=request.session['id_instance'])\n\t\t\tlisteAppartient=Appartient.objects.filter(instance_semestre=instance)\n\t\t\tform = EvolutionSemestreForm(request.POST, listeAppartient=listeAppartient,instanceSemestres=instances)\n\t\t\t\n\t\t\tif form.is_valid() :\n\t\t\t\tif form.cleaned_data['select']:\n\t\t\t\t\t\tnew_instance = form.cleaned_data['select']\n\t\t\t\t\t\tinstance = get_object_or_404(InstanceSemestre, id=new_instance)\n\t\t\t\tfor ligne in listeAppartient:\n\t\t\t\t\tif form.cleaned_data[str(ligne.etudiant.apogee)]:\n\t\t\t\t\t\tappartient = Appartient(\n\t\t\t\t\t\t\tinstance_semestre = instance,\n\t\t\t\t\t\t\tetudiant = ligne.etudiant,\n\t\t\t\t\t\t)\n\t\t\t\t\t\tappartient.save()\n\t\t\t\tres2=True\n\t\t\telse:\n\t\t\t\tprint(\"ERREUR : Afficher faire evoluer instance: VIEW faire evoluer instance : formulaire\")\t\n\telse:\n\t\tinstances = InstanceSemestre.objects.all()\n\t\trequest.session['inst']=False\n\t\tform = SelectInstanceSemestre(instanceSemestres=instances)\n\treturn render(request, 'contenu_html/faireEvoluerInstance.html',locals())","sub_path":"Semestre/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"395821191","text":"class Node(object):\n def __init__(self, data):\n self.data = data\n self.next = None\n #1 -> 2 -> 3 -> None\ndef length(node):\n # Your code goes here.\n nDone = True\n length = 0\n currentNode = node\n\n while True:\n if currentNode is None:\n nDone = False\n break\n \n length = length + 1\n currentNode = currentNode.next\n\n return length\n \ndef count(node, data):\n # Your code goes here.\n count = 0\n current_node = node\n while True:\n if current_node is None:\n break\n\n if current_node.data == data:\n count = count + 1\n \n current_node = current_node.next\n\n return count","sub_path":"python solutions/linkedListLest.py","file_name":"linkedListLest.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"516525580","text":"from django.shortcuts import render\nfrom django.shortcuts import get_object_or_404\nfrom django.http import HttpResponse,JsonResponse,HttpResponseRedirect\nfrom django.contrib.auth.decorators import login_required\n\n@login_required(login_url='/accounts/login/')\ndef index(request):\n return render(request, 'home.html')\n\n@login_required(login_url='/accounts/login/')\ndef profile(request):\n return render(request, 'profile.html')\n\n\nfrom django.http import HttpResponse\nfrom django.views.generic import FormView\nfrom .models import ExUserProfile\nfrom .forms import ProfileForm\n\n#\n# class ProfileEdit(FormView):\n# template_name = 'profile.html'\n# success_url = '/awesome/'\n# form_class = ProfileForm\n#\n# def form_valid(self, form):\n#\n# return HttpResponse(\"dlldsk\")\n\n\n@login_required(login_url='/accounts/login/')\ndef profile_view(request):\n error = False\n if request.method == \"POST\":\n form = ProfileForm(request.POST)\n if form.is_valid():\n\n userlastname = form.cleaned_data[\"last_name\"]\n userfirstname = form.cleaned_data[\"first_name\"]\n human=form.cleaned_data[\"is_human\"]\n\n u = request.user\n u.first_name = userfirstname\n u.last_name = userlastname\n u.save()\n form.save(commit=True)\n return index(request)\n else:\n error = True\n else:\n form = ProfileForm()\n return render(request, \"profile.html\", locals())\n","sub_path":"log/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"399725338","text":"import json\nfrom datetime import datetime\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np \nimport matplotlib.lines as mlines\nfrom os import listdir\nimport os\nimport time\nfrom os.path import isfile, join\nimport CMethods\nimport shutil\nprint(\"Starting!\")\nalgoNumber = 6\neverySo = 1\nINPUT_PATH = \"./data/USDT-BAT\"\nSUMMARIES_PATH = \"./data/summaries/\"\nOUTPUT_PATH = \"./CMData/USDT-BAT\"\nCANDLE_PATH = \"./candles/USDT-BAT-c.json\"\nfig, (ax1) = plt.subplots(1)\nfig.suptitle('Bottom: Volume - Top: Candles')\n\nonlyfiles = [f for f in sorted(listdir(INPUT_PATH)) if isfile(join(INPUT_PATH, f))]\nsummaryfiles = [f for f in sorted(listdir(SUMMARIES_PATH)) if isfile(join(SUMMARIES_PATH, f))]\ncounter = 0\n\n#Cleaning files\nif(os.path.exists(OUTPUT_PATH)):\n shutil.rmtree(OUTPUT_PATH)\nos.mkdir(OUTPUT_PATH)\nfor i in onlyfiles:\n if(counter % everySo == 0):\n CMethods.findAddressChanges((INPUT_PATH + \"/\" + i).encode(), (OUTPUT_PATH + \"/\" + i).encode(), CANDLE_PATH.encode(), (SUMMARIES_PATH + summaryfiles[counter]).encode(), algoNumber)\n print(\"Compiling data: \" + str((counter / len(summaryfiles)) * 100))\n counter += 1\n\ncounter = 0\n#Plotting the candles\ncandles = {}\n\nwith open(CANDLE_PATH) as json_file:\n candles = json.load(json_file)\n json_file.close()\n\ndef splitXandY(points, xLabel, yLabel):\n xArray = []\n yArray = []\n for i in points:\n xArray.append(i[xLabel])\n yArray.append(i[yLabel])\n return {'x':xArray, 'y': yArray}\n\ndef dateToUnix(date):\n year = 0\n month = 0\n day = 0\n hour = 0\n minute = 0\n second = 0\n temp = \"\"\n ticker = 0\n for i in date:\n if(i == '-' or i == 'T' or i == \":\"):\n if(ticker == 0):\n year = int(temp)\n if(ticker == 1):\n month = int(temp)\n if(ticker == 2):\n day = int(temp)\n if(ticker == 3):\n hour = int(temp)\n if(ticker == 4):\n minute = int(temp)\n if(ticker == 5):\n second = int(temp)\n temp = \"\"\n ticker += 1\n continue\n temp = temp + i\n return (datetime(year,month,day,hour,minute,second) - datetime(1970, 1, 1)).total_seconds()\n\nfor i in candles[\"result\"]:\n unixtime = dateToUnix(i[\"T\"])#time.mktime(time.strptime(i['T'], '%Y-%m-%dT%H:%M:%S'))\n \n i['TM'] = float(unixtime)\n #i['TM'] = i['T']\n i['C'] = float(i['C'])\n print(\"Plotting candles: \" + str((counter / len(candles[\"result\"])) * 100))\n counter += 1\n\ncoordinateData = splitXandY(candles['result'], 'TM', 'C')\n#volumeData = splitXandY(candles['result'], 'TM', 'V')\n#baseVolumeData = splitXandY(candles['result'], 'TM', 'H')\nax1.plot(coordinateData['x'], coordinateData['y'])\n#ax2.plot(volumeData['x'], volumeData['y'])\n\n\ncounter = 0\noutfiles = [f for f in sorted(listdir(OUTPUT_PATH)) if isfile(join(OUTPUT_PATH, f))]\n\n\n \ndef convertRGBtoHex(r,g,b):\n if(r > 255):\n r = 255\n elif(r < 0):\n r = 0\n if(g > 255):\n g = 255\n elif(g < 0):\n g = 0\n if(b > 255):\n b = 255\n elif(b < 0):\n b = 0\n return '#%02x%02x%02x' % (r,g,b)\n\nSCX = []\nSCY = []\nSCC = []\nfor i in outfiles:\n \n \n json_file = None\n with open(OUTPUT_PATH + \"/\" + i) as json_file:\n data2 = json.load(json_file)\n SCX += data2[\"book\"][\"data\"][\"x\"]\n SCY += data2[\"book\"][\"data\"][\"y\"]\n SCC += data2[\"book\"][\"data\"][\"c\"]\n \"\"\"if(algoNumber == 0):\n algo0(data2[\"book\"][\"data\"])\n elif(algoNumber == 1):\n algo1(data2)\n elif(algoNumber == 2):\n algo2(data2)\"\"\"\n json_file.close()\n print(\"Plotting dots: \" + str((counter / len(outfiles)) * 100))\n counter += 1\n \nax1.scatter(SCX, SCY, c=SCC)\n\nplt.xlabel('Date')\nplt.ylabel('Price')\nplt.show()\n#https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName=BTC-XMR&tickInterval=onemin&_=1499127220008","sub_path":"dataGrapher.py","file_name":"dataGrapher.py","file_ext":"py","file_size_in_byte":3968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"505280432","text":"from tkinter import *\nfrom tkinter import ttk\nimport sqlite3\nimport datetime\n\ndef add_customer():\n r = e_id.get()\n n = e_name.get()\n e = e_email.get()\n m = e_mobile.get()\n prod_name = e_prod_name.get()\n prod_price =e_prod_price.get()\n time= datetime.datetime.now()\n d = e_dob.get()\n a = t_address.get(\"1.0\",END)\n\n conn = sqlite3.connect('customerdatabase.db')\n c = conn.cursor()\n c.execute('INSERT INTO customer VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?)' , (r, n, e, m, prod_name,prod_price,time, d, a))\n conn.commit()\n conn.close()\n\n show_all()\n\n clear_all()\n\ndef show_all():\n e_search.delete(0, END)\n conn = sqlite3.connect('customerdatabase.db')\n c = conn.cursor()\n c.execute('SELECT * FROM customer')\n customer_table.delete(*customer_table.get_children())\n for r in c:\n customer_table.insert(\"\", \"end\", values=r)\n conn.commit()\n conn.close()\n\ndef clear_all():\n e_id.delete(0, END)\n e_name.delete(0, END)\n e_email.delete(0, END)\n e_mobile.delete(0, END)\n e_prod_name.delete(0, END)\n e_prod_price.delete(0, END)\n e_dob.delete(0, END)\n t_address.delete(1.0, END)\n\n\ndef get_data(event):\n current = customer_table.item(customer_table.focus())\n row = current[\"values\"] #focussed row stored in current as a dictionary\n\n clear_all()\n\n e_id.insert(0, row[0])\n e_name.insert(0, row[1])\n e_email.insert(0, row[2])\n e_mobile.insert(0, row[3])\n e_prod_name.insert(0, row[4])\n e_prod_price.insert(0, row[5])\n e_dob.insert(0, row[7])\n t_address.insert(1.0, row[8])\n \n\n \ndef update_customer():\n n = e_name.get()\n e = e_email.get()\n m = e_mobile.get()\n prod_name = e_prod_name.get()\n prod_price = e_prod_price.get()\n time = datetime.datetime.now()\n u = e_dob.get()\n a = t_address.get(\"1.0\",END)\n r = e_id.get()\n \n \n conn = sqlite3.connect('customerdatabase.db')\n c = conn.cursor()\n c.execute('UPDATE customer SET name= ?, email = ? , mobile = ?, prod_name= ? ,prod_price= ?, time= ?, dob= ?, address= ? WHERE id= ?' , (n,e,m,prod_name,prod_price,time,u,a,r))\n conn.commit()\n conn.close()\n show_all()\n clear_all()\n\ndef delete_customer():\n r = e_id.get()\n \n conn = sqlite3.connect('customerdatabase.db')\n c = conn.cursor()\n c.execute('DELETE FROM customer WHERE id = ?' , (r,) )\n conn.commit()\n conn.close()\n show_all()\n clear_all()\n\ndef search_customer():\n s = c_search.get()\n key = e_search.get()\n\n conn = sqlite3.connect('customerdatabase.db')\n c = conn.cursor()\n c.execute(\"SELECT * FROM customer WHERE \"+s+\"= ?\", (key,))\n customer_table.delete(*customer_table.get_children())\n for r in c:\n customer_table.insert(\"\", \"end\", values=r)\n conn.commit()\n conn.close()\n \n \nmaster = Tk()\nmaster.title('Customer Management System')\nmaster.geometry('1400x900')\n\n\ntitle = Label(master, text=\"Customer Management System\", font=(\"Roman\",40,\"bold\"), bg=\"crimson\", fg=\"white\", bd=7, relief=GROOVE)\ntitle.pack(side=TOP, fill=X)\n\nleft_frame = Frame(master, bg=\"crimson\", bd=4, relief=RIDGE)\nleft_frame.place(x=20, y=90, width=550, height=700)\n\nleft_frame_title = Label(left_frame, text=\"Manage Customer\", font=(\"Calibri\",30,\"bold\"), bg=\"white\", fg=\"crimson\", bd=4, relief=GROOVE)\nleft_frame_title.pack(side=TOP, fill=X)\n\nl_id = Label(left_frame, text=\"ID.\", font=(\"Calibri\",25,\"bold\"), fg=\"white\", bg=\"crimson\") #why bg\nl_id.place(x=20, y=60)\ne_id = Entry(left_frame, font=(\"Calibri\",18))\ne_id.place(x=230, y=70)\n\nl_name = Label(left_frame, text=\"Name\", font=(\"Calibri\",25,\"bold\"), fg=\"white\", bg=\"crimson\")\nl_name.place(x=20, y=110)\ne_name = Entry(left_frame, font=(\"Calibri\",18))\ne_name.place(x=230, y=120)\n\nl_email = Label(left_frame, text=\"Email\", font=(\"Calibri\",25,\"bold\"), fg=\"white\", bg=\"crimson\")\nl_email.place(x=20, y=160)\ne_email = Entry(left_frame, font=(\"Calibri\",18))\ne_email.place(x=230, y=170)\n\nl_mobile = Label(left_frame, text=\"Mobile\", font=(\"Calibri\",25,\"bold\"), fg=\"white\", bg=\"crimson\")\nl_mobile.place(x=20, y=215)\ne_mobile = Entry(left_frame, font=(\"Calibri\",18))\ne_mobile.place(x=230, y=220)\n\nl_prod_name = Label(left_frame, text=\"Product Name\", font=(\"Calibri\",25,\"bold\"), fg=\"white\", bg=\"crimson\")\nl_prod_name.place(x=20, y=265)\ne_prod_name = Entry(left_frame, font=(\"Calibri\",18))\ne_prod_name.place(x=230, y=270)\n\nl_prod_price = Label(left_frame, text=\"Product Price\", font=(\"Calibri\",25,\"bold\"), fg=\"white\", bg=\"crimson\")\nl_prod_price.place(x=20, y=310)\ne_prod_price = Entry(left_frame, font=(\"Calibri\",18))\ne_prod_price.place(x=230, y=320)\n\nl_dob1 = Label(left_frame, text=\"DOB\", font=(\"Calibri\",25,\"bold\"), fg=\"white\", bg=\"crimson\")\nl_dob1.place(x=20, y=370)\nl_dob2 = Label(left_frame, text=\"(dd/mm/yyyy)\", font=(\"Calibri\",20), fg=\"white\", bg=\"crimson\")\nl_dob2.place(x=20, y=410)\ne_dob = Entry(left_frame, font=(\"Calibri\",18))\ne_dob.place(x=230, y=390)\n\nl_address = Label(left_frame, text=\"Address\", font=(\"Calibri\",25,\"bold\"), fg=\"white\", bg=\"crimson\")\nl_address.place(x=20, y=460)\nt_address = Text(left_frame, font=(\"Calibri\",18), width=20, height=3)\nt_address.place(x=230, y=460)\n\n\n\nb_add = Button(left_frame, text='Add', width=8, height=1, command=add_customer)\nb_add.place(x=130, y=585)\n\nb_update = Button(left_frame, text='Update', width=8, height=1, command=update_customer)\nb_update.place(x=230, y=585)\n\nb_delete = Button(left_frame, text='Delete', width=8, height=1, command=delete_customer)\nb_delete.place(x=330, y=585)\n\nright_frame = Frame(master, bg=\"crimson\", bd=4, relief=RIDGE)\nright_frame.place(x=590, y=90, width=750, height=700)\n\nl_search = Label(right_frame, text=\"Search by\", font=(\"Calibri\",25,\"bold\"), fg=\"white\", bg=\"crimson\")\nl_search.place(x=11, y=8)\nc_search = ttk.Combobox(right_frame, width=7, font=(\"Calibri\",15), state='readonly')\nc_search[\"values\"] = (\"id\",\"name\",\"mobile\")\nc_search.current(0)\nc_search.place(x=170, y=18)\ne_search = Entry(right_frame, font=(\"Calibri\",16), width=10)\ne_search.place(x=280, y=18)\nb_search = Button(right_frame, text=\"Search\", font=(\"Calibri\",13), width=7, command=search_customer)\nb_search.place(x=420, y=16)\nb_showall = Button(right_frame, text=\"Show All\", font=(\"Calibri\",13), width=7, command=show_all)\nb_showall.place(x=520, y=16)\n\ntable_frame = Frame(right_frame, bg=\"crimson\", bd=4, relief=RIDGE)\ntable_frame.place(x=20, y=70, width=720, height=500)\n\nhs = Scrollbar(table_frame, orient=HORIZONTAL)\nhs.pack(side=BOTTOM, fill=X)\nvs = Scrollbar(table_frame, orient=VERTICAL)\nvs.pack(side=RIGHT, fill=Y)\ncustomer_table = ttk.Treeview(table_frame, columns=(\"r\", \"n\", \"e\", \"m\",\"prod_name\",\"prod_price\",\"time\", \"d\", \"a\"))\nhs.config(command=customer_table.xview)\nvs.config(command=customer_table.yview)\n\ncustomer_table.heading(\"r\", text=\"ID.\")\ncustomer_table.heading(\"n\", text=\"Name\")\ncustomer_table.heading(\"e\", text=\"Email ID\")\ncustomer_table.heading(\"m\", text=\"Mobile\")\ncustomer_table.heading(\"prod_name\", text=\"prod name\")\ncustomer_table.heading(\"prod_price\", text=\"price\")\ncustomer_table.heading(\"time\", text=\"time\")\n\ncustomer_table.heading(\"d\", text=\"DOB\")\ncustomer_table.heading(\"a\", text=\"Address\")\ncustomer_table[\"show\"] = \"headings\"\n#shows only those columns in which headings are present, does not show the default index column.\ncustomer_table.pack(fill=Y, expand=1)\n#customer_table.pack(fill=BOTH, expand=1)\ncustomer_table.column(\"r\", width=30)\ncustomer_table.column(\"n\", width=100)\ncustomer_table.column(\"e\", width=150)\ncustomer_table.column(\"m\", width=100)\ncustomer_table.column(\"prod_name\", width=100)\ncustomer_table.column(\"prod_price\", width=75)\ncustomer_table.column(\"time\", width=75)\ncustomer_table.column(\"d\", width=90)\ncustomer_table.column(\"a\", width=180)\ncustomer_table[\"show\"] = \"headings\"\ncustomer_table.bind(\"<ButtonRelease-1>\", get_data)\n\ntry:\n conn = sqlite3.connect('customerdatabase.db')\n c = conn.cursor()\n c.execute('CREATE TABLE customer (id CHAR(3), name VARCHAR(20), email VARCHAR(20), mobile CHAR(10),prod_name varchar(30),prod_price varchar(30),time varchar(30), dob CHAR(10), address VARCHAR(30))')\n conn.commit()\n conn.close()\nexcept sqlite3.OperationalError:\n pass\n\nmaster.mainloop()\n\n\n","sub_path":"customermanagementlatest.py","file_name":"customermanagementlatest.py","file_ext":"py","file_size_in_byte":8169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"440626237","text":"from twisted.internet import reactor, protocol, defer\nfrom twisted.python import log\n\nfrom txredis.protocol import Redis, RedisSubscriber\n\nimport sys\n\n\nREDIS_HOST = 'localhost'\nREDIS_PORT = 6379\n\n\nclass Subscriber(RedisSubscriber):\n\n num_channels = 0\n\n def channelSubscribed(self, channel, numSubscribed):\n self.num_channels += 1\n\n def channelUnsubscribed(self, channel, numSubscribed):\n self.num_channels -= 1\n\n def messageReceived(self, channel, message):\n log.msg(\"got message %r on channel %s\" % (message, channel))\n\n\n@defer.inlineCallbacks\ndef getRedisSubscriber():\n clientCreator = protocol.ClientCreator(reactor, Subscriber)\n redis = yield clientCreator.connectTCP(REDIS_HOST, REDIS_PORT)\n defer.returnValue(redis)\n\n\n@defer.inlineCallbacks\ndef getRedis():\n clientCreator = protocol.ClientCreator(reactor, Redis)\n redis = yield clientCreator.connectTCP(REDIS_HOST, REDIS_PORT)\n defer.returnValue(redis)\n\n\n@defer.inlineCallbacks\ndef runTest():\n redis1 = yield getRedisSubscriber()\n redis2 = yield getRedis()\n\n log.msg(\"redis1: SUBSCRIBE w00t\")\n response = yield redis1.subscribe(\"w00t\")\n log.msg(\"subscribed to w00t, response = %r\" % response)\n\n while redis1.num_channels == 0:\n d = defer.Deferred()\n reactor.callLater(0.1, d.callback, True)\n yield d\n\n log.msg(\"redis2: PUBLISH w00t 'Hello, world!'\")\n response = yield redis2.publish(\"w00t\", \"Hello, world!\")\n log.msg(\"published to w00t, response = %r\" % response)\n\n\ndef main():\n log.startLogging(sys.stdout)\n reactor.callLater(0, runTest)\n reactor.run()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"examples/pubsub.py","file_name":"pubsub.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"528771392","text":"from collections import UserDict\r\nfrom datetime import datetime\r\nfrom datetime import date\r\nimport math\r\nimport re\r\nimport json\r\n\r\nclass AddressBook(UserDict):\r\n def __init__(self, name):\r\n super().__init__()\r\n self.name = name\r\n self.current_page = 0\r\n self.records_on_the_page = 2\r\n\r\n def add_record(self,record):\r\n self.data [record.name.value] = record\r\n\r\n def __iter__(self):\r\n return self\r\n\r\n def __next__(self):\r\n if self.current_page < int(math.ceil(len(self.data)/self.records_on_the_page)) :\r\n keys = list(self.data.keys())\r\n r_list = [] \r\n for i in range(self.current_page*self.records_on_the_page ,min([(self.current_page+1)*self.records_on_the_page,len(self.data)])):\r\n a_dict = {} \r\n a_dict[\"Name\"] = keys[i]\r\n a_dict[\"Phones\"]= [x.value for x in self.data[keys[i]].phones]\r\n if type(self.data[keys[i]].birthday)!=type(\"\"):\r\n a_dict[\"Birthday\"]= str(self.data[keys[i]].birthday.value)\r\n r_list.append(a_dict)\r\n self.current_page+=1\r\n return r_list\r\n else:\r\n self.current_page = 0\r\n raise StopIteration\r\n\r\n def delete(self, name):\r\n if name in self.data.keys():\r\n print(\"Input 'Y' to delete the record for contact: \", name)\r\n if input() in [\"Y\", \"y\"]:\r\n self.data.pop(name)\r\n print(\"Record deleted\")\r\n else:\r\n print(\"Delete of the record cancelled\")\r\n\r\n def dump(self, file):\r\n with open(file, 'w+') as write_file:\r\n dump_dict ={self.name:{}}\r\n store_records_on_the_page = self.records_on_the_page\r\n self.records_on_the_page = 1\r\n id =1\r\n for page in self:\r\n dump_dict[self.name][\"RecID\"+str(id)]= page[0]\r\n id+=1\r\n json.dump(dump_dict, write_file)\r\n self.records_on_the_page = store_records_on_the_page\r\n print(\"Data exported to the file\")\r\n\r\n def load(self, file):\r\n with open(file, 'r') as read_file:\r\n data = json.load(read_file)\r\n self.name= list(data.keys())[0]\r\n for name in list(data[self.name].keys()):\r\n record = data[self.name][name]\r\n rec = Record(record[\"Name\"])\r\n if \"Phones\" in record.keys():\r\n for phone in record[\"Phones\"]:\r\n rec.add_phone(Phone(phone))\r\n if \"Birthday\" in record.keys():\r\n lst = record[\"Birthday\"].split(\"-\")\r\n birthday = Birthday(lst[2]+\".\"+lst[1]+\".\"+lst[0])\r\n rec.add_birthday(birthday)\r\n self.add_record(rec)\r\n print (\"Data have been loaded from file\") \r\n\r\n def find(self, request):\r\n result_lst = []\r\n for name in self.data.keys():\r\n search_list = [name]\r\n search_list.extend([phone.value for phone in self.data[name].phones])\r\n for field in search_list:\r\n if request[0]==\"+\":\r\n request = request[1:] \r\n if re.search(request.upper(),field.upper())!=None:\r\n result_lst.append(name)\r\n break\r\n return result_lst \r\n \r\nclass Record:\r\n def __init__(self, name):\r\n self.phones = list()\r\n self.birthday = \"\"\r\n self.name = Name(name)\r\n \r\n def add_phone(self,phone):\r\n if phone.value not in [ph.value for ph in self.phones]:\r\n self.phones.append(phone)\r\n\r\n def del_phone(self,phone):\r\n self.phones = list(filter(lambda x: x.value!=phone, self.phones))\r\n\r\n def edit_phone(self,phone, new_phone):\r\n status = \"\"\r\n if phone in [x.value for x in self.phones]:\r\n self.del_phone(phone)\r\n self.add_phone(Phone(new_phone))\r\n else:\r\n status = \"Can't find the number \"+phone+\" in the phone list\"\r\n return status \r\n\r\n \r\n def add_birthday(self,birthday):\r\n self.birthday = birthday\r\n\r\n def days_to_birthday(self):\r\n date1 = datetime(datetime.now().timetuple().tm_yday, self.birthday.value.timetuple().tm_mon, self.birthday.value.timetuple().tm_mday)\r\n delta = date1.timetuple().tm_yday - datetime.now().timetuple().tm_yday\r\n if delta > 0:\r\n return str(delta)\r\n else:\r\n date1 = datetime(datetime.now().timetuple().tm_year+1, self.birthday.value.timetuple().tm_mon, self.birthday.value.timetuple().tm_mday)\r\n date2 = datetime(datetime.now().timetuple().tm_year, datetime.now().timetuple().tm_mon, datetime.now().timetuple().tm_mday)\r\n delta = date1 - date2\r\n return str(delta.days)\r\n \r\nclass Field:\r\n def __init__(self, value):\r\n self.value = value\r\n\r\n def __str__(self):\r\n print(f\"{self.__dict__}\")\r\n\r\n @property\r\n def value(self):\r\n return self.__value \r\n\r\n @value.setter\r\n def value(self, value_):\r\n if len(value_) > 0:\r\n self.__value = value_\r\n\r\n\r\nclass Name(Field):\r\n def __init__(self, name):\r\n self.__value = name\r\n\r\n @property\r\n def value(self):\r\n return self.__value \r\n\r\n @value.setter\r\n def set_value(self, value):\r\n if len(value) > 0:\r\n self.__value = value \r\n\r\nclass Phone(Field):\r\n def __init__(self, phone):\r\n self.value = phone\r\n\r\n @property\r\n def value(self):\r\n return self.__value\r\n\r\n\r\n @value.setter\r\n def value(self, phone):\r\n if re.search('\\+\\d{12}', phone) != None:\r\n self.__value = phone\r\n else:\r\n raise ValueError(\"Phone should be in the next format: '+XXXXXXXXXXXX' (12 digits)\")\r\n \r\nclass Birthday(Field):\r\n def __init__(self, birthday):\r\n self.value = birthday\r\n\r\n @property\r\n def value(self):\r\n return self.__value\r\n\r\n @value.setter\r\n def value(self, birthday):\r\n if re.search('\\d{2}\\.\\d{2}\\.\\d{4}', birthday) != None:\r\n self.__value = datetime.strptime(birthday, '%d.%m.%Y').date()\r\n else:\r\n return False \r\n\r\n\r\n##################################################\r\n# CLI BOT section #\r\n##################################################\r\n\r\nexit_command = [\"good bye\", \"close\", \"exit\"]\r\n\r\n\r\ndef format_phone_number(func):\r\n def inner(phone):\r\n result=func(phone)\r\n if len(result) == 12:\r\n result='+'+result\r\n else: result='+38'+result \r\n return result\r\n return inner\r\n \r\n\r\n@format_phone_number\r\ndef sanitize_phone_number(phone):\r\n new_phone = (\r\n phone.strip()\r\n .removeprefix(\"+\")\r\n .replace(\"(\", \"\")\r\n .replace(\")\", \"\")\r\n .replace(\"-\", \"\")\r\n .replace(\" \", \"\")\r\n )\r\n return new_phone\r\n\r\ndef is_correct_input_add(data):\r\n name = \"\"\r\n phone = \"\"\r\n message =\"\"\r\n is_correct_input = re.search(\"[a-zA-Zа-яА-Я1-9]{1,100} \\+?[{0,1}\\d \\-\\(\\)]*$\",data)\r\n if is_correct_input!=None:\r\n match_ = re.search(\" \\+?[{0,1}\\d \\-\\(\\)]*$\", data)\r\n if match_!=None:\r\n phone = sanitize_phone_number(data[match_.start():match_.end()].strip())\r\n name = data[:match_.start()].strip().rstrip()\r\n if len(phone)!=13:\r\n message = \"Incorrect telephone number. Use (+)(Country code)(XXX Operator code) XXX XX XX\"\r\n else:\r\n message = \"Incorrect command format\"\r\n return (name, phone, message)\r\n\r\n\r\ndef is_correct_input_change(data):\r\n name = \"\"\r\n phone_old = \"\"\r\n phone_new = \"\"\r\n message =\"\"\r\n is_correct_input = re.search(\"[a-zA-Zа-яА-Я1-9]{1,100} \\+?[{0,1}\\d\\-\\(\\)]* \\+?[{0,1}\\d\\-\\(\\)]*$\",data)\r\n if is_correct_input!=None: \r\n phone_old, phone_new = data.split(\" \")[-2:]\r\n name = data[0: len(data)-len(phone_old)-len(phone_new)-2] \r\n phone_old = sanitize_phone_number(phone_old)\r\n phone_new = sanitize_phone_number(phone_new)\r\n if len(phone_new)!=13 or len(phone_old)!=13:\r\n message = \"Incorrect telephone number. Use (+)(Country code)-(XXX Operator code)-XXX-XX-XX\"\r\n else:\r\n message = \"Incorrect command format\"\r\n return (name, phone_old, phone_new, message)\r\n\r\n\r\ndef hello_(data):\r\n return \"How can I help You?\"\r\n\r\ndef add_(data):\r\n name, phone, message = is_correct_input_add(data)\r\n if message == \"\":\r\n print('Name ', name, ' phone ', phone,' message', message)\r\n if name in a.data.keys() and phone in [ph.value for ph in a.data[name].phones]:\r\n print (\"Contact is already exist with exactly the same number\")\r\n elif name not in a.data.keys() and phone in a.find(phone): \r\n print (\"Another contact has this number\")\r\n elif name in a.data.keys() and phone not in a.find(phone):\r\n a.data[name].add_phone(Phone(phone))\r\n print (\"Contact phone list successfully appended\")\r\n else:\r\n r = Record(name)\r\n p = Phone(phone)\r\n r.add_phone(p)\r\n a.add_record(r)\r\n print (\"Contact successfully added to phone_book\")\r\n else:\r\n print (message)\r\n print (\"Please use next format for add comand: \", exec_command[\"add\"][1]) \r\n return \"Please choose command\"\r\n\r\ndef change_(data):\r\n name, phone_old, phone_new, message = is_correct_input_change(data)\r\n if message == \"\":\r\n if name in a.data.keys():\r\n message = a.data[name].edit_phone(phone_old, phone_new)\r\n if message == \"\":\r\n print(\"Contact successfully changed\")\r\n else:\r\n print(message)\r\n else:\r\n print(\"Contact not in your phone book\")\r\n else:\r\n print (message)\r\n print (\"Please use next format for add comand: \", exec_command[\"change\"][1]) \r\n return \"Please choose command\" \r\n\r\ndef find_(data):\r\n name = data.strip().rstrip()\r\n res_lst = a.find(data)\r\n if res_lst == []:\r\n print(\"Couldn't find \", name, \" in the phone book\")\r\n else:\r\n print(\"Found next contacts:\")\r\n for contact in res_lst:\r\n print(contact)\r\n return \"Please choose command\"\r\n\r\ndef show_all(data):\r\n adress_book = a \r\n for page in adress_book:\r\n for record in page:\r\n print(\"Name:\", record[\"Name\"])\r\n print(\"Phone list:\")\r\n for phone in record[\"Phones\"]:\r\n print(phone)\r\n if \"Birthday\" in record.keys():\r\n print (\"Birthday: \", record[\"Birthday\"])\r\n input(\"Press enter to continue\")\r\n \r\n return \"Please choose command\"\r\n\r\ndef help_(command):\r\n print(\"List of available commands: \")\r\n for key in exec_command.keys():\r\n print (exec_command[key][1])\r\n return \"Please choose command\"\r\n\r\ndef birthday_(data):\r\n cmnd_lst = data.split(\" \")\r\n birthday = cmnd_lst[-1]\r\n name = data[0:len(data) - len(birthday)-1]\r\n if a.find(name)!=[]:\r\n b=Birthday(birthday)\r\n if b == False:\r\n return \"Birthday should be in the next format: 'dd.mm.yyyy'\"\r\n else: \r\n a.data[name].add_birthday(b)\r\n return \"Birthday setted successfully\"\r\n\r\ndef delete_(data):\r\n res = re.search(\" \\+?[\\d\\-\\(\\)]*$\",data)\r\n name = data.strip().split(\" \")[0]\r\n if name in a.data.keys():\r\n if res == None:\r\n for record in a.find(name):\r\n print(a.find(name))\r\n a.delete(record)\r\n else:\r\n phone = data.strip().split(\" \")[1]\r\n phone = sanitize_phone_number(phone)\r\n if phone in [ph.value for ph in a.data[name].phones]:\r\n a.data[name].delete_phone(phone)\r\n print (\"Phone deleted succesfully\")\r\n else:\r\n print( \"Couldn't find this phone number for the \"+name)\r\n else:\r\n print (\"Couldn't find user \"+name)\r\n return \"Please choose command\"\r\n\r\ndef save_(data):\r\n a.dump(\"Work telephones.json\")\r\n return \"Please choose command\"\r\n \r\nexec_command = {\r\n \"hello\": [hello_, \"hello\", 0], \r\n \"add\": [add_, \"add [name] [phone]\", 2], \r\n \"change\": [change_, \"change [name] [phone_old] [phone_new]\", 2], \r\n \"find\": [find_, \"phone or name\", 1], \r\n \"show all\": [show_all, \"show all\", 0],\r\n \"help\": [help_, \"help\",0], \r\n \"birthday\": [birthday_, \"birthday [name] [date of birthday dd.mm.yyyy]\",1],\r\n \"delete\": [delete_, \"delete [name] [phone (optional)]\", 2],\r\n \"save\": [save_, \"save\", 0]\r\n }\r\n\r\n\r\ndef handler(command, data):\r\n return exec_command[command][0](data.replace(command+\" \",\"\"))\r\n \r\n\r\ndef parser(input_str):\r\n for token in exec_command.keys():\r\n if token in input_str:\r\n return handler(token, input_str.replace(token+\" \", \"\"))\r\n return \"Input error, please type 'help' for commands description\"\r\n \r\ndef listener():\r\n command = \"\"\r\n communication_str = \"CLI phone book bot looking for your command\"\r\n while (command) not in exit_command:\r\n print(communication_str+\": \")\r\n command = input()\r\n communication_str = parser(command)\r\n\r\n\r\na = AddressBook(\"Work telephones\")\r\na.load(\"Work telephones.json\")\r\nlistener() \r\na.dump(\"Work telephones.json\")\r\n","sub_path":"homerwork12_new + CLI bot.py","file_name":"homerwork12_new + CLI bot.py","file_ext":"py","file_size_in_byte":13524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"90448292","text":"load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n\ndef github_bazel_erlang_lib(\n name = None,\n org = None,\n repo = None,\n version = \"master\",\n ref = \"refs/heads/master\",\n extra_apps = [],\n first_srcs = [],\n deps = [],\n runtime_deps = [],\n **kwargs):\n if not (\"build_file\" in kwargs.keys() or \"build_file_content\" in kwargs.keys()):\n kwargs.update(build_file_content = _BUILD_FILE_TEMPLATE.format(\n app_name = name,\n version = version,\n extra_apps = extra_apps,\n first_srcs = first_srcs,\n deps = deps,\n runtime_deps = runtime_deps,\n ))\n\n repo = name if repo == None else repo\n\n http_archive(\n name = name,\n urls = [\"https://github.com/{}/{}/archive/{}.zip\".format(org, repo, ref)],\n strip_prefix = \"{}-{}\".format(repo, version),\n **kwargs\n )\n\n_BUILD_FILE_TEMPLATE = \"\"\"\nload(\"@bazel-erlang//:bazel_erlang_lib.bzl\", \"erlang_lib\")\n\nerlang_lib(\n app_name = \"{app_name}\",\n app_version = \"{version}\",\n extra_apps = {extra_apps},\n first_srcs = {first_srcs},\n deps = {deps},\n runtime_deps = {runtime_deps},\n)\n\"\"\"\n","sub_path":"github.bzl","file_name":"github.bzl","file_ext":"bzl","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"116244502","text":"from set_2.challenge_15 import valid_pkcs7_padding\nfrom set_2.challenge_14 import key as key_bytes\nfrom utils import MyAES\nimport binascii\n\n\ndef convert_offending_chars(input_string):\n offending_chars = [(\";\", \"%3B\"), (\"=\", \"%3D\")]\n input_type = type(input_string)\n assert input_type is str, \"[convert_offending_char]: expecting input as str, found \" + input_type.__name__\n temp_string = input_string\n for tuple in offending_chars:\n temp_string = temp_string.replace(tuple[0], tuple[1])\n return temp_string\n\n\ndef aes_cbc_fixed_prefix_fixed_suffix(input_bytes):\n input_type = type(input_bytes)\n assert input_type is bytes, \"[convert_offending_char]: expecting input as bytes, found \" + input_type.__name__\n plaintext_bytes = bytearray()\n prefix_bytes = \"comment1=cooking%20MCs;userdata=\".encode(\"utf-8\")\n suffix_bytes = \";comment2=%20like%20a%20pound%20of%20bacon\".encode(\"utf-8\")\n plaintext_bytes.extend(prefix_bytes)\n plaintext_bytes.extend(input_bytes)\n plaintext_bytes.extend(suffix_bytes)\n plaintext_bytes = MyAES.pkcs7_pad(plaintext_bytes)\n print(plaintext_bytes)\n # IV all zeroes\n cipher = MyAES.new(key_bytes, MyAES.MODE_CBC, bytes(MyAES.block_size))\n return cipher.raw_encrypt(plaintext_bytes)\n\n\ndef is_token_admin(input_bytes):\n cipher = MyAES.new(key_bytes, MyAES.MODE_CBC, bytes(MyAES.block_size))\n plaintext_bytes = valid_pkcs7_padding(cipher.raw_decrypt(input_bytes), strip=True)\n print(plaintext_bytes)\n plaintext = plaintext_bytes.decode(\"utf-8\", errors=\"ignore\")\n parameter_list = plaintext.split(\";\")\n for parameter in parameter_list:\n values_list = parameter.split(\"=\")\n if len(values_list) == 2:\n name = values_list[0]\n value = values_list[1]\n if name == \"admin\" and value == \"true\":\n return True\n else:\n continue\n return False\n\ndef index_diff_block(f_ciph_bytes, s_ciph_bytes):\n assert len(f_ciph_bytes) == len(s_ciph_bytes), \"[index_diff_block]: len(f_ciph_bytes) != len(s_ciph_bytes)\"\n for i in range(len(s_ciph_bytes) // MyAES.block_size - 2):\n if f_ciph_bytes[i * MyAES.block_size:(i + 1) * MyAES.block_size] != s_ciph_bytes[i * MyAES.block_size:(i + 1) * MyAES.block_size]:\n print(binascii.hexlify(f_ciph_bytes[i * MyAES.block_size:(i + 1) * MyAES.block_size]))\n print(binascii.hexlify(s_ciph_bytes[i * MyAES.block_size:(i + 1) * MyAES.block_size]))\n print(i)\n return i\n\n\ndef bitflipping(ciphertext, index, xor_list):\n assert index >= 1, \"[bitflip]: something is horribly wrong\"\n\n\ndef main():\n\n last_input_block = \":admin?true:a?AA\"\n # tuples of \"bad\" chars in last_input_block, we want \";admin=true;a=AA\n positions = [(0, \";\"), (6, \"=\"), (11, \";\"), (13, \"=\")]\n\n # craft a suitable input for a bitflipping attack\n block_number = len(aes_cbc_fixed_prefix_fixed_suffix(b\"\")) // MyAES.block_size\n\n padding_input_string = \"\"\n while True:\n new_block_number = len(aes_cbc_fixed_prefix_fixed_suffix(bytes(padding_input_string, encoding=\"utf-8\"))) // MyAES.block_size\n if new_block_number > block_number:\n break\n padding_input_string += \"A\"\n\n probe_ciphertext = aes_cbc_fixed_prefix_fixed_suffix(bytes(padding_input_string + \"A\" * MyAES.block_size, encoding=\"utf-8\"))\n probing_input = padding_input_string + \"A\" * MyAES.block_size\n\n first = 0\n index = 0\n left_pad = 0\n for i in range(len(probing_input) - 1, -1, -1):\n probing_input = probing_input[:i] + \"B\" * (len(probing_input) - i)\n if i == (len(probing_input) - 1):\n first = index_diff_block(probe_ciphertext, aes_cbc_fixed_prefix_fixed_suffix(bytes(probing_input, encoding=\"utf-8\")))\n else:\n index = index_diff_block(probe_ciphertext, aes_cbc_fixed_prefix_fixed_suffix(bytes(probing_input, encoding=\"utf-8\")))\n if first != index:\n left_pad = i + 1\n break\n\n f_input_string = \"A\" * left_pad + last_input_block + padding_input_string\n s_input_string = \"A\" * left_pad + last_input_block[:-1] + \"B\" + padding_input_string\n\n first_ciphertext = aes_cbc_fixed_prefix_fixed_suffix(bytes(f_input_string, encoding=\"utf-8\"))\n second_ciphertext = aes_cbc_fixed_prefix_fixed_suffix(bytes(s_input_string, encoding=\"utf-8\"))\n\n print(binascii.hexlify(first_ciphertext))\n print(binascii.hexlify(second_ciphertext))\n\n index_of_last_input_block = index_diff_block(first_ciphertext, second_ciphertext)\n\n xor_list = [0] * len(positions)\n for i in range(len(positions)):\n xor_list[i] = ord(last_input_block[positions[i][0]]) ^ ord(positions[i][1])\n\n first_bytearray = bytearray(first_ciphertext)\n\n for i in range(len(positions)):\n first_bytearray[MyAES.block_size * (index_of_last_input_block - 1) + positions[i][0]] ^= xor_list[i]\n\n print(binascii.hexlify(first_bytearray))\n # decrypt\n print(is_token_admin(bytes(first_bytearray)))\n\nif __name__ == '__main__':\n main()\n","sub_path":"set_2/challenge_16.py","file_name":"challenge_16.py","file_ext":"py","file_size_in_byte":5057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"122576316","text":"'''\nExports a class, Attnception, that initializes Inception V3 models and handles\ncommon tasks related to them.\n'''\nimport models.slim_inception_v3 as inc\nfrom ops.metrics import class_accuracy\nfrom ops.map_loss import MapLoss\nfrom ops.loss_utils import inception_finetune_learning,\\\n combine\nfrom ops.tf_fun import blur\nimport tensorflow as tf\nslim = tf.contrib.slim\nfrom datetime import datetime\nnow = datetime.now\n\nclass Attnception:\n\n def __init__(self, images, labels, train_scopes, reinitialize_scopes,\n dropout_keep_prob=0.8, weight_decay=0.00004, is_training=True,\n num_classes=1000, stddev=0.1, modulators=None, name='inception'):\n '''\n Initialize an Attnception model. Note that this class does not\n deal with the configuration files. Just pass those parameters\n as arguments when necessary.\n\n Arguments:\n images tf.Tensor of shape [N, H, W, C]\n The model's input, images with pixel values in [0, 1].\n labels integer tf.Tensor of shape like [N]\n Sparse labels.\n train_scopes None or list of str\n A list of scopes (see `slim_inception_v3.py` for their names,\n like 'InceptionV3/Logits' for example) that should be trained\n at the full learning rate. If it is empty, the model will not\n be trained at all. If it is not falsey, all of the layers in\n these scopes will be trained at the full learning rate, and\n any other layers will be trained at the hold learning rate.\n is_training bool\n This will be passed through to Slim so that it can deal with\n dropout and stuff.\n reinitialize_scopes None or list of str\n A list of scopes whose layers should be randomly reinitialized.\n modulators None or tf.Tensor\n Shape should be broadcastable to that of the output of conv1.\n If this is not None, we will multiply the output of conv1 by\n these before sending it along to conv2.\n dropout_keep_prob, weight_decay, num_classes, stddev\n scalars for use in model initializer.\n '''\n # Inception expects input in the range [-1, 1]\n self.images = 2.0 * images - 1.0\n self.labels = labels\n self.train_scopes = train_scopes\n self.reinitialize_scopes = reinitialize_scopes\n self.modulators = modulators\n self.is_training = is_training\n self.num_classes = num_classes\n # Store a UID\n self.dt_stamp = '%s_%s_%s' % (name, str(labels.get_shape()[-1]),\n now().strftime('%Y_%m_%d_%H_%M_%S'))\n\n # The pretrained checkpoint has 1001 classes, where class 0 is a\n # \"background\" class. If we're reinitializing the logits, we can\n # only do this by having 1001 classes. But don't worry -- this class\n # will get rid of it in the logits and in the predictions before\n # returning.\n self.needs_bg_class = 'InceptionV3/Logits' not in reinitialize_scopes\n\n # Initialize the model\n with slim.arg_scope(inc.inception_v3_arg_scope()):\n self.logits, self.endpoints = inc.inception_v3(self.images,\n is_training=self.is_training, modulators=modulators,\n dropout_keep_prob=dropout_keep_prob,\n num_classes=self.num_classes + self.needs_bg_class)\n\n # Now get rid of bg class if necessary.\n if self.needs_bg_class:\n self.logits = self.logits[:, 1:]\n self.endpoints['Predictions'] = self.endpoints['Predictions'][:, 1:]\n\n # Store all parameters for later use\n self.variables = slim.get_model_variables()\n\n # Figure out which variables to restore\n if 'all' in reinitialize_scopes:\n self.vars_to_restore = []\n else:\n self.vars_to_restore = [var for var in self.variables\n if not var.op.name.startswith(tuple(reinitialize_scopes))]\n\n # Ad ops for class loss and class accuracy\n self.class_loss = tf.reduce_mean(\n tf.nn.sparse_softmax_cross_entropy_with_logits(logits=self.logits, labels=labels))\n\n with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):\n self.class_accuracy = class_accuracy(self.endpoints['Predictions'], labels)\n\n # Unless `add_attention_loss(...)` is called, total loss is just class_loss.\n self.loss = self.class_loss\n\n\n def add_attention_loss(self, clickmaps, beta, loss_type=None, targeted=True,\n click_weights=None, combine_type='pass',\n C_blur_kernel_size=0, G_blur_kernel_size=0):\n '''\n By default, Attnception does not add attention gradient ops to the graph.\n Call this function if you want them.\n\n This will add a `self.attention_loss` property, and will also add\n `beta * self.attention_loss` to `self.loss` (which only has the class\n loss before this is called).\n\n Internally, we just call out to the `map_loss` function provided in\n `ops/map_loss.py`. Accordingly, you can use any of the\n `MapLoss.$LOSS_TYPE` constants defined there for `loss_type`. Go\n check 'em out. `None` for the default loss type.\n\n Arguments:\n clickmaps tf.Tensor\n Raw heatmaps. This method will handle the blurring\n and normalization.\n beta scalar\n Global weight for attention loss.\n loss_type None or one of the MapLoss.XXX constants.\n Type of loss to compute. Check out `ops/map_loss.py` for\n the options.\n targeted bool\n If True, attention maps only care about the output neuron\n corresponding to the class label of the image in question.\n Otherwise, they care about all output neurons.\n click_weights tf.Tensor of shape like [N]\n Weight the loss per clickmap by multiplying through with this\n tensor.\n combine_type string\n How to combine the attention gradients into a map.\n Look at the implementation of `combine(...)` for details.\n C_blur_kernel_size, G_blur_kernel_size scalars\n Blur the clickmap and gradient heatmap by these values.\n '''\n # Compute attention gradients\n attention_neurons = self.logits\n if targeted:\n attention_neurons *= tf.one_hot(self.labels, self.num_classes)\n G = tf.gradients(attention_neurons, self.images)[0]\n G = combine(G, combine_type)\n\n # Blur G and C\n if G_blur_kernel_size > 0:\n G = blur(G, kernel=G_blur_kernel_size)\n if C_blur_kernel_size > 0:\n clickmaps = blur(clickmaps, kernel=C_blur_kernel_size)\n\n # Compute gammas. If we don't have click weights, weight evenly.\n gammas = click_weights if click_weights is not None else 1.0\n\n self.map_loss = MapLoss.map_loss(G, clickmaps, loss_type=loss_type,\n weights=gammas, normalize=True)\n\n self.loss += beta * self.map_loss\n\n\n def add_training(self, learning_rate, hold_learning_rate, optimizer,\n clip_grads=0):\n '''\n Handles the creation of finetuning/normal training ops.\n Raises a ValueError if there are no variables to train.\n\n Arguments:\n learning_rate scalar\n Learning rate for the variables in `self.train_scopes`,\n aka the finetuning layers.\n hold_learning_rate scalar\n Learning rate for the rest of the variables.\n optimizer a tf.train.XXXOptimizer\n Will be called like `optimizer(lr).minimize(loss)`, so don't\n initialize the optimizer.\n clip_grads bool\n If >0, max norm for gradients.\n '''\n if not self.is_training:\n raise ValueError('Attnception.add_training: `train_scopes` is empty.')\n\n # `self.variables` includes some things like batchnorm moving means that\n # we don't want to pass to the loss\n trainables = [var for var in self.variables\n if var in tf.trainable_variables()]\n vars_to_finetune = [var for var in trainables\n if var.op.name.startswith(tuple(self.train_scopes))]\n vars_to_hold = [var for var in trainables if var not in vars_to_finetune]\n\n # For slim models with batchnorm (that's us), you need to use\n # `slim.learning.create_train_op(...)` to ensure that batchnorm params\n # get updated appropriately. See link:\n # github.com/tensorflow/tensorflow/issues/1122#issuecomment-280325584\n train_ops = []\n if vars_to_finetune:\n train_ops.append(slim.learning.create_train_op(\n self.loss, optimizer(learning_rate),\n variables_to_train=vars_to_finetune,\n clip_gradient_norm=clip_grads))\n if vars_to_hold:\n train_ops.append(slim.learning.create_train_op(\n self.loss, optimizer(hold_learning_rate),\n variables_to_train=vars_to_hold,\n clip_gradient_norm=clip_grads))\n\n self.train_op = tf.group(*train_ops)\n","sub_path":"models/attnception.py","file_name":"attnception.py","file_ext":"py","file_size_in_byte":9766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"536786496","text":"import pytest\nimport requests\n\n\nclass GetToApi:\n def __init__(self, base_address):\n self.base_address = base_address\n\n def get(self, params=None, headers=None):\n url = self.base_address\n return requests.get(url=url, params=params, headers=headers)\n\n\n@pytest.fixture(scope=\"session\")\ndef req_ya_api_weather(request):\n return GetToApi(base_address=\"https://api.weather.yandex.ru/v2/forecast\")\n\n\ndef pytest_addoption(parser):\n parser.addoption(\"--url\",\n action=\"store\",\n default=\"https://ya.ru/\",\n help=\"This is request url.\")\n parser.addoption(\"--status_code\",\n action=\"store\",\n default=200,\n help=\"Status code.\")\n","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"65360168","text":"import socket\nimport sys\nfrom pathlib import Path\nimport hashlib\nimport os\nimport zipfile\n\n\n# 发送方\n# 使用示例:\n# python3 E:\\Project_for_VS\\FileTransport-master\\src\\client\\client.py E:\\background 193.112.59.84 1234\n# argv[1]: abcd 可以是任意文件或文件夹的相对或绝对路径\n# argv[2]: 123.123.123.123 是发送目的地的地址\n# argv[3]: 1234 是目的地端口\n\n# f 为文件到提供的文件夹的相对目录,用于传输报头\n# source 为提供的文件夹,用于读取文件\n########\ndef getAbsolutePath(f, source):\n absolute = Path(source).parent.joinpath(f)\n return str(absolute)\n\n\ndef CreateZipFile(f, source):\n absolute = getAbsolutePath(f, source)\n zipFilePath = absolute + \".zip\"\n fzip = zipfile.ZipFile(zipFilePath, \"w\", zipfile.ZIP_DEFLATED)\n fzip.write(absolute)\n\n\nclass FileInfo():\n def __init__(self, f, source): # f表示相对路径,source为根目录\n self.absolute = Path(source).parent.joinpath(f)\n\n self.file_name = str(f).encode('utf-8')\n\n self.file_name_size = len(self.file_name).to_bytes(4, byteorder=\"big\") # 文件名长度(4Byte)\n\n self.file_size = Path(self.absolute).stat().st_size.to_bytes(10, byteorder=\"big\")\n\n self.file_md5 = GetFileMd5(Path(self.absolute)).encode('utf-8')\n\n if os.path.exists(str(self.absolute) + \".zip\"):\n self.zip_name = (str(f) + \".zip\").encode(\"utf-8\")\n self.zip_name_size = len(self.zip_name).to_bytes(4, byteorder=\"big\")\n self.zipSize = os.path.getsize(str(self.absolute) + \".zip\").to_bytes(10, byteorder=\"big\")\n else:\n tmp = 1\n self.zipSize = tmp.to_bytes(10, byteorder=\"big\")\n self.zip_name_size = tmp.to_bytes(4, byteorder=\"big\")\n self.zip_name = \"x\".encode(\"utf-8\")\n\n\ndef GetFileMd5(filepath):\n # 获取文件的md5\n myhash = hashlib.md5()\n f = open(filepath, \"rb\")\n while True:\n b = f.read(8096)\n if not b:\n break\n myhash.update(b)\n f.close()\n return myhash.hexdigest()\n\n\n######## 获取MD5码\n\ndef transportFile(sock, f, fInfo, zipFlag):\n if zipFlag == 0:\n absolute = fInfo.absolute\n else:\n absolute = str(fInfo.absolute) + \".zip\"\n sock.send(fInfo.file_name_size) # 传输文件名大小\n sock.send(fInfo.file_name) # 传输文件名\n sock.send(fInfo.file_size) # 传输文件大小\n sock.send(fInfo.file_md5) ### 传输md5码\n sock.send(fInfo.zip_name_size) # 传输压缩名大小\n sock.send(fInfo.zip_name) # 传输压缩文件名\n sock.send(fInfo.zipSize) # 传输压缩文件大小\n recv_data = sock.recv(1) ### 这里用于接收文件在对方的存在情况\n ######### recv_data 2|已传 1|追加 0|未传\n if (int(recv_data) == 2): ###已传\n print(f\"this file {absolute} already in server\")\n return\n if (int(recv_data) == 1): ###追加\n recv_data = int.from_bytes(sock.recv(10), byteorder=\"big\") ### 获取\n print(f\"断点续传{absolute}\")\n fp = open(absolute, 'rb')\n fp.read(recv_data)\n if (int(recv_data) == 0): ### 包括两种情况新文件或者更新覆盖,但都是直接发送整个文件\n fp = open(absolute, 'rb')\n while True: # 连续传送文件\n data = fp.read(1024)\n if not data:\n break\n sock.send(data)\n print(f\"already transport {absolute}\") #########\n\n\ndef getHeader(__p, __s):\n file_name = str(__p).encode('utf-8') # (路径)文件名\n file_name_size = len(file_name).to_bytes(4, byteorder=\"big\") # 文件名长度(4Byte),\n file_size = Path(__s).stat().st_size.to_bytes(10, byteorder=\"big\") # 文件大小(32Byte)\n file_md5 = GetFileMd5(Path(__s)).encode('utf-8') ### md5码(32Byte)\n return [file_name_size, file_name, file_size, file_md5]\n\n\ndef getListOfFiles(__s):\n __p = Path(__s)\n if __p.is_file():\n return [__p.name] # 如果是文件则直接返回单元素列表\n else:\n return [__f.parent.relative_to(__p.parent).joinpath(__f.name) # 将文件名加上文件夹的相对路径\n for __f in __p.rglob('*') # 选择所有文件和文件夹\n if __f.is_file()] # 仅选择文件\n\n\nif __name__ == '__main__':\n zipFlag = 0\n total_File_info = []\n source = sys.argv[1]\n remoteAddr = sys.argv[2]\n remotePort = int(sys.argv[3])\n if len(sys.argv) == 5:\n zipFlag = 1\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 建立TCP连接\n s.connect((remoteAddr, remotePort)) # 发起连接\n s.send(str(zipFlag).encode(\"utf-8\"))\n relative_files = getListOfFiles(source) # 获得所有需要发送的所有原始文件\n\n for f in relative_files:\n if zipFlag == 1:\n CreateZipFile(f, source)\n fInfo = FileInfo(f, source)\n transportFile(s, f, fInfo, zipFlag)\n if(zipFlag == 1):\n os.remove(getAbsolutePath(f, source) + \".zip\")\n endByte = 0\n endFlag = endByte.to_bytes(4, byteorder=\"big\")\n s.send(endFlag)\n\n s.close()\n","sub_path":"src/ClientGui/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":5077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"337211784","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 27 21:53:41 2016\n\n@author: Ramanuja\n\"\"\"\n\na = [31, 41, 59, 26, 41, 58,45,0]\n\nfor index in range(1,len(a)):\n currentvalue = a[index]\n position = index\n\n while position>0 and a[position-1]>currentvalue:\n a[position]=a[position-1]\n position = position-1\n\n a[position]=currentvalue \n","sub_path":"insertionSort.py","file_name":"insertionSort.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"597185254","text":"\n'''\nDate: November 5, 2020\n\nVersions used: HA116.1, HassOS and Raspberry PI 3 B\n\nDescription:\nThis Python Script converts histogram type power to energy accumulation.\nIt needs two input_number entities to be passed as data values: power, last_power.\ninput_number.energy_accum is used to accumulate the energy calculation.\nThe hourly energy calculation is done in a separate script called energy_hour.py\nThe hourly energy script waits for this script to complete, preventing errors to due\nto power changes that occur on the hour boundary.\ninput_number entities restore the last known value on HA restart. Sensors do not restore.\n\nInstructions:\n1. Python Script setup\n 1.1 Create /config/python_scripts directory and copy this file to it.\n 1.2 Add this line to configuration.yaml\n python_script: \n \n2. Add these input_number entities to configuration.yaml\n input_number used because their values are restored after HA restarts.\n \n furnace_power:\n name: Furnace Power\n min: 0\n max: 50\n step: 0.1\n unit_of_measurement: 'kW'\n \n last_power:\n min: 0\n max: 100\n step: 0.1\n mode: box\n \n energy_accum:\n min: 0\n max: 1000\n step: 0.1 \n \n3. Add this automation to automations.yaml\n * items are your choosing but must match your sensor names above\n input_number.furnace_power is the input power sensor in this example\n\n- alias: Energy Integration\n initial_state: True\n trigger:\n - platform: state\n entity_id: input_number.furnace_power\n action:\n service: script.turn_on\n entity_id: script.energy\n \n4. Add this script to scripts.yaml\n\nenergy:\n alias: Energy Integrator\n sequence: \n - service: python_script.energy\n data:\n power: furnace_power\n last_power: last_power\n energy_accum: energy_accum\n\n5. Use the history_graph lovelace card to display the result.\n\n\n'''\n\n#logger.warning(\"Got to energy\")\nWINDOW_SIZE = 60*60\n\npower = data.get('power', '0')\nlast_power = data.get('last_power', '0')\nenergy_accum = data.get('energy_accum', '0')\n\nif power != '0':\n\tinput_number_power = \"input_number.\" + power\nelse:\n\tlogger.error(\"Energy script missing power data.\")\n \nif last_power != '0':\n\tinput_number_last_power = \"input_number.\" + last_power\nelse:\n\tlogger.error(\"Energy script missing last_power data.\")\n \nif energy_accum != '0':\n\tinput_number_energy_acum = \"input_number.\" + energy_accum\nelse:\n\tlogger.error(\"Energy script missing energy_accum data.\")\n\n# Get power unit and use to set the units for the other sensors used.\npower_attr = hass.states.get(input_number_power).attributes\npower_unit = power_attr['unit_of_measurement']\nenergy_unit = power_unit + 'h'\n \nenergy_accum_state = hass.states.get(input_number_energy_acum)\nenergy_accum = float(energy_accum_state.state)\n \npower_state = hass.states.get(input_number_power)\npower = float(power_state.state)\n\n#Need to get last_power_state since it is reset at start of window\nlast_power_state = hass.states.get(input_number_last_power)\nlast_power = float(last_power_state.state)\n#No new energy if last power was zero.\nif last_power > 0:\n ##logger.warning(\"Last Power = {}\".format(last_power))\n last_power_change = last_power_state.last_changed.timestamp()\n\n ##logger.warning(\"Power Test = {}\".format(power))\n power_change = power_state.last_changed.timestamp()\n ##logger.warning(\"power_change = {}\".format(power_change))\n\n delta_time = power_change - last_power_change\n #logger.warning(\"delta_time = {}\".format(delta_time))\n\n #Convert to energy per hour\n delta_energy = delta_time * last_power / WINDOW_SIZE\n #logger.warning(\"delta_energy = {}\".format(delta_energy))\n \n energy_accum = round(energy_accum + delta_energy,1)\n #logger.warning(\"energy_accum = {}\".format(energy_accum))\n hass.states.set(input_number_energy_acum, energy_accum, {\"unit_of_measurement\": energy_unit})\n #logger.warning(\"energy_accum next = {}\".format(energy_accum))\n\n#Update last_power with new power\nhass.states.set(input_number_last_power, power, {\"unit_of_measurement\": power_unit})\n\n\n","sub_path":"python_scripts/energy.py","file_name":"energy.py","file_ext":"py","file_size_in_byte":4122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"431340324","text":"\nfrom detect_secrets.core.usage import get_all_plugin_descriptors\nfrom detect_secrets.core.secrets_collection import SecretsCollection\nfrom detect_secrets.core.potential_secret import PotentialSecret\nfrom detect_secrets.plugins.common.initialize import from_plugin_classname\n\nfrom .base import Tool, Issue, AccessIssue, UnknownIssue\n\n\nclass DetectSecretsIssue(Issue):\n tool = 'secrets'\n pylint_type = 'W'\n\n\nPLUGINS = [\n from_plugin_classname(_plugin.classname, (), **dict([\n (\n _arg[0][2:].replace('-', '_'),\n _arg[1],\n )\n for _arg in _plugin.related_args\n ]))\n for _plugin in get_all_plugin_descriptors(())\n]\n\nDESCRIPTION = 'Possible secret detected: {description}'\n\n\ndef plugin_code(plugin):\n return plugin.__class__.__name__\n\n\nclass DetectSecretsTool(Tool):\n \"\"\"\n The secrets tool attempts to detect secrets (keys, passwords, etc) that are\n embedded in your codebase.\n \"\"\"\n\n @classmethod\n def get_all_codes(cls):\n return [\n (\n plugin_code(plugin),\n plugin.secret_type,\n )\n for plugin in PLUGINS\n ]\n\n def execute(self, finder):\n issues = []\n\n plugins = [\n plugin\n for plugin in PLUGINS\n if plugin_code(plugin) not in self.config['disabled']\n ]\n\n detector = SecretsCollection(plugins)\n\n for filepath in finder.files(self.config['filters']):\n try:\n detector.scan_file(filepath)\n except Exception as exc: # pylint: disable=broad-except\n issues.append(self.make_issue(exc, filepath))\n\n for filepath, problems in detector.data.items():\n for problem in problems:\n issues.append(self.make_issue(problem, filepath))\n\n return issues\n\n def make_issue(self, problem, filename):\n if isinstance(problem, PotentialSecret):\n plugin = [\n plugin\n for plugin in PLUGINS\n if plugin.secret_type == problem.type\n ][0]\n return DetectSecretsIssue(\n plugin_code(plugin),\n DESCRIPTION.format(description=problem.type),\n filename,\n problem.lineno,\n )\n\n if isinstance(problem, EnvironmentError):\n return AccessIssue(problem, filename)\n\n return UnknownIssue(problem, filename)\n\n","sub_path":"src/tidypy/tools/secrets.py","file_name":"secrets.py","file_ext":"py","file_size_in_byte":2456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"80096766","text":"import tkinter as tk\n\nclass Application(tk.Frame):\n def __init__(self, master=None):\n # Windowの初期設定を行う。\n super().__init__(master)\n\n # Windowの画面サイズを設定する。\n # geometryについて : https://kuroro.blog/python/rozH3S2CYE0a0nB3s2QL/\n self.master.geometry(\"300x200\")\n\n # Windowを親要素として、frame Widget(Frame)を作成する。\n # Frameについて : https://kuroro.blog/python/P20XOidA5nh583fYRvxf/\n frame = tk.Frame(self.master)\n # Windowを親要素とした場合に、frame Widget(Frame)をどのように配置するのか?\n # packについて : https://kuroro.blog/python/UuvLfIBIEaw98BzBZ3FJ/\n frame.pack()\n\n # frame Widget(Frame)を親要素として、label Widgetを作成する。\n # text : テキスト情報\n # width : label幅の設定\n # height : labelの高さ設定\n # bg : 背景色の設定\n # 色について : https://kuroro.blog/python/YcZ6Yh4PswqUzaQXwnG2/\n label = tk.Label(frame, text=\"label\", width=30, height=15, bg=\"red\")\n\n # frame Widget(Frame)を親要素とした場合に、label Widgetをどのように配置するのか?\n # packについて : https://kuroro.blog/python/UuvLfIBIEaw98BzBZ3FJ/\n label.pack()\n\n\n# Tkinter初学者参考 : https://docs.python.org/ja/3/library/tkinter.html#a-simple-hello-world-program\nif __name__ == \"__main__\":\n # Windowを生成する。\n # Windowについて : https://kuroro.blog/python/116yLvTkzH2AUJj8FHLx/\n root = tk.Tk()\n app = Application(master=root)\n\n # Windowをループさせて、継続的にWindow表示させる。\n # mainloopについて : https://kuroro.blog/python/DmJdUb50oAhmBteRa4fi/\n app.mainloop()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"555981607","text":"\"\"\"\nRead file into texts and calls.\nIt's ok if you don't understand how to read files\n\"\"\"\nimport csv\nwith open('texts.csv', 'r') as f:\n reader = csv.reader(f)\n texts = list(reader)\n\nwith open('calls.csv', 'r') as f:\n reader = csv.reader(f)\n calls = list(reader)\n\n\"\"\"\nTASK 2: Which telephone number spent the longest time on the phone\nduring the period? Don't forget that time spent answering a call is\nalso time spent on the phone.\nPrint a message:\n\"<telephone number> spent the longest time, <total time> seconds, on the phone during \nSeptember 2016.\".\n\"\"\"\n\n\ndef numbers_list(records):\n numbers = []\n for record in records:\n if record[0] not in numbers:\n numbers.append(record[0])\n if record[1] not in numbers:\n numbers.append(record[1])\n return numbers\n\n\ndef time_spent(numbers, records):\n time = {}\n for number in numbers:\n time[number] = 0\n for record in records:\n time[record[0]] += int(record[3])\n time[record[1]] += int(record[3])\n return time\n\n\ndef most_time(time):\n maximum_time = None\n maximum_number = None\n for number in time:\n if maximum_time is None or time[number] > maximum_time:\n maximum_time = time[number]\n maximum_number = number\n return maximum_number, maximum_time\n\n\nprint(most_time(time_spent(numbers_list(calls), calls))[0], \"spent the longest time,\", most_time(\n time_spent(numbers_list(calls), calls))[1], \"seconds, on the phone during September 2016.\")\n","sub_path":"Project 0/Task2.py","file_name":"Task2.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"297900740","text":"import pandas as pd\nimport csv\n\n#use only networklinks.tsv to create list of nodes\ndf = pd.read_csv('links_example1.csv',header=0)\ndf.to_csv('linksupdated.tsv',sep='\\t',index=False,header=False)\ndf_sorted = pd.unique(df[['i','j']].values.ravel())\nnodes_test = df_sorted.tolist()\n\nwith open('nodesupdated.tsv', 'w') as myfile:\n wr = csv.writer(myfile, delimiter='\\t')\n wr.writerow(nodes_test)\n\n#import links and strip /n\nlinks = open('linksupdated.tsv','r')\nh = links.read()\nlinksedit = h.rstrip()\n\nnodes = open('nodesupdated.tsv','r')\ng = nodes.read()\nnodesedit = g.rstrip()\n\n#write data.dat file\nf = open('data_example1.dat','w')\n\nf.write('set N :=\\n')\nf.write(nodesedit + ';\\n\\n')\n\nf.write('set k := 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15;\\n\\n')\n\nf.write('param source := SOURCE;\\n')\nf.write('param sink := SINK;\\n\\n')\n\nf.write('param: A: c a l u :=\\n')\nf.write(linksedit + ';')\n\n\n\n\n","sub_path":"abstract_model/compiler.py","file_name":"compiler.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"640185364","text":"#coding=utf-8\r\n\r\nimport os\r\nimport traceback\r\nimport tornado.ioloop\r\nimport tornado.web\r\nfrom config import kUploadSavePath, kFaceDBPath, kLogFile\r\nfrom errorNum import *\r\nfrom PLogger import Logger\r\nfrom FaceRecgModel import FaceRecgModel\r\nfrom ImgTool import img2Base64, getImgTypeByFileName\r\nfrom UuidTool import genUuidByFileName, genUuidRandom\r\nfrom jsonTool import generateJsonRetStr\r\n\r\n\r\nclass RecgForHtmlHandler(tornado.web.RequestHandler):\r\n def initialize(self, database):\r\n if not os.path.exists(kUploadSavePath):\r\n os.makedirs(kUploadSavePath)\r\n\r\n self.__logger = Logger()\r\n self.__faceRecgModel = database\r\n\r\n\r\n def get(self):\r\n self.write('you should have post request')\r\n\r\n def post(self):\r\n self.__logger.info('receive a request from client')\r\n try:\r\n upFile = self.__getUploadFile()\r\n if upFile == None:\r\n return\r\n self.__logger.info('file uploaded, save name is ' + upFile)\r\n # id, thumb, similarity, name, title, intro\r\n id, thumb, similarity, name, title, intro = self.__faceRecgModel.findIidentityByImage(upFile)\r\n # id, thumb, similarity = '1', '1010100103_thumb.jpg', 0.6\r\n self.__logger.info(upFile + ' id is ' + id + ' similarity is ' + str(similarity))\r\n\r\n # img to base64 and trans to client.\r\n imgFullPath = os.path.join(kFaceDBPath, thumb)\r\n imgBase64 = img2Base64(imgFullPath)\r\n ext = getImgTypeByFileName(thumb)[1:]\r\n jsonStr = '{\"errCode\":\"0\",\"id\":\"' + id + '\",\"thumb\":\"' + imgBase64 + '\",\"ext\":\"' + ext + '\",\"name\":\"' + name + '\",\"title\":\"' + title + '\",\"intro\":\"' + intro + '\"}'\r\n # self.__logger.info('ret str is ' + jsonStr)\r\n self.write(jsonStr)\r\n\r\n items = [ext, imgBase64,]\r\n self.render('../html/recgResult.html', items=items)\r\n except:\r\n f=open(kLogFile + '.error','a')\r\n traceback.print_exc(file=f)\r\n f.flush()\r\n f.close()\r\n unknownError = generateJsonRetStr(UNKONON_ERROR)\r\n self.write(unknownError)\r\n\r\n '''\r\n 文件上传,返回文件保存信息\r\n '''\r\n def __getUploadFile(self):\r\n self.__logger.info(\"receiving a file from client\")\r\n #check if upload file more than 1 then return error\r\n fileMetas = []\r\n try:\r\n #do some thing you need\r\n fileMetas = self.request.files['file']\r\n except Exception as e:\r\n retErrStr = generateJsonRetStr(SHOULD_UPLOAD_ONE_JPG_FILE, '请上传一张图片以供识别')\r\n self.write(retErrStr)\r\n return None\r\n #error: has not attribute\r\n fileMetas = self.request.files['file']\r\n if 1 != len(fileMetas):\r\n self.__logger.error(\"upload file num is not 1\")\r\n retErrStr = generateJsonRetStr(PIC_NUM_SHOUD_ONE, 'upload file num is not 1')\r\n self.write(retErrStr)\r\n return None\r\n\r\n #check if upload file type is not jpg then return error\r\n fileMeta = fileMetas[0]\r\n oriFileName = fileMeta['filename']\r\n baseName, extStr = os.path.splitext(oriFileName)\r\n if extStr.lower() != '.jpg':\r\n self.__logger.error(\"upload file type is not jpg\")\r\n retErrStr = generateJsonRetStr(PIC_TYPE_SHOUD_JPG, 'upload file type is not jpg')\r\n self.write(retErrStr)\r\n return None\r\n\r\n randomStr = genUuidRandom()\r\n uploadedFileName = genUuidByFileName(randomStr)\r\n uploadedFileSavePathWithName = os.path.join(kUploadSavePath, uploadedFileName + '.jpg')\r\n with open(uploadedFileSavePathWithName, 'wb') as up:\r\n up.write(fileMeta['body'])\r\n self.__logger.info(\"file saved name is \" + uploadedFileSavePathWithName)\r\n\r\n return uploadedFileSavePathWithName","sub_path":"src/server/bakHandlers/RecgForHtmlHandler.py","file_name":"RecgForHtmlHandler.py","file_ext":"py","file_size_in_byte":3932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"610996598","text":"import os, math, cv2, sys, glob, random, argparse, csv\nfrom multiprocessing import Pool\nfrom itertools import product\nimport numpy as np\nimport rasterio\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nsys.path.append('../utils')\nsys.path.append('../models')\nfrom dataloaders import *\nfrom unet_blocks import *\nfrom metrics_and_losses import *\n\n\n\n\ndef read_band(band):\n r = rasterio.open(band)\n data = r.read()[0]\n r.close()\n return data \n\ndef read_bands(band_paths):\n pool = Pool(26)\n bands = pool.map(read_band, band_paths)\n pool.close()\n return bands\n\ndef _match_band(two_date):\n return match_band(two_date[1], two_date[0])\n\ndef match_bands(date1, date2):\n pool = Pool(13)\n date2 = pool.map(_match_band, [[date1[i], date2[i]] for i in range(len(date1))])\n pool.close()\n return date2\n\ndef _resize(band):\n return cv2.resize(band, (10980, 10980))\n\ndef stack_bands(bands):\n pool = Pool(26)\n bands = pool.map(_resize, bands)\n pool.close()\n pool = Pool(26)\n bands = pool.map(stretch_8bit, bands)\n pool.close()\n\n return np.stack(bands[:13]).astype(np.float32), np.stack(bands[13:]).astype(np.float32)\n\n\ndef inference(tid, d1, d2, profile, date1, date2, model):\n out = np.zeros((d1.shape[1], d1.shape[2]))\n\n batches1 = []\n batches2 = []\n ijs = []\n for i in range(0,d1.shape[1],64):\n for j in range(0,d1.shape[2],64):\n if i+input_size <= d1.shape[1] and j+input_size <= d1.shape[2]:\n batches1.append(d1[:,i:i+input_size,j:j+input_size])\n batches2.append(d2[:,i:i+input_size,j:j+input_size])\n ijs.append([i,j])\n elif i+input_size>d1.shape[1] and j+input_size<=d1.shape[2]:\n batches1.append(d1[:,d1.shape[1]-input_size:d1.shape[1],j:j+input_size])\n batches2.append(d2[:,d2.shape[1]-input_size:d2.shape[1],j:j+input_size])\n ijs.append([d1.shape[1]-input_size,j])\n elif i+input_size<=d1.shape[1] and j+input_size>d1.shape[2]:\n batches1.append(d1[:,i:i+input_size,d1.shape[2]-input_size:d1.shape[2]])\n batches2.append(d2[:,i:i+input_size,d2.shape[2]-input_size:d2.shape[2]])\n ijs.append([i,d1.shape[2]-input_size])\n else:\n batches1.append(d1[:,d1.shape[1]-input_size:d1.shape[1],\n d1.shape[2]-input_size:d1.shape[2]])\n batches2.append(d2[:,d2.shape[1]-input_size:d2.shape[1],\n d2.shape[2]-input_size:d2.shape[2]])\n ijs.append([d1.shape[1]-input_size,d1.shape[2]-input_size])\n\n if len(batches1) == 110:\n inp1 = w(torch.from_numpy(np.asarray(batches1) / 255.))\n inp2 = w(torch.from_numpy(np.asarray(batches2) / 255.))\n logits = model(inp1, inp2)\n pred = F.sigmoid(logits) > 0.5\n pred = pred.data.cpu().numpy()\n\n batches1 = []\n batches2 = []\n\n del inp1\n del inp2\n\n for c in range(len(ijs)):\n out[ijs[c][0]:ijs[c][0]+input_size,ijs[c][1]:ijs[c][1]+input_size] = pred[c]\n\n ijs = []\n\n\n profile['dtype'] = 'uint8'\n profile['driver'] = 'GTiff'\n fout = rasterio.open(results_dir + tid + '_' + date1 + '_' + date2 + '.tif', 'w', **profile)\n fout.write(np.asarray([out]).astype(np.uint8) * 255)\n fout.close()\n print (results_dir + tid + '_' + date1 + '_' + date2 + '.tif')\n\n\nparser = argparse.ArgumentParser(description='Inference on Yiwu tiles')\nparser.add_argument('--gpu_id', type=int, default=0, required=False)\n# parser.add_argument('--tile_id', required=True)\n\nopt = parser.parse_args()\n\n# dates = \"\"\"T50RQS 20151126T024032 20170228T023631 20171225T024121 20180728T023549\n# T51RTM 20151126T024032 20170228T023631 20171225T024121 20181001T023551\n# T51RTN 20151126T024032 20170228T023631 20171225T024121 20180728T023549\n# T50RQT 20151126T024032 20170228T023631 20171225T024121 20181001T023551\"\"\"\n# samples = {}\n# for line in dates.split('\\n'):\n# row = line.split()\n# samples[row[0]] = row[1:]\n\n\ninput_size = 64\nweight_file = '../../weights/onera/unet_siamese_prod_relu_inp64_13band_2dates_focal_hm_cnc_all_14_cities.pt'\n\ndata_dir = '/media/Drive1/CDTiles/'\nresults_dir = data_dir + 'cd_out/'\n\nfin = open(data_dir + '100_cities_distinct_pairs.csv', 'r')\nr = csv.reader(fin)\npairs = []\nfor row in r:\n pairs.append(row)\n \nif opt.gpu_id == 0:\n pairs_gpu = pairs[:30]\nif opt.gpu_id == 1:\n pairs_gpu = pairs[30:60]\nif opt.gpu_id == 2:\n pairs_gpu = pairs[60:90]\nif opt.gpu_id == 3:\n pairs_gpu = pairs[90:120]\n \nUSE_CUDA = torch.cuda.is_available()\ndef w(v):\n if USE_CUDA:\n return v.cuda(opt.gpu_id)\n return v\n\nmodel = w(UNetClassify(layers=6, init_filters=32, num_channels=13, fusion_method='mul', out_dim=1))\nweights = torch.load(weight_file, map_location='cuda:' + str(opt.gpu_id))\nmodel.load_state_dict(weights)\nmodel = model.eval()\n\n# dates = samples[opt.tile_id]\n# dates = ['20151126T024032','20151126T024032']\n# dates = ['20151126T024032',' 20170228T023631']\n# dates = ['20170228T023631','20151126T024032']\n# dates.sort()\n\nfor pair in pairs_gpu:\n \n date1 = pair[0]\n date2 = pair[2]\n \n d1_bands = glob.glob(data_dir + 'SAFES/' + pair[1] + '/GRANULE/**/IMG_DATA/*_B*.jp2')\n d2_bands = glob.glob(data_dir + 'SAFES/' + pair[3] + '/GRANULE/**/IMG_DATA/*_B*.jp2')\n\n# print (d1_bands, d2_bands)\n profile = rasterio.open(d1_bands[2]).profile\n\n\n d1_bands.sort()\n d2_bands.sort()\n\n #load bands for two dates and do preprocessing\n d1d2 = read_bands(d1_bands + d2_bands)\n d1d2[13:] = match_bands(d1d2[:13], d1d2[13:])\n d1, d2 = stack_bands(d1d2)\n\n d1_d2 = inference(pair[-1], d1, d2, profile, date1, date2, model)\n","sub_path":"inference/world_inference.py","file_name":"world_inference.py","file_ext":"py","file_size_in_byte":5913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"645166701","text":"from api.exception import GENERIC_unknown_error\nfrom api.utils import logger\nimport traceback\nimport json\n\nlogging = logger(__name__)\n\n\nclass DomainException(Exception):\n def __init__(\n self,\n error_object: dict = GENERIC_unknown_error,\n exception_object: Exception = None,\n additional_error_info: tuple = None,\n error_input: dict = None,\n ):\n\n # Properties\n self.error_message = error_object.get(\"error_message\")\n self.error_code = error_object.get(\"error_code\")\n self.status_code = error_object.get(\"status_code\")\n self.additional_error_info = additional_error_info\n self.error_input = json.dumps(error_input) if error_input else None\n\n if exception_object:\n self.exception_traceback = \" \".join(\n traceback.format_tb(tb=exception_object.__traceback__)\n )\n if not self.additional_error_info:\n # If there is no additional info, use error args\n self.additional_error_info = exception_object.args\n else:\n self.exception_traceback = None\n\n self.error_detail = {\n \"message\": self.error_message,\n \"error_code\": self.error_code,\n \"additional_info\": self.additional_error_info,\n }\n logging.error(\n f\"Exception raised with: Status Code - {self.status_code} Error Detail - {self.error_detail}\"\n )\n\n self.error_log_object = {\n \"error_message\": self.error_message,\n \"error_code\": self.error_code,\n \"additional_error_info\": self.additional_error_info,\n \"exception_traceback\": self.exception_traceback,\n \"error_input\": self.error_input,\n \"domain_id\": error_input.get(\"domain_id\") if error_input else None,\n }\n","sub_path":"services/domain/api/exception/domain_exception.py","file_name":"domain_exception.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"342346806","text":"import os\nfrom segtypes.segment import N64Segment\nfrom pathlib import Path\n\nclass N64SegBin(N64Segment):\n def split(self, rom_bytes, base_path):\n if self.type in self.options[\"modes\"] or \"all\" in self.options[\"modes\"]:\n out_dir = self.create_split_dir(base_path, \"bin\")\n\n with open(os.path.join(out_dir, self.name + \".bin\"), \"wb\") as f:\n f.write(rom_bytes[self.rom_start : self.rom_end])\n\n\n def get_ld_section(self):\n section_name = \".data_{}\".format(self.name)\n\n lines = []\n lines.append(\" /* 0x00000000 {:X}-{:X} [{:X}] */\".format(self.rom_start, self.rom_end, self.rom_end - self.rom_start))\n lines.append(\" {} 0x{:X} : AT(0x{:X}) \".format(section_name, self.rom_start, self.rom_start) + \"{\")\n lines.append(\" build/bin/{}.o(.data);\".format(self.name))\n lines.append(\" }\")\n lines.append(\"\")\n lines.append(\"\")\n return \"\\n\".join(lines)\n\n\n @staticmethod\n def create_makefile_target():\n return \"\"","sub_path":"segtypes/bin.py","file_name":"bin.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"401535444","text":"import sys\r\nfrom PyQt5.QtCore import Qt, QSize\r\nfrom PyQt5.QtWidgets import (QApplication, QDockWidget, QListWidget, QMainWindow, QMessageBox, QLineEdit, QDesktopWidget, QTreeWidget, QTableWidgetItem, QGridLayout, QToolButton, QAction,\r\n QTreeWidgetItemIterator, QPushButton, QLabel, QListWidgetItem, QHBoxLayout, QFrame, QTableWidget, QVBoxLayout, QWidget, QTreeWidgetItem, QInputDialog,\r\n QDialog, QTextEdit, QRadioButton, QSizePolicy, QFormLayout, QGroupBox, QTabWidget, QCompleter, QCheckBox)\r\nfrom PyQt5.QtGui import QFont, QIcon, QPixmap, QColor, QPalette\r\nimport mysql.connector\r\nimport pyodbc\r\nfrom PyQt5.Qt import QTextCursor, QComboBox\r\n\r\nclass MainWindow(QMainWindow):\r\n \r\n def __init__(self):\r\n super(MainWindow, self).__init__()\r\n \r\n self.gt = GarmentTree()\r\n\r\n self.createMenus()\r\n self.createToolbars()\r\n self.createStatusBar()\r\n self.createDockWindows()\r\n \r\n self.setCentralWidget(self.createTabs())\r\n self.setWindowTitle(\"CSR Proving Ground\")\r\n \r\n self.resize(1500, 900)\r\n qr = self.frameGeometry()\r\n cp = QDesktopWidget().availableGeometry().center()\r\n qr.moveCenter(cp)\r\n self.move(qr.topLeft())\r\n \r\n \r\n def about(self):\r\n QMessageBox.about(self, \"C3PO\", \"His high exaltedness, the Great Jabba the Hutt, has decreed that you are to be terminated immediately.\")\r\n\r\n def createMenus(self):\r\n self.createActions()\r\n \r\n self.fileMenu = self.menuBar().addMenu(\"&File\")\r\n self.fileMenu.addSeparator()\r\n self.fileMenu.addAction(self.quitAct)\r\n\r\n self.editMenu = self.menuBar().addMenu(\"&Edit\")\r\n\r\n self.viewMenu = self.menuBar().addMenu(\"&View\")\r\n\r\n self.menuBar().addSeparator()\r\n\r\n self.helpMenu = self.menuBar().addMenu(\"&Help\")\r\n self.helpMenu.addAction(self.aboutAct)\r\n\r\n def createToolbars(self):\r\n #self.homeToolBar = self.addToolBar(\"Home\")\r\n\r\n \r\n self.searchToolBar = self.addToolBar(\"Search\")\r\n \r\n# self.searchToolBar.addAction(self.homeAct)\r\n# self.searchToolBar.addSeparator()\r\n \r\n self.searchBar = QLineEdit()\r\n self.searchBar.setMaximumWidth(150)\r\n self.searchBar.setPlaceholderText('Search for a design')\r\n self.searchBar.returnPressed.connect(self.btnSearch_Click)\r\n self.searchToolBar.addWidget(self.searchBar)\r\n \r\n self.searchToolBar.addAction(self.searchAct) \r\n \r\n self.searchToolBar.addSeparator()\r\n \r\n btnAddVars = QPushButton('Add Name', self)\r\n btnAddVars.clicked.connect(self.btnAddVars_Click)\r\n self.searchToolBar.addWidget(btnAddVars)\r\n \r\n self.searchToolBar.addSeparator()\r\n \r\n self.lblVar1 = QLabel()\r\n self.lblVar1.setFont(QFont('Veranda', 14, QFont.Bold))\r\n #self.lblVar1.setMargin(10)\r\n self.lblVar1.setStyleSheet('padding-left:10px')\r\n self.searchToolBar.addWidget(self.lblVar1)\r\n \r\n self.lblTxtVar1 = QLabel()\r\n self.lblTxtVar1.setFont(QFont('Veranda', 14, QFont.Bold))\r\n #self.lblTxtVar1.setMargin(0)\r\n self.lblTxtVar1.setStyleSheet('padding-left:1px')\r\n self.searchToolBar.addWidget(self.lblTxtVar1)\r\n \r\n self.lblVar2 = QLabel()\r\n self.lblVar2.setFont(QFont('Veranda', 14, QFont.Bold))\r\n self.lblVar2.setMargin(10) \r\n self.searchToolBar.addWidget(self.lblVar2)\r\n \r\n self.lblTxtVar2 = QLabel()\r\n self.lblTxtVar2.setFont(QFont('Veranda', 14, QFont.Bold))\r\n self.lblTxtVar2.setMargin(0) \r\n self.searchToolBar.addWidget(self.lblTxtVar2)\r\n \r\n self.lblSkuName = QLabel()\r\n self.lblSkuName.setFont(QFont('Veranda', 14, QFont.Bold))\r\n self.lblSkuName.setMargin(10)\r\n self.searchToolBar.addWidget(self.lblSkuName)\r\n \r\n spacer = QWidget()\r\n spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)\r\n self.searchToolBar.addWidget(spacer)\r\n \r\n self.searchToolBar.addSeparator()\r\n self.searchToolBar.addAction(self.quitAct)\r\n \r\n \r\n def createStatusBar(self):\r\n self.statusBar().showMessage(\"Ready\")\r\n\r\n def createDockWindows(self):\r\n dock = QDockWidget(\"Available Garments Types\", self)\r\n #dock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea)\r\n self.availableItems = QListWidget(dock)\r\n self.availableItems.setMinimumWidth(350)\r\n self.availableItems.setMaximumWidth(350)\r\n #self.availableItems.addItems((\"stuff\"))\r\n self.availableItems.itemClicked.connect(self.itemClicked_Click)\r\n dock.setWidget(self.availableItems)\r\n self.addDockWidget(Qt.RightDockWidgetArea, dock)\r\n self.viewMenu.addAction(dock.toggleViewAction())\r\n dock.hide()\r\n\r\n self.dock = QDockWidget(\"Available Garment Sizes\", self)\r\n self.orderItem = QTreeWidget(dock)\r\n #self.orderItem.setMinimumWidth(350)\r\n #self.orderItem.setMaximumWidth(350)\r\n #self.orderItem.insertText((\"more stuff\"))\r\n self.dock.setWidget(self.orderItem)\r\n self.addDockWidget(Qt.RightDockWidgetArea, self.dock)\r\n self.viewMenu.addAction(self.dock.toggleViewAction())\r\n self.dock.hide()\r\n #Create a tree widget for use when the t-shirt is clicked.\r\n\r\n \r\n self.gt.treeDock.hide()\r\n \r\n def btnSale_Click(self):\r\n btnName = self.sender()\r\n sku_code = str(btnName.objectName())\r\n self.loadDesignItem(sku_code)\r\n \r\n def btnAddVars_Click(self):\r\n self.gt.addVariables()\r\n \r\n \r\n def btnSearch_Click(self):\r\n self.availableItems.clear()\r\n #self.orderItem.clear()\r\n searchTerm = self.searchBar.text()\r\n self.clearLayout(self.vbSearch)\r\n self.vbSearch.addLayout(self.createDesignButtons(searchTerm))\r\n self.twMain.setCurrentIndex(0)\r\n\r\n def itemClicked_Click(self):\r\n button = self.sender()\r\n txtItem = button.uniqueId\r\n self.gt.loadGarmentInfo(self.currentInfo[txtItem][2], self.currentInfo[txtItem][1], self.currentInfo[txtItem][0])\r\n #self.garmName.setExpanded(False)\r\n\r\n def createDesignButtons(self, qryId):\r\n btnLayout = QGridLayout() \r\n buttons = {}\r\n if qryId == 'default':\r\n qryResult = mysql_db.sale_buttons(self)\r\n else:\r\n qryResult = mysql_db.search_designs(self, qryId)\r\n \r\n \r\n \r\n k = 0\r\n j = 0\r\n if qryResult:\r\n for i in range(len(qryResult)):\r\n t = qryResult[i]\r\n \r\n # keep a reference to the buttons\r\n buttons[(i)] = QToolButton(self)\r\n buttons[(i)].setIcon(QIcon(\"//wampserver/\" + str(t[2])))\r\n buttons[(i)].setIconSize(QSize(180, 180))\r\n buttons[(i)].setAutoRaise(True)\r\n buttons[(i)].setToolButtonStyle(Qt.ToolButtonTextUnderIcon)\r\n buttons[(i)].setStyleSheet(\"background-color: rgb(255, 255, 255);\")\r\n buttons[(i)].setFont(QFont(\"Helvetica\",12,QFont.Bold))\r\n buttons[(i)].setObjectName(str(t[1]))\r\n buttons[(i)].setText(str(t[1]) + '\\n' + str(t[0]))\r\n buttons[(i)].clicked.connect(self.btnSale_Click)\r\n \r\n # add to the layout\r\n btnLayout.addWidget(buttons[(i)], j, k) \r\n \r\n \r\n if k == 3:\r\n j += 1\r\n k = 0\r\n else:\r\n k += 1 \r\n \r\n btnLayout.setObjectName(\"designPage\") \r\n else:\r\n QMessageBox.information(self, 'No Match', 'No designs match the search terms. Please try again.', QMessageBox.Ok)\r\n \r\n return btnLayout\r\n \r\n def createTabs(self):\r\n self.twMain = QTabWidget()\r\n \r\n self.tabSearch = QWidget()\r\n self.tabOrder = QWidget()\r\n self.tabCust = QWidget()\r\n \r\n self.vbSearch = QVBoxLayout(self.tabSearch)\r\n self.vbSearch.addLayout(self.createDesignButtons('default'))\r\n self.twMain.addTab(self.tabSearch, 'Designs')\r\n \r\n self.vbOrder = QVBoxLayout(self.tabOrder)\r\n self.twMain.addTab(self.tabOrder, 'Order Details')\r\n \r\n self.hbCust = QVBoxLayout(self.tabCust)\r\n self.hbCust.addLayout(self.createCustInfo())\r\n self.hbCust.addStretch()\r\n self.twMain.addTab(self.tabCust, 'Customer Details')\r\n \r\n return self.twMain\r\n \r\n \r\n \r\n def createActions(self):\r\n\r\n self.quitAct = QAction(QIcon('icon/exit.png'), \"&Quit\", self, shortcut=\"Ctrl+Q\", statusTip=\"Quit the application\", \r\n triggered=self.close)\r\n\r\n self.aboutAct = QAction(\"&About\", self, statusTip=\"Show the application's About box\", triggered=self.about) \r\n self.searchAct = QAction(QIcon('icon/search.png'), '&Search', self, statusTip=\"Find a design.\",\r\n triggered=self.btnSearch_Click)\r\n# self.homeAct = QAction(QIcon('icon/home-icon.png'), '&Home', self, shortcut=\"Ctrl+H\", statusTip=\"Return to home screen.\", \r\n# triggered=self.btnHome_Click)\r\n \r\n def loadDesignItem(self, sku_code):\r\n self.lblSkuName.setText(sku_code)\r\n des = mysql_db.design_info(self, sku_code)\r\n \r\n self.clearLayout(self.vbOrder)\r\n\r\n self.currentInfo = {}\r\n for i in des:\r\n self.item = QListWidgetItem()\r\n self.item.setText(str(i[7])) \r\n self.currentInfo[i[7]] = (str(i[7]),str(i[8]),str(i[3]),str(i[9]),str(i[10]),str(i[11]),str(i[1]))\r\n smImage = self.currentInfo['T-Shirts'][3]\r\n\r\n hBox = QHBoxLayout()\r\n \r\n pix = QLabel()\r\n smImg = QPixmap(\"//wampserver/\"+ smImage)\r\n myScaledPixmap = smImg.scaled(125,125, Qt.KeepAspectRatio)\r\n pix.setPixmap(myScaledPixmap)\r\n\r\n hBox.addWidget(pix)\r\n \r\n icons = {}\r\n for i in des:\r\n icons[(i)] = QToolButton(self)\r\n icons[(i)].setIcon(QIcon(\"//wampserver/\" + str(i[10])))\r\n icons[(i)].setIconSize(QSize(44, 44))\r\n icons[(i)].setAutoRaise(True)\r\n icons[(i)].setToolButtonStyle(Qt.ToolButtonTextUnderIcon)\r\n #icons[(i)].setStyleSheet(\"background-color: rgb(255, 255, 255);\")\r\n icons[(i)].setFont(QFont(\"Helvetica\",8))\r\n #icons[(i)].setObjectName(str(i[7]))\r\n icons[(i)].setText(str(i[7]) + '\\n' + str(i[3]))\r\n icons[(i)].uniqueId = str(i[7])\r\n icons[(i)].clicked.connect(self.itemClicked_Click)\r\n hBox.addWidget(icons[(i)])\r\n \r\n hBox.addStretch(1)\r\n \r\n hFrame = QFrame()\r\n hFrame.setLayout(hBox)\r\n hFrame.setMaximumHeight(200)\r\n hFrame.setStyleSheet(\"background-color: rgb(255, 255, 255);\") \r\n\r\n self.tblOrderDetails = self.createOrderTable()\r\n frmCust = self.showCustInfo()\r\n totBox = self.totalBox()\r\n \r\n vbDetails = QVBoxLayout()\r\n vbDetails.addWidget(totBox)\r\n vbDetails.addLayout(frmCust)\r\n vbDetails.addStretch()\r\n \r\n hbTbl = QHBoxLayout()\r\n hbTbl.addWidget(self.tblOrderDetails)\r\n hbTbl.addLayout(vbDetails)\r\n #self.hbTbl.addStretch()\r\n \r\n if self.leFirstName.text() != \"\":\r\n self.gbCustInfo.show()\r\n self.gbPayInfo.show()\r\n self.gbGiftMsg.show()\r\n self.gbSpecInst.show()\r\n if self.chkDitto.isChecked() == False:\r\n self.gbShipInfo.show()\r\n \r\n self.vbOrder.addWidget(hFrame)\r\n self.vbOrder.addLayout(hbTbl)\r\n #self.vbOrder.addWidget(totBox)\r\n \r\n self.vbOrder.addStretch(1)\r\n \r\n self.updateOrderDetails()\r\n self.gt.getCustomerName(sku_code) \r\n self.twMain.setCurrentIndex(1)\r\n \r\n def clearLayout(self, layout):\r\n if layout is not None:\r\n while layout.count():\r\n item = layout.takeAt(0)\r\n widget = item.widget()\r\n if widget is not None:\r\n widget.deleteLater()\r\n else:\r\n self.clearLayout(item.layout()) \r\n \r\n def createOrderTable(self):\r\n #Create table to hold and display details of order order as they are selected from the tree. \r\n tblOrderDetails = QTableWidget(7, 0)\r\n # Build the table to hold the information from the tree.\r\n tblOrderDetails.setMinimumHeight(500)\r\n #tblOrderDetails.setMaximumWidth(500) \r\n tblOrderDetails.setColumnCount(7)\r\n tblOrderDetails.setAlternatingRowColors(True)\r\n head = tblOrderDetails.horizontalHeader()\r\n head.setStretchLastSection(True) \r\n\r\n lstHeader = [\"Variables\", \"Design\", \"Category\", \"Type\", \"Size\", \"Price\", \"Qty\" ] \r\n tblOrderDetails.setHorizontalHeaderLabels(lstHeader)\r\n tblOrderDetails.setWordWrap(False) \r\n \r\n return tblOrderDetails \r\n \r\n def updateOrderDetails(self):\r\n # If there is already a garment tree we want to clear out the old lists we do this to catch in an error\r\n # in case this function get's called before there is a tree build or grown, ha ha.\r\n od = self.tblOrderDetails\r\n if self.gt.garmentTree:\r\n lstItems = []\r\n totPcs = 0\r\n totPri = 0\r\n # Open a iterator to iterate through the tree (again) and build a list of lists of items in the tree to be added to the table.\r\n itOrders = QTreeWidgetItemIterator(self.gt.garmentTree)\r\n while itOrders.value():\r\n if itOrders.value() != None:\r\n # Below makes sure that there are values for both the price and the quantity.\r\n if itOrders.value().text(3) != \"\" and itOrders.value().text(2) != \"\":\r\n # This makes sure that we are at the correct level in the tree so we do try to add what shouldn't be added\r\n if itOrders.value().parent().parent().parent() != None:\r\n txtItems = []\r\n txtItems = [itOrders.value().parent().parent().parent().text(0), itOrders.value().parent().parent().text(0), \r\n itOrders.value().parent().text(0), itOrders.value().text(0), itOrders.value().text(1), \r\n str(format(float(itOrders.value().text(2)) * float(itOrders.value().text(3)), '.2f')), \r\n itOrders.value().text(3)]\r\n \r\n lstItems.append(txtItems)\r\n totPcs += int(itOrders.value().text(3))\r\n totPri += float(itOrders.value().text(2)) * float(itOrders.value().text(3))\r\n itOrders += 1\r\n # A check to make sure the iterator picked up items from the list.\r\n if len(lstItems) > 0:\r\n od.setRowCount(len(lstItems))\r\n # Another check to make sure the list is there and has data, then we go through it and add data to the table.\r\n if lstItems:\r\n for i, row in enumerate(lstItems):\r\n for j, col in enumerate(row):\r\n item = QTableWidgetItem(col)\r\n item.setFlags(Qt.ItemIsEditable)\r\n od.setItem(i, j, item) \r\n \r\n od.resizeColumnsToContents() \r\n #below will resize the table based on the contents of the length of the data in the rows and columns.\r\n tblWidth = od.columnWidth(0) + od.columnWidth(1) + od.columnWidth(2) + od.columnWidth(3) + od.columnWidth(4) + od.columnWidth(5) + od.columnWidth(6) + od.columnWidth(7) + 15\r\n #for the double digit numbering on left of the table.\r\n if len(lstItems) > 9:\r\n tblWidth = tblWidth + 10\r\n #for the scroll bar when table hits its max height.\r\n if len(lstItems) > 15:\r\n tblWidth = tblWidth + 10 \r\n\r\n od.setMaximumWidth(tblWidth)\r\n od.setMinimumWidth(tblWidth)\r\n od.show() \r\n self.lblTotPcs.setText(str(totPcs))\r\n tenPct = False\r\n if totPcs >= 1 and totPcs <= 2:\r\n shipCost = 7.95\r\n elif totPcs >= 3 and totPcs <= 6:\r\n shipCost = 6.95\r\n elif totPcs >= 7:\r\n shipCost = 0.00\r\n if totPcs >= 12:\r\n tenPct = True\r\n self.lblTotShip.setText('$' + format(shipCost, '.2f'))\r\n self.lblTotPri.setText('$' + format(totPri, '.2f'))\r\n if tenPct == True:\r\n totFinal = totPri - (totPri * .1)\r\n self.lblTotPct.setText(\"10 Percent Off.\")\r\n else:\r\n totFinal = totPri + shipCost\r\n self.lblTotPct.setText(None)\r\n self.lblTotFinal.setText('$' + format(totFinal, '.2f'))\r\n \r\n else:\r\n od.hide() \r\n self.gbTotal.hide()\r\n self.gbCustInfo.hide()\r\n self.gbShipInfo.hide()\r\n self.gbPayInfo.hide()\r\n self.gbGiftMsg.hide()\r\n self.gbSpecInst.hide()\r\n\r\n \r\n def totalBox(self):\r\n \r\n style = \"\"\"QGroupBox \r\n { \r\n background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\r\n stop: 0 #E0E0E0, stop: 1 #FFFFFF);\r\n border: 2px solid gray;\r\n border-radius: 5px;\r\n margin-top: 2.5ex; /* leave space at the top for the title */\r\n font-size: 14px;\r\n font-weight: bold;\r\n margin-left: 25px;\r\n } \r\n QLabel \r\n { \r\n font-size: 12px; \r\n font-weight: bold; \r\n font-family: Veranda; \r\n } \r\n QGroupBox::title\r\n {\r\n subcontrol-origin: margin;\r\n subcontrol-position: top center; /* position at the top center */\r\n padding: 0 3px;\r\n }\r\n \"\"\" \r\n \r\n self.gbTotal = QGroupBox('Order Totals')\r\n self.gbTotal.setStyleSheet(style)\r\n self.gbTotal.setMaximumWidth(325)\r\n \r\n frmTotal = QFormLayout()\r\n\r\n self.lblTotPcs = QLabel()\r\n frmTotal.addRow(QLabel('Total Pieces:'), self.lblTotPcs)\r\n \r\n self.lblTotPri = QLabel()\r\n frmTotal.addRow(QLabel('Sub-Total:'), self.lblTotPri)\r\n \r\n self.lblTotShip = QLabel()\r\n frmTotal.addRow(QLabel('Shipping:'), self.lblTotShip)\r\n\r\n self.lblTotPct = QLabel()\r\n frmTotal.addRow(QLabel('Qty Discount:'), self.lblTotPct)\r\n \r\n self.lblTotFinal = QLabel()\r\n frmTotal.addRow(QLabel('Grand-Total:'), self.lblTotFinal)\r\n \r\n self.gbTotal.setLayout(frmTotal)\r\n \r\n return self.gbTotal\r\n \r\n def groupBoxStyle(self):\r\n style = \"\"\"QGroupBox \r\n { \r\n background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\r\n stop: 0 #E0E0E0, stop: 1 #FFFFFF);\r\n border: 2px solid gray;\r\n border-radius: 5px;\r\n margin-top: 2.5ex; /* leave space at the top for the title */\r\n font-size: 12px;\r\n font-weight: bold;\r\n \r\n } \r\n QLabel \r\n { \r\n font-size: 12px; \r\n font-weight: bold; \r\n font-family: Veranda; \r\n } \r\n QCheckBox \r\n { \r\n font-size: 12px; \r\n font-weight: bold; \r\n font-family: Veranda; \r\n } \r\n QGroupBox::title\r\n {\r\n subcontrol-origin: margin;\r\n subcontrol-position: top center; /* position at the top center */\r\n padding: 0 3px;\r\n }\r\n \"\"\"\r\n \r\n return style \r\n \r\n \r\n def custInfoForm(self):\r\n \r\n style = self.groupBoxStyle()\r\n \r\n gbCustInfo = QGroupBox('Customer\\Billing Info')\r\n gbCustInfo.setStyleSheet(style) \r\n gbCustInfo.setMaximumWidth(325)\r\n gbCustInfo.setMinimumWidth(325)\r\n gbCustInfo.setMaximumHeight(375)\r\n \r\n frmCustInfo = QFormLayout()\r\n \r\n self.leFirstName = QLineEdit()\r\n self.leFirstName.textChanged.connect(self.custInfoChanged)\r\n self.leFirstName.setObjectName('firstName')\r\n self.leFirstName.setMaximumWidth(200)\r\n frmCustInfo.addRow(QLabel('First Name:'), self.leFirstName)\r\n \r\n self.leLastName = QLineEdit()\r\n self.leLastName.textChanged.connect(self.custInfoChanged)\r\n self.leLastName.setObjectName('lastName')\r\n self.leLastName.setMaximumWidth(200)\r\n frmCustInfo.addRow(QLabel('Last Name:'), self.leLastName)\r\n\r\n self.leCompany = QLineEdit()\r\n self.leCompany.setPlaceholderText('Not Required')\r\n self.leCompany.textChanged.connect(self.custInfoChanged)\r\n self.leCompany.setObjectName('company')\r\n self.leCompany.setMaximumWidth(200)\r\n frmCustInfo.addRow(QLabel('Company:'), self.leCompany)\r\n \r\n self.leAdd1 = QLineEdit()\r\n self.leAdd1.textChanged.connect(self.custInfoChanged)\r\n self.leAdd1.setObjectName('add1')\r\n self.leAdd1.setMaximumWidth(200)\r\n frmCustInfo.addRow(QLabel('Address 1:'), self.leAdd1)\r\n \r\n self.leAdd2 = QLineEdit()\r\n self.leAdd2.textChanged.connect(self.custInfoChanged)\r\n self.leAdd2.setObjectName('add2')\r\n self.leAdd2.setMaximumWidth(200)\r\n frmCustInfo.addRow(QLabel('Address 2:'), self.leAdd2)\r\n \r\n self.leCity = QLineEdit()\r\n self.leCity.textChanged.connect(self.custInfoChanged)\r\n self.leCity.setObjectName('city')\r\n self.leCity.setMaximumWidth(200)\r\n frmCustInfo.addRow(QLabel('City:'), self.leCity) \r\n\r\n states = mssql_db.getStates(self)\r\n \r\n stateCompleter = QCompleter(states)\r\n stateCompleter.setCompletionMode(QCompleter.UnfilteredPopupCompletion) \r\n stateCompleter.setCaseSensitivity(Qt.CaseInsensitive)\r\n \r\n self.leState = QLineEdit()\r\n self.leState.setPlaceholderText(\"State\")\r\n self.leState.setCompleter(stateCompleter)\r\n self.leState.textChanged.connect(self.custInfoChanged)\r\n self.leState.setObjectName('state')\r\n frmCustInfo.addRow(QLabel('State:'), self.leState)\r\n self.leState.setMaximumWidth(50)\r\n \r\n self.leZip = QLineEdit()\r\n self.leZip.textChanged.connect(self.custInfoChanged)\r\n self.leZip.setObjectName('zip')\r\n self.leZip.setMaximumWidth(75)\r\n frmCustInfo.addRow(QLabel('Zip:'), self.leZip)\r\n \r\n self.lePhone = QLineEdit()\r\n self.lePhone.textChanged.connect(self.custInfoChanged)\r\n self.lePhone.setObjectName('phone')\r\n self.lePhone.setMaximumWidth(200)\r\n frmCustInfo.addRow(QLabel('Phone:'), self.lePhone)\r\n \r\n self.leEmail = QLineEdit()\r\n self.leEmail.textChanged.connect(self.custInfoChanged)\r\n self.leEmail.setObjectName('email')\r\n self.leEmail.setMaximumWidth(200)\r\n frmCustInfo.addRow(QLabel('Email:'), self.leEmail)\r\n \r\n self.chkOffers = QCheckBox('Send product news and special offers.')\r\n frmCustInfo.addRow(self.chkOffers)\r\n \r\n self.chkDitto = QCheckBox('Shipping name and address same as billing.')\r\n self.chkDitto.clicked.connect(self.custInfoChanged)\r\n self.chkDitto.setObjectName('ditto')\r\n frmCustInfo.addRow(self.chkDitto)\r\n \r\n gbCustInfo.setLayout(frmCustInfo)\r\n \r\n return gbCustInfo \r\n \r\n def shippingInfoForm(self):\r\n \r\n style = self.groupBoxStyle()\r\n \r\n frmShipInfo = QFormLayout()\r\n self.gbShippingInfo = QGroupBox('Shipping Info')\r\n self.gbShippingInfo.setStyleSheet(style)\r\n self.gbShippingInfo.setMaximumWidth(325)\r\n self.gbShippingInfo.setMinimumWidth(325)\r\n \r\n self.leShipFn = QLineEdit()\r\n self.leShipFn.textChanged.connect(self.custInfoChanged)\r\n self.leShipFn.setObjectName('shipFn')\r\n self.leShipFn.setMaximumWidth(200)\r\n frmShipInfo.addRow(QLabel('First Name:'), self.leShipFn)\r\n \r\n self.leShipLn = QLineEdit()\r\n self.leShipLn.textChanged.connect(self.custInfoChanged)\r\n self.leShipLn.setObjectName('shipLn')\r\n self.leShipLn.setMaximumWidth(200)\r\n frmShipInfo.addRow(QLabel('Last Name:'), self.leShipLn)\r\n \r\n self.leShipCompany = QLineEdit()\r\n self.leShipCompany.textChanged.connect(self.custInfoChanged)\r\n self.leShipCompany.setObjectName('shipCompany')\r\n self.leShipCompany.setPlaceholderText('Not Required')\r\n self.leShipCompany.setMaximumWidth(200)\r\n frmShipInfo.addRow(QLabel('Company:'), self.leShipCompany)\r\n \r\n self.leShipAdd1 = QLineEdit()\r\n self.leShipAdd1.textChanged.connect(self.custInfoChanged)\r\n self.leShipAdd1.setObjectName('shipAdd1')\r\n self.leShipAdd1.setMaximumWidth(200)\r\n frmShipInfo.addRow(QLabel('Address 1:'), self.leShipAdd1)\r\n \r\n self.leShipAdd2 = QLineEdit()\r\n self.leShipAdd2.textChanged.connect(self.custInfoChanged)\r\n self.leShipAdd2.setObjectName('shipAdd2')\r\n self.leShipAdd2.setMaximumWidth(200)\r\n frmShipInfo.addRow(QLabel('Address 2:'), self.leShipAdd2)\r\n \r\n self.leShipCity = QLineEdit()\r\n self.leShipCity.textChanged.connect(self.custInfoChanged)\r\n self.leShipCity.setObjectName('shipCity')\r\n self.leShipCity.setMaximumWidth(200)\r\n frmShipInfo.addRow(QLabel('City:'), self.leShipCity)\r\n \r\n states = mssql_db.getStates(self)\r\n \r\n stateCompleter = QCompleter(states)\r\n stateCompleter.setCompletionMode(QCompleter.UnfilteredPopupCompletion) \r\n stateCompleter.setCaseSensitivity(Qt.CaseInsensitive)\r\n \r\n self.leShipState = QLineEdit()\r\n self.leShipState.setPlaceholderText(\"State\")\r\n self.leShipState.setCompleter(stateCompleter)\r\n self.leShipState.textChanged.connect(self.custInfoChanged)\r\n self.leShipState.setObjectName('shipState')\r\n self.leShipState.setMaximumWidth(50)\r\n frmShipInfo.addRow(QLabel('State:'), self.leShipState)\r\n \r\n self.leShipZip = QLineEdit()\r\n self.leShipZip.textChanged.connect(self.custInfoChanged)\r\n self.leShipZip.setObjectName('shipZip')\r\n self.leShipZip.setMaximumWidth(75)\r\n frmShipInfo.addRow(QLabel('Zip:'), self.leShipZip)\r\n \r\n self.leShipPhone = QLineEdit()\r\n self.leShipPhone.textChanged.connect(self.custInfoChanged)\r\n self.leShipPhone.setObjectName('shipPhone')\r\n self.leShipPhone.setMaximumWidth(200)\r\n frmShipInfo.addRow(QLabel('Phone:'), self.leShipPhone)\r\n \r\n self.gbShippingInfo.setLayout(frmShipInfo)\r\n \r\n return self.gbShippingInfo\r\n \r\n def paymentForm(self):\r\n \r\n style = self.groupBoxStyle()\r\n \r\n self.frmPayInfo = QFormLayout()\r\n gbPayInfo = QGroupBox('Payment Info')\r\n gbPayInfo.setStyleSheet(style)\r\n gbPayInfo.setMaximumWidth(325)\r\n gbPayInfo.setMinimumWidth(325)\r\n\r\n payTypes = ['Credit Card', 'Check or Money Order']\r\n \r\n self.cbPayType = QComboBox()\r\n self.cbPayType.addItems(payTypes)\r\n self.cbPayType.currentIndexChanged.connect(self.cbPayTypeChanged)\r\n self.cbPayType.currentIndexChanged.connect(self.custInfoChanged)\r\n self.cbPayType.setObjectName('cbPayType')\r\n self.cbPayType.setCurrentIndex(0)\r\n self.frmPayInfo.addRow(self.cbPayType)\r\n \r\n gbPayInfo.setLayout(self.frmPayInfo)\r\n \r\n self.cbPayTypeChanged(0)\r\n \r\n return gbPayInfo\r\n \r\n def cbPayTypeChanged(self, index):\r\n if index == 0:\r\n \r\n self.removePayInfo()\r\n self.frmPayInfo.addRow(self.cbPayType)\r\n \r\n ccTypes = [' - Please Select Card Type -', 'Visa', 'MasterCard', 'Discover', 'American Express']\r\n \r\n self.cbCardType = QComboBox()\r\n self.cbCardType.addItems(ccTypes)\r\n self.cbCardType.setObjectName('cardType')\r\n self.cbCardType.currentIndexChanged.connect(self.custInfoChanged)\r\n self.frmPayInfo.addRow(QLabel('Credit Card:'), self.cbCardType)\r\n \r\n self.leCardNumber = QLineEdit()\r\n self.leCardNumber.setObjectName('cardNumber')\r\n self.leCardNumber.textChanged.connect(self.custInfoChanged)\r\n self.frmPayInfo.addRow(QLabel('Card Number:'), self.leCardNumber)\r\n \r\n self.leCardExpire = QLineEdit()\r\n self.leCardExpire.setObjectName('cardExpire')\r\n self.leCardExpire.textChanged.connect(self.custInfoChanged)\r\n self.frmPayInfo.addRow(QLabel('Expiration Date:'), self.leCardExpire)\r\n \r\n self.leCardCode = QLineEdit()\r\n self.leCardCode.setObjectName('cardCode')\r\n self.leCardCode.textChanged.connect(self.custInfoChanged)\r\n self.frmPayInfo.addRow(QLabel('Security Code:'), self.leCardCode)\r\n \r\n elif index == 1:\r\n \r\n self.removePayInfo()\r\n self.frmPayInfo.addRow(self.cbPayType)\r\n \r\n self.leCheckNumber = QLineEdit()\r\n self.leCheckNumber.setObjectName('checkNumber')\r\n self.leCheckNumber.textChanged.connect(self.custInfoChanged)\r\n self.frmPayInfo.addRow(QLabel('Check\\MO Number:'), self.leCheckNumber)\r\n else:\r\n self.removePayInfo()\r\n \r\n \r\n def removePayInfo(self):\r\n for cnt in reversed(range(self.frmPayInfo.count())):\r\n # takeAt does both the jobs of itemAt and removeWidget\r\n # namely it removes an item and returns it\r\n widget = self.frmPayInfo.takeAt(cnt).widget()\r\n \r\n if widget is not None: \r\n if widget.objectName() != 'cbPayType':\r\n # widget will be None if the item is a layout\r\n widget.deleteLater() \r\n \r\n def createCustInfo(self):\r\n\r\n btnReview = QToolButton()\r\n btnReview.setIcon(QIcon(\"icon/review.png\"))\r\n btnReview.setAutoRaise(1)\r\n btnReview.setIconSize(QSize(50, 50))\r\n btnReview.clicked.connect(lambda: self.twMain.setCurrentIndex(1))\r\n \r\n custInfo = self.custInfoForm()\r\n shipInfo = self.shippingInfoForm()\r\n payInfo = self.paymentForm()\r\n \r\n gbSpecial = QGroupBox('Special Instructions')\r\n gbSpecial.setStyleSheet(self.groupBoxStyle())\r\n gbSpecial.setMaximumWidth(325)\r\n gbSpecial.setMaximumHeight(125)\r\n \r\n self.teSpecial = QTextEdit()\r\n self.teSpecial.setMaximumWidth(300)\r\n self.teSpecial.setObjectName('specInst')\r\n self.teSpecial.textChanged.connect(self.textEditChanged)\r\n \r\n hbSpecial = QHBoxLayout()\r\n hbSpecial.addWidget(self.teSpecial)\r\n \r\n gbSpecial.setLayout(hbSpecial)\r\n \r\n gbGiftMsg = QGroupBox('Gift Message')\r\n gbGiftMsg.setStyleSheet(self.groupBoxStyle())\r\n gbGiftMsg.setMaximumWidth(325)\r\n gbGiftMsg.setMaximumHeight(125)\r\n \r\n self.teGiftMsg = QTextEdit()\r\n self.teGiftMsg.setMaximumWidth(300)\r\n self.teGiftMsg.setObjectName('giftMsg')\r\n self.teGiftMsg.textChanged.connect(self.textEditChanged)\r\n \r\n hbGift = QHBoxLayout()\r\n hbGift.addWidget(self.teGiftMsg)\r\n \r\n gbGiftMsg.setLayout(hbGift)\r\n \r\n grdCust = QGridLayout()\r\n grdCust.addWidget(custInfo, 0, 0)\r\n grdCust.addWidget(shipInfo, 0, 1)\r\n grdCust.addWidget(payInfo, 0, 2)\r\n grdCust.addWidget(gbGiftMsg, 1, 0, 1, 1)\r\n grdCust.addWidget(gbSpecial, 1, 1, 1, 1)\r\n grdCust.addWidget(btnReview, 1, 2)\r\n \r\n return grdCust\r\n \r\n def textEditChanged(self):\r\n te = self.sender()\r\n self.custInfoChanged(te.toPlainText())\r\n \r\n def showCustInfo(self):\r\n \r\n styleCust = \"\"\"QGroupBox \r\n { \r\n background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\r\n stop: 0 #E0E0E0, stop: 1 #FFFFFF);\r\n border: 2px solid gray;\r\n border-radius: 5px;\r\n margin-top: 2.5ex; /* leave space at the top for the title */\r\n font-size: 14px;\r\n font-weight: bold;\r\n margin-left: 25px;\r\n } \r\n QLabel \r\n { \r\n font-size: 12px; \r\n font-weight: bold; \r\n font-family: Veranda; \r\n } \r\n QGroupBox::title\r\n {\r\n subcontrol-origin: margin;\r\n subcontrol-position: top center; /* position at the top center */\r\n padding: 0 3px;\r\n }\r\n QTextEdit\r\n {\r\n background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\r\n stop: 0 #E0E0E0, stop: 1 #FFFFFF);\r\n font-weight: bold;\r\n border: 0px;\r\n \r\n } \r\n \"\"\" \r\n \r\n styleShip = \"\"\"QGroupBox \r\n { \r\n background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\r\n stop: 0 #E0E0E0, stop: 1 #FFFFFF);\r\n border: 2px solid gray;\r\n border-radius: 5px;\r\n margin-top: 2.5ex; /* leave space at the top for the title */\r\n font-size: 14px;\r\n font-weight: bold;\r\n margin-left: 5px;\r\n } \r\n QLabel \r\n { \r\n font-size: 12px; \r\n font-weight: bold; \r\n font-family: Veranda; \r\n } \r\n QGroupBox::title\r\n {\r\n subcontrol-origin: margin;\r\n subcontrol-position: top center; /* position at the top center */\r\n padding: 0 3px;\r\n }\r\n QTextEdit\r\n {\r\n background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\r\n stop: 0 #E0E0E0, stop: 1 #FFFFFF);\r\n font-weight: bold;\r\n border: 0px;\r\n }\r\n \"\"\" \r\n \r\n \r\n self.gbCustInfo = QGroupBox('Customer\\Billing Info')\r\n self.gbCustInfo.setStyleSheet(styleCust)\r\n self.gbCustInfo.setMinimumWidth(325)\r\n \r\n frmCustInfo = QFormLayout()\r\n \r\n self.lblTxtFname = QLabel()\r\n self.lblTxtFname.setText(self.leFirstName.text())\r\n #frmCustInfo.addRow(QLabel('First Name:'), self.lblTxtFname)\r\n \r\n self.lblTxtLname = QLabel()\r\n self.lblTxtLname.setText(self.leLastName.text())\r\n #frmCustInfo.addRow(QLabel('Last Name:'), self.lblTxtLname)\r\n \r\n hbName = QHBoxLayout()\r\n #hbName.addWidget(QLabel('First Name:'))\r\n hbName.addWidget(self.lblTxtFname)\r\n #hbName.addWidget(QLabel('Last Name:'))\r\n hbName.addWidget(self.lblTxtLname)\r\n hbName.addStretch()\r\n frmCustInfo.addRow(QLabel('Name:'), hbName)\r\n\r\n self.lblTxtCompany = QLabel()\r\n self.lblTxtCompany.setText(self.leCompany.text())\r\n frmCustInfo.addRow(QLabel('Company:'), self.lblTxtCompany)\r\n \r\n self.lblTxtAdd1 = QLabel()\r\n self.lblTxtAdd1.setText(self.leAdd1.text())\r\n frmCustInfo.addRow(QLabel('Address 1:'), self.lblTxtAdd1)\r\n \r\n self.lblTxtAdd2 = QLabel()\r\n self.lblTxtAdd2.setText(self.leAdd2.text())\r\n frmCustInfo.addRow(QLabel('Address 2:'), self.lblTxtAdd2)\r\n\r\n self.lblTxtCity = QLabel()\r\n if self.leCity.text() != '':\r\n self.lblTxtCity.setText(self.leCity.text() + ',')\r\n #frmCustInfo.addRow(QLabel('City:'), self.lblTxtCity) \r\n \r\n self.lblTxtState = QLabel()\r\n self.lblTxtState.setText(self.leState.text())\r\n #frmCustInfo.addRow(QLabel('State:'), self.lblTxtState)\r\n \r\n self.lblTxtZip = QLabel()\r\n self.lblTxtZip.setText(self.leZip.text())\r\n #frmCustInfo.addRow(QLabel('Zip:'), self.lblTxtZip)\r\n \r\n hbAddy = QHBoxLayout()\r\n hbAddy.addWidget(self.lblTxtCity)\r\n hbAddy.addWidget(self.lblTxtState)\r\n hbAddy.addWidget(self.lblTxtZip)\r\n hbAddy.addStretch()\r\n frmCustInfo.addRow(QLabel('City/State/Zip:'), hbAddy)\r\n \r\n self.lblTxtPhone = QLabel()\r\n self.lblTxtPhone.setText(self.lePhone.text())\r\n frmCustInfo.addRow(QLabel('Phone:'), self.lblTxtPhone)\r\n \r\n self.lblTxtEmail = QLabel()\r\n self.lblTxtEmail.setText(self.leEmail.text())\r\n frmCustInfo.addRow(QLabel('Email:'), self.lblTxtEmail)\r\n \r\n self.lblTxtShipSame = QLabel()\r\n if self.chkDitto.isChecked():\r\n self.lblTxtShipSame.setText('*Shipping name and address same as billing.')\r\n\r\n frmCustInfo.addRow(self.lblTxtShipSame)\r\n \r\n self.gbCustInfo.setLayout(frmCustInfo)\r\n self.gbCustInfo.hide()\r\n \r\n \r\n self.gbShipInfo = QGroupBox('Shipping Info')\r\n self.gbShipInfo.setStyleSheet(styleShip)\r\n self.gbShipInfo.setMinimumWidth(325)\r\n frmShipInfo = QFormLayout()\r\n \r\n self.lblTxtShipFn = QLabel()\r\n self.lblTxtShipFn.setText(self.leShipFn.text())\r\n #frmShipInfo.addRow(QLabel('First Name:'), self.lblTxtShipFn)\r\n \r\n self.lblTxtShipLn = QLabel()\r\n self.lblTxtShipLn.setText(self.leShipLn.text())\r\n #frmShipInfo.addRow(QLabel('Last Name:'), self.lblTxtShipLn)\r\n \r\n hbShipName = QHBoxLayout()\r\n hbShipName.addWidget(self.lblTxtShipFn)\r\n hbShipName.addWidget(self.lblTxtShipLn)\r\n hbShipName.addStretch()\r\n frmShipInfo.addRow(QLabel('Name:'), hbShipName)\r\n \r\n self.lblTxtShipCompany = QLabel()\r\n self.lblTxtShipCompany.setText(self.leShipCompany.text())\r\n frmShipInfo.addRow(QLabel('Company:'), self.lblTxtShipCompany)\r\n \r\n self.lblTxtShipAdd1 = QLabel()\r\n self.lblTxtShipAdd1.setText(self.leShipAdd1.text())\r\n frmShipInfo.addRow(QLabel('Address 1:'), self.lblTxtShipAdd1)\r\n \r\n self.lblTxtShipAdd2 = QLabel()\r\n self.lblTxtShipAdd2.setText(self.leShipAdd2.text())\r\n frmShipInfo.addRow(QLabel('Address 2:'), self.lblTxtShipAdd2)\r\n \r\n self.lblTxtShipCity = QLabel()\r\n if self.leShipCity.text() != '':\r\n self.lblTxtShipCity.setText(self.leShipCity.text() + ',')\r\n \r\n self.lblTxtShipState = QLabel()\r\n self.lblTxtShipState.setText(self.leShipState.text())\r\n \r\n self.lblTxtShipZip = QLabel()\r\n self.lblTxtShipZip.setText(self.leShipZip.text())\r\n \r\n hbShipAdd = QHBoxLayout()\r\n hbShipAdd.addWidget(self.lblTxtShipCity)\r\n hbShipAdd.addWidget(self.lblTxtShipState)\r\n hbShipAdd.addWidget(self.lblTxtShipZip)\r\n hbShipAdd.addStretch()\r\n frmShipInfo.addRow(QLabel('City/State/Zip:'), hbShipAdd)\r\n \r\n self.lblTxtShipPhone = QLabel()\r\n self.lblTxtShipPhone.setText(self.leShipPhone.text())\r\n frmShipInfo.addRow(QLabel('Phone:'), self.lblTxtShipPhone)\r\n \r\n self.gbShipInfo.setLayout(frmShipInfo)\r\n self.gbShipInfo.hide()\r\n \r\n self.gbPayInfo = QGroupBox('Payment Details')\r\n self.gbPayInfo.setStyleSheet(styleCust)\r\n \r\n self.frmPaymentInfo = QFormLayout()\r\n self.lblTxtPayType = QLabel()\r\n self.lblTxtPayType.setText(self.cbPayType.currentText())\r\n \r\n self.getPaymentDetails()\r\n \r\n self.gbPayInfo.setLayout(self.frmPaymentInfo)\r\n self.gbPayInfo.hide()\r\n \r\n self.gbGiftMsg = QGroupBox('Gift Message')\r\n self.gbGiftMsg.setStyleSheet(styleCust)\r\n \r\n frmGiftMsg = QFormLayout()\r\n \r\n self.teTxtGiftMsg = QTextEdit()\r\n self.teTxtGiftMsg.setReadOnly(True)\r\n self.teTxtGiftMsg.setText(self.teGiftMsg.toPlainText())\r\n \r\n frmGiftMsg.addRow(self.teTxtGiftMsg)\r\n \r\n self.gbGiftMsg.setLayout(frmGiftMsg)\r\n self.gbGiftMsg.hide()\r\n \r\n self.gbSpecInst = QGroupBox('Special Instructions')\r\n self.gbSpecInst.setMinimumWidth(325)\r\n self.gbSpecInst.setStyleSheet(styleShip)\r\n \r\n frmSpecInst = QFormLayout()\r\n \r\n self.teTxtSpecInst = QTextEdit()\r\n self.teTxtSpecInst.setReadOnly(True)\r\n self.teTxtSpecInst.setText(self.teSpecial.toPlainText())\r\n \r\n frmSpecInst.addRow(self.teTxtSpecInst)\r\n \r\n self.gbSpecInst.setLayout(frmSpecInst)\r\n self.gbSpecInst.hide()\r\n \r\n grdShipBill = QGridLayout()\r\n grdShipBill.addWidget(self.gbCustInfo, 0, 0)\r\n grdShipBill.addWidget(self.gbShipInfo, 0, 1)\r\n grdShipBill.addWidget(self.gbPayInfo, 2, 0)\r\n grdShipBill.addWidget(self.gbGiftMsg, 3, 0)\r\n grdShipBill.addWidget(self.gbSpecInst, 3, 1)\r\n \r\n return grdShipBill\r\n \r\n def getPaymentDetails(self):\r\n if self.cbPayType.currentIndex() == 0:\r\n self.clearLayout(self.frmPaymentInfo)\r\n self.frmPaymentInfo.addRow(QLabel('Payment Type:'), self.lblTxtPayType)\r\n \r\n self.lblTxtCardType = QLabel()\r\n self.lblTxtCardType.setText(self.cbCardType.currentText())\r\n self.frmPaymentInfo.addRow(QLabel('Card Type:'), self.lblTxtCardType)\r\n \r\n self.lblTxtCardNumber = QLabel()\r\n self.lblTxtCardNumber.setText(self.leCardNumber.text())\r\n self.frmPaymentInfo.addRow(QLabel('Card number:'), self.lblTxtCardNumber)\r\n \r\n self.lblTxtCardExpire = QLabel()\r\n self.lblTxtCardExpire.setText(self.leCardExpire.text())\r\n self.frmPaymentInfo.addRow(QLabel('Expiration:'), self.lblTxtCardExpire)\r\n \r\n self.lblTxtCardCode = QLabel()\r\n self.lblTxtCardCode.setText(self.leCardCode.text())\r\n self.frmPaymentInfo.addRow(QLabel('Security Code:'), self.lblTxtCardCode)\r\n \r\n elif self.cbPayType.currentIndex() == 1:\r\n self.clearLayout(self.frmPaymentInfo)\r\n self.frmPaymentInfo.addRow(QLabel('Payment Type:'), self.lblTxtPayType)\r\n self.lblTxtChkNumber = QLabel()\r\n self.lblTxtChkNumber.setText(self.leCheckNumber.text())\r\n self.frmPaymentInfo.addRow(QLabel('Check\\MO Number:'), self.lblTxtChkNumber)\r\n \r\n \r\n def custInfoChanged(self, text):\r\n wdt = self.sender()\r\n \r\n if wdt.objectName() == 'cbPayType':\r\n self.lblTxtPayType = QLabel()\r\n self.lblTxtPayType.setText(self.cbPayType.currentText()) \r\n self.getPaymentDetails()\r\n \r\n if wdt != None:\r\n self.gbCustInfo.show()\r\n if self.chkDitto.isChecked() == False:\r\n self.gbShipInfo.show()\r\n self.gbPayInfo.show()\r\n self.gbGiftMsg.show()\r\n self.gbSpecInst.show()\r\n \r\n if wdt.objectName() == 'firstName':\r\n self.lblTxtFname.setText(text)\r\n elif wdt.objectName() == 'lastName':\r\n self.lblTxtLname.setText(text)\r\n elif wdt.objectName() == 'add1':\r\n self.lblTxtAdd1.setText(text)\r\n elif wdt.objectName() == 'add2':\r\n self.lblTxtAdd2.setText(text)\r\n elif wdt.objectName() == 'company':\r\n self.lblTxtCompany.setText(text)\r\n elif wdt.objectName() == 'city':\r\n self.lblTxtCity.setText(text + ',') \r\n elif wdt.objectName() == 'state':\r\n self.lblTxtState.setText(text)\r\n elif wdt.objectName() == 'zip':\r\n self.lblTxtZip.setText(text)\r\n elif wdt.objectName() == 'phone':\r\n self.lblTxtPhone.setText(text)\r\n elif wdt.objectName() == 'email':\r\n self.lblTxtEmail.setText(text)\r\n elif wdt.objectName() == 'cardType':\r\n self.lblTxtCardType.setText(self.cbCardType.currentText())\r\n elif wdt.objectName() == 'cbPayType':\r\n self.lblTxtPayType.setText(wdt.currentText())\r\n elif wdt.objectName() == 'checkNumber':\r\n self.lblTxtChkNumber.setText(text)\r\n elif wdt.objectName() == 'cardNumber':\r\n self.lblTxtCardNumber.setText(text)\r\n elif wdt.objectName() == 'cardExpire':\r\n self.lblTxtCardExpire.setText(text)\r\n elif wdt.objectName() == 'cardCode':\r\n self.lblTxtCardCode.setText(text)\r\n elif wdt.objectName() == 'giftMsg':\r\n self.teTxtGiftMsg.setText(text)\r\n elif wdt.objectName() == 'specInst':\r\n self.teTxtSpecInst.setText(text)\r\n elif wdt.objectName() == 'ditto':\r\n if wdt.isChecked() == True:\r\n self.lblTxtShipSame.setText('*Shipping name and address same as billing.')\r\n self.lblTxtShipSame.show()\r\n self.gbShipInfo.hide()\r\n self.gbShippingInfo.setEnabled(False)\r\n else:\r\n self.lblTxtShipSame.hide()\r\n self.gbShipInfo.show()\r\n self.gbShippingInfo.setEnabled(True)\r\n if self.leFirstName.text() == '':\r\n self.gbCustInfo.hide()\r\n self.gbShipInfo.hide()\r\n self.gbPayInfo.hide()\r\n self.gbPayInfo.hide()\r\n\r\n\r\n #if the shipping and the billing addresses are the same.\r\n if self.chkDitto.isChecked() == False:\r\n if wdt.objectName() == 'shipFn':\r\n self.lblTxtShipFn.setText(text)\r\n elif wdt.objectName() == 'shipLn':\r\n self.lblTxtShipLn.setText(text)\r\n elif wdt.objectName() == 'shipCompany':\r\n self.lblTxtShipCompany.setText(text)\r\n elif wdt.objectName() == 'shipAdd1':\r\n self.lblTxtShipAdd1.setText(text)\r\n elif wdt.objectName() == 'shipAdd2':\r\n self.lblTxtShipAdd2.setText(text)\r\n elif wdt.objectName() == 'shipCity':\r\n self.lblTxtShipCity.setText(text + ',')\r\n elif wdt.objectName() == 'shipState':\r\n self.lblTxtShipState.setText(text)\r\n elif wdt.objectName() == 'shipZip':\r\n self.lblTxtShipZip.setText(text)\r\n elif wdt.objectName() == 'shipPhone':\r\n self.lblTxtShipPhone.setText(text)\r\n \r\n#################################################################################################################################################### \r\n###### class for garment tree ###################################################################################################################### \r\n####################################################################################################################################################\r\n \r\nclass GarmentTree(QTreeWidget):\r\n var1 = \"\"\r\n var2 = \"\"\r\n \r\n def __init__(self):\r\n super(GarmentTree, self).__init__() \r\n \r\n self.treeDock = QDockWidget(\"Order Items\", self)\r\n self.garmentTree = QTreeWidget(self.treeDock)\r\n self.garmentTree.setObjectName('garmentTree')\r\n self.garmentTree.itemClicked.connect(self.sumQuantity)\r\n self.garmentTree.itemClicked.connect(self.updateNameDesign)\r\n self.garmentTree.setMaximumWidth(490)\r\n self.garmentTree.setMinimumWidth(490) \r\n \r\n def loadGarmentInfo(self,sku_code,garment_type,garment_name):\r\n\r\n #print(garment_type)\r\n #Query the database to get all garments available for this particular SKU. \r\n garm = mysql_db.garment_info(self, sku_code, garment_type)\r\n columnList = [\"Design\", \"Size\",\"Price\", \"Qty\",\"\", \"\"]\r\n \r\n #Set tree header/title stuff\r\n self.garmentTree.setHeaderLabels(columnList)\r\n self.garmentTree.setColumnCount(6)\r\n self.garmentTree.header().resizeSection(0, 280)\r\n self.garmentTree.header().resizeSection(1, 75)\r\n self.garmentTree.header().resizeSection(2, 45)\r\n self.garmentTree.header().resizeSection(3, 30)\r\n self.garmentTree.header().resizeSection(4, 30)\r\n self.garmentTree.header().resizeSection(5, 30)\r\n \r\n \r\n #If there are no nodes in this tree yet, create the first one\r\n if self.garmentTree.topLevelItemCount() == 0:\r\n #print(\"NEW PARENT NODE\")\r\n self.lblTotal = {}\r\n nm = QTreeWidgetItem(self.garmentTree)\r\n nm.setText(0, self.orderVars)\r\n nm.setToolTip(0, self.orderVars)\r\n nm.setBackground(0, QColor(180,180,180,127))\r\n nm.setBackground(1, QColor(180,180,180,127))\r\n nm.setBackground(2, QColor(180,180,180,127))\r\n nm.setBackground(3, QColor(180,180,180,127))\r\n nm.setBackground(4, QColor(180,180,180,127))\r\n nm.setBackground(5, QColor(180,180,180,127))\r\n nm.setFont(0, QFont(\"Helvetica\",16,QFont.Bold))\r\n \r\n sku = QTreeWidgetItem(nm)\r\n sku.setText(0, sku_code)\r\n sku.setBackground(0, QColor(180,180,180,127))\r\n sku.setBackground(1, QColor(180,180,180,127))\r\n sku.setBackground(2, QColor(180,180,180,127))\r\n sku.setBackground(3, QColor(180,180,180,127))\r\n sku.setBackground(4, QColor(180,180,180,127))\r\n sku.setBackground(5, QColor(180,180,180,127))\r\n sku.setFont(0, QFont(\"Helvetica\",12,QFont.Bold))\r\n \r\n #If the garment name does not exist we want to create a node for it. \r\n garmName = QTreeWidgetItem(sku)\r\n garmName.setText(0, garment_name)\r\n garmName.setText(3, \"\")\r\n garmName.setFont(0,QFont(\"Helvetica\",10,QFont.Bold))\r\n garmName.setFont(3,QFont(\"Helvetica\",10,QFont.Bold))\r\n garmName.setBackground(0, QColor(230,230,230,127))\r\n garmName.setBackground(1, QColor(230,230,230,127))\r\n garmName.setBackground(2, QColor(230,230,230,127))\r\n garmName.setBackground(3, QColor(230,230,230,127))\r\n garmName.setBackground(4, QColor(230,230,230,127))\r\n garmName.setBackground(5, QColor(230,230,230,127))\r\n \r\n removeName = QToolButton(self)\r\n removeName.setIcon(QIcon(\"Icon/close-widget.png\"))\r\n removeName.setIconSize(QSize(14,14))\r\n removeName.setAutoRaise(True)\r\n removeName.clicked.connect(self.removeTreeItem)\r\n \r\n removeSku = QToolButton(self)\r\n removeSku.setIcon(QIcon(\"icon/close-widget.png\"))\r\n removeSku.setIconSize(QSize(14, 14))\r\n removeSku.setAutoRaise(True)\r\n removeSku.clicked.connect(self.removeTreeItem)\r\n \r\n removeGarment = QToolButton(self)\r\n removeGarment.setIcon(QIcon(\"icon/close-widget.png\"))\r\n removeGarment.setIconSize(QSize(14, 14))\r\n removeGarment.setAutoRaise(True)\r\n removeGarment.clicked.connect(self.removeTreeItem)\r\n \r\n editName = QToolButton(self)\r\n editName.setIcon(QIcon(\"icon/undo.png\"))\r\n editName.setIconSize(QSize(14, 14))\r\n editName.setAutoRaise(True)\r\n editName.clicked.connect(self.editTreeName)\r\n \r\n editSku = QToolButton(self)\r\n editSku.setIcon(QIcon(\"icon/undo.png\"))\r\n editSku.setIconSize(QSize(14, 14))\r\n editSku.setAutoRaise(True)\r\n editSku.clicked.connect(self.editTreeSku) \r\n\r\n self.lblTotal[str(sku_code + garment_name)] = QLabel()\r\n self.lblTotal[str(sku_code + garment_name)].setMaximumWidth(30)\r\n self.lblTotal[str(sku_code + garment_name)].setFont(QFont(\"Helvetica\",10,QFont.Bold))\r\n \r\n self.garmentTree.setItemWidget(nm, 4, removeName)\r\n self.garmentTree.setItemWidget(sku, 4, removeSku)\r\n self.garmentTree.setItemWidget(garmName, 4, removeGarment) \r\n self.garmentTree.setItemWidget(garmName, 3, self.lblTotal[str(sku_code + garment_name)])\r\n self.garmentTree.setItemWidget(nm, 5, editName)\r\n self.garmentTree.setItemWidget(sku, 5, editSku)\r\n \r\n self.le = {}\r\n #Create all the garment types for the first node\r\n for i in garm:\r\n kiddo = QTreeWidgetItem(garmName)\r\n kiddo.setText(0, i[1])\r\n kiddo.setText(2, str(i[3]))\r\n kiddo.setText(1, i[2])\r\n kiddo.setText(3,\"\")\r\n kiddo.setFont(3, QFont(\"Helvetica\",10,QFont.Bold) )\r\n kiddo.setText(4,\"-\")\r\n \r\n nm.setExpanded(True)\r\n sku.setExpanded(True)\r\n garmName.setExpanded(True)\r\n kiddo.setExpanded(True)\r\n \r\n #If items already exist in the tree, do stuff depending on what sku/garment was clicked.\r\n else: \r\n name_match = 0\r\n sku_match = 0 \r\n itSku = QTreeWidgetItemIterator(self.garmentTree) \r\n\r\n #iterate through all tree items and see if anything matches the SKU we selected. \r\n while itSku.value():\r\n if itSku.value().text(0) == self.orderVars:\r\n name_match = 1\r\n #print(\"NAME MATCHED!!!\")\r\n #If the SKU we selected exists somewhere in the tree, set variable to indicate that.\r\n if itSku.value().text(0) == sku_code and itSku.value().parent().text(0) == self.orderVars:\r\n sku_match = 1\r\n #print(\"SKU MATCHED!!!\")\r\n #Collapse all non-parent nodes so we can selectively open the nodes we are currently working on below.\r\n if itSku.value().parent() != None: \r\n itSku.value().setExpanded(False)\r\n itSku += 1\r\n\r\n if name_match == 1:\r\n #print(\"NAME MATCHED!!!!!!!!\")\r\n #if the SKU we've selected already exists in the tree, check to see if the garment we've selected exists also \r\n if sku_match == 1:\r\n #print(\"SKU MATCHED!!!\")\r\n garm_match = 0\r\n #print(\"already\", sku_code)\r\n #Create an iterator to iterate through all the elements in the tree.\r\n itGarment = QTreeWidgetItemIterator(self.garmentTree)\r\n #Open up iterator\r\n while itGarment.value():\r\n #If BOTH the SKU and garment already exist in the tree, just expand it while collapsing all other items.\r\n if itGarment.value().text(0) == garment_name and itGarment.value().parent().text(0) == sku_code and itGarment.value().parent().parent().text(0) == self.orderVars:\r\n #itGarment.value().parent().setExpanded(True)\r\n #itGarment.value().setExpanded(True)\r\n garm_match = 1\r\n itGarment.value().parent().parent().setExpanded(True)\r\n itGarment.value().parent().setExpanded(True)\r\n itGarment.value().setExpanded(True)\r\n \r\n itGarment += 1\r\n \r\n \r\n #If the selected garment does NOT exist in the tree for this SKU, create it.\r\n if garm_match == 0:\r\n #create tree iterator\r\n itSizes = QTreeWidgetItemIterator(self.garmentTree)\r\n while itSizes.value():\r\n #When the iterator hits the correct SKU, create the new garment node that doesn't exist yet. \r\n if itSizes.value().text(0) == sku_code and itSizes.value().parent().text(0) == self.orderVars:\r\n #If the garment name does not exist we want to create a node for it. \r\n garmName = QTreeWidgetItem(itSizes.value())\r\n garmName.setText(0, garment_name)\r\n garmName.setText(3, \"\")\r\n garmName.setFont(0,QFont(\"Helvetica\",10,QFont.Bold))\r\n garmName.setFont(3,QFont(\"Helvetica\",10,QFont.Bold))\r\n \r\n \r\n garmName.setBackground(0, QColor(230,230,230,127))\r\n garmName.setBackground(1, QColor(230,230,230,127))\r\n garmName.setBackground(2, QColor(230,230,230,127))\r\n garmName.setBackground(3, QColor(230,230,230,127))\r\n garmName.setBackground(4, QColor(230,230,230,127))\r\n garmName.setBackground(5, QColor(230,230,230,127))\r\n \r\n removeGarment = QToolButton(self)\r\n removeGarment.setIcon(QIcon(\"icon/close-widget.png\"))\r\n removeGarment.setIconSize(QSize(14, 14))\r\n removeGarment.setAutoRaise(True)\r\n removeGarment.clicked.connect(self.removeTreeItem)\r\n \r\n self.lblTotal[str(sku_code + garment_name)] = QLabel(self.garmentTree)\r\n self.lblTotal[str(sku_code + garment_name)].setMaximumWidth(30)\r\n self.lblTotal[str(sku_code + garment_name)].setFont(QFont(\"Helvetica\",10,QFont.Bold))\r\n \r\n self.garmentTree.setItemWidget(garmName, 4, removeGarment)\r\n self.garmentTree.setItemWidget(garmName, 3, self.lblTotal[str(sku_code + garment_name)])\r\n #Create all the garment types for the node\r\n #self.le = {}\r\n for i in garm:\r\n kiddo = QTreeWidgetItem(garmName)\r\n kiddo.setText(0, i[1])\r\n kiddo.setText(2, str(i[3]))\r\n kiddo.setText(1, i[2])\r\n kiddo.setText(3,\"\")\r\n kiddo.setFont(3, QFont(\"Helvetica\",10,QFont.Bold) )\r\n kiddo.setText(4,\"-\")\r\n itSizes.value().setExpanded(True)\r\n garmName.setExpanded(True)\r\n kiddo.setExpanded(True)\r\n itSizes += 1 \r\n \r\n \r\n \r\n \r\n #If the SKU does NOT exist in the tree yet, but others already do, create this particular SKU.\r\n else:\r\n #print(\"SAME NAME, DIFFERENT SKU!!!!! SKU = \" + sku_code + \" -- Name = \" + self.orderVars) \r\n \r\n iterNewSku = QTreeWidgetItemIterator(self.garmentTree) \r\n \r\n while iterNewSku.value():\r\n \r\n if iterNewSku.value().childCount() > 0:\r\n if iterNewSku.value().text(0) == self.orderVars:\r\n \r\n sku = QTreeWidgetItem(iterNewSku.value()) \r\n sku.setText(0, sku_code)\r\n sku.setBackground(0, QColor(180,180,180,127))\r\n sku.setBackground(1, QColor(180,180,180,127))\r\n sku.setBackground(2, QColor(180,180,180,127))\r\n sku.setBackground(3, QColor(180,180,180,127))\r\n sku.setBackground(4, QColor(180,180,180,127))\r\n sku.setBackground(5, QColor(180,180,180,127))\r\n sku.setFont(0, QFont(\"Helvetica\",12,QFont.Bold) )\r\n \r\n garmName = QTreeWidgetItem(sku)\r\n garmName.setText(0, garment_name)\r\n garmName.setText(3, \"\")\r\n garmName.setFont(0,QFont(\"Helvetica\",10,QFont.Bold))\r\n garmName.setFont(3,QFont(\"Helvetica\",10,QFont.Bold))\r\n garmName.setBackground(0, QColor(230,230,230,127))\r\n garmName.setBackground(1, QColor(230,230,230,127))\r\n garmName.setBackground(2, QColor(230,230,230,127))\r\n garmName.setBackground(3, QColor(230,230,230,127))\r\n garmName.setBackground(4, QColor(230,230,230,127))\r\n garmName.setBackground(5, QColor(230,230,230,127)) \r\n\r\n removeSku = QToolButton(self)\r\n removeSku.setIcon(QIcon(\"icon/close-widget.png\"))\r\n removeSku.setIconSize(QSize(14, 14))\r\n removeSku.setAutoRaise(True)\r\n removeSku.clicked.connect(self.removeTreeItem)\r\n \r\n removeGarment = QToolButton(self)\r\n removeGarment.setIcon(QIcon(\"icon/close-widget.png\"))\r\n removeGarment.setIconSize(QSize(14, 14))\r\n removeGarment.setAutoRaise(True)\r\n removeGarment.clicked.connect(self.removeTreeItem)\r\n \r\n editSku = QToolButton(self)\r\n editSku.setIcon(QIcon(\"icon/undo.png\"))\r\n editSku.setIconSize(QSize(14, 14))\r\n editSku.setAutoRaise(True)\r\n editSku.clicked.connect(self.editTreeSku) \r\n \r\n self.lblTotal[str(sku_code + garment_name)] = QLabel(self.garmentTree)\r\n self.lblTotal[str(sku_code + garment_name)].setMaximumWidth(30)\r\n self.lblTotal[str(sku_code + garment_name)].setFont(QFont(\"Helvetica\",10,QFont.Bold))\r\n \r\n self.garmentTree.setItemWidget(sku, 4, removeSku)\r\n self.garmentTree.setItemWidget(sku, 5, editSku)\r\n self.garmentTree.setItemWidget(garmName, 4, removeGarment) \r\n self.garmentTree.setItemWidget(garmName, 3, self.lblTotal[str(sku_code + garment_name)])\r\n #self.le = {}\r\n #Create all the garment types for the first node\r\n for i in garm:\r\n kiddo = QTreeWidgetItem(garmName)\r\n kiddo.setText(0, i[1])\r\n kiddo.setText(2, str(i[3]))\r\n kiddo.setText(1, i[2])\r\n kiddo.setText(3,\"\")\r\n kiddo.setFont(3, QFont(\"Helvetica\",10,QFont.Bold))\r\n kiddo.setText(4,\"-\")\r\n #nm.setExpanded(True)\r\n sku.setExpanded(True)\r\n garmName.setExpanded(True)\r\n kiddo.setExpanded(True)\r\n \r\n iterNewSku += 1\r\n\r\n \r\n else:\r\n #print(\"NEW NAME\")\r\n\r\n self.lblTotal = {}\r\n nm = QTreeWidgetItem(self.garmentTree)\r\n nm.setText(0, self.orderVars)\r\n nm.setToolTip(0, self.orderVars)\r\n nm.setBackground(0, QColor(180,180,180,127))\r\n nm.setBackground(1, QColor(180,180,180,127))\r\n nm.setBackground(2, QColor(180,180,180,127))\r\n nm.setBackground(3, QColor(180,180,180,127))\r\n nm.setBackground(4, QColor(180,180,180,127))\r\n nm.setBackground(5, QColor(180,180,180,127))\r\n nm.setFont(0, QFont(\"Helvetica\",16,QFont.Bold))\r\n \r\n sku = QTreeWidgetItem(nm)\r\n sku.setText(0, sku_code)\r\n sku.setBackground(0, QColor(180,180,180,127))\r\n sku.setBackground(1, QColor(180,180,180,127))\r\n sku.setBackground(2, QColor(180,180,180,127))\r\n sku.setBackground(3, QColor(180,180,180,127))\r\n sku.setBackground(4, QColor(180,180,180,127))\r\n sku.setBackground(5, QColor(180,180,180,127))\r\n sku.setFont(0, QFont(\"Helvetica\",12,QFont.Bold))\r\n \r\n \r\n #If the garment name does not exist we want to create a node for it. \r\n garmName = QTreeWidgetItem(sku)\r\n garmName.setText(0, garment_name)\r\n garmName.setText(3, \"\")\r\n garmName.setFont(0,QFont(\"Helvetica\",10,QFont.Bold))\r\n garmName.setFont(3,QFont(\"Helvetica\",10,QFont.Bold))\r\n garmName.setBackground(0, QColor(230,230,230,127))\r\n garmName.setBackground(1, QColor(230,230,230,127))\r\n garmName.setBackground(2, QColor(230,230,230,127))\r\n garmName.setBackground(3, QColor(230,230,230,127))\r\n garmName.setBackground(4, QColor(230,230,230,127))\r\n garmName.setBackground(5, QColor(230,230,230,127))\r\n \r\n removeName = QToolButton(self)\r\n removeName.setIcon(QIcon(\"Icon/close-widget.png\"))\r\n removeName.setIconSize(QSize(14,14))\r\n removeName.setAutoRaise(True)\r\n removeName.clicked.connect(self.removeTreeItem) \r\n \r\n removeSku = QToolButton(self)\r\n removeSku.setIcon(QIcon(\"icon/close-widget.png\"))\r\n removeSku.setIconSize(QSize(14, 14))\r\n removeSku.setAutoRaise(True)\r\n removeSku.clicked.connect(self.removeTreeItem)\r\n \r\n removeGarment = QToolButton(self)\r\n removeGarment.setIcon(QIcon(\"icon/close-widget.png\"))\r\n removeGarment.setIconSize(QSize(14, 14))\r\n removeGarment.setAutoRaise(True)\r\n removeGarment.clicked.connect(self.removeTreeItem)\r\n \r\n editName = QToolButton(self)\r\n editName.setIcon(QIcon(\"icon/undo.png\"))\r\n editName.setIconSize(QSize(14, 14))\r\n editName.setAutoRaise(True)\r\n editName.clicked.connect(self.editTreeName)\r\n \r\n editSku = QToolButton(self)\r\n editSku.setIcon(QIcon(\"icon/undo.png\"))\r\n editSku.setIconSize(QSize(14, 14))\r\n editSku.setAutoRaise(True)\r\n editSku.clicked.connect(self.editTreeSku) \r\n \r\n self.lblTotal[str(sku_code + garment_name)] = QLabel()\r\n self.lblTotal[str(sku_code + garment_name)].setMaximumWidth(30)\r\n self.lblTotal[str(sku_code + garment_name)].setFont(QFont(\"Helvetica\",10,QFont.Bold))\r\n \r\n self.garmentTree.setItemWidget(nm, 4, removeName)\r\n self.garmentTree.setItemWidget(sku, 4, removeSku)\r\n self.garmentTree.setItemWidget(nm, 5, editName)\r\n self.garmentTree.setItemWidget(sku, 5, editSku)\r\n self.garmentTree.setItemWidget(garmName, 4, removeGarment) \r\n self.garmentTree.setItemWidget(garmName, 3, self.lblTotal[str(sku_code + garment_name)])\r\n self.le = {}\r\n #Create all the garment types for the first node\r\n for i in garm:\r\n kiddo = QTreeWidgetItem(garmName)\r\n kiddo.setText(0, i[1])\r\n kiddo.setText(2, str(i[3]))\r\n kiddo.setText(1, i[2])\r\n kiddo.setText(3,\"\")\r\n kiddo.setFont(3, QFont(\"Helvetica\",10,QFont.Bold) )\r\n kiddo.setText(4,\"-\")\r\n \r\n nm.setExpanded(True)\r\n sku.setExpanded(True)\r\n garmName.setExpanded(True)\r\n kiddo.setExpanded(True)\r\n #print(le.objectName())\r\n \r\n \r\n self.treeDock.show()\r\n mainWin.viewMenu.addAction(self.treeDock.toggleViewAction()) \r\n \r\n self.treeDock.setWidget(self.garmentTree)\r\n mainWin.addDockWidget(Qt.RightDockWidgetArea, self.treeDock)\r\n \r\n def editTreeSku(self):\r\n #EditTreeSku.editTreeSku(self)\r\n btn = self.sender()\r\n btn.setFocus()\r\n \r\n selItems = self.garmentTree.selectedItems()\r\n \r\n ets = EditTreeSku()\r\n ets.getAlternateSkus(selItems)\r\n ets.show()\r\n mainWin.setEnabled(False)\r\n \r\n def editTreeName(self):\r\n #If a customer wants to change the name or place during ordering.\r\n \r\n #Grabs the item that was clicked in the tree and set focus to it to be double sure we get the correct values\r\n btn = self.sender()\r\n btn.setFocus()\r\n \r\n #loop through the items in the row selected in the tree and grab the information we need.\r\n for item in self.garmentTree.selectedItems():\r\n name = item.text(0)\r\n sku = item.child(0).text(0)\r\n \r\n #go get the type of variables that go on the shirt.\r\n self.var1 = mysql_db.get_first_var(self, sku)\r\n self.var2 = mysql_db.get_second_var(self, sku)\r\n \r\n #Get the name the customer wants to change to.\r\n inVar1, ok = QInputDialog.getText(self, \"Enter \"+self.var1, \"Please enter \"+self.var1+\":\")\r\n if ok and inVar1:\r\n newName = inVar1\r\n #set the tree to the new name.\r\n item.setText(0, newName)\r\n #reset the order variables for the order.\r\n self.orderVars = newName\r\n #if the name had a second variable we need to get that too.\r\n if name.find('::', 0, len(name)) > 0:\r\n #ask for the second variable.\r\n inVar2, ok = QInputDialog.getText(self, \"Enter \"+self.var2, \"Please enter \"+self.var2+\":\")\r\n if ok and inVar2:\r\n #reset the order variables with the second variable.\r\n self.orderVars = newName + ' :: ' + inVar2\r\n #reset the name in the tree.\r\n item.setText(0, self.orderVars)\r\n mainWin.updateOrderDetails()\r\n\r\n def removeTreeItem(self):\r\n #This is for removing items as cleaning and efficiently as possible for the CSR's.\r\n btn = self.sender()\r\n btn.setFocus()\r\n root = self.garmentTree.invisibleRootItem()\r\n\r\n for item in self.garmentTree.selectedItems():\r\n #if the item has a parent keep moving.\r\n if item.parent():\r\n #sku level, if the item's parent does not have a parent\r\n if not item.parent().parent():\r\n itemParent = item.parent()\r\n #if the item being deleted is the only child left to the parent then we want to remove the parent as well.\r\n if itemParent.childCount() == 1:\r\n (item.parent() or root).removeChild(item)\r\n (item.parent() or root).removeChild(itemParent)\r\n #if there are other children with the item that is being deleted we only want to delete the item.\r\n else:\r\n (item.parent() or root).removeChild(item)\r\n #if the items parent has a parent then we are dealing with garment styles (ie. T-shirts)\r\n else:\r\n itemParent = item.parent()\r\n if itemParent.childCount() == 1:\r\n if itemParent.parent().childCount() == 1:\r\n (itemParent.parent().parent() or root).removeChild(itemParent.parent())\r\n else:\r\n (item.parent() or root).removeChild(item)\r\n (itemParent.parent() or root).removeChild(itemParent)\r\n else:\r\n (item.parent() or root).removeChild(item)\r\n #get rid of everything. \r\n else:\r\n (item.parent() or root).removeChild(item)\r\n \r\n #mainWin.updateOrderDetails()\r\n self.updateRemovedVars()\r\n \r\n def updateRemovedVars(self):\r\n #This is for updating the tree variables the best possible way so that the CSR's can keep moving.\r\n #Open another iterator.\r\n itVars = QTreeWidgetItemIterator(mainWin.gt.garmentTree)\r\n #variable to hold the new variables if needed.\r\n oldVars = None \r\n treeVars = None\r\n skuCode = None\r\n if mainWin.gt.garmentTree:\r\n while itVars.value():\r\n #if the orderVars of the last edited item are still in the tree we want to keep those..\r\n if itVars.value().text(0) == self.orderVars:\r\n oldVars = itVars.value().text(0)\r\n #next we want to get the sku value of the item that was selected.\r\n skuCode = itVars.value().child(itVars.value().childCount() - 1).text(0)\r\n for item in self.garmentTree.selectedItems():\r\n if item:\r\n #order variable level\r\n if not item.parent():\r\n skuCode = item.child(0).text(0)\r\n #sku level\r\n elif not item.parent().parent():\r\n skuCode = item.text(0)\r\n #garment level\r\n else:\r\n skuCode = item.parent().text(0)\r\n #if the orderVars are not in the tree anymore we need new ones.\r\n if itVars.value().text(0) != self.orderVars:\r\n #grabs parents as we are iterating through\r\n parent = itVars.value().parent()\r\n #if the parent does not have a parent then we have our order variables \r\n if not parent:\r\n # this will hold the last item needed for the order variables\r\n treeVars = itVars.value().text(0)\r\n skuCode = itVars.value().child(itVars.value().childCount() - 1).text(0)\r\n itVars += 1\r\n\r\n #if the variables haven't been assigned yet, it means they aren't in the tree\r\n if oldVars:\r\n self.orderVars = oldVars\r\n elif treeVars:\r\n self.orderVars = treeVars\r\n \r\n if self.orderVars:\r\n if self.orderVars.find('::', 0, len(self.orderVars)) > 0:\r\n #split them up in case there are more than one so we can set the labels.\r\n varis = self.orderVars.split(' :: ')\r\n #set our labels\r\n mainWin.lblTxtVar1.setText(varis[0])\r\n mainWin.lblTxtVar2.setText(varis[1])\r\n #get the second variable type for the variables(ie place, name, etc...)\r\n self.var2 = mysql_db.get_second_var(self, skuCode)\r\n #set the text label for the second variable\r\n mainWin.lblVar2.setText(self.var2)\r\n else:\r\n #otherwise we can just set the variable.\r\n mainWin.lblTxtVar1.setText(self.orderVars)\r\n mainWin.lblTxtVar2.setText(None)\r\n mainWin.lblVar2.setText(None)\r\n\r\n if skuCode:\r\n #get the variable type for the first variable(ie place, name, etc...)\r\n self.var1 = mysql_db.get_first_var(self, skuCode)\r\n #set the text label for the second variable\r\n mainWin.lblVar1.setText(self.var1)\r\n #set the sku label\r\n mainWin.lblSkuName.setText(skuCode) \r\n #load that design\r\n mainWin.loadDesignItem(skuCode) \r\n else:\r\n pass\r\n \r\n def sumQuantity(self, item, column):\r\n if item.text(column) and item.childCount() == 0 and item.parent() != None:\r\n #If this row has no Quantity yet, set it to zero.\r\n if item.text(3) == \"\":\r\n newNum = 0\r\n else:\r\n newNum = int(item.text(3))\r\n if item.parent().text(3) == \"\":\r\n newSum = 0\r\n else:\r\n newSum = int(item.parent().text(3))\r\n \r\n #If user clicks on the \"-\" sign in column 4, subtract 1\r\n if column == 4:\r\n if newNum > 0:\r\n newNum = newNum - 1\r\n if newSum > 0: \r\n newSum = newSum - 1\r\n \r\n #else if the user clicks anywhere BUT column 4, add number \r\n else:\r\n newNum = newNum + 1 \r\n newSum = newSum + 1\r\n\r\n #prepare the numbers for output \r\n if newNum == 0:\r\n newNum = \"\"\r\n else:\r\n newNum = str(newNum)\r\n \r\n if newSum == 0:\r\n newSum = \"\"\r\n else:\r\n newSum = str(newSum)\r\n #Output \r\n item.parent().setText(3,newSum)\r\n item.setText(3,newNum)\r\n \r\n def updateNameDesign(self, item):\r\n treeName = self.sender()\r\n \r\n if str(treeName.objectName()) == 'garmentTree':\r\n #If top level (Name) node is selected.\r\n if treeName.currentItem().parent() == None:\r\n var = treeName.currentItem().text(0)\r\n if var.find('::', 0, len(var)) > 0:\r\n var = var.split(' :: ')\r\n mainWin.lblTxtVar1.setText(var[0])\r\n mainWin.lblTxtVar2.setText(var[1])\r\n else: \r\n mainWin.lblTxtVar1.setText(var)\r\n mainWin.lblVar2.setText(None)\r\n mainWin.lblTxtVar2.setText(None)\r\n skuCode = treeName.currentItem().child(0).text(0)\r\n self.orderVars = (treeName.currentItem().text(0))\r\n #Fourth tree node selected (sizes)\r\n elif treeName.currentItem().child(0) == None:\r\n var = treeName.currentItem().parent().parent().parent().text(0)\r\n if var.find('::', 0, len(var)) > 0:\r\n var = var.split(' :: ')\r\n mainWin.lblTxtVar1.setText(var[0]) \r\n mainWin.lblTxtVar2.setText(var[1])\r\n else:\r\n mainWin.lblTxtVar1.setText(var)\r\n mainWin.lblVar2.setText(None)\r\n mainWin.lblTxtVar2.setText(None) \r\n skuCode = treeName.currentItem().parent().parent().text(0)\r\n self.orderVars = (treeName.currentItem().parent().parent().parent().text(0)) \r\n #Second tree node is selected (Sku)\r\n elif treeName.currentItem().child(0).child(0) != None and treeName.currentItem().parent() != None:\r\n var = treeName.currentItem().parent().text(0)\r\n if var.find('::', 0, len(var)) > 0:\r\n var = var.split(' :: ')\r\n mainWin.lblTxtVar1.setText(var[0])\r\n mainWin.lblTxtVar2.setText(var[1])\r\n else:\r\n mainWin.lblTxtVar1.setText(var)\r\n mainWin.lblVar2.setText(None)\r\n mainWin.lblTxtVar2.setText(None) \r\n skuCode = treeName.currentItem().text(0)\r\n self.orderVars = (treeName.currentItem().parent().text(0))\r\n #Third tree node selected (garment, T-Shirts)\r\n elif treeName.currentItem().child(0) != None and treeName.currentItem().parent().parent() != None:\r\n var = treeName.currentItem().parent().parent().text(0)\r\n if var.find('::', 0, len(var)) > 0:\r\n var = var.split(' :: ')\r\n mainWin.lblTxtVar1.setText(var[0])\r\n mainWin.lblTxtVar2.setText(var[1])\r\n else:\r\n mainWin.lblTxtVar1.setText(var)\r\n mainWin.lblVar2.setText(None)\r\n mainWin.lblTxtVar2.setText(None) \r\n skuCode = treeName.currentItem().parent().text(0) \r\n self.orderVars = (treeName.currentItem().parent().parent().text(0))\r\n \r\n self.var1 = mysql_db.get_first_var(self, skuCode)\r\n self.var2 = mysql_db.get_second_var(self, skuCode) \r\n if self.var2:\r\n mainWin.lblVar2.setText(self.var2) \r\n \r\n mainWin.lblSkuName.setText(skuCode)\r\n mainWin.loadDesignItem(skuCode)\r\n \r\n def addVariables(self):\r\n sku_code = mainWin.lblSkuName.text()\r\n self.var1 = mysql_db.get_first_var(self, sku_code)\r\n self.var2 = mysql_db.get_second_var(self, sku_code)\r\n \r\n inVar1, ok = QInputDialog.getText(self, \"Enter \"+self.var1, \"Please enter \"+self.var1+\":\")\r\n if ok and inVar1:\r\n self.orderVars = inVar1\r\n mainWin.lblTxtVar1.setText(inVar1)\r\n mainWin.lblVar1.setText(self.var1)\r\n \r\n if self.var2:\r\n inVar2, ok = QInputDialog.getText(self, \"Enter \"+self.var2, \"Please enter \"+self.var2+\":\")\r\n if ok and inVar2:\r\n self.orderVars = self.orderVars +\" :: \"+ inVar2\r\n mainWin.lblTxtVar2.setText(inVar2)\r\n mainWin.lblVar2.setText(self.var2)\r\n \r\n def getCustomerName(self, sku_code = None):\r\n #Grabs the last var2 that was used.\r\n if self.var2 == None and mainWin.lblVar2.text() != None:\r\n self.var2 = mainWin.lblVar2.text()\r\n #var2 = mysql_db.get_second_var(self, sku_code)\r\n if not self.var1:\r\n var1 = mysql_db.get_first_var(self, sku_code)\r\n inVar1, ok = QInputDialog.getText(self, \"Enter \"+var1, \"Please Enter \"+var1+\":\")\r\n if ok:\r\n mainWin.lblVar1.setText(var1)\r\n mainWin.lblTxtVar1.setText(inVar1)\r\n self.orderVars = inVar1\r\n var2 = mysql_db.get_second_var(self, sku_code)\r\n if not var2:\r\n self.var2 = None\r\n mainWin.lblVar2.setText(None)\r\n mainWin.lblTxtVar2.setText(None)\r\n #self.orderVars = inVar1 \r\n else:\r\n inVar2, ok = QInputDialog.getText(self, \"Enter \"+var2, \"Please Enter \" +var2+ \":\")\r\n if ok:\r\n mainWin.lblVar2.setText(var2)\r\n mainWin.lblTxtVar2.setText(inVar2)\r\n self.var2 = inVar2\r\n self.orderVars = self.orderVars + \" :: \" + inVar2\r\n elif self.var1 and not self.var2:\r\n var2 = mysql_db.get_second_var(self, sku_code)\r\n if var2:\r\n inVar2, ok = QInputDialog.getText(self, \"Enter \"+var2, \"Please Enter \" +var2+ \":\")\r\n if ok:\r\n mainWin.lblVar2.setText(var2)\r\n mainWin.lblTxtVar2.setText(inVar2)\r\n self.var2 = inVar2\r\n self.orderVars = self.orderVars + \" :: \" + inVar2\r\n elif self.var1 and self.var2:\r\n var1 = mysql_db.get_first_var(self, sku_code)\r\n var2 = mysql_db.get_second_var(self, sku_code)\r\n if not var2:\r\n self.var2 = None\r\n mainWin.lblVar2.setText(None)\r\n mainWin.lblTxtVar2.setText(None)\r\n if mainWin.lblVar1.text() == var1: \r\n self.orderVars = mainWin.lblTxtVar1.text()\r\n else:\r\n inVar1, ok = QInputDialog.getText(self, \"Enter \"+var1+\":\", \"Please Enter \"+var1+\":\")\r\n if ok and inVar1:\r\n mainWin.lblVar1.setText(var1)\r\n mainWin.lblTxtVar1.setText(inVar1)\r\n self.orderVars = inVar1\r\n else:\r\n if mainWin.lblVar1.text() == var1: \r\n self.orderVars = mainWin.lblTxtVar1.text()\r\n else:\r\n inVar1, ok = QInputDialog.getText(self, \"Enter \"+var1+\":\", \"Please Enter \"+var1+\":\")\r\n if ok and inVar1:\r\n mainWin.lblVar1.setText(var1)\r\n mainWin.lblTxtVar1.setText(inVar1)\r\n self.orderVars = inVar1\r\n if mainWin.lblVar2.text() == var2:\r\n self.orderVars = self.orderVars + \" :: \" + mainWin.lblTxtVar2.text()\r\n else:\r\n inVar2, ok = QInputDialog.getText(self, \"Enter \"+var2+\":\", \"Please Enter \"+var2+\":\")\r\n if ok and inVar2:\r\n mainWin.lblVar2.setText(var2)\r\n mainWin.lblTxtVar2.setText(inVar2)\r\n self.orderVars = self.orderVars + \" :: \" + inVar2 \r\n\r\n#########################################################################################################################################################################\r\n### Class for widget pop up to change sku value in garment tree. ########################################################################################################\r\n######################################################################################################################################################################### \r\nclass EditTreeSku(QDialog):\r\n newSku = \"\"\r\n \r\n def __init__(self, parent=None):\r\n super(EditTreeSku, self).__init__(parent)\r\n \r\n self.createHeader()\r\n \r\n self.gt = GarmentTree()\r\n \r\n self.mainLayout = QVBoxLayout()\r\n self.mainLayout.addLayout(self.createHeader())\r\n \r\n self.setLayout(self.mainLayout)\r\n \r\n self.setWindowFlags(Qt.FramelessWindowHint)\r\n bgColor = QPalette()\r\n bgColor.setColor(self.backgroundRole(), Qt.gray)\r\n self.setPalette(bgColor)\r\n \r\n def createHeader(self):\r\n wht = QPalette()\r\n wht.setColor(wht.Foreground, Qt.white)\r\n \r\n lblTitle = QLabel(\"Change Color\")\r\n lblTitle.setFont(QFont(\"Times\", 12, QFont.Bold))\r\n lblTitle.setPalette(wht)\r\n \r\n btnClose = QToolButton()\r\n btnClose.setIcon(QIcon(\"icon\\close-widget.png\"))\r\n btnClose.setAutoRaise(True)\r\n btnClose.setIconSize(QSize(25,25))\r\n btnClose.setStyleSheet(\"QToolButton:hover {background-color: gray;}\")\r\n btnClose.clicked.connect(lambda: self.close())\r\n btnClose.clicked.connect(lambda: mainWin.setEnabled(True))\r\n \r\n hbHeader = QHBoxLayout()\r\n hbHeader.addWidget(lblTitle)\r\n hbHeader.addWidget(btnClose)\r\n hbHeader.setContentsMargins(0, 0, 0, 0)\r\n \r\n return hbHeader\r\n \r\n def getAlternateSkus(self, selItems):\r\n \r\n lsTree = []\r\n for item in selItems:\r\n #Get sku from tree to use when deleting\r\n selSku = item.text(0)\r\n #Get the variables from the tree for use later on (ie Name and Place).\r\n treeVars = item.parent().text(0)\r\n self.gt.orderVars = treeVars\r\n \r\n lsGarmName = []\r\n lsGarmQty = []\r\n for i in range(item.childCount()):\r\n #get a list of all garment types that have been added to the tree for the sku.\r\n lsGarmName.append(item.child(i).text(0))\r\n for j in range(item.child(i).childCount()):\r\n #get a list of all the garment names and sizes that have a quantity of more that one for each garment type\r\n if item.child(i).child(j).text(3) != \"\":\r\n lsTree.append(item.child(i).child(j).text(0) + \" \" + item.child(i).child(j).text(1))\r\n lsGarmQty.append([item.child(i).child(j).text(0) + \" \" + item.child(i).child(j).text(1), item.child(i).child(j).text(3)]) \r\n #get a list of all the skus that are associated with the sku that was selected. \r\n aSkus = mysql_db.get_assoc_skus(self, selSku)\r\n skus = aSkus.split(\":\")\r\n \r\n layout = QGridLayout()\r\n rbSkus = {}\r\n hbSkus = {}\r\n i = 0\r\n j = 0\r\n #loop through the list of skus and create buttons and a list of items not available for each associated sku.\r\n for sku in skus:\r\n #so we do see the sku that was selected in the dialog.\r\n if sku != item.text(0):\r\n \r\n rbSkus = QRadioButton(sku)\r\n rbSkus.toggled.connect(self.setSku)\r\n rbSkus.setFont(QFont(\"Times\", 10, QFont.Bold))\r\n \r\n #get the t-shirt image from the database\r\n img = mysql_db.get_tshirt_image_color(self, sku)\r\n #get color of the t-shirt\r\n col = img[1]\r\n \r\n pix = QLabel()\r\n smImg = QPixmap(\"//wampserver/\"+img[0])\r\n myScaledPixmap = smImg.scaled(75, 75, Qt.KeepAspectRatio)\r\n pix.setPixmap(myScaledPixmap)\r\n \r\n #text edit to display items that are not available in the sku that were in the selected sku.\r\n teNotAvail = QTextEdit()\r\n teNotAvail.setMaximumHeight(100)\r\n teNotAvail.setReadOnly(True)\r\n teNotAvail.setMaximumWidth(200)\r\n teNotAvail.insertHtml(\"<b><u>Not Available:</u></b><br/>\\n\")\r\n \r\n hbSkus[sku] = QHBoxLayout()\r\n hbSkus[sku].setObjectName(sku)\r\n\r\n vbImg = QVBoxLayout()\r\n vbImg.setObjectName(\"img\")\r\n vbImg.addWidget(QLabel())\r\n vbImg.addWidget(pix)\r\n vbImg.addWidget(rbSkus)\r\n vbImg.addStretch(1)\r\n \r\n lblColor = QLabel(col)\r\n lblColor.setFont(QFont(\"Times\", 10, QFont.Bold))\r\n \r\n vbNotAvail = QVBoxLayout()\r\n vbNotAvail.setObjectName('not avail')\r\n vbNotAvail.addWidget(lblColor)\r\n vbNotAvail.addWidget(teNotAvail)\r\n vbNotAvail.addStretch(1) \r\n \r\n lnColor = QPalette()\r\n lnColor.setColor(self.foregroundRole(), Qt.white)\r\n \r\n vline = QFrame()\r\n vline.setFrameShape(QFrame.VLine)\r\n vline.setLineWidth(4)\r\n vline.setPalette(lnColor)\r\n \r\n hbSkus[sku].addLayout(vbImg)\r\n hbSkus[sku].addLayout(vbNotAvail)\r\n hbSkus[sku].addWidget(vline)\r\n \r\n hline = QFrame()\r\n hline.setFrameShape(QFrame.HLine)\r\n hline.setPalette(lnColor)\r\n hline.setLineWidth(3)\r\n \r\n vbSkus = QVBoxLayout()\r\n vbSkus.setObjectName('vb sku')\r\n vbSkus.addWidget(hline)\r\n vbSkus.addLayout(hbSkus[sku])\r\n \r\n layout.addLayout(vbSkus, j, i)\r\n layout.setObjectName('layout')\r\n \r\n availSkus = mysql_db.get_garments_sizes(self, sku)\r\n for row in lsTree:\r\n if row not in availSkus:\r\n teNotAvail.insertPlainText(\" \" + row + \"\\n\")\r\n teNotAvail.moveCursor(QTextCursor.Start)\r\n \r\n if j == 3:\r\n i += 1\r\n j = 0\r\n else:\r\n j += 1\r\n \r\n self.mainLayout.addLayout(layout)\r\n \r\n btnLayout = QHBoxLayout()\r\n \r\n btnChangeSku = QPushButton('Change SKU')\r\n btnChangeSku.clicked.connect(lambda: self.changeSku(lsGarmName, lsGarmQty))\r\n btnChangeSku.clicked.connect(lambda: self.removeOldSku(selItems))\r\n btnLayout.addWidget(btnChangeSku)\r\n \r\n btnCancel = QPushButton('Cancel')\r\n btnCancel.clicked.connect(self.reject)\r\n btnCancel.clicked.connect(lambda: mainWin.setEnabled(True))\r\n btnLayout.addWidget(btnCancel)\r\n \r\n self.mainLayout.addLayout(btnLayout)\r\n\r\n def setSku(self):\r\n rbSku = self.sender()\r\n self.newSku = rbSku.text()\r\n\r\n def changeSku(self, garmName, garmQtys):\r\n #garmName = list of garment names that were loaded for the sku that is being changed.\r\n #garmQtys = list of lists of the qtys that were attached to each individual garments.\r\n \r\n #make sure a radio button was selected\r\n if not self.newSku:\r\n QMessageBox.information(self, \"Select SKU\", \"Please Select a SKU!\", QMessageBox.Ok)\r\n else:\r\n #get information of the design\r\n availGarmTypes = mysql_db.design_info(self, self.newSku)\r\n #create a list and fill it with only the garment types available for that design\r\n lsAvailTypes = []\r\n for garm in availGarmTypes:\r\n lsAvailTypes.append(garm[7])\r\n\r\n for name in garmName:\r\n #if the garment type is in the list keep going.\r\n if name in lsAvailTypes:\r\n #grabs the id for the garment name (i.e. T-Shirt)\r\n garmID = mysql_db.get_garment_type_id(self, name)\r\n #loads the tree garments for the new sku, based on what was in the tree\r\n mainWin.gt.loadGarmentInfo(self.newSku, str(garmID), name)\r\n #this will refresh the design buttons on the top so the sku's match up.\r\n mainWin.loadDesignItem(self.newSku)\r\n \r\n #Update new sku with the order quantities of the old sku\r\n itChange = QTreeWidgetItemIterator(mainWin.gt.garmentTree)\r\n #First open yet another iterator.\r\n while itChange.value(): \r\n #if the variables and the sku match...keep going.\r\n if itChange.value().text(0) == self.newSku and itChange.value().parent().text(0) == self.gt.orderVars:\r\n tot = 0\r\n #get a count of all of the garment types for the sku.\r\n for j in range(itChange.value().childCount()):\r\n #set item equal to the garment type (ie T-Shirts)\r\n item = itChange.value().child(j)\r\n #get a count of all the styles and sizes for the garment type.\r\n for k in range(item.childCount()):\r\n #for every style and size that had a quantity we want to add that quantity to the new sku that was added.\r\n for i in range(len(garmQtys)):\r\n #make sure the style and size match.\r\n if item.child(k).text(0) + \" \" + item.child(k).text(1) == garmQtys[i][0]:\r\n #if there is a match set the quantity on the new sku\r\n item.child(k).setText(3, garmQtys[i][1]) \r\n #finally keep a running total for each garment and add the total to the garment type itself.\r\n if int(garmQtys[i][1]) > 0:\r\n tot += int(garmQtys[i][1])\r\n item.setText(3, str(tot))\r\n tot = 0\r\n itChange += 1\r\n self.close()\r\n mainWin.setEnabled(True)\r\n \r\n def removeOldSku(self, selItems):\r\n #make sure a radio button was selected\r\n if self.newSku:\r\n root = mainWin.gt.garmentTree.invisibleRootItem()\r\n for item in selItems:\r\n (item.parent() or root).removeChild(item)\r\n \r\n #this will update the table with the new sku and proper values from the old sku.\r\n mainWin.updateOrderDetails()\r\n else: pass\r\n \r\n def mousePressEvent(self, event):\r\n #This is to be able to move the window around without a frame\r\n if event.button() == Qt.LeftButton:\r\n self.leftClick = True\r\n self.offset = event.pos()\r\n else:\r\n self.leftClick = False\r\n \r\n def mouseMoveEvent(self, event):\r\n #This is to be able to move the window around without a frame\r\n if self.leftClick == True:\r\n x=event.globalX()\r\n y=event.globalY()\r\n x_w = self.offset.x()\r\n y_w = self.offset.y()\r\n self.move(x-x_w, y-y_w)\r\n \r\n def mouseReleaseEvent(self, event): \r\n self.leftClick = False \r\n\r\n#########################################################################################################################################################################\r\n### Class for connecting, retrieving and setting data on MySql ##########################################################################################################\r\n#########################################################################################################################################################################\r\n \r\nclass mysql_db():\r\n def mysql_connect(self):\r\n try:\r\n mysql_db.conn = mysql.connector.connect(user = 'AI_APP', password = 'rowsby01', host = 'wampserver', database = 'inkpixi', raise_on_warnings = True) \r\n mysql_db.db = mysql_db.conn.cursor()\r\n except BaseException as e:\r\n QMessageBox.critical(self, 'Database Error', \"Can not connect to the MySQL database: \\n\" + str(e), QMessageBox.Ok)\r\n \r\n return mysql_db.db\r\n \r\n def sale_buttons(self):\r\n sb = mysql_db.mysql_connect(self)\r\n sb.execute(\"\"\"SELECT ic.inventories_name, ic.inventories_lines_sku, ic.inventories_image_url \r\n FROM inventories_cache ic \r\n WHERE ic.on_sale = 1 \r\n GROUP BY ic.inventories_lines_sku\"\"\")\r\n return sb.fetchall()\r\n \r\n \r\n def design_info(self, sku_code):\r\n di = mysql_db.mysql_connect(self)\r\n di.execute(\"\"\"\r\n SELECT ic.inventories_id,ic.inventories_name,ic.inventories_price, ic.inventories_lines_sku, i.inventories_code,i.inventories_name,i.inventories_color, \r\n it.inventories_types_name, it.inventories_types_id, ic.inventories_image_url, it.inventories_types_icon_url,it.inventories_types_icon_hover_url\r\n FROM inventories_cache ic \r\n LEFT JOIN inventories i on ic.inventories_id = i.inventories_id\r\n LEFT JOIN inventories_types it on ic.join_inventories_types_id = it.inventories_types_id\r\n WHERE ic.inventories_lines_sku = '\"\"\" + sku_code + \"\"\"'\r\n GROUP BY it.inventories_types_id\r\n ORDER BY it.inventories_types_id, i.inventories_name\r\n \"\"\")\r\n return di.fetchall()\r\n \r\n def get_tshirt_image_color(self, sku_code):\r\n gti = mysql_db.mysql_connect(self)\r\n gti.execute(\"\"\"\r\n SELECT ic.inventories_image_url, i.inventories_color\r\n FROM inventories_cache ic \r\n LEFT JOIN inventories i on ic.inventories_id = i.inventories_id\r\n LEFT JOIN inventories_types it on ic.join_inventories_types_id = it.inventories_types_id\r\n WHERE ic.inventories_lines_sku = '\"\"\"+ sku_code +\"\"\"'\r\n AND inventories_types_id = 1\r\n GROUP BY it.inventories_types_id\r\n ORDER BY it.inventories_types_id, i.inventories_name\r\n \"\"\")\r\n return gti.fetchone()\r\n\r\n\r\n def search_designs(self, searchTerm):\r\n sd = mysql_db.mysql_connect(self)\r\n sd.execute(\"\"\" \r\n SELECT ic.inventories_name, ic.inventories_lines_sku, ic.inventories_image_url \r\n FROM inventories_cache ic\r\n LEFT JOIN inventories_lines il on il.inventories_lines_id = ic.inventories_lines_id\r\n WHERE il.inventories_lines_search_keywords like '%\"\"\"+ searchTerm +\"\"\"%' \r\n GROUP BY il.inventories_lines_id\r\n ORDER BY ic.inventories_name, ic.inventories_lines_sku\r\n \"\"\")\r\n return sd.fetchall()\r\n\r\n\r\n def garment_info(self, sku_code, garment_type):\r\n gi = mysql_db.mysql_connect(self)\r\n gi.execute(\"\"\"\r\n SELECT inv.inventories_code,inv.inventories_name, io.inventories_options_name, ic.inventories_price, ic.inventories_name\r\n FROM `inventories` inv \r\n LEFT JOIN inventories_cache ic on ic.inventories_id = inv.inventories_id\r\n LEFT JOIN inventories_accessories ia on inventories_accessories_id = ic.inventories_global_accessories_ids\r\n LEFT JOIN inventories_options io on io.join_inventories_accessories_id = ia.inventories_accessories_id\r\n \r\n LEFT JOIN inventories_types it on it.inventories_types_id = inv.join_inventories_types_id\r\n WHERE ic.inventories_lines_sku = '\"\"\" + sku_code + \"\"\"' \r\n AND it.inventories_types_id = '\"\"\" + garment_type + \"\"\"'\r\n ORDER BY it.inventories_types_order,inv.inventories_code, ia.inventories_accessories_order, io.inventories_options_order\r\n \"\"\")\r\n return gi.fetchall() \r\n \r\n def get_second_var(self, sku_code):\r\n if sku_code:\r\n db = mysql_db.mysql_connect(self)\r\n db.execute(\"SELECT var_2_text FROM designs WHERE sku_code = '\"+sku_code+\"'\")\r\n ds = db.fetchone()\r\n \r\n sv = ds[0]\r\n \r\n return sv\r\n \r\n def get_first_var(self, sku_code):\r\n db = mysql_db.mysql_connect(self)\r\n db.execute(\"SELECT var_1_text FROM designs WHERE sku_code = '\"+sku_code+\"'\")\r\n ds = db.fetchone()\r\n \r\n fv = ds[0]\r\n \r\n return fv\r\n \r\n def get_assoc_skus(self, sku_code):\r\n db = mysql_db.mysql_connect(self)\r\n db.execute(\"SELECT sku_link FROM designs WHERE sku_code = '\"+sku_code+\"'\")\r\n ds = db.fetchone()\r\n \r\n return ds[0]\r\n \r\n def get_garments_sizes(self, sku_code):\r\n db = mysql_db.mysql_connect(self)\r\n #removed ic.inventories_lines_sku, \r\n db.execute(\"\"\"SELECT CONCAT(inv.inventories_name, ' ', io.inventories_options_name) garm_type_size\r\n FROM `inventories` inv \r\n LEFT JOIN inventories_cache ic on ic.inventories_id = inv.inventories_id\r\n LEFT JOIN inventories_accessories ia on inventories_accessories_id = ic.inventories_global_accessories_ids\r\n LEFT JOIN inventories_options io on io.join_inventories_accessories_id = ia.inventories_accessories_id\r\n LEFT JOIN inventories_types it on it.inventories_types_id = inv.join_inventories_types_id\r\n WHERE ic.inventories_lines_sku = '\"\"\"+sku_code+\"\"\"'\r\n ORDER BY it.inventories_types_order,inv.inventories_code, ia.inventories_accessories_order, io.inventories_options_order\"\"\")\r\n ds = db.fetchall()\r\n \r\n lst = []\r\n for row in ds:\r\n lst.append(row[0])\r\n \r\n return lst\r\n \r\n def get_garment_type_id(self, garmType):\r\n db = mysql_db.mysql_connect(self)\r\n db.execute(\"SELECT inventories_types_id FROM inventories_types WHERE inventories_types_name = '\"+ garmType +\"'\")\r\n ds = db.fetchone()\r\n return ds[0]\r\n\r\n#########################################################################################################################################################################\r\n### Class for connecting, retrieving and setting data on SQL Server #####################################################################################################\r\n#########################################################################################################################################################################\r\n\r\nclass mssql_db():\r\n def mssql_connect(self, db):\r\n try:\r\n mssql_db.conn = pyodbc.connect('DRIVER={SQL Server}; SERVER=SQLSERVER; DATABASE='+db+'; Trusted_Connection=yes')\r\n mssql_db.db = mssql_db.conn.cursor()\r\n except BaseException as e:\r\n QMessageBox.critical(self, 'Database Error', \"Cannot connect to the MS SQL Server: \\n\" + str(e), QMessageBox.Ok)\r\n return mssql_db.db \r\n \r\n def getStates(self):\r\n db = mssql_db.mssql_connect(self, \"ProblemSheets\")\r\n db.execute(\"SELECT stateAbbr FROM dbo.tblState\")\r\n ds = db.fetchall()\r\n states = []\r\n for i in ds:\r\n states.append(i[0])\r\n return states\r\n \r\n\r\nif __name__ == '__main__':\r\n\r\n app = QApplication(sys.argv)\r\n app.setStyle(\"Fusion\")\r\n mainWin = MainWindow()\r\n mainWin.show()\r\n sys.exit(app.exec_())\r\n","sub_path":"CSR Order GUI/csr_interface.py","file_name":"csr_interface.py","file_ext":"py","file_size_in_byte":110155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"169378645","text":"\nimport argparse\nimport data\nimport ind_model\nimport cPickle\n\nSEP_TEST = True\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('corpus', help = 'the name of the input corpus file')\n parser.add_argument('link', help = 'the name of the input link file')\n parser.add_argument('--seeds', help = 'percentage of seeds', type = float, default = 0)\n parser.add_argument('--learning_rate', help = 'learning rate', type = float, default = 0.1)\n parser.add_argument('--embedding_size', help = 'embedding dimensions', type = int, default = 50)\n parser.add_argument('--window_size', help = 'window size in random walk sequences', type = int, default = 3)\n parser.add_argument('--path_size', help = 'length of random walk sequences', type = int, default = 10)\n parser.add_argument('--batch_size', help = 'the size of batch for training instances', type = int, default = 200)\n parser.add_argument('--g_batch_size', help = 'the batch size for graph', type = int, default = 20)\n parser.add_argument('--g_learning_rate', help = \"the learning rate of graphs\", type = float, default = 1e-3)\n parser.add_argument('--neg_samp', type = int, default = 0)\n args = parser.parse_args()\n\n args.sep_test = SEP_TEST\n\n if 'pubmed' in args.link:\n x, y, tx, ty, allx, graph = data.gen_ind_pubmed_dataset(args.link, args.corpus, args.seeds, args.sep_test)\n else:\n x, y, tx, ty, allx, graph = data.gen_ind_dataset(args.link, args.corpus, args.seeds, args.sep_test)\n\n # OBJS = [x, y, tx, ty, allx, graph]\n # NAMES = ['x', 'y', 'tx', 'ty', 'allx', 'graph']\n # DATASET = 'pubmed'\n # if 'citeseer' in args.link:\n # DATASET = 'citeseer'\n # if 'cora' in args.link:\n # DATASET = 'cora'\n # # print 'saving {}'.format(DATASET)\n # for i in range(len(OBJS)):\n # cPickle.dump(OBJS[i], open('dump/ind.{}.{}'.format(DATASET, NAMES[i]), 'w'), cPickle.HIGHEST_PROTOCOL)\n quit()\n\n m = ind_model.model(args)\n m.add_data(x, y, tx, ty, allx, graph)\n m.build()\n m.train()\n","sub_path":"theano/ind_main.py","file_name":"ind_main.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"188551073","text":"import numpy as np\nimport pickle as pkl\nfrom random import shuffle, randint, sample\nimport matplotlib.pyplot as plt\nimport itertools\nfrom collections import deque\n\nfrom decisiontree import *\n\n# data : tableau (films ,features), \n# id2titles : dictionnaire id -> titre ,\n# fields : id feature -> nom\n[data , id2titles , fields ]= pickle.load(open(\"imdb_extrait.pkl\",\"rb\"))\n# la derniere colonne est le vote\n\n###############################################################\n\n#1.1\ndef entropie(vect):\n count = Counter(vect)\n prob = []\n for v in vect:\n prob.append( count[v] / len(vect) )\n H = -sum(prob[:] * np.log(prob[:]))\n return H\n\n#1.2\ndef entropie_cond(liste_vect):\n probP = []\n len_all_sublist = 0\n for v in liste_vect:\n len_all_sublist += v.size\n for v in liste_vect:\n probP.append( v.size / len_all_sublist )\n H = 0.0\n it = 0\n for v in liste_vect:\n H += probP[it] * entropie(v)\n it += 1\n return H\n\n\n#no problem with learning multiple times the same data. \n#shouldn't need labels.\n#TODO : optimization : shuffle and slice the vector instead\ndef divide_db(data_base, label_base, percentage):\n data = data_base.copy()\n labels = label_base.copy()\n size = len(data)\n size_l = np.floor(size * percentage)\n size_t = np.floor(size - size_l)\n \n \n #data = shuffle(data)\n learn_x = [] \n learn_y = []\n test_x = []\n test_y = []\n\n for i in range(np.asscalar((size_l).astype(int))):\n d = randint(0, size-1)\n learn_x.append( data[d] )\n learn_y.append( labels[d] )\n for i in range(np.asscalar((size_t).astype(int))):\n d = randint(0, size-1)\n test_x.append( data[d] )\n test_y.append( labels[d] ) \n\n learn_x = np.array(learn_x)\n learn_y = np.array(learn_y)\n test_x = np.array(test_x)\n test_y = np.array(test_y)\n\n return learn_x, learn_y, test_x, test_y\n\n\ndef get_score(learn_x, learn_y, test_x, test_y, depth):\n dt = DecisionTree ()\n \n sequence = range(1,depth)\n score_l = []\n score_t = []\n\n #learning\n for d in sequence:\n dt.max_depth = d\n dt.min_samples_split = 2 \n dt.fit(learn_x , learn_y)\n dt.predict(learn_x [:d ,:])\n\n score_l.append(1 - dt.score(learn_x , learn_y)) #dt.score = moyenne des bonne prédictions donc ==> 1 - dt.score = moyenne des mauvais prédictions \n\n #testing\n for d in sequence:\n dt.max_depth = d\n dt.min_samples_split = 2\n dt.fit(test_x , test_y)\n dt.predict(test_x [:d ,:])\n\n score_t.append(1 - dt.score(test_x , test_y))\n\n print(score_l, score_t)\n return score_l, score_t\n\n\ndef cross_init( datax, datay, nb_chunks):\n cross_data = datax.copy()\n cross_label = datay.copy()\n\n both = list( zip(cross_data, cross_label) )\n shuffle(both)\n\n cross_data, cross_label = zip(*both)\n\n cross_data = np.array_split(cross_data, nb_chunks)\n cross_label = np.array_split(cross_label, nb_chunks)\n\n return cross_data, cross_label\n\ndef cross_reference(datax, datay, nb_chunks, depth):\n cross_data, cross_label = cross_init(datax, datay, nb_chunks)\n #order = sample(range(nb_chunks), nb_chunks)\n order = deque( [i for i in range(nb_chunks)] ) \n\n learn_x = []\n learn_y = []\n test_x = []\n test_y = []\n\n score_learn = None\n score_test = None\n\n last_t = 1866 #valeur >1 quelconque\n last_l = 1866\n\n for all_comb in range(nb_chunks):\n subL_x = []\n subL_y = []\n subT_x = []\n subT_y = []\n for i in order:\n if( i == order[-1]):\n subT_x = list( cross_data[i] )\n subT_y = list( cross_label[i] )\n break\n subL_x = list( itertools.chain(subL_x, cross_data[i]) )\n subL_y = list( itertools.chain(subL_y, cross_label[i]) )\n\n order.rotate(1) #decalage vers la droite\n\n subL_x = np.array(subL_x)\n subL_y = np.array(subL_y)\n subT_x = np.array(subT_x)\n subT_y = np.array(subT_y)\n score_l, score_t = get_score(subL_x, subL_y, subT_x, subT_y, depth)\n\n learn_x.append( subL_x )\n learn_y.append( subL_y )\n test_x.append( subT_x )\n test_y.append( subT_y )\n\n #meilleures résultats\n if(score_t[-1] < last_t):\n score_test = score_t\n last_t = score_t[-1]\n if(score_l[-1] < last_l):\n score_learn = score_l\n last_l = score_l[-1]\n\n\n score_learn = np.array(score_learn)\n score_test = np.array( score_test )\n\n plt.plot(score_learn, label=\"Learn\")\n plt.plot(score_test, label=\"Test\")\n plt.savefig(\"cross_ref\")\n plt.gcf().clear()\n \n\n\n\n\n##################################################################################################\ndatax= data [: ,:32]\ndatay= np.array ([1 if x[33] >6.5 else -1 for x in data])\n\n#1.3\n\n# features = data.copy().T\n# entrop = []\n# for xi in features:\n# entrop.append(entropie(xi))\n# entrop_c = entropie_cond(features)\n# entrop = np.array(entrop)\n# # print(entrop)\n\n\n# y_pos = np.arange(len(entrop))\n# plt.bar(y_pos, entrop, align='center', alpha=1)\n# plt.xticks(y_pos, y_pos, rotation=70)\n# plt.ylabel('Feature')\n# plt.title('Entropy')\n# # plt.show()\n# plt.savefig(\"entropy\")\n# plt.gcf().clear()\n\n\n# entrop = entrop[:] - entrop_c\n# print(np.argmax(entrop))\n# print(entrop)\n# y_pos = np.arange(len(entrop))\n# plt.bar(y_pos, entrop, align='center', alpha=1)\n# plt.xticks(y_pos, y_pos, rotation=70)\n# plt.ylabel('Feature')\n# plt.title('Entropy minus conditionnal')\n# # plt.show()\n# plt.savefig(\"entropy_minus_conditionnal\")\n# plt.gcf().clear()\n\n\n\n\n# dt = DecisionTree ()\n# dt.max_depth = 60 #on fixe la taille de l’arbre a 5\n# dt.min_samples_split = 2 #nombre minimum d’exemples pour spliter un noeud\n# dt.fit(datax ,datay)\n# dt.predict(datax [:5 ,:])\n\n# print(dt.score(datax ,datay)) \n\n# dt.to_pdf(\"test_tree.pdf\",fields) # dessine l’arbre dans un fichier pdf si pydot est installe.\n# sinon utiliser http :// www.webgraphviz.com/dt.to_dot(fields)\n#ou dans la console\n# print(dt.print_tree(fields ))\n\n\n#1.4 : plus c'est profond, plus c'est long à calculer [je n'ai pas le visuel]\n# depth = 5 --> precision 0.73\n# depth = 6 --> precision 0.75\n# depth = 7 --> precision 0.77\n# depth = 8 --> precision 0.78\n\n#1.5 : plus c'est profond, plus c'est précis. Oui, c'est normal.\n\n#1.6 : A très grande profondeur, on est en train d'apprendre par coeur. \n# On peut améliorer la fiabilité en ne testant pas sur les données d'apprentissage. \n\n###Il faut trouver la meilleure profondeur pour une bonne apprentissage. \n\n#1.7\n#bleu = learn\n#orange = test\n\ndepth = 20\n\n# learn_x, learn_y, test_x, test_y = divide_db(datax, datay, 0.2) #usage (data, percentage to learn)\n# score_l, score_t = get_score(learn_x, learn_y, test_x, test_y, depth)\n\n# plt.plot(score_l, label=\"Learn\")\n# plt.plot(score_t, label=\"Test\")\n# plt.savefig(\"learn02\")\n# plt.gcf().clear()\n\n# learn_x, learn_y, test_x, test_y = divide_db(datax, datay, 0.5) #usage (data, percentage to learn)\n# score_l, score_t = get_score(learn_x, learn_y, test_x, test_y, depth)\n\n# plt.plot(score_l, label=\"Learn\")\n# plt.plot(score_t, label=\"Test\")\n# plt.savefig(\"learn05\")\n# plt.gcf().clear()\n\n# learn_x, learn_y, test_x, test_y = divide_db(datax, datay, 0.8) #usage (data, percentage to learn)\n# score_l, score_t = get_score(learn_x, learn_y, test_x, test_y, depth)\n\n# plt.plot(score_l, label=\"Learn\")\n# plt.plot(score_t, label=\"Test\")\n# plt.savefig(\"learn08\")\n# plt.gcf().clear()\n\n\n#1.8\n# L'erreur progresse avec un 'pas' plus petit lorsqu'il y a plus de donnée à apprendre. \n\n\n#1.9\n#bleu = test\n# Validation croisée\nnb_chunks = 6\n# cross_reference(datax, datay, nb_chunks, depth)\n\n\n","sub_path":"M1/S2/ARF/TME1/TP.py","file_name":"TP.py","file_ext":"py","file_size_in_byte":7805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"529827591","text":"print(__file__)\n\nraise RuntimeError(\"This profile has not yet been configured for use.\")\n\nimport sys\nimport os\n\n# ensure Python 3.6+\n\nreq_version = (3,6)\ncur_version = sys.version_info\nif cur_version < req_version:\n msg = 'Requires Python %s+' % '.'.join(req_version)\n msg += ' with BlueSky packages\\n'\n msg += 'found: ' + sys.version\n msg += '\\nfrom directory: ' + sys.prefix\n msg += '\\n'*2\n msg += 'You should type `exit` now and find the ipython with BlueSky'\n raise RuntimeError(msg)\n\n\n# ensure BlueSky is available\ntry:\n import bluesky\nexcept ImportError:\n msg = 'No module named \"bluesky\"\\n'\n msg += 'This python is from directory: ' + sys.prefix\n msg += '\\n'*2\n msg += 'You should type `exit` now and find the ipython with BlueSky'\n raise ImportError(msg)\n\n\n_major, _minor, = map(int, bluesky.__version__.split(\".\")[:2])\nif _major == 1:\n if _minor < 0:\n msg = \"Need at least BlueSky 1.0+ you have \"\n msg += bluesky.__version__\n raise ValueError(msg)\nprint(\"BlueSky version:\", bluesky.__version__)\n","sub_path":"profile_BS_jupyter/startup/00-0-checks.py","file_name":"00-0-checks.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"421873986","text":"from unittest import TestCase, TestProgram\nfrom tempfile import mkdtemp\nfrom re import escape\nfrom os.path import curdir, pardir, join, split as pathsplit, exists,\\\n basename, relpath\nfrom os import readlink, symlink, getcwd, chdir\nfrom shutil import rmtree\n\ndef follow_path(path, base=curdir):\n head, tail = pathsplit(path)\n if not head:\n j = join(base, tail)\n try:\n l = readlink(j)\n return follow_path(l, base)\n except:\n if not exists(j):\n raise Exception(j)\n return j\n base = follow_path(head)\n return follow_path(tail, base)\n\nclass T(TestCase):\n @classmethod\n def setUpClass(cls):\n dir = mkdtemp()\n chdir(dir)\n symlink(curdir, 'cur')\n symlink(pardir, 'beef')\n symlink('beef', 'pork')\n j = join('beef', basename(getcwd()), 'cur')\n symlink(j, 'chicken')\n symlink('.no.such', 'fish')\n cls.dir = dir\n @classmethod\n def tearDownClass(cls):\n rmtree(cls.dir)\n def testBeef(self):\n self.expect(pardir, 'beef')\n def testPork(self):\n self.expect(pardir, 'pork')\n def testChicken(self):\n self.expect(curdir, 'chicken')\n def testFish(self):\n re = r'\\A' + escape(join(curdir, 'fish')) + r'\\Z'\n self.assertRaisesRegexp(Exception, re, follow_path, 'fish')\n def expect(self, expected, given):\n got = relpath(follow_path(given))\n self.assertEquals(expected, got)\n\nif __name__ == '__main__':\n TestProgram()\n","sub_path":"last-dropbox/resolvsymlink/followpath.py","file_name":"followpath.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"637337554","text":"from difflib import SequenceMatcher\nimport matplotlib.pyplot as plt\nimport matplotlib.pylab as pl\nimport numpy as np\nimport glob\nimport csv\n\ndef prepara(vec,ordem):\n for i in range(len(vec)):\n vec[i] = [vec[i][j] for j in ordem]\n for i,col in enumerate(vec[2:]):\n vec[i+2] = list(map(float,col))\n vec[1] = list(map(int,vec[1]))\n return vec\n\ndef fazfig(name):\n\n figname = name[:-3] + 'png'\n file = []\n with open('averageRelative_' + name, newline='') as csvfile:\n reader = csv.reader(csvfile, delimiter='\\t')\n for row in reader:\n file += [row]\n cab = file[0]\n data = file[1:]\n file = []\n with open('pvalue_' + name, newline='') as csvfile:\n reader = csv.reader(csvfile, delimiter='\\t')\n for row in reader:\n file += [row]\n pvnames = file[0]\n pval = file[1:]\n file = []\n with open(name, newline='') as csvfile:\n reader = csv.reader(csvfile, delimiter='\\t')\n for row in reader:\n file += [row]\n trans = file[2:]\n #Proteins = cab[0]\n #position = cab[1]\n catsize = []\n catnames = []\n itercab = iter(cab[2:])\n for indcat in range(len(cab[2:])//2):\n cat = next(itercab)\n catname = cat.split()\n catsize += [len(catname) -2]\n if len(catname) > 3:\n string1 = catname[1]\n string2 = catname[2]\n match = SequenceMatcher(None, string1, string2).find_longest_match(1, len(string1)-1, 1, len(string2)-1)\n catnames += [string1[match.a: match.a + match.size]]\n else:\n catnames += catname[1][1:-1]\n cat = next(itercab)\n \n datacols = [list(x) for x in zip(*data)]\n pvalcols = [list(x) for x in zip(*pval)]\n transcols = [list(x) for x in zip(*trans)]\n \n ordenado = list(map(int,datacols[1]))\n ordenado.sort()\n ordem = []\n for val in ordenado:\n ordem += [i for i,x in enumerate(datacols[1]) if int(x) == val]\n\n transcols = prepara(transcols, ordem)\n pvalcols = prepara(pvalcols, ordem)\n datacols = prepara(datacols, ordem)\n for i, col in enumerate(datacols[3::2]):\n datacols[2 * (i+1) + 1] = list(map(lambda x: x/np.sqrt(catsize[i]), col))\n\n x = datacols[1]\n proteins = datacols[0]\n datacols = datacols[2:]\n transcols = transcols[2:]\n pvalcols = pvalcols[2:]\n \n n = len(catnames)\n colors = pl.cm.nipy_spectral(np.linspace(0,1,n))\n\n plt.figure(figsize=(14,14))\n plt.subplot(3,1,1)\n for i,name in enumerate(catnames):\n for j in range(catsize[i]):\n soma = sum(catsize[:i])\n #print(i, 2+soma+j,len(transcols))\n plt.plot(x,transcols[soma+j],label=catnames[i],linewidth=0.5, color=colors[i])\n plt.xticks([])\n plt.xlim((1,x[-1]))\n plt.ylabel('Transcriptograms', fontsize=14)\n plt.yticks(fontsize=12)\n plt.subplot(3,1,2)\n for i, col in enumerate(datacols[::2]):\n plt.plot(x,col,label=catnames[i],linewidth=0.5, color=colors[i])\n plt.fill_between(x, [x - y for x, y in zip(col,datacols[2*(i+1)-1])],\n [x + y for x, y in zip(col,datacols[2*(i+1)-1])], alpha=0.4, color=colors[i])\n plt.xticks([])\n plt.ylabel('Averages', fontsize=14)\n plt.yticks(fontsize=12)\n plt.xlim((1,x[-1]))\n plt.legend(bbox_to_anchor=(1.25, 2.03), fontsize=14)\n plt.subplot(3,1,3)\n for i, col in enumerate(pvalcols):\n plt.plot(x,col,'k',linewidth=0.5)\n plt.xlim((1,x[-1]))\n plt.yscale('log')\n plt.ylabel('p-value', fontsize=14)\n plt.yticks(fontsize=12)\n plt.xticks(fontsize=12)\n plt.subplots_adjust(hspace=0.01)\n plt.savefig(figname, dpi=600)\n# plt.show()\n\n\npattern = input('Entre com o nome das figuras:\\n')\nfor name in glob.glob(pattern):\n fazfig(name)\n\n","sub_path":"auto_fig.py","file_name":"auto_fig.py","file_ext":"py","file_size_in_byte":3795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"643553531","text":"import wx\nimport wx.aui\n\nfrom pubsub import pub\n\nfrom topics.Topics import AppGUITopics\n\nclass AppGUI(wx.Frame):\n\n\tdef __init__( self, parent ):\n\t\twx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = u\"FPlus\", pos = wx.DefaultPosition, size = wx.Size( 970,689 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )\n\n\t\tself.SetSizeHints( wx.DefaultSize, wx.DefaultSize )\n\t\t\n\t\tself.menuBar = wx.MenuBar( 0 )\n\t\tself.fileMenu = wx.Menu()\n\t\tself.newMenuItem = wx.MenuItem( self.fileMenu, wx.ID_ANY, u\"New\", wx.EmptyString, wx.ITEM_NORMAL )\n\t\tself.newMenuItem.SetBitmap( wx.ArtProvider.GetBitmap( wx.ART_NEW, wx.ART_MENU ) )\n\t\tself.fileMenu.Append( self.newMenuItem )\n\n\t\tself.fileMenu.AppendSeparator()\n\n\t\tself.loadMenuItem = wx.MenuItem( self.fileMenu, wx.ID_ANY, u\"Load\", wx.EmptyString, wx.ITEM_NORMAL )\n\t\tself.loadMenuItem.SetBitmap( wx.ArtProvider.GetBitmap( wx.ART_FILE_OPEN, wx.ART_MENU ) )\n\t\tself.fileMenu.Append( self.loadMenuItem )\n\n\t\tself.menuBar.Append( self.fileMenu, u\"File\" )\n\n\t\tself.SetMenuBar( self.menuBar )\n\n\t\tmainSizer = wx.BoxSizer( wx.VERTICAL )\n\n\t\tself.auiToolBar = wx.aui.AuiToolBar( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.aui.AUI_TB_HORZ_LAYOUT )\n\t\tself.toolNewProject = self.auiToolBar.AddTool( wx.ID_ANY, u\"New\", wx.ArtProvider.GetBitmap( wx.ART_NEW, wx.ART_TOOLBAR ), wx.NullBitmap, wx.ITEM_NORMAL, wx.EmptyString, wx.EmptyString, None )\n\n\t\tself.auiToolBar.AddSeparator()\n\n\t\tself.toolLoadProject = self.auiToolBar.AddTool( wx.ID_ANY, u\"Load\", wx.ArtProvider.GetBitmap( wx.ART_FILE_OPEN, wx.ART_TOOLBAR ), wx.NullBitmap, wx.ITEM_NORMAL, wx.EmptyString, wx.EmptyString, None )\n\n\t\tself.auiToolBar.Realize()\n\n\t\tmainSizer.Add( self.auiToolBar, 0, wx.ALL, 5 )\n\n\n\t\tself.SetSizer( mainSizer )\n\t\tself.Layout()\n\t\tself.statusBar = self.CreateStatusBar( 1, wx.STB_SIZEGRIP, wx.ID_ANY )\n\n\t\tself.Centre( wx.BOTH )\n\n\t\t# connect events\n\t\tself.Bind(wx.EVT_TOOL, self.showProjectViewGUI, self.toolNewProject)\n\t\tself.Bind(wx.EVT_TOOL, self.loadProject, self.toolLoadProject)\n\n\tdef __del__( self ):\n\t\tpass\n\n\tdef showProjectViewGUI(self, event):\n\t\tpub.sendMessage(AppGUITopics.SHOW_PROEJCT_VIEW_GUI.value)\n\n\tdef loadProject(self, event):\n\t\twith wx.FileDialog(self, \"Select project\", wildcard=\"txt files (*.txt)|*.txt\", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog:\n\t\t\tif fileDialog.ShowModal() == wx.ID_CANCEL:\n\t\t\t\treturn\n\t\t\tfilePath = fileDialog.GetPath()\n\t\t\tpub.sendMessage(AppGUITopics.LOAD_PROJECT.value, projectFilePath = filePath)","sub_path":"views/AppGUI.py","file_name":"AppGUI.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"35265503","text":"# This code is adapted from Pyro:\n# 1. softplus transformation for Normal Mean Field approximation\n# unconstrained -> softplus -> sigma\n# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\nimport functools\nimport operator\nimport warnings\nimport weakref\nfrom contextlib import ExitStack # python 3\n\nimport torch\nfrom torch import nn\nfrom torch.distributions import biject_to, constraints\n\nimport pyro\nimport pyro.distributions as dist\nfrom pyro.distributions.util import sum_rightmost\nfrom pyro.infer.autoguide.initialization import InitMessenger, init_to_mean\nfrom pyro.nn import PyroModule, PyroParam\nfrom pyro.ops.tensor_utils import periodic_repeat\nfrom pyro.infer.autoguide.guides import AutoGuide\n\ndef _deep_setattr(obj, key, val):\n \"\"\"\n Set an attribute `key` on the object. If any of the prefix attributes do\n not exist, they are set to :class:`~pyro.nn.PyroModule`.\n \"\"\"\n\n def _getattr(obj, attr):\n obj_next = getattr(obj, attr, None)\n if obj_next is not None:\n return obj_next\n setattr(obj, attr, PyroModule())\n return getattr(obj, attr)\n\n lpart, _, rpart = key.rpartition(\".\")\n # Recursive getattr while setting any prefix attributes to PyroModule\n if lpart:\n obj = functools.reduce(_getattr, [obj] + lpart.split('.'))\n setattr(obj, rpart, val)\n\ndef _deep_getattr(obj, key):\n for part in key.split(\".\"):\n obj = getattr(obj, part)\n return obj\n\n\nclass AutoNormal(AutoGuide):\n \"\"\"This implementation of :class:`AutoGuide` uses a Normal distribution\n with a diagonal covariance matrix to construct a guide over the entire\n latent space. The guide does not depend on the model's ``*args, **kwargs``.\n\n It should be equivalent to :class: `AutoDiagonalNormal` , but with\n more convenient site names and with better support for\n :class:`~pyro.infer.trace_mean_field_elbo.TraceMeanField_ELBO` .\n\n In :class:`AutoDiagonalNormal` , if your model has N named\n parameters with dimensions k_i and sum k_i = D, you get a single\n vector of length D for your mean, and a single vector of length D\n for sigmas. This guide gives you N distinct normals that you can\n call by name.\n\n Usage::\n\n guide = AutoNormal(model)\n svi = SVI(model, guide, ...)\n\n :param callable model: A Pyro model.\n :param callable init_loc_fn: A per-site initialization function.\n See :ref:`autoguide-initialization` section for available functions.\n :param float init_scale: Initial scale for the standard deviation of each\n (unconstrained transformed) latent variable.\n :param callable create_plates: An optional function inputing the same\n ``*args,**kwargs`` as ``model()`` and returning a :class:`pyro.plate`\n or iterable of plates. Plates not returned will be created\n automatically as usual. This is useful for data subsampling.\n \"\"\"\n def __init__(self, model, *,\n init_loc_fn=init_to_mean,\n init_scale=0.0,\n create_plates=None):\n self.init_loc_fn = init_loc_fn\n\n if not isinstance(init_scale, float): # or not (init_scale > 0):\n raise ValueError(\"Expected init_scale > 0. but got {}\".format(init_scale))\n self._init_scale = init_scale\n\n model = InitMessenger(self.init_loc_fn)(model)\n super().__init__(model, create_plates=create_plates)\n\n self.softplus = nn.Softplus()\n\n def _setup_prototype(self, *args, **kwargs):\n super()._setup_prototype(*args, **kwargs)\n\n self._event_dims = {}\n self._cond_indep_stacks = {}\n self.locs = PyroModule()\n self.scales = PyroModule()\n\n # Initialize guide params\n for name, site in self.prototype_trace.iter_stochastic_nodes():\n # Collect unconstrained event_dims, which may differ from constrained event_dims.\n init_loc = biject_to(site[\"fn\"].support).inv(site[\"value\"].detach()).detach()\n event_dim = site[\"fn\"].event_dim + init_loc.dim() - site[\"value\"].dim()\n self._event_dims[name] = event_dim\n\n # Collect independence contexts.\n self._cond_indep_stacks[name] = site[\"cond_indep_stack\"]\n\n # If subsampling, repeat init_value to full size.\n for frame in site[\"cond_indep_stack\"]:\n full_size = getattr(frame, \"full_size\", frame.size)\n if full_size != frame.size:\n dim = frame.dim - event_dim\n init_loc = periodic_repeat(init_loc, full_size, dim).contiguous()\n init_scale = torch.full_like(init_loc, self._init_scale)\n\n _deep_setattr(self.locs, name, PyroParam(init_loc, constraints.real, event_dim))\n _deep_setattr(self.scales, name, PyroParam(init_scale, constraints.real, event_dim))\n\n def _get_loc_and_scale(self, name):\n site_loc = _deep_getattr(self.locs, name)\n site_scale = _deep_getattr(self.scales, name)\n return site_loc, site_scale\n\n def forward(self, *args, **kwargs):\n \"\"\"\n An automatic guide with the same ``*args, **kwargs`` as the base ``model``.\n\n .. note:: This method is used internally by :class:`~torch.nn.Module`.\n Users should instead use :meth:`~torch.nn.Module.__call__`.\n\n :return: A dict mapping sample site name to sampled value.\n :rtype: dict\n \"\"\"\n # if we've never run the model before, do so now so we can inspect the model structure\n if self.prototype_trace is None:\n self._setup_prototype(*args, **kwargs)\n\n plates = self._create_plates(*args, **kwargs)\n result = {}\n for name, site in self.prototype_trace.iter_stochastic_nodes():\n transform = biject_to(site[\"fn\"].support)\n\n with ExitStack() as stack:\n for frame in site[\"cond_indep_stack\"]:\n if frame.vectorized:\n stack.enter_context(plates[frame.name])\n\n site_loc, site_scale = self._get_loc_and_scale(name)\n unconstrained_latent = pyro.sample(\n name + \"_unconstrained\",\n dist.Normal(\n site_loc, self.softplus(site_scale),\n ).to_event(self._event_dims[name]),\n infer={\"is_auxiliary\": True}\n )\n\n value = transform(unconstrained_latent)\n log_density = transform.inv.log_abs_det_jacobian(value, unconstrained_latent)\n log_density = sum_rightmost(log_density, log_density.dim() - value.dim() + site[\"fn\"].event_dim)\n delta_dist = dist.Delta(value, log_density=log_density,\n event_dim=site[\"fn\"].event_dim)\n\n result[name] = pyro.sample(name, delta_dist)\n\n return result\n\n\n def median(self, *args, **kwargs):\n \"\"\"\n Returns the posterior median value of each latent variable.\n\n :return: A dict mapping sample site name to median tensor.\n :rtype: dict\n \"\"\"\n medians = {}\n for name, site in self.prototype_trace.iter_stochastic_nodes():\n site_loc, _ = self._get_loc_and_scale(name)\n median = biject_to(site[\"fn\"].support)(site_loc)\n if median is site_loc:\n median = median.clone()\n medians[name] = median\n\n return medians\n\n\n def quantiles(self, quantiles, *args, **kwargs):\n \"\"\"\n Returns posterior quantiles each latent variable. Example::\n\n print(guide.quantiles([0.05, 0.5, 0.95]))\n\n :param quantiles: A list of requested quantiles between 0 and 1.\n :type quantiles: torch.Tensor or list\n :return: A dict mapping sample site name to a list of quantile values.\n :rtype: dict\n \"\"\"\n results = {}\n\n for name, site in self.prototype_trace.iter_stochastic_nodes():\n site_loc, site_scale = self._get_loc_and_scale(name)\n\n site_quantiles = torch.tensor(quantiles, dtype=site_loc.dtype, device=site_loc.device)\n site_quantiles_values = dist.Normal(site_loc, self.softplus(site_scale)).icdf(site_quantiles)\n constrained_site_quantiles = biject_to(site[\"fn\"].support)(site_quantiles_values)\n results[name] = constrained_site_quantiles\n\n return results\n","sub_path":"cell2location/distributions/AutoNormal.py","file_name":"AutoNormal.py","file_ext":"py","file_size_in_byte":8424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"412038757","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 18 21:18:44 2021\n\n@author: kiera\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport json\nfrom tsfresh import extract_features\nimport ast\n\ng = open('data/uncategorised.json',\"r\")\nf = open('data/categorised.json',\"r\")\nh = open(\"Data/unlinked.json\",\"r\")\n \ng=json.loads(g.read())\n \ng=json.dumps(g,sort_keys=True, indent=4)\ng=g.replace(\"null\",\"None\")\nh=json.loads(h.read())\n \nh=json.dumps(h,sort_keys=True, indent=4)\nh=h.replace(\"null\",\"None\")\n \n \n \n #'uncatogorized = json.dumps(uncatogorized, indent=4,sort_keys=True)\n #print(uncatogorized)\n \n \nnewfile = open(r\"C:\\Users\\kiera\\Desktop\\categorized_data_reformated.txt\",\"w\")\nnewfile2 = open(r\"C:\\Users\\kiera\\Desktop\\uncategorized_data_reformated.txt\",\"w\")\nnewfile3 = open(r\"C:\\Users\\kiera\\Desktop\\unlinked_data_reformated.txt\",\"w\")\nnewfile.write(json.dumps(ast.literal_eval(f.read()), indent=4, sort_keys=True))\n #print(json.dumps(ast.literal_eval(g), indent=4, sort_keys=True))\n \n #print(json.dumps(ast.literal_eval(g.read()), indent=4, sort_keys=True))\nnewfile2.write(g)\nnewfile3.write(h)\nnewfile.close()\nnewfile2.close()\nnewfile3.close()","sub_path":"dataformatter.py","file_name":"dataformatter.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"446636350","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport time\n\nfrom agent import DQNAgent, PGAgent, RandomAgent, DumbAgent\nfrom env import Env\nfrom simulator import Simulator\n\nimport os\n\nFILE_DIR = os.path.dirname(os.path.realpath(__file__))\nROOT_DIR = os.path.dirname(FILE_DIR)\n\n\nfrom sacred import Experiment\nfrom sacred.observers import MongoObserver\nfrom sacred.observers import FileStorageObserver\n\nex = Experiment(\"bike-reposition-real\")\nex.observers.append(FileStorageObserver.create(\n os.path.join(ROOT_DIR, 'results')))\n\n# if you have mongoDB, the experiment result can also be dumped into mongoDB,\n# more details can be found here:\n# https://sacred.readthedocs.io/en/latest/observers.html#mongo-observer\n\n# ex.observers.append(MongoObserver.create())\n\n\n@ex.config\ndef configuration():\n # experiment\n num_rounds = 200\n\n # real data\n date = '2013/9/24'\n scale = 1\n episode = 0\n community = 1\n\n # real world parameters\n num_trikes = 5\n capacity = 30\n rho = -1 # for pruning\n mu = 30 / 3.6\n tr = 60 * 3\n er = 60 * 3\n\n # agents\n gamma = 0.95 # discount rate\n\n # neural net\n hidden_dims = [128, 128]\n eta = 1e-3 # learning rate\n batch_size = 128\n epochs = 5\n\n snapshots_path = os.path.join(\n ROOT_DIR, 'snapshots', 'json', str(int(time.time())))\n\n\n@ex.capture\ndef train(env, agent, round_, snapshot, snapshots_path):\n # switch to test mode, use real data\n name = agent.__class__.__name__\n\n done = False\n state = env.reset()\n\n if snapshot:\n snapshots_path += '/train/{}-{}.json'.format(\n name, round_)\n # reset() will clear all snapshot events, so please register after reset()\n env.register_snapshots(snapshots_path, 200)\n\n while not done:\n action = agent.act(state)\n action = env.pruning(prob=0.5) or action\n next_state, reward, done, _ = env.step(action)\n agent.remember(state, action, reward, next_state)\n state = next_state\n\n # train\n agent.replay()\n\n # print training info\n loss = env.loss\n print('train round {}, loss {}'.format(round_, loss))\n ex.log_scalar('{}.train.loss'.format(name), loss, round_)\n\n\n@ex.capture\ndef test(env, agent, round_, snapshot, snapshots_path):\n # switch to test mode, use real data\n name = agent.__class__.__name__\n\n done = False\n state = env.reset()\n\n if snapshot:\n snapshots_path += '/test/{}-{}.json'.format(\n name, round_)\n env.register_snapshots(snapshots_path, 200)\n\n while not done:\n action = agent.act(state)\n next_state, _, done, _ = env.step(action)\n state = next_state\n\n loss = env.loss\n print('test round {}, loss {}'.format(round_, loss))\n ex.log_scalar('{}.test.loss'.format(name), loss, round_)\n\n\n@ex.capture\ndef run_on_agents(env, _config):\n dumb_agent = DumbAgent()\n\n random_agent = RandomAgent(env.action_size)\n\n dqn_agent = DQNAgent(env.state_size,\n env.action_size,\n batch_size=_config['batch_size'],\n hidden_dims=_config['hidden_dims'],\n gamma=_config['gamma'],\n eta=_config['eta'],\n epochs=_config['epochs'])\n\n pg_agent = PGAgent(env.state_size,\n env.action_size,\n batch_size=_config['batch_size'],\n hidden_dims=_config['hidden_dims'],\n gamma=_config['gamma'],\n eta=_config['eta'],\n epochs=_config['epochs'])\n\n num_rounds = _config['num_rounds']\n num_snapshots = 10\n snapshot_rounds = [num_rounds-1] + \\\n np.linspace(0, num_rounds-1, num_snapshots-1, dtype=int).tolist()\n\n for round_ in range(num_rounds):\n env.simulator.resample() # train on resampled environment\n snapshot = round_ in snapshot_rounds\n train(env, pg_agent, round_=round_, snapshot=snapshot)\n train(env, dqn_agent, round_=round_, snapshot=snapshot)\n\n if round_ % 2 == 0:\n # test\n env.simulator.switch_mode(train=False)\n test(env, dumb_agent, round_, snapshot=snapshot)\n test(env, random_agent, round_, snapshot=snapshot)\n test(env, pg_agent, round_, snapshot=snapshot)\n test(env, dqn_agent, round_, snapshot=snapshot)\n env.simulator.switch_mode(train=True)\n\n\n@ex.automain\ndef main(_config):\n simulator = Simulator(date=_config['date'],\n scale=_config['scale'],\n episode=_config['episode'],\n community=_config['community'],\n mu=_config['mu'],\n tr=_config['tr'],\n er=_config['er'])\n\n env = Env(simulator=simulator,\n num_trikes=_config['num_trikes'],\n capacity=_config['capacity'],\n rho=_config['rho'])\n\n run_on_agents(env)\n","sub_path":"src/expt.py","file_name":"expt.py","file_ext":"py","file_size_in_byte":5057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"155050893","text":"import random\r\n\r\nclass food:\r\n\tdef __init__(self):\r\n\t\tself.foodx = 0\r\n\t\tself.foody = 0\r\n\r\n\tdef get_food_pos(self,dis_width,dis_height,snake_block):\r\n\t\tself.foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0\r\n\t\tself.foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0\r\n\r\n\tdef move_food_pos(self,snake_block):\r\n\t\tside = random.randrange(0,100)\r\n\r\n\t\tif side < 25:\r\n\t\t\tself.foodx -= snake_block\r\n\t\telif side > 25 and side < 50:\r\n\t\t\tself.foodx += snake_block\r\n\t\telif side > 50:\r\n\t\t\tself.foody += snake_block\r\n\t\telse:\r\n\t\t\tself.foody -= snake_block\r\n\t\r\n\tdef ret_food_pos(self):\r\n\t\treturn [self.foodx,self.foody]\r\n\r\n","sub_path":"food.py","file_name":"food.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"350938290","text":"\nfrom datetime import timedelta\n\ndef calc_estimation_time(estimate, realtime):\n # calculation of estimateb_by_calc from user data\n #estimated_dt = datetime.strptime(estimate, '%H:%M')\n #realtime_dt = datetime.strptime(realtime, '%H:%M')\n\n estimated_duration_td = timedelta(hours=estimate.hour, minutes=estimate.minute)\n realtime_duration_td = timedelta(hours=realtime.hour, minutes=realtime.minute)\n\n diff_td = realtime_duration_td - estimated_duration_td\n seconds = diff_td.seconds\n estimate_by_calc = f\"{int(seconds / 3600)}\"+f': {(int(seconds / 60)) % 60} '\n return estimate_by_calc\n\n\ndef calc_correctness(estimate, realtime):\n # calculation of correctness from user data\n\n estimated_duration_td = timedelta(hours=estimate.hour, minutes=estimate.minute)\n realtime_duration_td = timedelta(hours=realtime.hour, minutes=realtime.minute)\n\n correctness = 100 * realtime_duration_td.seconds / estimated_duration_td.seconds\n return correctness","sub_path":"tracker/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"238282596","text":"class Myclass():\n def __init__(self):\n name = input(\"Your name?\")\n age = input(\"Your Age?\")\n job = input(\"Your Job?\")\n his = input(\"Your Job History?\")\n\n def jobsal(self):\n if ( age < 20) and ( his < 3):\n print(\"You Are a junior\")\n elif (age > 20) and (his > 3):\n print(\"You Are A senior\")\n else:\n (\"Sorry Pls Try Again\")\nmyjob = Myclass()\nprint(jobsal)\n","sub_path":"My-Code/first-app.py","file_name":"first-app.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"604642118","text":"# -*-coding: utf-8 -*-\n# 使用Pil进行图像增强\nfrom PIL import Image, ImageFilter\nfrom matplotlib import pyplot as plt\nfrom IPython.display import display\nimport random\n\n\ndef resize_blur(img):\n \"\"\"\n ① NEAREST:最近滤波。从输入图像中选取最近的像素作为输出像素。\n ② BILINEAR:双线性内插滤波。在输入图像的2*2矩阵上进行线性插值。\n ③ BICUBIC:双立方滤波。在输入���像的4*4矩阵上进行立方插值。\n ④ ANTIALIAS:平滑滤波。对所有可以影响输出像素的输入像素进行高质量的重采样滤波,以计算输出像素值。\n \"\"\"\n seed = random.random()*3+1 # 放缩倍数\n filter_type = random.choice([0, 1, 2, 3]) # 插值方式\n width, height = img.size[0], img.size[0]\n if filter_type == 0:\n img = img.resize((int(width/seed), int(height/seed)),Image.NEAREST) \n img = img.resize((width, height),Image.NEAREST) \n elif filter_type == 1:\n img = img.resize((int(width/seed), int(height/seed)),Image.BILINEAR) \n img = img.resize((width, height),Image.BILINEAR) \n elif filter_type == 2:\n img = img.resize((int(width/seed), int(height/seed)),Image.BICUBIC) \n img = img.resize((width, height),Image.BICUBIC) \n else:\n img = img.resize((int(width/seed), int(height/seed)),Image.ANTIALIAS) \n img = img.resize((width, height),Image.ANTIALIAS) \n return img\n\ndef direct_blur(img):\n return img.filter(ImageFilter.BLUR)\n\n\ndef guass_blur(img):\n radius = random.random()*3 # 0-3\n return img.filter(ImageFilter.GaussianBlur(radius=radius)) \n\ndef apply_random_blur(img):\n blur_type = random.choice([0,0,0,0,0,0,0,2,3,1]) # 0-原图\n if blur_type == 1:\n img = resize_blur(img)\n elif blur_type == 2:\n img = guass_blur(img)\n elif blur_type == 3:\n img = direct_blur(img)\n return img, blur_type\n\nif __name__ == '__main__':\n for i in range(20):\n print(random.choice([0,10,0,0,1,3,4,5]))\n","sub_path":"shuili_detect/blur.py","file_name":"blur.py","file_ext":"py","file_size_in_byte":2015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"212657253","text":"#!python3\n\nexample = [27, 10, 12, 20, 25, 13, 15, 22]\n\n\ndef merge(low, mid, high):\n tmpData = []\n (left, right) = (low, mid + 1)\n while left <= mid and right <= high:\n if example[left] < example[right]:\n tmpData.append(example[left])\n left += 1\n else:\n tmpData.append(example[right])\n right += 1\n if left > mid:\n [tmpData.append(i) for i in example[right: high + 1]]\n else:\n [tmpData.append(i) for i in example[left: mid + 1]]\n example[low:high + 1] = tmpData\n\n\ndef mergeSort(low, high):\n mid = int((low + high)/2)\n if low < high:\n mergeSort(low, mid)\n mergeSort(mid+1, high)\n merge(low, mid, high)\n\n\nprint(f\"Origin: {example}\")\nmergeSort(0, len(example) - 1)\nprint(f\"Change to: {example}\")\n\n","sub_path":"面试-算法分析AlgorithmAnalysis/分治法(DivideAndConquer)/MergeSort.py","file_name":"MergeSort.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"602401469","text":"#!/usr/bin/env python\nimport os, vtk\nimport numpy as np\nfrom matplotlib import pyplot as plt, cm\n\nfrom pymicro.crystal.lattice import *\nfrom pymicro.crystal.microstructure import *\nfrom pymicro.xray.xray_utils import *\nfrom pymicro.view.vtk_utils import *\nfrom pymicro.view.scene3d import Scene3D\nfrom pymicro.xray.detectors import RegArrayDetector2d\nfrom pymicro.xray.laue import compute_Laue_pattern, diffracted_vector, compute_ellipsis\nfrom vtk.util.colors import gold\n\n'''\nThis script displays the transmission Laue diffraction for the paper by Wenk.\nA crystal lattice of Olivine is constructed with the indexed orientation and some lattice planes around the [111] zone axis are used.\nA 512x512 detector is used and the diffraction image is computed using only the selected hkl planes.\nA 3D scene of the diffraction is constructed using the exact angles to visualise the process.\n'''\n\n# create the 3D scene\nbase_name = os.path.splitext(__file__)[0]\ns3d = Scene3D(display=True, ren_size=(1000, 800), name=base_name)\nolivine = Lattice.orthorombic(1.022, 0.596, 0.481) # nm Barret & Massalski convention\nscale = 15.\nolivine_view = Lattice.orthorombic(scale * 1.022, scale * 0.596, scale * 0.481) # artificially larger lattice for the 3d view\n\nolivine = Lattice.orthorombic(0.481, 0.596, 1.022) # nm DCT convention\nolivine_view = Lattice.orthorombic(scale * 0.481, scale * 0.596, scale * 1.022)\n\ndetector = RegArrayDetector2d(size=(512, 512), u_dir=[0, -1, 0], v_dir=[0, 0, -1])\ndetector.pixel_size = 0.100 # mm\ndetector.ucen = 275\ndetector.vcen = 214\ndetector.ref_pos = np.array([111., 0., 0.]) + \\\n (detector.size[0] / 2 - detector.ucen) * detector.u_dir * detector.pixel_size + \\\n (detector.size[1] / 2 - detector.vcen) * detector.v_dir * detector.pixel_size # mm\ndet_size_mm = detector.get_size_mm()\n\n# orientation of the crystal\n\n# for [111] zone axis / DCT convention\ng12 = np.array([[-0.44894466, -0.61500929, -0.64823782],\n [-0.38435282, -0.52200508, 0.76143523],\n [-0.80667317, 0.59099431, -0.00202916]])\n'''\n# for [111] zone axis\ng12 = np.array([[-0.84339843, -0.4023908, -0.35603473],\n [-0.36699651, -0.0525326, 0.92873779],\n [-0.39241898, 0.9139595, -0.10337011]])\n# for [342] zone axis\ng23 = np.array([[ 0.71801397, -0.67252004, -0.17936758],\n [ 0.64559783, 0.73980215, -0.18946299],\n [ 0.26011418, 0.02023775, 0.96536576]])\n# for [231] zone axis\ng24 = np.array([[-0.74901623, -0.19211372, -0.63408754],\n [-0.65906697, 0.11801609, 0.74276707],\n [-0.06786321, 0.97425075, -0.21501177]])\n# for [332] zone axis\ng14 = np.array([[-0.89433299, -0.24003404, -0.37756081],\n [-0.39655259, 0.03453709, 0.91736211],\n [-0.20715828, 0.97014991, -0.12607378]])\n# for [332] zone axis\ng34 = np.array([[ 0.80213800, 0.23841449, -0.54747891],\n [ 0.56972577, -0.03095772, 0.82125158],\n [ 0.17884958, -0.97066995, -0.16066324]])\n'''\norientation = Orientation(g12)\ngt = orientation.orientation_matrix().transpose()\n\n# look at one particular zone axis\nuvw = HklDirection(1, 1, 1, olivine)\n#uvw = HklDirection(3, 4, 2, olivine)\n#uvw = HklDirection(2, 3, 1, olivine)\n#uvw = HklDirection(3, 3, 2, olivine)\nOA = gt.dot(uvw.direction())\nif OA[0] < 0:\n OA *= -1 # make sur the OA vector is going forward\nalpha0 = np.arccos(np.dot(OA, np.array([1., 0., 0.])))\nprint('XYZ coordinates of [111] zone axis = %s' % np.dot(gt, uvw.direction()))\nprint('angle between incident beam and zone axis is %.1f' % (alpha0 * 180 / np.pi))\nprint('ellipse b value is %.1f mm or %d pixels from the center' % (\n detector.ref_pos[0] * np.tan(alpha0), detector.ref_pos[0] * np.tan(alpha0) / detector.pixel_size))\n#hkl_planes = HklObject.skip_higher_order(uvw.find_planes_in_zone(max_miller=3), verbose=True)\nhkl_planes = [HklPlane(-1, 1, 0, olivine), HklPlane(-2, 1, 1, olivine)] # for [111]\n#hkl_planes = [HklPlane(-2, 1, 1, olivine), HklPlane(2, 0, -3, olivine)] # for [342]\n#hkl_planes = [HklPlane(-2, 1, 1, olivine), HklPlane(-3, 1, 3, olivine)] # for [231]\n#hkl_planes = [HklPlane(-1, 1, 0, olivine), HklPlane(-3, 1, 3, olivine), HklPlane(2, 0, -3, olivine), HklPlane(7, -5, -3, olivine)]#, HklPlane(1, 1, -3, olivine)] # for [332]\n#print('after skipping the high order reflections, the list contains %d planes:' % len(hkl_planes))\n\ncompute_Laue_pattern(orientation, detector, hkl_planes, r_spot=5, inverted=True, show_direct_beam=True)\nplt.figure(figsize=(8, 8))\nplt.imshow(detector.data.T, origin='upper', interpolation='nearest', cmap=cm.gray)\nplt.clim(0, 1)\n#plt.show()\n\ndif_planes = [] # a list of the plane to use in the 3d display\n# loop on all hkl planes\nfor hkl in hkl_planes[:]:\n K = diffracted_vector(hkl, orientation, min_theta=1.0)\n if K is None:\n continue\n dif_planes.append(hkl) # mark this lattice plane for 3d display\n R = detector.project_along_direction(K, origin=[0., 0., 0.])\n (u, v) = detector.lab_to_pixel(R)\n if u >= 0 and u < detector.size[0] and v >= 0 and v < detector.size[1]:\n print('diffracted beam will hit the detector at (%.3f, %.3f) mm or (%d, %d) pixels' % (R[1], R[2], u, v))\n plt.plot(u, v, 'ro')\n # annotate the detector image (comment the next line to turn it off)\n (h, k, l) = hkl.miller_indices()\n plt.annotate('$%d%d%d$' % (h, k, l), xycoords='data', xy=(u, v),\n horizontalalignment='center', verticalalignment='bottom', fontsize=16)\n # line showing the diffracted beam\n diffracted_beam = line_3d((0, 0, 0), R)\n diffracted_beam.GetProperty().SetLineWidth(3.0)\n diffracted_beam.GetProperty().SetDiffuseColor(black)\n s3d.add(diffracted_beam)\n\nA = detector.project_along_direction(OA) # A is the projection of the zone axis onto the detector\nprint('ZA cross the det plane at', A)\n\n# plot the ellipsis corresponding to the zone axis on the image\nellipsis_mm = compute_ellipsis(orientation, detector, uvw) # mm\nellipsis_px = np.empty((ellipsis_mm.shape[0], 2))\nfor i in range(ellipsis_mm.shape[0]):\n ellipsis_px[i, :] = detector.lab_to_pixel([detector.ref_pos[0], ellipsis_mm[i, 0], ellipsis_mm[i, 1]])\n\nplt.plot(ellipsis_px[:, 0], ellipsis_px[:, 1], '--')\n(uA, vA) = detector.lab_to_pixel(A)\nplt.plot([ellipsis_px[0, 0], ellipsis_px[50, 0]], [ellipsis_px[0, 1], ellipsis_px[50, 1]], '-o')\nplt.plot([ellipsis_px[25, 0], ellipsis_px[75, 0]], [ellipsis_px[25, 1], ellipsis_px[75, 1]], '-o')\nplt.plot(uA, vA, 'b+') # mark the trace of the zone axis on the detector with a cross\nplt.axis([0, detector.size[0] - 1, detector.size[1] - 1, 0])\n# now save the 2d image\nplt.subplots_adjust(top=1, bottom=0, left=0, right=1)\nplt.savefig('image.png')\n# plt.show()\n\n# detector actor positioned at det_distance mm from the center\ndet = vtk.vtkPlaneSource()\ndet.SetOrigin(detector.ref_pos[0], detector.ref_pos[1] + det_size_mm[0] / 2, detector.ref_pos[2] - det_size_mm[1] / 2)\ndet.SetPoint1(detector.ref_pos[0], detector.ref_pos[1] - det_size_mm[0] / 2, detector.ref_pos[2] - det_size_mm[1] / 2)\ndet.SetPoint2(detector.ref_pos[0], detector.ref_pos[1] + det_size_mm[0] / 2, detector.ref_pos[2] + det_size_mm[1] / 2)\nplaneMapper = vtk.vtkPolyDataMapper()\nplaneMapper.SetInputConnection(det.GetOutputPort())\nplaneActor = vtk.vtkActor()\nplaneActor.SetMapper(planeMapper)\n# create texture object (reuse the image we have just created)\nreader = vtk.vtkPNGReader()\n#reader.SetFileName('image.png')\nreader.SetFileName('Wenk_JSR_1997_Laue_indexed.png')\ntexture = vtk.vtkTexture()\ntexture.SetInputConnection(reader.GetOutputPort())\nplaneActor.SetTexture(texture)\ns3d.add(planeActor)\n\n# display a 3d cone around the zone axis\nf = 1.6 # factor to make the cone longer so that it completely crosses the detector plane, can be computed using the geometry...\nza_vector = f * A\nLZA = np.linalg.norm(za_vector) # also equal to f*detector.ref_pos[0]/np.cos(alpha0)\ncone = vtk.vtkConeSource()\ncone.CappingOff()\ncone.SetCenter(0.5 * za_vector)\ncone.SetHeight(LZA)\ncone.SetRadius(LZA * np.tan(alpha0))\ncone.SetDirection(-OA)\ncone.SetResolution(100)\ncone_normals = vtk.vtkPolyDataNormals()\ncone_normals.SetInputConnection(cone.GetOutputPort())\n\n# clip the cone by the plane\nclip = vtk.vtkClipPolyData()\nclip.SetInputConnection(cone_normals.GetOutputPort())\nplane = vtk.vtkPlane()\nplane.SetOrigin(detector.ref_pos)\nplane.SetNormal(-1., 0., 0.)\n# also cut the cone by the plane normal to the zone axis\nZA_normal_plane = vtk.vtkPlane()\nZA_normal_plane.SetOrigin(detector.ref_pos)\nZA_normal_plane.SetNormal(-OA)\nclip.SetClipFunction(plane)\ncone_mapper = vtk.vtkPolyDataMapper()\ncone_mapper.SetInputConnection(clip.GetOutputPort())\ncone = vtk.vtkActor()\ncone.GetProperty().SetColor(0., 1., 0.)\ncone.GetProperty().SetOpacity(0.3)\ncone.SetMapper(cone_mapper)\ns3d.add(cone)\n\n# use a vtkCutter to display the intersection of the cone and the detector plane\nfor p in [plane]:\n cut_edges = vtk.vtkCutter()\n cut_edges.SetInputConnection(cone_normals.GetOutputPort())\n cut_edges.SetCutFunction(p)\n strip_edges = vtk.vtkStripper()\n strip_edges.SetInputConnection(cut_edges.GetOutputPort())\n strip_edges.Update()\n ellipse_mapper = vtk.vtkPolyDataMapper()\n ellipse_mapper.SetInputConnection(strip_edges.GetOutputPort())\n ellipse = vtk.vtkActor()\n ellipse.SetMapper(ellipse_mapper)\n ellipse.GetProperty().SetColor(0., 0., 0.)\n ellipse.GetProperty().SetLineWidth(1.5)\n s3d.add(ellipse)\n\n# add the crystal lattice with all diffracting hkl planes, move it so the centre of the cell is at (0, 0, 0)\nlattice_with_planes = lattice_3d_with_planes(olivine_view, dif_planes, crystal_orientation=orientation, origin='mid',\n show_atoms=True, show_normal=True, plane_opacity=1.0, sphereRadius=0.1,\n sphereColor=gold)\ns3d.add(lattice_with_planes)\n\n# add axes actor\naxes = axes_actor(30, axisLabels=('X', 'Y', 'Z'), fontSize=50)\ns3d.add(axes)\n\n# line for direct beam\ndirect_beam = line_3d((-200, 0, 0), (detector.ref_pos[0], 0., 0.))\ndirect_beam.GetProperty().SetLineWidth(5.0)\ndirect_beam.GetProperty().SetDiffuseColor(black)\ns3d.add(direct_beam)\n\n# line showing the zone axis\nzone_axe_line = line_3d((0, 0, 0), A)\nzone_axe_line.GetProperty().SetLineWidth(1.0)\nzone_axe_line.GetProperty().SetDiffuseColor(black)\nzone_axe_line.GetProperty().SetLineStipplePattern(0xf0f0)\nzone_axe_line.GetProperty().SetLineStippleRepeatFactor(1)\nzone_axe_line.GetProperty().SetPointSize(1)\ns3d.add(zone_axe_line)\n\n# large sphere\nsphere = vtk.vtkSphereSource()\nsphere.SetRadius(detector.ref_pos[0])\nsphere.SetPhiResolution(40)\nsphere.SetThetaResolution(40)\nsphereMapper = vtk.vtkPolyDataMapper()\nsphereMapper.SetInputConnection(sphere.GetOutputPort())\nsphereActor = vtk.vtkActor()\nsphereActor.SetMapper(sphereMapper)\nsphereActor.GetProperty().SetOpacity(0.2)\n#s3d.add(sphereActor)\n\n# set up camera and render\ncam = setup_camera(size=(1, 1, 1))\ncam.SetFocalPoint(0.4 * detector.ref_pos)\ncam.SetPosition(-80, -80, 65)\ns3d.set_camera(cam)\ncam.SetClippingRange(1, 1000)\ncam.Dolly(0.95)\ns3d.render(key_pressed_callback=True)","sub_path":"Direct_Indexation/Wenk_article/crystal_Laue_3d_Wenk.py","file_name":"crystal_Laue_3d_Wenk.py","file_ext":"py","file_size_in_byte":11169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"199137541","text":"import requests\nfrom lxml import etree\nfrom collections import OrderedDict\nimport Utils.utils as utils\nfrom Utils.MysqlClass import Mysql\nimport json\nimport time\nfrom Utils.XmlController import deal_img_jianshu\nfrom Utils.GetProxy import get_proxy\nheaders = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:49.0) Gecko/20100101 Firefox/49.0'}\n\n\ndef get_json_resultlist(datadict):\n base_url = 'https://www.jianshu.com/search/do?'\n # data = urllib.parse.urlencode(datadict)\n time.sleep(3)\n html = requests.post(base_url, data=datadict, headers=headers, proxies=get_proxy()).text\n result = json.loads(html, encoding=\"utf-8\")\n if \"error\" in result.keys():\n return None\n else:\n return result\n\n\ndef save2db(mydict, scatalogid):\n article = OrderedDict()\n for tag in mydict['entries']:\n article['title'] = utils.dealstring(etree.HTML(tag['title']).xpath(\"string(.)\"))\n article['preid'] = scatalogid\n article['href'] = \"https://www.jianshu.com/p/\" + tag[\"slug\"]\n article['fullcontent'] = getmaincontenthtml(article['href'])\n article['content'] = getmaincontent(article['href'])\n mysql = Mysql()\n mysql.insert_data_to_pages(article)\n\n\ndef getmaincontenthtml(url):\n page = requests.get(url, headers=headers).text\n html = etree.HTML(page)\n result = html.xpath(\"//div[@class='show-content']\")\n ans = \"\"\n for i in result:\n tmp = etree.tostring(i, encoding=\"utf-8\")\n tmp = tmp.decode(\"utf-8\").replace(\"<\", \"<\").replace(\">\", \">\")\n tmp = utils.dealstring(tmp)\n ans += tmp\n # print(ans)\n ans = deal_img_jianshu(ans)\n return ans\n\n\ndef getmaincontent(url):\n page = requests.get(url, headers=headers).text\n html = etree.HTML(page)\n result = html.xpath(\"//div[@class='show-content']\")\n if result is None or len(result) <= 0:\n return \"\"\n tmp = result[0].xpath(\"string(.)\")\n tmp = utils.dealstring(tmp)\n # print(tmp)\n return tmp\n","sub_path":"spiders/jianshu_spider.py","file_name":"jianshu_spider.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"498904492","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jul 31 11:09:20 2019\r\n\r\n@author: Alessandro\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nfrom sklearn import linear_model\r\n\r\nsns.set(style='darkgrid')\r\n\r\nStock_Market = {'Year': [2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016],\r\n 'Month': [12, 11,10,9,8,7,6,5,4,3,2,1,12,11,10,9,8,7,6,5,4,3,2,1],\r\n 'Interest_Rate': [2.75,2.5,2.5,2.5,2.5,2.5,2.5,2.25,2.25,2.25,2,2,2,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75],\r\n 'Unemployment_Rate': [5.3,5.3,5.3,5.3,5.4,5.6,5.5,5.5,5.5,5.6,5.7,5.9,6,5.9,5.8,6.1,6.2,6.1,6.1,6.1,5.9,6.2,6.2,6.1],\r\n 'Stock_Index_Price': [1464,1394,1357,1293,1256,1254,1234,1195,1159,1167,1130,1075,1047,965,943,958,971,949,884,866,876,822,704,719] \r\n }\r\n\r\ndf = pd.DataFrame(Stock_Market)\r\n\r\ndf\r\n\r\ndf.describe()\r\n\r\ndf.head(10)\r\n\r\ndf['Interest_Rate'].corr(df['Unemployment_Rate'])\r\n\r\ndf.corr(method='spearman') # Spearman Method\r\ndf.corr() # Pearson Method\r\n\r\nplt.scatter(df['Interest_Rate'],df['Unemployment_Rate'], color = 'red')\r\nplt.title('Interest_Rate Vs Unemployment_Rate', fontsize = 14)\r\nplt.grid(True)\r\nplt.show()\r\n\r\nplt.boxplot(df['Interest_Rate'])\r\nplt.title('Diagrama de Caixa - Interest_Rate')\r\nplt.grid(True)\r\nplt.show()\r\n\r\nsns.boxplot(df['Interest_Rate'], orient='v', color='LightBlue')\r\n\r\nX = df[['Interest_Rate','Unemployment_Rate']] # here we have 2 variables for multiple regression. If you just want to use one variable for simple linear regression, then use X = df['Interest_Rate'] for example.Alternatively, you may add additional variables within the brackets\r\nY = df['Stock_Index_Price']\r\n\r\nregr = linear_model.LinearRegression()\r\n\r\nregr.fit(X,Y)\r\n\r\nregr.intercept_ #Intercepto\r\nregr.coef_ # Coeficiente\r\n\r\n\r\n#Prevendo resultados\r\nNew_Interest_Rate = float(input('Digite o valor no novo Interest_Rate:'))\r\nNew_Unemployment_Rate = float(input('Digite o valor no novo Unemployment_Rate:'))\r\n\r\nNew = regr.predict([[New_Interest_Rate,New_Unemployment_Rate]])\r\n\r\nprint('O Stock_Index_Price predito é:\\n', New)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"RegressãoLinear/Multivariable_Linear_Regression.py","file_name":"Multivariable_Linear_Regression.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"534768447","text":"import numpy as np\r\nimport time\r\nimport sys\r\nfrom scipy.optimize import curve_fit\r\n\r\ndef o_u(sigma,tau,dt):\r\n tmax = int(3000/dt)\r\n thetas = []\r\n theta = np.random.uniform(-np.pi,np.pi)\r\n thetas.append(theta)\r\n ts = [0]\r\n for i in range(tmax):\r\n theta += -((((theta+np.pi)%(2*np.pi))-np.pi)/tau)*dt + sigma*np.sqrt(dt)*np.random.normal(0,1)\r\n thetas.append(theta)\r\n ts.append((i+1)*dt)\r\n return np.array(ts),np.array(thetas)\r\n\r\ndef vel_correlation(vcor_samples,Vcs):\r\n vcor = []\r\n msq = np.dot(np.mean(Vcs,axis=0),np.mean(Vcs,axis=0))\r\n vcor.append(np.mean(Vcs[:,0]*Vcs[:,0]+Vcs[:,1]*Vcs[:,1])-msq)\r\n for i in vcor_samples[1:]:\r\n vcor.append(np.mean((Vcs[:-i:,0]*Vcs[i::,0])+(Vcs[:-i:,1]*Vcs[i::,1]))-msq)\r\n return np.array(vcor)\r\n\t\r\ndef tau_corr_sim(tau,delta_squared,trials):\r\n dt = 0.01\r\n sigma = np.sqrt(delta_squared)*np.sqrt(2/tau)\r\n Nsamples = 600\r\n vcor_samples = np.append(np.array([0]),np.unique(np.logspace(0,np.log10(Nsamples),num=int(Nsamples)/10,dtype=int)))\r\n samps = []\r\n for i in range(trials):\r\n ts,thetas = o_u(sigma,tau,dt)\r\n Vcs = np.array(np.array([np.cos(thetas),np.sin(thetas)]).T)\r\n vcorr = vel_correlation(vcor_samples,Vcs[int(3*tau/dt):,:])\r\n p,cov = curve_fit(exp_func,ts[vcor_samples],vcorr/vcorr[0])\r\n samps.append(p[0])\r\n samps = np.array(samps)\r\n return samps.mean(),samps.std()/np.sqrt(trials)\r\n\t\r\ndef exp_func(t,tau):\r\n return np.exp(-t/tau)\r\n\t\r\nn = int(sys.argv[1])\r\n# the grid spacing is one order of magnitude less than the initial value\r\ndeltas_squared = np.linspace(10**(n),10**(n+1),num=91)\r\n\r\ntcorrs = []\r\ntcorrs_err = []\r\nfor delta_sq in deltas_squared:\r\n s = time.time()\r\n tcorr, err = tau_corr_sim(1,delta_sq,100)\r\n tcorrs.append(tcorr)\r\n tcorrs_err.append(err)\r\n print(delta_sq,tcorr,err,time.time()-s)\r\n\t\r\nnp.save('./deltas_squared_'+str(n)+'_'+str(n+1)+'.npy',deltas_squared)\r\nnp.save('./tcorrs_'+str(n)+'_'+str(n+1)+'.npy',tcorrs)\r\nnp.save('./tcorrs_err_'+str(n)+'_'+str(n+1)+'.npy',tcorrs_err)\r\n","sub_path":"SingleAngleCorrelationTimes/generate_tau_table.py","file_name":"generate_tau_table.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"215543906","text":"class Solution:\n # @param n, an integer\n # @return an integer\n def reverseBits(self, n):\n res,i = 0,0\n while i < 32:\n res <<= 1\n res += n & 1\n n = n >> 1\n i+=1\n return res","sub_path":"Week_08/reverseBits.py","file_name":"reverseBits.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"64927759","text":"from textwrap import dedent\n\nimport pytest\n\nfrom myst_parser import text_to_tokens, render_tokens, parse_text\nfrom mistletoe.block_tokenizer import tokenize_main\n\nfrom myst_parser.html_renderer import HTMLRenderer\n\n\n@pytest.fixture\ndef renderer():\n renderer = HTMLRenderer()\n with renderer:\n yield renderer\n\n\ndef test_render_tokens():\n root = text_to_tokens(\"abc\")\n assert render_tokens(root, HTMLRenderer) == \"<p>abc</p>\\n\"\n\n\ndef test_math(renderer):\n output = renderer.render(tokenize_main([\"$a=1$\"])[0])\n assert output == dedent(\"<p>$$a=1$$</p>\")\n\n\ndef test_role(renderer):\n output = renderer.render(tokenize_main([\"{name}`content`\"])[0])\n assert output == (\n '<p><span class=\"myst-role\"><code>{name}content</code></span></p>'\n )\n\n\ndef test_directive(renderer):\n output = renderer.render(tokenize_main([\"```{name} arg\\n\", \"foo\\n\", \"```\\n\"])[0])\n assert output == dedent(\n \"\"\"\\\n <div class=\"myst-directive\">\n <pre><code>{name} arg\n foo\n </code></pre></span>\n </div>\"\"\"\n )\n\n\ndef test_block_break(renderer):\n output = renderer.render(text_to_tokens(\"+++ abc\"))\n assert output.splitlines() == [\n \"<!-- myst-block-data abc -->\",\n '<hr class=\"myst-block-break\" />',\n ]\n\n\ndef test_line_comment(renderer):\n output = renderer.render(tokenize_main([r\"% abc\"])[0])\n assert output == \"<!-- abc -->\"\n\n\ndef test_target():\n output = parse_text(\"(a)=\", \"html\")\n assert output == (\n '<p><a class=\"myst-target\" href=\"#a\" title=\"Permalink to here\">(a)=</a></p>\\n'\n )\n\n\ndef test_front_matter(renderer):\n output = renderer.render(text_to_tokens(\"---\\na: 1\\nb: 2\\nc: 3\\n---\"))\n assert output.splitlines() == [\n '<div class=\"myst-front-matter\"><pre><code class=\"language-yaml\">a: 1',\n \"b: 2\",\n \"c: 3\",\n \"</code></pre></div>\",\n ]\n\n\ndef test_minimal_html_page(file_regression):\n in_string = dedent(\n \"\"\"\\\n ---\n a: 1\n ---\n (title-target)=\n # title\n\n Abc $a=1$ {role}`content` then more text\n\n +++ my break\n\n ```{directive} args\n :option: 1\n content\n ```\n\n ```python\n def func(a):\n print(\"{}\".format(a))\n ```\n\n % a comment\n\n [link to target](#title-target)\n \"\"\"\n )\n\n out_string = parse_text(\n in_string,\n \"html\",\n add_mathjax=True,\n as_standalone=True,\n add_css=dedent(\n \"\"\"\\\n div.myst-front-matter {\n border: 1px solid gray;\n }\n div.myst-directive {\n background: lightgreen;\n }\n hr.myst-block-break {\n border-top:1px dotted black;\n }\n span.myst-role {\n background: lightgreen;\n }\n \"\"\"\n ),\n )\n file_regression.check(out_string, extension=\".html\")\n","sub_path":"tests/test_renderers/test_html.py","file_name":"test_html.py","file_ext":"py","file_size_in_byte":2961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"382913800","text":"# Copyright (c) 2018 Uber Technologies, Inc.\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport utilities.units as u\nfrom utilities.files import RunManager\nfrom utilities.transformations import TransMatrix\nimport logging\nimport openvsp as vsp\nimport degen_geom as dg\nimport numpy as np\nimport os\nfrom subprocess import Popen, PIPE, STDOUT\nimport io\nfrom enum import Enum\nimport collections\nimport re\nimport math\n\n\nclass AirfoilDataLocation(Enum):\n \"\"\"\n Defines an enum for where to retrieve an airfoil\n \"\"\"\n INVALID = 0\n FILE_LOCATION = 1\n\n\nclass AirfoilReynoldsDataType(Enum):\n \"\"\"\n Defines the type of reynolds number correction information this section contains\n \"\"\"\n NONE = 0\n METHOD1 = 1\n METHOD2 = 2\n\n\nclass AirfoilFileLocationOpt:\n def __init__(self, **kwargs):\n \"\"\"\n Specifies options associated with obtaining charm airfoil file\n :param kwargs: base_directory = directory of airfoil database\n filename = specifies name of the airfoil file to retrieve, path should be relative to\n base_directory\n \"\"\"\n\n self.base_directory = kwargs.get('base_directory', os.path.join(os.path.dirname(__file__), \"charm_airfoils\"))\n \"\"\"\n directory of airfoil database, if this is not specified the \"charm_airfoils\" directory of this package will\n be used\n \"\"\"\n\n self.filename = kwargs.get('filename', None)\n \"\"\"\n Specifies name of the airfoil file to retrieve, path should be relative to :attr:`base_directory`.\n\n The format of this file is the same as the CHARM sectional properites. See the\n *2-D AIRFOIL SECTION DATA INPUT FILE (nameaf.inp)* of the CHARM user manual for details. The file should\n contain everything below the *COMMENT#1* line in the :code:`K=1,NFOIL` loop. The only modification\n to the format is that the first line should be the maximum thickness/chord value of the airfoil.\n \"\"\"\n\n def get_fullpath(self):\n \"\"\"\n Gets full path of file to read\n\n :return: path to charm airfoil section file\n \"\"\"\n return os.path.join(self.base_directory, self.filename)\n\n\nclass CharmAirfoil:\n def __init__(self, thickness, section_string, reynolds_data_type: AirfoilReynoldsDataType):\n \"\"\"\n Contains data pertaining to a CHARM airfoil\n :param thickness: thickness of the airfoil\n :param section_string: string representing the section data\n :param reynolds_data_type: reynolds number correction type this airfoil has\n \"\"\"\n self.thickness = thickness\n self.section_string = section_string\n self.reynolds_data_type = reynolds_data_type\n\n\nclass CharmAirfoilSection:\n def __init__(self, airfoil: CharmAirfoil, radius_frac):\n \"\"\"\n Contains information related to an airfoil section in CHARM\n\n The difference between a CharmAirfoilSection and a CharmAirfoil is that a CharmAirfoil is airfoil data that is\n independent of the propeller it is related to, it simply contains airfoil data formatted for CHARM.\n CharmAirfoilSection contains a CharmAirfoil as well as any details specific to a rotor, such as radial location\n :param airfoil: CHARM airfoil data at this section\n :param radius_frac: radial location normalized by prop/rotor radius of this section\n \"\"\"\n self.airfoil = airfoil\n self.radius_frac = radius_frac\n\n\nclass CharmRotorSettings:\n def __init__(self, rpm=0.0, rotor_wake_template=None, initial_collective=None, ct=None,\n default_airfoil_opts=None, merge_wings=True, nspan_override=None,\n airfoil_opts=None, iaero=1, irvflo=0, icoll=None, airfoil_r_o_Rs=None):\n \"\"\"\n\n :param rpm: revolutions per minute of the rotor\n :param rotor_wake_template: list of string lines of a rotor wake template file\n :param initial_collective: initial rotor collective in degrees\n :param ct: thrust coefficient of rotor (T/(rho*pi*R^2*(R*Omega)^2))\n :param default_airfoil_opts: default airfoil options, used if airfoil_opts are not specified\n :param merge_wings: if true, touching symmetric wings are merged into one rotor component, otherwise they are treated\n as separate rotors. If merging is disabled, make sure the rotor wake template settings are specified to not\n shed root vortices\n :param nspan_override: if not none it will be used to override the nspan field\n in the generated blade geometry file\n :param airfoil_opts: if not none, this is a list of airfoil options corresponding to\n each cross-section specified on the VSP geometry\n :param iaero: value to set IAERO to in the blade dynamics file\n :param irvflo: value to set IVRFLO to in the blade dynamics file\n :param icoll: set ICOLL variable in CHARM rotor wake file. Controls how collective is adjusted\n :param airfoil_r_o_Rs: optional array of local radius/blade radius locations of airfoil sections\n specified in `airfoil_opts`. If not specified, an attempt to use VSP will be made to locate the airfoils\n \"\"\"\n self.__rpm = rpm\n self.__rotor_wake_template = rotor_wake_template\n self.__initial_collective = initial_collective\n self.__ct = ct\n self.__default_airfoil_opts = default_airfoil_opts\n self.__merge_wings = merge_wings\n self.__nspan_override = nspan_override\n self.__airfoil_opts = [] if airfoil_opts is None else airfoil_opts\n self.__airfoil_r_o_Rs = [] if airfoil_r_o_Rs is None else airfoil_r_o_Rs\n self.__iaero = iaero\n self.__irvflo = irvflo\n self.__icoll = None\n\n @property\n def rpm(self):\n return self.__rpm\n\n @rpm.setter\n def rpm(self, rpm):\n self.__rpm = rpm\n\n @property\n def rotor_wake_template(self):\n return self.__rotor_wake_template\n\n @rotor_wake_template.setter\n def rotor_wake_template(self, rotor_wake_template):\n self.__rotor_wake_template = rotor_wake_template\n\n @property\n def initial_collective(self):\n return self.__initial_collective\n\n @initial_collective.setter\n def initial_collective(self, initial_collective):\n self.__initial_collective = initial_collective\n\n @property\n def ct(self):\n return self.__ct\n\n @ct.setter\n def ct(self, ct):\n self.__ct = ct\n\n @property\n def default_airfoil_opts(self):\n return self.__default_airfoil_opts\n\n @default_airfoil_opts.setter\n def default_airfoil_opts(self, default_airfoil_opts):\n self.__default_airfoil_opts = default_airfoil_opts\n\n @property\n def merge_wings(self):\n return self.__merge_wings\n\n @merge_wings.setter\n def merge_wings(self, merge_wings):\n self.__merge_wings = merge_wings\n\n @property\n def nspan_override(self):\n return self.__nspan_override\n\n @nspan_override.setter\n def nspan_override(self, nspan_override):\n self.__nspan_override = nspan_override\n\n @property\n def airfoil_opts(self):\n return self.__airfoil_opts\n\n @airfoil_opts.setter\n def airfoil_opts(self, airfoil_opts):\n self.__airfoil_opts = [] if airfoil_opts is None else airfoil_opts\n\n @property\n def iaero(self):\n return self.__iaero\n\n @iaero.setter\n def iaero(self, iaero):\n self.__iaero = iaero\n\n @property\n def irvflo(self):\n return self.__irvflo\n\n @irvflo.setter\n def irvflo(self, irvflo):\n self.__irvflo = irvflo\n\n @property\n def icoll(self):\n return self.__icoll\n\n @icoll.setter\n def icoll(self, icoll):\n self.__icoll = icoll\n\n @property\n def airfoil_r_o_Rs(self):\n return self.__airfoil_r_o_Rs\n\n @airfoil_r_o_Rs.setter\n def airfoil_r_o_Rs(self, airfoil_r_o_Rs):\n self.__airfoil_r_o_Rs = [] if airfoil_r_o_Rs is None else airfoil_r_o_Rs\n\n\nclass CharmRotorSettingsCollection(collections.MutableMapping, CharmRotorSettings):\n \"\"\"\n Allows a collection of rotors settings to be treated like\n a single rotor setting\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n self.store = dict()\n self.update(dict(*args, **kwargs))\n super().__init__(**kwargs)\n\n def __getitem__(self, key):\n return self.store[key]\n\n def __setitem__(self, key, value):\n self.store[key] = value\n\n def __delitem__(self, key):\n del self.store[key]\n\n def __iter__(self):\n return iter(self.store)\n\n def __len__(self):\n return len(self.store)\n\n @property\n def rpm(self):\n rpm = 0.0\n for key, rotor_setting in self.store.items():\n rpm += rotor_setting.rpm\n if len(self.store) > 0:\n rpm /= len(self.store)\n return rpm\n\n @rpm.setter\n def rpm(self, rpm):\n for key, rotor_setting in self.store.items():\n rotor_setting.rpm = rpm\n\n @property\n def rotor_wake_template(self):\n return \"\"\n\n @rotor_wake_template.setter\n def rotor_wake_template(self, rotor_wake_template):\n for key, rotor_setting in self.store.items():\n rotor_setting.rotor_wake_template = rotor_wake_template\n\n @property\n def initial_collective(self):\n initial_collective = 0.0\n for key, rotor_setting in self.store.items():\n initial_collective += rotor_setting.initial_collective\n if len(self.store) > 0:\n initial_collective /= len(self.store)\n return initial_collective\n\n @initial_collective.setter\n def initial_collective(self, initial_collective):\n for key, rotor_setting in self.store.items():\n rotor_setting.initial_collective = initial_collective\n\n @property\n def ct(self):\n ct = 0.0\n for key, rotor_setting in self.store.items():\n ct += rotor_setting.ct\n if len(self.store) > 0:\n ct /= len(self.store)\n return ct\n\n @ct.setter\n def ct(self, ct):\n for key, rotor_setting in self.store.items():\n rotor_setting.ct = ct\n\n @property\n def default_airfoil_opts(self):\n return None\n\n @default_airfoil_opts.setter\n def default_airfoil_opts(self, default_airfoil_opts):\n for key, rotor_setting in self.store.items():\n rotor_setting.default_airfoil_opts = default_airfoil_opts\n\n @property\n def merge_wings(self):\n for key, rotor_setting in self.store.items():\n if not rotor_setting.merge_wings:\n return False\n return True\n\n @merge_wings.setter\n def merge_wings(self, merge_wings):\n for key, rotor_setting in self.store.items():\n rotor_setting.merge_wings = merge_wings\n\n @property\n def nspan_override(self):\n nspan_override = 0.0\n num_rotors = 0.0\n for key, rotor_setting in self.store.items():\n if rotor_setting.nspan_override is not None:\n nspan_override += rotor_setting.nspan_override\n num_rotors += 1\n if num_rotors < 1:\n return None\n else:\n return int(round(nspan_override/num_rotors))\n\n @nspan_override.setter\n def nspan_override(self, nspan_override):\n for key, rotor_setting in self.store.items():\n rotor_setting.nspan_override = nspan_override\n\n @property\n def airfoil_opts(self):\n for key, rotor_setting in self.store.items():\n if len(rotor_setting.airfoil_opts) > 0:\n return rotor_setting.airfoil_opts\n return []\n\n @airfoil_opts.setter\n def airfoil_opts(self, opts):\n for key, rotor_setting in self.store.items():\n rotor_setting.airfoil_opts = opts\n\n @property\n def iaero(self):\n iaero = 0\n for key, rotor_setting in self.store.items():\n iaero += rotor_setting.iaero\n if len(self.store) > 0:\n iaero /= len(self.store)\n return int(iaero)\n\n @iaero.setter\n def iaero(self, iaero):\n for key, rotor_setting in self.store.items():\n rotor_setting.iaero = iaero\n\n @property\n def irvflo(self):\n irvflo = 0\n for key, rotor_setting in self.store.items():\n irvflo += rotor_setting.irvflo\n if len(self.store) > 0:\n irvflo /= len(self.store)\n return int(irvflo)\n\n @irvflo.setter\n def irvflo(self, irvflo):\n for key, rotor_setting in self.store.items():\n rotor_setting.irvflo = irvflo\n\n @property\n def icoll(self):\n return None\n\n @icoll.setter\n def icoll(self, icoll):\n for key, rotor_setting in self.store.items():\n rotor_setting.icoll = icoll\n\n @property\n def airfoil_r_o_Rs(self):\n return None\n\n @airfoil_r_o_Rs.setter\n def airfoil_r_o_Rs(self, airfoil_r_o_Rs):\n for key, rotor_setting in self.store.items():\n rotor_setting.airfoil_r_o_Rs = airfoil_r_o_Rs\n\n\nclass CharmWingInfo:\n def __init__(self, charm_le, charm_te, toc, vsp_wing_origin, vsp_origin_2_wing_origin: TransMatrix,\n span, airfoils, geom_id, num_syms, flip_rotation_direction):\n \"\"\"\n Initializes a CHARM Wing Information object\n\n :param charm_le: leading edge coordinates in charm rotor frame\n :param charm_te: trailing edge coordinates in charm rotor frame\n :param toc: thickness/chord\n :param vsp_wing_origin: x, y, z location of root chord in VSP coordinates\n :param vsp_origin_2_wing_origin: transformation matrix from default vsp origin to the wing origin\n :param span: projected wing span\n :param airfoils: list of CharmAirfoilSections\n :param geom_id: id of the wing geometry in VSP\n :param num_syms: number of planar symmetries for this wing\n :param flip_rotation_direction: boolean to indicate if the rotation direction of this wing should be reversed\n reversed\n\n \"\"\"\n self.charm_le = charm_le\n self.charm_te = charm_te\n self.vsp_wing_origin = vsp_wing_origin\n self.vsp_origin_2_wing_origin = vsp_origin_2_wing_origin\n self.toc = toc\n self.span = span\n self.airfoils = airfoils\n self.geom_id = geom_id\n self.num_syms = num_syms\n self.flip_rotation_direction = flip_rotation_direction\n\n\ndef create_charm_blade_geom_file_from_propeller(prop_dg: dg.DegenComponent, unit_factor=u.in2ft,\n bg2charm_path=os.path.join(os.path.dirname(__file__),\n \"charm_fortran_utilities/build/bg2charm_thick\"),\n nspan_override=None, **kwargs):\n \"\"\"\n Create charm blade geometry file (*bg file)\n :param prop_dg: degen object of propeller to create bg file from\n :param unit_factor: unit conversion factor to go from units in vsp to feet\n :param bg2charm_path: path to bg2charm executable\n :param nspan_override: number of spanwise segments for the vortext lattice override\n :return: string of bg file contents\n \"\"\"\n\n # Use first surface from first copy since all blades should be the same\n prop_blade = prop_dg.copies[0][0]\n thickness = np.array(prop_blade.sticks[0].toc)\n\n # Transform degen geom output into charm coordinates\n leading_edge_charm, trailing_edge_charm = remove_le_te_transformations(prop_blade)\n\n # Create input settings for CHARM te and le transformation utilities\n # For CHARM x is out the radius and y is leading edge to trailing edge\n # The untransformed vsp blade has y out the radius and x going leading edge to trailing edge. Therefore, we need\n # to swap the x/z axes before running the CHARM utility\n # z is positive in the down direction\n\n data = [] # lex ley lez tex tey tez toc\n for i in range(leading_edge_charm.shape[1]):\n row = [leading_edge_charm[1, i], leading_edge_charm[2, i], leading_edge_charm[0, i],\n trailing_edge_charm[1, i], trailing_edge_charm[2, i], trailing_edge_charm[0, i],\n thickness[i]]\n data.append(row)\n\n data = np.array(data)\n\n # Run the utility in a temporary directory\n return create_charm_blade_geom_file(data[:, 0:3].T, data[:, 3:6].T, thickness, unit_factor=unit_factor,\n bg2charm_path=bg2charm_path, nspan_override=nspan_override)\n\n\ndef create_charm_blade_geom_file_from_wing(wing_info: CharmWingInfo, unit_factor=u.in2ft,\n bg2charm_path=os.path.join(os.path.dirname(__file__),\n \"charm_fortran_utilities/build/bg2charm_thick\"),\n nspan_override=None, **kwargs):\n \"\"\"\n\n :param wing_info: wing info object\n :param unit_factor: unit conversion factor to go from units in vsp to feet\n :param bg2charm_path: path to bg2charm executable\n :param nspan_override: number of spanwise segments for the vortext lattice override\n :return: string of bg file contents\n \"\"\"\n return create_charm_blade_geom_file(wing_info.charm_le, wing_info.charm_te, wing_info.toc, unit_factor=unit_factor,\n bg2charm_path=bg2charm_path, nspan_override=nspan_override)\n\n\ndef create_charm_blade_geom_file(leading_edge, trailing_edge, thickness, unit_factor=u.in2ft,\n bg2charm_path=os.path.join(os.path.dirname(__file__),\n \"charm_fortran_utilities/build/bg2charm_thick\"),\n nspan_override=None):\n \"\"\"\n Creates a CHARM blade geometry input file\n\n :param leading_edge: leading points (x,y,z) each point is a column\n :param trailing_edge: trailing edge points (x,y,z) each point is a column\n :param thickness: thickness/chord array\n :param unit_factor: unit conversion factor to go from units in vsp to feet\n :param bg2charm_path: path to bg2charm executable\n :param nspan_override: number of spanwise segments for the vortext lattice override\n :return: string of blade geometry file\n \"\"\"\n\n logger = logging.getLogger(__name__)\n\n data = np.concatenate((leading_edge.T, trailing_edge.T, thickness.reshape(len(thickness), 1)), 1)\n\n nseg = data.shape[0]-1\n if nseg > 50:\n raise ValueError(\"Number of segments exceeds 50, incompatible with CHARM. Reduce tesselation.\")\n\n bg_file_contents = None\n with RunManager() as rd:\n np.savetxt(\"blade.inp\", data, delimiter=' ', header=' lex ley lez tex tey tez toc', comments='*', fmt='%.10f')\n\n # build up command inputs for utility\n cmd = \"blade.inp\\n\"\n cmd += \"bladebg.inp\\n\"\n cmd += \"4\\n\"\n cmd += \"0\\n\"\n cmd += \"{:10f}\\n\".format(unit_factor)\n\n p = Popen([bg2charm_path], stdout=PIPE, stdin=PIPE, stderr=STDOUT, universal_newlines=True)\n stdout = p.communicate(input=cmd)[0]\n\n # Read contents into memory\n with open(\"bladebg.inp\", \"r\") as f:\n bg_file_contents = f.read()\n\n # If the nspan override is not none, modified the file contents\n if nspan_override is not None:\n # Warn if override is not a valid value\n if abs(nspan_override) < 2 or abs(nspan_override) > 100 or abs(nspan_override) < nseg:\n logger.warn(\"nspan override is invalid. using nspan=50\")\n nspan_override = 50\n\n re_expr = re.compile(r\"(^NCHORD\\s+NSPAN\\s+ICOS\\s?\\n\\s+[0-9]+\\s+)([0-9]+)\\s\", re.MULTILINE)\n bg_file_contents = re.sub(re_expr, r\"\\g<1>{}\".format(nspan_override), bg_file_contents)\n\n return bg_file_contents\n\n\ndef create_single_wing_info(wing_dg: dg.DegenComponent, settings: CharmRotorSettingsCollection):\n \"\"\"\n Creates wing information object from degen geom component\n\n :param wing_dg: degen object of wing to create bg file from\n :param settings: rotor settings for this wing component\n :return: wing information objects\n \"\"\"\n\n # Determine if the wing components should be connected as one\n leading_edges = []\n trailing_edges = []\n tocs = []\n transmats = []\n u_vals = []\n connected = False\n if wing_dg.max_copies == 2 and settings.merge_wings:\n wing1 = wing_dg.copies[0][0] # Get first wing\n wing2 = wing_dg.copies[1][0] # Get second wing\n\n # See if both leading edge and trailing edge are connected\n le1 = wing1.sticks[0].le\n te1 = wing1.sticks[0].te\n toc1 = wing1.sticks[0].toc\n u1 = wing1.sticks[0].u\n le2 = wing2.sticks[0].le\n te2 = wing2.sticks[0].te\n toc2 = wing2.sticks[0].toc\n u2 = wing2.sticks[0].u\n\n arr1 = np.append(np.array(le1), np.array([toc1, u1]).T, 1)\n arr2 = np.append(np.array(le2), np.array([toc2, u2]).T, 1)\n\n connected_le = _connect_arrays(arr1, arr2)\n connected_te = _connect_arrays(np.array(te1), np.array(te2))\n\n connected = connected_le is not None and connected_te is not None\n\n if connected:\n leading_edges.append(connected_le[:, 0:3])\n tocs.append(connected_le[:, 3])\n trailing_edges.append(connected_te)\n transmats.append(wing1.transmat)\n u_vals.append(connected_le[:, 4])\n\n if not connected:\n for i in range(wing_dg.max_copies):\n wing = wing_dg.copies[i][0]\n leading_edges.append(np.array(wing.sticks[0].le))\n trailing_edges.append(np.array(wing.sticks[0].te))\n transmats.append(wing.transmat)\n tocs.append(np.array(wing.sticks[0].toc))\n u_vals.append(np.array(wing.sticks[0].u))\n\n wing_infos = []\n for i in range(len(leading_edges)):\n le_vsp = leading_edges[i]\n te_vsp = trailing_edges[i]\n toc = tocs[i]\n inverse_vsp_tmat = transmats[i].get_inverse_transform()\n\n le_vsp_untrans = inverse_vsp_tmat.apply_transformation(le_vsp.T)\n\n # Check to see if the root le the origin, if not transform it to be so\n t_vsp2origin = TransMatrix(inverse_vsp_tmat.mat)\n if not _is_same_point(np.zeros(3), le_vsp_untrans[:, 0]):\n wing_origin2vsp_origin = TransMatrix()\n wing_origin2vsp_origin.set_translations(-1.0*le_vsp_untrans[:, 0])\n t_vsp2origin.mat = np.dot(wing_origin2vsp_origin.mat, t_vsp2origin.mat)\n\n t_vsp2charm_blade = TransMatrix()\n t_vsp2charm_blade.mat[0, 0:3] = np.array([0.0, 1.0, 0.0])\n t_vsp2charm_blade.mat[1, 0:3] = np.array([1.0, 0.0, 0.0])\n t_vsp2charm_blade.mat[2, 0:3] = np.array([0.0, 0.0, -1.0])\n\n le_charm = t_vsp2charm_blade.apply_transformation(t_vsp2origin.apply_transformation(le_vsp.T))\n te_charm = t_vsp2charm_blade.apply_transformation(t_vsp2origin.apply_transformation(te_vsp.T))\n vsp_origin = le_vsp.T[:, 0]\n\n span = abs(le_vsp_untrans[1, 0] - le_vsp_untrans[1, -1])\n\n # Get airfoils\n airfoils = []\n specified_airfoils = settings[i].airfoil_opts\n airfoil_r_o_Rs = settings[i].airfoil_r_o_Rs\n\n if len(airfoil_r_o_Rs) < 2:\n airfoil_r_o_Rs = []\n for u_index in range(len(u_vals[i])):\n u = u_vals[i][u_index]\n if math.isclose(u, round(u)):\n local_span = 0.75 * le_charm[0, u_index] + 0.25 * te_charm[0, u_index]\n airfoil_r_o_Rs.append(local_span / span)\n\n for irad, roR in enumerate(airfoil_r_o_Rs):\n af_opts = settings[i].default_airfoil_opts if irad >= len(specified_airfoils) else specified_airfoils[irad]\n airfoil = get_airfoil(AirfoilDataLocation.FILE_LOCATION, af_opts)\n airfoils.append(CharmAirfoilSection(airfoil=airfoil, radius_frac=roR))\n\n num_syms = _determine_num_symm(trans_orig=wing_dg.copies[0][0].transmat,\n trans_copy=wing_dg.copies[i][0].transmat)\n flip_rotation = False\n if not wing_dg.copies[i][0].flip_normal:\n flip_rotation = True\n wing_info = CharmWingInfo(charm_le=le_charm, charm_te=te_charm, toc=toc, vsp_wing_origin=vsp_origin,\n vsp_origin_2_wing_origin=t_vsp2origin, span=span, airfoils=airfoils,\n geom_id=wing_dg.copies[i][0].geom_id,\n num_syms=num_syms, flip_rotation_direction=flip_rotation)\n wing_infos.append(wing_info)\n\n return wing_infos\n\n\ndef create_all_wing_infos(degen_mgr: dg.DegenGeomMgr, settings: CharmRotorSettingsCollection):\n \"\"\"\n Creates a list of wing info objects from all wing objects in the degen geom manager\n :param degen_mgr: degen geom manager\n :param settings: settings for all wing objects\n :return: list of wing info objects\n \"\"\"\n wing_infos = []\n for wing_id, degen_component in degen_mgr.degen_objs.items():\n typ_name = vsp.GetGeomTypeName(wing_id)\n if typ_name != \"Wing\":\n continue\n wing_infos.extend(create_single_wing_info(degen_component, settings[wing_id]))\n return wing_infos\n\n\ndef remove_le_te_transformations(degen_blade: dg.DegenGeom):\n \"\"\"\n Removes transformations from leading and trailing edges of a blade\n :param degen_blade: degen geom object of a single blade\n :return: leading edge and trailing edge coordinates without transformations\n \"\"\"\n\n transform_inverse = degen_blade.transmat.get_inverse_transform()\n leading_edge_original = np.array(degen_blade.sticks[0].le)\n trailing_edge_original = np.array(degen_blade.sticks[0].te)\n\n leading_edge_charm = transform_inverse.apply_transformation(leading_edge_original.T)\n trailing_edge_charm = transform_inverse.apply_transformation(trailing_edge_original.T)\n\n rotation_deg = vsp.GetParmVal(degen_blade.geom_id, \"Rotate\", \"Design\")\n reverse_flag = vsp.GetParmVal(degen_blade.geom_id, \"ReverseFlag\", \"Design\")\n axis = np.array([-1.0, 0.0, 0.0])\n if reverse_flag > 0.5:\n axis[0] *= -1.0\n rot_mat = TransMatrix.create_from_axis_angle(axis, rotation_deg * u.deg2rad).get_inverse_transform()\n\n # if reversed, make y negative y and rotate 180 degrees about x\n if reverse_flag:\n ynegy = TransMatrix()\n ynegy.mat[1, 1] = -1.0\n rotx = TransMatrix.create_from_axis_angle(np.array([1.0, 0.0, 0.0]), angle=180*u.deg2rad)\n rot_mat.mat = np.dot(ynegy.mat, rot_mat.mat)\n rot_mat.mat = np.dot(rotx.mat, rot_mat.mat)\n\n leading_edge_charm = rot_mat.apply_transformation(leading_edge_charm)\n trailing_edge_charm = rot_mat.apply_transformation(trailing_edge_charm)\n\n return leading_edge_charm, trailing_edge_charm\n\n\ndef create_rigid_blade_dynamics_file(radius, unit_factor=u.in2ft, iaero=1, irvflo=0):\n \"\"\"\n Creates a rigid blade geometry file for degenerate propeller component\n :param radius: radius of propeller (span of wing)\n :param unit_factor: conversion factor to convert to feet\n :param iaero: value of IAERO variable in blade dyanmics file. Controls used for computing lift on rotor.\n :param irvflo: value of IRVFLO variable in blade dyanmics file. Controls used for computing reverse flow lift on rotor.\n :return:\n \"\"\"\n\n # Get propeller info\n with io.StringIO() as bd_file:\n\n def write_array(arr):\n for i, el in enumerate(arr):\n if i > 0 and i % 10 == 0:\n bd_file.write(\"\\n\")\n bd_file.write(\"{:8.3f}\".format(el))\n bd_file.write(\"\\n\")\n\n # Write out title line\n bd_file.write(\"bladebd.inp\\n\")\n\n # For rigid blade set ISTRM = 0\n bd_file.write(\" ISTRM\\n\")\n bd_file.write(\" 0\\n\")\n\n # Not sure what these do, but copying Dan\n bd_file.write(\"ISTRIP IFPC IAERO\\n\")\n bd_file.write(\" -1 0 {:d}\\n\".format(iaero))\n bd_file.write(\"ICOMP IRVFLO ISTFLO\\n\")\n bd_file.write(\" 1 {:d} 1\\n\".format(irvflo))\n bd_file.write(\" IART HINGE PRECONE\\n\")\n bd_file.write(\" 0 0.000 0.000\\n\")\n bd_file.write(\" NMODE\\n\")\n bd_file.write(\" 1\\n\")\n bd_file.write(\" NMDFLP NMDTOR NMDLAG NMDELG\\n\")\n bd_file.write(\" 1 0 0 0\\n\")\n bd_file.write(\" IFXMDE\\n\")\n bd_file.write(\" 1\\n\")\n bd_file.write(\"IMDFIX NPSIFX\\n\")\n bd_file.write(\" 1 20\\n\")\n bd_file.write(\"AMP\\n\")\n bd_file.write(\" 20*0.0\\n\")\n\n bd_file.write(\" FREQMD GMASS for Mode 1\\n\")\n bd_file.write(\" 1.000 1000.0\\n\")\n bd_file.write(\" NRBARS\\n\")\n bd_file.write(\" 51\\n\")\n\n bd_file.write(\" RBARS(IR), IR=1,NRBARS\\n\")\n\n # Compute rbars\n nrbars = 51\n rbars = np.array([float(i)/(nrbars-1) for i in range(nrbars)])\n write_array(rbars)\n\n bd_file.write(\" Rigid flap mode\\n\")\n write_array(np.zeros(nrbars))\n write_array(np.zeros(nrbars))\n\n write_array(rbars*radius*unit_factor)\n write_array(np.zeros(nrbars))\n write_array(np.ones(nrbars))\n write_array(np.zeros(nrbars))\n return bd_file.getvalue()\n\n\ndef create_airfoil_file(airfoils):\n \"\"\"\n Creates a CHARM *af.inp file given a list of airfoils\n :param airfoils: airfoil list\n :return: string of airfoil file contents\n \"\"\"\n\n # Check that type of reynolds data is consistent across all airfoils\n if len(airfoils) == 0:\n return\n reyn_type = airfoils[0].airfoil.reynolds_data_type\n for af in airfoils:\n if af.airfoil.reynolds_data_type != reyn_type:\n raise ValueError(\"All airfoils must have same reynolds number correction information type\")\n\n with io.StringIO() as af_file:\n num_airfoils = len(airfoils)\n if num_airfoils < 2:\n raise ValueError(\"must have at least two airfoils in order to be valid\")\n if num_airfoils > 20:\n raise ValueError(\"CHARM cannot handle more than 20 airfoils\")\n\n ithick = 0 # Assuming no thickness profiles for sections\n af_file.write(\"{:4} {:3} {:3}\\n\".format(num_airfoils, ithick, reyn_type.value))\n\n # Write out radial locations\n af_file.write(\" \")\n for af in airfoils:\n af_file.write(\" {:6.4f}\".format(af.radius_frac))\n af_file.write(\"\\n\")\n\n # Write out thickness\n af_file.write(\" \")\n for af in airfoils:\n af_file.write(\" {:6.4f}\".format(af.airfoil.thickness))\n af_file.write(\"\\n\")\n\n # Write out section data\n for af in airfoils:\n af_file.write(\"COMMENT#1\\n\")\n af_file.write(af.airfoil.section_string)\n\n return af_file.getvalue()\n\n\ndef get_airfoil(af_data_location: AirfoilDataLocation, af_options=None):\n \"\"\"\n Gets an airfoil from the specified data location\n :param af_data_location: enum indicating the type of location from which the data should be retrieved\n :param af_options: options related to retrieving airfoil, if None is specified the default options will be used\n :return: Charm airfoil section\n \"\"\"\n\n if af_data_location == AirfoilDataLocation.FILE_LOCATION:\n if af_options is None:\n af_options = AirfoilFileLocationOpt(filename='0012.inp')\n return _get_airfoil_from_file(af_options)\n else:\n raise ValueError(\"Unhandled data location: {}\".format(af_data_location))\n\n\ndef create_airfoil_sections(prop_id, rotor_setting: CharmRotorSettingsCollection):\n \"\"\"\n Creates a set CHARM airfoil sections based off of prop id\n :param prop_id: vsp geom id for propeller of interest\n :param rotor_setting: rotor settings for a single rotor. This is a :class:`CharmRotorSettingsCollection` object\n because it includes settings for symmetric copies\n :return: charm airfoil sections\n \"\"\"\n xsec_surf_id = vsp.GetXSecSurf(prop_id, 0)\n num_xsec = vsp.GetNumXSec(xsec_surf_id)\n\n airfoils = []\n\n specified_airfoils = rotor_setting[0].airfoil_opts\n default_af_opts = rotor_setting[0].default_airfoil_opts\n airfoil_r_o_Rs = rotor_setting[0].airfoil_r_o_Rs\n\n if len(airfoil_r_o_Rs) < 2:\n airfoil_r_o_Rs = []\n for i in range(num_xsec):\n xsec_id = vsp.GetXSec(xsec_surf_id, i)\n rad_frac = vsp.GetParmVal(vsp.GetXSecParm(xsec_id, \"RadiusFrac\"))\n airfoil_r_o_Rs.append(rad_frac)\n\n for irad, roR in enumerate(airfoil_r_o_Rs):\n af_opts = default_af_opts if irad >= len(specified_airfoils) else specified_airfoils[irad]\n charm_af = get_airfoil(AirfoilDataLocation.FILE_LOCATION, af_options=af_opts)\n charm_af_sect = CharmAirfoilSection(airfoil=charm_af, radius_frac=roR)\n airfoils.append(charm_af_sect)\n\n return airfoils\n\n\ndef create_rotor_wake_file_from_template(blade_degens, rotor_settings: CharmRotorSettings, num_psi,\n num_syms, unit_factor=u.in2ft):\n \"\"\"\n Modifies rotor wake template file and updates it with proper position of propeller/rotor along with\n input settings\n\n :param blade_degens: list of degen geoms for all of the blades associated with this prop/rotor\n :param rotor_settings: settings for this propeller/rotor\n :param num_psi: number of azimuthal points in CHARM computation, required to determine precision of azimuthal offset\n :param num_syms: number of planar symmetries from original copy to this copy\n :param unit_factor: factor to convert from vsp units to CHARM units\n :return: string containing modified rotor wake file\n \"\"\"\n\n # Get number of blades\n num_blades = len(blade_degens)\n\n # Compute radians per second\n omega = rotor_settings.rpm * u.rpm2rad_s\n\n # Compute positioning\n prop_info = vsp.get_single_propeller_info(blade_degens[0])\n\n vsp_rot_angle = vsp.GetParmVal(blade_degens[0].geom_id, \"Rotate\", \"Design\")\n\n # CHARM rotor to propeller transformation\n phi_offset = -90.0\n phi_offset_sym_dir = 1.0\n if num_syms % 2 == 1:\n phi_offset_sym_dir = -1.0\n charmrotor2propeller = TransMatrix(np.dot(TransMatrix.create_from_axis_angle([1.0, 0.0, 0.0],\n phi_offset_sym_dir*phi_offset*u.deg2rad).mat,\n TransMatrix.create_from_axis_angle(np.array([0, 1.0, 0]), -90.0*u.deg2rad).mat))\n\n # CHARM Body Frame to vsp Frame\n charm2vsp = TransMatrix()\n charm2vsp.mat[0, 0] = -1.0\n charm2vsp.mat[2, 2] = -1.0\n\n # VSP Frame to CHARM Body Frame\n vsp2charm = charm2vsp.get_inverse_transform()\n\n # Compute transform from charm blade frame to vsp coordinates\n charm2vspprop = TransMatrix(np.dot(charm2vsp.mat, charmrotor2propeller.mat))\n\n # Apply vsp transformation matrix\n vsp_trans = TransMatrix(np.dot(prop_info.transmat.mat,\n TransMatrix.create_from_axis_angle(\n np.array([1.0*prop_info.rotation_direction, 0.0, 0.0]),\n vsp_rot_angle*u.deg2rad*phi_offset_sym_dir).mat))\n final_trans_mat = TransMatrix(np.dot(vsp_trans.mat, charm2vspprop.mat))\n\n # Convert back to charm aircraft coordinates\n final_trans_mat.mat = np.dot(vsp2charm.mat, final_trans_mat.mat)\n\n # Get rotation angles\n xrot, yrot, zrot = final_trans_mat.get_angles_zxy()\n\n # Limit zrotation to an acceptable increment\n dpsi = 360.0/float(num_psi)\n zrot = round(zrot/dpsi) * dpsi\n\n itilt = 2\n irotat = prop_info.rotation_direction\n\n charm_trans = TransMatrix()\n charm_trans.mat[0, 0] = -1.0\n charm_trans.mat[2, 2] = -1.0\n\n # Create positioning string\n pos_string = \"{:2d} {:8.3f} {:8.3f} {:8.3f} {xrot:8.3f} {yrot:8.3f} {zrot:8.3f} {itilt:3d}\\n\".format(irotat,\n *charm_trans.apply_transformation(prop_info.hub_center*unit_factor).reshape(3),\n xrot=xrot, yrot=yrot,\n zrot=zrot,\n itilt=itilt)\n\n rw_file = rotor_settings.rotor_wake_template\n rw_file[2] = \"{:3d} {:8.4f}\\n\".format(num_blades, omega)\n rw_file[4] = pos_string\n\n rw_file = __modify_rotor_wake_template(rw_file, rotor_settings)\n\n with io.StringIO() as f:\n f.writelines(rw_file)\n return f.getvalue()\n\n\ndef create_wing_rotor_wake_file_from_template(wing_info: CharmWingInfo, wing_settings: CharmRotorSettings, num_psi,\n unit_factor=u.in2ft):\n \"\"\"\n Creates a rotor wake file for a wing described by a wing info object and a rotor settings\n :param wing_info: wing information object for this wing\n :param wing_settings: settings for this wing\n :param num_psi: number of azimuthal points in CHARM computation, required to determine precision of azimuthal offset\n :param unit_factor: factor to convert from vsp units to CHARM units\n :return: string containing modified rotor wake file\n \"\"\"\n\n # Get number of blades\n num_blades = 1\n\n # Compute radians per second\n omega = wing_settings.rpm * u.rpm2rad_s\n\n # Compute positioning\n phi_offset_dir = 1.0\n if wing_info.num_syms % 2 == 1:\n phi_offset_dir = -1.0\n charmrotor2wing = TransMatrix.create_from_axis_angle([0.0, 0.0, 1.0], 90.0*phi_offset_dir*u.deg2rad)\n\n # CHARM Body Frame to vsp Frame\n charm2vsp = TransMatrix()\n charm2vsp.mat[0, 0] = -1.0\n charm2vsp.mat[2, 2] = -1.0\n\n # VSP Frame to CHARM Body Frame\n vsp2charm = charm2vsp.get_inverse_transform()\n\n # Compute transform from charm blade frame to vsp coordinates\n charm2vspwing = TransMatrix(np.dot(charm2vsp.mat, charmrotor2wing.mat))\n\n # Apply vsp transformation matrix\n vsp_trans = wing_info.vsp_origin_2_wing_origin.get_inverse_transform()\n final_trans_mat = TransMatrix(np.dot(vsp_trans.mat, charm2vspwing.mat))\n\n # Convert back to charm aircraft coordinates\n final_trans_mat.mat = np.dot(vsp2charm.mat, final_trans_mat.mat)\n\n # Get rotation angles\n xrot, yrot, zrot = final_trans_mat.get_angles_zxy()\n\n # Limit zrotation to an acceptable increment\n dpsi = 360.0/float(num_psi)\n zrot = round(zrot/dpsi) * dpsi\n\n itilt = 2\n irotat = 1\n if wing_info.flip_rotation_direction:\n irotat = -1\n\n charm_trans = TransMatrix()\n charm_trans.mat[0, 0] = -1.0\n charm_trans.mat[2, 2] = -1.0\n\n # Create positioning string\n pos_string = \"{:2d} {:8.3f} {:8.3f} {:8.3f} {xrot:8.3f} {yrot:8.3f} {zrot:8.3f} {itilt:3d}\\n\".format(irotat,\n *charm_trans.apply_transformation(wing_info.vsp_wing_origin*unit_factor).reshape(3),\n xrot=xrot, yrot=-yrot,\n zrot=zrot,\n itilt=itilt)\n\n rw_file = wing_settings.rotor_wake_template\n rw_file[2] = \"{:3d} {:8.4f}\\n\".format(num_blades, omega)\n rw_file[4] = pos_string\n\n rw_file = __modify_rotor_wake_template(rw_file, wing_settings)\n\n with io.StringIO() as f:\n f.writelines(rw_file)\n return f.getvalue()\n\n\ndef build_default_rotor_settings(degen_mgr: dg.DegenGeomMgr, default_rpm=0.0, default_template=None):\n \"\"\"\n Builds up a default collection of rotor settings\n\n :param degen_mgr: degen_mgr with objects desired for this charm run\n :param default_rpm: this value will be used as the rpm value for all rotors\n :param default_template: this will used as the template file by default for all rotors/propellers\n :return: CharmRotorsSettingsCollection object\n \"\"\"\n\n # provided default template current template is empty\n if default_template is None:\n with open(os.path.join(os.path.dirname(__file__), \"test\", \"prop_rw.inp\")) as f:\n default_template = f.readlines()\n\n # Loop over each geom id\n default_settings = CharmRotorSettingsCollection()\n for geom_id, dg_component in degen_mgr.degen_objs.items():\n # If this geom is not a prop, move on to next item\n typename = vsp.GetGeomTypeName(geom_id)\n if typename != \"Propeller\":\n continue\n # Create a collection of settings for this geom\n settings_collection = CharmRotorSettingsCollection()\n\n # Create a new setting for each copy in the geom\n for copy_num in dg_component.copies.keys():\n settings_collection[copy_num] = CharmRotorSettings()\n\n default_settings[geom_id] = settings_collection\n\n default_settings.rpm = default_rpm\n default_settings.rotor_wake_template = default_template\n\n return default_settings\n\n\ndef build_default_wing_settings(degen_mgr: dg.DegenGeomMgr, default_template=None):\n \"\"\"\n Builds a default settings collection of rotor settings for wing components\n\n :param degen_mgr: degen geom manager with objects desired for this charm run\n :param default_template: this will be used as the default template for all wing like objects\n :return: CharmRotorSettingsCollection object with settings for wing components\n \"\"\"\n # provided default template current template is empty\n if default_template is None:\n with open(os.path.join(os.path.dirname(__file__), \"test\", \"prop_rw.inp\")) as f:\n default_template = f.readlines()\n\n # Loop over each geom id\n default_settings = CharmRotorSettingsCollection()\n for geom_id, dg_component in degen_mgr.degen_objs.items():\n # If this geom is not a prop, move on to next item\n typename = vsp.GetGeomTypeName(geom_id)\n if typename != \"Wing\":\n continue\n # Create a collection of settings for this geom\n settings_collection = CharmRotorSettingsCollection()\n\n # Create a new setting for each copy in the geom\n for copy_num in dg_component.copies.keys():\n settings_collection[copy_num] = CharmRotorSettings()\n\n default_settings[geom_id] = settings_collection\n\n default_settings.rpm = 0.0\n default_settings.rotor_wake_template = default_template\n\n return default_settings\n\n\ndef create_rotor_file_list(degen_mgr: dg.DegenGeomMgr, settings: CharmRotorSettingsCollection, num_psi,\n unit_factor=u.in2ft, **kwargs):\n \"\"\"\n Creates a list of input files for charm based off of degen geom objects and rotor settings\n :param degen_mgr: degen objects containing components to export to charm\n :param settings: rotor settings relating to each rotor to be exported to charm\n :param num_psi: number of azimuthal points in CHARM computation\n :param unit_factor: unit conversion factor to get from vsp units to feet\n :return: dictionary of filename, file contents to write to disk, dictionary of rotorname to input filenames to be\n written in the run characteristics input file\n \"\"\"\n\n rotor_files = {}\n files_to_write = {}\n for geom_count, (rotor_id, rotor_settings) in enumerate(settings.items()):\n # Create BG File\n bg_file = create_charm_blade_geom_file_from_propeller(degen_mgr.degen_objs[rotor_id], unit_factor=unit_factor,\n nspan_override=rotor_settings.nspan_override, **kwargs)\n\n # Create BD File\n prop_info = vsp.get_single_propeller_info(degen_mgr.degen_objs[rotor_id].copies[0][0])\n bd_file = create_rigid_blade_dynamics_file(prop_info.diameter/2.0, unit_factor=unit_factor,\n iaero=rotor_settings.iaero, irvflo=rotor_settings.irvflo)\n\n # Create Airfoil Files\n airfoils = create_airfoil_sections(rotor_id, rotor_settings)\n af_file = create_airfoil_file(airfoils)\n\n # Add blade specific files to files to write list based off of geom name\n basename = vsp.GetGeomName(rotor_id) + \"_{:03}\".format(geom_count)\n bg_file_name = _cleanup_filename_for_charm(basename + \"bg.inp\")\n bd_file_name = _cleanup_filename_for_charm(basename + \"bd.inp\")\n af_file_name = _cleanup_filename_for_charm(basename + \"af.inp\")\n\n files_to_write[bg_file_name] = bg_file\n files_to_write[bd_file_name] = bd_file\n files_to_write[af_file_name] = af_file\n\n # Create individual rotor specific files\n orig_trans_mat = degen_mgr.degen_objs[rotor_id].copies[0][0].transmat\n for rotor_count, rotor_setting in rotor_settings.items():\n # Create the rotor wake file\n copy_trans_mat = degen_mgr.degen_objs[rotor_id].copies[rotor_count][0].transmat\n num_syms = _determine_num_symm(trans_orig=orig_trans_mat, trans_copy=copy_trans_mat)\n rw_file = create_rotor_wake_file_from_template(degen_mgr.degen_objs[rotor_id].copies[rotor_count],\n rotor_settings=rotor_setting, num_psi=num_psi,\n unit_factor=unit_factor, num_syms=num_syms)\n\n rotor_base_name = _cleanup_filename_for_charm(basename + \"_{:03}\".format(rotor_count))\n rw_file_name = _cleanup_filename_for_charm(basename + \"_{:03}rw.inp\".format(rotor_count))\n files_to_write[rw_file_name] = rw_file\n\n rotor_files[rotor_base_name] = [rw_file_name, bg_file_name, bd_file_name, af_file_name, \"none\"]\n\n return files_to_write, rotor_files\n\n\ndef create_wing_file_list(wing_infos, settings: CharmRotorSettings, num_psi, unit_factor=u.in2ft, **kwargs):\n \"\"\"\n\n :param wing_infos: wing info objects\n :param settings: wing settings\n :param num_psi: azimuthal resolution\n :param unit_factor: unit conversion factor from vsp units to charm units\n :param kwargs:\n :return: files to write, and file list for run characteristics file\n \"\"\"\n\n wing_infos_dict = {}\n for wing_info in wing_infos:\n if wing_info.geom_id in wing_infos_dict:\n wing_infos_dict[wing_info.geom_id].append(wing_info)\n else:\n wing_infos_dict[wing_info.geom_id] = [wing_info]\n\n rotor_files = {}\n files_to_write = {}\n for geom_count, (wing_id, wing_info_list) in enumerate(wing_infos_dict.items()):\n for wing_count, wing_info in enumerate(wing_info_list):\n # Create BG File\n bg_file = create_charm_blade_geom_file_from_wing(wing_info, unit_factor=unit_factor,\n nspan_override=settings[wing_id][wing_count].nspan_override,\n **kwargs)\n\n # Create BD File\n bd_file = create_rigid_blade_dynamics_file(wing_info.span, unit_factor=unit_factor,\n iaero=settings[wing_id][wing_count].iaero,\n irvflo=settings[wing_id][wing_count].irvflo)\n\n # Create Airfoil Files\n af_file = create_airfoil_file(wing_info.airfoils)\n\n # Add blade specific files to files to write list based off of geom name\n basename = vsp.GetGeomName(wing_id) + \"_{:03}_{:03}\".format(geom_count, wing_count)\n bg_file_name = _cleanup_filename_for_charm(basename + \"bg.inp\")\n bd_file_name = _cleanup_filename_for_charm(basename + \"bd.inp\")\n af_file_name = _cleanup_filename_for_charm(basename + \"af.inp\")\n\n files_to_write[bg_file_name] = bg_file\n files_to_write[bd_file_name] = bd_file\n files_to_write[af_file_name] = af_file\n\n # Create the rotor wake file\n rw_file = create_wing_rotor_wake_file_from_template(wing_info, settings[wing_id][wing_count],\n num_psi=num_psi, unit_factor=unit_factor)\n\n rw_file_name = _cleanup_filename_for_charm(basename + \"rw.inp\")\n files_to_write[rw_file_name] = rw_file\n\n rotor_files[basename] = [rw_file_name, bg_file_name, bd_file_name, af_file_name, \"none\"]\n\n return files_to_write, rotor_files\n\n\ndef build_run_characteristics_file_from_template(rotor_files, template_filename=None, template_file=None, num_psi=None,\n velocity=None, rotation_rates=None, pitch=None):\n \"\"\"\n Uses a template run characteristics file to create a run characteristic file that is updated with\n all of the rotor filenames that are input\n\n :param rotor_files: dictionary with key of rotor name and value of list of input files for that rotor\n :param template_filename: filename of run characteristics file template (will be open in read mode)\n :param template_file: file like object (something from io.IOBase) that can be read\n :param num_psi: number of azimuthal points for charm calculation\n :param velocity: velocity vector (ft/s)\n :param rotation_rates: rotational rates (P, Q, R)\n :param pitch: pitch in degrees, vector length matching the number of aircraft\n :return: CHARM run characteristics file updated with the input list of rotor files\n \"\"\"\n\n # Check that both template file and filename are not None\n if template_file is None and template_filename is None:\n raise ValueError(\"template_file and template_filename cannot both be None\")\n\n # Determine if a template file object exists, if not then open template filename\n close_file = False\n if template_file is None:\n close_file = True\n template_file = open(template_filename, 'r')\n\n run_char_file = []\n try:\n template_file.seek(0)\n run_char_file = template_file.readlines()\n finally:\n if close_file:\n template_file.close()\n\n # Create list of lines for all of the rotor files\n file_string_list = []\n for rotorname, file_list in rotor_files.items():\n file_string_list.append(\"INPUT FILENAMES for {}\\n\".format(rotorname))\n for filename in file_list:\n file_string_list.append(\" {}\\n\".format(filename))\n\n # Modify the input for number of rotors\n num_rotors = len(rotor_files)\n\n # Find line with NROTOR\n for line_num in range(len(run_char_file)):\n line = run_char_file[line_num]\n if \"NROTOR\" in line:\n nrotor_line_num = line_num + 1\n data = run_char_file[nrotor_line_num].split()\n template_num_rotors = int(data[0])\n new_data_line = \" {:3} \".format(num_rotors)\n if len(data) > 1:\n new_data_line += data[1]\n new_data_line += \"\\n\"\n run_char_file[nrotor_line_num] = new_data_line\n\n if \"PATHNAME\" in line:\n filenames_start_line_num = line_num + 2\n filenames_end_line_num = filenames_start_line_num + template_num_rotors*6\n del run_char_file[filenames_start_line_num:filenames_end_line_num]\n run_char_file[filenames_start_line_num:filenames_start_line_num] = file_string_list\n break\n\n # Set NPSI, velocity, and rotation rates, aircraft pitch\n expr = re.compile(r\"(^|\\s)NPSI\\s+\")\n vel_expr = re.compile(r\"(^|\\s)U\\s+V\\s+W\\s\")\n pitch_expr = re.compile(r\"(^|\\s)YAW\\s*\\(\\s*IAC\\s*\\)\\s*,\\s*PITCH\\s*\\(\\s*IAC\\s*\\)\\s*,\\s*ROLL\\s*\\(\\s*IAC\\s*\\)\")\n num_pitches_found = 0\n for line_num in range(len(run_char_file)):\n line = run_char_file[line_num]\n if re.search(expr, line):\n npsi_line_num = line_num + 1\n npsi_rep_expr = r\"^(\\s*)-?([0-9]+)\"\n run_char_file[npsi_line_num] = re.sub(npsi_rep_expr, r\"\\g<1>{}\".format(num_psi),\n run_char_file[npsi_line_num])\n if re.search(vel_expr, line):\n vel_line_num = line_num + 1\n current_values = np.array([float(d) for d in run_char_file[vel_line_num].split()])\n if velocity is not None or rotation_rates is not None:\n if velocity is not None:\n current_values[0:3] = velocity[:]\n if rotation_rates is not None:\n current_values[3:] = rotation_rates[:]\n run_char_file[vel_line_num] = (\"{:8.4f} \"*6 + \"\\n\").format(*current_values)\n if re.search(pitch_expr, line):\n pitch_line_num = line_num + 1\n ypr = np.array([float(d) for d in run_char_file[pitch_line_num].split()])\n if pitch is not None and num_pitches_found < len(pitch):\n ypr[1] = pitch[num_pitches_found]\n num_pitches_found += 1\n run_char_file[pitch_line_num] = (\"{:8.4f} \"*3 + \"\\n\").format(*ypr)\n\n with io.StringIO() as string_io:\n string_io.writelines(run_char_file)\n return string_io.getvalue()\n\n\ndef read_run_characteristics_template(template_filename=None, template_file=None):\n \"\"\"\n Reads key inputs needed from a template run characteristics file\n\n :param template_filename: template file name, will be opened if template_file is None\n :param template_file: file like object (io.IOBase) containing the template file contents\n :return: dictionary of inputs\n \"\"\"\n # Check that both template file and filename are not None\n if template_file is None and template_filename is None:\n raise ValueError(\"template_file and template_filename cannot both be None\")\n\n # Determine if a template file object exists, if not then open template filename\n close_file = False\n if template_file is None:\n close_file = True\n template_file = open(template_filename, 'r')\n\n run_char_file = []\n try:\n template_file.seek(0)\n run_char_file = template_file.readlines()\n finally:\n if close_file:\n template_file.close()\n\n run_char_dict = {}\n\n npsi_expr = re.compile(r\"(^|\\s)NPSI\\s+\")\n nrotor_expr = re.compile(r\"(^|\\s)NROTOR\\s+\")\n file_names_expr = re.compile(r\"(^|\\s)INPUT FILENAMES\\s+\")\n vel_expr = re.compile(r\"(^|\\s)U\\s+V\\s+W\\s\")\n file_list = []\n for line_num in range(len(run_char_file)):\n line = run_char_file[line_num]\n if re.search(npsi_expr, line):\n npsi_line_num = line_num + 1\n data = run_char_file[npsi_line_num].split()\n npsi = int(data[0])\n run_char_dict['NPSI'] = npsi\n if re.search(nrotor_expr, line):\n nrotor_line_num = line_num + 1\n data = run_char_file[nrotor_line_num].split()\n nrotor = int(data[0])\n run_char_dict['NROTOR'] = nrotor\n if re.search(file_names_expr, line):\n filenames = []\n for file_line in range(1, 6):\n file_line_num = line_num + file_line\n filename = run_char_file[file_line_num].split()[0]\n filenames.append(filename)\n file_list.append(filenames)\n if re.search(vel_expr, line):\n vel_line_num = line_num + 1\n data = run_char_file[vel_line_num].split()\n run_char_dict['U'] = float(data[0])\n run_char_dict['V'] = float(data[1])\n run_char_dict['W'] = float(data[2])\n run_char_dict['P'] = float(data[3])\n run_char_dict['Q'] = float(data[4])\n run_char_dict['R'] = float(data[5])\n\n if len(file_list) > 0:\n run_char_dict['FILES'] = file_list\n\n return run_char_dict\n\n\ndef build_charm_input_files(degen_mgr: dg.DegenGeomMgr, case_name,\n rotor_settings: CharmRotorSettingsCollection=None,\n wing_settings=None,\n unit_factor=u.in2ft, run_char_template=None, run_char_filename=None,\n velocity=None, **kwargs):\n \"\"\"\n Creates input files for charm case\n\n :param degen_mgr: degen geom manager object with desired components for charm\n :param rotor_settings: rotor settings objects corresponding with the degen geoms\n :param wing_settings: rotor settings objects corresponding to the wing degen geoms\n :param case_name: name of the case these input files are for\n :param unit_factor: unit conversion factor to go from vsp units to charm units (normally feet)\n :param run_char_template: template run characteristic file object (io.IOBase like object)\n :param run_char_filename: name of run characteristic input file template if run_char_template is None\n :param velocity: vehicle velocity vector [u, v, w] in ft/s\n :return: dictionary of name, file contents pairs\n \"\"\"\n\n # Get key quantites from run characteristic file\n run_char_vars = read_run_characteristics_template(template_filename=run_char_filename,\n template_file=run_char_template)\n num_psi = run_char_vars['NPSI']\n files_to_write = {}\n rotor_files = {}\n\n if rotor_settings is not None:\n # Determine appropriate num_psi value, needs to be divisible all blade counts\n num_blades_list = [len(degen_mgr.degen_objs[prop_id].copies[0]) for prop_id in rotor_settings.keys()]\n\n num_psi = _determine_num_psi(base_num_psi=run_char_vars['NPSI'], num_blades_list=num_blades_list)\n\n files_to_write, rotor_files = create_rotor_file_list(degen_mgr=degen_mgr,\n settings=rotor_settings, num_psi=num_psi,\n unit_factor=unit_factor, **kwargs)\n\n if wing_settings is not None:\n wing_infos = create_all_wing_infos(degen_mgr=degen_mgr, settings=wing_settings)\n wing_files_to_write, wing_files = create_wing_file_list(wing_infos, settings=wing_settings,\n num_psi=num_psi, unit_factor=unit_factor, **kwargs)\n files_to_write = dict(files_to_write, **wing_files_to_write)\n rotor_files = dict(rotor_files, **wing_files)\n\n run_char_file = build_run_characteristics_file_from_template(rotor_files=rotor_files,\n template_filename=run_char_filename,\n template_file=run_char_template,\n num_psi=num_psi, velocity=velocity, **kwargs)\n files_to_write[_cleanup_filename_for_charm(case_name + \".inp\")] = run_char_file\n return files_to_write\n\n\ndef create_scan_grid(xpnts=None, ypnts=None, zpnts=None):\n \"\"\"\n Creates scan grid file for input point vectors, one must be length of one\n\n :param xpnts: array of x points\n :param ypnts: array of y points\n :param zpnts: array of z points\n :return: string contents of scan.inp file\n \"\"\"\n\n xlen = len(xpnts)\n ylen = len(ypnts)\n zlen = len(zpnts)\n shift = 0\n nd1 = xlen\n nd2 = ylen\n num_grids = zlen\n\n if xlen <= ylen and xlen <= zlen:\n shift = 2\n nd1 = ylen\n nd2 = zlen\n num_grids = xlen\n elif ylen <= xlen and ylen <= zlen:\n shift = 1\n nd1 = zlen\n nd2 = xlen\n num_grids = ylen\n\n with io.StringIO() as f:\n f.write(\"{:8d}\\n\".format(num_grids))\n for igrid in range(num_grids):\n f.write(\"{:8d}{:8d}\\n\".format(nd1, nd2))\n for igrid in range(num_grids):\n for i in range(nd1):\n for j in range(nd2):\n indices = [i, j, igrid]\n f.write(\"{:12.3f}{:12.3f}{:12.3f}\\n\".format(xpnts[indices[shift % 3]],\n ypnts[indices[(shift+1) % 3]],\n zpnts[indices[(shift+2) % 3]]))\n return f.getvalue()\n\n\ndef _determine_num_psi(base_num_psi, num_blades_list):\n \"\"\"\n Determines the number of azimuthal computation points based on a template number of desired resolution\n and a list of all the number of blades\n :param base_num_psi: template number azimuthal computation points\n :param num_blades_list: list of blade counts\n :return: closest azimuthal resolution value that is divisible by all of the blade counts\n \"\"\"\n\n # Compute the least common multiple of all of the numbers\n lcm = 1\n for number in num_blades_list:\n lcm = _compute_least_common_multiple(lcm, number)\n\n # Determine the closest number to the template number and the least common multiple\n remainder = base_num_psi % lcm\n num_psi = base_num_psi\n if remainder < lcm/2.0 and base_num_psi - remainder > 0:\n num_psi -= remainder\n else:\n num_psi += (lcm - remainder)\n\n return num_psi\n\n\ndef _compute_least_common_multiple(num1: int, num2: int):\n \"\"\"\n Finds the least common multiple between the two input numbers\n :param num1: first number\n :param num2: second number\n :return: least common multiple\n \"\"\"\n import math\n return int(num1*num2/math.gcd(num1, num2))\n\n\ndef _get_airfoil_from_file(af_opts: AirfoilFileLocationOpt):\n \"\"\"\n Gets an airfoil section from a file location\n :param af_opts: Options associated with getting the file\n :return: Charm airfoil section\n \"\"\"\n # Get full path to the file\n fullpath = af_opts.get_fullpath()\n\n thickness = 0.0\n with open(fullpath, 'r') as f:\n line = f.readline()\n # Assuming thickness is on the first line\n thickness = float(line)\n\n # Read file line by line\n with io.StringIO() as section_str_io:\n reynolds_data = AirfoilReynoldsDataType.NONE\n for iline, line in enumerate(f):\n if iline == 0 and 'COMMENT' not in line:\n try:\n data = [float(d) for d in line.split()]\n except ValueError:\n data = []\n\n if len(data) == 4:\n reynolds_data = AirfoilReynoldsDataType.METHOD1\n elif len(data) == 2:\n reynolds_data = AirfoilReynoldsDataType.METHOD2\n section_str_io.write(line)\n return CharmAirfoil(thickness=thickness, section_string=section_str_io.getvalue(),\n reynolds_data_type=reynolds_data)\n\n\ndef _cleanup_filename_for_charm(name):\n \"\"\"\n Cleans up a filename into something charm can handle\n :param name: unclean filename\n :return: filename suitable for charm\n \"\"\"\n # Replacing spaces with \"_\"\n return name.replace(\" \", \"_\")\n\n\ndef _determine_num_symm(trans_orig: TransMatrix, trans_copy: TransMatrix):\n \"\"\"\n Determines the number of planar symmetries between an original transformation matrix and the transformation matrix\n of a copy\n :param trans_orig: original transformation matrix\n :param trans_copy: transformation matrix of a potentially symmetric copy\n :return: number of planar symmetries between the two matrices\n \"\"\"\n\n orig_inv = trans_orig.get_inverse_transform()\n trans_diff = TransMatrix(np.dot(trans_copy.mat, orig_inv.mat))\n\n # if the difference is only planar symmetries, then off diagonal elements should zero\n num_syms = 0\n if not np.allclose(trans_diff.mat[0, 1:3], np.zeros(2)):\n return num_syms\n if not np.isclose(trans_diff.mat[1, 0], 0.0):\n return num_syms\n if not np.isclose(trans_diff.mat[1, 2], 0.0):\n return num_syms\n if not np.allclose(trans_diff.mat[2, 0:2], np.zeros(2)):\n return num_syms\n\n if np.isclose(trans_diff.mat[0, 0], -1.0):\n num_syms += 1\n if np.isclose(trans_diff.mat[1, 1], -1.0):\n num_syms += 1\n if np.isclose(trans_diff.mat[2, 2], -1.0):\n num_syms += 1\n\n return num_syms\n\n\ndef _connect_arrays(arr1, arr2):\n \"\"\"\n Checks if two arrays could be connected\n :param arr1: np array, each row is a 3d point\n :param arr2: np array, each row is a 3d point\n :return: None if unable to connect, connected array if could connect\n \"\"\"\n if _is_same_point(arr1[0], arr2[0]):\n connected = np.concatenate((np.flipud(arr2)[:-1, :], arr1))\n return connected\n if _is_same_point(arr1[0], arr2[-1]):\n connected = np.concatenate((arr2[:-1, :], arr1))\n return connected\n if _is_same_point(arr1[-1], arr2[-1]):\n connected = np.concatenate((arr2, np.flipud(arr1)[:-1, :]))\n return connected\n if _is_same_point(arr1[-1], arr2[0]):\n connected = np.concatenate(arr1[:-1, :], arr2)\n return connected\n return None\n\n\nSAME_POINT_ATOL = 1.0E-8\n\n\ndef _is_same_point(point1, point2):\n \"\"\"\n Checks if two points are the same\n :param point1: first point\n :param point2: second point\n :return: returns True if the are the same, False otherwise\n \"\"\"\n from numpy.linalg import norm\n\n if abs(norm(point1-point2)) < SAME_POINT_ATOL:\n return True\n return False\n\n\ndef __modify_rotor_wake_template(rw_template, rotor_setting: CharmRotorSettings):\n \"\"\"\n Modifies a rotor wake template given rotor settings object\n :param rw_template: array of rotor wake file lines\n :param rotor_setting: CharmRotorSettings object\n :return: modified template\n \"\"\"\n\n # If there is a specified initial collective, then set that in the template\n if rotor_setting.initial_collective is not None or rotor_setting.ct is not None:\n # Collective line is index 6\n line_num = 6\n line = rw_template[line_num]\n data = line.split()\n icoll = int(data[0]) if rotor_setting.icoll is None else rotor_setting.icoll\n coll = float(data[1]) if rotor_setting.initial_collective is None else rotor_setting.initial_collective\n ct = float(data[2]) if rotor_setting.ct is None else rotor_setting.ct\n print_str = \"{:4d} {:8.3f} {:8.6f}\".format(icoll, coll, ct)\n if len(data) >= 4:\n icoax = int(data[3])\n print_str += \" {:4d}\".format(icoax)\n print_str += \"\\n\"\n rw_template[line_num] = print_str\n\n return rw_template\n","sub_path":"src/python_api/packages/CHARM/charm/input_automation.py","file_name":"input_automation.py","file_ext":"py","file_size_in_byte":67350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"215755838","text":"# -*- coding: utf-8 -*-\n\"\"\"\nMake plots for Tip Trajectory Tracking Chapter.\n@author: J\n\"\"\"\n\nimport matplotlib.pyplot as plt\nfrom JaimesThesisModule import PostProc\nimport importlib, os\n\nOVERWRITE = False\nFigDir = '../Figures/Chapter_TipTrajectory/'\nif not os.path.isdir(FigDir):\n os.makedirs(FigDir)\n\nexistingFigs = [x[:-4] for x in os.listdir(FigDir)]\nfigScripts = [x[:-3] for x in os.listdir('../Postprocessing') if 'Ch3_' in x]\n\ndlcs = {'dlc11_0':PostProc.DLC('dlc11_0'),\n'dlc11_1':PostProc.DLC('dlc11_1'),\n'dlc11_3':PostProc.DLC('dlc11_3'),\n'dlc15_0':PostProc.DLC('dlc15_0'),\n'dlc15_1':PostProc.DLC('dlc15_1'),\n'dlc15_2':PostProc.DLC('dlc15_2')}\n\n#%%\nplt.rc('text', usetex=True)\nfor script in figScripts:\n if any(script in x for x in existingFigs) and (not OVERWRITE):\n print(f'{script} figures already exists.')\n else:\n print(f'Running {script}.py...')\n module = importlib.import_module('Postprocessing.' + script)\n module.run(dlcs, SAVE = FigDir + script + '.png')\nplt.rc('text', usetex=False)\n\n\n\n","sub_path":"Chapters/Chapter_TipTrajectory.py","file_name":"Chapter_TipTrajectory.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"635395524","text":"from django import forms\nfrom django.contrib import admin\nfrom django.db.models import Max\nfrom django_countries.fields import CountryField\nfrom masters.models import Role, Center\nfrom profiles.models import Profile, Membership\nfrom profiles.models import Mobile, Email\nfrom profiles.models import Address, Education\nfrom profiles.models import Job, GNCSevaDetail\nfrom profiles.models import LocalEventSevaDetail, GlobalEventSevaDetail\nfrom .models import GNCSeva, UserPreferences\nfrom mhtsessions.models import Session, Report\nfrom mhtsessions.models import SessionFlow, SessionMedia\nfrom mhtsessions.models import Attendance, CoordinatorsAttendance\nfrom constants import PARTICIPANT_ROLE_LEVEL\n\n\nclass RequiredFormSet(forms.models.BaseInlineFormSet):\n\n def __init__(self, *args, **kwargs):\n\n super(RequiredFormSet, self).__init__(*args, **kwargs)\n \n self.forms[0].empty_permitted = False\n\n\nclass MobileInline(admin.StackedInline):\n model = Mobile\n formset = RequiredFormSet\n extra = 1\n\n\nclass EmailInline(admin.StackedInline):\n model = Email\n extra = 1\n\n\nclass AddressInline(admin.StackedInline):\n model = Address\n extra = 1\n\n\nclass EducationInline(admin.StackedInline):\n model = Education\n extra = 1\n\n\nclass JobInline(admin.StackedInline):\n model = Job\n extra = 1\n\n\nclass MembershipInline(admin.StackedInline):\n # fields = ('profile' , 'center' , 'role', 'since', 'till', 'is_active')\n list_display = ('center')\n model = Membership\n formset = RequiredFormSet\n extra = 1\n\n def get_readonly_fields(self, request, obj=None):\n\n if obj:\n\n if request.user.is_superuser or not Profile.objects.filter(user=request.user).exists():\n\n return self.readonly_fields \n\n current_profile = Profile.objects.get(user=request.user)\n\n user_level = Membership.objects.filter(profile=current_profile,is_active=True).aggregate(Max('role__level'))\n\n accessed_obj_level = Membership.objects.filter(profile=obj,is_active=True).aggregate(Max('role__level'))\n \n if (accessed_obj_level['role__level__max'] >= user_level['role__level__max']):\n\n self.extra = 0\n\n self.max_num = 0\n\n self.can_delete = False\n\n return self.readonly_fields + ('center', 'role',\n 'sub_role', 'since', 'till', 'is_active')\n else:\n\n return self.readonly_fields\n else:\n\n return self.readonly_fields \n\n def formfield_for_foreignkey(self, db_field, request, **kwargs):\n\n if request.user.is_superuser or not Profile.objects.filter(user=request.user).exists():\n\n return super(MembershipInline, self).formfield_for_foreignkey(db_field, request, **kwargs)\n\n current_profile = Profile.objects.get(user=request.user)\n\n current_membership = Membership.objects.filter(profile=current_profile, is_active = True)\n\n current_centers_pk = []\n\n current_roles = []\n\n for membership in current_membership:\n\n current_centers_pk.append(membership.center.pk)\n\n current_roles.append(membership.role.level)\n\n if db_field.name == 'center':\n\n kwargs['queryset'] = Center.objects.filter(pk__in=current_centers_pk)\n\n if db_field.name == 'role':\n\n try:\n kwargs['queryset'] = Role.objects.filter(level__lt=max(current_roles))\n\n except:\n kwargs['queryset'] = Role.objects.none()\n\n return super(MembershipInline, self).formfield_for_foreignkey(db_field, request, **kwargs)\n\n def get_formset(self, request, obj=None, **kwargs):\n\n self.exclude = []\n\n if not request.user.is_superuser:\n self.exclude.append('sub_role')\n\n return super(MembershipInline, self).get_formset(request, obj, **kwargs)\n\n\nclass GlobalEventSevaDetailInline(admin.TabularInline):\n model = GlobalEventSevaDetail\n extra = 1\n\n\nclass LocalEventSevaDetailInline(admin.StackedInline):\n # fields = ('event', 'profile' , 'coordinator', 'attended' , 'attended_days' , 'comments')\n model = LocalEventSevaDetail\n extra = 1\n\n\nclass GNCSevaDetailInline(admin.StackedInline):\n # fields = ('event', 'profile' , 'coordinator', 'attended' , 'attended_days' , 'comments')\n model = GNCSevaDetail\n extra = 1\n\n\nclass ProfileAdmin(admin.ModelAdmin):\n\n list_display = ('user','first_name', 'last_name', 'date_of_birth', 'role',\n 'center_name')\n\n list_filter = ('first_name', 'hobby')\n\n search_fields = ('first_name', 'last_name',)\n\n inlines = [\n MobileInline,\n AddressInline,\n EmailInline,\n EducationInline,\n JobInline,\n MembershipInline,\n GlobalEventSevaDetailInline,\n LocalEventSevaDetailInline,\n GNCSevaDetailInline,\n ]\n\n def role(self, obj):\n\n current_profile = obj\n\n if not Membership.objects.filter(profile=current_profile, is_active=True).exists():\n\n return \" \"\n\n max_role_level = Membership.objects.filter(profile=current_profile, is_active=True).aggregate(Max('role__level')) \n\n if max_role_level == 0:\n\n return \" \"\n\n return Role.objects.get(level=max_role_level['role__level__max'])\n\n role.short_description = 'Role'\n role.admin_order_field = 'membership__role__role'\n\n def center_name(self, obj):\n\n current_profile = obj\n\n if not Membership.objects.filter(profile=current_profile, is_active=True).exists():\n\n return \" \"\n\n current_membership = Membership.objects.filter(profile=current_profile, is_active=True)\n\n count = 0\n\n current_centers = \"\"\n\n for membership in current_membership:\n\n center = membership.center\n\n count += 1\n\n current_centers += \"(%s) %s, %s \" % (count, center.center_name, center.city.name)\n\n return current_centers\n\n center_name.admin_order_field = 'membership__center__center_name'\n\n def get_form(self, request, obj=None, **kwargs):\n self.exclude = []\n\n if not request.user.is_superuser:\n\n self.exclude.append('user')\n\n return super(ProfileAdmin, self).get_form(request, obj, **kwargs)\n\n def get_queryset(self, request):\n\n qs = super(ProfileAdmin, self).get_queryset(request)\n\n if request.user.is_superuser:\n\n return qs\n\n if not Profile.objects.filter(user=request.user).exists():\n\n return Profile.objects.none()\n\n current_profile = Profile.objects.get(user=request.user)\n\n if not Membership.objects.filter(profile=current_profile, is_active=True).exists():\n\n return current_profile\n\n current_membership = Membership.objects.filter(profile=current_profile, is_active=True)\n\n current_centers = []\n\n current_roles = []\n\n for membership in current_membership:\n\n current_roles.append(membership.role.level)\n\n current_centers.append(membership.center)\n\n user_level = Membership.objects.filter(profile=current_profile,is_active=True).aggregate(Max('role__level')) \n\n for i, item in enumerate(current_roles):\n\n if current_roles[i] > PARTICIPANT_ROLE_LEVEL:\n\n memberships = (Membership.objects.filter(\n center=current_centers[i],\n role__level__lte=current_roles[i]))\n\n qs = qs.filter(membership__in=memberships)\n\n return qs.distinct()\n\n def get_formsets(self, request, obj=None):\n\n for inline in self.get_inline_instances(request, obj):\n\n yield inline.get_formset(request, obj)\n\nadmin.site.register(Profile, ProfileAdmin)\nadmin.site.register(GNCSeva)\nadmin.site.register(UserPreferences)\n","sub_path":"profiles/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":7842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"451206814","text":"from harp.daal.applications import KMeansDaalApplication\nimport numpy\n\nmy_app = KMeansDaalApplication('My KMeansDaal with Harp')\n\nmy_app.args('50 10 10 1 1 4 10 5120 /daal-kmeans-work /tmp/kmeans true')\n\nmy_app.run()\n\nmy_app.print_result('/daal-kmeans-work/centroids/out/output')\n\narr = my_app.result_to_array('/daal-kmeans-work/centroids/out/output')\n\nprint(arr)\n\nsorted_arr = numpy.sort(arr)\n\nprint(sorted_arr)\n","sub_path":"harp-daal-python/examples/daal/run_harp_daal_KMeansDaal.py","file_name":"run_harp_daal_KMeansDaal.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"387125305","text":"import json\nfrom sys import argv\nimport subprocess\ninput_url = argv[1]\n\ndef form_url(play_list_id, vid):\n return \"https://www.youtube.com/watch?v=%s&list=%s\"%(vid, play_list_id)\n\nwith open(input_url, 'r') as f:\n data = json.load(f)\n\nplay_list = []\nplay_list_id = data['id']\nfor i in data['entries']:\n vid = i['id']\n url = form_url(play_list_id, vid)\n play_list.append(url)\n\nplay_url = \" \".join(play_list)\nprint(play_url)\n#bash_command = \"vlc %s\"%(play_url)\n#subprocess.run(bash_command)\n","sub_path":"script/util/youtubelist_player.py","file_name":"youtubelist_player.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"70299702","text":"import pandas as pd\n\nfrom sklearn.linear_model import (\n RANSACRegressor,\n HuberRegressor\n)\n\nfrom sklearn.svm import SVR\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\n\nif __name__ == '__main__':\n\n df = pd.read_csv('./Datasets/felicidad_corrupt.csv')\n print(df.describe())\n\n y = df['score']\n X = df.drop(['country','score'], axis = 1)\n \n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 42)\n\n estimadores = {\n 'SVR' : SVR(gamma = 'auto', C = 1.0, epsilon = 0.1),\n 'RANSAC': RANSACRegressor(),\n 'HUBER': HuberRegressor(epsilon = 1.35)\n }\n\n for name, estimador in estimadores.items():\n estimador.fit(X_train, y_train)\n predictions = estimador.predict(X_test)\n\n print('='*64)\n print(name)\n print('MSE: ', mean_squared_error(y_test, predictions))\n\n\n","sub_path":"robust.py","file_name":"robust.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"107958061","text":"# -*- coding: utf-8 -*-\n\nfrom django.conf.urls import patterns, url\n\nurlpatterns = patterns(\n 'apps.usual.views',\n # organize\n url('^organize$', 'getOrganize'),\n url('^orgUser$', 'getOrgUser'),\n url('^deptUser$', 'getDeptUser'),\n # other\n url('^findUsers$', 'findUsers'),\n url('^uploadFile$', 'uploadFile'),\n url('^dropFile$', 'dropFile'),\n)","sub_path":"sample/wsw/apps/usual/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"311702705","text":"'''\nSecure Triplet Loss Project Repository (https://github.com/jtrpinto/SecureTL)\n\nFile: ecg_train_securetl_model.py\n- Used to train a model with ECG data, with the original formulation of the Secure Triplet Loss.\n\n\"Secure Triplet Loss: Achieving Cancelability and Non-Linkability in End-to-End Deep Biometrics\"\nJoão Ribeiro Pinto, Miguel V. Correia, and Jaime S. Cardoso\nIEEE Transactions on Biometrics, Behavior, and Identity Science\n\njoao.t.pinto@inesctec.pt | https://jtrpinto.github.io\n'''\n\nimport os\nimport torch\nimport numpy as np\nimport pickle as pk\nfrom models import SecureModel, SecureECGNetwork\nfrom losses import SecureTripletLoss\nfrom dataset import SecureECGDataset\nfrom trainer import train_secure_triplet_model\nfrom torch.utils.data import DataLoader\n\n\nDEVICE = 'cuda:0' if torch.cuda.is_available() else 'cpu'\n\nSAVE_MODEL = 'model_name'\nTRAIN_DATA = 'ecg_train_data.pickle'\n\nLEARN_RATE = 1e-4 # learning rate\nREG = 0 # L2 regularization hyperparameter\n\nN_EPOCHS = 100\nBATCH_SIZE = 32\nVALID_SPLIT = .2 \n\nprint('Training model: ' + SAVE_MODEL)\n\n# Preparing and dividing the dataset\ntrainset = SecureECGDataset(TRAIN_DATA)\n\ndataset_size = len(trainset) # number of samples in training + validation sets\nindices = list(range(dataset_size))\nsplit = int(np.floor(VALID_SPLIT * dataset_size)) # number of samples in validation set\nnp.random.seed(42)\nnp.random.shuffle(indices)\ntrain_indices, valid_indices = indices[split:], indices[:split]\n\ntrain_sampler = torch.utils.data.sampler.SubsetRandomSampler(train_indices)\nvalid_sampler = torch.utils.data.sampler.SubsetRandomSampler(valid_indices)\n\ntrain_loader = DataLoader(trainset, batch_size=BATCH_SIZE, shuffle=False, num_workers=4, sampler=train_sampler)\nvalid_loader = DataLoader(trainset, batch_size=BATCH_SIZE, shuffle=False, num_workers=4, sampler=valid_sampler)\n\n# Creating the network and the model\nnetwork = SecureECGNetwork().to(DEVICE)\nmodel = SecureModel(network)\nloss = SecureTripletLoss(margin=1.0)\noptimizer = torch.optim.Adam(model.parameters(), lr=LEARN_RATE, weight_decay=REG)\n\n# Training the model\ntrain_hist, valid_hist = train_secure_triplet_model(model, loss, optimizer, train_loader, N_EPOCHS, BATCH_SIZE, DEVICE, patience=10, valid_loader=valid_loader, filename=SAVE_MODEL)\n\n","sub_path":"ecg_train_securetl_model.py","file_name":"ecg_train_securetl_model.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"334985649","text":"import sys\r\nimport os\r\nimport math\r\nimport torch\r\nimport torch.nn as nn\r\nfrom torch.nn import Identity\r\nimport torch.nn.functional as F\r\nfrom torch.autograd import Function\r\nfrom functools import partial, reduce, wraps\r\nfrom itertools import chain\r\nfrom operator import mul\r\n\r\nfrom local_attention import LocalAttention\r\nfrom axial_positional_embedding import AxialPositionalEmbedding\r\nfrom product_key_memory import PKM\r\nfrom reversible import ReversibleSequence\r\n\r\nfile_dir = os.path.dirname(os.path.realpath(__file__))\r\nparent_dir = os.path.dirname(file_dir)\r\nprint(file_dir)\r\nprint(parent_dir)\r\nsys.path.append(parent_dir)\r\nfrom two_steps_quantized_matmul import quantized_matmul, calc_topk_matrix_after_masking\r\n\r\n# sys.path.append(os.path.join(file_dir, 'reformer_pytorch'))\r\nsys.path.append('/home/gzy/anaconda3/envs/pytorch/lib/python3.8/site-packages/reformer_pytorch/')\r\nfrom reformer_pytorch import *\r\n\r\ndef default(val, default_val):\r\n return default_val if val is None else val\r\n\r\nclass QuantizedQKLSHAttention(LSHAttention):\r\n\tdef __init__( self,\r\n\t\t\t\t dropout = 0.,\r\n\t\t\t\t bucket_size = 64,\r\n\t\t\t\t n_hashes = 8,\r\n\t\t\t\t causal = False,\r\n\t\t\t\t allow_duplicate_attention = True,\r\n\t\t\t\t attend_across_buckets = True,\r\n\t\t\t\t rehash_each_round = True,\r\n\t\t\t\t drop_for_hash_rate = 0.0,\r\n\t\t\t\t random_rotations_per_head = False,\r\n\t\t\t\t return_attn = False,\r\n\t\t\t\t K = None):\r\n\t\tsuper().__init__()\r\n\t\tself.K = K\r\n\r\n\tdef forward(self, qk, v, query_len = None, input_mask = None, input_attn_mask = None, **kwargs):\r\n\t\tbatch_size, seqlen, dim, device = *qk.shape, qk.device\r\n\r\n\t\tquery_len = default(query_len, seqlen)\r\n\t\tis_reverse = kwargs.pop('_reverse', False)\r\n\t\tdepth = kwargs.pop('_depth', None)\r\n\r\n\t\tassert seqlen % (self.bucket_size * 2) == 0, f'Sequence length ({seqlen}) needs to be divisible by target bucket size x 2 - {self.bucket_size * 2}'\r\n\r\n\t\tn_buckets = seqlen // self.bucket_size\r\n\t\tbuckets = self.hash_vectors(n_buckets, qk, key_namespace=depth, fetch=is_reverse, set_cache=self.training)\r\n\r\n\t\t# We use the same vector as both a query and a key.\r\n\t\tassert int(buckets.shape[1]) == self.n_hashes * seqlen\r\n\r\n\t\ttotal_hashes = self.n_hashes\r\n\r\n\t\tticker = torch.arange(total_hashes * seqlen, device=device).unsqueeze(0).expand_as(buckets)\r\n\t\tbuckets_and_t = seqlen * buckets + (ticker % seqlen)\r\n\t\tbuckets_and_t = buckets_and_t.detach()\r\n\r\n\t\t# Hash-based sort (\"s\" at the start of variable names means \"sorted\")\r\n\t\tsbuckets_and_t, sticker = sort_key_val(buckets_and_t, ticker, dim=-1)\r\n\t\t_, undo_sort = sticker.sort(dim=-1)\r\n\t\tdel ticker\r\n\r\n\t\tsbuckets_and_t = sbuckets_and_t.detach()\r\n\t\tsticker = sticker.detach()\r\n\t\tundo_sort = undo_sort.detach()\r\n\r\n\t\tst = (sticker % seqlen)\r\n\t\tsqk = batched_index_select(qk, st)\r\n\t\tsv = batched_index_select(v, st)\r\n\r\n\t\t# Split off a \"bin\" axis so that attention only occurs within chunks.\r\n\t\tchunk_size = total_hashes * n_buckets\r\n\t\tbq_t = bkv_t = torch.reshape(st, (batch_size, chunk_size, -1))\r\n\t\tbqk = torch.reshape(sqk, (batch_size, chunk_size, -1, dim))\r\n\t\tbv = torch.reshape(sv, (batch_size, chunk_size, -1, dim))\r\n\r\n\t\t# Hashing operates on unit-length vectors. Unnormalized query vectors are\r\n\t\t# fine because they effectively provide a learnable temperature for the\r\n\t\t# attention softmax, but normalizing keys is needed so that similarity for\r\n\t\t# the purposes of attention correctly corresponds to hash locality.\r\n\t\tbq = bqk\r\n\t\tbk = F.normalize(bqk, p=2, dim=-1).type_as(bq)\r\n\r\n\t\t# Allow each chunk to attend within itself, and also one chunk back. Chunk\r\n\t\t# boundaries might occur in the middle of a sequence of items from the\r\n\t\t# same bucket, so this increases the chances of attending to relevant items.\r\n\t\tdef look_one_back(x):\r\n\t\t\tx_extra = torch.cat([x[:, -1:, ...], x[:, :-1, ...]], dim=1)\r\n\t\t\treturn torch.cat([x, x_extra], dim=2)\r\n\r\n\t\tbk = look_one_back(bk)\r\n\t\tbv = look_one_back(bv)\r\n\t\tbkv_t = look_one_back(bkv_t)\r\n\r\n\t\t# Dot-product attention.\r\n\t\tdots = quantized_matmul(bq, bk.transpose(2, 3)) * (dim ** -0.5)\r\n\t\t# dots = torch.einsum('bhie,bhje->bhij', bq, bk) * (dim ** -0.5)\r\n\t\tmasked_value = max_neg_value(dots)\r\n\r\n\t\t# Mask for post qk attention logits of the input sequence\r\n\t\tif input_attn_mask is not None:\r\n\t\t\tinput_attn_mask = F.pad(input_attn_mask, (0, seqlen - input_attn_mask.shape[-1], 0, seqlen - input_attn_mask.shape[-2]), value=True)\r\n\t\t\tdot_attn_indices = ((bq_t * seqlen)[:, :, :, None] + bkv_t[:, :, None, :])\r\n\t\t\tinput_attn_mask = input_attn_mask.reshape(batch_size, -1)\r\n\t\t\tdot_attn_indices = dot_attn_indices.reshape(batch_size, -1)\r\n\t\t\tmask = input_attn_mask.gather(1, dot_attn_indices).reshape_as(dots)\r\n\t\t\tdots.masked_fill_(~mask, masked_value)\r\n\t\t\tdel mask\r\n\r\n\t\t# Input mask for padding in variable lengthed sequences\r\n\t\tif input_mask is not None:\r\n\t\t\tinput_mask = F.pad(input_mask, (0, seqlen - input_mask.shape[1]), value=True)\r\n\t\t\tmq = input_mask.gather(1, st).reshape((batch_size, chunk_size, -1))\r\n\t\t\tmkv = look_one_back(mq)\r\n\t\t\tmask = mq[:, :, :, None] * mkv[:, :, None, :]\r\n\t\t\tdots.masked_fill_(~mask, masked_value)\r\n\t\t\tdel mask\r\n\r\n\t\t# Causal masking\r\n\t\tif self.causal:\r\n\t\t\tmask = bq_t[:, :, :, None] < bkv_t[:, :, None, :]\r\n\t\t\tif seqlen > query_len:\r\n\t\t\t\tmask = mask & (bkv_t[:, :, None, :] < query_len)\r\n\t\t\tdots.masked_fill_(mask, masked_value)\r\n\t\t\tdel mask\r\n\r\n\t\t# Mask out attention to self except when no other targets are available.\r\n\t\tself_mask = bq_t[:, :, :, None] == bkv_t[:, :, None, :]\r\n\t\tdots.masked_fill_(self_mask, TOKEN_SELF_ATTN_VALUE)\r\n\t\tdel self_mask\r\n\r\n\t\t# Mask out attention to other hash buckets.\r\n\t\tif not self._attend_across_buckets:\r\n\t\t\tbq_buckets = bkv_buckets = torch.reshape(sbuckets_and_t // seqlen, (batch_size, chunk_size, -1))\r\n\t\t\tbkv_buckets = look_one_back(bkv_buckets)\r\n\t\t\tbucket_mask = bq_buckets[:, :, :, None] != bkv_buckets[:, :, None, :]\r\n\t\t\tdots.masked_fill_(bucket_mask, masked_value)\r\n\t\t\tdel bucket_mask\r\n\r\n\t\t# Don't double-count query-key pairs across multiple rounds of hashing.\r\n\t\t# There are two possible strategies here. (1) The default is to count how\r\n\t\t# many times a query-key pair is repeated, and to lower its log-prob\r\n\t\t# correspondingly at each repetition. (2) When hard_k is set, the code\r\n\t\t# instead masks all but the first occurence of each query-key pair.\r\n\t\tif not self._allow_duplicate_attention:\r\n\t\t\tlocs1 = undo_sort // bq_t.shape[-1]\r\n\t\t\tlocs2 = (locs1 + 1) % chunk_size\r\n\t\t\tif not self._attend_across_buckets:\r\n\t\t\t\tlocs1 = buckets * chunk_size + locs1\r\n\t\t\t\tlocs2 = buckets * chunk_size + locs2\r\n\t\t\tlocs = torch.cat([\r\n\t\t\t\ttorch.reshape(locs1, (batch_size, total_hashes, seqlen)),\r\n\t\t\t\ttorch.reshape(locs2, (batch_size, total_hashes, seqlen)),\r\n\t\t\t], 1).permute((0, 2, 1))\r\n\r\n\t\t\tslocs = batched_index_select(locs, st)\r\n\t\t\tb_locs = torch.reshape(slocs, (batch_size, chunk_size, -1, 2 * total_hashes))\r\n\r\n\t\t\tb_locs1 = b_locs[:, :, :, None, :total_hashes]\r\n\r\n\t\t\tbq_locs = b_locs1.expand(b_locs.shape[:3] + (2, total_hashes))\r\n\t\t\tbq_locs = torch.reshape(bq_locs, b_locs.shape)\r\n\t\t\tbkv_locs = look_one_back(b_locs)\r\n\r\n\t\t\tdup_counts = (bq_locs[:, :, :, None, :] == bkv_locs[:, :, None, :, :])\r\n\t\t\t# for memory considerations, chunk summation of last dimension for counting duplicates\r\n\t\t\tdup_counts = chunked_sum(dup_counts, chunks=(total_hashes * batch_size))\r\n\t\t\tdup_counts = dup_counts.detach()\r\n\t\t\tassert dup_counts.shape == dots.shape\r\n\t\t\tdots = dots - torch.log(dup_counts + 1e-9)\r\n\t\t\tdel dup_counts\r\n\r\n\t\tdots = calc_topk_matrix_after_masking(bq, bk.transpose(2, 3), dots, self.K)\r\n\r\n\t\t# Softmax.\r\n\t\tdots_logsumexp = torch.logsumexp(dots, dim=-1, keepdim=True)\r\n\t\tdots = torch.exp(dots - dots_logsumexp).type_as(dots)\r\n\t\tdropped_dots = self.dropout(dots)\r\n\r\n\t\tbo = torch.einsum('buij,buje->buie', dropped_dots, bv)\r\n\t\tso = torch.reshape(bo, (batch_size, -1, dim))\r\n\t\tslogits = torch.reshape(dots_logsumexp, (batch_size, -1,))\r\n\r\n\t\t# unsort logits\r\n\t\to = batched_index_select(so, undo_sort)\r\n\t\tlogits = slogits.gather(1, undo_sort)\r\n\r\n\t\to = torch.reshape(o, (batch_size, total_hashes, seqlen, dim))\r\n\t\tlogits = torch.reshape(logits, (batch_size, total_hashes, seqlen, 1))\r\n\r\n\t\tif query_len != seqlen:\r\n\t\t\tquery_slice = (slice(None), slice(None), slice(0, query_len))\r\n\t\t\to, logits = o[query_slice], logits[query_slice]\r\n\r\n\t\tprobs = torch.exp(logits - torch.logsumexp(logits, dim=1, keepdim=True))\r\n\t\tout = torch.sum(o * probs, dim=1)\r\n\r\n\t\tattn = torch.empty(0, device=device)\r\n\r\n\t\t# return unsorted attention weights\r\n\t\tif self._return_attn:\r\n\t\t\tattn_unsort = ((bq_t * seqlen)[:, :, :, None] + bkv_t[:, :, None, :])\r\n\t\t\tattn_unsort = attn_unsort.view(batch_size * total_hashes, -1).long()\r\n\t\t\tunsorted_dots = torch.zeros(batch_size * total_hashes, seqlen * seqlen, device=device)\r\n\t\t\tunsorted_dots.scatter_add_(1, attn_unsort, dots.view_as(attn_unsort))\r\n\t\t\tdel attn_unsort\r\n\t\t\tunsorted_dots = unsorted_dots.reshape(batch_size, total_hashes, seqlen, seqlen)\r\n\t\t\tattn = torch.sum(unsorted_dots[:, :, 0:query_len, :] * probs, dim=1)\r\n\r\n\t\t# return output, attention matrix, and bucket distribution\r\n\t\treturn out, attn, buckets\r\n\r\nclass QuantizedQKLSHSelfAttention(LSHSelfAttention):\r\n\tdef __init__(self, dim, heads = 8, bucket_size = 64, n_hashes = 8, causal = False, dim_head = None, attn_chunks = 1, random_rotations_per_head = False, attend_across_buckets = True, allow_duplicate_attention = True, num_mem_kv = 0, one_value_head = False, use_full_attn = False, full_attn_thres = None, return_attn = False, post_attn_dropout = 0., dropout = 0., n_local_attn_heads = 0, K = None, **kwargs):\r\n\t\tsuper(LSHSelfAttention, self).__init__() # only call `nn.Module` init\r\n\t\tassert dim_head or (dim % heads) == 0, 'dimensions must be divisible by number of heads'\r\n\t\tassert n_local_attn_heads < heads, 'local attention heads must be less than number of heads'\r\n\r\n\t\tdim_head = default(dim_head, dim // heads)\r\n\t\tdim_heads = dim_head * heads\r\n\r\n\t\tself.dim = dim\r\n\t\tself.heads = heads\r\n\t\tself.dim_head = dim_head\r\n\t\tself.attn_chunks = default(attn_chunks, 1)\r\n\r\n\t\tself.v_head_repeats = (heads if one_value_head else 1)\r\n\t\tv_dim = dim_heads // self.v_head_repeats\r\n\r\n\t\tself.toqk = nn.Linear(dim, dim_heads, bias = False)\r\n\t\tself.tov = nn.Linear(dim, v_dim, bias = False)\r\n\t\tself.to_out = nn.Linear(dim_heads, dim)\r\n\r\n\t\tself.bucket_size = bucket_size\r\n\t\tself.lsh_attn = QuantizedQKLSHAttention(bucket_size=bucket_size, n_hashes=n_hashes, causal=causal, random_rotations_per_head=random_rotations_per_head, attend_across_buckets = attend_across_buckets, allow_duplicate_attention = allow_duplicate_attention, return_attn = return_attn, dropout = dropout, K = K, **kwargs)\r\n\t\tself.full_attn = FullQKAttention(causal=causal, dropout=dropout)\r\n\t\tself.post_attn_dropout = nn.Dropout(post_attn_dropout)\r\n\r\n\t\tself.use_full_attn = use_full_attn\r\n\t\tself.full_attn_thres = default(full_attn_thres, bucket_size)\r\n\r\n\t\tself.num_mem_kv = num_mem_kv\r\n\t\tself.mem_kv = nn.Parameter(torch.randn(1, num_mem_kv, dim, requires_grad=True)) if num_mem_kv > 0 else None\r\n\r\n\t\tself.n_local_attn_heads = n_local_attn_heads\r\n\t\tself.local_attn = LocalAttention(window_size=bucket_size * 2, causal=causal, dropout=dropout, shared_qk=True, look_forward=(1 if not causal else 0))\r\n\r\n\t\tself.callback = None\r\n\r\nclass QuantizedQKReformer(Reformer):\r\n\tdef __init__(self, dim, depth, max_seq_len, heads = 8, dim_head = None, bucket_size = 64, n_hashes = 8, ff_chunks = 100, attn_chunks = None, causal = False, weight_tie = False, lsh_dropout = 0., ff_dropout = 0., ff_activation = None, ff_mult = 4, ff_glu = False, post_attn_dropout = 0., layer_dropout = 0., lsh_attend_across_buckets = True, lsh_allow_duplicate_attention = True, random_rotations_per_head = False, twin_attention = False, use_scale_norm = False, use_rezero = False, use_full_attn = False, full_attn_thres = 0, reverse_thres = 0, num_mem_kv = 0, one_value_head = False, n_local_attn_heads = 0, pkm_layers = tuple(), pkm_num_keys = 128, Ks = None):\r\n\t\tsuper(Reformer, self).__init__() # only call `nn.Module` init\r\n\t\tself.dim = dim\r\n\t\tself.depth = depth\r\n\r\n\t\tself.bucket_size = bucket_size\r\n\t\tself.num_mem_kv = num_mem_kv\r\n\r\n\t\tself.twin_attention = twin_attention\r\n\t\tself.full_attn_thres = full_attn_thres\r\n\r\n\t\tget_attn = lambda K: QuantizedQKLSHSelfAttention(dim, heads, bucket_size, n_hashes, causal = causal, dim_head = dim_head, dropout = lsh_dropout, post_attn_dropout = post_attn_dropout, attn_chunks = attn_chunks, allow_duplicate_attention = lsh_allow_duplicate_attention, attend_across_buckets = lsh_attend_across_buckets, random_rotations_per_head = random_rotations_per_head, num_mem_kv = num_mem_kv, use_full_attn = use_full_attn, full_attn_thres = full_attn_thres, one_value_head = one_value_head, n_local_attn_heads = n_local_attn_heads, K = K)\r\n\t\tget_ff = lambda: Chunk(ff_chunks, FeedForward(dim, dropout = ff_dropout, activation = ff_activation, mult = ff_mult, glu = ff_glu), along_dim = -2)\r\n\t\tget_pkm = lambda: PKM(dim, num_keys = pkm_num_keys)\r\n\r\n\t\tif weight_tie:\r\n\t\t\tget_attn, get_ff, get_pkm = map(cache_fn, (get_attn, get_ff, get_pkm))\r\n\r\n\t\tblocks = []\r\n\r\n\t\tnorm_type = ScaleNorm if use_scale_norm else nn.LayerNorm\r\n\r\n\t\tresidual_fn_wrapper = ReZero if use_rezero else partial(PreNorm, norm_type, dim)\r\n\r\n\t\tfor ind in range(depth):\r\n\t\t\tlayer_num = ind + 1\r\n\t\t\tuse_pkm = layer_num in cast_tuple(pkm_layers)\r\n\t\t\tparallel_net = None\r\n\r\n\t\t\tattn = get_attn(Ks[ind])\r\n\r\n\t\t\tif use_pkm:\r\n\t\t\t\tparallel_net = get_pkm()\r\n\t\t\telif twin_attention:\r\n\t\t\t\tparallel_net = get_attn(Ks[ind])\r\n\t\t\telse:\r\n\t\t\t\tparallel_net = get_ff()\r\n\r\n\t\t\tf = residual_fn_wrapper(attn)\r\n\t\t\tg = residual_fn_wrapper(parallel_net)\r\n\r\n\t\t\tblocks.append(nn.ModuleList([f, g]))\r\n\r\n\t\tself.layers = ReversibleSequence(nn.ModuleList(blocks), layer_dropout = layer_dropout, reverse_thres = reverse_thres, send_signal = True)\r\n\r\nclass QuantizedQKReformerLM(ReformerLM):\r\n\tdef __init__(self, num_tokens, dim, depth, max_seq_len, heads = 8, dim_head = None, bucket_size = 64, n_hashes = 4, ff_chunks = 100, attn_chunks = 1, causal = False, weight_tie = False, lsh_dropout = 0., ff_dropout = 0., ff_mult = 4, ff_activation = None, ff_glu = False, post_attn_dropout = 0., layer_dropout = 0., random_rotations_per_head = False, twin_attention = False, use_scale_norm = False, use_rezero = False, use_full_attn = False, full_attn_thres = 0, reverse_thres = 0, num_mem_kv = 0, one_value_head = False, emb_dim = None, return_embeddings = False, weight_tie_embedding = False, fixed_position_emb = False, absolute_position_emb = False, axial_position_shape = None, n_local_attn_heads = 0, pkm_layers = tuple(), pkm_num_keys = 128, Ks = None):\r\n\t\tassert len(Ks) == depth\r\n\t\tsuper(ReformerLM, self).__init__() # only call `nn.Module` init\r\n\t\temb_dim = default(emb_dim, dim)\r\n\t\tself.max_seq_len = max_seq_len\r\n\r\n\t\tself.token_emb = nn.Embedding(num_tokens, emb_dim)\r\n\r\n\t\tself.to_model_dim = Identity() if emb_dim == dim else nn.Linear(emb_dim, dim)\r\n\r\n\t\tif absolute_position_emb:\r\n\t\t\tself.pos_emb = AbsolutePositionalEmbedding(emb_dim, max_seq_len)\r\n\t\telif fixed_position_emb:\r\n\t\t\tself.pos_emb = FixedPositionalEmbedding(emb_dim)\r\n\t\telse:\r\n\t\t\taxial_position_shape = default(axial_position_shape, (math.ceil(max_seq_len / bucket_size), bucket_size))\r\n\t\t\tself.pos_emb = AxialPositionalEmbedding(emb_dim, axial_position_shape)\r\n\r\n\t\tself.reformer = QuantizedQKReformer(dim, depth, max_seq_len, heads = heads, dim_head = dim_head, bucket_size = bucket_size, n_hashes = n_hashes, ff_chunks = ff_chunks, attn_chunks = attn_chunks, causal = causal, weight_tie = weight_tie, lsh_dropout = lsh_dropout, ff_mult = ff_mult, ff_activation = ff_activation, ff_glu = ff_glu, ff_dropout = ff_dropout, post_attn_dropout = 0., layer_dropout = layer_dropout, random_rotations_per_head = random_rotations_per_head, twin_attention = twin_attention, use_scale_norm = use_scale_norm, use_rezero = use_rezero, use_full_attn = use_full_attn, full_attn_thres = full_attn_thres, reverse_thres = reverse_thres, num_mem_kv = num_mem_kv, one_value_head = one_value_head, n_local_attn_heads = n_local_attn_heads, pkm_layers = pkm_layers, pkm_num_keys = pkm_num_keys, Ks = Ks)\r\n\t\tself.norm = nn.LayerNorm(dim)\r\n\r\n\t\tif return_embeddings:\r\n\t\t\tself.out = Identity()\r\n\t\t\treturn\r\n\r\n\t\tself.out = nn.Sequential(\r\n\t\t\tnn.Linear(dim, emb_dim) if emb_dim != dim else Identity(),\r\n\t\t\tnn.Linear(emb_dim, num_tokens) if not weight_tie_embedding else MatrixMultiply(self.token_emb.weight, transpose=True, normalize=True)\r\n\t\t)","sub_path":"image_generation_cifar/reformer_pytorch/quantized_qk_reformer.py","file_name":"quantized_qk_reformer.py","file_ext":"py","file_size_in_byte":16339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"162131863","text":"#!/usr/bin/env python\nimport os\nimport sys\n\nfrom setuptools import setup, find_packages, Command\n\nsys.path.insert(0, 'src')\nimport smsreport\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\n\n\nclass BowerInstallCommand(Command):\n user_options = []\n\n description = 'run bower install command'\n\n def initialize_options(self):\n pass\n\n def finalize_options(self):\n pass\n\n def run(self):\n cmd = ['bower', 'install']\n self.spawn(cmd)\n\nrequires = [\n 'Django==1.9.9',\n 'psycopg2==2.6.2',\n 'django-filter==0.14.0',\n 'django-picklefield==0.3.2',\n 'django-constance[database]==1.2',\n]\n\nsetup(\n name='smsreport',\n version='0.0.2',\n keywords='web django',\n packages=find_packages('src'),\n package_dir={'': 'src'},\n url='https://github.com/dmtmalin/smsreport',\n license='',\n author='dmt',\n author_email='',\n description='',\n zip_safe=False,\n include_package_data=True,\n install_requires=requires,\n entry_points={\n 'console_scripts': [\n 'smsreport = smsreport.manage:main',\n ]\n },\n cmdclass={\n 'bower_install': BowerInstallCommand,\n },\n data_files=[\n (smsreport.CONFIG_PATH, [os.path.join(BASE_DIR, 'config/settings.py')])\n ]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"499758792","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom . import views\nurlpatterns = [\n path('', views.index, name='index'),\n path('create-post', views.create_post, name='create-post'),\n path('likes', views.likes, name='likes'),\n path('saved', views.saved, name='saved'),\n path('create-story', views.create_story, name='create-story'),\n path('search', views.search, name='search'),\n path('follow', views.follow, name='follow'),\n path('like_list', views.like_list, name='like_list'),\n path('notification', views.notification, name='notification'),\n\n\n path('chat', views.chat, name='chat'),\n path('search-chat-user', views.searchUserChat, name='search-chat-user'),\n path('send-msg-to-partner', views.send_msg_to_partner, name='send-msg-to-partner'),\n path('chat-to-partner/<int:partner_id>', views.chat_to_partner, name='chat-to-partner'),\n\n\n\n path('post/<int:post_id>', views.post, name='post'),\n path('addComment', views.addComment, name='addComment'),\n path('addReply', views.addReply, name='addReply'),\n\n\n path('deleteContent', views.deleteContent, name='deleteContent'),\n path('changeCaption', views.changeCaption, name='changeCaption'),\n\n\n\n path('suggestions', views.suggestions, name='suggestions'),\n path('addCommentIndex', views.addCommentIndex, name='addCommentIndex'),\n\n\n\n path('sharePost', views.sharePost, name='sharePost'),\n path('share/<int:shared_id>', views.sharedPost, name='sharedPost')\n]","sub_path":"pages/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"10020595","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\"\"\"\nModule to collect configuration to run specific jobs\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\n\nimport os\nimport sys\nimport argparse\n\nfrom fermipy.jobs.file_archive import FileFlags\nfrom fermipy.jobs.chain import Link, Chain\nfrom fermipy.jobs.gtlink import Gtlink\nfrom fermipy.jobs.scatter_gather import ConfigMaker, build_sg_from_link\nfrom fermipy.jobs.lsf_impl import make_nfs_path, get_lsf_default_args, LSF_Interface\nfrom fermipy.diffuse.name_policy import NameFactory\nfrom fermipy.diffuse.binning import Component\nfrom fermipy.diffuse import defaults as diffuse_defaults\n\nNAME_FACTORY = NameFactory()\n\n\ndef create_link_gtexphpsun(**kwargs):\n \"\"\"Make a `fermipy.jobs.Gtlink` object to run gtexphpsun \"\"\"\n gtlink = Gtlink(linkname=kwargs.pop('linkname', 'gtexphpsun'),\n appname='gtexphpsun',\n options=dict(irfs=diffuse_defaults.gtopts['irfs'],\n evtype=(3, \"Event type selection\", int),\n emin=(100., \"Start energy (MeV) of first bin\", float),\n emax=(1000000., \"Stop energy (MeV) of last bin\", float),\n enumbins=(12,\"Number of logarithmically-spaced energy bins\", int),\n binsz=(1.,\"Image scale (in degrees/pixel)\", float), \n infile=(None, \"Input livetime cube file\", str),\n outfile=diffuse_defaults.gtopts['outfile']),\n file_args=dict(infile=FileFlags.input_mask,\n outfile=FileFlags.output_mask),\n **kwargs)\n return gtlink\n\ndef create_link_gtsuntemp(**kwargs):\n \"\"\"Make a `fermipy.jobs.Gtlink` object to run gtsuntemp \"\"\"\n gtlink = Gtlink(linkname=kwargs.pop('linkname', 'gtsuntemp'),\n appname='gtsuntemp',\n options=dict(expsun=(None, \"Exposure binned in healpix and solar angles\", str),\n avgexp=(None, \"Binned exposure\", str),\n sunprof=(None, \"Fits file containing solar intensity profile\", str),\n cmap=(\"none\", \"Counts map file\", str),\n irfs=diffuse_defaults.gtopts['irfs'],\n evtype=(3, \"Event type selection\", int),\n coordsys=(\"GAL\", \"Coordinate system (CEL - celestial, GAL -galactic)\", str),\n emin=(100., \"Start energy (MeV) of first bin\", float),\n emax=(1000000., \"Stop energy (MeV) of last bin\", float),\n enumbins=(12,\"Number of logarithmically-spaced energy bins\", int),\n nxpix=(1440, \"Size of the X axis in pixels\", int),\n nypix=(720, \"Size of the Y axis in pixels\", int),\n binsz=(0.25, \"Image scale (in degrees/pixel)\", float),\n xref=(0., \"First coordinate of image center in degrees (RA or GLON)\", float),\n yref=(0., \"Second coordinate of image center in degrees (DEC or GLAT)\", float),\n axisrot=(0., \"Rotation angle of image axis, in degrees\", float),\n proj=(\"CAR\", \"Projection method e.g. AIT|ARC|CAR|GLS|MER|NCP|SIN|STG|TAN\", str),\n outfile=diffuse_defaults.gtopts['outfile']),\n file_args=dict(expsun=FileFlags.input_mask,\n avgexp=FileFlags.input_mask,\n sunprof=FileFlags.input_mask,\n outfile=FileFlags.output_mask),\n **kwargs)\n return gtlink\n\n\n\n\n\nclass ConfigMaker_Gtexphpsun(ConfigMaker):\n \"\"\"Small class to generate configurations for gtexphpsun \n\n This takes the following arguments:\n --comp : binning component definition yaml file\n --data : datset definition yaml file\n \"\"\"\n default_options = dict(comp=diffuse_defaults.sun_moon['binning_yaml'],\n data=diffuse_defaults.sun_moon['dataset_yaml'])\n\n def __init__(self, link, **kwargs):\n \"\"\"C'tor\n \"\"\"\n ConfigMaker.__init__(self, link,\n options=kwargs.get('options', self.default_options.copy()))\n\n def build_job_configs(self, args):\n \"\"\"Hook to build job configurations\n \"\"\"\n job_configs = {}\n\n components = Component.build_from_yamlfile(args['comp'])\n NAME_FACTORY.update_base_dict(args['data'])\n\n for comp in components:\n zcut = \"zmax%i\" % comp.zmax\n key = comp.make_key('{ebin_name}_{evtype_name}')\n name_keys = dict(zcut=zcut,\n ebin=comp.ebin_name,\n psftype=comp.evtype_name,\n irf_ver=NAME_FACTORY.irf_ver(),\n fullpath=True)\n outfile = NAME_FACTORY.bexpcube_sun(**name_keys)\n job_configs[key] = dict(infile=NAME_FACTORY.ltcube_sun(**name_keys),\n outfile=outfile,\n irfs=NAME_FACTORY.irfs(**name_keys),\n evtype=comp.evtype,\n emin=comp.emin,\n emax=comp.emax,\n enumbins=comp.enumbins,\n logfile=outfile.replace('.fits', '.log'))\n\n return job_configs\n\n\nclass ConfigMaker_Gtsuntemp(ConfigMaker):\n \"\"\"Small class to generate configurations for gtsuntemp\n\n This takes the following arguments:\n --comp : binning component definition yaml file\n --data : datset definition yaml file\n --sourcekeys : Keys for sources to make template for\n \"\"\"\n default_options = dict(comp=diffuse_defaults.sun_moon['binning_yaml'],\n data=diffuse_defaults.sun_moon['dataset_yaml'],\n sourcekeys=diffuse_defaults.sun_moon['sourcekeys'])\n\n def __init__(self, link, **kwargs):\n \"\"\"C'tor\n \"\"\"\n ConfigMaker.__init__(self, link,\n options=kwargs.get('options', self.default_options.copy()))\n\n def build_job_configs(self, args):\n \"\"\"Hook to build job configurations\n \"\"\"\n job_configs = {}\n\n components = Component.build_from_yamlfile(args['comp'])\n NAME_FACTORY.update_base_dict(args['data'])\n\n for comp in components:\n for sourcekey in args['sourcekeys']:\n zcut = \"zmax%i\" % comp.zmax\n key = comp.make_key('{ebin_name}_{evtype_name}') + \"_%s\"%sourcekey\n name_keys = dict(zcut=zcut,\n ebin=comp.ebin_name,\n psftype=comp.evtype_name,\n irf_ver=NAME_FACTORY.irf_ver(),\n sourcekey=sourcekey,\n fullpath=True)\n outfile = NAME_FACTORY.template_sunmoon(**name_keys)\n job_configs[key] = dict(expsun=NAME_FACTORY.bexpcube_sun(**name_keys),\n avgexp=NAME_FACTORY.bexpcube(**name_keys),\n sunprof=NAME_FACTORY.angprofile(**name_keys),\n cmap='none',\n outfile=outfile,\n irfs=NAME_FACTORY.irfs(**name_keys),\n evtype=comp.evtype,\n emin=comp.emin,\n emax=comp.emax,\n enumbins=comp.enumbins,\n logfile=outfile.replace('.fits', '.log'))\n\n return job_configs\n\n\n\ndef create_sg_Gtexphpsun(**kwargs):\n \"\"\"Build and return a ScatterGather object that can invoke gtexphpsun\"\"\"\n appname = kwargs.pop('appname', 'fermipy-gtexphpsun-sg')\n link = create_link_gtexphpsun(**kwargs)\n linkname = kwargs.pop('linkname', link.linkname)\n\n batch_args = get_lsf_default_args() \n batch_interface = LSF_Interface(**batch_args)\n\n usage = \"%s [options]\"%(appname)\n description = \"Run gtexpcube2 for a series of event types.\"\n\n config_maker = ConfigMaker_Gtexphpsun(link)\n lsf_sg = build_sg_from_link(link, config_maker,\n interface=batch_interface,\n usage=usage,\n description=description,\n linkname=linkname,\n appname=appname,\n **kwargs)\n return lsf_sg\n\n\ndef create_sg_Gtsuntemp(**kwargs):\n \"\"\"Build and return a ScatterGather object that can invoke gtexphpsun\"\"\"\n appname = kwargs.pop('appname', 'fermipy-gtsuntemp-sg')\n link = create_link_gtsuntemp(**kwargs)\n linkname = kwargs.pop('linkname', link.linkname)\n\n batch_args = get_lsf_default_args() \n batch_interface = LSF_Interface(**batch_args)\n\n usage = \"%s [options]\"%(appname)\n description = \"Run gtexpcube2 for a series of event types.\"\n\n config_maker = ConfigMaker_Gtsuntemp(link)\n lsf_sg = build_sg_from_link(link, config_maker,\n interface=batch_interface,\n usage=usage,\n description=description,\n linkname=linkname,\n appname=appname,\n **kwargs)\n return lsf_sg\n\n\n\nclass SunMoonChain(Chain):\n \"\"\"Small class to construct sun and moon templates\n \"\"\" \n def __init__(self, linkname):\n \"\"\"C'tor\n \"\"\"\n link_gtexphpsun = create_sg_Gtexphpsun(linkname=\"%s.gtexphpsun\"%linkname,\n mapping={'data':'dataset_yaml',\n 'comp':'binning_yaml'})\n link_gtsuntemp = create_sg_Gtsuntemp(linkname=\"%s.gtsuntemp\"%linkname,\n mapping={'data':'dataset_yaml',\n 'comp':'binning_yaml'})\n options = diffuse_defaults.sun_moon.copy()\n options['dry_run'] = (False, 'Print commands but do not run', bool)\n parser = argparse.ArgumentParser(usage='fermipy-solar-chain',\n description=\"Build sun and moon templates\")\n Chain.__init__(self, linkname,\n appname='FIXME',\n links=[link_gtexphpsun, link_gtsuntemp],\n options=options,\n parser=parser)\n \n def run_argparser(self, argv):\n \"\"\"Initialize a link with a set of arguments using argparser\n \"\"\"\n args = Link.run_argparser(self, argv)\n for link in self._links.values():\n link.run_link(stream=sys.stdout, dry_run=True)\n return args\n\n\ndef create_chain_sun_moon(**kwargs):\n \"\"\"Build and return a `ResidualCRChain` object \"\"\"\n ret_chain = SunMoonChain(linkname=kwargs.pop('linkname', 'SunMoon'))\n return ret_chain\n\n\ndef invoke_sg_Gtexphpsun():\n \"\"\"Entry point for command line use for dispatching batch jobs \"\"\"\n lsf_sg = create_sg_Gtexphpsun()\n lsf_sg(sys.argv)\n\n\ndef invoke_sg_Gtsuntemp():\n \"\"\"Entry point for command line use for dispatching batch jobs \"\"\"\n lsf_sg = create_sg_Gtsuntemp()\n lsf_sg(sys.argv)\n\n\ndef main_chain():\n \"\"\"Energy point for running the entire Cosmic-ray analysis \"\"\"\n the_chain = SunMoonChain('SunMoon')\n args = the_chain.run_argparser(sys.argv[1:])\n the_chain.run_chain(sys.stdout, args.dry_run)\n the_chain.finalize(args.dry_run)\n\n\nif __name__ == '__main__':\n main_chain()\n","sub_path":"fermipy/diffuse/solar.py","file_name":"solar.py","file_ext":"py","file_size_in_byte":12185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"620102501","text":"# Mark and Toys\n\ndef maximumToys(prices, k): \n edited_lis = sorted([i for i in prices if i <= k])\n m = []\n for i in edited_lis:\n m.append(i)\n print(m, sum(m))\n if sum(m) > k:\n break\n if sum(m) >= k:\n m.pop(-1)\n return len(m)","sub_path":"Sorting/mark_and_toys.py","file_name":"mark_and_toys.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"28333511","text":"buka = open(\"d:\\latihan2.txt\", \"r\")\r\nfile = buka.readlines()\r\nfileMahasiswa = {}\r\n\r\nfor b in range(len(file)):\r\n\r\n mahasiswa = file[b] \r\n nim, nama, alamat = mahasiswa.split('|')\r\n alamat = alamat.replace('\\n', '') \r\n fileMhs = {'nim': nim, 'nama': nama, 'alamat': alamat}\r\n fileMahasiswa[nama] = fileMhs\r\n\r\nprint(fileMahasiswa)\r\nbuka.close()\r\n","sub_path":"Tugas9/latihan3.py","file_name":"latihan3.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"138518562","text":"\"\"\" aoc_22.py\n\n Solution for Advent of Code 2018\n\"\"\"\n\nimport aoc_22_input\n\n\ndef main():\n \"\"\" main()\n\n Main function that use the input from Advent of Code and print the\n answer to the problems for day one.\n \"\"\"\n aoc_input = aoc_22_input.get_input()\n\n print('Part 1: {}'.format(0))\n print('Part 2: {}'.format(0))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"2018/22/aoc_22.py","file_name":"aoc_22.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"306882656","text":"# Egypt - Masrawy\n# https://www.masrawy.com\n\n# This code uses BeautifulSoup to grab the title, article date, and article text from\n# a single article\n\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef grabPage(url):\n\n page = requests.get(url)\n soup = BeautifulSoup(page.content, 'lxml')\n\n title_box = soup.find('div', attrs={'class': 'articleHeader'}).find('h1')\n date_box = soup.find('div', attrs={'class': 'time icon-time'}).find_all('span')[1]\n article_box_group = soup.find('div', attrs={'class': 'details'}).find_all('p', attrs={'style': 'direction: rtl;'})\n\n try:\n title = title_box.text.strip()\n date = date_box.text.strip()\n article = ''\n for p in article_box_group:\n article += p.text.strip()\n return [title,date,article]\n\n except AttributeError as e:\n return([None,None,None])\n\nif __name__ == \"__main__\":\n\n page = 'https://www.masrawy.com/news/news_egypt/details/2019/2/15/1514740/'\n\n output = grabPage()\n for o in range (0,len(output)):\n print(output[o])","sub_path":"YaleBigData/SeleniumBeautifulSoup/Egypt/Masrawy_grabSingleArticle.py","file_name":"Masrawy_grabSingleArticle.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"429214142","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom data.mnist_seven import MNISTSeven\nfrom model.stupid_recognizer import StupidRecognizer\nfrom model.perceptron import Perceptron\nfrom model.logistic_regression import LogisticRegression\nfrom model.mlp import MultilayerPerceptron\nfrom report.evaluator import Evaluator\n\n\ndef main():\n #one_digit_data = MNISTSeven(\"../data/mnist_seven.csv\", 3000, 1000, 1000)\n #print(\"\")\n #runStupidClassifier(one_digit_data)\n #runPerceptronClassifier(one_digit_data)\n #runLogisticClassifier(one_digit_data)\n #one_digit_data = None\n\n all_digits_data = MNISTSeven(\"../data/mnist_seven.csv\", 3000, 1000, 1000, one_hot=False)\n print(\"\")\n runMultilayerClassifier(all_digits_data)\n\ndef trainAndEvaluateClassifier(classifier, test_set, verbose=False, graph=False):\n # Train\n print(\"Train \" + classifier.__class__.__name__ + \"..\")\n classifier.train(verbose=verbose, graph=graph)\n print(\"Done..\")\n print(\"\")\n\n # Evaluate\n print(\"Evaluate..\")\n pred = classifier.evaluate()\n print(\"Done..\")\n print(\"\")\n\n # Results\n print(\"Result:\")\n evaluator = Evaluator()\n # evaluator.printComparison(data.test_set, stupidPred)\n evaluator.printAccuracy(test_set, pred)\n print(\"\")\n\n\ndef runStupidClassifier(data):\n c = StupidRecognizer(data.training_set,\n data.validation_set,\n data.test_set)\n trainAndEvaluateClassifier(c, data.test_set)\n\ndef runPerceptronClassifier(data):\n c = Perceptron(data.training_set,\n data.validation_set,\n data.test_set,\n learningRate=0.005,\n epochs=10)\n trainAndEvaluateClassifier(c, data.test_set)\n\ndef runLogisticClassifier(data):\n c = LogisticRegression(data.training_set,\n data.validation_set,\n data.test_set,\n learningRate=0.005,\n epochs=30)\n trainAndEvaluateClassifier(c, data.test_set, verbose=True)\n\ndef runMultilayerClassifier(data):\n c = MultilayerPerceptron(data.training_set,\n data.validation_set,\n data.test_set,\n epochs=30,\n layers=MultilayerPerceptron.createLayers([784, 100, 10], 0.05))\n trainAndEvaluateClassifier(c, data.test_set, verbose=True)\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/Run.py","file_name":"Run.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"588811803","text":"from django.shortcuts import render,redirect\nfrom .forms import User_Form\nfrom . models import Category,Products,Cart,Order\nfrom django.contrib.auth import authenticate,login,logout\nfrom django.contrib.auth.models import User\n\nc=Category.objects.all()\np=Products.objects.all()\n# Create your views here.\ndef index(request):\n d={'clist':c,'plist':p}\n return render(request,'index.html',d)\n\ndef addUser(request):\n if request.method ==\"POST\":\n f=User_Form(request.POST)\n f.save()\n return redirect('/')\n else:\n f=User_Form()\n b={'form':f}\n return render(request,'form.html',b)\n\ndef user_login(request):\n if request.method == 'POST':\n uname=request.POST.get('username')\n passcode=request.POST.get('password')\n user=authenticate(request,username=uname,password=passcode)\n if user is not None:\n request.session['user_id1']=uname\n login(request,user)\n return redirect('/')\n else:\n return render(request,'login.html',{'err_msg':'Incorrect Username or Password'})\n else:\n return render(request,'login.html')\n\ndef user_logout(request):\n request.session.flush()\n logout(request)\n return redirect('/')\n\ndef getProductByCategory(request):\n id=request.GET.get('id')\n pl=Products.objects.filter(category_id=id)\n d={'clist':c,'plist':pl}\n return render(request,'index.html',d)\n\ndef searchProduct(request):\n if request.method == 'POST':\n pname=request.POST.get('sp')\n pl=Products.objects.filter(pname__icontains = pname)\n a={'clist':c,'plist':pl}\n return render(request,'searchProduct.html',a)\n else:\n d={'clist':c,'plist':p}\n return render(request,'searchProduct.html',d)\n\ndef addToCart(request):\n pid=request.GET.get('pid')\n prd=Products.objects.get(id=pid)\n uname=request.session.get('user_id1')\n usr=User.objects.get(username=uname)\n c=Cart()\n c.products=prd\n c.user=usr\n c.save()\n return redirect('/')\n\ndef cartList(request):\n u_name=request.session.get('user_id1')\n usr=User.objects.get(username=u_name)\n if request.method=='POST':\n totalBill=request.POST.get(\"bill\")\n order=Order()\n order.totalBill=totalBill\n order.user=usr\n order.save()\n cartlist=Cart.objects.filter(user_id=usr.id)\n for i in cartlist:\n i.delete()\n return redirect(\"/myOrder\")\n\n else:\n cartlist=Cart.objects.filter(user_id=usr.id)\n totalBill=0\n for i in cartlist:\n totalBill = totalBill + i.products.price\n\n d={'clist':c,'cartlist':cartlist,'totalBill':totalBill}\n return render(request,'cartList.html',d)\n\ndef deleteProduct_userCart(request,id):\n c=Cart.objects.get(id=id)\n c.delete()\n return redirect('/cartList')\n\ndef editProfile(request):\n u_name=request.session.get('user_id1')\n usr=User.objects.get(username=u_name)\n if request.method == \"POST\":\n f=User_Form(request.POST,instance=usr)\n f.save()\n return redirect('/')\n else:\n f=User_Form(instance=usr)\n d={'clist':c,'form':f}\n return render(request,'form.html',d)\n\ndef myOrder(request):\n u_name=request.session.get('user_id1')\n usr=User.objects.get(username=u_name)\n orlist=Order.objects.filter(user_id=usr.id)\n d={'catlist':c,'orderlist':orlist}\n return render(request,'myorder.html',d)\n\nfrom .models import MyImage\nfrom .forms import MyImageForm\ndef imagedata(request):\n\n if request.method=='POST':\n f=MyImageForm(request.POST,request.FILES)\n f.save()\n f=MyImageForm\n imagelist=MyImage.objects.all()\n return render(request,'imageaccess.html',{'imagelist':imagelist,'form':f})\n else:\n f=MyImageForm\n imagelist=MyImage.objects.all()\n return render(request,'imageaccess.html',{'imagelist':imagelist,'form':f})\n\ndef productList(request):\n d={'p':p}\n return render(request,'productList.html',d)\n","sub_path":"ecommercce/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"290224145","text":"#!/usr/bin/env python3\n\n#===============================================================================\n# JAVA AND SELENIUM INSTALLATION\n# Install pip\n# Install selenium\n# Install java\n#===============================================================================\n\nimport os\nimport requests\nimport time\n\ndef wait_until_is_downloaded(path, isDownloaded):\n time.sleep(3)\n if not isDownloaded:\n print(\"Is downloading\")\n downloads = os.listdir(path)\n count = 0\n for file in downloads:\n if file.endswith(\".part\"):\n count += 1\n if count != 0:\n wait_until_is_downloaded(path, False)\n print(\"FINISH\") \n \ndef install_java():\n username = \"javiernegsb1997@gmail.com\"\n password = \"Ingles123.\"\n filename = \"jdk-8u251-linux-x64.tar.gz\"\n path_jdk_downloaded = os.path.expanduser(\"~/Downloads/\" + filename);\n path_scriptfolder = os.path.expanduser(\"~/Desktop/scriptfiles\");\n \n print(\"Installing pip...\")\n _ = os.system('sudo apt install python3-pip')\n os.system(\"clear\")\n \n print(\"Installing selenium\")\n _ = os.system('pip3 install selenium')\n os.system(\"clear\")\n from selenium import webdriver\n \n print(\"Downloading firefox driver...\")\n r = requests.get('https://github.com/mozilla/geckodriver/releases/download/v0.26.0/geckodriver-v0.26.0-linux64.tar.gz', allow_redirects=True)\n f = open('geckodriver.tar.gz', 'wb').write(r.content)\n _ = os.system('tar -xf geckodriver.tar.gz'); # Unpack file\n \n print(\"Downloading Java 1.8\")\n _ = os.system('chmod +x ./geckodriver');\n \n print(\"Creating profile to Firefox\")\n profile = webdriver.FirefoxProfile()\n profile.set_preference(\"browser.helperApps.neverAsk.saveToDisk\",\"application/x-gzip\");\n \n print(\"Creating Web Driver and go to oracle downloads\")\n browser = webdriver.Firefox(firefox_profile=profile, executable_path='./geckodriver')\n browser.get('https://www.oracle.com/java/technologies/javase/javase-jdk8-downloads.html')\n time.sleep(10)\n \n print(\"Accept cookies\")\n iframe = browser.find_element_by_xpath('//*[@title=\"TrustArc Cookie Consent Manager\"]')\n browser.switch_to.frame(iframe);\n browser.find_element_by_link_text(\"I accept all cookies\").click()\n browser.switch_to.default_content();\n time.sleep(1)\n \n print(\"Download Linux file\")\n browser.find_element_by_xpath('/html/body/div[2]/section[5]/div/div/div/table/tbody/tr[6]/td[3]/div/a').click()\n time.sleep(1)\n browser.find_element_by_xpath('/html/body/div[5]/div/div[1]/div/div/div/form/ul/li/label/input').click()\n time.sleep(1)\n browser.find_element_by_xpath('/html/body/div[5]/div/div[1]/div/div/div/form/div/div[2]/div/div/a').click()\n time.sleep(5)\n \n print(\"Sign in and download file\")\n browser.find_element_by_xpath('//*[@id=\"sso_username\"]').send_keys(username)\n browser.find_element_by_xpath('//*[@id=\"ssopassword\"]').send_keys(password)\n browser.find_element_by_xpath('/html/body/div/div[3]/div[1]/form/div[2]/span/input').click()\n time.sleep(2)\n \n # Wait until is downloaded\n wait_until_is_downloaded(os.path.expanduser(\"~/Downloads\"), False)\n # Move file to our directory\n print(\"Extract JDK to Java's default location\")\n \n _ = os.system(\"mv \" + path_jdk_downloaded + \" \" + path_scriptfolder);\n \n _ = os.system(\"sudo mkdir /usr/lib/jvm\");\n os.chdir(\"/usr/lib/jvm\")\n _ = os.system(\"sudo tar -xvzf \" + path_scriptfolder + \"/\" + filename);\n \n print(\"Set environment variables\")\n _ = os.system(\"echo 'export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/lib/jvm/jdk1.8.0_251/bin:/usr/lib/jvm/jdk1.8.0_251/db/bin:/usr/lib/jvm/jdk1.8.0_251/jre/bin' >> ~/.bashrc\");\n _ = os.system(\"echo 'export J2SDKDIR=/usr/lib/jvm/jdk1.8.0_251' >> ~/.bashrc\");\n _ = os.system(\"echo 'export J2REDIR=/usr/lib/jvm/jdk1.8.0_251/jre' >> ~/.bashrc\");\n _ = os.system(\"echo 'export JAVA_HOME=/usr/lib/jvm/jdk1.8.0_251' >> ~/.bashrc\");\n _ = os.system(\"echo 'export DERBY_HOME=/usr/lib/jvm/jdk1.8.0_251/db' >> ~/.bashrc\");\n _ = os.system(\"exec bash\");\n\n \n print(\"Inform Ubuntu about the installed location\")\n _ = os.system('sudo update-alternatives --install \"/usr/bin/java\" \"java\" \"/usr/lib/jvm/jdk1.8.0_251/bin/java\" 0');\n _ = os.system('sudo update-alternatives --install \"/usr/bin/javac\" \"javac\" \"/usr/lib/jvm/jdk1.8.0_251/bin/javac\" 0');\n _ = os.system('sudo update-alternatives --set java /usr/lib/jvm/jdk1.8.0_251/bin/java');\n _ = os.system('sudo update-alternatives --set javac /usr/lib/jvm/jdk1.8.0_251/bin/javac');\n \n print(\"Setup verification\")\n _ = os.system('update-alternatives --list java');\n _ = os.system('update-alternatives --list javac');\n \n","sub_path":"Task5_EnvInstallaion/java.py","file_name":"java.py","file_ext":"py","file_size_in_byte":4831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"73753340","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\nGiven a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.\n\nA region is captured by flipping all 'O's into 'X's in that surrounded region.\n\nFor example,\nX X X X\nX O O X\nX X O X\nX O X X\nAfter running your function, the board should be:\n\nX X X X\nX X X X\nX X X X\nX O X X\n\"\"\"\n\n# 可能会stackoverflow\nclass Solution(object):\n def solve(self, board):\n \"\"\"\n :type board: List[List[str]]\n :rtype: void Do not return anything, modify board in-place instead.\n \"\"\"\n def search(i, j):\n board[i][j] = '*'\n if i - 1 > 0 and board[i-1][j] == 'O':\n search(i - 1, j)\n if i + 1 < m and board[i+1][j] == 'O':\n search(i + 1, j)\n if j - 1 > 0 and board[i][j-1] == 'O':\n search(i, j - 1)\n if j + 1 < n and board[i][j+1] == 'O':\n search(i, j + 1)\n if board:\n m = len(board)\n n = len(board[0])\n for i in xrange(n):\n if board[0][i] == 'O':\n search(0, i)\n if board[m-1][i] == 'O':\n search(m - 1, i)\n for i in xrange(m):\n if board[i][0] == 'O':\n search(i, 0)\n if board[i][n-1] == 'O':\n search(i, n - 1)\n for i in xrange(m):\n for j in xrange(n):\n board[i][j] = 'O' if board[i][j] == '*' else 'X'\n","sub_path":"Python/130-SurroundedRegions/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"614936025","text":"import math\n\nimport torch\nimport torch.nn as nn\n\n\ndef autopad(k, p=None): # kernel, padding\n # Pad to 'same'\n if p is None:\n p = (\n k // 2 if isinstance(k, int) else [x // 2 for x in k]\n ) # auto-pad\n return p\n\n\nclass Conv(nn.Module):\n # Standard convolution\n def __init__(\n self, c1, c2, k=1, s=1, p=None, g=1, act=True\n ): # ch_in, ch_out, kernel, stride, padding, groups\n super().__init__()\n self.conv = nn.Conv2d(\n c1, c2, k, s, autopad(k, p), groups=g, bias=False\n )\n self.bn = nn.BatchNorm2d(c2)\n self.act = (\n nn.SiLU()\n if act is True\n else (\n act if isinstance(act, nn.Module) else nn.Identity()\n )\n )\n\n def forward(self, x):\n return self.act(self.bn(self.conv(x)))\n\n def forward_fuse(self, x):\n return self.act(self.conv(x))\n\n\nclass DWConv(Conv):\n # Depth-wise convolution class\n def __init__(\n self, c1, c2, k=1, s=1, act=True\n ): # ch_in, ch_out, kernel, stride, padding, groups\n super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), act=act)\n\n\nclass Bottleneck(nn.Module):\n # Standard bottleneck\n def __init__(\n self, c1, c2, shortcut=True, g=1, e=0.5\n ): # ch_in, ch_out, shortcut, groups, expansion\n super().__init__()\n c_ = int(c2 * e) # hidden channels\n self.cv1 = Conv(c1, c_, 1, 1)\n self.cv2 = Conv(c_, c2, 3, 1, g=g)\n self.add = shortcut and c1 == c2\n\n def forward(self, x):\n return (\n x + self.cv2(self.cv1(x))\n if self.add\n else self.cv2(self.cv1(x))\n )\n\n\nclass C3(nn.Module):\n # CSP Bottleneck with 3 convolutions\n def __init__(\n self, c1, c2, n=1, shortcut=True, g=1, e=0.5\n ): # ch_in, ch_out, number, shortcut, groups, expansion\n super().__init__()\n c_ = int(c2 * e) # hidden channels\n self.cv1 = Conv(c1, c_, 1, 1)\n self.cv2 = Conv(c1, c_, 1, 1)\n self.cv3 = Conv(2 * c_, c2, 1) # act=FReLU(c2)\n self.m = nn.Sequential(\n *[\n Bottleneck(c_, c_, shortcut, g, e=1.0)\n for _ in range(n)\n ]\n )\n # self.m = nn.Sequential(*[CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)])\n\n def forward(self, x):\n return self.cv3(\n torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1)\n )\n\n\nclass SPP(nn.Module):\n # Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729\n def __init__(self, c1, c2, k=(5, 9, 13)):\n super().__init__()\n c_ = c1 // 2 # hidden channels\n self.cv1 = Conv(c1, c_, 1, 1)\n self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)\n self.m = nn.ModuleList(\n [\n nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2)\n for x in k\n ]\n )\n\n def forward(self, x):\n x = self.cv1(x)\n return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))\n\n\nclass Focus(nn.Module):\n def __init__(\n self, c1, c2, k=1, s=1, p=None, g=1, act=True\n ): # ch_in, ch_out, kernel, stride, padding, groups\n super().__init__()\n self.conv = Conv(c1 * 4, c2, k, s, p, g, act)\n\n def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)\n return self.conv(\n torch.cat(\n [\n x[..., ::2, ::2],\n x[..., 1::2, ::2],\n x[..., ::2, 1::2],\n x[..., 1::2, 1::2],\n ],\n 1,\n )\n )\n\n\nclass Concat(nn.Module):\n # Concatenate a list of tensors along dimension\n def __init__(self, dimension=1):\n super().__init__()\n self.d = dimension\n\n def forward(self, x):\n return torch.cat(x, self.d)\n","sub_path":"src/vtccvision/models/yolov5/_models/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":3870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"264533894","text":"#!/usr/bin/env python3\n\nfrom pathlib import Path\nfrom shutil import rmtree\n\ndatafolder = Path('/home/hernandom/data/Behavioural_Data/Bpod_data')\n\nfor folder in datafolder.glob('**/**/Data_Analysis'):\n print(f'::: {folder} :::')\n for content in folder.iterdir():\n print(content)\n content.rename(folder.parent / content.name)\n for item in folder.parent.iterdir():\n if item.is_dir():\n print(item)\n rmtree(str(item))\n","sub_path":"move_data_folders.py","file_name":"move_data_folders.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"133090404","text":"import matplotlib\nmatplotlib.use(\"TkAgg\")\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk\nfrom matplotlib.figure import Figure\nimport matplotlib.animation as animation\nfrom matplotlib import style, ticker\nfrom matplotlib import pyplot as plt\nfrom time import sleep\n\nfrom datetime import datetime\ndatetime(2019, 9, 28)\n\nimport tkinter as tk\nfrom tkinter.ttk import Label, Button, Frame, Entry\n\nfrom edwardsPGCController import EdwardsPGCController\nfrom mockController import MockController\nfrom logManager import LogManager\n#from animatedFigure import AnimatedFigure\n\n\"\"\"\nADD HERE ALL CHANNELS TO DISPLAY\n\"\"\"\nGAUGES = {\"Chamber 1\": [EdwardsPGCController(\"Chamber1\", \"COM9\", 19200, \"Edwards PGC202\")],\n \"Chamber 2\": [EdwardsPGCController(\"Chamber2\", \"COM8\", 19200, \"Edwards PGC202\")],\n \"Prepump\": [EdwardsPGCController(\"Prepump\", \"COM15\", 19200, \"Edwards PGC202\", default_channel=1)]\n }\n\nANIMATORS = []\n\n#LARGE_FONT = (\"Verdana\", 12)\nstyle.use(\"ggplot\")\n\nclass gaugeControllerApplication(tk.Tk):\n\n def __init__(self, default_animation_interval=1000, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.animation_interval = default_animation_interval\n self.winfo_toplevel().title(\"Pressure gauge controllers manager\")\n self.container = Frame(self)\n self.container.grid()\n self.init_measure_logging()\n self.init_interval_controls()\n self.init_gauge_handles()\n self.init_animations()\n\n def init_measure_logging(self):\n self.measure_log_handle = LogManager(\"logbook\")\n\n def init_interval_controls(self):\n interval_controls_frame = Frame(self.container, padding=(10, 10))\n interval_controls_frame.grid(row=0, column=0, columnspan=len(GAUGES))\n interval_controls_label = Label(interval_controls_frame, text=\"REFRESH [ms]\", padding=(10, 10))\n interval_controls_label.grid(row=0, column=0)\n self.interval_controls_input = Entry(interval_controls_frame)\n self.interval_controls_input.grid(row=0, column=1)\n self.interval_controls_input.insert(tk.END, self.animation_interval)\n interval_controls_save_button = Button(interval_controls_frame, text=\"SET\", command=self.set_animation_interval)\n interval_controls_save_button.grid(row=0, column=2)\n\n def set_animation_interval(self):\n interval_value = float(self.interval_controls_input.get())\n if interval_value < 3000:\n interval_value = 3000 \n self.animation_interval = interval_value\n self.interval_controls_input.delete(0, tk.END)\n self.interval_controls_input.insert(0, str(interval_value))\n self.update_animators(interval_value)\n\n def init_gauge_handles(self):\n col = 0\n self.gauge_handles = []\n for gauge_name, gauge_classes in GAUGES.items():\n self.container.grid_columnconfigure(col, weight=1)\n self.measure_log_handle.add_channel(gauge_classes[0].get_name())\n widget = gaugeWidget(self.container, self, gauge_name, self.measure_log_handle)\n self.gauge_handles.append(widget)\n col+=1\n for i in range(len(GAUGES)):\n self.gauge_handles[i].grid(row=1, column=i, sticky=\"W\")\n self.gauge_handles[i].tkraise()\n\n def init_animations(self):\n for gauges, gauge_parameters in GAUGES.items():\n gauge_parameters[1].refresh_figure(1)\n ANIMATORS.append(animation.FuncAnimation(gauge_parameters[2], gauge_parameters[1].refresh_figure, interval=self.animation_interval))\n\n def update_animators(self, interval):\n for animator in ANIMATORS:\n animator.event_source.interval=interval\n\n\nclass gaugeWidget(Frame):\n\n def __init__(self, parent, controller, gauge_name, instance_log_manager):\n Frame.__init__(self, parent)\n self.container = tk.Frame(self, padx=5, pady=5)\n GAUGES[gauge_name].append(self)\n self.gauge_name = gauge_name\n self.log_manager = instance_log_manager\n self.gauge_instance = GAUGES[gauge_name][0]\n self.init_title()\n self.init_animated_figure()\n self.init_controls()\n\n def init_title(self):\n title_frame = Frame(self, padding=(10, 10))\n title_frame.grid(row=0, column=0)\n #self.grid_columnconfigure(0, weight=1)\n #self.grid_rowconfigure(0, weight=1)\n title = Label(title_frame, text=self.gauge_name, font=(\"Sans\", 18))\n title.grid(row=0, column=0)\n information_str = \"{} | {} | FW-ver.: {}\".format(self.gauge_instance.get_product_name(), self.gauge_instance.get_port(), self.gauge_instance.read_version_number())\n informations = Label(title_frame, text=information_str, font=(\"Sans\", 10))\n informations.grid(row=1, column=0)\n\n def init_controls(self):\n if isinstance(self.gauge_instance, EdwardsPGCController):\n first_group = tk.Frame\n\n ## TODO: START HERE WITH UI-PROGRAMMING\n\n def init_animated_figure(self):\n self.x_values = []\n self.y_values = []\n figure = plt.figure()\n self.plt = plt\n GAUGES[self.gauge_name].append(figure)\n self.axes = figure.add_subplot(1, 1, 1)\n self.canvas = FigureCanvasTkAgg(figure, self)\n self.canvas.draw()\n self.canvas.get_tk_widget().grid(row=1, column=0)\n #self.canvas_background = self.canvas.copy_from_bbox(figure.bbox)\n\n def refresh_figure(self, i):\n #self.canvas.restore_region(self.canvas_background)\n self.x_values.append(datetime.now().strftime(\"%H:%M:%S\"))\n pressure_value = self.gauge_instance.read_pressure() \n if pressure_value != False:\n self.y_values.append(pressure_value[1])\n self.log_manager.append_value(self.gauge_instance.get_name(), pressure_value[1])\n else:\n self.y_values.append(0)\n self.log_manager.append_value(self.gauge_instance.get_name(), 0)\n self.x_values = self.x_values[-360:]\n self.y_values = self.y_values[-360:]\n self.axes.clear()\n ln, = self.axes.plot(self.x_values, self.y_values)\n self.format_figure()\n #return ln,\n #self.canvas.blit(self.axes.bbox)\n\n def format_figure(self):\n plt.sca(self.axes)\n plt.xticks(rotation=90, ha=\"right\")\n self.axes.xaxis.set_major_locator(ticker.MaxNLocator(4))\n plt.subplots_adjust(bottom=0.30)\n plt.ylabel('Pressure [mbar]')\n\n\n\napp = gaugeControllerApplication(default_animation_interval=1000*10)\n\n\napp.mainloop()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"11000387","text":"# 使用BeautifulSoup解析网页\r\n\r\nimport requests\r\nfrom bs4 import BeautifulSoup as bs\r\nimport re\r\n# bs4是第三方库需要使用pip命令安装\r\n\r\n\r\nuser_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36'\r\n\r\ncookie ='__mta=188530583.1593047225871.1593185358494.1593225778640.11; uuid_n_v=v1; uuid=2EC17180B68011EAAD7CEBC74F78E0F9DD26B3CEC01F4F87ABC6F58DECAC0426; _lxsdk_cuid=172e9039597c8-069e4aca47e822-4353761-1fa400-172e9039598c8; _lxsdk=2EC17180B68011EAAD7CEBC74F78E0F9DD26B3CEC01F4F87ABC6F58DECAC0426; mojo-uuid=42130ff45299550fcbc6964c316387d7; _csrf=9e18975dcc9dd6fc22535a95d46c15dc67f863c84ac51c418f079403c548c046; Hm_lvt_703e94591e87be68cc8da0da7cbd0be2=1593047226,1593075023; _lx_utm=utm_source%3DBaidu%26utm_medium%3Dorganic; __mta=188530583.1593047225871.1593178154867.1593178227507.9; mojo-session-id={\"id\":\"e131db068734a8d1cf2a6f40e1e6d7ca\",\"time\":1593225778472}; mojo-trace-id=1; Hm_lpvt_703e94591e87be68cc8da0da7cbd0be2=1593225779; _lxsdk_s=172f3a7b7cb-2ac-680-042%7C%7C3'\r\n\r\nheader = {'user-agent':user_agent,'Cookie':cookie}\r\n\r\nmyurl = 'https://maoyan.com/films?showType=3'\r\n\r\nresponse = requests.get(myurl,headers=header)\r\n\r\nbs_info = bs(response.text, 'html.parser')\r\n#print(bs_info)\r\n\r\nlink_list = []\r\n#考虑以字典的形式组装所有的电影形式,电影名称、类型、日期以列表的形式获取\r\nmovie_dict = {}\r\nmovie_name_list = []\r\nmovie_type_list = []\r\nmovie_date_list= []\r\n# 获取top10电影的链接\r\ntags_temp = bs_info.find_all('div', attrs={'class': 'movie-item film-channel'})\r\nfor tags in tags_temp[0:10]:\r\n for atag in tags.find_all('a',):\r\n link_temp = \"https://maoyan.com\" + atag.get('href')\r\n \r\n if link_temp not in link_list:\r\n link_list.append(link_temp)\r\n\r\n# movie_name_list.append(atag.get('title'))\r\n\r\n# print(atag.get('href'))\r\n # 获取所有链接\r\n# print(atag.get('title'))\r\n# print(atag.find('span',).text)\r\n # 获取电影名字\r\n\r\n#遍历top10的电影链接,取出上映时间和电影类型\r\nfor link_temp in link_list:\r\n response_temp = requests.get(link_temp,headers=header)\r\n bs_info_temp = bs(response_temp.text, 'html.parser')\r\n tags_temp = bs_info_temp.find_all('div', attrs={'class': 'movie-brief-container'})\r\n# print(tags_temp)\r\n li_temp = tags_temp[0].find_all('li', attrs={'class': 'ellipsis'})\r\n \r\n \r\n movie_name_temp = tags_temp[0].find_all('h1')\r\n movie_name_list.append(movie_name_temp[0].text)\r\n \r\n# print(li_temp)\r\n movie_date = li_temp[-1].text\r\n movie_date = re.search(r'(\\S+\\d)',movie_date).group()\r\n movie_date_list.append(movie_date)\r\n print(\"上映时间%s\" % movie_date)\r\n movie_type = \"\"\r\n for atag_temp in tags_temp[0].find_all('a',):\r\n movie_type_temp = atag_temp.text.strip()\r\n if movie_type == \"\":\r\n movie_type = movie_type_temp\r\n else:\r\n movie_type = movie_type + \",\" + movie_type_temp\r\n movie_type_list.append(movie_type)\r\n print(\"电影类型%s\" % movie_type)\r\n\r\nimport pandas as pd\r\n#将电影名称、类型、日期列表组装在字典里\r\nmovie_dict['name'] = movie_name_list\r\nmovie_dict['type'] = movie_type_list\r\nmovie_dict['date'] = movie_date_list\r\n\r\nprint(movie_dict)\r\n\r\nmovie_maoyan_req = pd.DataFrame(movie_dict,columns=['name','type','date'])\r\nmovie_maoyan_req.to_csv('./movie_maoyan_req.csv', encoding='gbk', index=False, header=False)\r\n\r\n\r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"week01/maoyan_requests.py","file_name":"maoyan_requests.py","file_ext":"py","file_size_in_byte":3537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"203001332","text":"from django.shortcuts import render, redirect\nfrom applstion.models import UserInfo, Publisher, Book, Author\n\n\n# Create your views here.\n# 登录功能\ndef login(request):\n if request.method == 'POST':\n user = request.POST.get('user')\n pwd = request.POST.get('pwd')\n if UserInfo.objects.filter(username=user, password=pwd):\n return redirect('/publisher_list/')\n return render(request, 'login.html', {'error_msg': '用户名或密码输入错误!'})\n return render(request, 'login.html')\n\n\n# 查看出版社名称\ndef publisher_list(request):\n # 获取数据库出版社所有的内容\n data = Publisher.objects.all()\n return render(request, 'publisher_list.html', {'publisher_list': data})\n\n\n# 增加出版社名称\ndef add_publisher(request):\n if request.method == 'POST':\n p_name = request.POST.get('name')\n Publisher.objects.create(p_name=p_name)\n return redirect('/publisher_list/')\n return render(request, 'add_publisher.html')\n\n\n# 删除出版社名称\ndef delete_publisher(request):\n delete = request.GET.get('id') # id 一定是\"/delete_publisher/?id={{ publisher.id }}\"的id\n Publisher.objects.get(id=delete).delete()\n return redirect('/publisher_list/')\n\n\n# 修改出版社名称\ndef edit_publisher(request):\n # 判断是否是post\n if request.method == 'POST':\n # 如果是,获取用户输入的内容\n new_name = request.POST.get('name')\n new_id = request.POST.get('id')\n data = Publisher.objects.get(id=new_id)\n data.p_name = new_name\n data.save() # 更新到数据库中\n return redirect('/publisher_list/')\n # 获取数据库里的内容\n data_id = request.GET.get('id')\n data = Publisher.objects.get(id=data_id) # 总是忘记前面写id=或者name=一定记得要写对应关系,不然数据库不知道怎么对应找\n # 不是 ,点击编辑按钮,获取编辑页面\n return render(request, 'edit_publisher.html', {'obj': data})\n\n\n# 查看书籍名跟出版社名\ndef select_book(request):\n all_book = Book.objects.all()\n all_publisher = Publisher.objects.all()\n return render(request, 'select_book.html', {'book_list': all_book, 'publisher_list': all_publisher}) #\n\n\n# # 增加书名跟出版社名,无模态框\n# def add_book(request):\n# if request.method == 'POST':\n# book_name = request.POST.get('b_name')\n# publisher_id = request.POST.get('id')\n# data = Book.objects.create(b_name=book_name, publisher_id=publisher_id)\n# return redirect('/select_book/')\n# return render(request, 'add_book.html')\n\n\n# 增加书名跟出版社名,点击出现模态框\ndef add_book(request):\n b_name = request.POST.get('b_name')\n publisher_id = request.POST.get('publisher')\n Book.objects.create(b_name=b_name, publisher_id=publisher_id)\n # Book.objects.create(b_name=b_name, publisher=Publisher.objects.get(id=publisher_id))\n return redirect('/select_book/') # 循环出版社名称时一直显示不出来\n\n\n# 删除书名和出版社,结果全部删除了\ndef delete_book(request):\n delete_id = request.GET.get('id')\n Book.objects.filter(id=delete_id).delete() # 这边用了get\n return redirect('/select_book/')\n\n\n# 修改书名跟出版社名\ndef edit_book(request):\n # 先获取要编辑的书籍的id\n b_id = request.GET.get('id')\n # 在获取要编辑的书籍的对象\n b_obj = Book.objects.get(id=b_id)\n # 判断是否是POST\n if request.method == 'POST':\n new_b_name = request.POST.get('b_name')\n new_p_id = request.POST.get('publisher')\n b_obj.b_name = new_b_name\n b_obj.publisher_id = new_p_id\n b_obj.save()\n return redirect('/select_book/') # 这个跳转不成功\n # 拿到所有的出版社数据,用来展示页面上的select标签\n all_publisher = Publisher.objects.all()\n return render(request, 'edit_book.html', {'book': b_obj, 'publisher_list': all_publisher})\n\n\n# 查看作者表格\ndef author_list(request):\n data = Author.objects.all()\n book_all = Book.objects.all()\n return render(request, 'author_list.html', {'author_list': data,'book_list':book_all})\n\n\n# 修改作者表格,书名\ndef edit_author(request):\n # pass\n # 从数据库中提取到作者信息\n a_id = request.GET.get('id')\n author_obj = Author.objects.get(id=a_id) # 获取一个作者对象all是获取的一个所有的作者的对象的列表\n\n # 判断是否是post\n if request.method == 'POST':\n new_a_name = request.POST.get('author_name')\n new_a_age = request.POST.get('age')\n new_book_id = request.POST.getlist('book') # 获取的是一个列表,并且里面全部是id\n\n # 把新的数据替换到数据库中\n author_obj.a_name = new_a_name\n author_obj.age = new_a_age\n author_obj.save()\n\n # 把书籍名称更新到第三章表格中,之所以author_obj能调用book是因为它本身在Python中是属于Author类中的,并不涉及到数据库层面\n author_obj.book.set(new_book_id) # set设置:在列表找寻,如果原来有,就留着,如果原来没有就加上\n # 把作者关联的书籍id设置成指定的值\n return redirect('/author_list/')\n # 把所提取的信息放在input框中\n book_all = Book.objects.all()\n return render(request, 'edit_author.html', {'author':author_obj,'book_list':book_all})\n\n\n# 删除作者表格,书名\ndef delete_author(request):\n a_delete = request.GET.get('id')\n Author.objects.filter(id=a_delete).delete()\n return redirect('/author_list/')\n\n\n# 增加作者,书名\ndef add_author(request):\n if request.method == 'POST':\n # 获取作者名跟书的id\n data = request.POST.get('a_name')\n a_age = request.POST.get('a_age')\n book_id = request.POST.getlist('book') # 一个列表\n # 创建一个新的作者\n author_obj = Author.objects.create(a_name=data,age=a_age)\n # 创建第三张表格中的书籍\n book_obj = author_obj.book.add(*book_id) # 因为book_id里面可能会有很多个id值,所以打散传入,*是打散\n return redirect('/author_list/')\n boos = Book.objects.all()\n return render(request,'author_list.html',{'book_list':boos})\n\n\n\n","sub_path":"datas/applstion/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"89194805","text":"from lookup import Lookup_table as lt\r\nfrom ops_comp import OPS\r\nimport os\r\nimport sys\r\nimport torch\r\n\r\nif __name__=='__main__':\r\n os.environ[\"CUDA_VISIBLE_DEVICES\"]='3'\r\n torch.backends.cudnn.benchmark = True\r\n shapes=[\r\n (3,64,64),\r\n (64,32,32),\r\n (64,32,32),\r\n (128,16,16),\r\n (128,16,16),\r\n (128,16,16),\r\n (256,8,8),\r\n (256,8,8),\r\n ]\r\n l=lt(OPS,shapes,name='comp')\r\n ss=l.get()\r\n for s in ss:\r\n print(s)","sub_path":"lookup/comp.py","file_name":"comp.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"311715252","text":"n=int(input())\r\nnumbers = [int(n) for n in input().split()]\r\nmin=0\r\nmax=0\r\nz=sorted(numbers)\r\nprint(z)\r\nfor i in z:\r\n max=sum(z[1:n])\r\n min=sum(z[:n-1])\r\nprint(min,max) \r\n","sub_path":"minmax.py","file_name":"minmax.py","file_ext":"py","file_size_in_byte":180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"595376878","text":"#!/bin/env/python\nimport pygame\nfrom pygame.locals import *\nimport shapes_center\nimport sys\nimport math\nimport random\n\ndef get_pos(degree, radius, xCenter, yCenter):\n assert degree <= 360.0 # not needed mathmatically. \n angle = math.radians(degree)\n x = xCenter + radius * math.cos(angle)\n y = yCenter + radius * math.sin(angle) \n\n return ( int(x), int(y))\n\ndef main(resolution, fullscreen=False, num_objects=24, radius=300):\n #radius = int (9.0 * float(resolution[1] / num_circles))\n res_x_half = resolution[0] / 2\n res_y_half = resolution[1] / 2 \n # start everything\n pygame.init()\n if fullscreen:\n screen = pygame.display.set_mode(resolution, FULLSCREEN)\n else:\n screen = pygame.display.set_mode(resolution, DOUBLEBUF)\n pygame.mouse.set_visible(False) \n pygame.display.set_caption(\"squares\")\n\n # start everything else\n clock = pygame.time.Clock()\n pygame.display.flip() \n while True:\n clock.tick(10)\n\n for event in pygame.event.get():\n if event.type == QUIT or event.type == KEYDOWN:\n pygame.quit(); sys.exit();\n\n screen.fill(pygame.color.Color(\"black\"))\n \n x,y = ( random.randint(0, resolution[0]), random.randint(0, resolution[1])) \n degree = random.uniform(0, 360)\n randnum = random.randint(1, 50) \n for i in range(randnum):\n x += random.uniform(-20,20)\n y += random.uniform(-10,10)\n r = (i+1) * 10 \n #pygame.draw.circle(screen, pygame.color.Color(\"blue\"), pos, r, 4) \n #shapes_center.square(screen, pygame.color.Color(\"green\"), pos, r, 4)\n #shapes_center.square(screen, pygame.color.Color(\"green\"), pos, r/2, 4)\n #shapes_center.octagon(screen, pygame.color.Color(\"yellow\"), pos, r, 4)\n shapes_center.hexagon(screen, pygame.color.Color(\"green\"), (x,y), r, 4)\n \n pygame.display.flip()\n\n \n\nif __name__ == '__main__':\n main(resolution=(1024,768), fullscreen=True, num_objects=24, radius=240)\n #main(resolution=(1440,900), fullscreen=True, num_objects=128, radius=320)\n #main(resolution=(1280,1024), fullscreen=False, num_objects=24, radius=320)\n","sub_path":"python/graphics/concentric-01.py","file_name":"concentric-01.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"565763899","text":"# Trying to improve bishop magics\n\nimport random, math\nimport numpy as np\nimport pickle\nimport tqdm\nfrom pcs import bishop\n\nedge_mask = 0x7E7E7E7E7E7E00\n\n# Function for helping the visualization of bitboards\ndef viz_bb(bb):\n\tstring_buf='{:064b}'.format(bb)\n\tfor i in range(64):\n\t\tif i%8==0 and i!=0:\n\t\t\tprint()\n\t\t\tprint(string_buf[i],end='')\n\t\telse:\n\t\t\tprint(string_buf[i],end='',sep='')\n\tprint('\\n----')\n\n# Function for convering binary list of length 64 to integer\ndef b64_2_int(list):\n\tacum=0x0\n\tfor i in range(64):\n\t\tacum+=int(list[i]*2**(63-i))\n\treturn acum\n\n# Get hamming weight from integer\ndef hamming_weight(x):\n\tbin_str=bin(x)[2:]\n\tcnt=0\n\tfor bit in bin_str:\n\t\tif bit=='1':\n\t\t\tcnt+=1\n\treturn cnt\n\n# From an int, returns a string with left side zero fill to target length\ndef zero_fill(x,target_len):\n\tbin_str=bin(x)[2:]\n\tmissing_len=target_len-len(bin_str)\n\tleft_fill=''\n\tfor i in range(missing_len):\n\t\tleft_fill+='0'\n\treturn left_fill+bin_str\n\n\n\n# Function for generating attack masks\ndef gen_att_masks():\t\n\tattack_list=[]\n\tfor i in range(64):\n\t\tsquare_efen=[]\n\t\tattack_set_bishop=bishop(color=0, sqr=i)\n\t\t# Set up empty board with bishop in square i\n\t\tfor j in range(64):\n\t\t\tif j!= i:\n\t\t\t\tsquare_efen.append('u')\n\t\t\telse:\n\t\t\t\tsquare_efen.append('B')\n\t\tsquare_efen=''.join(square_efen)\n\t\tsquare_efen=square_efen+' w - - 0 1'\n\t\t# Get bishop controlled squares\n\t\t_,ctrl_sqrs=attack_set_bishop.avl_movs(square_efen, return_ctrl_sqr=True)\n\t\tattack_set=np.zeros(64)\n\t\tfor j in range(64):\n\t\t\tif j in ctrl_sqrs:\n\t\t\t\tattack_set[j]=1\n\t\t# Add to list of attack set masks\n\t\tattack_list.append(attack_set)\n\n\t# Convert list of binaries into int masks\n\tattack_masks=[]\n\tfor attack in attack_list:\n\t\tattack_masks.append(b64_2_int(attack))\n\treturn attack_masks\n\ndef gen_block_sets(attack_masks):\n\t# For each square attack set generate relevant blocker sets\n\tblocker_sets=[] # Contains a list for each square, containing all possible blocker arrangements relevant for that square\n\tfor i in range(64):\n\t\t# Get relevant blocker squares\n\t\trel_sqrs=[]\n\t\tfor j in range(64):\n\t\t\tif '{:064b}'.format(attack_masks[i]&edge_mask)[j]=='1':\n\t\t\t\trel_sqrs.append(j)\n\t\t# How many blocker squares?\n\t\tn_bits=len(rel_sqrs)\n\t\t# Get all possible blocker arrangements (i.e. count in binary to n_bits)\t\n\t\tblocker_group=[]\n\t\tfor j in range(2**n_bits):\n\t\t\tblockers=['0' for ii in range(64)]\n\t\t\tbin_j=zero_fill(j,n_bits)\n\t\t\tfor k in range(n_bits):\n\t\t\t\tblockers[rel_sqrs[k]]=bin_j[k]\n\t\t\tblocker_group.append(''.join(blockers))\n\t\tblocker_sets.append(blocker_group)\n\treturn blocker_sets\n\ndef gen_min_move_sets(blocker_sets):\n\t# Returns distinct move sets of each square\n\t# (initially of the size of the blocker arrangements, then smaller)\n\tmove_sets=[] # List of pseudolegal move bitboards for each square given each blocker arangement of that square\n\tfor i in range(64):\n\t\tvalid_moves_list=[] # List of distinct pseudolegal move bitboards for THIS square\n\t\ttest_bishop=bishop(color=0, sqr=i)\n\t\tfor blockers in blocker_sets[i]:\n\t\t\t# Create a efen for this blocker arrangement with enemy pawns for blockers\n\t\t\tblockers_efen=['p' if blockers[j]=='1' else 'u' for j in range(64)]\n\t\t\tblockers_efen[i]='B'\n\t\t\tblockers_efen=''.join(blockers_efen)+' w - - 0 1'\n\t\t\t# Compute pseudolegal moves and convert bitboard to int\n\t\t\t_,ctrl_sqrs=test_bishop.avl_movs(blockers_efen, return_ctrl_sqr=True)\n\t\t\tmoves=[1 if j in ctrl_sqrs else 0 for j in range(64)]\n\t\t\tmoves=b64_2_int(moves)\n\t\t\t# Add to list if it is not in list\n\t\t\tif moves not in valid_moves_list:\n\t\t\t\tvalid_moves_list.append(moves)\n\t\tmove_sets.append(valid_moves_list)\n\treturn move_sets\n\ndef gen_move_sets(blocker_sets):\n\t# Returns distinct move sets of each square\n\t# (initially of the size of the blocker arrangements, then smaller)\n\tmove_sets=[] # List of pseudolegal move bitboards for each square given each blocker arangement of that square\n\tfor i in range(64):\n\t\tvalid_moves_list=[] # List of distinct pseudolegal move bitboards for THIS square\n\t\ttest_bishop=bishop(color=0, sqr=i)\n\t\tfor blockers in blocker_sets[i]:\n\t\t\t# Create a efen for this blocker arrangement with enemy pawns for blockers\n\t\t\tblockers_efen=['p' if blockers[j]=='1' else 'u' for j in range(64)]\n\t\t\tblockers_efen[i]='B'\n\t\t\tblockers_efen=''.join(blockers_efen)+' w - - 0 1'\n\t\t\t# Compute pseudolegal moves and convert bitboard to int\n\t\t\t_,ctrl_sqrs=test_bishop.avl_movs(blockers_efen, return_ctrl_sqr=True)\n\t\t\tmoves=[1 if j in ctrl_sqrs else 0 for j in range(64)]\n\t\t\tmoves=b64_2_int(moves)\n\t\t\t# Add to list\n\t\t\tvalid_moves_list.append(moves)\n\t\tmove_sets.append(valid_moves_list)\n\treturn move_sets\n\n\ndef improve_magics(blocker_sets, min_max_bits, n_tries=1000000):\n\t# Generate a magic for each square\n\tdatabase=[]\n\tfor i in range(64):\n\t\tprint('Trying n={}'.format(i),end='')\n\t\t# Init database of (move_list, magic number, bits) tuples for each square\n\t\t# Prepare bishop \n\t\ttest_bishop=bishop(color=0, sqr=i) \n\t\t# Leave for other function: Start from the more compressed table and go towards the more expansive table\n\t\t#for bits in range(min_max_bits[i][0],min_max_bits[i][1]+1):\n\t\t# For now, use max bits\n\t\tfor bits in [min_max_bits[i][1]-1]:\n\t\t\t# Flag to see if we found a magic of size bits\n\t\t\tfound_magic=False\n\t\t\tfor j in tqdm.tqdm(range(int(n_tries))):\n\t\t\t\t# Fail flag starts false, is raised if clash occurs\n\t\t\t\tfail_flag=False\n\t\t\t\t# Generate a 64 bit magic number candidate with few nonzero bits\n\t\t\t\tmagic_cand=random.getrandbits(64)&random.getrandbits(64)\n\t\t\t\t# Start with empty move list of size 2^bits every try\n\t\t\t\tmoves_list=[None] * (2**bits)\n\t\t\t\t# Go through each blocker arrangement for this square\n\t\t\t\tfor k in range(len(blocker_sets[i])):\n\t\t\t\t\tmoves=move_sets[i][k]\n\t\t\t\t\t# Get index from magic number and bitshift\n\t\t\t\t\tidx=((int(blocker_sets[i][k],2)*magic_cand)&0xFFFFFFFFFFFFFFFF\t)>>(64-bits)\n\n\t\t\t\t\t# If database[index] is not None and the result board stored there is not compatible with variation, then we have a clash and we have to try a new magic number.\n\t\t\t\t\tif moves_list[idx]!=None and moves_list[idx]!=moves:\n\t\t\t\t\t\t# Clash!\n\t\t\t\t\t\tfail_flag=True\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\t# Otherwise, store moves in the database\n\t\t\t\t\t\tmoves_list[idx]=moves\n\t\t\t\t# If clash didn't occur, then we found a magic of size 'bits'\n\t\t\t\tif fail_flag==False:\n\t\t\t\t\tfound_magic=True\n\t\t\t\t\t# Store: move sets, magic number, bits\n\t\t\t\t\tdatabase.append((moves_list, magic_cand, bits))\n\t\t\t\t\tprint('Improved n={} with {} bits, max of {} bits'.format(i,bits,min_max_bits[i][1]))\n\t\t\t\t\t# Break out of 'tries' loop\n\t\t\t\t\tbreak\n\t\t\tif found_magic==True:\n\t\t\t\t# Stop right after we found a magic of size bits, since bits will only increase here\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\t# If we didn't find a magic for this number, print fail message and append none to list\n\t\t\t\tprint(' |Failed for n={} with {} of {} bits'.format(i,bits,min_max_bits[i][1]))\n\t\t\t\tdatabase.append(None)\n\t\t\n\treturn database\n\n\n\n# Generate attack set masks (for each square)\nattack_masks=gen_att_masks()\n# Generate relevant blocker arrangements (for each square)\nblocker_sets=gen_block_sets(attack_masks)\n# Find out what the minimal move set table looks like and their sizes\nsmallest_move_sets=gen_min_move_sets(blocker_sets)\n# Precaulculate move sets for each square and blocker arrangement\nmove_sets=gen_move_sets(blocker_sets)\n# Get sizes of the most compressed tables and the largest addressable table for each square\nmin_max_move_set_sizes=[(len(smallest_move_sets[i]),len(blocker_sets[i])) for i in range(64)] # Tuples (min size, max size)\n# Calculate how many bits in the max and min move tables\nmin_max_bits=[(math.ceil(math.log(x[0],2)), math.ceil(math.log(x[1],2))) for x in min_max_move_set_sizes]\n\ndatabase = pickle.load( open( \"bishop_magics.p\", \"rb\" ) )\n\nimp_database=improve_magics(blocker_sets, min_max_bits, n_tries=10000000)\n\nif imp_database!=[None]*len(imp_database):\n\tprint(imp_database)\n\tprint([None]*len(imp_database))\n\tpickle.dump( imp_database, open( \"improved_bishop_magics.p\", \"wb\" ) )","sub_path":"magics/improve_b_magics.py","file_name":"improve_b_magics.py","file_ext":"py","file_size_in_byte":7942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"605399697","text":"from openpyxl import load_workbook\nfrom Common.Reflection import get_data\n\n\nclass Case:\n def get_case(self, file_name, sheet_name): # 读excel测试用例\n wb = load_workbook(file_name)\n title = []\n sheet = wb[sheet_name]\n for j in range(1, sheet.max_column + 1):\n title.append(sheet.cell(1, j).value)\n setattr(get_data, \"title_case\", title)\n test_case = []\n for i in range(3, sheet.max_row + 1):\n data = {}\n for j in range(1, sheet.max_column + 1):\n if title[j - 1] is not None:\n data[title[j - 1]] = sheet.cell(i, j).value\n test_case.append(data)\n return test_case\n\n def get_variable(self, file_name, sheet_name): # 读excel变量基础数据\n wb = load_workbook(file_name)\n title = []\n data = {}\n sheet = wb[sheet_name]\n for j in range(1, sheet.max_row + 1):\n title.append(sheet.cell(j, 1).value)\n for j in range(1, sheet.max_row + 1):\n if title[j - 1] is not None:\n data[title[j - 1]] = sheet.cell(j, 2).value\n return data","sub_path":"pytest_api/Common/Read_case.py","file_name":"Read_case.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"251021244","text":"def read(typ)->int:\n\treturn typ(input())\ndef read_arr(typ)->list:\n\treturn list(map(typ,input().split()))\nclass graph:\n\tdef __init__(self):\n\t\tself.gp = dict()\n\tdef create(self,paths = list()):\n\t\tfor start,end in paths:\n\t\t\tif not self.gp.get(start):\n\t\t\t\tself.gp[start] = list()\n\t\t\tif not self.gp.get(end):\n\t\t\t\tself.gp[end] = list()\n\t\t\tself.gp[start].append(end)\n\t\t\tself.gp[end].append(start)\t\t\n\tdef bfs(self,current:int):\n\t\tn = len(self.gp)\n\t\tvisited = [False for i in range(n+1)]\n\t\tqueue = [current]\n\t\twhile queue:\n\t\t\ttmp = queue.pop()\n\t\t\tif not visited[tmp]:\n\t\t\t\tprint(tmp,end = ' ')\n\t\t\tvisited[tmp] = True\n\t\t\tfor i in self.gp.get(tmp):\n\t\t\t\tif not visited[i] :\n\t\t\t\t\tqueue.append(i)\ndef dfs_helper(self,visited:list,current:int):\n\t\tprint(current,end=' ')\n\t\tvisited[current] = True\n\t\tfor i in self.gp.get(current):\n\t\t\tif visited[i] == False:\n\t\t\t\tself.dfs_helper(visited,i)\ndef dfs(self,start:int):\n\t\tn = len(self.gp)\n\t\tvisited = [False for i in range(n+1)]\n\t\tself.dfs_helper(visited,start)\nn = read(int)\npaths = list()\nfor i in range(n):\n\ttmp = read_arr(int)\n\tpaths.append(tmp)\nobj = graph()\nobj.create(paths)\nobj.bfs(4)\nprint()\n","sub_path":"Graph.py","file_name":"Graph.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"614826009","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import roc_curve, auc\n\n\n##########################################################\n# Fonction de perte au cours de l'entraînement du modèle #\n##########################################################\n\ndef courbe_loss(history_loss, history_val_loss, machinetype, xlim=None, ylim=None):\n # Labels et limites des axes\n plt.xlabel('Epochs')\n plt.ylabel('Accuracy')\n \n # Limites des axes\n if xlim!=None : plt.xlim(xlim)\n if ylim!=None : plt.ylim(ylim)\n\n # Traçage de la courbe de la précision sur l'échantillon de validation\n plt.plot([x for x in range(len(history_loss))],\n history_loss, \n label = 'Loss',\n color = 'red') \n \n # Traçage de la courbe de la précision sur l'échantillon d'entrainement\n plt.plot([x for x in range(len(history_val_loss))],\n history_val_loss,\n label = 'Validation Loss',\n color = 'blue')\n \n #Titre\n plt.title(\"Évolution de la fonction de perte lors de l'apprentissage sur la machine \"+machinetype)\n # Affichage de la légende\n plt.legend()\n \n # Affichage de la figure\n return plt.show()\n\n##########################################################\n# Calcul des données à partir des fichiers de sauvegarde #\n##########################################################\n\ndef get_y_true(path_csv, machinetype, machineID):\n df = pd.read_csv(path_csv)\n return df[(df.Dataset == \"test\") & (df.Machine_Type == machinetype) & (df.Machine_ID == machineID)]['Status'].replace(['normal', 'anomaly'], [0,1])\n \n\ndef get_y_pred(percentile, errors_train, errors_test):\n seuil = np.percentile(errors_train,percentile)\n return np.where(errors_test[:] > seuil, 1, 0)\n\n\n################################################################\n# Fonctions d'affichage de graphiques sur les données d'une ID #\n################################################################\n \n# ROC Curve\ndef courbe_ROC(y_true, errors_test, machinetype, machineID):\n # calcul des données\n fpr, tpr, seuils = roc_curve(y_true, errors_test, pos_label = 1)\n roc_auc = auc(fpr, tpr)\n \n # Définition des limites des axes\n plt.xlim(0,1)\n plt.ylim(0,1.05)\n \n # Traçage des courbes\n plt.plot(fpr, tpr, 'orange', label = 'Modèle conv. (auc = %0.2f)' % roc_auc)\n plt.plot(fpr, fpr, 'b--', label = 'Aléatoire (aux = 0.5)')\n \n #Titre\n plt.title('Courbe ROC associée à la machine '+machinetype+'_'+machineID)\n \n #Noms des axes\n plt.xlabel('Taux faux positifs')\n plt.ylabel('Taux vrais positifs')\n \n # Affichage de la légende\n plt.legend(loc = 'lower right')\n \n # Affichage de la figure\n return plt.show()\n\n \n\n# F1-scores\ndef courbes_f1score(f1_1, f1_0, somme, machinetype, machineID):\n # Traçage des courbes\n plt.plot(range(101),f1_1,label=\"Anomaly\")\n plt.plot(range(101),f1_0,label=\"Normal\")\n plt.plot(range(101),somme,label=\"Somme\")\n \n # Noms des axes\n plt.xlabel('Percentile de seuil')\n plt.ylabel('F1-score')\n \n #Titre\n plt.title('Courbes des F1-scores associés à la machine '+machinetype+'_'+machineID)\n \n # Affichage de la légende\n plt.legend()\n \n # Affichage de la figure\n plt.show()\n \n return print('\\nLe score F1 maximum de la classe \\\"Anomaly\\\" est',max(f1_1).round(3),\n 'et est atteint lorsque le seuil est au percentile',np.where(f1_1==max(f1_1))[0][0],\n '\\n\\nLe score F1 maximum de la classe \\\"Normal\\\" est',max(f1_0).round(3),\n 'et est atteint lorsque le seuil est au percentile',np.where(f1_0==max(f1_0))[0][0],\n '\\n\\nLa somme maximum des scores F1 est',max(somme).round(3),\n 'et est atteinte lorsque le seuil est au percentile',np.where(somme==max(somme))[0][0])\n\n\n\n########################\n# Matrice de confusion #\n########################\n\ndef matrice_confusion(y_true, y_pred):\n return pd.crosstab(y_true, y_pred, rownames=['Classe réelle'], colnames=['Classe prédite'])\n\n","sub_path":"Evaluations.py","file_name":"Evaluations.py","file_ext":"py","file_size_in_byte":4103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"630320793","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom socket import *\nimport threading\nimport time\n\nPORT = 17788\nDEST = ('<broadcast>', PORT)\n\n\ndef send_udp_data(udpSocket):\n send_data = \"hello world\"\n\n while True:\n udpSocket.sendto(send_data.encode(\"utf-8\"), DEST)\n time.sleep(1)\n print(\"send boradcast: hello world\")\n\ndef recv_udp_data(udpSocket):\n while True:\n recv_data, recv_addr = udpSocket.recvfrom(1024)\n print(\"\\ntime:\",time.asctime( time.localtime(time.time()) ))\n print(\"recv_data:\",recv_data.decode(\"utf-8\"))\n print(\"recv_addr:\", recv_addr)\n print(\"\")\n\ndef main():\n ''' this is test main '''\n udpSocket = socket(AF_INET,\tSOCK_DGRAM)\n #\t对这个需要发送⼴播数据的套接字进⾏修改设置,否则不能发送⼴播数据\n udpSocket.setsockopt(SOL_SOCKET, SO_BROADCAST,1)\n #\t以⼴播的形式发送数据到本⽹络的所有电脑中\n udpSocket.bind(('', PORT))\n\n thread_send = threading.Thread(target=send_udp_data, name=\"send_udp_data\", args=(udpSocket,))\n thread_recv = threading.Thread(target=recv_udp_data, name=\"recv_udp_data\", args=(udpSocket,))\n\n thread_send.start()\n thread_recv.start()\n\n # udpSocket.close()\n print(\"main exit reeturn 0\")\n\nif __name__ == \"__main__\":\n #print(\">>%s<<\" %(main.__doc__))\n main()\n","sub_path":"python/PythonStudy/MyPackage/py_28_broadcast.py","file_name":"py_28_broadcast.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"421634467","text":"# Converter tag terminal para um bloco. \n# [terminal ]\n# rogerio@chamonix:calculator-tutorial-2$ ./calculadora.exe \n# --(end of buffer or a NUL)\n# 1+2\n# --accepting rule at line 15 (\"1\")\n# --accepting rule at line 20 (\"+\")\n# --accepting rule at line 15 (\"2\")\n# --accepting rule at line 20 (\"\")\n# 3\n# rogerio@chamonix:calculator-tutorial-2$\n# [/terminal]\n####################\n# Latex que deve ser gerado:\n# \\setbeamercolor*{block title example}{fg=green!10,bg=gray!90}\n# \\setbeamercolor*{block body example}{fg=green, bg=black!80}\n# \\begin{exampleblock}{\\centering {Terminal}}\n# \\vspace{-0.3cm}\n# \\begin{lstlisting}[style=bash, frame=none, numbers=none, xleftmargin=0pt, framexleftmargin=0pt]\n# rogerio@chamonix:calculator-tutorial-2$ ./calculadora.exe \n# --(end of buffer or a NUL)\n# 1+2\n# --accepting rule at line 15 (\"1\")\n# --accepting rule at line 20 (\"+\")\n# --accepting rule at line 15 (\"2\")\n# --accepting rule at line 20 (\"\")\n# 3\n# rogerio@chamonix:calculator-tutorial-2$\n# \\end{lstlisting}\n# \\vspace{-0.3cm}\n# \\end{exampleblock}\n\nimport pandocfilters as pf\n\ndef latex(s):\n return pf.RawBlock('latex', s)\n\ndef mk_terminal(key, value, format, meta):\n if key == \"Para\":\n val = pf.stringify(value)\n if val.startswith('[') and val.endswith(']'):\n content = val[1:-1]\n if content == \"terminal\":\n if (format == \"beamer\"):\n return latex('\\setbeamercolor*{block title example}{fg=darkgray!95!white,bg=darkgray!50!white}' + '\\n' +\n '\\setbeamercolor*{block body example}{fg=green!75!black,bg=black!80}' + '\\n' + \n '\\\\begin{exampleblock}{\\centering {Terminal}}' + '\\n' +\n ' \\\\vspace{-0.3cm}' + '\\n' + \n ' \\\\begin{lstlisting}[style=bash, frame=none, numbers=none, xleftmargin=0pt, framexleftmargin=0pt]'\n )\n elif (format == \"latex\"):\n return latex('\\\\begin{terminalbox}{}{' + '\\n' +\n ' \\\\begin{lstlisting}[style=bash, frame=none, numbers=none, xleftmargin=0pt, framexleftmargin=0pt]' \n )\n elif content == \"/terminal\":\n if (format == \"beamer\"):\n return latex(' \\end{lstlisting}' + '\\n' + ' \\\\vspace{-0.3cm}' + '\\n' + '\\end{exampleblock}')\n elif (format == \"latex\"):\n return latex(' \\end{lstlisting}' + '\\n' + '}\\end{terminalbox}')\n\nif __name__ == \"__main__\":\n pf.toJSONFilter(mk_terminal)\n ","sub_path":"aulas/md/filters/terminal-filter-v1.py","file_name":"terminal-filter-v1.py","file_ext":"py","file_size_in_byte":2616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"38217616","text":"def total(student):\n if student is None:\n return 0\n elif len(student) < 4:\n return 0\n \n return student[1]+student[2]+student[3]\n\ndef ave(student):\n if student is None:\n return 0\n elif len(student) < 5:\n return 0\n \n return student[4]/3\n\ndef grade(student):\n if student is None:\n return ''\n elif len(student) < 6:\n return ''\n \n if student[5] >= 90:\n return 'A'\n elif student[5] >= 80:\n return 'B'\n elif student[5] >= 70:\n return 'C'\n elif student[5] >= 60:\n return 'D'\n else:\n return 'F'\n\ndef output(student):\n if student is not None:\n if len(student) >= 7:\n print('%s : 국어 :%d 영어:%d 수학:%d 총점:%d 평균:%.2f 학점:%s' %(student[0], student[1], student[2], student[3], student[4], student[5], student[6]))\n\ndef max_student(*student):\n max1 = -1\n maxStudent = []\n\n for i in range(0, len(student), 1):\n if student[i] is not None:\n if len(student[i]) >= 7:\n if max1 < student[i][4]:\n max1 = student[i][4]\n maxStudent = student[i]\n\n return maxStudent\n","sub_path":"score.py","file_name":"score.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"20410515","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/bee/Dev/piu/django/testSite/bee_django_referral/migrations/0012_auto_20190821_1315.py\n# Compiled at: 2019-08-21 01:15:54\nfrom __future__ import unicode_literals\nfrom django.db import migrations\n\nclass Migration(migrations.Migration):\n dependencies = [\n ('bee_django_referral', '0011_activity_link')]\n operations = [\n migrations.AlterModelOptions(name=b'activity', options={b'permissions': (('can_manage_referral', '可以进入转介活动管理页'), )})]","sub_path":"pycfiles/bee-django-referral-0.1.24.tar/0012_auto_20190821_1315.py","file_name":"0012_auto_20190821_1315.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"407606992","text":"from django.core.files import File\nimport os\n\nfrom django.core.management.base import BaseCommand\nfrom Statistics.models import *\n\nimport urllib\nfrom urllib import request\nfrom urllib.request import urlretrieve\nimport json\n\n\nclass Command(BaseCommand):\n\targs = 'not required'\n\thelp = 'populates or verifies/updates fixture data for all gameweek objects'\n\n\tdef populate_fixture_objects(self):\n\t\tapi_token = 'VLOpn8fyodXRigQlOuxzzgfI1D2IW6risWDraB3u4jYPCTUlwTH4EOcV8a6o'\n\t\tgameweeks = Gameweek.objects.all()\n\n\t\tfor g in gameweeks:\n\t\t\turl = 'https://soccer.sportmonks.com/api/v2.0/rounds/'+str(g.gw_id)+'?api_token='+api_token+'&include=fixtures'\n\t\t\td = json.load(urllib.request.urlopen(url))\n\t\t\ta = d['data']\n\t\t\tb = a['fixtures']\n\t\t\tc = b['data']\n\t\t\ty = len(c)\n\t\t\tfor i in range(0,y):\n\t\t\t\tx = c[i]\n\t\t\t\tn = x['id']\n\t\t\t\tif Fixture.objects.filter(fixture_id = n).exists():\n\t\t\t\t\tf = Fixture.objects.get(fixture_id = n)\n\t\t\t\t\tf.fixture_id= x['id']\n\t\t\t\t\tfixture_gameweek = g\n\t\t\t\t\tv = x['venue_id']\n\t\t\t\t\tf.fixture_venue = Venue.objects.get(venue_id = v)\n\t\t\t\t\tt = x['time']\n\t\t\t\t\tt_s = t['starting_at']\n\t\t\t\t\tf.fixture_start = t_s['date_time']\n\t\t\t\t\tth = x['localteam_id'] \n\t\t\t\t\tf.fixture_team_home = Team.objects.get(team_id = th)\n\t\t\t\t\tta = x['visitorteam_id']\n\t\t\t\t\tf.fixture_team_away = Team.objects.get(team_id = ta)\n\t\t\t\t\txs = x['scores']\n\t\t\t\t\tf.fixture_ht_score = xs['ht_score']\n\t\t\t\t\tf.fixture_ft_score = xs['ft_score']\n\t\t\t\t\tf.save()\n\t\t\t\telse:\n\t\t\t\t\tv = x['venue_id']\n\t\t\t\t\tif Venue.objects.filter(venue_id = v).exists():\n\t\t\t\t\t\tv_obj = Venue.objects.get(venue_id = v)\n\t\t\t\t\telse:\n\t\t\t\t\t\turl_two = 'https://soccer.sportmonks.com/api/v2.0/venues/'+str(x['venue_id'])+'?api_token='+api_token\n\t\t\t\t\t\td_two = json.load(urllib.request.urlopen(url_two))\n\t\t\t\t\t\ty = d_two['data']\n\t\t\t\t\t\tv = Venue(venue_id = y['id'], venue_name = y['name'], venue_city = y['city'], venue_capacity = y['capacity'])\n\t\t\t\t\t\tv.save()\n\t\t\t\t\t\tv_obj = Venue.objects.get(venue_id = v)\n\n\t\t\t\t\tth = x['localteam_id'] \n\t\t\t\t\tth_obj = Team.objects.get(team_id = th)\n\t\t\t\t\tta = x['visitorteam_id'] \n\t\t\t\t\tta_obj = Team.objects.get(team_id = ta)\n\t\t\t\t\txs = x['scores']\n\t\t\t\t\tt = x['time']\n\t\t\t\t\tt_s = t['starting_at']\n\t\t\t\t\tf_s = t_s['date_time']\n\t\t\t\t\tf = Fixture(fixture_id = x['id'], fixture_gameweek = g, fixture_venue = v_obj, fixture_start = f_s, fixture_team_home = th_obj, fixture_team_away = ta_obj, fixture_ht_score = xs['ht_score'], fixture_ft_score = xs['ft_score'])\n\t\t\t\t\tf.save()\n\n\t\tprint('Data Collection Done')\n\n\tdef handle(self, *args, **options):\n\t\tself.populate_fixture_objects()\t\t","sub_path":"Statistics/management/commands/fixture_data.py","file_name":"fixture_data.py","file_ext":"py","file_size_in_byte":2532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"496982691","text":"\"\"\"\nInitialize the application and api blueprints\n\"\"\"\nfrom flask import Flask\nfrom config import config\n\n\ndef create_app(config_name='default', **config_overrides):\n app = Flask(__name__)\n\n # Load configuration\n app.config.from_object(config[config_name])\n # Override configurations with **kwargs\n app.config.update(config_overrides)\n config[config_name].init_app(app)\n\n # Register blueprints\n from .api import api as api_blueprint\n app.register_blueprint(api_blueprint, url_prefix='/api')\n\n return app","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"426049014","text":"import random\n\nfrom custom.dtlz_problems import DTLZ1P\nfrom custom.instance import DTLZInstance\nfrom custom.utils import DIRECTORY_RESULTS, print_solutions_to_file\nfrom jmetal.algorithm.multiobjective.nsgaiii import NSGAIII, UniformReferenceDirectionFactory\nfrom jmetal.lab.visualization import Plot\nfrom jmetal.operator import SBXCrossover, PolynomialMutation\nfrom jmetal.problem import DTLZ1\nfrom jmetal.problem.multiobjective.dtlz import DTLZ7\nfrom jmetal.util.observer import ProgressBarObserver\nfrom jmetal.util.ranking import FastNonDominatedRanking\nfrom jmetal.util.solution import read_solutions\nfrom jmetal.util.termination_criterion import StoppingByEvaluations\n\nif __name__ == '__main__':\n random.seed(8435)\n random.seed(1)\n\n instance = DTLZInstance()\n path = '/home/thinkpad/PycharmProjects/jMetalPy/resources/DTLZ_INSTANCES/DTLZ1_Instance.txt'\n # path = '/home/thinkpad/PycharmProjects/jMetalPy/resources/DTLZ_INSTANCES/DTLZ1P_10.txt'\n instance.read_(path)\n\n problem = DTLZ1P(instance)\n problem.reference_front = read_solutions(filename='resources/reference_front/DTLZ1.3D.pf')\n\n max_evaluations = 25000\n experiment = 50\n bag = []\n algorithm = NSGAIII(\n problem=problem,\n population_size=92,\n reference_directions=UniformReferenceDirectionFactory(3, n_points=91),\n mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20),\n crossover=SBXCrossover(probability=1.0, distribution_index=30),\n termination_criterion=StoppingByEvaluations(max_evaluations=max_evaluations)\n )\n for i in range(experiment):\n algorithm = NSGAIII(\n problem=problem,\n population_size=92,\n reference_directions=UniformReferenceDirectionFactory(3, n_points=91),\n mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20),\n crossover=SBXCrossover(probability=1.0, distribution_index=30),\n termination_criterion=StoppingByEvaluations(max_evaluations=max_evaluations)\n )\n progress_bar = ProgressBarObserver(max=max_evaluations)\n algorithm.observable.register(progress_bar)\n\n algorithm.run()\n bag += algorithm.get_result()\n print(len(bag))\n print_solutions_to_file(bag, DIRECTORY_RESULTS + 'Solutions.bag.' + algorithm.label)\n ranking = FastNonDominatedRanking()\n\n ranking.compute_ranking(bag)\n front = ranking.get_subfront(0)\n print(len(front))\n # Save results to file\n print_solutions_to_file(front, DIRECTORY_RESULTS + 'front0.' + algorithm.label)\n plot_front = Plot(title='Pareto front approximation', axis_labels=['x', 'y', 'z'])\n plot_front.plot(front, label='NSGAII-ZDT7', filename=DIRECTORY_RESULTS + 'NSGAII-ZDT1P', format='png')\n print(f'Algorithm: ${algorithm.get_name()}')\n print(f'Problem: ${problem.get_name()}')\n print(f'Computing time: ${algorithm.total_computing_time}')\n","sub_path":"examples/multiobjective/nsgaiii/nsgaiii_dtlz2.py","file_name":"nsgaiii_dtlz2.py","file_ext":"py","file_size_in_byte":2978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"496834942","text":"import pandas as pd\r\nimport numpy as np\r\nimport csv\r\nimport platform\r\n\"\"\"Embeddings reader and manager class\r\n Programmed by Jonathan Quijas\r\n Last modified 9/21/2016\r\n\"\"\"\r\n\r\nclass EmbeddingsReader(object):\r\n def __init__(self, embedding_size = 50):\r\n self.embedding_size = embedding_size\r\n if(platform.system() == 'Windows'):\r\n self.embeddings_path = 'C:\\\\Users\\\\Jona Q\\\\Documents\\\\Embeddings\\\\glove.6B.'+str(embedding_size)+'d.txt'\r\n else:\r\n self.embeddings_path = '/home/jonathan/Documents/WordEmbedding/glove.6B.'+str(embedding_size)+'d.txt'\r\n\r\n #Safeguard vector for out of vocabulary words\r\n self.zero_vec = np.zeros(embedding_size)\r\n self.read_embs = False\r\n\r\n #Read embeddings file and store embeddings in object\r\n #Returns embeddings dictionary <key, value>\r\n def readEmbeddings(self, normalize=True):\r\n #embeddings_path = '/home/jonathan/Documents/WordEmbedding/glove.6B.'+str(self.embedding_size)+'d.txt'\r\n data = pd.read_csv(self.embeddings_path, header=None, delimiter=' ', quoting=csv.QUOTE_NONE).as_matrix()\r\n [n, p] = data.shape\r\n if normalize:\r\n norms = np.linalg.norm(np.float64(data[:, 1:p]), axis = 1)\r\n self.data = dict(zip(data[:,0], data[:,1:p]/ norms[:,np.newaxis]))\r\n self.read_embs = True\r\n return self.data\r\n else:\r\n self.data = dict(zip(data[:,0], data[:,1:p]))\r\n self.read_embs = True\r\n return self.data\r\n\r\n def embeddingSize(self):\r\n return self.embedding_size\r\n\r\n #Return array with embedding vectors\r\n def valuesArray(self):\r\n if self.read_embs:\r\n #return list(self.data.values())\r\n return np.array(list(self.data.values()))\r\n else:\r\n raise RuntimeError('Embeddings must be read first!')\r\n\r\n #Return array with embedding keys\r\n def keysArray(self):\r\n if self.read_embs:\r\n return np.array(list(self.data.keys()))\r\n else:\r\n raise RuntimeError('Embeddings must be read first!')\r\n\r\n def mapWords(self, message):\r\n return [[self.data.get(word, self.zero_vec) for word in sentence]for sentence in message]\r\n","sub_path":"TopicExtraction/EmbeddingModule.py","file_name":"EmbeddingModule.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"646235444","text":"# Copyright 2021 Nokia\n# Licensed under the BSD 3-Clause License.\n# SPDX-License-Identifier: BSD-3-Clause\n\nfrom flask import Blueprint, request, jsonify\nimport json\nimport datetime\nfrom claims import claimstructure\n\ntpm2_endpoint = Blueprint('tpm2_endpoint', __name__)\n\n\n@tpm2_endpoint.route('/pcrs', methods=['GET','POST'])\ndef returnPCRREAD():\n c = claimstructure.Claim()\n c.addHeaderItem(\"ta_received\",str(datetime.datetime.now(datetime.timezone.utc)))\n q = tpmdevice.readPCRs()\n c.addPayloadItem(\"pcrs\",q)\n c.addHeaderItem(\"ta_complete\",str(datetime.datetime.now(datetime.timezone.utc)))\n c.addHeaderItem(\"ak_name\",\"whatever the AK name is here\") \n c.sign()\n rc = c.getClaim()\n\n return jsonify(rc), 200\n\n\n# @tpm2_endpoint.route('/quote', methods=['POST'])\n# def returnTPMSATTEST():\n# tpmdevice = tpm.TPM()\n\n# # This is how it works\n\n# # 1. take the policy and extract the PCRs\n# #print(\"Now in TA\")\n# #print(request.json)\n# body = json.loads(request.json)\n# print(\"\\n*********************\\nReceived body is\",body) \n\n# # 2. deal with any additional information, eg: nonce etc from the additional parameters\n\n# pcrselection = body['policyparameters']['pcrselection']\n# hashalg = body['policyparameters']['hashalg']\n# callparameters = body['callparameters']\n\n# #print(\"Policy & Parameters\",pcrselection,\"\\n\",hashalg,\"\\n\",parameters,\"\\n\")\n\n# # 3. call tpm2_quote accordingly\n \n# # 3.1 decided which AK to use locally, or if supplied in the parameters\n\n# #We need to wrap this into an exception because the parameters[\"ak\"] might not exist.\n# #In which case we need to let the TA decided ... or use a default of 0x810100aa\n# ak_to_use=\"0x810100aa\" \n# try:\n# ak_to_use=callparameters[\"ak\"]\n# except KeyError:\n# \tprint(\"AK Missing , using default of 0x810100aa\")\n\n\n# # 3.1.1 build the initial claim structure\n \n# c = claimstructure.Claim()\n# c.addHeaderItem(\"ta_received\",str(datetime.datetime.now(datetime.timezone.utc)))\n\n# # 3.2 call quote \n# q = tpmdevice.quote(ownak=ak_to_use,pcrs=pcrselection)\n \n\n# #j = tpmdevice.tpms_attest_as_yaml(q[0])\n# #print(\"AS YAML=\",j)\n \n# # 4. populate the claim with the quote and other header items\n\n# c.addPayloadItem(\"quote\",q)\n# c.addHeaderItem(\"ta_complete\",str(datetime.datetime.now(datetime.timezone.utc)))\n \n# # 5. Signing ... this should be done by the TPM and use the same key (AK) as the quote\n# # also include the ak.name in the header for completeness\n \n# c.addHeaderItem(\"ak_name\",\"whatever the AK name is here\") \n# c.sign()\n\n# rc = c.getClaim()\n \n# #print(\"Returned claim is \",rc)\n\n# # 6. return the claim\n\n# # In the case of success we return a claim and HTTP 200\n# # In the case of failure we return a message and something that isn't HTTP\n# # 20x\n\n# return jsonify(rc), 200\n\n","sub_path":"t10/A10httprest/endpoints/tpm2/tpm2_endpoint.py","file_name":"tpm2_endpoint.py","file_ext":"py","file_size_in_byte":2963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"12071197","text":"# -*- coding: utf-8 -*-\n\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\ntest_compute\n----------------------------------\n\nFunctional tests for `shade` compute methods.\n\"\"\"\n\nfrom shade import openstack_cloud\nfrom shade.tests import base\nfrom shade.tests.functional.util import pick_flavor, pick_image\n\n\nclass TestCompute(base.TestCase):\n def setUp(self):\n super(TestCompute, self).setUp()\n self.cloud = openstack_cloud(cloud='devstack')\n self.nova = self.cloud.nova_client\n self.flavor = pick_flavor(self.nova.flavors.list())\n if self.flavor is None:\n self.assertFalse('no sensible flavor available')\n self.image = pick_image(self.nova.images.list())\n if self.image is None:\n self.assertFalse('no sensible image available')\n\n def _cleanup_servers(self):\n for i in self.nova.servers.list():\n if i.name.startswith('test_create'):\n self.nova.servers.delete(i)\n\n def test_create_server(self):\n self.addCleanup(self._cleanup_servers)\n server = self.cloud.create_server(name='test_create_server',\n image=self.image, flavor=self.flavor)\n self.assertEquals(server['name'], 'test_create_server')\n self.assertEquals(server['image']['id'], self.image.id)\n self.assertEquals(server['flavor']['id'], self.flavor.id)\n\n def test_delete_server(self):\n self.cloud.create_server(name='test_delete_server',\n image=self.image, flavor=self.flavor)\n server_deleted = self.cloud.delete_server('test_delete_server',\n wait=True)\n self.assertIsNone(server_deleted)\n\n def test_get_image_id(self):\n self.assertEqual(\n self.image.id, self.cloud.get_image_id(self.image.id))\n self.assertEqual(\n self.image.id, self.cloud.get_image_id(self.image.name))\n\n def test_get_image_name(self):\n self.assertEqual(\n self.image.name, self.cloud.get_image_name(self.image.id))\n self.assertEqual(\n self.image.name, self.cloud.get_image_name(self.image.name))\n","sub_path":"shade/tests/functional/test_compute.py","file_name":"test_compute.py","file_ext":"py","file_size_in_byte":2688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"157641175","text":"from django.conf import settings\nfrom django.template import loader\nfrom . import models\n\nadmin_email = 'david.fishman@dfo-mpo.gc.ca'\napp_name = settings.WEB_APP_NAME # should be a single word with one space\nfrom_email='DoNotReply@{}.com'.format(app_name)\n\nclass NewBugNotificationEmail:\n\n def __init__(self, object, application):\n self.subject = '{}: A new bug has been logged'.format(app_name)\n self.message = self.load_html_template(object,application)\n self.from_email = from_email\n self.to_list = [admin_email,]\n\n def load_html_template(self,object, application):\n t = loader.get_template('bugs/email_new_bug_notification.html')\n context = {\n 'object': object,\n 'app_name': models.Bug.APP_DICT[application]\n }\n rendered = t.render(context)\n return rendered\n","sub_path":"bugs/emails.py","file_name":"emails.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"530007791","text":"class Solution:\r\n\tdef solveSudokuInt(self, board: [[int]]) -> None:\r\n\t\t\"\"\"\r\n\t\tDo not return anything, modify board in-place instead.\r\n\t\t\"\"\"\r\n\t\tself.original = set()\r\n\t\tfor i in range(9):\r\n\t\t\tself.original.add(i+1)\r\n\r\n\t\tpossibles = self.constructPossibilities(board)\r\n\t\trowPossible = possibles[0]\r\n\t\tcolumnPossible = possibles[1]\r\n\t\tsectorPossible = possibles[2]\r\n\r\n\t\tfor y in range(9):\r\n\t\t\tfor x in range(9):\r\n\t\t\t\tif board[y][x] == 0:\r\n\t\t\t\t\tallowed = rowPossible[y]&columnPossible[x]§orPossible[int(y/3)][int(x/3)]\r\n\t\t\t\t\tif len(allowed) == 1:\r\n\t\t\t\t\t\tnum = list(allowed)[0]\r\n\t\t\t\t\t\tboard[y][x] = list(allowed)[0]\r\n\t\t\t\t\t\trowPossible[y].remove(num)\r\n\t\t\t\t\t\tcolumnPossible[x].remove(num)\r\n\t\t\t\t\t\tsectorPossible[int(y/3)][int(x/3)].remove(num)\r\n\t\tself.solve(board, rowPossible, columnPossible, sectorPossible)\r\n\r\n\tdef getCoordinate(self, board: [[int]]) -> (int, int):\r\n\t\tfor y in range(9):\r\n\t\t\tfor x in range(9):\r\n\t\t\t\tif board[y][x] == 0:\r\n\t\t\t\t\treturn x, y\r\n\t\treturn -1, -1\r\n\r\n\tdef solve(self, board: [[int]], rowPossible, columnPossible, sectorPossible) -> bool:\r\n\t\tx, y = self.getCoordinate(board)\r\n\r\n\t\tif x == -1:\r\n\t\t\treturn True\r\n\r\n\t\tallowed = rowPossible[y]&columnPossible[x]§orPossible[int(y/3)][int(x/3)]\r\n\r\n\t\tif not len(allowed):\r\n\t\t\treturn False\r\n\r\n\t\tfor num in list(allowed):\r\n\t\t\tboard[y][x] = num\r\n\t\t\trowPossible[y].remove(num)\r\n\t\t\tcolumnPossible[x].remove(num)\r\n\t\t\tsectorPossible[int(y/3)][int(x/3)].remove(num)\r\n\t\t\ttryThis = self.solve(board, rowPossible, columnPossible, sectorPossible)\r\n\t\t\tif not tryThis:\r\n\t\t\t\tboard[y][x] = 0\r\n\t\t\t\trowPossible[y].add(num)\r\n\t\t\t\tcolumnPossible[x].add(num)\r\n\t\t\t\tsectorPossible[int(y/3)][int(x/3)].add(num)\r\n\t\t\telse:\r\n\t\t\t\treturn True\r\n\r\n\t\treturn False\r\n\r\n\tdef constructPossibilities(self, board) -> []:\r\n\t\toriginal = self.original\r\n\r\n\t\txPossible = []\r\n\t\tyPossible = []\r\n\t\tsectorPossible = []\r\n\r\n\t\tfor y in range(9):\r\n\t\t\trow = self.original.copy()\r\n\t\t\tcolumn = self.original.copy()\r\n\t\t\tfor x in range(9):\r\n\t\t\t\tif board[y][x] in row:\r\n\t\t\t\t\trow.remove(board[y][x])\r\n\t\t\t\tif board[x][y] in column:\r\n\t\t\t\t\tcolumn.remove(board[x][y])\r\n\t\t\txPossible.append(row)\r\n\t\t\tyPossible.append(column)\r\n\r\n\t\tfor i in range(3):\r\n\t\t\trow = []\r\n\t\t\tfor j in range(3):\r\n\t\t\t\tstartingY = i*3\r\n\t\t\t\tstartingX = j*3\r\n\t\t\t\tsector = self.original.copy()\r\n\t\t\t\tfor y in range(3):\r\n\t\t\t\t\tfor x in range(3):\r\n\t\t\t\t\t\tif board[startingY+y][startingX+x] in sector:\r\n\t\t\t\t\t\t\tsector.remove(board[startingY+y][startingX+x])\r\n\t\t\t\trow.append(sector)\r\n\t\t\tsectorPossible.append(row)\r\n\t\treturn [xPossible, yPossible, sectorPossible]\r\n\t\t","sub_path":"Python/files/solveSudokuInt.py","file_name":"solveSudokuInt.py","file_ext":"py","file_size_in_byte":2528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"113484917","text":"import pygame\nfrom threading import Thread\nimport time\nclass rangedAttack:\n def __init__(self,world,target,x,y):\n self.x=x\n self.y=y\n self.world=world\n self.target=target\n self.running=True\n def start(self):\n Thread(target=self.update,args=()).start()\n return self\n def update(self):\n start_time=time.time()\n if self.target==None:\n self.stop()\n else:\n xvel=((self.target.x+self.target.w/2)-self.x)/45\n yvel=((self.target.y+self.target.h/2)-self.y)/45\n \n while self.running:\n if self.target==None:\n self.stop()\n break\n else:\n self.x+=xvel\n self.y+=yvel\n if time.time()-start_time>45/self.world.FPS:\n self.stop()\n\n time.sleep(1.0/self.world.FPS - ((time.time() - start_time) % (1.0/self.world.FPS)))\n def draw(self):\n xx=self.world.viewport[0]\n yy=self.world.viewport[1]\n pygame.draw.circle(self.world.screen, (0,255,255), (int(self.x+xx),int(self.y+yy)), 5)\n \n def stop(self):\n self.running=False\n if self in self.world.attacks:\n self.world.attacks.remove(self)","sub_path":"client/rangedattacks.py","file_name":"rangedattacks.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"283375558","text":"##########################################\n#\n# Input:\n# AtomArray: 4x1 array of the 4 atom indexes involved in the dihedral angle\n# position: Nx3 array of atomic coordinates\n#\n# New approach is from https://stackoverflow.com/questions/20305272/dihedral-torsion-angle-from-four-points-in-cartesian-coordinates-in-python\n##########################################\n\ndef calcDihedral(AtomArray, position):\n import numpy as np\n\n # sub_ij = position[AtomArray[0], :] - position[AtomArray[1], :]\n # sub_jk = position[AtomArray[1], :] - position[AtomArray[2], :]\n # sub_kl = position[AtomArray[2], :] - position[AtomArray[3], :]\n\n # cross_ijk = np.cross(sub_ij, sub_jk)\n # cross_jkl = np.cross(sub_jk, sub_kl)\n\n # ijk_jkl = sum(cross_ijk * cross_jkl)\n\n # cijk_mag2 = np.sum(np.square(cross_ijk))\n # cjkl_mag2 = np.sum(np.square(cross_jkl))\n\n # kj_mag = np.sqrt(np.sum(np.square(sub_jk)))\n\n # cijk_cjlk = np.cross(cross_ijk, cross_jkl)\n # cosphi = ijk_jkl / np.sqrt(cijk_mag2 * cjkl_mag2)\n # sinphi = np.sum(cijk_cjlk * sub_jk) / np.sqrt(cijk_mag2 * cjkl_mag2) / kj_mag\n # #print('sin', sinphi, 'cos', cosphi)\n # if (sinphi < 0):\n # phi = np.arccos(cosphi)\n # else:\n # phi = -np.arccos(cosphi)\n # DA = phi / np.pi * 180.0\n # print(DA)\n # #return DA\n\n \"\"\"Praxeolitic formula\n 1 sqrt, 1 cross product\"\"\"\n p0 = position[AtomArray[0], :]\n p1 = position[AtomArray[1], :]\n p2 = position[AtomArray[2], :]\n p3 = position[AtomArray[3], :]\n\n b0 = -1.0 * (p1 - p0)\n b1 = p2 - p1\n b2 = p3 - p2\n\n # normalize b1 so that it does not influence magnitude of vector\n # rejections that come next\n b1 /= np.linalg.norm(b1)\n\n # vector rejections\n # v = projection of b0 onto plane perpendicular to b1\n # = b0 minus component that aligns with b1\n # w = projection of b2 onto plane perpendicular to b1\n # = b2 minus component that aligns with b1\n v = b0 - np.dot(b0, b1) * b1\n w = b2 - np.dot(b2, b1) * b1\n\n # angle between v and w in a plane is the torsion angle\n # v and w may not be normalized but that's fine since tan is y/x\n x = np.dot(v, w)\n y = np.dot(np.cross(b1, v), w)\n #print(DA, np.degrees(np.arctan2(y, x)) )\n return np.degrees(np.arctan2(y, x))","sub_path":"calcDihedral.py","file_name":"calcDihedral.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"461704598","text":"from argparse import ArgumentParser\nimport chart_studio.plotly as py\nimport plotly.graph_objects as go\nimport plotly.io as pio\nimport json\nimport csv\n\ndef parse_data(ping_loc, test_num):\n\t\n\tdata = {}\n\t# Replace 58 with the actual number of hops to remote data center\n\thops = [2, 4, 6, 9, 9]\n\t\n\tcount = 0\n\tdata[\"initial_ping\"] = []\n\tdata[\"steady_ping\"] = []\n\tping = open(ping_loc, \"r\")\n\tfor line in ping.readlines():\n\t\tfields = line.split(\" \")\n\t\tif len(fields) == 0:\n\t\t\tcontinue\n\t\tif fields[0] == \"rtt\":\n\t\t\tstats = fields[3].split(\"/\")\n\t\t\tentry = {\"test_id\": test_num, \"min\": float(stats[0]), \"avg\": float(stats[1]),\n\t\t\t\t\t\t\"max\": float(stats[2]), \"dev\": float(stats[3])}\n\t\t\tif count/2 < len(hops):\n\t\t\t\tentry[\"hops\"] = hops[count/2]\n\t\t\telse:\n\t\t\t\tentry[\"hops\"] = hops[len(hops)]\n\t\t\tif count % 2 == 0:\n\t\t\t\tdata[\"initial_ping\"].append(entry)\n\t\t\telse:\n\t\t\t\tdata[\"steady_ping\"].append(entry)\n\t\t\tcount += 1\n\t\telif len(fields) > 1 and fields[1] == \"error\":\n\t\t\tcount += 1\n\t\t\tprint(\"Error encountered in file \" + ping_loc)\n\tping.close()\n\treturn data\n\nparser = ArgumentParser(\"Parse data from ping output files\")\nparser.add_argument(\"file1\")\nparser.add_argument(\"file2\")\n\nargs = parser.parse_args()\nloc = args.file1\ndata = []\nfor i in range(1, 21):\n\tdata.append(parse_data(loc + \"/run\" + str(i) + \"/ping_test.out\", i))\nplots = []\nxinit = []\nyinit = []\nfor result in data:\n\tfor point in result[\"initial_ping\"]:\n\t\txinit.append(point[\"hops\"])\n\t\tyinit.append(point[\"max\"])\nplots.append(go.Scatter(x=xinit, y=yinit, mode = \"markers\", name = \"DCnet Initial Ping\"))\n\nloc = args.file2\ndata = []\nfor i in range(1, 21):\n\tdata.append(parse_data(loc + \"/run\" + str(i) + \"/ping_test.out\", i))\nxinit = []\nyinit = []\nfor result in data:\n\tfor point in result[\"initial_ping\"]:\n\t\txinit.append(point[\"hops\"])\n\t\tyinit.append(point[\"max\"])\nplots.append(go.Scatter(x=xinit, y=yinit, mode = \"markers\", name = \"Reactive Initial Ping\"))\n\nlayout = go.Layout(title = \"Ping Delay vs. Number of Hops\",\n\t\t\t\t\txaxis = {\"title\" : \"Number of Hops\", \"ticklen\" : 1},\n\t\t\t\t\tyaxis = {\"title\" : \"Delay in Milliseconds\", \"ticklen\" : 0.1})\n\npio.write_html(go.Figure(data = plots, layout = layout),\n\t\t\t\tfile = loc + \"../plots/ping_comparison_init.html\", auto_open=True)\n","sub_path":"python/src/plot_init_ping_comp.py","file_name":"plot_init_ping_comp.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"18537412","text":"import re\n\npath_spec = \"C:\\py\\spec_list.txt\"\npath_support = \"C:\\py\\support_list.txt\"\n\n\ndef txt_read(file_path):\n fo = open(file_path, \"r\")\n cont = fo.readlines()\n fo.close()\n return cont\n\n\ncontent_support = txt_read(path_support)\ncontent_spec = txt_read(path_spec)\n\n# print(content_spec)\n# print(content_support)\n\ndef intersection_kai(list_a, list_b):\n same = []\n for str_a in list_a:\n for str_b in list_b:\n if match_kai(str_a, str_b):\n same.append(str_a + \"-\" + str_b)\n return same\n\n\ndef match_kai(str_a, str_b):\n return re.match(str_a, str_b)\n\n# print(intersection_kai(txt_read(path_support), txt_read(path_spec)))\n\n# if match_kai(\"社会医療法人愛仁会\", \"社会医療法人愛仁会_0945000\"):\n# print(\"match\")\n\ndef char_rmv(lst):\n lst_mod = []\n for str in lst:\n lst_mod.append(re.sub(r\"(_[0-9])+\", \"\", str))\n return lst_mod\n\nlist_a = [\"アース製薬株式会社_1274000\\n\", \"アイ・ティー・エックス株式会社_1044000\\n\", \"あいおいニッセイ同和損害保険株式会社_1204000\\n\"]\n\nprint(char_rmv(content_spec))\nprint(char_rmv(list_a))\n\n\n\n","sub_path":"my_tools/bkup.py","file_name":"bkup.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"425678734","text":"import torch\nimport torch.nn as nn\nfrom src.models.modules.StackedDilation import StackedDilation\nfrom warnings import filterwarnings\n\nfilterwarnings(\"ignore\", category=UserWarning)\n\n\nclass RDCBlock(nn.Module):\n def __init__(self, in_channels: int) -> None:\n super(RDCBlock, self).__init__()\n\n self.conv1x1 = nn.Conv3d(in_channels * 2, in_channels, kernel_size=1)\n self.grouped_conv = StackedDilation(in_channels, in_channels, kernel=5)\n self.activation = nn.ReLU()\n\n self.batch_norm_conv = nn.BatchNorm3d(in_channels)\n self.batch_norm_group = nn.BatchNorm3d(in_channels)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n\n x = self.activation(self.batch_norm_conv(self.conv1x1(x)))\n x = self.activation(self.batch_norm_group(self.grouped_conv(x)))\n\n return x\n","sub_path":"src/models/modules/RDCblock.py","file_name":"RDCblock.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"457015603","text":"import math\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.utils import shuffle\nfrom random import randint\n\nimport ball_3d_coordinates.util.util as util\n\nclass ConvPreprocessor(object):\n\tdef __init__(self, max_x, max_y, max_z, input_trace):\n\t\tsuper(ConvPreprocessor, self).__init__()\n\t\tself.max_x = max_x\n\t\tself.max_y = max_y\n\t\tself.max_z = max_z\n\t\tself.input_trace = input_trace\n\n\tdef fit_transform(self, X, y):\n\n\t\t# Rescale labels /IMG_DIM and transform it into a numpy array\n\t\ty = self.rescale_labels(y)\n\n\t\t# Generate the Data\n\t\tX, y = self.generate_data(X, y)\n\n\t\t# Reshaping the Label \n\t\ty = np.squeeze(y)\n\t\t\n\t\t# Train, test, validation split\n\t\tX_train, X_test, X_val, y_train, y_test, y_val = self.train_test_validation_split(X, y)\n\n\t\treturn X_train, y_train, X_test, y_test, X_val, y_val\n\n\tdef preprocess_images(self, X):\n\t\t# Rescale the images /255\n\t\t# X = self.rescale_features(X)\n\t\tX = self.normalize_features(X)\n\t\treturn X\n\n\tdef transform(self, X):\n\t\t# Rescale the features for the prediction\n\t\tX = self.rescale_features(X)\n\t\treturn X\n\n\tdef rescale_labels(self, labels):\n\t\t# labels[\"x\"] = labels[\"x\"].apply(lambda x: x / self.max_x)\n\t\t# labels[\"y\"] = labels[\"y\"].apply(lambda x: x / self.max_y)\n\t\t# labels[\"z\"] = labels[\"z\"].apply(lambda x: x / self.max_z)\n\t\treturn labels.values\n\n\tdef rescale_features(self, features):\n\t\tfeatures = features.astype('float32')\n\t\tfeatures /= 255.0\n\t\treturn features\n\t\n\tdef normalize_features(self, features):\n\t\tfeatures = features.astype('float32')\n\t\tfeatures -= features.mean(axis=0)\n\t\tfeatures /= features.std(axis=0)\n\t\treturn features\n\n\tdef train_test_validation_split(self, features, labels, val_samples=25, test_samples=50):\n\n\t\tX_test = features[0:test_samples]\n\t\ty_test = labels[0:test_samples]\n\n\t\tX_val = features[test_samples:test_samples + val_samples]\n\t\ty_val = labels[test_samples:test_samples + val_samples]\n\n\t\tX_train = features[test_samples + val_samples:]\n\t\ty_train = labels[test_samples + val_samples:]\n\t\t\n\t\treturn X_train, X_test, X_val, y_train, y_test, y_val\n\n\tdef generate_data(self, features, labels):\n\t\tdata_x = []\n\t\tdata_y = []\n\t\tfor i in range(0, len(features)-self.input_trace):\n\t\t\tinitial_idx = randint(0, len(features)-self.input_trace-1)\n\t\t\tx = features[initial_idx:initial_idx+self.input_trace]\n\t\t\ty = labels[initial_idx+int(self.input_trace/2):initial_idx+int(self.input_trace/2)+1,:]\n\t\t\tdata_x.append(x)\n\t\t\tdata_y.append(y)\n\t\tdata_x = np.asarray(data_x)\n\t\tdata_y = np.asarray(data_y)\n\t\t\n\t\treturn data_x, data_y\n","sub_path":"ball_3d_coordinates/end_to_end/preprocessing/data_preprocessing.py","file_name":"data_preprocessing.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"440381566","text":"import gym\r\nimport numpy as np\r\nimport random\r\nfrom collections import deque\r\nfrom keras.layers import Dense, Input, Lambda, convolutional, core\r\nfrom keras.models import Model\r\nfrom keras.optimizers import Adam\r\nimport matplotlib.pyplot as plt\r\nfrom keras.losses import logcosh\r\n#from ReinforcementLearning.DQN import dqn_v1_brain\r\n\r\n# https://becominghuman.ai/lets-build-an-atari-ai-part-1-dqn-df57e8ff3b26\r\n# Mnih et al., Human-level control through deep reinforcement learning. Nature, 2015.\r\n# https://github.com/fg91/Deep-Q-Learning/blob/master/DQN.ipynb\r\n# CartPole-v1, MountainCar-v0, MountainCarContinuous-v0, NChain-v0, BreakoutDeterministic-v4\r\n\r\n'''Version 2\r\nAIMS \r\n1) Model to use CNN instead of FC for pixel based play -> DONE\r\n2) continuous state space & continuous action\r\n3) clip results to [-1,1]\r\n4) use Huber/Logcosh loss --> y_pred = prediction, y_true = target (prediction + updated reward)\r\n5) skip 4 frames to process instead of single frames\r\n- determine environment state space by agent \r\n- CNN model implementation & follows DM parameters from paper \r\n- preprocess pixel input to grayscale & downsample\r\n- save state information in memory in uint8 to save space'''\r\n\r\n\r\ndef preprocess(state):\r\n process_state = np.mean(state, axis=2).astype(np.uint8) # compress 3 channels into 1: RGB --> grayscale\r\n process_state = process_state[::2, ::2] # downsample pixels by half or crop by tf bounding box\r\n process_state_size = list(process_state.shape)\r\n process_state_size.append(1) # reshape state size into [batch_size=1, state_size] for model\r\n process_state = np.reshape(process_state, process_state_size)\r\n return process_state\r\n\r\n\r\nclass DQNAgent:\r\n def __init__(self, env, cnn):\r\n self.env = env\r\n self.action_size = env.action_space.n\r\n self.state_size = self.select_state_size()\r\n\r\n self.memory = deque(maxlen=10000) # specify memory size\r\n self.gamma = 0.99\r\n self.eps = 1.0\r\n self.eps_min = 0.01\r\n self.decay = 0.95\r\n self.lr = 0.00025\r\n\r\n self.tau = 0.125 # special since 2 models to be trained\r\n\r\n if cnn:\r\n self.model = self.create_cnnmodel() # do actual predictions on what action to take given states\r\n self.target_model = self.create_cnnmodel() # Have a slow changing goal that changes less rapidly as model\r\n\r\n else:\r\n self.model = self.create_fcmodel() # do actual predictions on what action to take given states\r\n self.target_model = self.create_fcmodel() # Have a slow changing goal that changes less rapidly as model\r\n\r\n def select_state_size(self):\r\n if self.env.observation_space.shape == ():\r\n state_size = self.env.observation_space.n # discrete state size\r\n elif len(self.env.observation_space.shape) == 1:\r\n state_size = self.env.observation_space.shape[0] # convert box vector to 1 unit state space\r\n else:\r\n process_state = preprocess(self.env.reset())\r\n state_size = process_state.shape\r\n return state_size\r\n\r\n def create_fcmodel(self):\r\n\r\n data_input = Input(shape=(self.state_size,), name='data_input')\r\n h1 = Dense(24, activation='relu')(data_input)\r\n h2 = Dense(48, activation='relu')(h1)\r\n h3 = Dense(24, activation='relu')(h2)\r\n prediction_output = Dense(self.action_size, name='prediction_output', activation='linear')(h3) # activation?\r\n\r\n model = Model(inputs=data_input, outputs=prediction_output)\r\n model.compile(optimizer=Adam(lr=self.lr),\r\n loss='mean_squared_error') # keras.losses.logcosh(y_true, y_pred)\r\n return model\r\n\r\n def create_cnnmodel(self):\r\n\r\n data_input = Input(shape=self.state_size, name='data_input', dtype='int32')\r\n normalized = Lambda(lambda x: x/255)(data_input) # normalise data in input\r\n conv1 = convolutional.Convolution2D(32, 8, strides=(4, 4), activation='relu')(normalized) #, data_format='channels_last')\r\n conv2 = convolutional.Convolution2D(64, 4, strides=(2,2), activation='relu')(conv1)\r\n conv3 = convolutional.Convolution2D(64, 3, strides=(1,1), activation='relu')(conv2)\r\n conv_flatten = core.Flatten()(conv3) # flatten to feed cnn to fc\r\n h4 = Dense(512, activation='relu')(conv_flatten)\r\n prediction_output = Dense(self.action_size, name='prediction_output', activation='linear')(h4)\r\n\r\n model = Model(inputs=data_input, outputs=prediction_output)\r\n model.compile(optimizer=Adam(lr=self.lr),\r\n loss='mean_squared_error') # 'mean_squared_error') keras.losses.logcosh(y_true, y_pred)\r\n return model\r\n\r\n def remember(self, state, action, reward, new_state, done): # store past experience as a pre-defined table\r\n self.memory.append([state, action, reward, new_state, done])\r\n\r\n def replay(self, batch_size):\r\n if batch_size > len(self.memory):\r\n return\r\n\r\n samples = random.sample(self.memory, batch_size) # select batches of memory to learn without biasing train set\r\n for sample in samples:\r\n state, action, reward, new_state, done = sample\r\n target = self.target_model.predict(state) # compute rewards given state\r\n #self.y_pred = tuple(target)\r\n if done:\r\n target[0][action] = reward # if episode ended, take reward from action\r\n else:\r\n # take reward with discounted future reward from next state\r\n target[0][action] = reward + self.gamma*np.max(self.target_model.predict(new_state)[0])\r\n self.model.fit(state, target, epochs=1, verbose=0) # Train NN parameter with\r\n\r\n def act(self, state):\r\n self.eps *= self.decay # compute eps decay\r\n self.eps = max(self.eps_min, self.eps)\r\n if np.random.random() < self.eps:\r\n return self.env.action_space.sample() # depend on env use self.env.action_space.sample()\r\n return np.argmax(self.model.predict(state)[0]) # WHY NOT TARGET_MODEL HERE?\r\n\r\n def train_target(self):\r\n weights = self.model.get_weights()\r\n target_weights = self.target_model.get_weights()\r\n for i in range(len(target_weights)):\r\n target_weights[i] = (1-self.tau)*target_weights[i] + self.tau*weights[i] # slower update of target weights\r\n self.target_model.set_weights(target_weights) # Take action using model but replay using target_model???\r\n\r\n def save_model(self, fn):\r\n self.model.save(fn)\r\n\r\n\r\ndef main():\r\n\r\n env = gym.make('BreakoutDeterministic-v4')\r\n # env._max_episode_steps = 500\r\n\r\n cnn = True # specify if need CNN model\r\n agent = DQNAgent(env, cnn) # dqn_v1_brain.DQNAgent(env, cnn)\r\n\r\n episodes = int(input('How many episodes?'))\r\n save_file = input('Save Model? [y/n]: ')\r\n save_plot = input('Save Plot? [y/n]: ')\r\n rend_env = input('Render Environment? [y/n]: ')\r\n\r\n time = 1000001\r\n batch_size = 32\r\n\r\n tot_r = []\r\n tot_t = []\r\n\r\n for e in range(episodes):\r\n r = 0\r\n state = env.reset()\r\n state = preprocess(state)\r\n state_size = list(state.shape)\r\n state_size.insert(0,1) # define shape to be [batch size, height, width, channel]\r\n state = np.reshape(state, state_size) # reshape state size into [batch_size=1, state_size] for model\r\n\r\n for t in range(time):\r\n if rend_env == 'y':\r\n env.render()\r\n\r\n T = 0\r\n action = agent.act(state)\r\n new_state, reward, done, _ = env.step(action)\r\n new_state = preprocess(new_state) # process new_state\r\n new_state = np.reshape(new_state, state_size) # reshape new_state to have batch size 1\r\n\r\n agent.remember(state, action, reward, new_state, done)\r\n\r\n agent.replay(batch_size) # train agent with number of batch_size\r\n agent.train_target()\r\n\r\n state = new_state\r\n r += reward\r\n\r\n if done:\r\n print('Episode {} of {}, last for {}s'.format(e, episodes, t))\r\n T +=t\r\n break\r\n tot_r.append(r)\r\n tot_t.append(np.mean(T))\r\n\r\n if save_file == 'y':\r\n agent.save_model('Breakout_success_model_{}epi.h5'.format(episodes))\r\n\r\n if rend_env == 'y':\r\n env.close()\r\n\r\n plt.figure(1)\r\n plt.plot(list(range(1, episodes + 1)), tot_r)\r\n plt.xlabel('Episodes')\r\n plt.ylabel('Total Reward per Episode')\r\n plt.title('DQNv2 Breakout {}eps'.format(episodes))\r\n plt.plot(list(range(1, episodes + 1)), tot_t)\r\n plt.legend(['reward','time'])\r\n if save_plot == 'y':\r\n plt.savefig(\r\n 'C:\\\\Users\\\\User\\\\PycharmProjects\\\\GaneshLearning\\\\ReinforcementLearning\\\\DQN\\\\CartPole_{}eps.png'.format(\r\n episodes))\r\n plt.show()\r\n\r\n return tot_r, tot_t, episodes\r\n\r\n\r\nif __name__ == '__main__':\r\n total_reward, total_time, epi = main()\r\n\r\n","sub_path":"dqn_v2.py","file_name":"dqn_v2.py","file_ext":"py","file_size_in_byte":9032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"194400651","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\n@File : settingsView.py\n@Date : 2021/05/11\n@Author : Yaronzz\n@Version : 1.0\n@Contact : yaronhuang@foxmail.com\n@Desc :\n\"\"\"\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QGridLayout\n\nfrom tidal_gui.control.checkBox import CheckBox\nfrom tidal_gui.control.comboBox import ComboBox\nfrom tidal_gui.control.label import Label\nfrom tidal_gui.control.line import Line\nfrom tidal_gui.control.lineEdit import LineEdit\nfrom tidal_gui.control.pushButton import PushButton\nfrom tidal_gui.style import LabelStyle, ButtonStyle, ThemeStyle\n\n\nclass SettingsView(QWidget):\n def __init__(self):\n super(SettingsView, self).__init__()\n self.__initView__()\n\n def __initView__(self):\n grid = QVBoxLayout(self)\n grid.addLayout(self.__initHeader__())\n grid.addLayout(self.__initContent__())\n grid.addLayout(self.__initToolButton__())\n\n def __initHeader__(self):\n self._header = Label(\"SETTINGS\", LabelStyle.PageTitle)\n layout = QVBoxLayout()\n layout.addWidget(self._header)\n layout.addWidget(Line('H'))\n layout.setSpacing(10)\n layout.setContentsMargins(0, 0, 0, 10)\n return layout\n\n def __initToolButton__(self) -> QHBoxLayout:\n self._logoutBtn = PushButton('Logout', ButtonStyle.Danger, 100)\n self._cancelBtn = PushButton('Cancel', ButtonStyle.Default, 100)\n self._confirmBtn = PushButton('OK', ButtonStyle.Primary, 100)\n\n layout = QHBoxLayout()\n layout.addWidget(self._logoutBtn)\n layout.addStretch(1)\n layout.addWidget(self._cancelBtn)\n layout.addWidget(self._confirmBtn)\n return layout\n\n def __addContent__(self, control, desc=''):\n rowIdx = self._contentLayout.rowCount()\n if desc != '':\n self._contentLayout.addWidget(Label(desc), rowIdx, 0, Qt.AlignRight)\n self._contentLayout.addWidget(control, rowIdx, 1)\n\n def __initContent__(self):\n self._contentLayout = QGridLayout()\n self._contentLayout.setSpacing(15)\n\n self._pathEdit = LineEdit()\n self._threadNumComboBox = ComboBox([1, 5, 10, 20])\n self._searchNumComboBox = ComboBox([10, 20, 30, 40, 50])\n self.__addContent__(self._pathEdit, 'Path:')\n self.__addContent__(self._threadNumComboBox, 'ThreadNum:')\n self.__addContent__(self._searchNumComboBox, 'SearchNum:')\n\n self._contentLayout.setRowStretch(self._contentLayout.rowCount(), 1)\n\n self._albumFolderFormatEdit = LineEdit()\n self._trackFileFormatEdit = LineEdit()\n self._videoFileFormatEdit = LineEdit()\n self.__addContent__(self._albumFolderFormatEdit, 'AlbumFolderFormat:')\n self.__addContent__(self._trackFileFormatEdit, 'TrackFileFormat:')\n self.__addContent__(self._videoFileFormatEdit, 'VideoFileFormat:')\n\n self._saveCoverCheck = CheckBox('Download album cover')\n self._skipExistCheck = CheckBox('Skip exist file when downloading')\n self._convertMp4ToM4a = CheckBox('Convert mp4 to m4a')\n self.__addContent__(self._saveCoverCheck)\n self.__addContent__(self._skipExistCheck)\n self.__addContent__(self._convertMp4ToM4a)\n\n self._contentLayout.setRowStretch(self._contentLayout.rowCount(), 1)\n\n self._themeComboBox = ComboBox(list(map(lambda x: x.name, ThemeStyle)))\n self._languageComboBox = ComboBox(['Default'])\n self.__addContent__(self._themeComboBox, 'Theme:')\n self.__addContent__(self._languageComboBox, 'Language:')\n\n self._contentLayout.setRowStretch(self._contentLayout.rowCount(), 10)\n return self._contentLayout\n","sub_path":"TIDALDL-GUI-CROSS/tidal_gui/view/settingsView.py","file_name":"settingsView.py","file_ext":"py","file_size_in_byte":3726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"98531664","text":"#variables = {}\n\n# imported from cuts.py\n# cuts\n\ntry:\n variables\nexcept NameError:\n import collections\n variables = collections.OrderedDict()\n cuts = []\n\nsr = [ckey for ckey in cuts if '_CR' not in ckey]\n\n#'fold' : # 0 = not fold (default), 1 = fold underflowbin, 2 = fold overflow bin, 3 = fold underflow and overflow\n\nvariables['events'] = {\n 'name': '0.5',\n 'range': (1,0,1),\n 'xaxis': 'events'\n}\n\nmthbinning = [60,80,90,100,110,120,130,150,200]\nmllbinning = [10,25,35,40,45,50,55,70,90,210]\nname = ''\nmllbin = ['1'] # folding underflow -> always 1\nfor imll in range(1, len(mllbinning) - 1):\n mllbin.append('(mll >= %d)' % mllbinning[imll])\nname += '+'.join(mllbin)\nname += ' + %d*(' % (len(mllbinning) - 1)\nmthbin = [] # 1-1 for first bin\nfor imth in range(1, len(mthbinning) - 1):\n mthbin.append('(mth >= %d)' % mthbinning[imth])\nname += '+'.join(mthbin)\nname += ') - 0.5'\n\nvariables['mllVSmth_8x9'] = {\n 'name': name,\n 'range': (72, 0., 72.),\n 'xaxis': 'm^{ll}:m_{T}^{H}', # x axis name\n 'doWeight': 1, # do weighted plot too\n 'cuts': sr\n}\n\nmthbinning = [60,80,90,110,130,150,200]\nmllbinning = [10,25,40,50,70,90,210]\nname = ''\nmllbin = ['1'] # folding underflow -> always 1\nfor imll in range(1, len(mllbinning) - 1):\n mllbin.append('(mll >= %d)' % mllbinning[imll])\nname += '+'.join(mllbin)\nname += ' + %d*(' % (len(mllbinning) - 1)\nmthbin = [] # 1-1 for first bin\nfor imth in range(1, len(mthbinning) - 1):\n mthbin.append('(mth >= %d)' % mthbinning[imth])\nname += '+'.join(mthbin)\nname += ') - 0.5'\n\nvariables['mllVSmth_6x6'] = {\n 'name': name,\n 'range': (36, 0., 36.),\n 'xaxis': 'm^{ll}:m_{T}^{H}', # x axis name\n 'doWeight': 1, # do weighted plot too\n 'cuts': sr\n}\n","sub_path":"Configurations/Differential/ggH2017/variables.py","file_name":"variables.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"623766564","text":"import pandas as pk\nimport numpy as np\nimport datetime as dt\nimport matplotlib.pyplot as plt\n\nstartTime = dt.datetime.now()\n\nWeekLabels = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\n\n\n# df = pk.read_excel(\"/home/tcs/Desktop/pavan_guest/neway.xlsx\", sheetname=0) #dat.dropna(how='any')\ndf = pk.read_excel('/home/pavan/PAVANKUMAR/MachineLearning/CaseStudy/ML_DATA/v4/k5/FinalFiles/Data_Sorted_nan.xlsx',\n sheetname=0)\n# print df\nCinBsyList = []\nCoutBsyList = []\nn = []\n\nCin_Uniq = df['CheckInDate'].unique()\n#print Cin_Uniq\n\nCout_Uniq = df['CheckOutDate'].unique()\n\n\n# ds = df[df.CheckOutDate == Cout_Uniq[0]]\n# q = ds[ds.CheckOutTime == 17]\n# print len(q)\n\n\ndef F(h):\n\n ds = df[df.CheckInDate == h]\n Z = (map(lambda y: CinBsyList.append(len(ds[ds.CheckinTime == y])), range(0, 25)))\n\n\n\ndef G(k):\n\n ds = df[df.CheckOutDate == k]\n Z = (map(lambda y: CoutBsyList.append(len(ds[ds.CheckOutTime == y])), range(0, 25)))\n\n\nmap(F, Cin_Uniq)\nmap(G, Cout_Uniq)\n\n#print n\n\n#print 'CinBsyList'\n#print CinBsyList\nprint\n#print 'CoutBsyList'\n#print CoutBsyList\n\nCinchunk = [CinBsyList[x:x+24] for x in range(0, len(CinBsyList), 24)]\n#print Cinchunk\n\nCoutchunk = [CoutBsyList[x:x+24] for x in range(0, len(CoutBsyList), 24)]\n#print Coutchunk\n\ndy = pk.read_excel(\"/home/pavan/PAVANKUMAR/MachineLearning/CaseStudy/ML_DATA/v4/k5/FinalFiles/DayFile.xlsx\", sheetname=0)\n\ndy2 = pk.read_excel(\"/home/pavan/PAVANKUMAR/MachineLearning/CaseStudy/ML_DATA/v4/k5/FinalFiles/DayFile_Cout.xlsx\", sheetname=0)\n\n\nkk = dy.groupby(\"WeekDay\")\npp = dy2.groupby('CoutWeekDay')\n\n\nfg = 0\nfig1 = plt.figure()\n#fig2 = plt.figure()\n\nfor label in WeekLabels:\n\n L = kk.get_group(label)\n M = pp.get_group(label)\n qq = np.column_stack(map(lambda c: Cinchunk[c], L.index))\n nn = np.column_stack(map(lambda d: Coutchunk[d], M.index))\n fg += 1\n #print qq\n\n\n zz = np.mean(qq, axis=1)\n tt = np.mean(nn, axis=1)\n #print tt\n\n ax1 = fig1.add_subplot(3, 3, fg)\n ax1.set_axis_bgcolor(\"lightslategray\")\n ax1.xaxis.label.set_color('g')\n ax1.yaxis.label.set_color('g')\n plt.plot(zz, color='w')\n plt.xlabel(label)\n plt.ylabel('Mean of Cars')\n\n'''\n ax2 = fig2.add_subplot(3, 3, fg)\n ax2.set_axis_bgcolor(\"lightslategray\")\n ax2.xaxis.label.set_color('g')\n ax2.yaxis.label.set_color('g')\n plt.plot(tt, color='w')\n plt.xlabel(label)\n plt.ylabel('Mean of Cars')\n plt.show()\n'''\n\n\nplt.show()\n\n\n\n\n# map(lambda y: n.append(len(ds[ds.CheckOutTime == y])), range(0,25))\n\n\n# t = list(map(lambda x: list(map(lambda y: n.append(x + y), Y)),X))\n\n\n'''\n\ndef myFun(j):\n x_ = df.CheckinTime[j]\n z[x_] = z[x_] + 1\n return z\n\n\ndef YFun(k):\n x_ = df.CheckOutTime[k]\n z[x_] = z[x_] + 1\n return z\n\n\nfor rin in range(0, len(Cin_Uniq)):\n z = np.zeros(24)\n qin = df[df.CheckInDate == Cin_Uniq[rin]].index.tolist()\n # print q\n\n WER = map(myFun, qin)\n CinBsyList.append(WER[0])\n del WER[:]\n # break\n\nprint 'Busiest CheckinList is :'\nprint CinBsyList\n\nfor rout in range(0, len(Cout_Uniq)):\n z = np.zeros(24)\n qout = df[df.CheckOutDate == Cout_Uniq[rout]].index.tolist()\n # print qout\n\n WER = map(YFun, qout)\n CoutBsyList.append(WER[0])\n del WER[:]\n\nprint 'Busiest CheckouList is :'\nprint CoutBsyList\n\nEndTime = dt.datetime.now() - startTime\nprint EndTime\n\n'''\n#/home/pavan/PycharmProjects/CaseStudy/check_2.py","sub_path":"Busiest_Cin_Cout.py","file_name":"Busiest_Cin_Cout.py","file_ext":"py","file_size_in_byte":3414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"362678004","text":"from tkinter import *\nwn=Tk()\nwn.title(\"hddh\")\nwn.geometry(\"200x20\")\ndef abc():\n lbl_1 = Label(wn, text=\"hello ! \")\n\n lbl_2 = Label(wn, text=\"world\")\n lbl_1.pack(padx=10, pady=20)\n lbl_2.pack(padx=10, pady=20)\n Button_1=Button(wn,text=\"check\")\n Button_1.pack(side=\"right\")\n\n Button_1.bind(\"<Button_1>\",abc)\n\nwn.mainloop()\n","sub_path":"sjsj.py","file_name":"sjsj.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"55671734","text":"import os\r\nimport urllib.request\r\nimport json\r\nimport tqdm\r\n\r\ndata_dir = \"./infographicVQA_train_0.1/infographicVQA_train_v0.1.json\"\r\nimg_dir = \"./img\"\r\nwith open(data_dir,'r') as load_f:\r\n data_raw = json.load(load_f)\r\n\r\nopener = urllib.request.build_opener()\r\nopener.addheaders = [('User-Agent',\r\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36')]\r\n\r\nurllib.request.install_opener(opener)\r\nurl = []\r\nurl_complete = []\r\nfor i, data in enumerate(data_raw[\"data\"]):\r\n if not (data[\"image_url\"] in url):\r\n url.append(data[\"image_url\"])\r\n try:\r\n filename = '{}/{}'.format(img_dir, data[\"image_local_name\"])\r\n if not os.path.isfile(filename):\r\n urllib.request.urlretrieve(data[\"image_url\"], filename)\r\n url_complete.append(data[\"image_url\"])\r\n except:\r\n continue\r\n\r\nurl_error = list(set(url).difference(set(url_complete)))\r\nprint(len(url_error))\r\n\r\n\r\nwith open('url_error.txt', 'w') as f:\r\n for i in range(len(url_error)):\r\n for key, values in url_error[i].items():\r\n print(key+\",\"+values+\"\\r\")\r\n f.write(key+\",\"+values+\"\\r\")\r\n\r\n\r\n\r\n\r\n","sub_path":"20201201/img_download.py","file_name":"img_download.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"328653147","text":"import os\nimport sys\nimport click\nfrom lxml import etree\nimport json\nimport antlr2xsd\n\n@click.command()\n@click.argument('infile', nargs=1)\n@click.argument('roottype',nargs=1)\n@click.argument('rootname',nargs=1)\n@click.argument('outfile', nargs=1)\ndef main(infile,roottype,rootname,outfile):\n listener_opts = {\n 'root_name': rootname,\n 'root_type': roottype,\n 'tns': 'http://www.sharpx.org/'+rootname,\n }\n xsd = antlr2xsd.g4_parser.parse(\n infile,\n listener_opts\n )\n xsd_str = etree.tostring(xsd, pretty_print=True).decode('utf-8')\n with open(outfile, 'w') as f:\n f.write(xsd_str)\n","sub_path":"src/antlr2xsd/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"509545546","text":"# import the necessary packages\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import confusion_matrix\nfrom imutils import build_montages\nfrom imutils import paths\nimport numpy as np\nimport argparse\nimport cv2\nimport os\nimport lib\nfrom datetime import date\n\ndef function(image_entered, name_entered):\n\n # construct the argument parser and parse the arguments\n ap = argparse.ArgumentParser()\n #ap.add_argument(\"-n\", \"--name\", required=True, help=\"patient name\")\n #ap.add_argument(\"-i\", \"--image\", required=True, help=\"image test\")\n ap.add_argument(\"-t\", \"--trials\", type=int, default=5, help=\"# of trials to run\")\n args = vars(ap.parse_args())\n\n # define the path to the training and testing directories\n trainingPath = os.path.sep.join([\"dataset\", \"training\"])\n\n patientPath = os.path.sep.join([\"dataset\", name_entered])\n \n x = list(paths.list_images(patientPath))\n today = date.today()\n p1=patientPath+\"/\"+str(today)\n p = os.path.sep.join([p1, \"{}.png\".format(str(len(x)))])\n\n i=cv2.imread(image_entered)\n cv2.imwrite(p,i)\n\n # loading the training and testing data\n print(\"[INFO] loading data...\")\n (trainFeatures, trainLabels) = lib.load_split(trainingPath)\n\n # encode the labels as integers 0:healthy, 1:parkinsons\n le = LabelEncoder()\n trainLabels = le.fit_transform(trainLabels)\n #testLabels = le.transform(testLabels)\n\n # initialize our trials dictionary\n trials = {}\n\n # loop over the number of trials to run\n for i in range(0, args[\"trials\"]):\n # train the model\n print(\"[INFO] training model {} of {}...\".format(i + 1,args[\"trials\"]))\n model = RandomForestClassifier(n_estimators=100)\n model.fit(trainFeatures, trainLabels)\n metrics = {}\n\n # select last 4 images in the patient path\n patientPaths = list(paths.list_images(patientPath))\n y = len(patientPaths)\n z = 0\n if y > 4: z = y-4;\n idxs = np.arange(z, y)\n images = []\n print(z,y)\n\n # loop over the testing samples\n for i in idxs:\n # load the testing image, clone it, and resize it\n image = cv2.imread(patientPaths[i])\n output = image.copy()\n output = cv2.resize(output, (128, 128))\n\n #pre-process the image in the same manner we did earlier\n image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n image = cv2.resize(image, (200, 200))\n image = cv2.threshold(image, 0, 255,\n cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]\n img_date=os.path.split(patientPaths[i])\n liste=img_date[0].split(\"\\\\\")\n # quantify the image and make predictions based on the extracted\n # features using the last trained Random Forest\n features = lib.quantify_image(image)\n preds = model.predict([features])\n label = le.inverse_transform(preds)[0]\n\n # draw the colored class label on the output image and add it to\n # the set of output images\n color = (0, 255, 0) if label == \"healthy\" else (0, 0, 255)\n cv2.putText(output, label, (3, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5,\n color, 2)\n cv2.putText(output, liste[2], (3, 45), cv2.FONT_HERSHEY_SIMPLEX, 0.5,\n color, 2)\n images.append(output)\n\n # create a montage using 128x128 \"tiles\" with 1 row and 4 columns\n montage = build_montages(images, (140, 140), (4, 1))[0]\n\n # show the output montage\n cv2.imshow(\"Output\", montage)\n cv2.waitKey(0)\n","sub_path":"detect.py","file_name":"detect.py","file_ext":"py","file_size_in_byte":3533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"29420185","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nplt.close()\n\nf=open(\"../toPlot/Cube.dat\", \"r\")\nn = f.read().split(\"\\n\")\nA=[i.split(\" \") for i in n]\nB=[[] for _ in n]\nfor i in range(1,len(A)):\n B[i] = filter(lambda a : len(a) > 0, A[i])\nB = filter(lambda a : len(a)>1, B)\n##plt.axis([-1, 1, -50, 50])\nC = [[float(B[i][j]) for i in range(len(B))] for j in range(len(B[0]))]\nX = np.linspace(-5, 5, len(C[0]))\nfor i in C:\n print(\"Y : \" + str(i))\n plt.plot(X, i)\nplt.savefig('../plotted/cube.svg')","sub_path":"src/traitementCube.py","file_name":"traitementCube.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"65649417","text":"'''\nThis App illustrates the use of Sliders to set window size in Tkinter\n'''\n#Packages\nfrom tkinter import *\nfrom PIL import ImageTk,Image\nfrom tkinter import messagebox\nfrom tkinter import filedialog\n\nwindow = Tk()\nwindow.title(\"Sliders\")\nwindow.iconbitmap('D:/e-Learning/Tkinter/Images/India-flag.ico')\nwindow.geometry(\"400x400\")\n\ndef slide1():\n #lbl = Label(window, text=horizontal.get()).pack()\n window.geometry(str(horizontal.get()) + \"x\" + str(vertical.get()))\n\n#def slide2(var):\n #lbl = Label(window, text=vertical.get()).pack()\n #window.geometry(str(vertical.get()) + \"\")\n\nvertical = Scale(window, from_=0, to=650)\nvertical.pack()\n\nhorizontal = Scale(window, from_=0, to=1300, orient=HORIZONTAL)\nhorizontal.pack()\n\n#lbl = Label(window, text=horizontal.get()).pack()\n\nbtn = Button(window, text=\"Click to fetch size!\", command=slide1).pack()\n#btn2 = Button(window, text=\"Click to fetch vertical\", command=slide2).pack()\n\n#event handler\nwindow.mainloop()\n","sub_path":"App's/sliders.py","file_name":"sliders.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"260314886","text":"import os\nimport shutil\nimport numpy as np\nfrom PIL import Image\nimport imagehash\n\npath = input('Files Folder (full path): ')\nname_files = os.listdir(path)\nnfiles = len(name_files)\n\nsimilar = input('Similar pics?[y/n]: ')\nquite = input('Quite_similar pics?[y/n]: ')\ncloser = input('Nearest pics?[y/n]: ')\n\nlevel = 1\n\nif closer == 'y':\n os.mkdir(path + 'nearest')\n closer_path = path + 'nearest/'\n level = 25\n\nif quite == 'y':\n os.mkdir(path + 'quite_similar')\n less_similar_path = path + 'quite_similar/'\n level = 10\n\nif similar == 'y':\n os.mkdir(path + 'similar')\n similar_path = path + 'similar/'\n level = 5\n\nfor n in range(0,nfiles):\n if n == 0:\n try:\n aux = np.array([imagehash.average_hash(Image.open(path + name_files[n]))])\n except:\n print('Error: '+ name_files[n])\n delete = input('Delete file?[y/n]: ')\n if delete == 'y':\n os.remove(path + name_files[n])\n else:\n try:\n aux = np.concatenate((aux, np.array([imagehash.average_hash(Image.open(path + name_files[n]))])), axis=0)\n except:\n print('Error: ' + name_files[n])\n delete = input('Delete file?[y/n]: ')\n if delete == 'y':\n os.remove(path + name_files[n])\n\nname_files = os.listdir(path)\nnfiles = len(name_files)\nos.mkdir(path + 'identical')\nidentical_path = path + 'identical/'\n\n\ni = 0\nnfiles = len(aux)\nfor n in range(0,nfiles):\n current_file = name_files[n]\n for n2 in range(n+1,nfiles):\n check_file = name_files[n2]\n hash0 = aux[n]\n hash1 = aux[n2]\n\n dif = hash0 - hash1\n\n if dif < level:\n i = i\n if dif == 0:\n print('Identical pics found')\n shutil.copyfile(path + current_file, identical_path + current_file)\n shutil.copyfile(path + check_file, identical_path + check_file)\n elif (dif >1 ) & (dif < 5):\n print('Similar pics found')\n shutil.copyfile(path + current_file, similar_path + current_file)\n shutil.copyfile(path + check_file, similar_path + check_file)\n elif (dif > 5) & (dif < 10):\n print('Quite similar pics found')\n shutil.copyfile(path + current_file, less_similar_path + current_file)\n shutil.copyfile(path + check_file, less_similar_path + check_file)\n elif (dif > 10) & (dif < 25) & (closer == 'y'):\n print('Nearest pics found')\n shutil.copyfile(path + current_file, closer_path + current_file)\n shutil.copyfile(path + check_file, closer_path + check_file)\n\n if i == 0:\n found = [name_files[n]]\n else:\n found.append(name_files[n])\n\n i = i + 1\n\ntry:\n found = list(set(found))\n for i in range(0, len(found)):\n os.remove(path + found[i])\n rm_identical = input('Remove Identicals? (Warning bw pics!)[y/n]: ' )\n if rm_identical == 'y':\n shutil.rmtree(identical_path)\nexcept:\n print('No similar images found')\n shutil.rmtree(identical_path)\n\n\n\n","sub_path":"ImageSearch.py","file_name":"ImageSearch.py","file_ext":"py","file_size_in_byte":2864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"258576977","text":"#!/usr/bin/env python\n# vim: ai ts=4 sts=4 et sw=4\n\nfrom datetime import datetime, timedelta\nfrom rapidsms.contrib.handlers.handlers.keyword import KeywordHandler\nfrom rapidsms.contrib.handlers.handlers.tagging import TaggingHandler\nfrom django.db.models import Q\nfrom django.utils.translation import ugettext as _\nfrom logistics.util import config\nfrom logistics.shortcuts import create_stock_report\nfrom logistics.const import Reports\nfrom logistics.decorators import logistics_contact_required\nimport logging\nfrom logistics_project.apps.tanzania.models import SupplyPointStatus,\\\n SupplyPointStatusTypes, SupplyPointStatusValues\nfrom logistics.models import ProductStock, Product\n\nCHARS_IN_CODE = \"2, 4\"\nNUMERIC_LETTERS = (\"lLIoO\", \"11100\")\n\nclass StockOnHandHandler(KeywordHandler,TaggingHandler):\n \"\"\"\n \"\"\"\n keyword = \"soh|hmk\"\n \n def help(self):\n self.respond(_(config.Messages.SOH_HELP_MESSAGE))\n\n @logistics_contact_required()\n def handle(self, text):\n contact = self.msg.logistics_contact\n sp = self.msg.logistics_contact.supply_point\n stock_report = create_stock_report(Reports.SOH, \n sp,\n text, \n self.msg.logger_msg,\n self.msg.timestamp)\n \n if stock_report.errors:\n self.respond_error(_(config.Messages.SOH_BAD_FORMAT))\n return\n \n else: \n expected_products = set(contact.commodities.all())\n \n # define missing as products not seen in the last 7 days\n # the exclusion prevents newly added products from counting as \"seen\"\n start_date = datetime.utcnow() + timedelta(days=-7)\n seen_products = set(Product.objects.get(pk=product_id) for product_id in \\\n ProductStock.objects.filter\\\n (supply_point=sp, last_modified__gte=start_date)\\\n .exclude(quantity=None)\\\n .values_list(\"product\", flat=True))\n \n # if missing products tell them they still need to report, otherwise send confirmation \n missing_products = expected_products - seen_products\n if missing_products:\n kwargs = {'contact_name': self.msg.contact.name,\n 'facility_name': sp.name,\n 'product_list': ' '.join(sorted([p.sms_code for p in missing_products]))}\n self.respond(_(config.Messages.SOH_PARTIAL_CONFIRM), **kwargs)\n else: \n self.respond(_(config.Messages.SOH_CONFIRM), \n reply_list=','.join(sorted(stock_report.reported_products())))\n\n SupplyPointStatus.objects.create(supply_point=sp,\n status_type=SupplyPointStatusTypes.SOH_FACILITY,\n status_value=SupplyPointStatusValues.SUBMITTED,\n status_date=self.msg.timestamp)\n # this is an artifact of the response generating the l&a reminder\n SupplyPointStatus.objects.create(supply_point=sp,\n status_type=SupplyPointStatusTypes.LOSS_ADJUSTMENT_FACILITY,\n status_value=SupplyPointStatusValues.REMINDER_SENT,\n status_date=self.msg.timestamp)\n \n","sub_path":"logistics_project/apps/tanzania/handlers/stockonhand.py","file_name":"stockonhand.py","file_ext":"py","file_size_in_byte":3621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"113636187","text":"\"\"\"\nPrototype selection\n\nGiven a set of n elements (S) and their pairwise distances in terms of a\nskbio distance matrix (DM) and a given number (k << n), find the sub-set (s)\nconsisting of exactly k elements, such that s best represents the full set S.\n\nHere, we define \"best represents\" as maximizing the sum of distances between\nall points, i.e. sum {over a,b in S} DM[a,b]. This is our objective function.\n\nThis problem is known to be NP-hard [1], thus we need to resort to heuristics.\nThis module implements several heuristics, whose quality can be measured by\nthe objective function for each problem instance, since there is no global\nwinner. Currently implemented are:\n - prototype_selection_constructive_maxdist\nFor completeness, the exact but exponential algorithm is implemented, too.\n \"prototype_selection_exhaustive\"\n\n[1] Gamez, J. Esteban, François Modave, and Olga Kosheleva.\n \"Selecting the most representative sample is NP-hard:\n Need for expert (fuzzy) knowledge.\"\n Fuzzy Systems, 2008. FUZZ-IEEE 2008.\n\"\"\"\n\n# needed for signature type annotations, but only works for python >= 3.5\n# from typing import Sequence, Tuple\nfrom itertools import combinations\n\nimport numpy as np\nimport scipy as sp\nfrom skbio.stats.distance import DistanceMatrix\n\n\ndef distance_sum(elements, dm):\n '''Compute the sum of pairwise distances for the given elements according to\n the given distance matrix.\n\n Parameters\n ----------\n elements: sequence of str\n List or elements for which the sum of distances is computed.\n dm: skbio.stats.distance.DistanceMatrix\n Pairwise distance matrix.\n\n Returns\n -------\n float:\n The sum of all pairwise distances of dm for IDs in elements.\n\n Notes\n -----\n function signature with type annotation for future use with python >= 3.5\n def distance_sum(elements: Sequence[str], dm: DistanceMatrix) -> float:\n '''\n\n return np.tril(dm.filter(elements).data).sum()\n\n\ndef prototype_selection_exhaustive(dm, num_prototypes,\n max_combinations_to_test=200000):\n '''Select k prototypes for given distance matrix\n\n Parameters\n ----------\n dm: skbio.stats.distance.DistanceMatrix\n Pairwise distances for all elements in the full set S.\n num_prototypes: int\n Number of prototypes to select for distance matrix.\n Must be >= 2, since a single prototype is useless.\n Must be smaller than the number of elements in the distance matrix,\n otherwise no reduction is necessary.\n max_combinations_to_test: int\n The maximal number of combinations to test. If exceeding, the function\n declines execution.\n\n Returns\n -------\n list of str\n A sequence holding selected prototypes, i.e. a sub-set of the\n elements in the distance matrix.\n\n Raises\n ------\n RuntimeError\n Combinatorics explode even for small instances. To save the user from\n waiting (almost) forever, this function declines execution if the\n number of combinations to test are too high,\n i.e. > max_combinations_to_test\n ValueError\n The number of prototypes to be found should be at least 2 and at most\n one element smaller than elements in the distance matrix. Otherwise, a\n ValueError is raised.\n\n Notes\n -----\n This is the reference implementation for an exact algorithm for the\n prototype selection problem. It has an exponential runtime and will only\n operate on small instances (< max_combinations_to_test).\n Idea: test all (n over k) combinations of selecting k elements from n with-\n out replacement. Compute the objective for each such combination and\n report the combination with maximal value.\n\n function signature with type annotation for future use with python >= 3.5:\n def prototype_selection_exhaustive(dm: DistanceMatrix, num_prototypes: int,\n max_combinations_to_test: int=200000) -> List[str]:\n '''\n if num_prototypes < 2:\n raise ValueError((\"'num_prototypes' must be >= 2, since a single \"\n \"prototype is useless.\"))\n if num_prototypes >= len(dm.ids):\n raise ValueError((\"'num_prototypes' must be smaller than the number of\"\n \" elements in the distance matrix, otherwise no \"\n \"reduction is necessary.\"))\n\n num_combinations = sp.special.binom(len(dm.ids), num_prototypes)\n if num_combinations >= max_combinations_to_test:\n raise RuntimeError((\"Cowardly refuse to test %i combinations. Use a \"\n \"heuristic implementation for instances with more \"\n \"than %i combinations instead!\")\n % (num_combinations, max_combinations_to_test))\n\n max_dist, max_set = -1 * np.infty, None\n for s in set(combinations(dm.ids, num_prototypes)):\n d = distance_sum(s, dm)\n if d > max_dist:\n max_dist, max_set = d, s\n return list(max_set)\n\n\ndef prototype_selection_constructive_maxdist(dm, num_prototypes):\n '''Heuristically select k prototypes for given distance matrix.\n\n Prototype selection is NP-hard. This is an implementation of a greedy\n correctness heuristic: Greedily grow the set of prototypes by adding the\n element with the largest sum of distances to the non-prototype elements.\n Start with the two elements that are globally most distant from each\n other. The set of prototypes is then constructively grown by adding the\n element showing largest sum of distances to all non-prototype elements\n in the distance matrix in each iteration.\n\n Parameters\n ----------\n dm: skbio.stats.distance.DistanceMatrix\n Pairwise distances for all elements in the full set S.\n num_prototypes: int\n Number of prototypes to select for distance matrix.\n Must be >= 2, since a single prototype is useless.\n Must be smaller than the number of elements in the distance matrix,\n otherwise no reduction is necessary.\n\n Returns\n -------\n list of str\n A sequence holding selected prototypes, i.e. a sub-set of the\n elements in the distance matrix.\n\n Raises\n ------\n ValueError\n The number of prototypes to be found should be at least 2 and at most\n one element smaller than elements in the distance matrix. Otherwise, a\n ValueError is raised.\n\n Notes\n -----\n Timing: %timeit -n 100 prototype_selection_constructive_maxdist(dm, 100)\n 100 loops, best of 3: 1.43 s per loop\n where the dm holds 27,398 elements\n function signature with type annotation for future use with python >= 3.5:\n def prototype_selection_constructive_maxdist(dm: DistanceMatrix,\n num_prototypes: int) -> List[str]:\n '''\n if num_prototypes < 2:\n raise ValueError((\"'num_prototypes' must be >= 2, since a single \"\n \"prototype is useless.\"))\n if num_prototypes >= len(dm.ids):\n raise ValueError((\"'num_prototypes' must be smaller than the number of\"\n \" elements in the distance matrix, otherwise no \"\n \"reduction is necessary.\"))\n\n # initially mark all elements as uncovered, i.e. as not being a prototype\n uncovered = np.asarray([np.True_] * dm.shape[0])\n\n # the first two prototypes are those elements that have the globally\n # maximal distance in the distance matrix. Mark those two elements as\n # being covered, i.e. prototypes\n distance = dm.data.max()\n res_set = list(np.unravel_index(dm.data.argmax(), dm.data.shape))\n uncovered[res_set] = np.False_\n # counts the number of already found prototypes\n num_found_prototypes = len(res_set)\n\n # repeat until enough prototypes have been selected:\n # the new prototype is the element that has maximal distance sum to all\n # non-prototype elements in the distance matrix.\n while num_found_prototypes < num_prototypes:\n max_elm_idx = (dm.data[res_set, :].sum(axis=0) * uncovered).argmax()\n uncovered[max_elm_idx] = np.False_\n num_found_prototypes += 1\n res_set.append(max_elm_idx)\n\n # return the ids of the selected prototype elements\n return [dm.ids[idx] for idx, x in enumerate(uncovered) if not x]\n","sub_path":"phylogeny/prototypeSelection.py","file_name":"prototypeSelection.py","file_ext":"py","file_size_in_byte":8354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"387039575","text":"# derived_h5.py\n#\n# 05-may-20\n# Author: F. Gent (fred.gent.ncl@gmail.com).\n#\n\"\"\" Derive auxilliary data and other diagnostics from var.h5 file and \n save to new h5 file\n \n uses:\n compute 'data' arrays of size [nz,ny,nx] as required\n store 'time' of snapshot\n compute 'masks' for example by temperature phase\n compute summary statistics 'stats' \n compute 'structure' functions as required\n\"\"\"\nimport numpy as np\nfrom scipy.interpolate import interp1d\nfrom ..math import dot, dot2, natural_sort, helmholtz_fft, cpu_optimal\nfrom ..math.derivatives import curl, div, curl2, grad\nfrom ..calc import fluid_reynolds, magnetic_reynolds\nfrom ..io import open_h5, group_h5, dataset_h5\nfrom fileinput import input\nfrom sys import stdout\nimport subprocess as sub\nfrom .. import read \nimport os\n\ndef is_vector(key):\n \"\"\"Check if the variable denoted by the label key is a vector.\n \"\"\"\n vec = False\n for tag in ('aa', 'uu', 'bb', 'jj', 'upot', 'urot', 'vort'):\n if key in tag:\n vec = True\n return vec\n\ndef der_limits(n1,n2,m1,m2,l1,l2,nghost):\n if n1 >= nghost:\n n1shift = n1 - nghost\n else:\n n1shift = n1\n if m1 >= nghost:\n m1shift = m1 - nghost\n else:\n m1shift = m1\n if l1 >= nghost:\n l1shift = l1 - nghost\n else:\n l1shift = l1\n n2shift = n2 + nghost\n m2shift = m2 + nghost\n l2shift = l2 + nghost\n return n1shift,n2shift,m1shift,m2shift,l1shift,l2shift\n\ndef under_limits(n1,m1,l1,n1shift,m1shift,l1shift,nghost):\n if n1shift == n1:\n n1r = 0\n else:\n n1r = nghost\n if m1shift == m1:\n m1r = 0\n else:\n m1r = nghost\n if l1shift == l1:\n l1r = 0\n else:\n l1r = nghost\n return n1r,m1r,l1r\n\ndef derive_data(sim_path, src, dst, magic=['pp','tt'], par=[], comm=None,\n gd=[], overwrite=False, rank=0, size=1, nghost=3,status='a',\n chunksize = 1000.0, dtype=np.float64, quiet=True, nmin=32 \n ):\n\n if comm:\n overwrite = False \n if isinstance(par, list):\n os.chdir(sim_path)\n par = read.param(quiet=True,conflicts_quiet=True)\n if isinstance(gd, list):\n os.chdir(sim_path)\n gd = read.grid(quiet=True)\n #get data dimensions\n nx, ny, nz = src['settings']['nx'][0],\\\n src['settings']['ny'][0],\\\n src['settings']['nz'][0]\n mx, my, mz = src['settings']['mx'][0],\\\n src['settings']['my'][0],\\\n src['settings']['mz'][0]\n #split data into manageable memory chunks\n dstchunksize = 8*nx*ny*nz/1024*1024\n if dstchunksize > chunksize:\n nchunks = cpu_optimal(nx,ny,nz,quiet=quiet,\n mvar=src['settings/mvar'][0],\n maux=src['settings/maux'][0],\n MBmin=chunksize,nmin=nmin,size=size)[1]\n else:\n nchunks = [1,1,1]\n print('nchunks {}'.format(nchunks)) \n # for mpi split chunks across processes\n if size > 1:\n locindx = np.array_split(np.arange(nx)+nghost,nchunks[0]) \n locindy = np.array_split(np.arange(ny)+nghost,nchunks[1]) \n locindz = np.array_split(np.arange(nz)+nghost,nchunks[2])\n indx = [locindx[np.mod(rank+int(rank/nchunks[2])\n +int(rank/nchunks[1]),nchunks[0])]]\n indy = [locindy[np.mod(rank+int(rank/nchunks[2]),nchunks[1])]]\n indz = [locindz[np.mod(rank,nchunks[2])]]\n allchunks = 1\n else:\n locindx = np.array_split(np.arange(nx)+nghost,nchunks[0]) \n locindy = np.array_split(np.arange(ny)+nghost,nchunks[1]) \n locindz = np.array_split(np.arange(nz)+nghost,nchunks[2])\n indx = np.array_split(np.arange(nx)+nghost,nchunks[0]) \n indy = np.array_split(np.arange(ny)+nghost,nchunks[1]) \n indz = np.array_split(np.arange(nz)+nghost,nchunks[2])\n allchunks = nchunks[0]*nchunks[1]*nchunks[2]\n # save time\n dataset_h5(dst, 'time', status=status, data=src['time'][()],\n comm=comm, size=size, rank=rank,\n overwrite=overwrite, dtype=dtype)\n # ensure derived variables are in a list\n if isinstance(magic, list):\n magic = magic\n else:\n magic = [magic]\n # initialise group \n group = group_h5(dst, 'data', status='a', overwrite=overwrite,\n comm=comm, rank=rank, size=size)\n for key in magic:\n if is_vector(key):\n dataset_h5(group, key, status=status, shape=[3,mz,my,mx],\n comm=comm, size=size, rank=rank,\n overwrite=overwrite, dtype=dtype)\n print('writing '+key+' shape {}'.format([3,mz,my,mx]))\n else:\n dataset_h5(group, key, status=status, shape=[mz,my,mx],\n comm=comm, size=size, rank=rank,\n overwrite=overwrite, dtype=dtype)\n print('writing '+key+' shape {}'.format([mz,my,mx]))\n for ichunk in range(allchunks):\n for iz in [indz[np.mod(ichunk,nchunks[2])]]:\n n1, n2 = iz[ 0]-nghost,\\\n iz[-1]+nghost+1\n n1out = n1+nghost\n n2out = n2-nghost\n varn1 = nghost\n varn2 = -nghost\n if iz[0] == locindz[0][0]:\n n1out = 0\n varn1 = 0\n if iz[-1] == locindz[-1][-1]:\n n2out = n2\n varn2 = n2\n for iy in [indy[np.mod(ichunk+\n int(ichunk/nchunks[2]),nchunks[1])]]:\n m1, m2 = iy[ 0]-nghost,\\\n iy[-1]+nghost+1\n m1out = m1+nghost\n m2out = m2-nghost\n varm1 = nghost\n varm2 = -nghost\n if iy[0] == locindy[0][0]:\n m1out = 0\n varm1 = 0\n if iy[-1] == locindy[-1][-1]:\n m2out = m2\n varm2 = m2\n for ix in [indx[np.mod(ichunk+int(ichunk/nchunks[2])\n +int(ichunk/nchunks[1]),nchunks[0])]]:\n l1, l2 = ix[ 0]-nghost,\\\n ix[-1]+nghost+1\n l1out = l1+nghost\n l2out = l2-nghost\n varl1 = nghost\n varl2 = -nghost\n if ix[0] == locindx[0][0]:\n l1out = 0\n varl1 = 0\n if ix[-1] == locindx[-1][-1]:\n l2out = l2\n varl2 = l2\n if not quiet:\n print('remeshing '+key+' chunk {}'.format(\n [iz,iy,ix]))\n var = calc_derived_data(src['data'], dst['data'],\n key, par, gd, l1, l2, m1, m2, n1, n2, nghost=nghost)\n #print('var shape {}'.format(var.shape))\n #if not quiet:\n # print('writing '+key+\n # ' shape {} chunk {}'.format(\n # var.shape, [iz,iy,ix]))\n if is_vector(key):\n dst['data'][key][:,n1out:n2out,\n m1out:m2out,\n l1out:l2out] = dtype(var[:,\n varn1:varn2,\n varm1:varm2,\n varl1:varl2])\n else:\n dst['data'][key][n1out:n2out,\n m1out:m2out,\n l1out:l2out] = dtype(var[\n varn1:varn2,\n varm1:varm2,\n varl1:varl2])\n#==============================================================================\ndef calc_derived_data(src, dst, key, par, gd, l1, l2, m1, m2, n1, n2,\n nghost=3):\n \"\"\" \n compute from src data and existing dst data derived data\n \"\"\"\n #==========================================================================\n def pressure(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost):\n if 'rho' in src.keys():\n rho = src['rho'][n1:n2,m1:m2,l1:l2]\n elif 'lnrho' in src.keys():\n rho = np.exp(src['lnrho'][n1:n2,m1:m2,l1:l2])\n else: \n print('no density used setting rho=1 in pressure calculation')\n rho = 1\n\n if 'ss' in src.keys():\n ss = src['ss'][n1:n2,m1:m2,l1:l2]\n var = np.exp(par.gamma*(ss + np.log(rho)))\n elif 'tt' in dst.keys():\n tt = dst['tt'][n1:n2,m1:m2,l1:l2]\n if not par.gamma == 1:\n cv = par.cp/par.gamma\n else:\n cv = 1\n var = (par.cp - cv)*tt*rho\n else:\n if 'rho' is src.keys() or 'lnrho' in src.keys():\n print('no entropy or temperature using cs^2'+\n ' in pressure calculation')\n var = rho*par.cs0**2\n else:\n print('no density or temperature,'+\n ' pressure cannot be calculated')\n return 1\n return var\n \n #==========================================================================\n def temperature(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost):\n if 'rho' in src.keys():\n rho = src['rho'][n1:n2,m1:m2,l1:l2]\n elif 'lnrho' in src.keys():\n rho = np.exp(src['lnrho'][n1:n2,m1:m2,l1:l2])\n else: \n print('no density used setting rho=1 in temperature calculation')\n rho = 1\n if 'ss' in src.keys():\n ss = src['ss'][n1:n2,m1:m2,l1:l2]\n lnrho0 = np.log(par.rho0)\n if not par.gamma == 1:\n lnTT0 = np.log(par.cs0**2/(par.cp*(par.gamma-1)))\n lnTT = lnTT0 + par.gamma/par.cp*ss +\\\n (par.gamma-1)*(np.log(rho)-lnrho0)\n else:\n lnTT0 = np.log(par.cs0**2/par.cp)\n lnTT = lnTT0 + par.gamma/par.cp*ss\n else:\n lnTT0 = np.log(par.cs0**2/(par.cp*(par.gamma-1)))\n lnTT = (par.gamma-1)*(np.log(rho)-lnrho0)+lnTT0\n return np.exp(lnTT)\n\n #======================================================================\n def Re_number(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost):\n n1shift,n2shift,m1shift,m2shift,l1shift,l2shift=der_limits(\n n1,n2,m1,m2,l1,l2,nghost)\n uu = np.array([\n src['ux'][n1shift:n2shift,m1shift:m2shift,l1shift:l2shift],\n src['uy'][n1shift:n2shift,m1shift:m2shift,l1shift:l2shift],\n src['uz'][n1shift:n2shift,m1shift:m2shift,l1shift:l2shift]\n ])\n if 'rho' in src.keys():\n lnrho = np.log(src['rho'][n1shift:n2shift,m1shift:m2shift,l1shift:l2shift])\n elif 'lnrho' in src.keys():\n lnrho = src['lnrho'][n1shift:n2shift,m1shift:m2shift,l1shift:l2shift]\n else: \n lnrho = list()\n if 'shock' in src.keys():\n shock = src['shock'][n1shift:n2shift,m1shift:m2shift,l1shift:l2shift]\n else:\n shock = list()\n var = fluid_reynolds(uu, par, gd, lnrho=lnrho, shock=shock)\n n1r,m1r,l1r = under_limits(n1,m1,l1,n1shift,m1shift,l1shift,nghost)\n return var[n1r:n2-n1+n1r,m1r:m2-m1+m1r,l1r:l2-l1+l1r]\n \n #======================================================================\n def Rm_number(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost):\n n1shift,n2shift,m1shift,m2shift,l1shift,l2shift=der_limits(\n n1,n2,m1,m2,l1,l2,nghost)\n uu = np.array([\n src['ux'][n1shift:n2shift,m1shift:m2shift,l1shift:l2shift],\n src['uy'][n1shift:n2shift,m1shift:m2shift,l1shift:l2shift],\n src['uz'][n1shift:n2shift,m1shift:m2shift,l1shift:l2shift]\n ])\n aa = np.array([\n src['ax'][n1shift:n2shift,m1shift:m2shift,l1shift:l2shift],\n src['ay'][n1shift:n2shift,m1shift:m2shift,l1shift:l2shift],\n src['az'][n1shift:n2shift,m1shift:m2shift,l1shift:l2shift]\n ])\n if 'bb' in dst.keys():\n bb = dst['bb'][:,n1shift:n2shift,m1shift:m2shift,l1shift:l2shift]\n else:\n bb = bfield(src, dst, par, gd, l1shift, l2shift, m1shift, m2shift, n1shift, n2shift, nghost)\n if 'jj' in dst.keys():\n jj = dst['jj'][:,n1shift:n2shift,m1shift:m2shift,l1shift:l2shift]\n else:\n jj = current(src, dst, par, gd, l1shift, l2shift, m1shift, m2shift, n1shift, n2shift, nghost)\n var = magnetic_reynolds(uu, par, gd, aa=aa, bb=bb, jj=jj)\n n1r,m1r,l1r = under_limits(n1,m1,l1,n1shift,m1shift,l1shift,nghost)\n return var[n1r:n2-n1+n1r,m1r:m2-m1+m1r,l1r:l2-l1+l1r]\n\n #======================================================================\n def Pm_number(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost):\n if 'Re' in dst.keys():\n Re = dst['Re'][n1:n2,m1:m2,l1:l2]\n else:\n Re = Re_number(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost)\n if 'Rm' in dst.keys():\n Rm = dst['Rm'][n1:n2,m1:m2,l1:l2]\n else:\n Rm = Rm_number(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost)\n if Re.max() > 0:\n Re[np.where(Re==0)] = Re[np.where(Re>0)].min()\n else:\n if Rm.max() > 0:\n Re[:] = Rm.min()\n else:\n Re[:] = 1\n return Rm/Re\n\n #======================================================================\n def rot_flow(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost):\n uu = np.array([\n src['ux'][n1:n2,m1:m2,l1:l2],\n src['uy'][n1:n2,m1:m2,l1:l2],\n src['uz'][n1:n2,m1:m2,l1:l2]\n ])\n var = helmholtz_fft(uu, gd, par, rot=True, pot=False)\n #print('helmholtz shape {}'.format(var.shape))\n return var\n\n #======================================================================\n def pot_flow(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost):\n uu = np.array([\n src['ux'][n1:n2,m1:m2,l1:l2],\n src['uy'][n1:n2,m1:m2,l1:l2],\n src['uz'][n1:n2,m1:m2,l1:l2]\n ])\n var = helmholtz_fft(uu, gd, par, pot=True, rot=False)\n return var\n\n #======================================================================\n def Mach_cs(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost):\n uu = np.array([\n src['ux'][n1:n2,m1:m2,l1:l2],\n src['uy'][n1:n2,m1:m2,l1:l2],\n src['uz'][n1:n2,m1:m2,l1:l2]\n ])\n if 'tt' in dst.keys():\n tt = dst['tt'][n1:n2,m1:m2,l1:l2]\n else:\n tt = temperature(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost)\n if not par.gamma == 1:\n cs2 = par.cp*(par.gamma-1)*tt\n else:\n cs2 = par.cp*tt\n print('tt min {} max {}'.format(tt.min(),tt.max())) \n var = np.sqrt(dot2(uu)/cs2)\n return var\n\n #======================================================================\n def Mach_Av(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost):\n if 'bb' in dst.keys():\n bb = dst['bb'][:,n1:n2,m1:m2,l1:l2]\n else:\n bb = bfield(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost)\n if 'rho' in src.keys():\n rho = src['rho'][n1:n2,m1:m2,l1:l2]\n elif 'lnrho' in src.keys():\n rho = np.exp(src['lnrho'][n1:n2,m1:m2,l1:l2])\n else: \n print('no density used setting rho=1 in pressure calculation')\n rho = 1\n var = np.sqrt(dot2(bb)/(par.mu0*rho))\n return var\n\n #======================================================================\n def mag_pressure(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost):\n if 'bb' in dst.keys():\n bb = dst['bb'][:,n1:n2,m1:m2,l1:l2]\n else:\n bb = bfield(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost)\n var = 0.5*dot2(bb)/par.mu0\n return var\n\n #======================================================================\n def vorticity(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost):\n n1shift,n2shift,m1shift,m2shift,l1shift,l2shift=der_limits(\n n1,n2,m1,m2,l1,l2,nghost)\n uu = np.array([\n src['ux'][n1shift:n2shift,m1shift:m2shift,l1shift:l2shift],\n src['uy'][n1shift:n2shift,m1shift:m2shift,l1shift:l2shift],\n src['uz'][n1shift:n2shift,m1shift:m2shift,l1shift:l2shift]\n ])\n var = curl(uu, gd.dx, gd.dy, gd.dz)\n n1r,m1r,l1r = under_limits(n1,m1,l1,n1shift,m1shift,l1shift,nghost)\n return var[:,n1r:n2-n1+n1r,m1r:m2-m1+m1r,l1r:l2-l1+l1r]\n\n #======================================================================\n def bfield(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost):\n n1shift,n2shift,m1shift,m2shift,l1shift,l2shift=der_limits(\n n1,n2,m1,m2,l1,l2,nghost)\n aa = np.array([\n src['ax'][n1shift:n2shift,m1shift:m2shift,l1shift:l2shift],\n src['ay'][n1shift:n2shift,m1shift:m2shift,l1shift:l2shift],\n src['az'][n1shift:n2shift,m1shift:m2shift,l1shift:l2shift]\n ])\n var = curl(aa, gd.dx, gd.dy, gd.dz)\n n1r,m1r,l1r = under_limits(n1,m1,l1,n1shift,m1shift,l1shift,nghost)\n return var[:,n1r:n2-n1+n1r,m1r:m2-m1+m1r,l1r:l2-l1+l1r]\n\n #======================================================================\n def current(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost):\n n1shift,n2shift,m1shift,m2shift,l1shift,l2shift=der_limits(\n n1,n2,m1,m2,l1,l2,nghost)\n aa = np.array([\n src['ax'][n1shift:n2shift,m1shift:m2shift,l1shift:l2shift],\n src['ay'][n1shift:n2shift,m1shift:m2shift,l1shift:l2shift],\n src['az'][n1shift:n2shift,m1shift:m2shift,l1shift:l2shift]\n ])\n var = curl2(aa, gd.dx, gd.dy, gd.dz)\n n1r,m1r,l1r = under_limits(n1,m1,l1,n1shift,m1shift,l1shift,nghost)\n return var[:,n1r:n2-n1+n1r,m1r:m2-m1+m1r,l1r:l2-l1+l1r]\n\n #======================================================================\n def kin_helicity(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost):\n uu = np.array([\n src['ux'][n1:n2,m1:m2,l1:l2],\n src['uy'][n1:n2,m1:m2,l1:l2],\n src['uz'][n1:n2,m1:m2,l1:l2]\n ])\n if 'vort' in dst.keys():\n oo = dst['vort'][:,n1:n2,m1:m2,l1:l2]\n else:\n oo = vorticity(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost)\n var = dot(uu, oo)\n return var\n\n #======================================================================\n def mag_helicity(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost):\n aa = np.array([\n src['ax'][n1:n2,m1:m2,l1:l2],\n src['ay'][n1:n2,m1:m2,l1:l2],\n src['az'][n1:n2,m1:m2,l1:l2]\n ])\n if 'bb' in dst.keys():\n bb = dst['bb'][:,n1:n2,m1:m2,l1:l2]\n else:\n bb = bfield(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost)\n var = dot(aa, bb)\n return var\n\n #==========================================================================\n def calc_derived_item(key):\n case = {\n 'urot': rot_flow( src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost),\n 'upot': pot_flow( src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost),\n 'vort': vorticity( src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost),\n 'ou' : kin_helicity(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost),\n 'tt' : temperature( src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost),\n 'pp' : pressure( src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost),\n 'Re' : Re_number( src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost),\n 'Ms' : Mach_cs( src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost),\n 'bb' : bfield( src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost),\n 'pb' : mag_pressure(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost),\n 'ab' : mag_helicity(src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost),\n 'jj' : current( src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost),\n 'Ma' : Mach_Av( src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost),\n 'Rm' : Rm_number( src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost),\n 'Pm' : Pm_number( src, dst, par, gd, l1, l2, m1, m2, n1, n2, nghost),\n }\n func = case.get(key, lambda: 'No function for '+key)\n return func\n #======================================================================\n return calc_derived_item(key)\n\n\n# print('end at {} after {} seconds'.format(\n# time.ctime(end_time),end_time-start_time))\n# remains to copy other files and edit param files\n","sub_path":"python/pencil/ism_dyn/derived_h5.py","file_name":"derived_h5.py","file_ext":"py","file_size_in_byte":22292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"120105399","text":"\"\"\" moduuli, joka sisältää Gamemenu luokan\n\"\"\"\nimport pygame\nfrom gamemodules.game import Game\nfrom gamemodules.field import Field\n\nclass GameMenu:\n \"\"\" Luokka, joka vastaa pelivalikosta.\n Attributes:\n running: Boolean-arvo, joka kuvaa onko pelivalikko käynnissä.\n screen_height: Lukuarvo, joka kuvaa näytön korkeutta pikseleinä.\n screen_width: Lukuarvo, joka kuvaa näytön leveyttä pikseleinä.\n screen: kuvaa pygamen kuvaruutua.\n easy_button: pygamen rect-olio, joka kuvaa valikon easy näppäintä.\n easy: Tuple, jonka arvot ovat easy tasoisen pelin korkeus, leveys ja\n miinojen määrä.\n mediumhard_button: pygamen rect-olio, joka kuvaa valikon mediumhard näppäintä.\n mediumhard: Tuple, jonka arvot ovat mediumhard tasoisen pelin korkeus,\n leveys ja miinojen määrä.\n expert_button: pygamen rect-olio, joka kuvaa valikon expert näppäintä.\n expert: Tuple, jonka arvot ovat expert tasoisen pelin korkeus, leveys,\n ja miinojen määrä.\n back_button: pygamen rect-olio, joka kuvaa valikon back näppäintä.\n button_color: Tuple, joka kuvaa värikoodina valikon näppäimien väriä.\n background_color: Tuple, joka kuvaa värikoodina valikon taustan väriä.\n cell_size: Lukuarvo, joka kuvaa yksittäisen miinaharavakentän ruudun\n kokoa pikseleinä.\n font: pygame fontti valikon suuremmille teksteille.\n font_small: pygame fontti valikon pienemmille teksteille.\n \"\"\"\n def __init__(self):\n \"\"\" Luokan kostruktori.\n \"\"\"\n self.running = False\n self.screen_height = 600\n self.screen_width = 500\n self.screen = pygame.display.set_mode((self.screen_width, self.screen_height))\n self.easy_button = pygame.Rect(50, 125, 400, 75)\n self.easy = (9, 9, 10)\n self.mediumhard_button = pygame.Rect(50, 250, 400, 75)\n self.mediumhard = (16, 16, 40)\n self.expert_button = pygame.Rect(50, 375, 400, 75)\n self.expert = (16, 30, 99)\n self.back_button = pygame.Rect(75, 500, 350, 50)\n self.button_color = (140, 140, 150)\n self.background_color = (50, 50, 50)\n self.cell_size = 50\n self.font = None\n self.font_small = None\n def run_menu(self):\n \"\"\" Käynnistää pelivalikon\n \"\"\"\n pygame.init()\n self.font = pygame.font.SysFont(\"Arial\", 50, 1)\n self.font_small = pygame.font.SysFont(\"Arial\", 30, 1)\n self.running = True\n self.menu_loop()\n def left_click(self, position):\n \"\"\" Käsittelee vasemman hiiren näppäimen painalluksesta seuraavat toimenpiteet.\n Args:\n position: Tuple, joka kuvaa koordinaatteja pisteeseen, jossa hiiri oli\n klikkaus hetkellä\n \"\"\"\n if self.easy_button.collidepoint(position):\n self.setup_game(self.easy, \"easy\")\n self.reset_screen_size()\n self.reset_caption()\n if self.mediumhard_button.collidepoint(position):\n self.setup_game(self.mediumhard, \"mediumhard\")\n self.reset_screen_size()\n self.reset_caption()\n if self.expert_button.collidepoint(position):\n self.setup_game(self.expert, \"expert\")\n self.reset_screen_size()\n self.reset_caption()\n if self.back_button.collidepoint(position):\n self.running = False\n def setup_game(self, difficulty, difficulty_text):\n \"\"\" Käynnistää parametreina annetun vaikeustason pelin.\n Args:\n difficulty: tuple, joka kertoo vaikeustason miinakentän\n korkeuden, leveyden ja miinojen määrän.\n difficulty_text: Merkkijonoarvo, joka kertoo vaikeustason\n nimen.\n \"\"\"\n field = Field(difficulty[0], difficulty[1], difficulty[2])\n game = Game(field, self.cell_size, difficulty_text)\n game.run_game()\n def draw_button(self, button):\n \"\"\" Piirtää näytölle parametrinä annetun näppäimen\n Args:\n button: rect-olio, joka kuvastaa näppäintä\n \"\"\"\n pygame.draw.rect(self.screen, self.button_color, button)\n def draw_text(self, text, font, x_value, y_value):\n \"\"\" Piirtää näytölle parametrien mukaisen tekstin.\n Args:\n text: Merkkijonoarvo, joka kuvaa piirrettävää tekstin\n sisältöä\n font: käytettävä fontti\n x_value: Lukuarvo, joka kuvastaa tekstin paikan\n x-koordinaattia\n y_value: Lukuarvo, joka kuvastaa tekstin paikan\n y-koordinaattia\n \"\"\"\n button_text = font.render(text, True, (0, 0, 0))\n self.screen.blit(button_text, (x_value, y_value))\n def draw_instruction(self, text, x_value, y_value):\n \"\"\" Piirtää näytölle ohjeistuksen parametrien mukaisesti.\n Args:\n text: Merkkijonoarvo, joka kuvastaa ohjeistuksen sisältöä.\n x_value: Lukuarvo, joka kuvastaa ohjeistuksen paikan\n x-koordinaattia\n y_value: Lukuarvo, joka kuvastaa ohjeistuksen paikan\n y-koordinaattia\n \"\"\"\n instruction = self.font_small.render(text, True, (220, 220, 220))\n self.screen.blit(instruction, (x_value, y_value))\n def check_events(self):\n \"\"\" Tarkastaa kaikki olennaiset tapahtumat\n \"\"\"\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit()\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n position = pygame.mouse.get_pos()\n self.left_click(position)\n def draw_screen(self):\n \"\"\" Piirtää pelin näytön\n \"\"\"\n self.screen.fill(self.background_color)\n self.draw_button(self.easy_button)\n self.draw_text(\"EASY\", self.font, self.easy_button.left+138, self.easy_button.top+11)\n self.draw_button(self.mediumhard_button)\n x_value = self.mediumhard_button.left+28\n y_value = self.mediumhard_button.top+11\n self.draw_text(\"MEDIUMHARD\", self.font, x_value, y_value)\n self.draw_button(self.expert_button)\n self.draw_text(\"EXPERT\", self.font, self.expert_button.left+108, self.expert_button.top+11)\n self.draw_button(self.back_button)\n self.draw_text(\"BACK\", self.font_small, self.back_button.left+135, self.back_button.top+9)\n self.draw_instruction(\"CHOOSE DIFFICULTY :\", 100, 50)\n pygame.display.flip()\n def menu_loop(self):\n \"\"\"Silmukka, joka aina valikon käynnissä ollessa tarkastaa\n vuorotellen tapahtuneet tapahtumat ja piirtää näytön\n \"\"\"\n while self.running:\n self.check_events()\n self.draw_screen()\n def reset_screen_size(self):\n \"\"\" Uudelleenasettaa ruudun koon halutuksi\n \"\"\"\n self.screen_height = 600\n self.screen_width = 500\n self.screen = pygame.display.set_mode((self.screen_width, self.screen_height))\n def reset_caption(self):\n \"\"\" Uudelleenasettaa ruudun otsikon halutuksi\n \"\"\"\n pygame.display.set_caption(\"MINESWEEPER\")\n ","sub_path":"src/menumodules/gamemenu.py","file_name":"gamemenu.py","file_ext":"py","file_size_in_byte":7274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"123159922","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"LHC\")\nimport FWCore.ParameterSet.VarParsing as VarParsing\noptions = VarParsing.VarParsing ('analysis') \noptions.parseArguments()\n\nif len(options.inputFiles)<1:\n raise Exception(\"Please insert an inputFile. Eg. cmsRun RawToRootConverter.py inputFiles=/store/error_stream/run356997/run356997_ls0142_index000229_fu-c2b03-37-01_pid3478586.raw outputFile=outputFile.root\")\n\nif len(options.inputFiles)>1:\n raise Exception(\"Please insert only one inputFile\")\n\nfile_ = options.inputFiles[0]\nif \"run\" in file_ and \"_ls\" in file_:\n run = int(file_.split(\"run\")[-1].split(\"_ls\")[0])\nelse:\n raise Exception(\"%s has not the format [...]runNNNNNN_ls[...]\")\n\nprocess.source = cms.Source(\"ErrorStreamSource\",\n fileNames = cms.untracked.vstring(options.inputFiles),\n firstRun = cms.untracked.uint32(run),\n firstLuminosityBlockForEachRun = cms.untracked.VLuminosityBlockID([])\n )\n\nfrom EventFilter.RawDataCollector.rawDataCollectorByLabel_cfi import rawDataCollector\nprocess.rawDataCollector = rawDataCollector.clone(\n verbose = cms.untracked.int32(0),\n RawCollectionList = cms.VInputTag( cms.InputTag('source') )\n )\n\nprocess.output = cms.OutputModule( \"PoolOutputModule\",\n fileName = cms.untracked.string( options.outputFile ),\n outputCommands = cms.untracked.vstring(\n'drop *',\n'keep *_rawDataCollector_*_*'\n )\n)\n\nprocess.raw = cms.Path( process.rawDataCollector )\nprocess.end = cms.EndPath( process.output )\n\nprocess.maxEvents = cms.untracked.PSet(\n input = cms.untracked.int32( -1 )\n)\n","sub_path":"hltpro/RawToRootConverter.py","file_name":"RawToRootConverter.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"8627047","text":"import math\nfrom collections import defaultdict\n\nimport networkx as nx\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom sklearn.metrics import roc_auc_score\n\nfrom torch_geometric.nn.conv.gcn_conv import GCNConv\nfrom torch_geometric.nn.conv.gat_conv import GATConv\nfrom torch_geometric.nn.conv.rgcn_conv import RGCNConv\n\n\ndef kaiming_reset_parameters(linear_module):\n nn.init.kaiming_uniform_(linear_module.weight, a=math.sqrt(5))\n if linear_module.bias is not None:\n fan_in, _ = nn.init._calculate_fan_in_and_fan_out(linear_module.weight)\n bound = 1 / math.sqrt(fan_in)\n nn.init.uniform_(linear_module.bias, -bound, bound)\n\nclass GraphConvolution(nn.Module):\n \"\"\"\n Simple GCN layer, similar to https://arxiv.org/abs/1609.02907\n \"\"\"\n\n def __init__(self, in_features, out_features, bias=True):\n super(GraphConvolution, self).__init__()\n self.in_features = in_features\n self.out_features = out_features\n self.weight = nn.Parameter(torch.FloatTensor(in_features, out_features))\n if bias:\n self.bias = nn.Parameter(torch.FloatTensor(out_features))\n else:\n self.register_parameter('bias', None)\n self.reset_parameters()\n\n def reset_parameters(self):\n # stdv = 1. / math.sqrt(self.weight.size(1))\n # self.weight.data.uniform_(-stdv, stdv)\n # if self.bias is not None:\n # self.bias.data.uniform_(-stdv, stdv)\n\n kaiming_reset_parameters(self)\n\n def forward(self, input, adj):\n support = torch.mm(input, self.weight)\n output = torch.spmm(adj, support)\n if self.bias is not None:\n return output + self.bias\n else:\n return output\n\n def __repr__(self):\n return self.__class__.__name__ + ' (' \\\n + str(self.in_features) + ' -> ' \\\n + str(self.out_features) + ')'\n\n\nclass GCN(nn.Module):\n def __init__(self, ninp, nhid, dropout=0.5):\n super(GCN, self).__init__()\n\n # self.gc1 = GraphConvolution(ninp, nhid)\n self.gc2 = GraphConvolution(ninp, nhid)\n self.dropout = dropout\n\n def forward(self, x, adj):\n \"\"\"x: shape (|V|, |D|); adj: shape(|V|, |V|)\"\"\"\n # x = F.relu(self.gc1(x, adj))\n # x = F.dropout(x, self.dropout, training=self.training)\n x = self.gc2(x, adj)\n return x\n # return F.log_softmax(x, dim=1)\n\nclass GraphAttentionLayer(nn.Module):\n \"\"\"\n Simple GAT layer, similar to https://arxiv.org/abs/1710.10903\n \"\"\"\n\n def __init__(self, in_features, out_features, dropout, alpha, concat=True):\n super(GraphAttentionLayer, self).__init__()\n self.dropout = dropout\n self.in_features = in_features\n self.out_features = out_features\n self.alpha = alpha\n self.concat = concat\n\n self.W = nn.Parameter(torch.zeros(size=(in_features, out_features)))\n nn.init.xavier_uniform_(self.W.data, gain=1.414)\n self.a = nn.Parameter(torch.zeros(size=(2*out_features, 1)))\n nn.init.xavier_uniform_(self.a.data, gain=1.414)\n\n self.leakyrelu = nn.LeakyReLU(self.alpha)\n\n def forward(self, input, adj):\n h = torch.mm(input, self.W)\n N = h.size()[0]\n\n a_input = torch.cat([h.repeat(1, N).view(N * N, -1), h.repeat(N, 1)], dim=1).view(N, -1, 2 * self.out_features)\n e = self.leakyrelu(torch.matmul(a_input, self.a).squeeze(2))\n\n zero_vec = -9e15*torch.ones_like(e)\n attention = torch.where(adj > 0, e, zero_vec)\n attention = F.softmax(attention, dim=1)\n attention = F.dropout(attention, self.dropout, training=self.training)\n h_prime = torch.matmul(attention, h)\n\n if self.concat:\n return F.elu(h_prime)\n else:\n return h_prime\n\n def __repr__(self):\n return self.__class__.__name__ + ' (' + str(self.in_features) + ' -> ' + str(self.out_features) + ')'\n\n\nclass SelfAttentionLayer(nn.Module):\n def __init__(self, dim, da, alpha=0.2, dropout=0.5):\n super(SelfAttentionLayer, self).__init__()\n self.dim = dim\n self.da = da\n self.alpha = alpha\n self.dropout = dropout\n # self.a = nn.Parameter(torch.zeros(size=(2*self.dim, 1)))\n # nn.init.xavier_uniform_(self.a.data, gain=1.414)\n self.a = nn.Parameter(torch.zeros(size=(self.dim, self.da)))\n self.b = nn.Parameter(torch.zeros(size=(self.da, 1)))\n nn.init.xavier_uniform_(self.a.data, gain=1.414)\n nn.init.xavier_uniform_(self.b.data, gain=1.414)\n # self.leakyrelu = nn.LeakyReLU(self.alpha)\n\n def forward(self, h):\n N = h.shape[0]\n assert self.dim == h.shape[1]\n # a_input = torch.cat([h.repeat(1, N).view(N * N, -1), h.repeat(N, 1)], dim=1).view(N, -1, 2 * self.dim)\n # e = self.leakyrelu(torch.matmul(a_input, self.a).squeeze(2))\n # attention = F.softmax(e, dim=1)\n e = torch.matmul(torch.tanh(torch.matmul(h, self.a)), self.b).squeeze(dim=1)\n attention = F.softmax(e)\n # attention = F.dropout(attention, self.dropout, training=self.training)\n return torch.matmul(attention, h)\n\nclass SelfAttentionLayer2(nn.Module):\n def __init__(self, dim, da):\n super(SelfAttentionLayer2, self).__init__()\n self.dim = dim\n self.Wq = nn.Parameter(torch.zeros(self.dim, self.dim))\n self.Wk = nn.Parameter(torch.zeros(self.dim, self.dim))\n nn.init.xavier_uniform_(self.Wq.data, gain=1.414)\n nn.init.xavier_uniform_(self.Wk.data, gain=1.414)\n # self.leakyrelu = nn.LeakyReLU(self.alpha)\n\n def forward(self, h):\n N = h.shape[0]\n assert self.dim == h.shape[1]\n q = torch.matmul(h, self.Wq)\n k = torch.matmul(h, self.Wk)\n e = torch.matmul(q, k.t()) / math.sqrt(self.dim)\n attention = F.softmax(e, dim=1)\n attention = attention.mean(dim=0)\n x = torch.matmul(attention, h)\n return x\n\nclass BiAttention(nn.Module):\n def __init__(self, input_size, dropout):\n super().__init__()\n self.dropout = nn.Dropout(p=dropout)\n self.input_linear = nn.Linear(input_size, 1, bias=False)\n self.memory_linear = nn.Linear(input_size, 1, bias=False)\n\n self.dot_scale = nn.Parameter(torch.Tensor(input_size).uniform_(1.0 / (input_size ** 0.5)))\n\n def forward(self, input, memory, mask=None):\n bsz, input_len, memory_len = input.size(0), input.size(1), memory.size(1)\n\n input = self.dropout(input)\n memory = self.dropout(memory)\n\n input_dot = self.input_linear(input)\n memory_dot = self.memory_linear(memory).view(bsz, 1, memory_len)\n cross_dot = torch.bmm(input * self.dot_scale, memory.permute(0, 2, 1).contiguous())\n att = input_dot + memory_dot + cross_dot\n if mask is not None:\n att = att - 1e30 * (1 - mask[:,None])\n\n weight_one = F.softmax(att, dim=-1)\n output_one = torch.bmm(weight_one, memory)\n weight_two = F.softmax(att.max(dim=-1)[0], dim=-1).view(bsz, 1, input_len)\n output_two = torch.bmm(weight_two, input)\n return torch.cat([input, output_one, input*output_one, output_two*output_one], dim=-1)\n\nclass GAT(nn.Module):\n def __init__(self, nfeat, nhid, nclass, dropout, alpha, nheads):\n \"\"\"Dense version of GAT.\"\"\"\n super(GAT, self).__init__()\n self.dropout = dropout\n\n self.attentions = [GraphAttentionLayer(nfeat, nhid, dropout=dropout, alpha=alpha, concat=True) for _ in range(nheads)]\n for i, attention in enumerate(self.attentions):\n self.add_module('attention_{}'.format(i), attention)\n\n self.out_att = GraphAttentionLayer(nhid * nheads, nclass, dropout=dropout, alpha=alpha, concat=False)\n\n def forward(self, x, adj):\n x = F.dropout(x, self.dropout, training=self.training)\n x = torch.cat([att(x, adj) for att in self.attentions], dim=1)\n x = F.dropout(x, self.dropout, training=self.training)\n x = F.elu(self.out_att(x, adj))\n return F.log_softmax(x, dim=1)\n\n\nclass SpecialSpmmFunction(torch.autograd.Function):\n \"\"\"Special function for only sparse region backpropataion layer.\"\"\"\n @staticmethod\n def forward(ctx, indices, values, shape, b):\n assert indices.requires_grad == False\n a = torch.sparse_coo_tensor(indices, values, shape)\n ctx.save_for_backward(a, b)\n ctx.N = shape[0]\n return torch.matmul(a, b)\n\n @staticmethod\n def backward(ctx, grad_output):\n a, b = ctx.saved_tensors\n grad_values = grad_b = None\n if ctx.needs_input_grad[1]:\n grad_a_dense = grad_output.matmul(b.t())\n edge_idx = a._indices()[0, :] * ctx.N + a._indices()[1, :]\n grad_values = grad_a_dense.view(-1)[edge_idx]\n if ctx.needs_input_grad[3]:\n grad_b = a.t().matmul(grad_output)\n return None, grad_values, None, grad_b\n\n\nclass SpecialSpmm(nn.Module):\n def forward(self, indices, values, shape, b):\n return SpecialSpmmFunction.apply(indices, values, shape, b)\n\n\nclass SpGraphAttentionLayer(nn.Module):\n \"\"\"\n Sparse version GAT layer, similar to https://arxiv.org/abs/1710.10903\n \"\"\"\n\n def __init__(self, in_features, out_features, dropout, alpha, concat=True):\n super(SpGraphAttentionLayer, self).__init__()\n self.in_features = in_features\n self.out_features = out_features\n self.alpha = alpha\n self.concat = concat\n\n self.W = nn.Parameter(torch.zeros(size=(in_features, out_features)))\n nn.init.xavier_normal_(self.W.data, gain=1.414)\n\n # self.a = nn.Parameter(torch.zeros(size=(1, 2*out_features)))\n self.a = nn.Parameter(torch.zeros(size=(1, out_features)))\n nn.init.xavier_normal_(self.a.data, gain=1.414)\n\n # self.dropout = nn.Dropout(dropout)\n self.leakyrelu = nn.LeakyReLU(self.alpha)\n self.special_spmm = SpecialSpmm()\n\n def forward(self, input, adj):\n N = input.size()[0]\n # edge = adj.nonzero().t()\n edge = adj._indices()\n\n h = torch.mm(input, self.W)\n # h: N x out\n assert not torch.isnan(h).any()\n\n # Self-attention on the nodes - Shared attention mechanism\n # edge_h = torch.cat((h[edge[0, :], :], h[edge[1, :], :]), dim=1).t()\n edge_h = h[edge[1, :], :].t()\n # edge: 2*D x E\n\n edge_e = torch.exp(-self.leakyrelu(self.a.mm(edge_h).squeeze()))\n assert not torch.isnan(edge_e).any()\n # edge_e: E\n\n e_rowsum = self.special_spmm(edge, edge_e, torch.Size([N, N]), torch.ones(size=(N,1)).cuda())\n # e_rowsum: N x 1\n\n # edge_e = self.dropout(edge_e)\n # edge_e: E\n\n h_prime = self.special_spmm(edge, edge_e, torch.Size([N, N]), h)\n assert not torch.isnan(h_prime).any()\n # h_prime: N x out\n\n h_prime = h_prime.div(e_rowsum)\n # h_prime: N x out\n assert not torch.isnan(h_prime).any()\n\n if self.concat:\n # if this layer is not last layer,\n return F.elu(h_prime)\n else:\n # if this layer is last layer,\n return h_prime\n\n def __repr__(self):\n return self.__class__.__name__ + ' (' + str(self.in_features) + ' -> ' + str(self.out_features) + ')'\n\n\nclass SpGAT(nn.Module):\n def __init__(self, nfeat, nhid, nclass, dropout, alpha, nheads):\n \"\"\"Sparse version of GAT.\"\"\"\n super(SpGAT, self).__init__()\n self.dropout = dropout\n\n # self.attentions = [SpGraphAttentionLayer(nfeat,\n # nhid,\n # dropout=dropout,\n # alpha=alpha,\n # concat=True) for _ in range(nheads)]\n # for i, attention in enumerate(self.attentions):\n # self.add_module('attention_{}'.format(i), attention)\n\n # self.out_att = SpGraphAttentionLayer(nhid * nheads,\n # nclass,\n # dropout=dropout,\n # alpha=alpha,\n # concat=False)\n self.out_att = SpGraphAttentionLayer(nhid,\n nclass,\n dropout=dropout,\n alpha=alpha,\n concat=False)\n\n def forward(self, x, adj):\n # x = F.dropout(x, self.dropout, training=self.training)\n # x = torch.cat([att(x, adj) for att in self.attentions], dim=1)\n # x = F.dropout(x, self.dropout, training=self.training)\n # x = F.elu(self.out_att(x, adj))\n x = self.out_att(x, adj)\n return x\n # return F.log_softmax(x, dim=1)\n\n\ndef _add_neighbors(kg, g, seed_set, hop):\n tails_of_last_hop = seed_set\n for h in range(hop):\n next_tails_of_last_hop = []\n for entity in tails_of_last_hop:\n if entity not in kg:\n continue\n for tail_and_relation in kg[entity]:\n g.add_edge(entity, tail_and_relation[1])\n if entity != tail_and_relation[1]:\n next_tails_of_last_hop.append(tail_and_relation[1])\n tails_of_last_hop = next_tails_of_last_hop\n\n# http://dbpedia.org/ontology/director\nEDGE_TYPES = [58, 172]\ndef _edge_list(kg, n_entity, hop):\n edge_list = []\n for h in range(hop):\n for entity in range(n_entity):\n # add self loop\n # edge_list.append((entity, entity))\n # self_loop id = 185\n edge_list.append((entity, entity, 185))\n if entity not in kg:\n continue\n for tail_and_relation in kg[entity]:\n if entity != tail_and_relation[1] and tail_and_relation[0] != 185 :# and tail_and_relation[0] in EDGE_TYPES:\n edge_list.append((entity, tail_and_relation[1], tail_and_relation[0]))\n edge_list.append((tail_and_relation[1], entity, tail_and_relation[0]))\n\n relation_cnt = defaultdict(int)\n relation_idx = {}\n for h, t, r in edge_list:\n relation_cnt[r] += 1\n for h, t, r in edge_list:\n if relation_cnt[r] > 1000 and r not in relation_idx:\n relation_idx[r] = len(relation_idx)\n\n return [(h, t, relation_idx[r]) for h, t, r in edge_list if relation_cnt[r] > 1000], len(relation_idx)\n\nclass KBRD(nn.Module):\n def __init__(\n self,\n n_entity,\n n_relation,\n dim,\n n_hop,\n kge_weight,\n l2_weight,\n n_memory,\n item_update_mode,\n using_all_hops,\n kg,\n entity_kg_emb,\n entity_text_emb,\n num_bases\n ):\n super(KBRD, self).__init__()\n\n self.n_entity = n_entity\n self.n_relation = n_relation\n self.dim = dim\n self.n_hop = n_hop\n self.kge_weight = kge_weight\n self.l2_weight = l2_weight\n self.n_memory = n_memory\n self.item_update_mode = item_update_mode\n self.using_all_hops = using_all_hops\n\n self.entity_emb = nn.Embedding(self.n_entity, self.dim)\n # self.entity_kg_emb = nn.Embedding(self.n_entity, self.dim)\n self.relation_emb = nn.Embedding(self.n_relation, self.dim)\n # nn.init.uniform_(self.entity_emb.weight.data)\n nn.init.kaiming_uniform_(self.entity_emb.weight.data)\n # nn.init.xavier_uniform_(self.entity_kg_emb.weight.data)\n # nn.init.xavier_uniform_(self.relation_emb.weight.data)\n\n # self.entity_text_emb = entity_text_emb.cuda()\n\n self.criterion = nn.CrossEntropyLoss()\n self.kge_criterion = nn.Softplus()\n\n # self.gcn = GCN(self.dim, self.dim)\n # self.gcn = GCN(self.entity_text_emb.shape[1], self.dim)\n # self.transform = nn.Sequential(\n # nn.Linear(self.entity_text_emb.shape[1], 128),\n # # nn.ReLU(),\n # # nn.Linear(32, 32),\n # nn.ReLU(),\n # nn.Linear(128, self.dim),\n # )\n # self.gat = SpGAT(self.dim, self.dim, self.dim, dropout=0., alpha=0.2, nheads=4)\n # self.gcn = GCNConv(self.dim, self.dim)\n # self.gat = GATConv(self.dim, self.dim, dropout=0.1)\n\n self.self_attn = SelfAttentionLayer(self.dim, self.dim)\n # self.self_attn = SelfAttentionLayer2(self.dim, self.dim)\n # self.bi_attn = BiAttention(self.dim, dropout=0)\n self.output = nn.Linear(self.dim, self.n_entity)\n # kaiming_reset_parameters(self.output)\n # stdv = 1. / math.sqrt(self.output.weight.size(1))\n # nn.init.xavier_normal_(self.output.weight.data, gain=1.414)\n # if self.output.bias is not None:\n # self.output.bias.data.uniform_(-stdv, stdv)\n\n self.kg = kg\n # triples = self._get_triples(kg)\n # np.random.shuffle(triples)\n # self.train_triples = triples[:int(len(triples) * 0.95)]\n # self.valid_triples = triples[int(len(triples) * 0.95):]\n # self.train_idx = 0\n # self.valid_idx = 0\n # KG emb as initialization\n # self.entity_emb.weight.data[entity_kg_emb != 0] = entity_kg_emb[entity_kg_emb != 0]\n # self.entity_emb.weight.requires_grad_(False)\n # self.entity_kg_emb.weight.data[entity_kg_emb != 0] = entity_kg_emb[entity_kg_emb != 0]\n # self.entity_kg_emb.weight.requires_grad_(False)\n # self.transform = nn.Sequential(\n # nn.Linear(self.dim, self.dim),\n # nn.ReLU(),\n # nn.Linear(self.dim, self.dim),\n # )\n\n edge_list, self.n_relation = _edge_list(self.kg, self.n_entity, hop=2)\n self.rgcn = RGCNConv(self.n_entity, self.dim, self.n_relation, num_bases=num_bases)\n edge_list = list(set(edge_list))\n print(len(edge_list), self.n_relation)\n edge_list_tensor = torch.LongTensor(edge_list).cuda()\n # self.adj = torch.sparse.FloatTensor(edge_list_tensor[:, :2].t(), torch.ones(len(edge_list))).cuda()\n # self.edge_idx = self.adj._indices()\n self.edge_idx = edge_list_tensor[:, :2].t()\n self.edge_type = edge_list_tensor[:, 2]\n\n def _get_triples(self, kg):\n triples = []\n for entity in kg:\n for relation, tail in kg[entity]:\n if entity != tail:\n triples.append([entity, relation, tail])\n # triples.append([tail, self.n_relation + relation, entity])\n return triples\n\n def forward(\n self,\n seed_sets: list,\n labels: torch.LongTensor,\n ):\n # [batch size, dim]\n u_emb, nodes_features = self.user_representation(seed_sets)\n # scores = self.output(u_emb)\n # scores = F.linear(u_emb, self.entity_emb.weight, self.output.bias)\n scores = F.linear(u_emb, nodes_features, self.output.bias)\n # scores = F.linear(u_emb, torch.cat([self.transform(self.entity_text_emb), self.entity_emb.weight], dim=1), self.output.bias)\n\n base_loss = self.criterion(scores, labels)\n # base_loss = torch.Tensor([0])\n\n # kge_loss, l2_loss = self.compute_kge_loss()\n kge_loss = torch.Tensor([0])\n l2_loss = torch.Tensor([0])\n\n loss = base_loss# + kge_loss + l2_loss\n\n return dict(scores=scores.detach(), base_loss=base_loss, kge_loss=kge_loss, loss=loss, l2_loss=l2_loss)\n\n def _calc(self, h_re, h_im, r_re, r_im, t_re, t_im):\n return -torch.sum(\n h_re * r_re * t_re + h_im * r_re * t_im\n + h_re * r_im * t_im - h_im * r_im * t_re,\n -1\n )\n\n def compute_kge_loss(self):\n bs = 4096\n if self.training:\n triples = self.train_triples[self.train_idx:self.train_idx+bs]\n self.train_idx += bs\n if self.train_idx >= len(self.train_triples):\n np.random.shuffle(self.train_triples)\n self.train_idx = 0\n else:\n triples = self.valid_triples[self.valid_idx:self.valid_idx+bs]\n self.valid_idx += bs\n if self.valid_idx >= len(self.valid_triples):\n np.random.shuffle(self.valid_triples)\n self.valid_idx = 0\n triples_tensor = torch.LongTensor(triples).cuda()\n batch_h = triples_tensor[:, 0]\n batch_r = triples_tensor[:, 1]\n batch_t = triples_tensor[:, 2]\n # negative samples\n neg_batch_h = batch_h.clone()\n neg_batch_r = batch_r.clone()\n neg_batch_t = batch_t.clone()\n for i in range(batch_h.shape[0]):\n if np.random.random() < 0.5:\n neg_batch_h[i] = np.random.choice(self.n_entity)\n else:\n neg_batch_t[i] = np.random.choice(self.n_entity)\n ys = torch.cat([torch.ones(batch_h.shape[0]), -torch.ones(batch_h.shape[0])]).cuda()\n batch_h = torch.cat([batch_h, neg_batch_h])\n batch_r = torch.cat([batch_r, neg_batch_r])\n batch_t = torch.cat([batch_t, neg_batch_t])\n kge_loss, l2_loss = self._kge_loss(batch_h, batch_r, batch_t, ys)\n return kge_loss, l2_loss\n\n def _kge_loss(self, batch_h, batch_r, batch_t, ys):\n h_re, h_im = torch.chunk(self.entity_emb(batch_h), 2, dim=1)\n r_re, r_im = torch.chunk(self.relation_emb(batch_r), 2, dim=1)\n t_re, t_im = torch.chunk(self.entity_emb(batch_t), 2, dim=1)\n score = self._calc(h_re, h_im, r_re, r_im, t_re, t_im)\n regul = (\n torch.mean(h_re ** 2)\n + torch.mean(h_im ** 2)\n + torch.mean(r_re ** 2)\n + torch.mean(r_im ** 2)\n + torch.mean(t_re ** 2)\n + torch.mean(t_im ** 2)\n )\n lmbda = 0.0\n kge_loss = torch.mean(self.kge_criterion(score * ys))\n l2_loss = lmbda * regul\n return kge_loss, l2_loss\n\n def user_representation(self, seed_sets):\n # find subgraph for this batch\n # g = nx.Graph()\n # for seed_set in seed_sets:\n # for seed in seed_set:\n # g.add_node(seed)\n # _add_neighbors(self.kg, g, seed_set, hop=2)\n # add self-loops\n # for node in g.nodes:\n # g.add_edge(node, node)\n\n # create temporary nodes for user representation readout\n # n_readout_nodes = 0\n # for i, seed_set in enumerate(seed_sets):\n # if seed_set == []:\n # continue\n # n_readout_nodes += 1\n # for seed in seed_set:\n # g.add_edge(-i, seed)\n\n # nodes_list = list(set([seed for seed_set in seed_sets for seed in seed_set]))\n # nodes = torch.LongTensor(nodes_list)\n # to cuda\n # nodes = torch.LongTensor(list(g.nodes))\n # adj = torch.FloatTensor(nx.to_numpy_matrix(g))\n # nodes = nodes.cuda()\n # adj = adj.cuda()\n\n # nodes_embed = torch.cat([self.entity_emb(nodes[:-n_readout_nodes]), torch.zeros(n_readout_nodes, self.dim).cuda()])\n # nodes_features = torch.cat([self.entity_text_emb[nodes[:-n_readout_nodes]].cuda(), torch.zeros(n_readout_nodes, self.entity_text_emb.shape[1]).cuda()])\n # nodes_features = self.transform(nodes_features)\n # nodes_features = self.entity_emb(nodes[:-n_readout_nodes])\n # nodes_features = self.transform(nodes_embed + nodes_features)\n # nodes_features = self.transform(self.entity_text_emb)\n # nodes_features = self.gcn(self.entity_emb.weight, self.adj)\n # nodes_features = self.entity_emb.weight\n # nodes_features += self.transform(self.entity_text_emb)\n # nodes_features = self.gcn(nodes_features, self.edge_idx)\n # nodes_features = self.gat(nodes_features, self.edge_idx)\n nodes_features = self.rgcn(None, self.edge_idx, self.edge_type)\n\n # node2id = dict([(n, i) for i, n in enumerate(list(g.nodes))])\n user_representation_list = []\n for i, seed_set in enumerate(seed_sets):\n if seed_set == []:\n user_representation_list.append(torch.zeros(self.dim).cuda())\n continue\n # seed_set_ids = list(map(lambda x: node2id[x], seed_set))\n # user_representation = torch.cat([nodes_features[seed_set_ids], nodes_embed[seed_set_ids]], dim=1)\n user_representation = nodes_features[seed_set]\n user_representation = self.self_attn(user_representation)\n # text_features = self.entity_text_emb[seed_set]\n # print(user_representation.shape, text_features.shape)\n # user_representation = self.bi_attn(user_representation.unsqueeze(0), text_features.unsqueeze(0))\n # user_representation = user_representation.mean(dim=0)\n # user_representation = torch.relu(user_representation)\n # user_representation = nodes_features[node2id[-i]]\n user_representation_list.append(user_representation)\n return torch.stack(user_representation_list), nodes_features\n\n","sub_path":"parlai/agents/kbrd/modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":25243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"32911655","text":"'''*******************************************************************************\r\n*\r\n* FILE NAME: \r\n* bta_util_serv_bsc_response_parser.py\r\n*\r\n* DESCRIPTION:\r\n* This file contains the Classes implementation for parsing the command response from the BSC.\r\n* \r\n* \r\n* \r\n* REVISION HISTORY:\r\n*\r\n* Date Author REASON\r\n* 3rd Nov 2009 Saurabh Mittal Module restructuring as per New Coding Guidelines\r\n* Vipin Batra Initial Draft\r\n*\r\n* Copyright 2009, Aricent\r\n*\r\n******************************************************************************'''\r\n\r\n'''Import Statements'''\r\n\r\n\r\nimport re\r\nfrom xml.dom import minidom\r\nfrom bta_util_common import obj_util_comm\r\nfrom bta_util_xml_parser import obj_xml_parser\r\nimport bta_util_constants as CONSTANTS\r\n\r\n\r\n'''MODULE CONSTANTS'''\r\nMODULE_NAME = \"bta_util_serv_bsc_response_parser\"\r\n\r\n'''CONSTANTS FOR XML TAGS USED IN CONFIGURATION XML FILE '''\r\n\r\nXML_FILE_ROOT_ELEMENT_TAG = \"bsc_response\"\r\nXML_FILE_BSC_VERSION_TAG = \"bsc_ver\"\r\nXML_FILE_BSC_RESPONSE_TAG = \"response\"\r\nXML_FILE_BSC_COMMAND_TAG = \"command\"\r\nXML_FILE_BSC_RESPONSE_ERROR_TAG = \"_ERROR_\"\r\nXML_FILE_BSC_RESPONSE_START_TAG = \"_RESPONSE_START_\"\r\nXML_FILE_BSC_RESPONSE_END_TAG = \"_RESPONSE_END_\"\r\nXML_FILE_BSC_VALID_RESPONSE_TAG = \"_VALID_RESPONSE_\"\r\nXML_FILE_BSC_RESPONSE_ATTRIBUTE_ID_TAG = \"id\"\r\nXML_FILE_BSC_RESPONSE_OBJECT_TAG = \"object\"\r\nXML_FILE_BSC_RESPONSE_OBJECT_NAME_TAG = \"name\"\r\nXML_FILE_BSC_RESPONSE_OBJECT_PARENT_NAME_TAG = \"parent_name\"\r\nXML_FILE_BSC_RESPONSE_OBJECT_LEVEL_TAG = \"level\"\r\nXML_FILE_BSC_RESPONSE_PARSE_START_TAG = \"start_parse\"\r\n\r\nXML_FILE_LINE_TAG = \"line\"\r\nXML_FILE_LINE_START_ATTRIBUTE_TAG = \"start\"\r\nXML_FILE_LINE_CONTAINS_ATTRIBUTE_TAG = \"contains\"\r\nXML_FILE_LINE_HAS_GIVEN_CHAR_AT_POS_N_ATTRIBUTE_TAG = \"chars_at_pos_n\"\r\nXML_FILE_LINE_CREATE_OBJECT_TAG = \"create_object\"\r\nXML_FILE_LINE_LIST_KEY_TAG = \"list_key\" \r\nXML_FILE_LINE_CREATE_OBJECT_YES_VALUE = \"yes\"\r\nXML_FILE_LINE_CREATE_OBJECT_NO_VALUE = \"no\"\r\n\r\nXML_FILE_FIELD_DECODE_TAG = \"decode\"\r\nXML_FILE_FIELD_IDENTIFIER_TAG = \"id\"\r\nXML_FILE_FIELD_TYPE_TAG = \"type\"\r\nXML_FILE_FIELD_VALUE_START_AFTER_TAG = \"value_start_pattern\"\r\nXML_FILE_FIELD_VALUE_END_BEFORE_TAG = \"value_end_pattern\"\r\nXML_FILE_FIELD_START_AFTER_TAG = \"chars_starts_after\"\r\nXML_FILE_FIELD_END_BEFORE_TAG = \"chars_ends_before\"\r\nXML_FILE_FIELD_SKIP_LINE_START_TAG = \"chars_skip_line_start\"\r\nXML_FILE_FIELD_CHARS_AFTER_TAG = \"chars_after\"\r\nXML_FILE_FIELD_SIZE_TAG = \"field_size\"\r\nXML_FILE_FIELD_REFERENCE_TAG = \"ref\"\r\nXML_FILE_PARSED_OBJECT_NAME_TAG = \"__NAME__\"\r\n\r\n\r\n\r\nMATCH_LINE_START_VALUE = 1\r\nMATCH_LINE_CONTAINS_VALUE = 2\r\nMATCH_LINE_CONTAINS_CHAR_AT_POS_N_VALUE = 3\r\n\r\n\r\n\r\nBSC_RESPONSE_ERROR_UNEXPECTED_START_OF_NEW_MESSAGE = \"Unexpected Start of new\\\r\n message, while first one in progress\"\r\nBSC_RESPONSE_ERROR_UNEXPECTED_NEW_MESSAGE = \"Unexpected new message line,\\\r\n while first message in middle of decoding\"\r\nBSC_RESPONSE_ERROR_UNEXPECTED_END_OF_MESSAGE = \"Unexpected end of message,\\\r\n while decoding in progress\"\r\nBSC_RESPONSE_ERROR_UNEXPECTED_ERROR_MESSAGE = \"Unexpected error message,\\\r\n while decoding in progress\"\r\n\r\n\r\n'''CONSTANTS OTHER THAN XML TAGS'''\r\n\r\nJUNK_CHAR = '\\r'\r\nBACK_SLASH_STRING = \"\\\\\"\r\nBLANK_STRING = \" \"\r\nNEWLINE_CHAR = \"\\n\"\r\nCHAR_POS_SEPARATOR = \":\"\r\n\r\n'''CONSTANTS FOR DIFFERENT STATES OF THE BSC PARSER'''\r\nSTATE_SEARCH_BSC_RESPONSE_START = 1\r\nSTATE_IDENTIFY_RESPONSE = 2\r\nSTATE_DECODE_RESPONSE_LINES = 3\r\n\r\n\r\n\r\n\r\n# BSC Parameter tags\r\nDEFAULT_PARAMETER_PREFIX = CONSTANTS.EMPTY_STRING\r\nDEFAULT_PARAMETER_POSTFIX = CONSTANTS.EMPTY_STRING\r\nDEFAULT_PARAMETER_VALUE = CONSTANTS.EMPTY_STRING\r\n\r\nDECODE_SKIP_CHARS_CODE = 1\r\nDECODE_CHARS_AFTER_REF_CODE = 2\r\nDECODE_CHARS_BETWEEN_PATTERN_CODE = 3\r\n \r\nDEFAULT_DECODE_TYPE = DECODE_SKIP_CHARS_CODE\r\nDEFAULT_DECODE_FIELD_CHAR_SKIP = 0\r\nDEFAULT_DECODE_FIELD_SIZE = 0\r\nDEFAULT_DECODE_FIELD_REFERENCE = CONSTANTS.EMPTY_STRING\r\nDEFAULT_DECODE_REMOVE_CHAR = CONSTANTS.EMPTY_STRING\r\nDEFAULT_DECODE_FIELD_TYPE = CONSTANTS.TYPE_STRING\r\nDEFAULT_LEVEL = 0 #added by Yogesh\r\n\r\n'''\r\nClass Name : clsServBSCRespFieldDecoder\r\nDescription : This class reads the field parameters from BSC Response Parser\r\nFile and decodes the corresponding field from a BSC Response\r\n'''\r\nclass clsServBSCRespFieldDecoder:\r\n def __init__( self, field_name,\r\n field_type,\r\n value_start_pattern,\r\n value_end_pattern ):\r\n\r\n '''\r\n * FUNCTION NAME: \r\n * __init__( self, field_name, field_type, value_start, value_end )\r\n *\r\n * DESCRIPTION: \r\n * Constructor for the class clsServBSCRespFieldDecoder\r\n * \r\n * INPUT:\r\n * field_name: Name of the field which is decoded\r\n * field_type: Data type of the field\r\n * value_start_pattern: Pattern string indicating the start of\r\n * field value\r\n * value_end_pattern: Pattern string indicating the end of\r\n * field value\r\n *\r\n * RETURNS: \r\n * Nothing\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n self.field_name = field_name\r\n self.field_type = field_type\r\n self.field_value = None\r\n self.decode_type = DEFAULT_DECODE_TYPE\r\n self.skip_char_count = DEFAULT_DECODE_FIELD_CHAR_SKIP\r\n self.field_size = DEFAULT_DECODE_FIELD_SIZE\r\n self.reference_start = DEFAULT_DECODE_FIELD_REFERENCE\r\n self.remove_char = DEFAULT_DECODE_REMOVE_CHAR\r\n self.start_after = CONSTANTS.EMPTY_STRING\r\n self.end_before = CONSTANTS.EMPTY_STRING\r\n self.value_start_pattern = value_start_pattern\r\n self.value_end_pattern = value_end_pattern \r\n \r\n def readFieldParameters( self, field_xml_node ):\r\n\r\n '''\r\n * FUNCTION NAME: \r\n * readFieldParameters( self, field_xml_node )\r\n *\r\n * DESCRIPTION: \r\n * This function reads the values of attributes of class\r\n * clsServBSCRespFieldDecoder from the xml node supplied to it.\r\n * \r\n * \r\n * INPUT:\r\n * field_xml_node: XML Node containing the field definition\r\n *\r\n * RETURNS: \r\n * Nothing\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n\r\n try:\r\n self.field_size = obj_xml_parser.getFirstElementNodeData( XML_FILE_FIELD_SIZE_TAG,\\\r\n field_xml_node,\r\n CONSTANTS.TYPE_INT )\r\n self.skip_char_count = obj_xml_parser.getFirstElementNodeData( XML_FILE_FIELD_SKIP_LINE_START_TAG,\r\n field_xml_node,\r\n CONSTANTS.TYPE_INT )\r\n self.start_after = obj_xml_parser.getFirstElementNodeData( XML_FILE_FIELD_START_AFTER_TAG,\r\n field_xml_node )\r\n self.end_before = obj_xml_parser.getFirstElementNodeData( XML_FILE_FIELD_END_BEFORE_TAG,\r\n field_xml_node )\r\n field_size_node = field_xml_node.getElementsByTagName( XML_FILE_FIELD_SIZE_TAG )\r\n if field_size_node:\r\n self.reference_start = obj_xml_parser.getAttributeNodeValue( XML_FILE_FIELD_REFERENCE_TAG,\r\n field_size_node[0] )\r\n if self.reference_start:\r\n self.decode_type = DECODE_CHARS_AFTER_REF_CODE\r\n elif self.start_after:\r\n self.decode_type = DECODE_CHARS_BETWEEN_PATTERN_CODE\r\n except (Exception, Exception) as detail:\r\n #log error into log file and raise error\r\n raise Exception(MODULE_NAME + \".clsServBSCRespFieldDecoder.readFieldParameters, \" + str( detail ))\r\n \r\n \r\n \r\n def decodeField( self, line_string, name_value_dict ):\r\n\r\n '''\r\n * FUNCTION NAME: \r\n * decodeField( self, line_string, name_value_dict )\r\n *\r\n * DESCRIPTION: \r\n * This function decode the Field value and Name as per the\r\n * parameters specified in the field xml\r\n * \r\n * INPUT:\r\n * line_string: a string containing a part of response received.\r\n * value_dict: a dictionary object used to store field info in\r\n * name-value pairs\r\n *\r\n * RETURNS: \r\n * Nothing\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n\r\n try:\r\n field_value_except_pattern = None\r\n field_value = None\r\n reference_index = None\r\n start_index = None\r\n end_index = None\r\n temp_start_index = None\r\n temp_end_index = None\r\n matched_object_value_start = None\r\n matched_object_value_end = None\r\n field_name = None\r\n field_name_in_dict = None\r\n field_value_in_dict = None\r\n\r\n if self.decode_type == DECODE_CHARS_AFTER_REF_CODE:\r\n reference_index = line_string.find( self.reference_start )\r\n if reference_index != -1:\r\n start_index = reference_index + len( self.reference_start )\r\n end_index = start_index + self.field_size\r\n field_value_except_pattern = line_string[start_index:end_index] \r\n elif self.decode_type == DECODE_SKIP_CHARS_CODE:\r\n start_index = self.skip_char_count\r\n end_index = start_index + self.field_size\r\n field_value_except_pattern = line_string[start_index:end_index]\r\n elif self.decode_type == DECODE_CHARS_BETWEEN_PATTERN_CODE:\r\n line_string = line_string.replace( JUNK_CHAR, CONSTANTS.EMPTY_STRING )\r\n temp_start_index = self.start_after.replace( BACK_SLASH_STRING,\r\n CONSTANTS.EMPTY_STRING )\r\n temp_end_index = self.end_before.replace( BACK_SLASH_STRING,\r\n CONSTANTS.EMPTY_STRING )\r\n start_index = line_string.find( temp_start_index )\r\n end_index = line_string.find( temp_end_index )\r\n start_index = start_index + len( temp_start_index )\r\n field_value_except_pattern = line_string[start_index:end_index] \r\n\r\n if self.value_start_pattern and self.value_end_pattern:\r\n line_string = line_string.replace( JUNK_CHAR, CONSTANTS.EMPTY_STRING )\r\n matched_object_value_start = re.search( self.value_start_pattern, line_string )\r\n matched_object_value_end = re.search( self.value_end_pattern, line_string )\r\n if matched_object_value_start and matched_object_value_end:\r\n start_index = matched_object_value_start.end() \r\n end_index = matched_object_value_end.end() - 1\r\n field_value = line_string[start_index:end_index]\r\n\r\n if (not (field_value_except_pattern == None)) and\\\r\n (not (field_value_except_pattern.strip() == CONSTANTS.EMPTY_STRING )):\r\n self.field_value = str(obj_util_comm.convertDataType( field_value_except_pattern, self.field_type ))\r\n else:\r\n self.field_value = None\r\n \r\n \r\n field_name_in_dict = self.field_name\r\n field_value_in_dict = self.field_value\r\n \r\n if ( re.match( \"__NAME__\",self.field_name ) ):\r\n field_name_in_dict = field_value_in_dict.lower()\r\n if( field_value ):\r\n field_value_in_dict = field_value\r\n if field_name_in_dict not in name_value_dict:\r\n if type( 'string' ) == type( field_value_in_dict ):\r\n name_value_dict[field_name_in_dict] = field_value_in_dict.strip( )\r\n else:\r\n name_value_dict[field_name_in_dict] = field_value_in_dict\r\n elif self.field_type == CONSTANTS.TYPE_MULTI_LINE_STRING_STR:\r\n name_value_dict[field_name_in_dict] = name_value_dict[field_name_in_dict].strip() + CONSTANTS.SPACE + field_value_in_dict.strip()\r\n except (Exception, Exception) as detail:\r\n #log error into log file and raise error\r\n raise Exception(MODULE_NAME + \".clsServBSCRespFieldDecoder.decodeField, \" + str( detail ))\r\n\r\n \r\n'''\r\nClass Name : clsServBSCRespLineDecoder\r\nDescription : This class reads the line parameters from BSC Response Parser\r\nFile and decodes the corresponding line from a BSC Response\r\n'''\r\nclass clsServBSCRespLineDecoder:\r\n def __init__( self, match_criteria, is_create_object, list_key ):\r\n\r\n '''\r\n * FUNCTION NAME: \r\n * __init__( self, match_criteria, create_object )\r\n *\r\n * DESCRIPTION: \r\n * Constructor for the class clsServBSCRespLineDecoder\r\n * \r\n * INPUT:\r\n * match_criteria: dictionary containing the matching criteria\r\n * create_object_value: Data type of the field\r\n * value_start_pattern: Pattern string indicating the start of\r\n * field value\r\n * value_end_pattern: Pattern string indicating the end of\r\n * field value\r\n *\r\n * RETURNS: \r\n * Nothing\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n self.field_decoders_list = []\r\n self.match_criteria = match_criteria\r\n self.is_create_object = is_create_object\r\n self.list_key = list_key\r\n\r\n\r\n\r\n\r\n def readLineParameters( self, line_xml_node ):\r\n\r\n '''\r\n * FUNCTION NAME: \r\n * readLineParameters( self, line_xml_node )\r\n *\r\n * DESCRIPTION: \r\n * This function decode the Field value and Name as per the\r\n * parameters specified in the line node of the xml\r\n * \r\n * INPUT:\r\n * line_xml_node: XML Node containing the line decode definition\r\n *\r\n * RETURNS: \r\n * Nothing\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n try:\r\n field_nodes = None\r\n field_node = None\r\n value_start_pattern = None\r\n value_end_pattern = None\r\n node_id = None\r\n node_type = None\r\n node_value_start = None\r\n node_value_end = None\r\n field_decoder_obj = None\r\n field_nodes = line_xml_node.getElementsByTagName( XML_FILE_FIELD_DECODE_TAG )\r\n \r\n for field_node in field_nodes:\r\n node_id = field_node.getAttributeNode( XML_FILE_FIELD_IDENTIFIER_TAG )\r\n node_type = field_node.getAttributeNode( XML_FILE_FIELD_TYPE_TAG )\r\n node_value_start = field_node.getAttributeNode( XML_FILE_FIELD_VALUE_START_AFTER_TAG )\r\n\r\n if node_value_start:\r\n value_start_pattern = obj_xml_parser.getAttributeNodeValue( XML_FILE_FIELD_VALUE_START_AFTER_TAG,\r\n field_node )\r\n \r\n node_value_end = field_node.getAttributeNode( XML_FILE_FIELD_VALUE_END_BEFORE_TAG )\r\n\r\n if node_value_end:\r\n value_end_pattern = obj_xml_parser.getAttributeNodeValue( XML_FILE_FIELD_VALUE_END_BEFORE_TAG,\r\n field_node )\r\n if node_id and node_type:\r\n field_decoder_obj = clsServBSCRespFieldDecoder( node_id.value,\r\n node_type.value,\r\n value_start_pattern,\r\n value_end_pattern )\r\n field_decoder_obj.readFieldParameters( field_node )\r\n self.field_decoders_list.append( field_decoder_obj )\r\n except (Exception, Exception) as detail:\r\n #log error into log file and raise error\r\n raise Exception(MODULE_NAME + \".clsServBSCRespLineDecoder.readLineParameters, \" + str( detail ))\r\n \r\n def isPatternMatches( self, line_string ):\r\n\r\n '''\r\n * FUNCTION NAME: \r\n * isPatternMatches( self, line_string )\r\n *\r\n * DESCRIPTION: \r\n * This function checks whether the string line passed matches any of\r\n * the patterns present or not\r\n * \r\n * INPUT:\r\n * line_string: line string which is to be checked for matching patterns\r\n *\r\n * RETURNS: \r\n * Boolean value (True or False)\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n try:\r\n pattern_matched = False\r\n match_key = None\r\n match_object = None\r\n if len( self.match_criteria ):\r\n for match_key, match_object in self.match_criteria.items():\r\n # match based on start of line with a given string\r\n if MATCH_LINE_START_VALUE == match_key:\r\n pattern_matched = re.match( match_object, line_string )\r\n if not pattern_matched:\r\n break\r\n \r\n # match based on chars contained in the line\r\n elif MATCH_LINE_CONTAINS_VALUE == match_key:\r\n pattern_matched = re.search( match_object, line_string )\r\n if not pattern_matched:\r\n break\r\n elif MATCH_LINE_CONTAINS_CHAR_AT_POS_N_VALUE == match_key:\r\n char_value_list = match_object.split(CHAR_POS_SEPARATOR)\r\n match_chars = char_value_list[0]\r\n chars_size = len(match_chars)\r\n start_pos = int(char_value_list[1])\r\n if line_string.startswith( match_chars, start_pos):\r\n pattern_matched = True\r\n break\r\n else:\r\n pattern_matched = False\r\n break\r\n else: # if no match criteria matches, line is assumed to match and hence is to be decoded\r\n pattern_matched = True\r\n return pattern_matched\r\n except (Exception, Exception) as detail:\r\n #log error into log file and raise error\r\n raise Exception(MODULE_NAME + \".clsServBSCRespLineDecoder.isPatternMatches, \" + str( detail ))\r\n\r\n def decodeLine( self, line_string, name_value_dict ):\r\n\r\n '''\r\n * FUNCTION NAME: \r\n * decodeLine( self, line_string, name_value_dict )\r\n *\r\n * DESCRIPTION: \r\n * This function decode the line as per the\r\n * parameters specified in the field xml\r\n * \r\n * INPUT:\r\n * line_string: line string which is to be checked for matching patterns\r\n * name_value_dict : dictionary used to store parsed\r\n * parameter name-value pairs\r\n *\r\n * RETURNS: \r\n * Boolean value (True or False)\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n try:\r\n field_decoder_obj = None\r\n for field_decoder_obj in self.field_decoders_list:\r\n field_decoder_obj.decodeField( line_string, name_value_dict )\r\n except (Exception, Exception) as detail:\r\n #log error into log file and raise error\r\n raise Exception(MODULE_NAME + \".clsServBSCRespLineDecoder.decodeLine, \" + str( detail ))\r\n\r\n\r\n\r\n\r\n'''\r\nClass Name : clsServBSCRespObjectDecoders\r\nDescription : This class is a container for the decoded response objects of an object \r\n'''\r\nclass clsServBSCRespObjectDecoders:\r\n def __init__( self, resp_object_name, parent_name, level, line_decoders_object_list ):\r\n \r\n '''\r\n * FUNCTION NAME: \r\n * __init__( self, resp_object_name, line_decoders_object_list )\r\n *\r\n * DESCRIPTION: \r\n * Constructor for the class clsServBSCRespObjectDecoders\r\n * \r\n * INPUT:\r\n * resp_object_name: name of the response object\r\n * line_decoders_object_list: list of the object of line decoders\r\n *\r\n * RETURNS: \r\n * Nothing\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n self.resp_object_name = resp_object_name\r\n self.parent_name = parent_name\r\n if level:\r\n self.level = level\r\n else:\r\n self.level = DEFAULT_LEVEL #added by Yogesh\r\n self.line_decoders_object_list = line_decoders_object_list\r\n self.object_dict = {}\r\n \r\n \r\n\r\n\r\n\r\n\r\n'''\r\nClass Name : clsServBSCRespObjectParser\r\nDescription : This class reads the response object parameters from BSC Response Parser\r\nFile and decodes the corresponding response object from a BSC Response\r\n'''\r\nclass clsServBSCRespObjectParser:\r\n\r\n def __init__( self ):\r\n\r\n '''\r\n * FUNCTION NAME: \r\n * __init__( self )\r\n *\r\n * DESCRIPTION: \r\n * Constructor for the class clsServBSCRespObjectParser\r\n * \r\n * INPUT:\r\n * Nothing\r\n *\r\n * RETURNS: \r\n * Nothing\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n self.object_name = CONSTANTS.EMPTY_STRING\r\n #self.line_decoders = []\r\n self.response_objects_dict = {}\r\n \r\n\r\n def readBSCRespObjectParameters( self, response_xml_node ):\r\n\r\n '''\r\n * FUNCTION NAME: \r\n * readBSCRespObjectParameters( self, response_xml_node )\r\n *\r\n * DESCRIPTION: \r\n * This function decode the Various parameters name and values\r\n * specified in the object nodes of the xml\r\n * \r\n * INPUT:\r\n * response_xml_node: a xml node containing a response decode definition\r\n *\r\n * RETURNS: \r\n * Nothing\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n # Initialize Object properties\r\n try:\r\n object_xml_nodes = None\r\n object_xml_node = None\r\n object_name = None\r\n line_xml_nodes = None\r\n line_xml_node = None\r\n line_decoders_object_list = []\r\n matching_criteria_dict = {}\r\n line_start_value = None\r\n line_contain_value = None\r\n is_object_create = None\r\n line_decoder_object = None\r\n\r\n object_xml_nodes = response_xml_node.getElementsByTagName( XML_FILE_BSC_RESPONSE_OBJECT_TAG )\r\n for object_xml_node in object_xml_nodes:\r\n object_name = obj_xml_parser.getAttributeNodeValue( XML_FILE_BSC_RESPONSE_OBJECT_NAME_TAG,\r\n object_xml_node)\r\n #self.object_name = object_name\r\n parent_name = obj_xml_parser.getAttributeNodeValue( XML_FILE_BSC_RESPONSE_OBJECT_PARENT_NAME_TAG,\r\n object_xml_node)\r\n\r\n level = obj_xml_parser.getAttributeNodeValue( XML_FILE_BSC_RESPONSE_OBJECT_LEVEL_TAG,\r\n object_xml_node, CONSTANTS.TYPE_INT )\r\n #self.parent_name = parent_name\r\n line_xml_nodes = object_xml_node.getElementsByTagName( XML_FILE_LINE_TAG )\r\n for line_xml_node in line_xml_nodes:\r\n line_start_value = obj_xml_parser.getAttributeNodeValue( XML_FILE_LINE_START_ATTRIBUTE_TAG,\r\n line_xml_node )\r\n if line_start_value:\r\n matching_criteria_dict[MATCH_LINE_START_VALUE] = line_start_value\r\n \r\n line_contain_value = obj_xml_parser.getAttributeNodeValue( XML_FILE_LINE_CONTAINS_ATTRIBUTE_TAG,\r\n line_xml_node )\r\n if line_contain_value:\r\n matching_criteria_dict[MATCH_LINE_CONTAINS_VALUE] = line_contain_value\r\n\r\n char_at_pos_n = obj_xml_parser.getAttributeNodeValue( XML_FILE_LINE_HAS_GIVEN_CHAR_AT_POS_N_ATTRIBUTE_TAG,\r\n line_xml_node ) \r\n\r\n if char_at_pos_n:\r\n matching_criteria_dict[MATCH_LINE_CONTAINS_CHAR_AT_POS_N_VALUE] = char_at_pos_n\r\n \r\n is_object_create = obj_xml_parser.getAttributeNodeValue( XML_FILE_LINE_CREATE_OBJECT_TAG,\r\n line_xml_node )\r\n list_key = obj_xml_parser.getAttributeNodeValue( XML_FILE_LINE_LIST_KEY_TAG,\r\n line_xml_node ) \r\n if len( matching_criteria_dict ):\r\n line_decoder_object = clsServBSCRespLineDecoder( matching_criteria_dict,\r\n is_object_create, list_key )\r\n line_decoder_object.readLineParameters( line_xml_node )\r\n line_decoders_object_list.append( line_decoder_object )\r\n matching_criteria_dict={} \r\n self.response_objects_dict[object_name] = clsServBSCRespObjectDecoders( object_name, parent_name, level,\r\n line_decoders_object_list )\r\n line_decoders_object_list=[]\r\n except (Exception, Exception) as detail:\r\n #log error into log file and raise error\r\n raise Exception(MODULE_NAME + \".clsServBSCRespObjectParser.readBSCRespObjectParameters, \" + str( detail ))\r\n\r\n \r\n\r\n def parseBSCRespObject( self, line_string, response_object_list ):\r\n \r\n '''\r\n * FUNCTION NAME: \r\n * parseBSCRespObject( self, line_string, object_list )\r\n *\r\n * DESCRIPTION: \r\n * This function decodes an response object\r\n * \r\n * INPUT:\r\n * line_string: a line of response from BSC\r\n * object_list: list containing the object_dictionaries of\r\n * Response Object Decoders\r\n *\r\n * RETURNS: \r\n * Nothing\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n try:\r\n object_name = None\r\n resp_decoder_object = None\r\n line_decoder_objects = None\r\n line_decoder_object = None\r\n for object_name, resp_decoder_object in self.response_objects_dict.items( ):\r\n line_decoder_objects = resp_decoder_object.line_decoders_object_list\r\n for line_decoder_object in line_decoder_objects:\r\n if line_decoder_object.isPatternMatches( line_string ):\r\n if( XML_FILE_LINE_CREATE_OBJECT_YES_VALUE == line_decoder_object.is_create_object ):\r\n resp_decoder_object.object_dict = {}\r\n response_object_list.append( resp_decoder_object.object_dict )\r\n line_decoder_object.decodeLine( line_string, resp_decoder_object.object_dict )\r\n except (Exception, Exception) as detail:\r\n #log error into log file and raise error\r\n raise Exception(MODULE_NAME + \".clsServBSCRespObjectParser.parseBSCRespObject, \" + str( detail ))\r\n\r\n\r\n \r\n\r\n def parseBSCRespObjectHierarchy( self, line_string, resp_obj ):\r\n '''\r\n * FUNCTION NAME: \r\n * parseBSCRespObjectHierarchy( self, line_string, resp_dict )\r\n *\r\n *\r\n * Dictionary is created for each object encountered by default. The dictionary for new object is created, \r\n * and added to a list which has objects sharing same name. All lines in a object go into the object dictionary\r\n * object dictionary is contained in dictionary at a higher level (levels are numbered 1 (highest) to n (lowest)\r\n * \r\n *\r\n * DESCRIPTION: \r\n * This function decodes an response object\r\n * \r\n * INPUT:\r\n * line_string: a line of response from BSC\r\n * resp_dict: dict containing parsed objects\r\n *\r\n * RETURNS: \r\n * Nothing\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n try:\r\n object_name = None\r\n resp_decoder_object = None\r\n line_decoder_objects = None\r\n line_decoder_object = None\r\n parent_dict = resp_obj.data_dict\r\n for object_name, resp_decoder_object in self.response_objects_dict.items():\r\n \r\n line_decoder_objects = resp_decoder_object.line_decoders_object_list\r\n for line_decoder_object in line_decoder_objects:\r\n if line_decoder_object.isPatternMatches( line_string ):\r\n\r\n # Linking Parent.. See if parent dict exists, if so add self to it, not to original response obj\r\n my_level = resp_decoder_object.level\r\n if my_level > 1 and my_level - 1 in resp_obj.level_dict:\r\n parent_dict = resp_obj.level_dict[ my_level - 1 ]\r\n\r\n if( XML_FILE_LINE_CREATE_OBJECT_YES_VALUE == line_decoder_object.is_create_object ):\r\n \r\n line_dict = {}\r\n #response_object_list.append( resp_decoder_object.object_dict )\r\n if object_name in parent_dict: \r\n lst_obj = parent_dict[ object_name ]\r\n lst_obj.append( line_dict ) \r\n else:\r\n lst_obj = [] \r\n parent_dict[ object_name ] = lst_obj\r\n lst_obj.append( line_dict )\r\n\r\n resp_obj.level_dict[my_level] = line_dict \r\n \r\n else:\r\n line_dict = resp_obj.level_dict[my_level]\r\n \r\n line_decoder_object.decodeLine( line_string, line_dict )\r\n except (Exception, Exception) as detail:\r\n #log error into log file and raise error\r\n raise Exception(MODULE_NAME + \".clsServBSCRespObjectParser.parseBSCRespObjectHierarchy, \" + str( detail ))\r\n \r\n\r\n \"\"\" \r\n\r\n def parseBSCRespObjectHierarchy( self, line_string, resp_obj ):\r\n '''\r\n * FUNCTION NAME: \r\n * parseBSCRespObjectHierarchy( self, line_string, resp_dict )\r\n *\r\n * DESCRIPTION: \r\n * This function decodes an response object\r\n * \r\n * INPUT:\r\n * line_string: a line of response from BSC\r\n * resp_dict: dict containing parsed objects\r\n *\r\n * RETURNS: \r\n * Nothing\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n try:\r\n object_name = None\r\n resp_decoder_object = None\r\n line_decoder_objects = None\r\n line_decoder_object = None\r\n obj_dict = resp_obj.data_dict\r\n\r\n for object_name, resp_decoder_object in self.response_objects_dict.iteritems():\r\n #obj_dict = None\r\n\r\n \r\n\r\n line_decoder_objects = resp_decoder_object.line_decoders_object_list\r\n for line_decoder_object in line_decoder_objects:\r\n if line_decoder_object.isPatternMatches( line_string ):\r\n\r\n # Linking Parent.. See if parent dict exists, if so add self to it, not to original response obj\r\n if resp_decoder_object.parent_name and resp_obj.parent_dict.has_key( resp_decoder_object.parent_name ):\r\n obj_dict = resp_obj.parent_dict[resp_decoder_object.parent_name]\r\n print \" parent dict for \",object_name,\" parent \",resp_decoder_object.parent_name,\" is : FOUND\"\r\n\r\n #print \"overall dict \",resp_obj.data_dict,\" my dict \",obj_dict \r\n if( XML_FILE_LINE_CREATE_OBJECT_YES_VALUE == line_decoder_object.is_create_object ):\r\n line_dict = {}\r\n #response_object_list.append( resp_decoder_object.object_dict )\r\n if line_decoder_object.list_key:\r\n if obj_dict.has_key( line_decoder_object.list_key ): \r\n lst_obj = obj_dict[ line_decoder_object.list_key ]\r\n lst_obj.append( line_dict ) \r\n else:\r\n lst_obj = [] \r\n obj_dict[line_decoder_object.list_key ] = lst_obj\r\n lst_obj.append( line_dict )\r\n else:\r\n obj_dict[object_name] = line_dict\r\n else:\r\n line_dict = obj_dict\r\n\r\n print \" dict \",str(line_dict),\"is for \",object_name\r\n resp_obj.parent_dict[object_name] = line_dict\r\n \r\n line_decoder_object.decodeLine( line_string, line_dict )\r\n except (StandardError, Exception), detail:\r\n #log error into log file and raise error\r\n raise StandardError, MODULE_NAME + \".clsServBSCRespObjectParser.parseBSCRespObjectHierarchy, \" + str( detail )\r\n \"\"\" \r\n \r\n'''\r\nState Machine of the BSC Response Parser\r\n \r\n __________ ____________ ______________ \r\n | SEARCH | ----Start of BSC response--->| IDENTIFY |--particular response identified--->|DECODE_OBJECT|\r\n ---------- ----------- -------|------- \r\n ^ | \r\n |__________________________________________________________________________________________| | \r\n Error in Line, End of Response Found \r\n\r\n\r\n LEGENDS:\r\n\r\n 1. State\r\n __________\r\n | STATE | \r\n ----------\r\n \r\n 2. Transition from State A to State B on event 'E'\r\n \r\n A ----E----> B\r\n\r\n\r\n'''\r\n\r\n'''\r\nClass Name : clsServBSCResponseParser\r\nDescription : This class reads the response object parser parameters from BSC Response Parser\r\nFile and parse the response corresponding to a response object parser from a BSC Response\r\n'''\r\nclass clsServBSCResponseParser:\r\n def __init__( self, response_type ):\r\n\r\n '''\r\n * FUNCTION NAME: \r\n * __init__( self, response_type )\r\n *\r\n * DESCRIPTION: \r\n * Constructor for the class clsServBSCResponseParser\r\n * \r\n * INPUT:\r\n * response_type: Indicate the response type\r\n *\r\n * RETURNS: \r\n * Nothing\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n self.response_type = response_type\r\n self.command = CONSTANTS.EMPTY_STRING\r\n self.start_parse_value = CONSTANTS.EMPTY_STRING\r\n #self.xml_node = xml_response_node\r\n self.resp_object_parser = None\r\n #self.initialize( )\r\n\r\n def readRespParserParameters( self, response_xml_node ):\r\n\r\n '''\r\n * FUNCTION NAME: \r\n * readRespParserParameters( self, response_xml_node )\r\n *\r\n * DESCRIPTION: \r\n * This function decode the Various parameters name and values\r\n * specified in the object nodes of the xml\r\n * \r\n * INPUT:\r\n * response_xml_node: a xml node containing a response decode definition\r\n *\r\n * RETURNS: \r\n * Nothing\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n try:\r\n self.command = obj_xml_parser.getFirstElementNodeData( XML_FILE_BSC_COMMAND_TAG,\r\n response_xml_node )\r\n self.start_parse_value = obj_xml_parser.getFirstElementNodeData( XML_FILE_BSC_RESPONSE_PARSE_START_TAG,\r\n response_xml_node )\r\n self.resp_object_parser = clsServBSCRespObjectParser()\r\n self.resp_object_parser.readBSCRespObjectParameters( response_xml_node )\r\n except (Exception, Exception) as detail:\r\n #log error into log file and raise error\r\n raise Exception(MODULE_NAME + \".clsServBSCRespObjectParser.readRespParserParameters, \" + str( detail ))\r\n\r\n\r\n \r\n def parseResponse( self, line_string, response_object_list ):\r\n '''\r\n * FUNCTION NAME: \r\n * parseResponse( self, line_string, response_object_list )\r\n *\r\n * DESCRIPTION: \r\n * This function parses the line_string passed to it\r\n * \r\n * INPUT:\r\n * line_string: part of response to be parsed\r\n * response_object_list: list of objects which are already parsed\r\n *\r\n * RETURNS: \r\n * Nothing\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n try:\r\n if (line_string != None and response_object_list != None)\\\r\n and (type( response_object_list ) == type( [] )) :\r\n line_string = str( line_string )\r\n self.resp_object_parser.parseBSCRespObject( line_string,\r\n response_object_list )\r\n except (Exception, Exception) as detail:\r\n #log error into log file and raise error\r\n raise Exception(MODULE_NAME + \".clsServBSCRespObjectParser.parseResponse, \" + str( detail ))\r\n\r\n\r\n def parseResponseHierarchy( self, line_string, data_obj ):\r\n '''\r\n * FUNCTION NAME: \r\n * parseResponseHierarchy( self, line_string, response_object_list )\r\n *\r\n * DESCRIPTION: \r\n * This function parses the line_string passed to it\r\n * \r\n * INPUT:\r\n * line_string: part of response to be parsed\r\n * response_object_dict: dict of objects\r\n *\r\n * RETURNS: \r\n * Nothing\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n try:\r\n if (line_string != None and data_obj != None):\r\n line_string = str( line_string )\r\n self.resp_object_parser.parseBSCRespObjectHierarchy( line_string,\r\n data_obj )\r\n except (Exception, Exception) as detail:\r\n #log error into log file and raise error\r\n raise Exception(MODULE_NAME + \".clsServBSCRespObjectParser.parseResponse, \" + str( detail ))\r\n\r\n\r\n\r\n\r\n \r\n def isLineMatches( self, line_string ):\r\n '''\r\n * FUNCTION NAME: \r\n * isLineMatches( self, line_string )\r\n *\r\n * DESCRIPTION: \r\n * This function checks whether the string line passed matches\r\n * with the start parse value specified or not\r\n * \r\n * INPUT:\r\n * line_string: line string which is to be checked for matching\r\n *\r\n * RETURNS: \r\n * Boolean value (True or False)\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n try:\r\n is_matched = False\r\n line_string = str( line_string )\r\n if re.search( self.start_parse_value, line_string ):\r\n is_matched = True \r\n return is_matched\r\n except (Exception, Exception) as detail:\r\n #log error into log file and raise error\r\n raise Exception(MODULE_NAME + \".clsServBSCRespObjectParser.isLineMatches, \" + str( detail ))\r\n \r\n \r\n\r\n\r\n'''\r\nThis is main class of this module.\r\nThis class processes the provided XML file ( as part of init ), parses and stores BSC command\r\ndetails using respective class objects.\r\n'''\r\n \r\nclass clsServBSCResponseParseController:\r\n\r\n def __init__( self, xml_file_name, logger=None ):\r\n\r\n '''\r\n * FUNCTION NAME: \r\n * __init__( self, xml_file_name )\r\n *\r\n * DESCRIPTION: \r\n * Constructor for the class clsServBSCResponseParseController\r\n * \r\n * INPUT:\r\n * xml_file_name: file name of the system file\r\n *\r\n * RETURNS: \r\n * Nothing\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n try:\r\n root_node = None\r\n bsc_version_node = None\r\n \r\n self.bsc_responses_list = []\r\n self.bsc_version = None\r\n self.response_parsers_dict = {}\r\n self.response_parsers_by_command_dict= {}\r\n self.error_parser = None\r\n self.response_end_parser = None\r\n self.response_start_parser = None\r\n self.decode_in_progress_resp = None\r\n \r\n self.state = STATE_SEARCH_BSC_RESPONSE_START\r\n self.file_name = xml_file_name\r\n self.error_flag = False\r\n self.doc = minidom.parse( self.file_name )\r\n self.logger = logger\r\n root_node = self.doc.getElementsByTagName( XML_FILE_ROOT_ELEMENT_TAG )\r\n if root_node and root_node.length > 0:\r\n bsc_version_node = root_node[0].getAttributeNode( XML_FILE_BSC_VERSION_TAG )\r\n self.bsc_version = bsc_version_node.value\r\n \r\n except (Exception, Exception) as detail:\r\n #log error into log file and raise error\r\n raise Exception(MODULE_NAME + \".clsServBSCResponseParseController.__init__, \" + str( detail ))\r\n\r\n def resetToDefaults( self ):\r\n\r\n '''\r\n * FUNCTION NAME: \r\n * resetToDefaults( self )\r\n *\r\n * DESCRIPTION: \r\n * Resets the instance attributes to default values\r\n * \r\n * INPUT:\r\n * Nothing\r\n *\r\n * RETURNS: \r\n * Nothing\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n self.decode_in_progress_resp = None\r\n self.state = STATE_SEARCH_BSC_RESPONSE_START\r\n self.bsc_responses_list = []\r\n\r\n def getFirstValueFromObjects( self, command, key_searched ):\r\n\r\n '''\r\n * FUNCTION NAME: \r\n * getFirstValueFromObjects( self, command, key_searched )\r\n *\r\n * DESCRIPTION: \r\n * Returns the value of an specified key from within a specified command's response\r\n * \r\n * INPUT:\r\n * command: command name\r\n * key_searched: key name\r\n *\r\n * RETURNS: \r\n * value of key\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n try:\r\n matched_value = None\r\n is_matched = False\r\n command_object = None\r\n resp_object = None\r\n key = None\r\n value = None\r\n for command_object in self.bsc_responses_list:\r\n if( command == command_object.command ):\r\n for resp_object in command_object.objects:\r\n for key, value in resp_object.items():\r\n if key == key_searched:\r\n matched_value = value\r\n is_matched = True\r\n break\r\n if is_matched:\r\n break\r\n if is_matched:\r\n break\r\n return matched_value\r\n except (Exception, Exception) as detail:\r\n #log error into log file and raise error\r\n raise Exception(MODULE_NAME + \".clsServBSCResponseParseController.getFirstValueFromObjects, \" + str( detail ))\r\n \r\n\r\n def getAllObjectsForName( self, command, key_searched ):\r\n\r\n '''\r\n * FUNCTION NAME: \r\n * getAllObjectsForName( self, command, key_searched )\r\n *\r\n * DESCRIPTION: \r\n * Returns the list of all value present of an specified key\r\n * from within a specified command's response\r\n * \r\n * INPUT:\r\n * command: command name\r\n * key_searched: key name\r\n *\r\n * RETURNS: \r\n * list containing all the values of that key\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n try:\r\n is_matched = False\r\n command_object = None\r\n resp_object = None\r\n key = None\r\n value = None\r\n matched_value_list = [] \r\n for command_object in self.bsc_responses_list:\r\n if( command == command_object.command ):\r\n for resp_object in command_object.objects: \r\n for key, value in resp_object.items( ):\r\n if( key == key_searched ):\r\n matched_value_list.append( value )\r\n return matched_value_list\r\n except (Exception, Exception) as detail:\r\n #log error into log file and raise error\r\n raise Exception(MODULE_NAME + \".clsServBSCResponseParseController.getAllObjectsForName, \" + str( detail ))\r\n\r\n def getFirstCommandObject( self, command ):\r\n '''\r\n * FUNCTION NAME: \r\n * getFirstCommandObject( self, command )\r\n *\r\n * DESCRIPTION: \r\n * Returns the first command object corresponding to the supplied command name\r\n * \r\n * INPUT:\r\n * command: command name\r\n *\r\n * RETURNS: \r\n * object of clsServParsedBSCResponse\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n try:\r\n matched_command_object = None\r\n command_object = None \r\n for command_object in self.bsc_responses_list:\r\n if( command == command_object.command ):\r\n matched_command_object = command_object\r\n break\r\n return matched_command_object \r\n except (Exception, Exception) as detail:\r\n #log error into log file and raise error\r\n raise Exception(MODULE_NAME + \".clsServBSCResponseParseController.getFirstCommandObject, \" + str( detail ))\r\n \r\n def getAllCommandObjects( self, command ):\r\n\r\n '''\r\n * FUNCTION NAME: \r\n * getAllCommandObjects( self, command )\r\n *\r\n * DESCRIPTION: \r\n * Returns list of all command objects corresponding to the supplied command name\r\n * \r\n * INPUT:\r\n * command: command name\r\n *\r\n * RETURNS: \r\n * a list containing object of clsServParsedBSCResponse\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n try:\r\n command_object = None\r\n matched_command_object_list = []\r\n for command_object in self.bsc_responses_list:\r\n if( command == command_object.command ):\r\n matched_command_object_list.append( command_object )\r\n return matched_command_object_list \r\n except (Exception, Exception) as detail:\r\n #log error into log file and raise error\r\n raise Exception(MODULE_NAME + \".clsServBSCResponseParseController.getAllCommandObjects, \" + str( detail ))\r\n \r\n def readResponseNodeParameters( self ): \r\n\r\n '''\r\n * FUNCTION NAME: \r\n * readResponseNodeParameters( self )\r\n *\r\n * DESCRIPTION: \r\n * Reads the parameter values from xml\r\n * \r\n * INPUT:\r\n * Nothing\r\n *\r\n * RETURNS: \r\n * Nothing\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n try:\r\n response_nodes = None\r\n response_node = None\r\n response_type = None\r\n start_parse_value = None\r\n bsc_resp_parser_object = None\r\n \r\n response_nodes = self.doc.getElementsByTagName( XML_FILE_BSC_RESPONSE_TAG )\r\n for response_node in response_nodes:\r\n response_type = obj_xml_parser.getAttributeNodeValue( XML_FILE_BSC_RESPONSE_ATTRIBUTE_ID_TAG,\r\n response_node )\r\n if re.match( response_type, XML_FILE_BSC_RESPONSE_ERROR_TAG ):\r\n self.error_parser = clsServBSCResponseParser( XML_FILE_BSC_RESPONSE_ERROR_TAG )\r\n self.error_parser.readRespParserParameters( response_node )\r\n elif re.match( response_type, XML_FILE_BSC_RESPONSE_END_TAG ):\r\n self.response_end_parser = clsServBSCResponseParser( XML_FILE_BSC_RESPONSE_END_TAG )\r\n self.response_end_parser.readRespParserParameters( response_node )\r\n elif re.match( response_type, XML_FILE_BSC_RESPONSE_START_TAG ):\r\n self.response_start_parser = clsServBSCResponseParser( XML_FILE_BSC_RESPONSE_START_TAG )\r\n self.response_start_parser.readRespParserParameters( response_node )\r\n else:\r\n start_parse_value = obj_xml_parser.getFirstElementNodeData( XML_FILE_BSC_RESPONSE_PARSE_START_TAG,\r\n response_node )\r\n bsc_resp_parser_object = clsServBSCResponseParser( response_type )\r\n bsc_resp_parser_object.readRespParserParameters( response_node )\r\n self.response_parsers_dict[start_parse_value] = bsc_resp_parser_object\r\n self.response_parsers_by_command_dict[bsc_resp_parser_object.command] = bsc_resp_parser_object\r\n \r\n except (Exception, Exception) as detail:\r\n #log error into log file and raise error\r\n raise Exception(MODULE_NAME + \".clsServBSCResponseParseController.readResponseNodeParameters, \" + str( detail ))\r\n\r\n\r\n\r\n def getResponseParserByCommand(self, command ):\r\n\r\n '''\r\n * FUNCTION NAME: \r\n * getResponseParserByCommand( self, command )\r\n *\r\n * DESCRIPTION: \r\n * Returns the response parser for a given command\r\n * \r\n * INPUT:\r\n * command: command for which respone parser object is to be searched\r\n *\r\n * RETURNS: \r\n * Object of clsServBSCResponseParser corresponding for the command provided\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n parser = None\r\n \r\n if command in self.response_parsers_by_command_dict:\r\n parser = self.response_parsers_by_command_dict[ command ]\r\n \r\n return parser\r\n\r\n \r\n \r\n def findResponseParser( self, line_string ):\r\n\r\n '''\r\n * FUNCTION NAME: \r\n * findResponseParser( self, line_string )\r\n *\r\n * DESCRIPTION: \r\n * finds an appropriate response parser object for the line provided\r\n * which matches with the line_stringReads the parameter values from xml\r\n * \r\n * INPUT:\r\n * line_string: line for which respone parser object is to be searched\r\n *\r\n * RETURNS: \r\n * Object of clsServBSCResponseParser corresponding for the line provided\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n try:\r\n matched_resp_parser_object = None\r\n parser_key = None\r\n resp_parser_object = None\r\n \r\n line_string = str( line_string )\r\n if self.error_parser.isLineMatches( line_string ):\r\n matched_resp_parser_object = self.error_parser\r\n elif self.response_start_parser.isLineMatches( line_string ):\r\n matched_resp_parser_object = self.response_start_parser\r\n elif self.response_end_parser.isLineMatches( line_string ):\r\n matched_resp_parser_object = self.response_end_parser\r\n else:\r\n for parser_key, resp_parser_object in self.response_parsers_dict.items():\r\n if re.search( parser_key, line_string ) != None:\r\n matched_resp_parser_object = resp_parser_object\r\n break\r\n return matched_resp_parser_object\r\n except (Exception, Exception) as detail:\r\n #log error into log file and raise error\r\n raise Exception(MODULE_NAME + \".clsServBSCResponseParseController.findResponseParser, \" + str( detail ))\r\n\r\n def parseBSCResponseFile( self, file_name ):\r\n '''\r\n * FUNCTION NAME: \r\n * parseBSCResponseFile( self, file_name )\r\n *\r\n * DESCRIPTION: \r\n * parses a response file, inturn called parseBSCResponse function of the class\r\n * \r\n * INPUT:\r\n * file_name: name of the response file which is to be parsed\r\n *\r\n * RETURNS: \r\n * Nothing\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n try:\r\n file_handle = None\r\n file_contents = None\r\n \r\n fh = open( file_name, CONSTANTS.FILE_MODE_ASCII_READ ) \r\n file_contents = fh.read()\r\n fh.close()\r\n self.parseBSCResponse( file_contents )\r\n except (Exception, Exception) as detail:\r\n #log error into log file and raise error\r\n raise Exception(MODULE_NAME + \".clsServBSCResponseParseController.parseBSCResponseFile, \" + str( detail ))\r\n \r\n\r\n def parseBSCResponse( self, response_string ):\r\n '''\r\n * FUNCTION NAME: \r\n * parseBSCResponse( self, response_string )\r\n *\r\n * DESCRIPTION: \r\n * parses a response string\r\n * \r\n * INPUT:\r\n * response_string: response string which is to be parsed\r\n *\r\n * RETURNS: \r\n * Nothing\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n try:\r\n line_strings = None\r\n line_string = None\r\n response_type = None\r\n matched_resp_parser_object = None\r\n prev_matched_resp_parser_object = None\r\n \r\n \r\n self.resetToDefaults()\r\n \r\n #YKV, 08-05-09 response_string is converted into string so that if anythig else comes then no error will be raised\r\n line_strings = str( response_string ).splitlines()\r\n \r\n #mode = MODE_SEARCH \r\n for line_string in line_strings: #YKV, 08-05-09 for loop is optimized\r\n line_string = line_string + NEWLINE_CHAR\r\n matched_resp_parser_object = self.findResponseParser( line_string )\r\n #print \"Parsing line \",line,\" parser \",chk,\" parser \",parser\r\n #ignore error\r\n #ignore end of line\r\n #ignore all lines except generic /specific start of response, in such cases create a\r\n #response object and move to \r\n if STATE_SEARCH_BSC_RESPONSE_START == self.state:\r\n if matched_resp_parser_object:\r\n if (XML_FILE_BSC_RESPONSE_ERROR_TAG == matched_resp_parser_object.response_type):\r\n #print\" ERROR in line \",line #executed\r\n pass\r\n elif (XML_FILE_BSC_RESPONSE_START_TAG == matched_resp_parser_object.response_type):\r\n #print \"In decoding date time\"\r\n self.decode_in_progress_resp = clsServParsedBSCResponse()\r\n #self.temp_date_holder = []\r\n #self.decode_in_progress_resp.date_holder = self.temp_date_holder\r\n self.bsc_responses_list.append( self.decode_in_progress_resp )\r\n self.decode_in_progress_resp.command = matched_resp_parser_object.command\r\n self.state = STATE_IDENTIFY_RESPONSE \r\n matched_resp_parser_object.parseResponse( line_string,\r\n self.decode_in_progress_resp.date_holder )\r\n elif (XML_FILE_BSC_VALID_RESPONSE_TAG == matched_resp_parser_object.response_type):\r\n self.decode_in_progress_resp = clsServParsedBSCResponse() \r\n #self.decode_in_progress_resp.date_holder = self.temp_date_holder\r\n self.bsc_responses_list.append( self.decode_in_progress_resp )\r\n self.decode_in_progress_resp.command = matched_resp_parser_object.command\r\n self.state = STATE_DECODE_RESPONSE_LINES\r\n matched_resp_parser_object.parseResponse( line_string,\r\n self.decode_in_progress_resp.objects )\r\n prev_matched_resp_parser_object = matched_resp_parser_object\r\n \r\n elif STATE_IDENTIFY_RESPONSE == self.state:\r\n if matched_resp_parser_object:\r\n if (XML_FILE_BSC_RESPONSE_ERROR_TAG == matched_resp_parser_object.response_type):\r\n self.decode_in_progress_resp.error = True\r\n self.decode_in_progress_resp.error_description = BSC_RESPONSE_ERROR_UNEXPECTED_ERROR_MESSAGE\r\n self.decode_in_progress_resp = None\r\n self.state = STATE_SEARCH_BSC_RESPONSE_START \r\n elif (XML_FILE_BSC_RESPONSE_START_TAG == matched_resp_parser_object.response_type):\r\n #self.temp_date_holder = []\r\n self.decode_in_progress_resp.error = True\r\n self.decode_in_progress_resp.error_description = BSC_RESPONSE_ERROR_UNEXPECTED_START_OF_NEW_MESSAGE\r\n self.decode_in_progress_resp = clsServParsedBSCResponse()\r\n #self.decode_in_progress_resp.date_holder = self.temp_date_holder\r\n self.bsc_responses_list.append( self.decode_in_progress_resp )\r\n self.decode_in_progress_resp.command = matched_resp_parser_object.command\r\n self.state = STATE_DECODE_RESPONSE_LINES \r\n matched_resp_parser_object.parseResponse( line_string,\r\n self.decode_in_progress_resp.date_holder )\r\n prev_matched_resp_parser_object = matched_resp_parser_object\r\n elif (XML_FILE_BSC_RESPONSE_END_TAG == matched_resp_parser_object.response_type):\r\n self.decode_in_progress_resp.error = True\r\n self.decode_in_progress_resp.error_description = BSC_RESPONSE_ERROR_UNEXPECTED_END_OF_MESSAGE\r\n self.decode_in_progress_resp = None\r\n self.state = STATE_SEARCH_BSC_RESPONSE_START \r\n elif (XML_FILE_BSC_VALID_RESPONSE_TAG == matched_resp_parser_object.response_type):\r\n self.state = STATE_DECODE_RESPONSE_LINES\r\n self.decode_in_progress_resp.command = matched_resp_parser_object.command\r\n matched_resp_parser_object.parseResponse( line_string,\r\n self.decode_in_progress_resp.objects )\r\n prev_matched_resp_parser_object = matched_resp_parser_object\r\n elif STATE_DECODE_RESPONSE_LINES == self.state:\r\n if matched_resp_parser_object:\r\n if (XML_FILE_BSC_RESPONSE_ERROR_TAG == matched_resp_parser_object.response_type):\r\n self.decode_in_progress_resp.error = True\r\n self.decode_in_progress_resp.error_description = BSC_RESPONSE_ERROR_UNEXPECTED_ERROR_MESSAGE\r\n matched_resp_parser_object.parseResponse( line_string,\\\r\n self.decode_in_progress_resp.error_object )\r\n #print self.decode_in_progress.error_description\r\n #self.decode_in_progress = None\r\n #self.state = STATE_SEARCH_BSC_RESPONSE_START\r\n elif ( XML_FILE_BSC_RESPONSE_START_TAG == matched_resp_parser_object.response_type):\r\n self.decode_in_progress_resp.error = True\r\n self.decode_in_progress_resp.error_description = BSC_RESPONSE_ERROR_UNEXPECTED_START_OF_NEW_MESSAGE\r\n #self.temp_date_holder = []\r\n self.decode_in_progress_resp = clsServParsedBSCResponse()\r\n #self.decode_in_progress_resp.date_holder = self.temp_date_holder\r\n self.bsc_responses_list.append( self.decode_in_progress_resp )\r\n self.decode_in_progress_resp.command = matched_resp_parser_object.command\r\n self.state = STATE_IDENTIFY_RESPONSE \r\n matched_resp_parser_object.parseResponse( line_string,\r\n self.decode_in_progress_resp.date_holder )\r\n elif (XML_FILE_BSC_RESPONSE_END_TAG == matched_resp_parser_object.response_type):\r\n self.decode_in_progress_resp = None #executed\r\n self.state = STATE_SEARCH_BSC_RESPONSE_START \r\n elif (XML_FILE_BSC_VALID_RESPONSE_TAG == matched_resp_parser_object.response_type):\r\n self.decode_in_progress_resp.error = True\r\n self.decode_in_progress_resp.error_description = BSC_RESPONSE_ERROR_UNEXPECTED_NEW_MESSAGE\r\n self.decode_in_progress_resp = clsServParsedBSCResponse()\r\n self.bsc_responses_list.append( self.decode_in_progress_resp )\r\n #self.decode_in_progress_resp.date_holder = self.temp_date_holder\r\n self.decode_in_progress_resp.command = matched_resp_parser_object.command\r\n self.state = STATE_DECODE_RESPONSE_LINES\r\n matched_resp_parser_object.parseResponse( line_string,\r\n self.decode_in_progress_resp.objects )\r\n prev_matched_resp_parser_object = matched_resp_parser_object\r\n else:\r\n matched_resp_parser_object.parseResponse( line_string,\\\r\n self.decode_in_progress_resp.objects )\r\n elif prev_matched_resp_parser_object:\r\n prev_matched_resp_parser_object.parseResponse( line_string,\r\n self.decode_in_progress_resp.objects ) #executed\r\n else:\r\n #print \"WHY IS PARSER NULL?\"\r\n pass\r\n else:\r\n #print \"Invalid State \",self.state,\" Ignoring line \",line\r\n pass\r\n #print \"End of Parsing , Objects Parsed = \",len( self.bsc_responses ) #executed\r\n except (Exception, Exception) as detail:\r\n #log error into log file and raise error\r\n raise Exception(MODULE_NAME + \".clsServBSCResponseParseController.parseBSCResponse, \" + str( detail ))\r\n\r\n\r\n\r\n def parseBSCResponseForCommand(self, command_name, response_string ):\r\n '''\r\n * FUNCTION NAME: \r\n * parseBSCResponse( self, response_string )\r\n *\r\n * DESCRIPTION: \r\n * Parses the data containing several parameters for a BSC response and adds them to a dictionary\r\n * \r\n * INPUT:\r\n * response_string: response string which is to be parsed\r\n *\r\n * RETURNS: \r\n * Nothing\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n line_strings = str( response_string ).splitlines()\r\n data_obj = clsServParsedBSCResponseHierarchy()\r\n data_obj.command = command_name\r\n date_parser = self.response_start_parser\r\n \r\n for line_string in line_strings: \r\n line_string = line_string + NEWLINE_CHAR\r\n if date_parser.isLineMatches( line_string ):\r\n date_parser.parseResponseHierarchy( line_string, data_obj )\r\n \r\n matched_resp_parser_object = self.getResponseParserByCommand( command_name )\r\n if matched_resp_parser_object:\r\n matched_resp_parser_object.parseResponseHierarchy( line_string, data_obj )\r\n \r\n else:\r\n if self.logger:\r\n self.logger.logError(\"BSC response Parser cannot parse command \"+str(command)+\" : Parser is missing.\")\r\n\r\n return data_obj \r\n \r\n \r\n\r\n'''\r\nClass to hold the Parsed BSC Reponses\r\n List\r\n of\r\n responses ( e.g. ZEEI, ZERO )\r\n ParsedResponse Object \r\n __ __________ \r\n |__|--->| date | List of Objects ( bcf data, trx data etc )\r\n |__| | error | __ Dictionary is lowest level object having name value pairs for each object \r\n |__| | objects|-------> |__|-->{ name1:value1, name2:value2,bcf_id:37, bcf_type:FLEXI EDGE,...} \r\n |________| |__|-->{ trx_id:1, arfn:121, ... } \r\n'''\r\n\r\nclass clsServParsedBSCResponse:\r\n\r\n def __init__( self ): \r\n\r\n '''\r\n * FUNCTION NAME: \r\n * __init__( self )\r\n *\r\n * DESCRIPTION: \r\n * Constructor for the class clsServParsedBSCResponse\r\n * \r\n * INPUT:\r\n * Nothing\r\n *\r\n * RETURNS: \r\n * Nothing\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n \r\n self.date_holder = []\r\n self.error = False\r\n self.command = CONSTANTS.EMPTY_STRING\r\n self.error_description = CONSTANTS.EMPTY_STRING\r\n self.objects = []\r\n self.error_object = []\r\n\r\n def printParsedObjects( self ):\r\n '''\r\n * FUNCTION NAME: \r\n * printParsedObjects( self )\r\n *\r\n * DESCRIPTION: \r\n * prints the objects along with their key-value pairs of a parsed response\r\n * \r\n * INPUT:\r\n * Nothing\r\n *\r\n * RETURNS: \r\n * Nothing\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n try:\r\n parsed_object = None\r\n key = None\r\n error_object = None\r\n print(\"--------------------------\")\r\n print(\"Command: \" , self.command)\r\n print(\" No of objects parsed \",len( self.objects ))\r\n if self.date_holder and ( 1 == len( self.date_holder )):\r\n print(\"Date:\", self.date_holder[0][\"date\"], \" Time: \", self.date_holder[0][\"time\"])\r\n else:\r\n print(\"No Date/time recorded\")\r\n\r\n for parsed_object in self.objects:\r\n print(\"Parsed Object size \", len( parsed_object ))\r\n for key in parsed_object:\r\n print(key, \" : \", parsed_object[key])\r\n\r\n if self.error_object:\r\n print(\" Error Objects\")\r\n error_object = self.error_object[0]\r\n for key in error_object:\r\n print(key ,\" : \", error_object[key])\r\n \r\n except (Exception, Exception) as detail:\r\n #log error into log file and raise error\r\n raise Exception(MODULE_NAME + \".clsServBSCResponseParseController.printParsedObjects, \" + str( detail ))\r\n \r\nclass clsServParsedBSCResponseHierarchy:\r\n\r\n def __init__( self ): \r\n\r\n '''\r\n * FUNCTION NAME: \r\n * __init__( self )\r\n *\r\n * DESCRIPTION: \r\n * Constructor for the class clsServParsedBSCResponse\r\n * \r\n * INPUT:\r\n * Nothing\r\n *\r\n * RETURNS: \r\n * Nothing\r\n * \r\n * NOTES: \r\n * <Optional Notes If any>\r\n '''\r\n self.command = None\r\n self.level_dict = {}\r\n self.data_dict = {}\r\n\r\n\r\n\r\n\r\n","sub_path":"kk_ADTRAN/Execution_Framework1_build25/Execution_Framework1_build25/bta_util_serv_bsc_response_parser.py","file_name":"bta_util_serv_bsc_response_parser.py","file_ext":"py","file_size_in_byte":72283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"441213596","text":"from .Lima import LimaDetector\nfrom ..environment import env\n\nimport numpy as np\ntry:\n import PyTango\nexcept ModuleNotFoundError:\n pass\nimport os\n\nclass Pilatus(LimaDetector):\n def __init__(self, *args, **kwargs):\n super(Pilatus, self).__init__(*args, **kwargs)\n self._hdf_path_base = 'entry_%04d/measurement/Pilatus/data'\n\n def _initialize_det(self):\n self.energy = 10.0\n\n @property\n def energy(self):\n return self.det.energy_threshold\n \n @energy.setter\n def energy(self, value):\n if value < 4.5 or value > 36:\n raise ValueError('Requested value is outside the Pilatus range of 4.5-36 keV')\n self.det.write_attribute('energy_threshold', value)\n\n","sub_path":"contrast/detectors/Pilatus.py","file_name":"Pilatus.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"496910917","text":"from openpyxl import load_workbook\n\n#https://letscode.com.br/blog/aprenda-a-integrar-python-e-excel\n#https://openpyxl.readthedocs.io/en/stable/tutorial.html\n\n#caminho = 'AULAS-EAD-REGISTRO-DE-ATIVIDADE.xlsx'\n#lendo a planilha\ncaminho = 'Aprendendoalerplanilhas.xlsx'\n#abrindo\narquivo_excel = load_workbook(caminho, data_only=True)\n#setando na aba da planilha\nplanilha = arquivo_excel.active\n#apontando na linha e coluna\nsim =0\nnao=0\n\ncolunas = 6\n\ncolunan = 6\nxx = 6\nxy = 6\n\nplanilha.cell(row=2, column=5, value='SIM:')\nplanilha.cell(row=3, column=5, value='NAO:')\n\nfor x in range(1,40):\n\n aluno = [\"Aluno\"]\n alunonum = [x]\n str(alunonum)\n aluno += alunonum\n uniao = \" \".join([str(_) for _ in aluno])\n str(uniao)\n print(uniao)\n\n conteudo = planilha.cell(row=x, column=2)\n ponteirocont = planilha.cell(row=x, column=3)\n if conteudo.value == uniao and ponteirocont.value == \"SIM\":\n sim +=1\n planilha.cell(row=1, column=xx, value= uniao)\n planilha.cell(row=2, column=colunas, value=sim)\n colunas += 1\n xx += 1\n elif conteudo.value == uniao and ponteirocont.value == \"NÃO\":\n nao += 1\n planilha.cell(row=1, column=xy, value= uniao)\n planilha.cell(row=3, column=colunan, value= nao)\n colunan += 1\n xy += 1\n print(sim)\n print(nao)\n\n#print(sim)\n#print(nao)\n#botando conteúdo\n#planilha.cell(row=1, column=4, value=\"Aluno 5\")\n#planilha.cell(row=8, column=4, value='SIM:')\n#planilha.cell(row=8, column=5, value= sim)\n#planilha.cell(row=9, column=4, value='NAO:')\n#planilha.cell(row=9, column=5, value= nao)\n#salvando na planilha\narquivo_excel.save(\"Aprendendoalerplanilhas.xlsx\")\nprint(conteudo.value)","sub_path":"Planilhas/02.py","file_name":"02.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"548477557","text":"import networkx as nx\nimport numpy as np\n#import matplotlib.pyplot as plt\nimport random\nimport pandas as pd\nimport math\nimport time\nimport multiprocessing\nimport datetime\nfrom collections import Counter\nfrom tqdm import tqdm\nimport array as arr\nimport copy\nfrom multiprocessing import Pool\nfrom itertools import repeat\nimport tqdm\n\nfilepathTXT = \"input/BlogCatalog-edgelist.txt\"\nfilepathCSV = \"input/BlogCatalog-edgelist.csv\"\n#embeddingsrecursive = \"../embeddings/BlogCatalog-edgelist.txt.embeddings-recursive\"\n#embeddingsiterative = \"../embeddings/BlogCatalog-edgelist.txt.embeddings-iterative\"\n\ndef toyGraph():\n G = nx.Graph()\n G.add_nodes_from([1,2,3,4,5,6,7,8,9,10,11])\n G.add_edge(2, 1);G.add_edge(3, 1); G.add_edge(3, 2); G.add_edge(4, 1)\n G.add_edge(4, 2);G.add_edge(4, 3);G.add_edge(5, 1); G.add_edge(6, 1)\n G.add_edge(7, 1);G.add_edge(7, 5);G.add_edge(7, 6); G.add_edge(8, 1)\n G.add_edge(8, 2);G.add_edge(8, 3);G.add_edge(8, 4); G.add_edge(9, 1)\n G.add_edge(9, 3);G.add_edge(10, 3);G.add_edge(11, 1); G.add_edge(11, 5)\n print(\"Nodes: \", G.number_of_nodes(),\" Edges: \", G.number_of_edges())\n # Draw graph\n # nx.draw(G, with_labels = True)\n # plt.show()\n return G\n\ndef parseEdgeList2(graph_file, direction=\"undirected\"):\n G = nx.Graph()\n colNames=[\"Start\", \"End\"]\n edgeData = pd.read_csv(filepathCSV, names=colNames)\n nodes = []\n for i in range (0, edgeData.shape[0]):\n nodes.append(edgeData.iloc[i,0])\n nodes.append(edgeData.iloc[i,1])\n nodes = set(nodes)\n uniqueNodes = (list(nodes))\n uniqueNodes.sort()\n G.add_nodes_from(uniqueNodes)\n edgeCount = 0\n for i in range (0, edgeData.shape[0]):\n edgeCount += 1\n G.add_edge(edgeData.iloc[i,0], edgeData.iloc[i,1])\n print(\"Nodes: \", G.number_of_nodes(),\" Edges: \", G.number_of_edges(), \" loaded from \", graph_file)\n if(direction == \"undirected\"):\n return G.to_undirected()\n else:\n return G\n\ndef getAdjNPList(graph):\n adjdict = {}\n for vertex in graph:\n adjdict[vertex] = np.array([n for n in G.neighbors(vertex)])\n np.random.shuffle(adjdict[vertex])\n return adjdict\n\ndef chooseNodes(list_nodes, sample_size):\n return random.sample(population=list_nodes, k=sample_size)\n\n\ndef getPerNodeBudget(numNodes, budget):\n return math.floor(budget / numNodes)\n\n\ndef storeContextPairs(context_pair, budget, context_pairs):\n if context_pair not in context_pairs:\n context_pairs[context_pair] = budget\n else:\n context_pairs[context_pair] = context_pairs[context_pair] + budget\n\n\ndef updateContextPairs(window, window_count, context_pairs):\n lastNode = window[window_count]\n labelOfLastNode, budgetOfLastNode = lastNode\n index_count = 0\n window_except_last = window[:window_count]\n window_reversed = window_except_last[::-1]\n for node in window_reversed:\n node_label = node[0]\n if index_count == ORIGINAL_WINDOW_SIZE:\n break\n context_pair1 = (labelOfLastNode, node_label)\n context_pairs.extend([context_pair1 for i in range(budgetOfLastNode)])\n #context_pairs.append(context_pair1)\n\n context_pair2 = (node_label, labelOfLastNode)\n context_pairs.extend([context_pair2 for i in range(budgetOfLastNode)])\n #context_pairs.append(context_pair2)\n\n index_count = index_count + 1\n return context_pairs\n\n\ndef addNewNodeToWindow(tempwindow, temp_window_count, window_size, vertex, budget):\n newWindowElement = np.array([[vertex,budget]])\n if temp_window_count+1 == window_size:\n tempwindow = tempwindow[1:]\n tempwindow[temp_window_count] = newWindowElement\n return tempwindow, temp_window_count\n\n tempwindow[temp_window_count+1] = newWindowElement\n temp_window_count+=1\n return tempwindow, temp_window_count\n\n\ndef BFSRandomWalkWindow(startvertex, adjdict):\n\n context_pairs = []\n\n window_count = 0\n WINDOW = np.zeros(shape=(WINDOW_SIZE + 20, 2), dtype=int)\n firstWindowElement = np.array([[startvertex, BUDGET]])\n WINDOW[window_count] = firstWindowElement\n\n queue_len = 0\n queue_pop_idx = 0\n queue_add_idx = 0\n queue = np.zeros(shape=(BUDGET, 5), dtype=object)\n firstQueueElement = np.array([[startvertex, BUDGET, 1, window_count, WINDOW]])\n queue[queue_len] = firstQueueElement\n queue_len += 1\n queue_add_idx += 1\n\n queue_buffer_size = (queue.size / 5) - 1\n\n while queue_len > 0:\n vertex, budget, current_walk_lenght, window_count, window = queue[queue_pop_idx]\n queue_len -= 1\n if queue_len > 0:\n if queue_pop_idx == queue_buffer_size:\n queue_pop_idx = 0\n else:\n queue_pop_idx += 1\n else:\n queue_add_idx = 0\n\n vertex_neighbors = adjdict[vertex]\n num_neighbors = vertex_neighbors.size\n per_node_budget = getPerNodeBudget(num_neighbors, budget)\n remainder = budget - (per_node_budget * num_neighbors)\n\n bonus = 0\n if remainder > 0:\n np.random.shuffle(vertex_neighbors)\n bonus = remainder\n\n current_walk_lenght += 1\n for neighbor in vertex_neighbors:\n\n budget_for_this_node = per_node_budget\n temp_window = np.copy(window)\n temp_window_count = window_count\n\n if bonus == 0 and budget_for_this_node == 0:\n break\n\n if bonus > 0:\n bonus -= 1\n budget_for_this_node += 1\n\n temp_window, temp_window_count = addNewNodeToWindow(temp_window, temp_window_count, WINDOW_SIZE, neighbor,\n budget_for_this_node)\n context_pairs = updateContextPairs(temp_window, temp_window_count, context_pairs)\n\n if current_walk_lenght < WALK_LENGHT:\n newQueueElement = np.array(\n [[neighbor, budget_for_this_node, current_walk_lenght, temp_window_count, temp_window]])\n queue[queue_add_idx] = newQueueElement\n queue_len += 1\n if queue_add_idx == queue_buffer_size:\n queue_add_idx = 0\n continue\n queue_add_idx += 1\n return context_pairs\n\n\n# Set the actual parameters and graph\nWALK_LENGHT = 40\nBUDGET = 1\nORIGINAL_WINDOW_SIZE = 10\n\n# Set toy parameters and graph\n#WALK_LENGHT = 3\n#BUDGET = 1\n#ORIGINAL_WINDOW_SIZE = 1\n\nWINDOW_SIZE = ORIGINAL_WINDOW_SIZE * 2 + 1\n\nif __name__ == '__main__':\n start = time.time()\n\n #Load Toy graph\n #G = toyGraph()\n #adjdict = getAdjNPList(G)\n\n #Load real graph\n print(\"Loading Data...\")\n G = parseEdgeList2(filepathCSV)\n adjdict = getAdjNPList(G)\n\n num_processors = multiprocessing.cpu_count()\n print(\"Running BFSRandomWalk...\")\n print(\"Walk lenght:\", WALK_LENGHT, \", Budget:\", BUDGET, \", Window size:\", ORIGINAL_WINDOW_SIZE, \", Workers:\",num_processors)\n p = Pool(processes=num_processors)\n nodes = [i for i in adjdict.keys()]\n contextPairs = p.starmap(BFSRandomWalkWindow, zip(nodes, repeat(adjdict)))\n\n total_count = 0\n for cp_set in contextPairs:\n total_count += len(cp_set)\n #print(\"Set lenght ->\", len(cp_set) )\n print(\"Total amount of context pairs :\", total_count)\n\n end = time.time()\n result = end - start\n print(\"The execution time ->\", str(datetime.timedelta(seconds=round(result))))\n p.terminate()\n\n\n\n\n\n","sub_path":"DeepWalk_Modified/approximate2.py","file_name":"approximate2.py","file_ext":"py","file_size_in_byte":7465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"334588552","text":"from flask_restful import Api\nfrom predict import Predict\nfrom example import run_request\nfrom flask import Flask, render_template, jsonify, request, redirect\nimport numpy as np\nimport pandas as pd\nimport requests\nimport os\nimport joblib\nimport json\nimport pickle\n\n# Create APP\napp = Flask(__name__)\nAPI = Api(app)\n\n# Load database\n# From prepared CSV files\n# Separate files for machine learning and other data due to data source limitations\ncyclone_data = pd.read_csv(\"data/Cyclone_1990_clean.csv\")\ncyclone_ml_data = pd.read_csv(\"data/Cyclone_ML.csv\")\n\n# Flask Routes\n\n# Add predict to route predict\nAPI.add_resource(Predict, '/predict')\n\n# create route that renders html pages\n@app.route(\"/\")\ndef home():\n return render_template(\"index.html\")\n\n@app.route(\"/plots\")\ndef plots():\n return render_template(\"plots.html\")\n\n@app.route(\"/api\")\ndef api():\n return render_template(\"api.html\")\n\n@app.route(\"/ml\", methods=[\"POST\",\"GET\"])\ndef ml():\n if request.method == 'POST':\n surface_code = request.form.get(\"surface_code\")\n cyclone_type = request.form.get(\"cyclone_type\")\n latitude = request.form.get(\"latitude\")\n longitude = request.form.get(\"longitude\")\n central_pressure = request.form.get(\"central_pressure\")\n max_wind_speed = request.form.get(\"max_wind_speed\")\n central_index = request.form.get(\"central_index\")\n wave_height = request.form.get(\"wave_height\")\n CYCLONE_MODEL_SVM = joblib.load('training/cyclone_SVM.smd')\n CYCLONE_MODEL_KNN = joblib.load('training/cyclone_KNN.smd')\n CYCLONE_MODEL_RF = joblib.load('training/cyclone_RF.smd')\n X_string =[surface_code,cyclone_type,latitude, longitude, central_pressure, max_wind_speed, central_index, wave_height]\n X_new=[float(x) for x in X_string]\n pred1 = CYCLONE_MODEL_SVM.predict([X_new])[0]\n pred2 = CYCLONE_MODEL_KNN.predict([X_new])[0]\n pred3 = CYCLONE_MODEL_RF.predict([X_new])[0]\n return render_template(\"ml.html\", out1=f\"Prediction for SVM = {pred1}\", out2=f\"Prediction for KNN = {pred2}\", out3=f\"Prediction for Random Forest = {pred3}\")\n else:\n return render_template(\"ml.html\")\n \n\n@app.route(\"/aboutus\")\ndef aboutus():\n return render_template(\"aboutus.html\")\n\n# Example prediction\n@app.route('/example')\ndef run_example():\n res = run_request()\n return res\n\n@app.route('/parameters/<surface_code>&<cyc_type>&<lat>&<lon>&<central_pres>&<max_wind_spd>&<central_index>&<wave_height>')\ndef get_prediction(surface_code=1, cyc_type=20, lat=-11, lon=92.6, central_pres=1001, max_wind_spd=12.9, central_index=2.064004808, wave_height=3.337484):\n url = 'http://127.0.0.1/predict'\n # url = 'https://et-cyclonesau.herokuapp.com/predict'\n body = {\n \"surface_code\": surface_code,\n \"cyc_type\": cyc_type,\n \"lat\": lat,\n \"lon\": lon,\n \"central_pres\" : central_pres,\n \"max_wind_spd\" : max_wind_spd,\n \"central_index\" : central_index,\n \"wave_height\" : wave_height\n }\n response = requests.post(url, data=body)\n return response.json()\n\n@app.route('/api/cyclones')\ndef cyclones():\n cyclone_json = cyclone_data.to_json(orient=\"records\")\n cyclone_json_parsed = json.loads(cyclone_json)\n cyclone_json_string = json.dumps(cyclone_json_parsed, indent=4) \n return cyclone_json_string\n\n@app.route('/api/mldata')\ndef mldata():\n ml_json = cyclone_ml_data.to_json(orient=\"records\")\n ml_json_parsed = json.loads(ml_json)\n ml_json_string = json.dumps(ml_json_parsed, indent=4) \n return ml_json_string\n\nif __name__ == '__main__':\n app.run(debug=True, port='80')\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"241465189","text":"from django.db import models\nfrom django.conf import settings\n# from django.template.defaultfilters import slugify\nfrom django.core.exceptions import ValidationError\nfrom django.contrib.auth.models import User\nfrom django.db.models.signals import ( post_save,pre_save )\nfrom django.dispatch import receiver\nfrom plots.utils import unique_slug_generator\n\n\nsale_type=((\"Rent\",\"Rent\"),\n\t(\"Sale\",\"Sale\"),\n\t(\"Lease\",\"Lease\"),\n\t)\n# Create your models here.\n\n\n#Email validator\ndef check_gmail(value):\n\tif \"@gmail.com\" in value:\n\t\treturn value\n\telse:\n\t\traise ValidationError(\"This field accepts only gmail\")\n\n# class Profile(models.Model):\n# \tname=models.OneToOneField(User, on_delete=models.CASCADE)\n# \temail=models.EmailField(max_length=100,validators=[check_gmail],default=\"abc@gmail.com\")\n# \tpassword1=models.CharField(max_length=14,default=\"******\")\n# \tbio = models.TextField(max_length=500, blank=True)\n# \tlocation = models.CharField(max_length=30, blank=True)\n# \tbirth_date = models.DateField(null=True, blank=True)\n\n# \tdef __str__(self):\n# \t\treturn self.name\n# \t@receiver(post_save, sender=User)\n# \tdef update_user_profile(sender, instance, created, **kwargs):\n# \t if created:\n# \t Profile.objects.create(user=instance)\n# \t instance.profile.save()\n\nclass Properties(models.Model):\n\ttitle=models.CharField(max_length=500,blank=False,null=False,default=\"No Title property\")\n\t# Name=models.ForeignKey(Profile,on_delete=models.CASCADE,related_name=\"property\",default=1)\n\tlocation=models.CharField(max_length=500, blank=False, null=False)\n\tdescription=models.TextField()\n\tcontact_num=models.CharField(max_length=10, blank=False, null=False)\n\tPrice=models.IntegerField(default=1)\n\tType=models.CharField(max_length=30)\n\tsale_type=models.CharField(max_length=30,choices=sale_type,default=\"Rent\")\n\tposted_on=models.DateTimeField(auto_now=True)\n\tupdated_on=models.DateTimeField(auto_now_add=True)\n\tslug=models.SlugField(max_length=255)\n\tImg=models.ImageField(upload_to=\"images/\", default=None)\n\n\tdef __str__(self):\n\t\treturn self.location\n\n\tdef get_description(self):\n\t\treturn self.description.split(',')\n\ndef rl_pre_save_receiver(sender,instance, *args, **kwargs):\n\tprint('saving...')\n\tprint(instance.posted_on)\n\tif not instance.slug:\n\t\tinstance.slug=unique_slug_generator(instance)\n\ndef rl_post_save_receiver(sender,instance, *args, **kwargs):\n\tprint('saved...')\n\tprint(instance.posted_on)\n\n\npre_save.connect(rl_pre_save_receiver, sender=Properties)","sub_path":"plots/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"350986717","text":"vocab = {}\r\n\r\ndef get_feature_vectors(x, binary=False):\r\n #Add more features here, if you want to!\r\n global vocab\r\n v_size = len(vocab)\r\n if binary:\r\n X = [get_binary_features(transform_data(ex), vocab_size=v_size) for ex in x]\r\n else:\r\n X = [get_frequency_features(transform_data(ex), vocab_size=v_size) for ex in x]\r\n return X\r\n\r\n\r\n\r\ndef transform_data(ex_str):\r\n global vocab\r\n ex_str = '<BOS> ' + ex_str.strip().lower() + ' <EOS>'\r\n ex_toks = []\r\n tokens = ex_str.split()\r\n for tok in tokens:\r\n if tok in vocab:\r\n ex_toks.append(vocab[tok])\r\n else:\r\n ex_toks.append(vocab['<oov>'])\r\n return ex_toks\r\n\r\ndef build_vocab(filepath, vocab_size=10000):\r\n global vocab\r\n vocab_dict = {}\r\n data = open(filepath + 'train.tsv', 'r').read().split('\\n')[1:]\r\n examples = [ex.split('\\t') for ex in data]\r\n for example in examples:\r\n if len(example) == 3:\r\n tokens = example[1].strip().lower().split()\r\n for tok in tokens:\r\n if tok in vocab_dict:\r\n vocab_dict[tok] += 1\r\n else:\r\n vocab_dict[tok] = 1\r\n vocab_list = []\r\n for tok in vocab_dict:\r\n vocab_list.append((tok, vocab_dict[tok]))\r\n freq_sorted_vocab = sorted(vocab_list, key=lambda x:x[1], reverse=True)\r\n pruned_vocab = freq_sorted_vocab[:vocab_size-3]\r\n vocab['<BOS>'] = 0 #beginning of the post token\r\n vocab['<EOS>'] = 1 #end of the post token\r\n vocab['<oov>'] = 2 #out-of-vocabulary token\r\n with open(filepath + 'vocab', 'w') as outfile:\r\n for i, tup in enumerate(pruned_vocab):\r\n outfile.write(tup[0] + '\\n')\r\n vocab[tup[0]] = i + 3","sub_path":"src/cs373-hw3/src/utils2.py","file_name":"utils2.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"168434718","text":"\"\"\"rest URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import include, path\nfrom rest_framework import routers\nfrom rest.api import views\n\nauthorView = views.AuthorView.as_view()\ntaxesView = views.TaxesView.as_view()\nnutrientsView = views.NutrientsView.as_view()\n\nrouter = routers.DefaultRouter()\nrouter.register(r'users', views.UserViewSet)\nrouter.register(r'groups', views.GroupViewSet)\n# router.register(r'authors', views.AuthorView, basename='authors')\nrouter.register(r'books', views.BookViewSet)\nrouter.register(r'states', views.StatesViewSet)\nrouter.register(r'countries', views.CountriesViewSet)\nrouter.register(r'food_stuff', views.FoodStuffViewSet)\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('api/', include(router.urls)),\n path('api/authors/', authorView),\n path('api/nutrients/', nutrientsView),\n path('api/taxes/', taxesView),\n path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n]\n\n","sub_path":"rest/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"587999089","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n # ex: /polls/\n url(r'^$', views.index, name='index'),\n url(r'^shouyin/$', views.shouyin, name='shouyin'),\n url(r'^ruku/$', views.ruku, name='ruku'),\n url(r'^get/txt/$', views.gettxt, name='gettxt'),\n]","sub_path":"dazuozhan/dzz/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"203178582","text":"\"\"\"\nCreate a function that returns the CSV representation of a two-dimensional numeric array.\n\nExample:\n\ninput:\n [[ 0, 1, 2, 3, 4 ],\n [ 10,11,12,13,14 ],\n [ 20,21,22,23,24 ],\n [ 30,31,32,33,34 ]] \n\noutput:\n '0,1,2,3,4\\n'\n +'10,11,12,13,14\\n'\n +'20,21,22,23,24\\n'\n +'30,31,32,33,34'\nArray's length > 2.\n\nMore details here: https://en.wikipedia.org/wiki/Comma-separated_values\n\"\"\"\ndef toCsvText(array) :\n s = \"\"\n for item in array:\n s += f\"{','.join([str(i) for i in item])}\\n\"\n return s[:-1]\n ","sub_path":"Python/8-KYU/CSV representation of array.py","file_name":"CSV representation of array.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"15602032","text":"#\n# --> Python 3.6.2 \n# --> WxPython Gui \n# --> wx01.py\n#\n\n# First App With OOP \nimport wx\n\nclass Window(wx.Frame):\n\n\tdef __init__(self,*k,**kw):\n\t\tsuper(Window,self).__init__(*k,**kw)\n\t\tself.panel = wx.Panel(self)\n\t\t\n\t\tlabel = wx.StaticText(self.panel,label=\"Hello World\")\n\n\n\napp = wx.App()\n# ^_^\nWindow(\n\tNone,\n\ttitle=\"Frame\",\n\tsize=(600,400),\n\tpos=(550,50)\n).Show()\n\napp.MainLoop()\n","sub_path":"wx02.py","file_name":"wx02.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"607349753","text":"from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport os\nimport json\nimport torch\nfrom utils.util import AttrDict\nfrom models.vocoder.fregan.generator import FreGAN\n\ngenerator = None # type: FreGAN\noutput_sample_rate = None\n_device = None\n\n\ndef load_checkpoint(filepath, device):\n assert os.path.isfile(filepath)\n print(\"Loading '{}'\".format(filepath))\n checkpoint_dict = torch.load(filepath, map_location=device)\n print(\"Complete.\")\n return checkpoint_dict\n\n\ndef load_model(weights_fpath, config_fpath=None, verbose=True):\n global generator, _device, output_sample_rate\n\n if verbose:\n print(\"Building fregan\")\n\n if config_fpath == None:\n model_config_fpaths = list(weights_fpath.parent.rglob(\"*.json\"))\n if len(model_config_fpaths) > 0:\n config_fpath = model_config_fpaths[0]\n else:\n config_fpath = \"./vocoder/fregan/config.json\"\n with open(config_fpath) as f:\n data = f.read()\n json_config = json.loads(data)\n h = AttrDict(json_config)\n output_sample_rate = h.sampling_rate\n torch.manual_seed(h.seed)\n\n if torch.cuda.is_available():\n # _model = _model.cuda()\n _device = torch.device('cuda')\n else:\n _device = torch.device('cpu')\n\n generator = FreGAN(h).to(_device)\n state_dict_g = load_checkpoint(\n weights_fpath, _device\n )\n generator.load_state_dict(state_dict_g['generator'])\n generator.eval()\n generator.remove_weight_norm()\n\n\ndef is_loaded():\n return generator is not None\n\n\ndef infer_waveform(mel, progress_callback=None):\n\n if generator is None:\n raise Exception(\"Please load fre-gan in memory before using it\")\n\n mel = torch.FloatTensor(mel).to(_device)\n mel = mel.unsqueeze(0)\n\n with torch.no_grad():\n y_g_hat = generator(mel)\n audio = y_g_hat.squeeze()\n audio = audio.cpu().numpy()\n\n return audio, output_sample_rate\n\n","sub_path":"models/vocoder/fregan/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"466818384","text":"#!/usr/bin/env python\n# -*- coding: iso-8859-1 -*-\n\n\nclass A():\n pass\n\nclass B():\n def __eq__(self, other):\n return True\n\nclass C():\n def __eq__(self, other):\n return False\n\n\ndef ejemplo(cls):\n elem1 = construct('elem1', cls)\n elem2 = construct('elem2', cls)\n print(\"Hacemos elem3 = elem1\")\n elem3 = elem1\n display(\"elem1 == elem2\", elem1 == elem2)\n display(\"elem1 == elem3\", elem1 == elem3)\n display(\"elem1 is elem2\", elem1 is elem2)\n display(\"elem1 is elem3\", elem1 is elem3)\n print(\"elem1: %r\" % elem1)\n print(\"elem2: %r\" % elem2)\n print(\"elem3: %r\" % elem3)\n print(\"\")\n\n\ndef construct(name, cls):\n print(\"Construimos %s = %s()\" % (name, cls.__name__))\n return cls()\n\ndef display(cadena, valor):\n print(\"%-12s: ? (pulsa ENTER para continuar) \" % cadena, end='')\n input()\n print(\" %4r\" % valor)\n\ndef main():\n ejemplo(A)\n ejemplo(B)\n ejemplo(C)\n\nif __name__ == '__main__':\n main()\n","sub_path":"tutorial/basicos/igualdad-identidad.py","file_name":"igualdad-identidad.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"380715847","text":"import unittest\nimport requests\nfrom tests.test_utils import *\nimport json\n\nclass TestCase1(unittest.TestCase):\n\n def test_a_edit_bleat(self):\n\n insert_test_data()\n\n payload = {'ID':13,'USER_ID':5,'BLEAT_CONTENT':\"game bro is a joke and we both know it.\"}\n\n put_rest_call(self, 'http://localhost:5000/edit/bleat', payload)\n\n http = 'http://localhost:5000/info/'+ str(13)\n\n value = get_rest_call(self, http)\n\n print(\"Question 1: \" + str(value))\n\n assert(\"game bro is a joke and we both know it.\" == value)\n\n def test_b_get_info(self):\n\n user = get_rest_call(self, 'http://localhost:5000/users/SansUndertale')\n\n print(\"Question 2: { Username: \" + str(user[0][1])+ \", Favorite Thing: \" + str(user[0][3])+ \", Email: \" + user[0][2])\n\n \n def test_c_edit_bleat(self):\n\n http = 'http://localhost:5000/info/'+ str(3)\n\n values = get_rest_call(self, http)\n\n bleat_text = values + \" ok, i will send someone over to fix it.\" \n\n payload = {'ID':3,'USER_ID':2,'BLEAT_CONTENT':bleat_text}\n\n put_rest_call(self, 'http://localhost:5000/edit/bleat', payload)\n\n value = get_rest_call(self, http)\n\n assert(bleat_text == value)\n\n print(\"Question 3:\" + value)\n \n def test_d_print_all_Jegbert(self):\n\n value = get_rest_call(self, 'http://localhost:5000/users/Jegbert/bleats')\n\n text = \"\"\n ints = 0\n\n for x in value :\n text += str(value[ints][2]) + \",\"\n ints += 1\n\n print(\"Question 4: \" + text)\n\n def test_e_print_all_SansUndertale(self):\n\n value = get_rest_call(self, 'http://localhost:5000/users/SansUndertale/bleats')\n\n text = \"\"\n ints = 0\n\n for x in value :\n text += str(value[ints][2]) + \",\"\n ints += 1\n\n print(\"Question 5: \" + text)\n\n def test_f_delete_bealts(self):\n\n delete_rest_call(self,'http://localhost:5000/delete/bleat?ID=8')\n delete_rest_call(self,'http://localhost:5000/delete/bleat?ID=9')\n\n print(\"Question 6: Deleting bleat id 9 and 8\")\n \n\n def test_g_check_delete(self):\n\n value = get_rest_call(self, 'http://localhost:5000/users/Boba/bleats')\n value2 = get_rest_call(self, 'http://localhost:5000/users/Jeffie/bleats')\n\n\n text = \"\"\n ints = 0\n\n for x in value :\n text += str(value[ints][2]) + \",\"\n ints += 1\n\n ints = 0\n for x in value2 :\n text += str(value[ints][2]) + \",\"\n ints += 1\n\n\n print(\"Question 7: \" + text)\n\n def test_h_add_bleat(self):\n\n bleat_text = 'No burg is complete without cheese'\n\n payload = {'ID':16,'USER_ID':1,'BLEAT_CONTENT':bleat_text}\n\n post_rest_call(self, 'http://localhost:5000/compose/bleat', payload)\n\n print('Question 8: Adding SarahZ bleat')\n\n def test_i_check_add(self):\n\n value = get_rest_call(self, 'http://localhost:5000/users/SarahZ/bleats')\n\n text = \"\"\n ints = 0\n\n for x in value :\n text += str(value[ints][2]) + \",\"\n ints += 1\n\n print(\"Question 9: \" + text)\n\n \n \n","sub_path":"swen-344-01-02-master/exam-2/tests/api/test_endpoints.py","file_name":"test_endpoints.py","file_ext":"py","file_size_in_byte":3183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"170064","text":"import shelve\nfrom flask import Flask, g\nfrom flask_restful import Resource, reqparse\n\napp = Flask(__name__)\n\nclass UserList(Resource):\n def get(self, cid):\n shelf = get_mem()\n \n if not (str(cid) in shelf):\n return {'message': 'No attendees', 'data': {}}, 404\n\n return {'message': 'Attendees', 'data': shelf[str(cid)]}, 200\n\n def post(self, cid):\n shelf = get_mem()\n \n previous = shelf[str(cid)] if str(cid) in shelf else {}\n \n parser = reqparse.RequestParser()\n parser.add_argument('firstName', required=True)\n parser.add_argument('lastName', required=True)\n parser.add_argument('email', required=True)\n\n # Parser arguments into obj\n args = parser.parse_args()\n\n if args['email'] in previous:\n return {'message': 'Email Already Exists', 'data': {}}, 409\n \n previous[args['email']] = args\n shelf[str(cid)] = previous\n #shelf[args['email']] = args\n\n return {'message': 'Attendee created', 'data': args}, 201, {'Location': '/users/' + args['email']}\n\n\nclass Users(Resource):\n def get(self, cid, email):\n shelf = get_mem()\n \n if not (str(cid) in shelf):\n return {'message': 'No attendees', 'data': {}}, 404\n\n if not (email in shelf[str(cid)]):\n return {'message': 'Attendee not found', 'data': {}}, 404\n\n return {'message': 'Attendee', 'data': shelf[str(cid)][email]}, 200\n\n def put(self, cid, email):\n shelf = get_mem()\n \n if not (str(cid) in shelf):\n return {'message': 'No attendees', 'data': {}}, 404\n\n if not (email in shelf[str(cid)]):\n return {'message': 'Attendee not found', 'data': {}}, 404\n\n parser = reqparse.RequestParser()\n parser.add_argument('firstName', required=True)\n parser.add_argument('lastName', required=True)\n parser.add_argument('email', required=True)\n\n # Parser arguments into obj\n args = parser.parse_args()\n\n if (args['email'] in shelf[str(cid)]) and (args['email'] != email):\n return {'message': 'Email Already Exists', 'data': {}}, 409\n\n #del shelf[str(cid)][email]\n previous = shelf[str(cid)]\n if args['email'] != email:\n del previous[email]\n previous[args['email']] = args\n else:\n previous[email] = args\n shelf[str(cid)] = previous\n #newHash = shelf[str(cid)]\n #del newHash[email]\n #shelf[str(cid)][args['email']] = args\n\n return {'message': 'Attendee updated successfully', 'data': args}, 202\n\n def patch(self, cid, email):\n shelf = get_mem()\n \n if not (str(cid) in shelf):\n return {'message': 'No attendees', 'data': {}}, 404\n\n if not (email in shelf[str(cid)]):\n return {'message': 'Attendee not found', 'data': {}}, 404\n\n parser = reqparse.RequestParser()\n parser.add_argument('firstName', required=False)\n parser.add_argument('lastName', required=False)\n parser.add_argument('email', required=False)\n\n args = parser.parse_args()\n\n user = shelf[str(cid)][email]\n previous = shelf[str(cid)]\n\n if not (args['firstName'] is None):\n user['firstName'] = args['firstName']\n\n if not (args['lastName'] is None):\n user['lastName'] = args['lastName']\n\n if not (args['email'] is None):\n user['email'] = args['email']\n \n if args['email'] in shelf[str(cid)]:\n return {'message': 'Email Already Exists', 'data': {}}, 409\n\n #del shelf[str(cid)][email]\n \n if not (args['email'] is None):\n #shelf[str(cid)][args['email']] = user\n del previous[email]\n previous[args['email']] = user\n \n else:\n #shelf[str(cid)][email] = user\n previous[email] = user\n \n shelf[str(cid)] = previous\n\n return {'message': 'Attendee updated successfully', 'data': user}, 202, {'Location': '/users/' + email}\n\n def delete(self, cid, email):\n shelf = get_mem()\n \n if not (str(cid) in shelf):\n return {'message': 'No attendees', 'data': {}}, 404\n\n if not (email in shelf[str(cid)]):\n return {'message': 'Attendee not found', 'data': {}}, 404\n\n newHash = shelf[str(cid)]\n del newHash[email]\n shelf[str(cid)] = newHash\n \n if not newHash:\n del shelf[str(cid)]\n\n return '', 204\n\n\ndef fill_start():\n shelf = get_db()\n test_user1 = \\\n {\n 'firstName': 'Seras',\n 'lastName': 'Meras',\n 'email': 'eskaferas@gmail.com'\n }\n test_user2 = \\\n {\n 'firstName': 'Oras',\n 'lastName': 'Moras',\n 'email': 'Soras@gmail.com'\n }\n\n if test_user1['email'] in shelf:\n return\n\n shelf[test_user1['email']] = test_user1\n shelf[test_user2['email']] = test_user2\n\n\ndef get_db():\n db = getattr(g, '_database', None)\n \n if db is None:\n db = g._database = shelve.open(\"conferences.db\")\n \n return db\n\ndef get_mem():\n db = getattr(g, '_members', None)\n \n if db is None:\n db = g._database = shelve.open(\"attendees.db\")\n \n return db\n\n\n@app.teardown_appcontext\ndef teardown_db(exception):\n db = getattr(g, '_database', None)\n \n if db is not None:\n db.close()\n \n db = getattr(g, '_members', None)\n \n if db is not None:\n db.close()\n","sub_path":"2/WebServices/Pirmas/User.py","file_name":"User.py","file_ext":"py","file_size_in_byte":5641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"93287199","text":"# -*- coding: utf-8 -*-\r\nimport numpy as np\r\nfrom Course1_3.planar_utils import sigmoid\r\n\r\n\r\ndef layer_size(X, Y):\r\n\t\"\"\"\r\n 参数:\r\n X - 输入数据集,维度为(输入的数量,训练/测试的数量)\r\n Y - 标签,维度为(输出的数量,训练/测试数量)\r\n\r\n 返回:\r\n n_x - 输入层的数量\r\n n_h - 隐藏层的数量\r\n n_y - 输出层的数量\r\n \"\"\"\r\n\tn_x = X.shape[0]\r\n\tn_h = 4 # 这里使用的隐藏层是4,hard code\r\n\tn_y = Y.shape[0]\r\n\treturn n_x, n_h, n_y\r\n\r\n\r\ndef initialize_parameters(n_x, n_h, n_y):\r\n\t\"\"\"\r\n\t参数:\r\n\t\tn_x - 输入层节点的数量\r\n\t\tn_h - 隐藏层节点的数量\r\n\t\tn_y - 输出层节点的数量\r\n\r\n\t返回:\r\n\t\tparameters - 包含参数的字典:\r\n\t\t\tW1 - 权重矩阵,维度为(n_h,n_x)\r\n\t\t\tb1 - 偏向量,维度为(n_h,1)\r\n\t\t\tW2 - 权重矩阵,维度为(n_y,n_h)\r\n\t\t\tb2 - 偏向量,维度为(n_y,1)\r\n\t\"\"\"\r\n\tnp.random.seed(2)\r\n\tW1 = np.random.randn(n_h, n_x) * 0.01 # 这里提前进行了转置\r\n\tb1 = np.zeros(shape=(n_h, 1))\r\n\tW2 = np.random.randn(n_y, n_h) * 0.01\r\n\tb2 = np.zeros(shape=(n_y, 1))\r\n\r\n\tassert (W1.shape == (n_h, n_x))\r\n\tassert (b1.shape == (n_h, 1))\r\n\tassert (W2.shape == (n_y, n_h))\r\n\tassert (b2.shape == (n_y, 1))\r\n\r\n\tparameters = {\"W1\": W1,\r\n\t \"b1\": b1,\r\n\t \"W2\": W2,\r\n\t \"b2\": b2}\r\n\r\n\treturn parameters\r\n\r\n\r\ndef forward_propagation(X, parameters):\r\n\t\"\"\"\r\n 参数:\r\n X - 维度为(n_x,m)的输入数据。\r\n parameters - 初始化函数(initialize_parameters)的输出\r\n\r\n 返回:\r\n A2 - 使用sigmoid()函数计算的第二次激活后的数值\r\n cache - 包含“Z1”,“A1”,“Z2”和“A2”的字典类型变量\r\n \"\"\"\r\n\tW1 = parameters[\"W1\"]\r\n\tb1 = parameters[\"b1\"]\r\n\tW2 = parameters[\"W2\"]\r\n\tb2 = parameters[\"b2\"]\r\n\t# 前向传播\r\n\tZ1 = np.dot(W1, X) + b1\r\n\tA1 = np.tanh(Z1)\r\n\tZ2 = np.dot(W2, A1) + b2\r\n\tA2 = sigmoid(Z2)\r\n\tassert (A2.shape == (1, X.shape[1]))\r\n\tcache = {\"Z1\": Z1,\r\n\t \"A1\": A1,\r\n\t \"Z2\": Z2,\r\n\t \"A2\": A2}\r\n\r\n\treturn A2, cache\r\n\r\n\r\ndef compute_cost(A2, Y):\r\n\t\"\"\"\r\n 计算交叉熵成本,\r\n\r\n 参数:\r\n A2 - 使用sigmoid()函数计算的第二次激活后的数值\r\n Y - \"True\"标签向量,维度为(1,数量)\r\n\r\n 返回:\r\n 成本 - 交叉熵成本\r\n \"\"\"\r\n\tm = Y.shape[1]\r\n\tlogprobs = np.multiply(Y, np.log(A2)) + np.multiply((1 - Y), np.log(1 - A2))\r\n\tcost = - np.sum(logprobs) / m\r\n\tcost = float(np.squeeze(cost))\r\n\treturn cost\r\n\r\n\r\ndef backward_propagation(parameters, cache, X, Y):\r\n\t\"\"\"\r\n 参数:\r\n parameters - 包含我们的参数的一个字典类型的变量。\r\n cache - 包含“Z1”,“A1”,“Z2”和“A2”的字典类型的变量。\r\n X - 输入数据,维度为(2,数量)\r\n Y - “True”标签,维度为(1,数量)\r\n\r\n 返回:\r\n grads - 包含W和b的导数一个字典类型的变量。\r\n \"\"\"\r\n\tm = X.shape[1]\r\n\tW1 = parameters[\"W1\"]\r\n\tW2 = parameters[\"W2\"]\r\n\tA1 = cache[\"A1\"]\r\n\tA2 = cache[\"A2\"]\r\n\r\n\tdZ2 = A2 - Y # sigmoid函数的导数\r\n\tdW2 = np.dot(dZ2, A1.T) / m\r\n\tdb2 = np.sum(dZ2, axis=1, keepdims=True) / m\r\n\tdZ1 = np.multiply(np.dot(W2.T, dZ2), 1 - np.power(A1, 2)) # tanh函数的导数是 1- x * x\r\n\tdW1 = np.dot(dZ1, X.T) / m\r\n\tdb1 = np.sum(dZ1, axis=1, keepdims=True) / m\r\n\tgrads = {\"dW1\": dW1,\r\n\t \"db1\": db1,\r\n\t \"dW2\": dW2,\r\n\t \"db2\": db2}\r\n\r\n\treturn grads\r\n\r\n\r\ndef update_parameters(parameters, grads, learning_rate=1.2):\r\n\t\"\"\"\r\n 参数:\r\n parameters - 包含参数的字典类型的变量。\r\n grads - 包含导数值的字典类型的变量。\r\n learning_rate - 学习速率\r\n\r\n 返回:\r\n parameters - 包含更新参数的字典类型的变量。\r\n \"\"\"\r\n\tW1, W2 = parameters[\"W1\"], parameters[\"W2\"]\r\n\tb1, b2 = parameters[\"b1\"], parameters[\"b2\"]\r\n\r\n\tdW1, dW2 = grads[\"dW1\"], grads[\"dW2\"]\r\n\tdb1, db2 = grads[\"db1\"], grads[\"db2\"]\r\n\r\n\tW1 = W1 - learning_rate * dW1\r\n\tb1 = b1 - learning_rate * db1\r\n\tW2 = W2 - learning_rate * dW2\r\n\tb2 = b2 - learning_rate * db2\r\n\r\n\tparameters = {\"W1\": W1,\r\n\t \"b1\": b1,\r\n\t \"W2\": W2,\r\n\t \"b2\": b2}\r\n\r\n\treturn parameters\r\n\r\n\r\ndef nn_model(X, Y, n_h, num_iterations, learning_rate=0.5, print_cost=False):\r\n\t\"\"\"\r\n 参数:\r\n X - 数据集,维度为(2,示例数)\r\n Y - 标签,维度为(1,示例数)\r\n n_h - 隐藏层的数量\r\n num_iterations - 梯度下降循环中的迭代次数\r\n learning_rate - 学习率\r\n print_cost - 如果为True,则每1000次迭代打印一次成本数值\r\n\r\n 返回:\r\n parameters - 模型学习的参数,它们可以用来进行预测。\r\n \"\"\"\r\n\tnp.random.seed(3)\r\n\tn_x, _, n_y = layer_size(X, Y)\r\n\tparameters = initialize_parameters(n_x, n_h, n_y)\r\n\r\n\tfor i in range(num_iterations):\r\n\t\tA2, cache = forward_propagation(X, parameters)\r\n\t\tcost = compute_cost(A2, Y)\r\n\t\tgrads = backward_propagation(parameters, cache, X, Y)\r\n\t\tparameters = update_parameters(parameters, grads, learning_rate)\r\n\r\n\t\tif print_cost:\r\n\t\t\tif i % 1000 == 0:\r\n\t\t\t\tprint(\"第 \", i, \" 次循环,成本为:\" + str(cost))\r\n\treturn parameters\r\n\r\ndef predict(parameters, X):\r\n\t\"\"\"\r\n\t使用model返回的parameters进行预测\r\n\t参数:\r\n\t\tparameters - 包含参数的字典类型的变量。\r\n\t X - 输入数据(n_x,m)\r\n\r\n 返回\r\n\t\tpredictions - 我们模型预测的向量(红色:0 /蓝色:1)\r\n\t\"\"\"\r\n\tA2, cache = forward_propagation(X, parameters)\r\n\tpredictions = np.round(A2) # 以0.5为界区分2分类\r\n\r\n\treturn predictions\r\n","sub_path":"Course1_3/nn_helper.py","file_name":"nn_helper.py","file_ext":"py","file_size_in_byte":5683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"452957026","text":"'''\n(Optional) \nWrite a function that combines several dictionaries \nby creating a new dictionary with all the keys of the original ones. \nIf a key appears in more than one input dictionary, \nthe value corresponding to that key in the new dictionary should be a list \ncontaining all the values encountered in the input dictionaries that correspond to that key.\n'''\n\ndef combine_dict(*args):\n # prepare the empty dictionary that will store the output elements\n dict = {}\n\n # loop\n for i in args: # loop in each dictionary in *args\n for j in i.items(): # loop in each key and value in the dictionary\n k = j[0] # value\n v = j[1] # key\n if k not in dict.keys(): # if the key is the first occurrence, simply add to the output\n dict[k] = v \n else: # when the key is already in the output\n try: # if the values of the key is list, append the additional value\n dict[k].append(v)\n except AttributeError: # if the valus is not list, we cannot use append method\n dict[k] = [dict[k], v] \n \n # return the output\n return dict\n\n\n# sample dictionaries \nx = {'Apple': 2, 'Banana': 3, 'Cherry': 1}\ny = {'Banana': 4, 'Cantaloupe': 2}\nz = {'Banana': 3, 'Cherry': 2, 'Melon': 5, 'Orange': 1}\n\n# use the function\ncombine_dict(x, y, z)","sub_path":"Module_6/Daisuke_X442.3_Assignment_6_5.py","file_name":"Daisuke_X442.3_Assignment_6_5.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"424110481","text":"\n\"\"\"\nRicky Cheah\n3/11/2020\n\nThis is a driver program to test __contains__ and remove methods in ArrayBag.\n\"\"\"\n\nfrom arraybag import ArrayBag\n\ndef main():\n bag1 = ArrayBag([1,2,3,4,5,6])\n\n print(\"bag1 is\", bag1)\n\n bag2 = ArrayBag([7, 8, 9, 10, 11])\n print(\"bag2 is\", bag2)\n \n bag1 = bag1 + bag2\n print(\"bag1 after bag1 + bag2 =\", bag1, \"length =\", len(bag1))\n \n sep()\n \n for number in range(1,12):\n if number in bag1:\n bag1.remove(number)\n \n print(\"bag1 after removing every number in range(1,12) =\", bag1, \"length =\", (len(bag1)))\n bag1.remove(0)\n \ndef sep():\n print(\"_\"*60)\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"csc242/Lab5_Option1_Cheah/Lab5_Option1_Cheah.py","file_name":"Lab5_Option1_Cheah.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"489452534","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nfrom tkinter import * # 导入 Tkinter 库\n\nfrom img_read import wxsc_main\nfrom name import is_dish_name\nfrom PIL import Image, ImageTk\n\nroot = Tk() # 创建窗口对象的背景色\nroot.geometry()\n# 创建两个列表\nli = []\nw = Entry(root,width = 40)\n\nroot.title(\"闻香识菜\")\nlistb = Listbox(root,height = 5,width = 40)\n\ndef ver():\n dir = w.get() #获取文本框内容\n listb.insert(0,\"正在识别...\")\n\n flag = wxsc_main(dir)\n name = is_dish_name(flag)\n #listb.insert(1,\"正在识别2\")\n listb.insert(1,name)\n\n\nbut = Button(root,\n height = 2,width = 12 ,text=\"识别\",command=ver)\nlistb.pack() # 将小部件放置到主窗口中\nw.pack()\nbut.pack()\n\n\nroot.mainloop() # 进入消息循环","sub_path":"ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"563751615","text":"\"\"\"\nIt contains functions to support the creation of gene correlation matrices.\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom statsmodels.stats.correlation_tools import corr_nearest\nfrom IPython.display import display\n\n\ndef check_pos_def(matrix: pd.DataFrame, debug_messages: bool = True):\n \"\"\"\n Checks that a correlation matrix is positive definite.\n \"\"\"\n # show nonpositive eigenvalues\n if debug_messages:\n eigs = np.linalg.eigvals(matrix.to_numpy())\n neg_eigs = eigs[eigs <= 0]\n display(f\"Number of negative eigenvalues: {len(neg_eigs)}\")\n display(f\"Negative eigenvalues:\\n{neg_eigs}\")\n\n def _print(message):\n if debug_messages:\n print(message)\n\n # check what statsmodels.GLS expects\n try:\n # decomposition used by statsmodels.GLS\n np.linalg.cholesky(np.linalg.inv(matrix.to_numpy())).T\n _print(\"Works! (statsmodels.GLS)\")\n except Exception as e:\n _print(f\"Cholesky decomposition failed (statsmodels.GLS): {str(e)}\")\n\n # check\n CHOL_DECOMPOSITION_WORKED = None\n\n try:\n np.linalg.inv(np.linalg.cholesky(matrix.to_numpy()))\n _print(\"Works!\")\n CHOL_DECOMPOSITION_WORKED = True\n except Exception as e:\n _print(f\"Cholesky decomposition failed: {str(e)}\")\n CHOL_DECOMPOSITION_WORKED = False\n\n return CHOL_DECOMPOSITION_WORKED\n\n\ndef correct_corr_mat(corr_mat: pd.DataFrame, threshold):\n \"\"\"\n If necessary, it fixes a correlation matrix using its eigenvalues. The approach uses this function:\n\n https://www.statsmodels.org/dev/generated/statsmodels.stats.correlation_tools.corr_nearest.html\n\n However, it could be slow in some cases. An alternative implementation is commented out below (read\n details below).\n\n It always returns a numpy array.\n \"\"\"\n\n if check_pos_def(corr_mat, debug_messages=False):\n return corr_mat.to_numpy()\n\n return corr_nearest(corr_mat, threshold=threshold, n_fact=100)\n\n # commented out below there is a manual method that is faster and computes the\n # eigenvalues only once; it should be equivalent to the function corr_clipped from statsmodels.\n # Compared to corr_neareast, the difference with the original correlation matrix is larger with\n # the implementation below\n #\n # eigvals, eigvects = np.linalg.eigh(corr_mat)\n # eigvals = np.maximum(eigvals, threshold)\n # corr_mat_fixed = eigvects @ np.diag(eigvals) @ eigvects.T\n # return corr_mat_fixed\n\n\ndef adjust_non_pos_def(matrix, threshold=1e-15):\n \"\"\"\n It is the same as correct_corr_mat, but it returns a dataframe with the same\n row and columns as the original matrix.\n \"\"\"\n matrix_fixed = correct_corr_mat(matrix, threshold)\n\n return pd.DataFrame(\n matrix_fixed,\n index=matrix.index.copy(),\n columns=matrix.columns.copy(),\n )\n\n\ndef compare_matrices(matrix1, matrix2, check_max=1e-10):\n \"\"\"\n Compares two matrices of the same dimension and returns the differences.\n It is used to compare how different is the original correlation matrix from\n the corrected one.\n \"\"\"\n _diff = (matrix1 - matrix2).unstack()\n display(_diff.describe())\n display(_diff.sort_values())\n\n if check_max is not None:\n assert _diff.abs().max() < check_max, \"Difference is larger than threshold\"\n\n return _diff\n","sub_path":"libs/correlations.py","file_name":"correlations.py","file_ext":"py","file_size_in_byte":3361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"472315461","text":"import os\nfrom typing import List\n\n\ndef main():\n\tif(os.path.isdir('dist')):\n\t\tos.chdir('dist')\n\t\tfiles: List[str] = list()\n\n\t\tcombinedDFName: str = 'combined'\n\t\toutFileName: str = 'all.json'\n\n\t\tfor dir in os.listdir('.'):\n\t\t\tif os.path.isdir(dir):\n\t\t\t\tos.chdir(dir)\n\t\t\t\tif os.path.isdir(combinedDFName):\n\t\t\t\t\tos.chdir(combinedDFName)\n\t\t\t\t\tif os.path.exists(combinedDFName + '.json'):\n\t\t\t\t\t\tfiles.append(os.path.join(os.getcwd(), combinedDFName + '.json'))\n\t\t\t\t\t\tprint('Found ' + combinedDFName + '.json for: ' + dir)\n\t\t\t\t\tos.chdir('..')\t\t\n\t\t\t\tos.chdir('..')\n\n\t\twith open(outFileName, 'w') as outFile:\n\t\t\toutFile.write('{\"canteens\": [\\n')\n\t\t\tfor i, f in enumerate(files):\n\t\t\t\twith open(f) as inFile:\n\t\t\t\t\tfor line in inFile:\n\t\t\t\t\t\toutFile.write(line)\n\t\t\t\t\tif i < len(files) -1:\n\t\t\t\t\t\toutFile.write(',')\n\t\t\toutFile.write(']}')\n\nif __name__ == \"__main__\":\n main()","sub_path":"scripts/combine.py","file_name":"combine.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"183362559","text":"#!/usr/bin/env python3\n\n'''\nservice account from raspberries.sirrisdiepenbeek2@gmail.com\nsending through google-api-python-client\nto spreadsheet in google drive from abovementioned google account.\n'''\n\nimport os\nimport sys\nimport math\nimport time\nfrom oauth2client.service_account import ServiceAccountCredentials\nfrom httplib2 import Http\nfrom googleapiclient.discovery import build\n\nscopes = ['https://spreadsheets.google.com/feeds']\ncredentials = ServiceAccountCredentials.from_json_keyfile_name('/home/jan/klima2_Grpi_secret.json', scopes=scopes)\nspreadsheetID = '1fJ5-2CCK3b5yTaENa4srdhkgqqIhx8pj9psYG9SijFo'\nhttp_auth = credentials.authorize(Http())\nservice = build('sheets', 'v4', http=http_auth)\n\n# reading from a spreadsheet just to see whether communication works\nresult = service.spreadsheets().values().get(\n spreadsheetId=spreadsheetID,\n range='b1:b3').execute()\nprint(result)\n\ndef add_row_to_google_sheet():\n # request to add one Row at the end of the spreadsheet\n requests = [{\n \"appendDimension\": {\n \"sheetId\": 0,\n \"dimension\": \"ROWS\",\n \"length\": 1}}]\n body = {\"requests\": requests}\n response = service.spreadsheets().batchUpdate(spreadsheetId=spreadsheetID, body=body).execute()\n\ndef add_variable_to_google_sheet(values):\n result = service.spreadsheets().values().append(\n spreadsheetId=spreadsheetID, valueInputOption='RAW', range='a2:b2', body=values).execute()\n\ndef create_sine_variable():\n sine_variables=[]\n for x in range(0, 359):\n weight = math.sin(math.radians(x))*100 # create sine shaped variable in time\n sine_variables.append(weight)\n return sine_variables\n\n# service.spreadsheets().sheets().copyTo(spreadsheetId='1BiuNIMDZ3hCJxhVDoHtK-HbSXcYHDBVPMxNxIfF_qyE')\n# service.spreadsheets().sheets().duplicateActiveSheet()\n\ndef get_cpu_temperature():\n # Return CPU temperature as a character string\n res = os.popen('vcgencmd measure_temp').readline()\n return(float(res.replace(\"temp=\",\"\").replace(\"'C\\n\",\"\")))\n\ndef main():\n while 1:\n #create sine variable\n # result=create_sine_variable()\n # for i in range (0, len(result)):\n # this_value = result[i]\n # this_time = time.strftime('%m/%d/%Y %H:%M:%S')\n # this_value_pair = [[this_time, this_value]]\n # add_row_to_google_sheet()\n # values = {'values': this_value_pair}\n # add_variable_to_google_sheet(values)\n # print(values)\n # time.sleep(5)\n\n this_value = get_cpu_temperature()\n this_time = time.strftime('%d/%m/%Y %H:%M:%S')\n this_value_pair = [[this_time, \"\", this_value]]\n add_row_to_google_sheet()\n values = {'values': this_value_pair}\n add_variable_to_google_sheet(values)\n print(values)\n time.sleep(60)\n\n\nif __name__ == \"__main__\":\n main()\n sys.exit(0)\n","sub_path":"cpu_temp_toGoogle_rpi.py","file_name":"cpu_temp_toGoogle_rpi.py","file_ext":"py","file_size_in_byte":2908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"134427547","text":"from django.db import IntegrityError\r\nfrom django import forms\r\nfrom django.contrib.auth.models import User\r\nfrom contacts.models import Account,ResellerAccount,ResellerContact\r\nfrom quotes.models import UseCase\r\nimport pandas as pd\r\n\r\nclass AccountForm(forms.ModelForm):\r\n def __init__(self,*args,**kwargs):\r\n self.user = kwargs.pop('user')\r\n super (AccountForm,self ).__init__(*args,**kwargs) # populates the post\r\n self.fields['use_case'].queryset = UseCase.objects.filter(profile_selected_use_case=self.user.profile)\r\n\r\n class Meta:\r\n model = Account\r\n fields = '__all__'\r\n\r\ndef process_data(account_file,contact_file):\r\n account_df = pd.read_csv(account_file, na_filter=False)\r\n account_df['lower_Company'] = account_df['Company'].str.lower()\r\n account_df = account_df.sort_values('PartnerId').drop_duplicates(subset='lower_Company', keep='last')\r\n contact_df = pd.read_csv(contact_file, na_filter=False)\r\n contact_df = contact_df[contact_df['Status'] == 'Active']\r\n required_account_columns = set(['PartnerId',\r\n 'Company',\r\n 'SalesRepEmail',\r\n 'ChannelSpecialist',\r\n 'DistributorNumbers',\r\n 'PartnerType',\r\n 'PartnerLevel'\r\n ])\r\n required_contact_columns = set(['InternalId',\r\n 'PartnerId',\r\n 'Status',\r\n 'Email',\r\n 'FirstName',\r\n 'LastName'\r\n ])\r\n if not required_account_columns.issubset(set(list(account_df))):\r\n return 'Account headers must contain PartnerId, Company, SalesRepEmail, ChannelSpecialist ,DistributorNumbers, PartnerType, PartnerLevel'\r\n if not required_contact_columns.issubset(set(list(contact_df))):\r\n return 'Contact headers must contain InternalId, PartnerId, Status, Email, FirstName, LastName'\r\n \r\n for row in account_df.itertuples():\r\n account_isr = User.objects.filter(email=row.SalesRepEmail).first()\r\n if len(row.ChannelSpecialist.split(' ',1))==2:\r\n pdm_first_name,pdm_last_name = row.ChannelSpecialist.split(' ',1)\r\n else:\r\n pdm_first_name,pdm_last_name = '',''\r\n account_pdm = User.objects.filter(first_name=pdm_first_name,last_name=pdm_last_name).first()\r\n obj, created = ResellerAccount.objects.update_or_create(\r\n id = row.PartnerId,\r\n defaults = {\r\n 'name':row.Company,\r\n 'account_number':row.DistributorNumbers,\r\n 'isr':account_isr,\r\n 'pdm':account_pdm,\r\n 'partner_type':row.PartnerType,\r\n 'partner_level':row.PartnerLevel\r\n }\r\n )\r\n for row in contact_df.itertuples():\r\n reseller = ResellerAccount.objects.filter(id=row.PartnerId).first()\r\n if reseller:\r\n obj, created = ResellerContact.objects.update_or_create(\r\n id = row.InternalId,\r\n defaults = {\r\n 'reseller_account':reseller,\r\n 'first_name':row.FirstName,\r\n 'last_name':row.LastName,\r\n 'email':row.Email\r\n }\r\n )\r\n \r\nclass ResellerUploadForm(forms.Form):\r\n reseller_account_file = forms.FileField()\r\n reseller_contact_file = forms.FileField()\r\n\r\nclass IsrUpdateForm(forms.Form):\r\n queryset=User.objects.filter(groups__name='ISR').order_by('first_name')\r\n current = forms.ModelChoiceField(queryset=queryset)\r\n replaced_by = forms.ModelChoiceField(queryset=queryset)\r\n\r\nclass PdmUpdateForm(forms.Form):\r\n queryset=User.objects.filter(groups__name='PDM').order_by('first_name')\r\n current = forms.ModelChoiceField(queryset=queryset)\r\n replaced_by = forms.ModelChoiceField(queryset=queryset)","sub_path":"contacts/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"213621390","text":"\nimport os\nimport re\nimport time\nimport datetime\nfrom providers import Provider\nimport logging\nfrom subprocess import Popen, PIPE\n\n\nclass VolumeProvider(Provider):\n def __init__(self, config):\n self.name = \"volume\"\n self.setup(config)\n self.VOLUME_ICON = os.path.join(self.config['options']['icon_path'], 'volume.xbm')\n self.MUTED_FG = '#C47A7A'\n self.UNMUTED_FG = '#80C47A'\n self.NEUTRAL_FG = 'white'\n\n def status(self):\n response = Popen([\"amixer\", \"get\", \"Master\"], stdout=PIPE).communicate()[0].split('\\n')\n response = filter(lambda x: 'Playback' in x, response)\n\n limit = 65536.0\n\n for item in response:\n if 'Limits' in item:\n limit = float(item.split(' ')[-1])\n break\n\n vol = response[-1]\n matches = re.search(r' (\\d+) ', vol)\n level = float(matches.group(0)) if hasattr(matches, 'group') else 0\n\n muted = True if '[off]' in vol else False\n\n level = int((level / limit) * 100.0)\n\n return (level, muted)\n\n def update(self):\n (level, muted) = self.status()\n fg_color = self.MUTED_FG if muted else self.UNMUTED_FG\n\n indicator = ''\n for x in range(1, 10):\n max_level = x * 10\n indicate = '|' if not muted else 'x'\n if level >= max_level:\n indicator = indicator + indicate\n else:\n indicator = indicator + '^fg(%s)-' % self.NEUTRAL_FG\n\n return '^fg(%s)%s^i(%s)%s\\n' % (fg_color, level, self.VOLUME_ICON, indicator)\n\ndef init(configs):\n return VolumeProvider(configs)\n\n\n","sub_path":"providers/volume.py","file_name":"volume.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"523523480","text":"def search (nums,target):\n L = 0\n R = len(nums) - 1\n\n while L <= R:\n mid = (L + R) // 2\n if (nums[mid] == target):\n return mid\n if (target < nums[0]) == (nums[mid] < nums[0]):\n num = nums[mid]\n else:\n if (target < nums[0]):\n num = -float('inf')\n else:\n num = float('inf')\n \n if target > num:\n L = mid + 1\n elif target < num:\n R = mid - 1\n else:\n return mid\n return -1\n\nnums = [3]\ntarget = 1\nprint(search(nums,target))","sub_path":"Array/33_Search_in_Rotated_Sorted_Array/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"274936257","text":"import json\n\nfrom apps.workspaces.models import Workspace\nfrom tests.helper import dict_compare_keys\nfrom tests.test_workspaces.test_apis.test_advanced_config.fixtures import data\n\n\ndef test_advanced_config(api_client, test_connection):\n\n workspace = Workspace.objects.get(id=3)\n workspace.onboarding_state = 'ADVANCED_CONFIGURATION'\n workspace.save()\n\n url = '/api/v2/workspaces/3/advanced_configurations/'\n api_client.credentials(HTTP_AUTHORIZATION='Bearer {}'.format(test_connection.access_token))\n\n response = api_client.put(url, data=data['advanced_config'], format='json')\n\n assert response.status_code == 200\n\n response = json.loads(response.content)\n assert dict_compare_keys(response, data['response']) == [], 'workspaces api returns a diff in the keys'\n\n response = api_client.put(url, data={'general_mappings': {}}, format='json')\n\n assert response.status_code == 400\n\n response = api_client.put(url, data={'workspace_general_settings': {}}, format='json')\n\n assert response.status_code == 400\n\n response = api_client.put(url, data={'workspace_schedules': {}}, format='json')\n\n assert response.status_code == 400\n","sub_path":"tests/test_workspaces/test_apis/test_advanced_config/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"67037284","text":"# Initialize a model and data loaders\nkwargs = {'num_workers': 1, 'pin_memory': True} if cuda else {}\ntrain_loader = torch.utils.data.DataLoader(\n datasets.MNIST('../data', train=True, download=True,\n transform=transforms.ToTensor()),\n batch_size=batch_size, shuffle=True, **kwargs)\ntest_loader = torch.utils.data.DataLoader(\n datasets.MNIST('../data', train=False, transform=transforms.ToTensor()),\n batch_size=test_batch_size, shuffle=True, **kwargs)\n\ndevice = torch.device('cuda')\nmodel = mnist1_model().to(device)\n\n# Call the training shenanigans\nif torch.cuda.is_available(): \n print(\"Training on GPU\")\n logging.info(\"Training on GPU\")\n\nos.makedirs(f'{model_type}_{data_name}_K{K}_M{batch_size}',exist_ok=True)\nos.makedirs(f'{model_type}_{data_name}_K{K}_M{batch_size}/samples',exist_ok=True)\nos.makedirs(f'{model_type}_{data_name}_K{K}_M{batch_size}/recons',exist_ok=True)\n\nprint(datetime.datetime.now())\nlogging.info(datetime.datetime.now())\nfor r in range(num_rounds+1):\n current_round_lr = learning_rate*(10**(-r/7))\n optimizer = optim.Adam(model.parameters(), lr=current_round_lr)\n print(f\"====== About to train for {3**r} epochs in round {r} with learning rate {round(current_round_lr,7)}========\")\n logging.info(f\"====== About to train for {3**r} epochs in round {r} with learning rate {round(current_round_lr,7)}========\")\n for epoch in range(3**r):\n train(r,epoch,optimizer)\n with open(f'{model_type}_{data_name}_K{K}_M{batch_size}/{model_type}_{data_name}_K{K}_M{batch_size}.pt','wb') as f:\n print(datetime.datetime.now())\n logging.info(datetime.datetime.now())\n torch.save(model,f)\n\n \n _test(r,epoch)\n with torch.no_grad():\n sample = torch.randn(64, 50).to(device)\n sample = model.decode(sample,test=True).cpu()\n save_image(sample.view(64, 1, 28, 28),\n f'{model_type}_{data_name}_K{K}_M{batch_size}/samples/sample_' +str(r)+'_'+ str(epoch) + '.png')\n \n_test(r,epoch)\nwith open(f'{model_type}_{data_name}_K{K}_M{batch_size}/{model_type}_{data_name}_K{K}_M{batch_size}_{r}_{epoch}.pt','wb') as f:\n print(datetime.datetime.now())\n logging.info(datetime.datetime.now())\n torch.save(model,f)\nprint(\"Training finished\")\nlogging.info(\"Training finished\")\n","sub_path":"experiments/exact_replication/mnist/iwae_mnist_L1_K5_M20/runtime.py","file_name":"runtime.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"121265577","text":"from gi.repository import Gtk, Gio, Gdk, GtkSource\nimport models\n\n\ndef button_factory(icon_name=None):\n button = Gtk.Button()\n icon = Gio.ThemedIcon(name=icon_name)\n image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)\n button.add(image)\n button.show_all()\n return button\n\n\nclass MainWindow(Gtk.Window):\n def __init__(self, app):\n self.app = app\n self.paned, self.notebook, self.headerbar, = None, None, None\n super().__init__(title=\"gSqueal\")\n self.add_main_paned()\n self.add_notebook()\n self.add_headerbar()\n\n def add_main_paned(self):\n self.paned = Gtk.Paned()\n self.paned.set_orientation(Gtk.Orientation.HORIZONTAL)\n self.paned.set_position(400)\n self.paned.set_wide_handle(True)\n self.add(self.paned)\n\n def add_left(self, thing):\n if self.paned.get_child1() is not None:\n self.paned.get_child1().destroy()\n\n self.paned.add1(thing)\n\n def add_notebook(self):\n self.notebook = Notebook(self.app)\n self.paned.add2(self.notebook)\n\n def add_headerbar(self):\n self.headerbar = Gtk.HeaderBar()\n self.headerbar.set_show_close_button(True)\n self.headerbar.set_title(\"gSqueal\")\n self.set_titlebar(self.headerbar)\n\n button = Gtk.Button()\n icon = Gio.ThemedIcon(name=\"open-menu-symbolic\")\n image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)\n button.add(image)\n self.headerbar.pack_end(button)\n\n\nclass Notebook(Gtk.Notebook):\n def __init__(self, app):\n self.app = app\n self.button_box = Gtk.Box()\n self.add_button = button_factory(\"list-add-symbolic\")\n self.connection_page = None\n self.database_page = None\n self.table_page = None\n self.table_data_page = None\n self.positions = {\"connection\": 1, \"database\": 2, \"table\": 3, \"table_data\": 4}\n\n super().__init__()\n\n self.set_property(\"scrollable\", True)\n self.add_buttons()\n self.show_all()\n\n def add_buttons(self):\n self.add_button.set_relief(Gtk.ReliefStyle.NONE)\n\n self.button_box.pack_end(self.add_button, True, True, 0)\n self.button_box.show_all()\n\n self.add_button.connect(\"clicked\", self.app.add_query_page)\n self.set_action_widget(self.button_box, Gtk.PackType.END)\n\n def add_page(self, thing, text=None, reorderable=True, closeable=True, position=None):\n box = Gtk.Box()\n label = Gtk.Label(text)\n thing.remove_me = lambda button: self.remove_page(self.child_get_property(thing, \"position\"))\n\n if closeable:\n button = button_factory(\"window-close-symbolic\")\n box.pack_end(button, True, True, 0)\n\n box.pack_end(label, True, True, 0)\n box.show_all()\n\n if type(position) is int:\n index = self.insert_page(thing, box, position)\n else:\n index = self.append_page(thing, box)\n\n if index > -1 and closeable:\n button.connect(\"clicked\", thing.remove_me)\n\n self.set_tab_reorderable(thing, reorderable)\n self.show_all()\n\n def set_table_data_page(self, thing, table):\n if isinstance(self.table_data_page, DataGrid):\n self.table_data_page.destroy()\n\n self.add_page(thing, text=\"Data [\" + table + \"]\",\n reorderable=False, closeable=False, position=self.positions['table_data'])\n\n\nclass QueryPage(Gtk.Paned):\n def __init__(self, app):\n self.app = app\n super().__init__()\n self.set_orientation(Gtk.Orientation.VERTICAL)\n self.set_position(200)\n\n self.window_top = Gtk.ScrolledWindow()\n self.window_bottom = Gtk.ScrolledWindow()\n\n self.add1(self.window_top)\n self.add2(self.window_bottom)\n\n self.add_query_box()\n self.add_datagrid()\n\n def add_query_box(self):\n lang_man = GtkSource.LanguageManager()\n lang = lang_man.get_language(\"sql\")\n\n src_buf = GtkSource.Buffer()\n src_buf.set_language(lang)\n\n box = GtkSource.View()\n box.set_buffer(src_buf)\n box.set_monospace(True)\n box.set_left_margin(5)\n box.set_right_margin(5)\n box.set_wrap_mode(Gtk.WrapMode.WORD)\n\n if len(self.window_top.get_children()) > 0:\n for child in self.window_top.get_children():\n child.destroy()\n\n self.window_top.add(box)\n\n def add_datagrid(self, data=None):\n if len(self.window_bottom.get_children()) > 0:\n for child in self.window_bottom.get_children():\n child.destroy()\n\n grid = DataGrid(self.app, data)\n self.window_bottom.add(grid)\n\n\nclass ConnectionList(Gtk.TreeView):\n def __init__(self, app, connections=None):\n self.data_models = {}\n self.app = app\n\n super().__init__()\n self.store = Gtk.TreeStore(str)\n self.set_model(self.store)\n\n if connections is not None:\n for connection in connections:\n self.add_connection(connection)\n\n conn_col = Gtk.TreeViewColumn(\"Connections\", Gtk.CellRendererText(), text=0)\n conn_col.set_sort_column_id(0)\n self.append_column(conn_col)\n\n self.select = self.get_selection()\n self.select.connect(\"changed\", self.row_clicked)\n\n def add_connection(self, connection):\n conniter = self.get_model().append(None, [connection.name])\n path = self.get_model().get_path(conniter).__str__()\n self.data_models[path] = connection\n\n dbnames = sorted(connection.databases.keys())\n\n for db in dbnames:\n dbiter = self.store.append(conniter, [db])\n path = self.get_model().get_path(dbiter).__str__()\n self.data_models[path] = connection.databases[db]\n connection.databases[db].load_tables()\n\n table_names = sorted(connection.databases[db].tables.keys())\n\n for table in table_names:\n iter = self.store.append(dbiter, [table])\n path = self.get_model().get_path(iter).__str__()\n self.data_models[path] = connection.databases[db].tables[table]\n\n def row_clicked(self, selection):\n model, treeiter = selection.get_selected()\n path = model.get_path(treeiter).__str__()\n\n if treeiter is not None:\n table_name = None\n\n if isinstance(self.data_models[path], models.Connection):\n name = \"test\"\n\n if model[treeiter].parent is None:\n connection_name = model[treeiter][0]\n elif model[treeiter].parent.parent is None:\n connection_name = model[treeiter].parent[0]\n db_name = model[treeiter][0]\n else:\n table_name = model[treeiter][0]\n table = self.data_models[path]\n data = table.get_data()\n grid = DataGrid(self.app, data)\n self.app.window.notebook.set_table_data_page(grid, table_name)\n\n @property\n def selected_model(self):\n model, iter = self.select.get_selected()\n path = model.get_path(iter).__str__()\n return self.data_models[path]\n\n\nclass ConnectionWindow(Gtk.Box):\n def __init__(self, app, connections=None):\n super().__init__()\n self.set_orientation(Gtk.Orientation.VERTICAL)\n self.set_homogeneous(False)\n self.app = app\n self.connection_list = None\n self.button_box = None\n self.add_button_box()\n self.add_connection_list(connections)\n\n def add_connection_list(self, connections=None):\n self.connection_list = ConnectionList(self.app, connections)\n\n window = Gtk.ScrolledWindow()\n window.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)\n window.add(self.connection_list)\n window.show_all()\n\n self.pack_end(window, True, True, 0)\n self.show_all()\n\n def add_button_box(self):\n self.button_box = Gtk.Box()\n self.button_box.set_valign(Gtk.BaselinePosition.BOTTOM)\n\n for operation in [\"add\", \"remove\"]:\n button = button_factory(\"list-\" + operation + \"-symbolic\")\n button.operation = operation\n button.connect(\"clicked\", self.operation_dispatch)\n self.button_box.pack_end(button, True, True, 0)\n\n self.pack_end(self.button_box, False, False, 0)\n self.show_all()\n\n def operation_dispatch(self, selection):\n operation = selection.operation\n model = self.connection_list.selected_model\n print(operation, model.name)\n\n\nclass DataGrid(Gtk.TreeView):\n def __init__(self, app, data=None):\n self.app = app\n super().__init__()\n self.store = None\n\n self.set_grid_lines(Gtk.TreeViewGridLines.BOTH)\n\n if data is not None:\n self.add_data(data)\n\n self.select = self.get_selection()\n\n def add_data(self, data):\n column_names = data[0].keys()\n cell = Gtk.CellRendererText()\n cell.set_property(\"editable\", True)\n cell.set_property(\"placeholder_text\", \"[null]\")\n\n def data_func(col, cell, model, iter, index):\n data = model[iter][index]\n red = Gdk.RGBA(red=1, green=0, blue=0, alpha=1)\n green = Gdk.RGBA(red=0, green=1, blue=0, alpha=1)\n if data in [None, '']:\n cell.set_property(\"foreground-rgba\", red)\n else:\n cell.set_property(\"foreground-rgba\", green)\n\n for i, name in enumerate(column_names):\n column = Gtk.TreeViewColumn(name.replace(\"_\", \"__\"), cell, text=i)\n column.set_cell_data_func(cell, data_func, i)\n column.set_sort_column_id(i)\n self.append_column(column)\n\n column_types = []\n for v in data[0].values():\n if type(v) not in [int, str, float, object]:\n column_types.append(str)\n else:\n column_types.append(type(v))\n\n self.store = Gtk.TreeStore(*(column_types))\n\n for row in data:\n new_row = []\n for name in column_names:\n if type(row[name]) not in [int, str, float, object, type(None)]:\n new_row.append(row[name].__str__())\n else:\n new_row.append(row[name])\n\n self.store.append(None, new_row)\n\n self.set_model(self.store)\n","sub_path":"ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":10432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"551049313","text":"\"\"\"Tests core command line interface\"\"\"\n\nfrom parrotfish.core import CLI\nfrom parrotfish import utils\nfrom parrotfish.session_environment import SessionManager\nimport os\nfrom pydent import AqSession\nimport uuid\n\n\nlogin = \"vrana\"\npassword = \"Mountain5\"\nurl = \"http://52.27.43.242:81/\"\n\n\ndef test_register(cli, credentials):\n assert len(cli.sessions) == 0\n cli.register(**credentials['nursery'])\n assert len(cli.sessions) == 1\n\n # add another session\n cli.register(**credentials['production'])\n assert len(cli.sessions) == 2\n\n\ndef test_register_with_same_name(cli, credentials):\n assert len(cli.sessions) == 0\n cli.register(**credentials['nursery'])\n assert len(cli.sessions) == 1\n\n # register with same name\n cli.register(**credentials['nursery'])\n assert len(cli.sessions) == 1\n\n\ndef test_unregister(cli):\n assert len(cli.sessions) == 0\n cli.register(login, password, url, \"nursery\")\n assert len(cli.sessions) == 1\n\n cli.unregister(\"nursery\")\n assert len(cli.sessions) == 0\n\n\ndef test_load(cli, credentials):\n assert len(cli.sessions) == 0\n cli.register(**credentials['nursery'])\n cli._save()\n\n # load another cli using same files\n old_sm = cli._session_manager\n copied_sm = SessionManager(old_sm.abspath, meta_dir=old_sm.metadata.abspath, meta_name=old_sm.metadata.env_settings.name)\n copied_sm.load()\n cli2 = CLI(copied_sm)\n\n assert len(cli.sessions) == 1\n assert len(cli2.sessions) == 1\n\n\ndef test_set_current(cli, credentials):\n assert len(cli.sessions) == 0\n cli.register(**credentials['nursery'])\n assert len(cli.sessions) == 1\n assert cli._session_manager.current_session.name == 'nursery'\n\n # add another session\n cli.register(**credentials['production'])\n assert len(cli.sessions) == 2\n assert cli._session_manager.current_session.name == 'production'\n\n # switch to nursery\n cli.set_session(\"nursery\")\n assert cli._session_manager.current_session.name == \"nursery\"\n\n # switch to non-existent session\n cli.set_session(\"does not exist\")\n\n\ndef test_move_repo(cli, tmpdir_factory, credentials):\n newdir = tmpdir_factory.mktemp('new_dir')\n\n # register and move repo\n cli.register(**credentials['nursery'])\n\n # assert root directory\n old_root = cli._session_manager._SessionManager__meta['root']\n\n # move the repo\n cli.move_repo(newdir)\n\n # add some random file\n cli._session_manager.add_file(\"newfile.txt\", attr=\"newfile\")\n cli._session_manager.get(\"newfile\").write(\"something\")\n assert os.path.exists(os.path.join(cli._session_manager.abspath, \"newfile.txt\"))\n\n # assert path of session_manager moved\n assert str(cli._session_manager.abspath) == os.path.join(str(newdir), cli._session_manager.name)\n\n # assert root in env.json was changed\n new_root = cli._session_manager._SessionManager__meta['root']\n assert new_root == os.path.join(str(newdir), cli._session_manager.name)\n assert old_root != new_root\n\n # ensure file moved along with repo move\n assert os.path.exists(os.path.join(newdir, cli._session_manager.name, \"newfile.txt\"))\n\n\ndef test_categories(cli, credentials):\n cli.register(**credentials['nursery'])\n categories = cli._get_categories()\n assert len(categories) > 0\n\n cli.categories()\n\n\ndef test_list_protocols(cli, credentials):\n cli.register(**credentials['nursery'])\n cli.fetch(\"ParrotFishTest\")\n cli.protocols()\n\n\ndef test_fetch(cli, credentials):\n cli.register(**credentials['nursery'])\n cli.fetch(\"ParrotFishTest\")\n cli.ls()\n\n sm = cli._session_manager\n\n # get first session folder\n session = sm.list_dirs()[0]\n\n categories = session.categories\n assert \"ParrotFishTest\" in [x.name for x in categories]\n\n # files\n for cat in categories:\n protocols = cat.list_dirs()\n for protocol in protocols:\n files = protocol.list_files()\n assert len(files) > 0\n\n\ndef test_push_category(cli, credentials):\n cli.register(**credentials['nursery'])\n cli.fetch(\"ParrotFishTest\")\n cli.ls()\n\n # just get the first operation type\n sm = cli._session_manager\n session = sm.list_dirs()[0]\n protocol = session.categories[0].list_dirs()[0]\n\n old_local_ot = session.read_operation_type(\"ParrotFishTest\", protocol.name)\n aqsession = AqSession(**credentials['nursery'])\n old_loaded_ot = aqsession.OperationType.find_by_name(old_local_ot.name)\n\n # push the content\n new_content = str(uuid.uuid4())\n protocol.protocol.write(new_content)\n cli.push_category(\"ParrotFishTest\")\n\n # new operation types\n new_local_ot = session.read_operation_type(\"ParrotFishTest\", protocol.name)\n new_loaded_ot = aqsession.OperationType.find_by_name(new_local_ot.name)\n\n # compare content\n assert new_loaded_ot.protocol.content == new_content\n assert new_local_ot.protocol.content == new_content\n assert old_local_ot.protocol.content != new_content\n print(utils.compare_content(old_local_ot.protocol.content, new_local_ot.protocol.content))\n","sub_path":"tests/test_core.py","file_name":"test_core.py","file_ext":"py","file_size_in_byte":5042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"316246621","text":"import re\nimport os\nimport pandas as pd\nimport glob\nimport subprocess\n\nname = 'stacey_'\nnodes = 1\ncpu = 4\nmem = 16\nhours = 240\n\ndir = '/scratch/drabosky_flux/sosi/AWT_delimit/stacey'\n\nn = 0\ndirs = os.listdir(dir)\nfor dir3 in dirs:\n\tnewdir = os.path.join(dir, dir3)\n\n\to = open(\"%s%s.sh\" % (name, n), 'w')\n\to.write(\"#PBS -N %s%s\\n\" % (name, n))\n\to.write(\"#PBS -M sosi@umich.edu\\n\")\n\to.write(\"#PBS -A drabosky_flux\\n\")\n\to.write(\"#PBS -l qos=flux\\n\")\n\to.write(\"#PBS -q flux\\n\")\n\to.write(\"#PBS -l nodes=%s:ppn=%s,mem=%sgb\\n\" % (nodes, cpu, mem))\n\to.write(\"#PBS -l walltime=%s:00:00\\n\" % hours)\n\t# o.write(\"#PBS -l walltime=06:14:21:58\\n\")\n\to.write(\"#PBS -j oe\\n\")\n\to.write(\"#PBS -V\\n\")\n\to.write(\"cd %s\\n\" % newdir)\n\n\tfiles = glob.glob(newdir + '/*')\n\to.write(\"~/bin/beast/bin/beast -threads 4 %s\" % files[0])\n\to.close()\n\n\t# if n > 1:\n\t#\tsubprocess.call(\"qsub %s%s.sh\" % (name, n), shell=True)\n\tn += 1\n","sub_path":"stacey_run.py","file_name":"stacey_run.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"288269962","text":"\nfrom flask.ext.assets import Environment, Bundle\n\nfrom . import app\n\nbundles={\n 'js_base_libs' : Bundle(\n 'pubswh/js/vendor/bootstrap.js',\n 'pubswh/js/plugins.js',\n filters='rjsmin',\n output='gen/base_libs.js'\n ),\n 'js_advanced_search' : Bundle(\n 'pubswh/js/select2.js',\n 'pubswh/js/searchMap.js',\n 'pubswh/js/clearFeatureControl.js',\n filters='rjsmin',\n output='gen/advanced_search.js'\n ),\n 'usgs_style' : Bundle(\n 'manager/less/usgs_header_footer.less',\n filters='less,cssmin',\n output='gen/usgs_style.css'\n ),\n 'css_base' : Bundle(\n 'pubswh/css/normalize.css',\n 'pubswh/css/main.css',\n 'pubswh/css/bootstrap.css',\n 'pubswh/css/select2.css',\n 'pubswh/css/select2-bootstrap.css',\n filters='cssmin',\n output='gen/min_base.css'\n ),\n 'auth_style' : Bundle(\n 'auth/less/auth.less',\n depends=[\n 'manager/less/usgs_header_footer.less'\n ],\n filters='less,cssmin',\n output='gen/auth_style.css'\n ),\n 'manager_style' : Bundle(\n 'manager/less/manager_custom.less',\n depends=[\n 'manager/less/usgs_header_footer.less',\n 'manager/less/search.less',\n 'manager/less/publication.less',\n 'manager/less/bibliodata.less'\n ],\n filters='less,cssmin',\n output='gen/manager_style.css'\n )\n}\n\nassets = Environment(app)\nassets.register(bundles)\n\n","sub_path":"pubs_ui/assets.py","file_name":"assets.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"296139604","text":"# leetcode no.19 Remove Nth Node From End of List\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n dummy, cur = ListNode(-1), head\n dummy.next = cur\n node_list = [dummy]\n while cur != None:\n node_list.append(cur)\n cur = cur.next\n\n prev, cur = node_list[-n-1], node_list[-n]\n prev.next = cur.next\n\n return dummy.next\n","sub_path":"Leetcode/rnnfeol.py","file_name":"rnnfeol.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"485309847","text":"\"\"\"djangoserver URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/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,include,re_path\nfrom django.views.generic import TemplateView\nurlpatterns = [\n path('service-worker.js', (TemplateView.as_view(template_name=\"service-worker.js\",content_type='application/javascript',)), name='service-worker.js'),\n path('manifest.json', (TemplateView.as_view(template_name=\"manifest.json\",content_type='application/javascript',)), name='manifest.json'),\n path('robots.txt', (TemplateView.as_view(template_name=\"robots.txt\",content_type='application/javascript',)), name='robots.txt'),\n path('admin/', admin.site.urls),\n path('api/article/',include('newsarticle.urls')),\n path('',include('reactroute.urls')),\n]\n","sub_path":"djangoserver/djangoserver/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"83302245","text":"# Copyright (c) 2019 ETH Zurich, Lukas Cavigelli\n# large parts of the code taken or adapted from torchvision\n\nimport math\nimport torch\nimport torch.nn as nn\n\n#from quantlab.indiv.stochastic_ops import StochasticActivation, StochasticLinear, StochasticConv2d\nfrom quantlab.indiv.inq_ops import INQController, INQLinear, INQConv2d\n#from quantlab.indiv.ste_ops import STEActivation\n\nmodel_urls = {\n 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',\n 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',\n 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',\n 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',\n 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',\n 'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',\n 'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth',\n 'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth',\n 'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth',\n}\n\nclass BasicBlock(nn.Module):\n expansion = 1\n __constants__ = ['downsample']\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,\n base_width=64, dilation=1, norm_layer=None, convGen=None):\n super(BasicBlock, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n if groups != 1 or base_width != 64:\n raise ValueError('BasicBlock only supports groups=1 and base_width=64')\n if dilation > 1:\n raise NotImplementedError(\"Dilation > 1 not supported in BasicBlock\")\n # Both self.conv1 and self.downsample layers downsample the input when stride != 1\n self.conv1 = convGen(inplanes, planes, kernel_size=3, stride=stride)\n self.bn1 = norm_layer(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = convGen(planes, planes, kernel_size=3)\n self.bn2 = norm_layer(planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n identity = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,\n base_width=64, dilation=1, norm_layer=None, convGen=None):\n super(Bottleneck, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n width = int(planes * (base_width / 64.)) * groups\n # Both self.conv2 and self.downsample layers downsample the input when stride != 1\n self.conv1 = convGen(inplanes, width, kernel_size=1)\n self.bn1 = norm_layer(width)\n self.conv2 = convGen(width, width, kernel_size=3, \n stride=stride, groups=groups, dilation=dilation)\n self.bn2 = norm_layer(width)\n self.conv3 = convGen(width, planes * self.expansion, kernel_size=1)\n self.bn3 = norm_layer(planes * self.expansion)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n identity = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(nn.Module):\n def __init__(self, arch='resnet18', quant_schemes=None, \n quantWeights=True, quantAct=True,\n weightInqSchedule=None, weightInqBits=None, weightInqLevels=None,\n weightInqStrategy=\"magnitude\", weightInqQuantInit=None,\n quantSkipFirstLayer=False, quantSkipLastLayer=False, pretrained=False):\n \n super(ResNet, self).__init__()\n assert(quantAct == False)\n assert(quantSkipFirstLayer)\n assert(quantSkipLastLayer)\n if weightInqBits != None:\n print('warning: weightInqBits deprecated')\n if weightInqBits == 1:\n weightInqLevels = 2\n elif weightInqBits >= 2:\n weightInqLevels = 2**weightInqBits\n else:\n assert(False) \n \n def convGen(in_planes, out_planes, kernel_size=None, stride=1, \n groups=1, dilation=1, firstLayer=False):\n \"\"\"3x3 convolution with padding\"\"\"\n \n if kernel_size == 3:\n padding = dilation\n elif kernel_size == 1:\n padding = 0\n elif kernel_size == 7:\n padding = 3\n else:\n assert(False)\n \n if firstLayer or not(quantWeights): \n return nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,\n padding=padding, groups=groups, bias=False, dilation=dilation)\n else:\n return INQConv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,\n padding=padding, groups=groups, bias=False, dilation=dilation, \n numLevels=weightInqLevels, strategy=weightInqStrategy,\n quantInitMethod=weightInqQuantInit)\n \n class BasicBlockWrap(BasicBlock):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs, convGen=convGen)\n class BottleneckWrap(Bottleneck):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs, convGen=convGen)\n \n if arch == 'resnet18':\n block = BasicBlockWrap\n layers = [2, 2, 2, 2]\n elif arch == 'resnet34':\n block = BasicBlockWrap\n layers = [3, 4, 6, 3]\n elif arch == 'resnet50':\n block = BottleneckWrap\n layers = [3, 4, 6, 3]\n elif arch == 'resnet101':\n block = BottleneckWrap\n layers = [3, 4, 23, 3]\n elif arch == 'resnet152':\n block = BottleneckWrap\n layers = [3, 8, 36, 3]\n else:\n assert(False)\n \n self.createNet(block, layers, convGen,\n num_classes=1000, zero_init_residual=False, groups=1, \n width_per_group=64, replace_stride_with_dilation=None, norm_layer=None)\n \n if pretrained:\n from torch.hub import load_state_dict_from_url\n state_dict = load_state_dict_from_url(model_urls[arch])\n missing_keys, unexpected_keys = self.load_state_dict(state_dict, strict=False)\n \n missing_keys_nonInq = [s for s in missing_keys if not (s.endswith('.sParam') or s.endswith('.weightFrozen'))]\n assert(len(unexpected_keys) == 0)\n assert(len(missing_keys_nonInq) == 0)\n# if len(missing_keys) > 0:\n# print('load_state_dict -- missing keys:')\n# print(missing_keys)\n# if len(unexpected_keys) > 0:\n# print('load_state_dict -- unexpected keys:')\n# print(unexpected_keys)\n \n if weightInqSchedule != None: \n self.inqController = INQController(INQController.getInqModules(self), \n weightInqSchedule, \n clearOptimStateOnStep=True)\n\n\n def createNet(self, block, layers, convGen, \n num_classes=1000, zero_init_residual=False, groups=1, \n width_per_group=64, replace_stride_with_dilation=None, norm_layer=None):\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n self._norm_layer = norm_layer\n\n self.inplanes = 64\n self.dilation = 1\n if replace_stride_with_dilation is None:\n # each element in the tuple indicates if we should replace\n # the 2x2 stride with a dilated convolution instead\n replace_stride_with_dilation = [False, False, False]\n if len(replace_stride_with_dilation) != 3:\n raise ValueError(\"replace_stride_with_dilation should be None \"\n \"or a 3-element tuple, got {}\".format(replace_stride_with_dilation))\n self.groups = groups\n self.base_width = width_per_group\n self.conv1 = convGen(3, self.inplanes, kernel_size=7, stride=2, firstLayer=True)\n# self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,\n# bias=False)\n self.bn1 = norm_layer(self.inplanes)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, 64, layers[0], \n convGen=convGen)\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2,\n dilate=replace_stride_with_dilation[0], \n convGen=convGen)\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2,\n dilate=replace_stride_with_dilation[1], \n convGen=convGen)\n self.layer4 = self._make_layer(block, 512, layers[3], stride=2,\n dilate=replace_stride_with_dilation[2], \n convGen=convGen)\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\n self.fc = nn.Linear(512 * block.expansion, num_classes)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, INQConv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n # Zero-initialize the last BN in each residual branch,\n # so that the residual branch starts with zeros, and each residual block behaves like an identity.\n # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677\n if zero_init_residual:\n for m in self.modules():\n if isinstance(m, Bottleneck):\n nn.init.constant_(m.bn3.weight, 0)\n elif isinstance(m, BasicBlock):\n nn.init.constant_(m.bn2.weight, 0)\n \n\n def _make_layer(self, block, planes, blocks, stride=1, dilate=False, convGen=None):\n norm_layer = self._norm_layer\n downsample = None\n previous_dilation = self.dilation\n if dilate:\n self.dilation *= stride\n stride = 1\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n convGen(self.inplanes, planes*block.expansion, \n kernel_size=1, stride=stride),\n norm_layer(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample, self.groups,\n self.base_width, previous_dilation, norm_layer))\n self.inplanes = planes * block.expansion\n for _ in range(1, blocks):\n layers.append(block(self.inplanes, planes, groups=self.groups,\n base_width=self.base_width, dilation=self.dilation,\n norm_layer=norm_layer))\n\n return nn.Sequential(*layers)\n\n def forward(self, x, withStats=False):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n x = self.avgpool(x)\n x = torch.flatten(x, 1)\n x = self.fc(x)\n \n if withStats:\n stats = []\n return stats, x\n\n return x\n \n\n def forward_with_tensor_stats(self, x):\n stats, x = self.forward(x, withStats=True)\n return stats, x\n \n \nif __name__ == \"__main__\":\n model = ResNet(arch='resnet18', quantAct=False, weightInqSchedule={}, \n quantSkipFirstLayer=True, quantSkipLastLayer=True, \n pretrained=True)\n \n loadModel = True\n if loadModel:\n # path = '../../../ImageNet/logs/exp038/saves/best-backup.ckpt' # BWN\n# path = '../../../ImageNet/logs/exp043/saves/best.ckpt' # TWN\n path = '../../../ImageNet/logs/exp054/saves/best.ckpt' # BWN\n fullState = torch.load(path, map_location='cpu')\n netState = fullState['indiv']['net']\n model.load_state_dict(netState)\n \n import matplotlib.pyplot as plt\n layerNames = list(netState.keys())\n selectedLayers = ['layer4.0.conv1', \n 'layer2.1.conv2', \n 'layer1.0.conv2']\n # selectedLayers = [l + '.weight' for l in selectedLayers]\n selectedLayers = [l + '.weightFrozen' for l in selectedLayers]\n _, axarr = plt.subplots(len(selectedLayers))\n for ax, layerName in zip(axarr, selectedLayers):\n plt.sca(ax)\n plt.hist(netState[layerName].flatten(), \n bins=201, range=(-3,3))\n plt.xlim(-3,3)\n plt.title(layerName)\n \n exportONNX = False\n if exportONNX:\n modelFullPrec = ResNet(arch='resnet18', quantAct=False, quantWeights=False, \n weightInqSchedule={}, \n quantSkipFirstLayer=True, \n quantSkipLastLayer=True, \n pretrained=True)\n dummyInput = torch.randn(1, 3, 224, 224)\n pbuf = torch.onnx.export(modelFullPrec, dummyInput, \n \"export.onnx\", verbose=True, \n input_names=['input'], \n output_names=['output'])\n \n \n \n \n \n \n \n \n","sub_path":"quantlab/ImageNet/ResNet/resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":14661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"545759529","text":"from sqlalchemy import Column, Integer, ForeignKey, String, Table, Text\nfrom sqlalchemy.orm import relationship\n\nfrom basic_.sqlalchemy_.schemas import User, Database\n\nsession = Database.get_session(echo=True)\n\n# association table\n# We can see declaring a Table directly is a little different than declaring a mapped class. Table is a constructor function,\n# so each individual Column argument is separated by a comma.\n# The Column object is also given its name explicitly, rather than it being taken from an assigned attribute name.\npost_keywords = Table('post_keywords', Database.Base.metadata,\n Column('post_id', ForeignKey('posts.id'), primary_key=True),\n Column('keyword_id', ForeignKey('keywords.id'), primary_key=True)\n )\n\n\nclass BlogPost(Database.Base):\n __tablename__ = 'posts'\n id = Column(Integer, primary_key=True)\n user_id = Column(Integer, ForeignKey('users.id'))\n headline = Column(String(255), nullable=False)\n body = Column(Text)\n\n # many to many BlogPost<->Keyword\n keywords = relationship('Keyword', secondary=post_keywords, back_populates=__tablename__)\n\n # note: declarations illustrate explicit __init__() methods. Remember, when using Declarative, it’s optional!\n def __init__(self, headline, body, author):\n self.author = author\n self.headline = headline\n self.body = body\n\n def __repr__(self) -> str:\n return f\"BLogPost({self.headline}, {self.body}, {self.author}\"\n\n\nclass Keyword(Database.Base):\n __tablename__ = \"keywords\"\n id = Column(Integer, primary_key=True)\n keyword = Column(String(50), nullable=False, unique=True)\n posts = relationship('BlogPost', secondary=post_keywords, back_populates=__tablename__)\n\n def __init__(self, keyword):\n self.keyword = keyword\n\n\n# We would also like our BlogPost class to have an author field.\n# We will add this as another bidirectional relationship, except one issue we’ll have is that a single user might have lots of blog posts.\n# When we access User.posts, we’d like to be able to filter results further so as not to load the entire collection.\n# For this we use a setting accepted by relationship() called lazy='dynamic', which configures an alternate loader strategy on the attribute:\nBlogPost.author = relationship(User, back_populates=BlogPost.__tablename__)\nUser.posts = relationship(BlogPost, back_populates=\"author\", lazy=\"dynamic\")\n\nDatabase.create_tables()\n\nwendy = session.query(User).filter_by(name='wendy').one()\npost = BlogPost(\"Wendy's Blog Post\", \"This is a test\", wendy)\nsession.add(post)\n\npost.keywords.append(Keyword('wendy'))\npost.keywords.append(Keyword('firstpost'))\n\nprint(session.query(BlogPost).\n filter(BlogPost.keywords.any(keyword='firstpost')).\n all())\n\nprint(session.query(BlogPost).filter(BlogPost.author == wendy). \\\n filter(BlogPost.keywords.any(keyword='firstpost')). \\\n all())\n\nprint(wendy.posts.filter(BlogPost.keywords.any(keyword='firstpost')).all())\n","sub_path":"basic_/sqlalchemy_/many_to_many_relationship.py","file_name":"many_to_many_relationship.py","file_ext":"py","file_size_in_byte":3028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"111616127","text":"import os, math\n\n# import keras libs\nfrom keras import applications\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras import optimizers\nfrom keras.models import Sequential, Model,load_model\nfrom keras.layers import Dropout, Flatten, Dense, GlobalAveragePooling2D\nfrom keras import backend as k\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler, TensorBoard, EarlyStopping\n\n\ndef create_model(model_name,training_type,num_classes):\n #Initializing the image width and image height : This will be updated as per the model which is going to be used\n img_width,img_height = 224,224\n\n #InceptionV3\n if (model_name.lower() == 'inceptionv3'):\n img_width,img_height = 299,299\n if(training_type == 'train_all'):\n model = applications.inception_v3.InceptionV3(weights = \"imagenet\", include_top=False, input_shape = (img_width, img_height, 3))\n model.layers.pop()\n for layer in model.layers:\n \tlayer.trainable = True\n top_model = Sequential()\n top_model.add(Flatten(input_shape=model.output_shape[1:]))\n top_model.add(Dense(1024, activation='relu'))\n top_model.add(Dropout(0.5))\n top_model.add(Dense(512, activation='relu'))\n top_model.add(Dropout(0.5))\n top_model.add(Dense(num_classes, activation='softmax'))\n #Final model\n model_final = Model(inputs = model.input, outputs = top_model(model.output))\n\n return model_final,img_width,img_height\n\ndef test_model(model_name,save_loc,test_generator):\n #load the saved model\n model_loc = save_loc + model_name + \".h5\"\n model = load_model(model_loc)\n\n #predict\n logits = model.predict_generator(test_generator,verbose = 1)\n\n return logits\n","sub_path":"models_keras.py","file_name":"models_keras.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"240966577","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'medical'\nurlpatterns = [\n url(r'^$',\n views.insp,\n name='insp'\n ),\n url(r'^calend/(?P<insp_id>[0-9]+)/(?P<doc_id>[0-9]+)/$',\n views.calend,\n name='calend',\n ),\n url(r'^time/(?P<receipt_id>[0-9]+)/(?P<date>[0-9]+)/$',\n views.time,\n name='time',\n ),\n url(r'^form/$',\n views.form,\n name='form',\n ),\n]","sub_path":"medical/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"72202138","text":"import glob\nimport os\nfrom datetime import datetime\n\nimport pandas as pd\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nfrom matplotlib.ticker import MultipleLocator, AutoMinorLocator\n\nfrom src import wa_parser\nfrom src.helpers import write_file\nfrom src.reports.bbcode_reports import *\nfrom src.reports.pandas_reports import create_leaderboards, create_aliases\n\nprint('starting')\nupdating_database = True\nwriting_files = True\n\n# ensure folders for relevant directories exist\nfor p in ['../output', '../db']:\n os.makedirs(p, exist_ok=True)\n\nif updating_database:\n print('updating database')\n df_path = '../db/resolutions_{}.csv'.format(pd.Timestamp.now().strftime('%Y-%m-%d'))\n df = wa_parser.parse()\n df.to_csv(df_path, index=False)\n\n# parse database\nprint('parsing database')\ndb = Database.create(max(glob.glob('../db/resolutions*.csv'), key=os.path.getctime), '../db/aliases.csv')\n# > uncomment below to generate for explicit path\n# db = Database.create('../db/resolutions.csv', '../db/aliases.csv')\n\n# create table\nprint('creating markdown table')\ns = create_leaderboards(db, how='markdown')\nwrite_file('../md_output/leaderboard.md', s, print_input=True)\n\n# create alias table\nprint('creating alias table')\ns = create_aliases()\nwrite_file('../md_output/aliases.md', s, print_input=True)\n\n# create chart\nprint('creating chart')\nranks = create_leaderboards(db, how='pandas', keep_puppets=False)\nranks['Name'] = ranks['Name'].str.replace(r'\\[PLAYER\\]', '').str.strip() # de-dup from players\nranks.drop_duplicates(subset='Name', keep='first', inplace=True)\nranks = ranks.head(30)\n\nf, ax = plt.subplots(figsize=(8.25, 11.71))\nax.barh(ranks['Name'], ranks['Total'], color=sns.color_palette('muted'), zorder=2)\nax.set_ylim([-1, ranks['Name'].size])\nax.invert_yaxis()\nax.xaxis.set_minor_locator(AutoMinorLocator())\nax.xaxis.grid(True, linestyle='dashed', which='major', zorder=0)\nax.xaxis.grid(True, linestyle='dotted', which='minor', zorder=0)\nax.set_title('Players with most WA resolutions')\nax.annotate(\n 'Data as of {}. See https://github.com/ifly6/WA-Authorboards.'.format(datetime.today().strftime('%Y-%m-%d')),\n (0, 0), (0, -20), xycoords='axes fraction', textcoords='offset points', va='top'\n)\n\nf.tight_layout()\nf.savefig('../md_output/leaderboard_top30.pdf')\nf.savefig('../md_output/leaderboard_top30.jpg')\nprint('wrote chart')\n\n# write old bbCode files\nif writing_files:\n print('saving tables')\n write_file('../output/author_index', generate_author_index(db))\n write_file('../output/table_AUTHOR', generate_author_table(db, OrderType.AUTHOR))\n write_file('../output/table_LEADERBOARDS', generate_author_table(db, OrderType.TOTAL))\n write_file('../output/table_ACTIVE_TOTAL', generate_author_table(db, OrderType.ACTIVE_TOTAL))\n write_file('../output/table_NON_REPEALS', generate_author_table(db, OrderType.ACTIVE_NON_REPEALS_TOTAL))\n write_file('../output/table_REPEALS', generate_author_table(db, OrderType.ACTIVE_REPEALS_TOTAL))\n write_file('../output/table_REPEALED', generate_author_table(db, OrderType.REPEALED_TOTAL))\n write_file('../output/author_aliases', generate_known_aliases(db))\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"165767105","text":"import geopandas as gpd\nfrom typing import List, Union\nfrom pyspark.sql.session import SparkSession\n\ndef load_tables(\n sparkSession: SparkSession, tablenames: Union[str, List[str]], **kwargs\n):\n \"\"\"\n Summary\n -------\n 테이블명을 기반으로 Spark DataFrame을 반환합니다.\n\n Parameter\n ----\n sparkSession: Active Spark Session\n tablenames: DataFrame으로 만들 테이블명\n **kwargs: `driver`, `url`, `user`, `password`\n\n Raises:\n ValueError\n\n Returns:\n `DataFrame`s from database\n\n\n Usage\n -----\n >>> import SPDataFrame\n >>> ss = SparkSession.builder.getOrCreate()\n >>> tablenames = ['integrated_address_seoul', 'integrated_address_incheon', 'integrated_address_gyeonggi']\n >>> table_dfs = SPDataFrame(ss, tablenames,\n driver='com.mysql.cj.jdbc.Driver',\n url='jdbc:mysql://localhost:3306/sparkplus',\n user='root',\n password='password'\n )\n >>> table_dfs.select('roadname_code', 'sido', 'sigungu', 'eupmyeondong').show()\n +-------------+----------+-------------+------------+\n |roadname_code| sido| sigungu|eupmyeondong|\n +-------------+----------+-------------+------------+\n | 261103125011|부산광역시| 중구| 영주동|\n | 261104006006|부산광역시| 중구| 영주동|\n | 261104006006|부산광역시| 중구| 영주동|\n | 261104006006|부산광역시| 중구| 영주동|\n | 261103125011|부산광역시| 중구| 영주동|\n | 111104100289|서울특별시| 종로구| 청운동|\n | 111104100289|서울특별시| 종로구| 청운동|\n | 111103100014|서울특별시| 종로구| 청운동|\n | 111104100289|서울특별시| 종로구| 청운동|\n | 111104100289|서울특별시| 종로구| 청운동|\n | 411114322017| 경기도|수원시 장안구| 파장동|\n | 411114322017| 경기도|수원시 장안구| 파장동|\n | 411114322017| 경기도|수원시 장안구| 파장동|\n | 411114322017| 경기도|수원시 장안구| 파장동|\n | 411114322017| 경기도|수원시 장안구| 파장동|\n +-------------+----------+-------------+------------+\n \"\"\"\n sess_conf = sparkSession.sparkContext.getConf().getAll()\n\n # If SparkConf doesn't contain MySQL connector, raise `ValueError`\n jdbc_driver_flag = False\n\n # If you use `spark.jars.packages`, value should like `mysql:mysql-connector-java:YOUR_MYSQL_VERSION`\n available_configs = [\n \"spark.jars\",\n \"spark.driver.extraClassPath\",\n \"spark.jars.packages\",\n ]\n\n for (conf_key, conf_val) in sess_conf:\n if conf_key in available_configs and conf_val.__contains__(\"mysql\"):\n jdbc_driver_flag = True\n break\n\n if not jdbc_driver_flag:\n raise ValueError(\n \"[SPARKPLUS_MYSQL_CONNECTOR_ERR] \"\n \"Your spark session seems like it doesn't contains mysql-connector-java path to connect mysql database. \"\n \"Please specify it to use SparkPlus package properly.\\n\\n\"\n \"$ spark-submit <your-spark-app> --jars <mysql-jar-path>\\n\\n\"\n \"In programming way, if you have mysql-connector jar file locally, set spark configuration like\\n\\n\"\n \">>> ss = SparkSession.builder.config('spark.jars', MYSQL_JAR_PATH)\\n\\n\"\n \"or if you don't,\\n\\n\"\n \">>> ss = SparkSession.builder.config('spark.jars.packages', 'mysql:mysql-connector-java:YOUR_MYSQL_VERSION')\\n\\n\"\n \"Check https://spark.apache.org/docs/latest/configuration.html for detail.\"\n )\n\n ss_read = sparkSession.read.format(\"jdbc\")\n\n # set DB options such as driver, url, user, password\n for opt_key, opt_val in kwargs.items():\n ss_read.option(opt_key, opt_val)\n\n if isinstance(tablenames, str):\n return ss_read.option(\"dbtable\", tablenames).load()\n else:\n dfs = ss_read.option(\"dbtable\", tablenames.pop()).load()\n\n while tablenames:\n dfs = dfs.union(ss_read.option(\"dbtable\", tablenames.pop()).load())\n\n return dfs\n\ndef load_gdf(shp_path , epsg):\n gdf = gpd.read_file(shp_path, encoding=\"euc-kr\")\n gdf.crs = f'epsg:{epsg}'\n gdf = gdf.to_crs(epsg=4326)\n\n return gdf","sub_path":"sparkplus/core/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"600000174","text":"import doctest\nimport unittest\nimport zope.component.testing\n\nfrom Products.PloneTestCase import ptc\nimport collective.testcaselayer.ptc\n\nimport plone.app.textfield\n\nptc.setupPloneSite()\n\nclass UnitTestLayer:\n \n @classmethod\n def testTearDown(cls):\n zope.component.testing.tearDown()\n\nclass IntegrationTestLayer(collective.testcaselayer.ptc.BasePTCLayer):\n\n def afterSetUp(self):\n from Products.Five import zcml\n from Products.Five import fiveconfigure\n \n fiveconfigure.debug_mode = True\n zcml.load_config('configure.zcml', package=plone.app.textfield)\n fiveconfigure.debug_mode = False\n\nIntegrationLayer = IntegrationTestLayer([collective.testcaselayer.ptc.ptc_layer])\n\nclass TestIntegration(ptc.PloneTestCase):\n \n layer = IntegrationLayer\n\n def testTransformPlain(self):\n from zope.interface import Interface\n from plone.app.textfield import RichText\n \n class IWithText(Interface):\n \n text = RichText(title=u\"Text\",\n default_mime_type='text/plain',\n output_mime_type='text/html')\n \n value = IWithText['text'].fromUnicode(u\"Some **text**\")\n self.assertEquals(u'<p>Some **text**</p>', value.output)\n \n def testTransformStructured(self):\n from zope.interface import Interface\n from plone.app.textfield import RichText\n \n class IWithText(Interface):\n \n text = RichText(title=u\"Text\",\n default_mime_type='text/structured',\n output_mime_type='text/html')\n \n value = IWithText['text'].fromUnicode(u\"Some **text**\")\n self.assertEquals(u'<p>Some <strong>text</strong></p>\\n', value.output)\n \n def testTransformView(self):\n from zope.interface import Interface, implements\n from plone.app.textfield import RichText\n from Products.CMFCore.PortalContent import PortalContent\n \n class IWithText(Interface):\n \n text = RichText(title=u\"Text\",\n default_mime_type='text/structured',\n output_mime_type='text/html')\n \n class Context(PortalContent):\n implements(IWithText)\n \n id = 'context'\n text = None\n \n context = Context()\n context.text = IWithText['text'].fromUnicode(u\"Some **text**\")\n \n self.portal._setObject('context', context)\n context = self.portal['context']\n \n output = context.restrictedTraverse('@@text-transform/text')()\n self.assertEquals(u'<p>Some <strong>text</strong></p>', output.strip())\n \n output = context.restrictedTraverse('@@text-transform/text/text/plain')()\n self.assertEquals(u'Some text', output.strip())\n\n # test transform shortcircuit when input and output type is the\n # same. this used to cause infinite recursion\n class IWithText(Interface):\n text = RichText(title=u\"Text\",\n default_mime_type='text/html',\n output_mime_type='text/html')\n\n context.text = IWithText['text'].fromUnicode(u\"<span>Some html</span>\")\n output = context.restrictedTraverse('@@text-transform/text')()\n self.assertEquals(u\"<span>Some html</span>\", output.strip())\n \n def testWidgetExtract(self):\n from zope.interface import Interface, implements\n from plone.app.textfield import RichText\n from zope.publisher.browser import TestRequest\n from Products.CMFCore.PortalContent import PortalContent\n from plone.app.textfield.widget import RichTextWidget\n from z3c.form.widget import FieldWidget\n from z3c.form.interfaces import NOVALUE\n \n class IWithText(Interface):\n \n text = RichText(title=u\"Text\",\n default_mime_type='text/structured',\n output_mime_type='text/html')\n \n class Context(PortalContent):\n implements(IWithText)\n \n text = None\n \n request = TestRequest()\n \n widget = FieldWidget(IWithText['text'], RichTextWidget(request))\n widget.update()\n \n value = widget.extract()\n self.assertEquals(NOVALUE, value)\n \n request.form['%s' % widget.name] = u\"Sample **text**\"\n request.form['%s.mimeType' % widget.name] = 'text/structured'\n \n value = widget.extract()\n self.assertEquals(u\"<p>Sample <strong>text</strong></p>\", value.output.strip())\n \n def testWidgetConverter(self):\n from zope.interface import Interface\n from plone.app.textfield import RichText\n from zope.publisher.browser import TestRequest\n from plone.app.textfield.value import RichTextValue\n from plone.app.textfield.widget import RichTextWidget, RichTextConverter\n from z3c.form.widget import FieldWidget\n\n _marker = object()\n\n class IWithText(Interface):\n \n text = RichText(title=u\"Text\",\n default_mime_type='text/structured',\n output_mime_type='text/html',\n missing_value = _marker)\n\n request = TestRequest()\n\n widget = FieldWidget(IWithText['text'], RichTextWidget(request))\n widget.update()\n\n converter = RichTextConverter(IWithText['text'], widget)\n self.assertTrue(converter.toFieldValue(u'') is _marker)\n self.assertTrue(converter.toFieldValue(RichTextValue(u'')) is _marker)\n \n def testWidgetAllowedTypesDefault(self):\n from zope.interface import Interface, implements\n from plone.app.textfield import RichText\n from zope.publisher.browser import TestRequest\n from Products.CMFCore.PortalContent import PortalContent\n from plone.app.textfield.widget import RichTextWidget\n from z3c.form.widget import FieldWidget\n \n class IWithText(Interface):\n \n text = RichText(title=u\"Text\",\n default_mime_type='text/structured',\n output_mime_type='text/html')\n \n class Context(PortalContent):\n implements(IWithText)\n \n text = None\n \n request = TestRequest()\n \n widget = FieldWidget(IWithText['text'], RichTextWidget(request))\n widget.update()\n \n self.portal['portal_properties']['site_properties']._setPropValue('forbidden_contenttypes', ['text/structured'])\n \n allowed = widget.allowedMimeTypes()\n self.failUnless('text/html' in allowed)\n self.failIf('text/structured' in allowed)\n \n def testWidgetAllowedTypesField(self):\n from zope.interface import Interface, implements\n from plone.app.textfield import RichText\n from zope.publisher.browser import TestRequest\n from Products.CMFCore.PortalContent import PortalContent\n from plone.app.textfield.widget import RichTextWidget\n from z3c.form.widget import FieldWidget\n \n class IWithText(Interface):\n \n text = RichText(title=u\"Text\",\n default_mime_type='text/structured',\n output_mime_type='text/html',\n allowed_mime_types=('text/structured', 'text/html'))\n \n class Context(PortalContent):\n implements(IWithText)\n \n text = None\n \n request = TestRequest()\n \n widget = FieldWidget(IWithText['text'], RichTextWidget(request))\n widget.update()\n \n self.portal['portal_properties']['site_properties']._setPropValue('forbidden_contenttypes', ['text/structured'])\n \n allowed = widget.allowedMimeTypes()\n self.failUnless('text/html' in allowed)\n self.failUnless('text/structured' in allowed)\n \n \ndef test_suite():\n \n field = doctest.DocFileSuite('field.txt', optionflags=doctest.ELLIPSIS)\n field.layer = UnitTestLayer\n \n handler = doctest.DocFileSuite('handler.txt', optionflags=doctest.ELLIPSIS)\n handler.layer = UnitTestLayer\n \n marshaler = doctest.DocFileSuite('marshaler.txt', optionflags=doctest.ELLIPSIS)\n marshaler.layer = UnitTestLayer\n \n return unittest.TestSuite((\n field, handler, marshaler,\n unittest.makeSuite(TestIntegration),\n ))\n","sub_path":"workspace/buildout-cache/eggs/plone.app.textfield-1.2.2-py2.7.egg/plone/app/textfield/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":8640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"136117035","text":"import os\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom trips_count_predictor.utils.path_utils import check_create_path\nfrom trips_count_predictor.config.config import root_figures_path\nfrom trips_count_predictor.multivariate.plot_stuff import plot_result, plot_residuals_hist\n\n\nclass TimeSeriesRegressionPlotter():\n\n def __init__(\n self,\n trips_h,\n y_true,\n y_hat,\n trainer_config,\n df_coef\n ):\n\n self.trips_h = trips_h\n self.y_true = y_true\n self.y_hat = y_hat\n self.trainer_config = trainer_config\n self.df_coef = df_coef\n\n check_create_path(root_figures_path)\n\n def plot_charts(self):\n\n model_config_string = \"_\".join([str(v) for v in self.trainer_config.values()])\n\n plot_result(self.trips_h, self.y_hat, self.trainer_config[\"regr_type\"])\n plt.tight_layout()\n plt.savefig(os.path.join(\n root_figures_path,\n model_config_string + \"_result.png\"\n )\n )\n plt.close()\n\n plot_residuals_hist(self.y_true, self.y_hat)\n plt.savefig(os.path.join(\n root_figures_path,\n model_config_string + \"_residuals_hist.png\"\n )\n )\n plt.close()\n\n # self.df_coef.plot.barh(stacked=True, figsize=(15,7))\n # plt.tight_layout()\n # plt.savefig(os.path.join(\n # root_figures_path,\n # model_config_string + \"_all_coefs.png\"\n # )\n # )\n # plt.close()\n\t\t#\n # self.df_coef.mean().plot.bar(stacked=False, figsize=(15,7))\n # plt.tight_layout()\n # plt.savefig(os.path.join(\n # root_figures_path,\n # model_config_string + \"_mean_coefs.png\"\n # )\n # )\n # plt.close()\n","sub_path":"trips_count_predictor/multivariate/plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"148115017","text":"import sys\nfrom decimal import Decimal\n\nimport pytest\nfrom pytest import param as p\n\nfrom jschon import JSON, JSONSchema\nfrom tests import metaschema_uri_2020_12, example_schema, example_valid, example_invalid\n\n\n@pytest.mark.parametrize('value', (\n p(None, id='null'),\n p(True, id='bool'),\n p(sys.maxsize, id='int'),\n p(1.1111111111, id='float'),\n p(sys.float_info.max, id='max float'),\n p(Decimal('100.00'), id='decimal int'),\n p(Decimal('99.9999'), id='decimal float'),\n p('Hello, World!', id='string'),\n p([], id='empty array'),\n p([1] * 10, id='10x int array'),\n p([1] * 100, id='100x int array'),\n p({}, id='empty object'),\n p(dict(zip(map(str, range(10)), [1] * 10)), id='10x int object'),\n p(dict(zip(map(str, range(100)), [1] * 100)), id='100x int object'),\n p(example_valid, id='simple example'),\n p(example_schema, id='complex example'),\n))\ndef test_create_json(benchmark, value):\n benchmark(JSON, value)\n\n\n@pytest.mark.parametrize('value', (\n p(example_valid, id='valid'),\n p(example_invalid, id='invalid'),\n))\ndef test_evaluate_json(benchmark, request, value):\n json = JSON(value)\n schema = JSONSchema(example_schema, metaschema_uri=metaschema_uri_2020_12)\n scope = benchmark(schema.evaluate, json)\n assert scope.valid is (True if '[valid]' in request.node.name else False)\n\n\nschema_tests = (\n p(True, id='bool'),\n p({}, id='empty'),\n p({\"const\": \"foo\"}, id='simple'),\n p(example_schema, id='complex'),\n)\n\n\n@pytest.mark.parametrize('value', schema_tests)\ndef test_create_schema(benchmark, value):\n benchmark(JSONSchema, value, metaschema_uri=metaschema_uri_2020_12)\n\n\n@pytest.mark.parametrize('value', schema_tests)\ndef test_validate_schema(benchmark, value):\n schema = JSONSchema(value, metaschema_uri=metaschema_uri_2020_12)\n benchmark(schema.validate)\n","sub_path":"tests/test_benchmarks.py","file_name":"test_benchmarks.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"442289634","text":"# class Node(object):\n# def __init__(self, elem):\n# #节点数据\n# self.elem = elem\n# #节点指针\n# self.next = None\n#\n# class Link(object):\n# def __init__(self, node=None):\n# #初始化头指针指向None\n# self.head = node\n#\n# def travel(self):\n# #头指针\n# cur = self.head\n# while cur != None:\n# print(cur.elem , end=' ')\n# cur = cur.next\n#\n# def add(self, item):\n# #创建新节点\n# node = Node(item)\n# #新节点指针指向上一个节点\n# node.next = self.head\n# #头指针指向新插入的节点\n# self.head = node\n\n\n\n\nclass Node(object):\n def __init__(self, elem):\n # 节点前指针\n self.last = None\n #节点数据\n self.elem = elem\n #节点后指针\n self.next = None\n\nclass Link(object):\n def __init__(self, node=None):\n #初始化头指针指向None\n self.head = node\n # 初始化头指针指向None\n self.end = node\n\n def travel(self):\n #头指针\n cur = self.head\n while cur != None:\n print(cur.elem , end=' ')\n cur = cur.next\n\n def add(self, item):\n #创建新节点\n node = Node(item)\n # 新节点指针指向下一个节点\n node.next = self.head\n # 新节点指针指向上一个节点\n node.last = self.end\n #头指针指向新插入的节点\n self.head = node\n\n\n\nif __name__ == '__main__':\n MyLink=Link()\n MyLink.add(1)\n MyLink.add(3)\n MyLink.travel()","sub_path":"数据结构/MyLink.py","file_name":"MyLink.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"288819250","text":"from __future__ import unicode_literals\n\nfrom gge_proxy_manager.models import Alliance, AllianceRelation\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass AllianceMiddleware():\n @staticmethod\n def inbound(context, message):\n if not message.type == 'in' or not message.command == 'ain':\n return context, message\n\n kingdom = context.get_kingdom()\n if not kingdom:\n return context, message\n\n data = message.get_data()\n\n alliance_data = data.get(\"A\", {})\n alliance_id = alliance_data.get(\"AID\")\n\n if not alliance_id:\n return context, message\n\n related_list_data = alliance_data.get(\"ADL\", [])\n alliance = Alliance.objects.get(game=kingdom.game, gge_id=alliance_id)\n\n for relation in alliance.get_relations():\n relation.delete()\n\n for related_data in related_list_data:\n acknowledged = bool(related_data.get(\"AC\", 0))\n\n if not acknowledged:\n continue\n\n type = related_data.get(\"AS\") # 3=BND, 2=NAP, 1=?\n related_alliance_id = related_data.get(\"AID\")\n related_alliance = Alliance.objects.get(game=kingdom.game, gge_id=related_alliance_id)\n ar = AllianceRelation(alliance_a=alliance, alliance_b=related_alliance, type=type)\n ar.save()\n\n return context, message\n","sub_path":"lib/socket/middleware/alliance.py","file_name":"alliance.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"162748870","text":"#!/usr/bin/python\n\nfrom flask import request\nfrom flask_api import FlaskAPI\nimport RPi.GPIO as GPIO\nimport time\n\nLEDS = {\"green\": 7, \"red\": 5}\nGPIO.setmode(GPIO.BOARD)\nGPIO.setup(LEDS[\"green\"], GPIO.OUT)\nGPIO.setup(LEDS[\"red\"], GPIO.OUT)\n\napp = FlaskAPI(__name__)\n\n@app.route('/', methods=[\"GET\"])\ndef api_root():\n offcount = 0\n incount = 0\n get_color = []\n get_color_status = []\n for color in LEDS:\n status = GPIO.input(LEDS[color])\n if status == 1:\n get_color.append(color)\n get_color_status.append(status)\n incount = incount + 1\n elif status == 0:\n offcount = offcount + 1\n def loop_status(color):\n return{\n get_color[color]:get_color_status[color]\n }\n if incount >= 1:\n return {\n \"status\": [loop_status(color) for color in range(len(get_color))]\n }\n elif offcount == 2:\n return {\n \"status\":\"All LEDs are turned off\"\n }\n\n@app.route('/led/<color>/', methods=[\"GET\", \"POST\"])\ndef api_leds_control(color):\n if request.method == \"POST\":\n if color in LEDS:\n GPIO.output(LEDS[color], 1)\n time.sleep(1)\n GPIO.output(LEDS[color], 0)\n return {color: GPIO.input(LEDS[color])}\n\nif __name__ == \"__main__\":\n app.run()","sub_path":"raspberry_pi/fl-app.py","file_name":"fl-app.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"490411543","text":"\"\"\"Data source specification for Solar Edge data.\n\nSolarEdge supplies an API with their solar panels which allows you to view\nthe power supplied by you panels in high detail. In this module we collect that\ndata and convert it into a useful daily summation of energy production.\n\nSolar Edge API documentation (ca 2019):\nhttps://www.solaredge.com/sites/default/files/se_monitoring_api.pdf\n\"\"\"\nimport datetime\nimport json\nimport os\nimport requests\nimport sqlite3\n\nimport netzero.util\n\n\nclass Solar:\n name = \"solaredge\"\n summary = \"Solar Edge data\"\n\n default_start = datetime.date(2016, 1, 27)\n default_end = datetime.date.today()\n\n def __init__(self, config, database):\n netzero.util.validate_config(\n config, entry=\"solar\", fields=[\"api_key\", \"site_id\"]\n )\n\n self.api_key = config[\"solar\"][\"api_key\"]\n self.site_id = config[\"solar\"][\"site_id\"]\n\n self.conn = sqlite3.connect(database)\n\n self.conn.execute(\n \"CREATE TABLE IF NOT EXISTS solaredge (time TIMESTAMP PRIMARY KEY, watt_hrs FLOAT)\"\n )\n\n def collect(self, start_date=None, end_date=None):\n \"\"\"Collect raw solar data from SolarEdge\n\n Collects data using the SolarEdge API, storing it in the database.\n \n Parameters\n ----------\n start : datetime.date, optional\n The end of the time interval to collect data from\n end : datetime.date, optional\n The end of the time interval to collect data from\n \"\"\"\n if start_date is None:\n start_date = self.default_start\n if end_date is None:\n end_date = self.default_end\n\n cur = self.conn.cursor()\n\n # Iterate through each date range\n for interval in netzero.util.time_intervals(start_date, end_date, days=30):\n netzero.util.print_status(\n \"SolarEdge\",\n \"Collecting: {} to {}\".format(\n interval[0].strftime(\"%Y-%m-%d\"), interval[1].strftime(\"%Y-%m-%d\")\n ),\n )\n\n result = self.query_api(interval[0], interval[1])\n\n for entry in result[\"energy\"][\"values\"]:\n date = datetime.datetime.strptime(entry[\"date\"], \"%Y-%m-%d %H:%M:%S\")\n value = entry[\"value\"] or 0\n\n cur.execute(\n \"INSERT OR IGNORE INTO solaredge VALUES (?, ?)\", (date, value)\n )\n\n self.conn.commit()\n\n cur.close()\n\n netzero.util.print_status(\"SolarEdge\", \"Complete\", newline=True)\n\n def query_api(self, start_date, end_date):\n \"\"\"A method to query the Solar Edge api for energy data\n\n Parameters\n ----------\n start_date : datetime.date\n The start of the time interval to query the api for\n end_date : datetime.date\n The end of the time interval to query the api for\n\n Returns\n -------\n The API response in python dict format:\n {\n \"energy\":{\n \"timeUnit\": _,\n \"unit\":_,\n \"values\":[\n {\n \"date\":\"YYYY-MM-DD HH:MM:SS\",\n \"value\":_\n }, ...\n ]\n }\n }\n \"\"\"\n payload = {\n \"api_key\": self.api_key,\n \"startDate\": start_date.strftime(\"%Y-%m-%d\"),\n \"endDate\": end_date.strftime(\"%Y-%m-%d\"),\n # Even though we condense this data down to a daily sum we still want to\n # collect as much data as possible because perhaps it may some day be\n # useful. Because of this we do quarter of an hour\n \"timeUnit\": \"QUARTER_OF_AN_HOUR\",\n }\n data = requests.get(\n \"https://monitoringapi.solaredge.com/site/\" + self.site_id + \"/energy.json\",\n params=payload,\n )\n return json.loads(data.text)\n\n def min_date(self):\n result = self.conn.execute(\"SELECT date(min(time)) FROM solaredge\").fetchone()[\n 0\n ]\n\n if result is None:\n return None\n else:\n return datetime.datetime.strptime(result, \"%Y-%m-%d\").date()\n\n def max_date(self):\n result = self.conn.execute(\"SELECT date(max(time)) FROM solaredge\").fetchone()[\n 0\n ]\n\n if result is None:\n return None\n else:\n return datetime.datetime.strptime(result, \"%Y-%m-%d\").date()\n\n def format(self, start_date, end_date):\n netzero.util.print_status(\"SolarEdge\", \"Querying Database\")\n\n data = self.conn.execute(\n \"\"\"\n WITH RECURSIVE\n range(d) AS (\n SELECT date(?)\n UNION ALL\n SELECT date(d, '+1 day')\n FROM range\n WHERE range.d <= date(?)\n ),\n data(d, v) AS (\n SELECT date(time), SUM(watt_hrs) / 1000\n FROM solaredge\n GROUP BY date(time)\n )\n SELECT v FROM range NATURAL LEFT JOIN data\"\"\",\n (start_date, end_date),\n )\n\n netzero.util.print_status(\"SolarEdge\", \"Complete\", newline=True)\n\n return data\n","sub_path":"netzero/builtin/solar.py","file_name":"solar.py","file_ext":"py","file_size_in_byte":5357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"137231468","text":"from pymongo import MongoClient\n\nuri = \"mongodb://admin:admin123@ds235411.mlab.com:35411/c4e19-lab\"\n\n# 1. Connect to database\nclient = MongoClient(uri)\nclient = MongoClient(uri)\n# 2. Get database\ndb = client.get_default_database()\ndb1 = client.get_default_database()\n# 3. Create Collection\ngames = db['games']\ndata_game = db1['data game']\n# 4. Create Document\n# new_game = {\n# \"name\": \" Chú cuội tìm trâu \",\n# \"description\": \"League of Legend\"\n# }\n# new_datagame = {\n# \"name\" : \" code python \",\n# \"description\": \" print('hello C4E 19')\"\n# }\n# # 5. Insert doc into collection \n\n# games.insert_one(new_game)\n# data_game.insert_one(new_datagame)\n\n\n# get all document \nall_games = games.find()\n\nprint(all_games[1]['name'])","sub_path":"Lab01/db_intro.py","file_name":"db_intro.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"72854523","text":"import datetime\nimport threading\nimport copy\nimport socket\n\nimport drv_ftdi\n\nHOST = '0.0.0.0'\nSTOP_THREAD = False\n\n\ndef client_thread(board, conn, addr):\n global STOP_THREAD\n last_sec_len_buf = 0\n while not STOP_THREAD:\n try:\n d = conn.recv(1024)\n if not d:\n break\n except socket.error as err:\n print(\"error while receiving:: \" + str(err))\n break\n drv_ftdi.DATA_LOCK.acquire()\n rail_buf = copy.deepcopy(board.data_buf)\n drv_ftdi.DATA_LOCK.release()\n data = datetime.datetime.now().isoformat() + \";\"\n curr_len_buf = len(rail_buf[-1]['voltage'])\n rail_buf_len = curr_len_buf - last_sec_len_buf\n for d_rail in rail_buf:\n tmp_v = d_rail['voltage'][-rail_buf_len:, 1].mean()\n tmp_c = d_rail['current'][-rail_buf_len:, 1].mean()\n tmp_p = tmp_v * tmp_c\n tmp = d_rail['railnumber'] + ':' + str(tmp_p)\n data = data + tmp + \";\"\n try:\n conn.sendall(bytes(data, encoding='utf8'))\n last_sec_len_buf = curr_len_buf\n except socket.error as e:\n print(\"error while sending:: \" + str(e))\n print('Closing connection from {:s}:{:d}'.format(addr[0], addr[1]))\n conn.close()\n\n\ndef run_server(board, port):\n global STOP_THREAD\n thread_process = threading.Thread(target=board.get_data)\n thread_process.start()\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.bind((HOST, port))\n s.listen(10)\n while True:\n try:\n try:\n conn, addr = s.accept()\n print('Accepting connection from {:s}:{:d}'.format(addr[0], addr[1]))\n try:\n threading.Thread(target=client_thread, args=(board, conn, addr)).start()\n except:\n import traceback\n traceback.print_exc()\n except socket.error as err:\n print(\"error while accepting connections:: \" + str(err))\n except KeyboardInterrupt:\n STOP_THREAD = True\n drv_ftdi.FLAG_UI_STOP = True\n s.close()\n break\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"581674555","text":"def CSVWriter (iterable, outLoc, header=\"\", ):\n\n if not iterable:\n print (\"nothing to write\")\n return 0\n\n out = open(outLoc, 'w')\n\n if header:\n out.write(header+'\\n')\n\n #Only works if iterable is a nested list\n for member in iterable:\n for item in member:\n out.write(str(item)+',')\n out.write('\\n')\n\n print(\"write to \"+outLoc+\" successful.\")\n return 1\n\ndef repeater(item, list, reps):\n '''Takes an item and a list and then adds a copy of the item to the list reps number of times.'''\n\n for i in range(reps):\n list.append(item)\n return\n\n","sub_path":"Tools.py","file_name":"Tools.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"73017385","text":"#!/usr/bin/env python3\n\nclass Node:\n\tdef __init__(self, value=None):\n\t\tself.left = None\n\t\tself.right = None\n\t\tself.value = value\n\n# Python trick to pass infinity via string\nINFINITY = float('infinity')\nNEG_INFINITY = float('-infinity')\n\ndef isBST(tree, minVal=NEG_INFINITY, maxVal=INFINITY):\n\t\n\tif tree is None:\n\t\treturn True\n\t\n\tif not minVal <= tree.value <= maxVal:\n\t\treturn False\n\n\treturn isBST(tree.left, minVal, tree.value) and isBST(tree.right, tree.value, maxVal)\n\n# Using inorder tree traversal\ndef isBST2(tree, lastNode=[NEG_INFINITY]):\n\n\tif tree is None:\n\t\treturn True\n\n\tif not isBST2(tree.left, lastNode):\n\t\treturn False\n\n\tif tree.value < lastNode[0]:\n\t\treturn False\n\n\tlastNode[0] = tree.value\n\n\treturn isBST2(tree.right, lastNode)","sub_path":"Mock Interviews/Ride Share Start-Up Company/On-Site-Question-3.py","file_name":"On-Site-Question-3.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"429042552","text":"import time \nimport pigpio\nfrom today import *\nfrom signal_generator import * \nfrom decoding import *\n\npi = pigpio.pi()\n\ndef receive(k):\n\tif(k==0):\n\t\tprint(\"Sender is sleeping? \")\n\tresult=top(0)\n\n\tif not (result==\"Timeout\"):\n\t\tm = str(hamming_decoder(result))\n\t\tif not (m==\"-1\"):\n\t\t\tprint(m)\n\t\t\tgenerate(\"111\")\n\t\telse:\n\t\t\treceive(k-1)\n\telse:\n\t\treceive(k-1)\nreceiver(3)\n","sub_path":"top_receiver.py","file_name":"top_receiver.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"582654830","text":"class NPC(Actor):\n\tdef __init__(self):\n\t\tActor.__init__(self)\n\t\tattributes = {\n\t\t\t'wanderRate'\t: 0,\n\t\t\t'spawnRate'\t\t: 0,\n\t\t\t'numberInRoom'\t: 0,\n\t\t\t'minimumWait'\t: 5000,\n\t\t\t'spawnTime'\t\t: '',\n\t\t\t'pluralName'\t: ''\n\t\t}\n\t\t\n\t\tfor key in attributes.keys():\n\t\t\tself.attributes[key] = attributes[key]","sub_path":"Actor/NPC.py","file_name":"NPC.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"556912135","text":"#ffmpeg -i video_files/Thenextoutbreak_We’renotready_BillGates.mp3 -ss 00:00:00 -codec copy -t 10 video_files/Thenextoutbreak_We’renotready_BillGates/1.mp3\nimport os\nfrom subprocess import Popen, PIPE\nimport datetime\nimport ffmpy\nimport math\n\npath = 'audio_files/'\nfiles = []\n# r=root, d=directories, f = files\nfor r, d, f in os.walk(path):\n files.extend(f)\n break\n\nfor f in files:\n\t\n\t# checking if the directory already exists for video\n\tif (os.path.exists(path+f[0:-4])):\n\t\tcontinue\n\n\t#otherwise split this video and add to directory of same name\n\telse:\n\t\t\n\t\tos.mkdir(path+f[0:-4])\n\t\t\n\t\t# output gives the time duration of the video\n\t\tcomd = \"ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 -sexagesimal \"+path+f\n\t\tstdout = Popen(comd, shell=True, stdout=PIPE).stdout\n\t\toutput = stdout.read()\n\t\t\n\t\t# t is total time hr is hours, m is minutes, sec is seconds for converting to timeframe format\n\t\tt = output[:-8]\n\t\thr = int(t[:-6])\n\t\tm = int(t[-5:-3])\n\t\tsec = int(t[-2:])\n\t\t\n\t\t#total time of audio\n\t\td1 = datetime.timedelta(seconds=sec, minutes=m, hours=hr)\n\t\t\n\t\t#start time of clipped audio\n\t\td2 = datetime.timedelta(seconds=0, minutes=0, hours=0)\n\t\t\n\t\t#end time of clipped audio\n\t\td3 = datetime.timedelta(seconds=0, minutes=5, hours=0)\n\t\tprint(str(d1))\n\t\tprint(str(d2))\n\t\ti=0\n\t\t\n\t\t#while endtime < totaltime\n\t\twhile(d3<d1):\n\t\t\tos.system(\"ffmpeg -i \" + path+f + \" -ss \"+str(d2)+\" -codec copy -t 300 \"+path+f[0:-4]+\"/\"+str(i)+\".wav\")\n\t\t\td2 = d2 + datetime.timedelta(seconds=0, minutes=5, hours=0)\n\t\t\td3 = d3 + datetime.timedelta(seconds=0, minutes=5, hours=0)\n\t\t\ti+=1\n\t\tremain = str(math.floor((d1-d2).total_seconds()))\n\t\tos.system(\"ffmpeg -i \" + path+f + \" -ss \"+str(d2)+\" -codec copy -t \" + remain + ' '+path+f[0:-4]+\"/\"+str(i)+\".wav\")\n\t\t\n\t\t\n\t\t\n\n","sub_path":"split_audio.py","file_name":"split_audio.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"569909126","text":"# _*_ coding:utf-8 _*_\n\nimport sys\nimport csv\nimport json\nimport multiprocessing\nimport time\nfrom multiprocessing import Manager\n# from tqdm import tqdm\n\n\"\"\" this script find duplicats and after create output json \"\"\"\n\n\nDATA = []\nSAVED_LINE_COUNT = 0\nFOUND_EMAILS = 0\n\n\ndef start_emails_result(start, big, out):\n\n ''' start program here; this function will create tuple start.emails '''\n\n result = {\n 'files': {\n 'big': big,\n 'out': out,\n 'start': start\n }\n }\n\n start_emails = set()\n total_start = 0\n with open(start, 'r') as f_in:\n reader = csv.reader(f_in)\n for row in reader:\n email = row[0]\n total_start += 1\n if email in start_emails:\n print('duplicate')\n continue\n start_emails.add(tuple(row))\n result['counts'] = {\n 'start_total_count': total_start,\n 'start_no_duplicates': len(start_emails),\n 'total_duplicates_removed': total_start - len(start_emails)\n }\n return result, start_emails\n\n\ndef start_for_multi(big):\n\n '''prepare list big_lines for multi'''\n\n with open(big, 'r') as r:\n big_lines = [x for x in r.readlines()]\n return big_lines\n\n\ndef flow(header, start_emails, big, out, multi=False, lines=None, DD=None, spamtrap=None, disposable=None, SL=None, FE=None):\n\n '''\n this function takes 'multi' as parametr for multiprocessing\n and lines for multiprocessing also\n DD special list for multiproceesing\n '''\n\n write_headers = False\n\n if header == 0 or header is True:\n write_headers = True\n\n found_emails = set()\n saved_line_count = 0\n write_data = []\n global DATA\n # not_found = set()\n\n # one flow\n if multi is False:\n with open(big, 'r') as fp_in:\n for line in fp_in:\n if write_headers:\n write_data.append('{};{}'.format(\"Result\", line.replace('\\n', '')))\n write_headers = False\n header = False\n continue\n\n found = False\n for row in start_emails:\n if row[0] in line and row[0] not in spamtrap and row[0] not in disposable:\n found = True\n the_r = row[1]\n found_emails.add(row)\n break\n\n if found:\n write_data.append(\"{};{}\".format(the_r, line.replace('\\n', '')))\n saved_line_count += 1\n\n for i in spamtrap:\n if i in line:\n write_data.append(\"{};{}\".format(\"spamtrap\", line.replace('\\n', '')))\n saved_line_count += 1\n break\n for i in disposable:\n if i in line:\n write_data.append(\"{};{}\".format(\"disposable\", line.replace('\\n', '')))\n saved_line_count += 1\n break\n\n DATA.append(write_data)\n\n # multiprocessing start here\n else: # is multiprocessing\n # pbar = tqdm(total=len(lines))\n for line in lines:\n # pbar.update(1)\n if write_headers:\n DD.append('{};{}'.format('Result', line.replace('\\n', '')))\n write_headers = False\n\n found = False\n for row in start_emails:\n if row[0] in line and row[0] not in spamtrap and row[0] not in disposable:\n found = True\n try:\n the_r = row[1]\n FE.append(row)\n break\n except IndexError:\n break\n\n if found:\n SL.value += 1\n DD.append('{};{}'.format(the_r, line.replace('\\n', '')))\n\n for s in spamtrap:\n if s in line:\n FE.append(row)\n SL.value += 1\n DD.append('{};{}'.format('spamtrap', line.replace('\\n', '')))\n break\n\n for s in disposable:\n if s in line:\n FE.append(row)\n SL.value += 1\n DD.append('{};{}'.format('disposable', line.replace('\\n', '')))\n break\n\n\n # write data from process in big world\n global SAVED_LINE_COUNT\n try:\n SAVED_LINE_COUNT += saved_line_count\n except:\n time.sleep(0.3)\n SAVED_LINE_COUNT += saved_line_count\n global FOUND_EMAILS\n FOUND_EMAILS = found_emails\n return 0\n\n\ndef results(result, saved_line_count, found_emails, out):\n ''' create json output and DATA to out'''\n with open(out, 'w') as w:\n pre = []\n for i in DATA[0]:\n l = []\n # 24 may fix doublequote\n for i in i.split(\";\"):\n l.append(i.replace('\"', ''))\n pre.append(l)\n writer = csv.writer(w, delimiter=',')\n writer.writerows(pre)\n print(\"{} was created\".format(out))\n not_found_emails = tuple(set(start_emails - found_emails))\n result['counts'].update({\n 'big_saved_line_count': saved_line_count,\n 'big_email_found_count': len(found_emails),\n 'big_email_not_found_count': len(not_found_emails)\n })\n\n r = json.dumps(result, indent=4, sort_keys=True)\n return r\n\n\ndef spamtrap_disposable(spam, disp):\n\n '''this function will create data of spamtrap and disposable'''\n with open(spam, 'r') as sp, open(disp, 'r') as dp:\n sp = sp.read()\n dp = dp.read()\n sp_r = [x for x in sp.split('\\n')]\n dp_r = [x for x in dp.split('\\n')]\n return sp_r, dp_r\n\nif __name__ == \"__main__\":\n # check amount arg before tart the program\n\n if len(sys.argv) != 6:\n sys.exit('Usage: python {} start.csv big.csv path/to/spamtrap.txt path/to/dispsable.txt out.csv'.format(sys.argv[0]))\n\n start = sys.argv[1]\n big = sys.argv[2]\n spam = sys.argv[3]\n disp = sys.argv[4]\n out = sys.argv[5]\n # start = \"debug/start.csv\"\n # big = \"debug/big.csv\"\n # out = \"out.csv\"\n # spam = 'debug/spamtrap.txt'\n # disp = 'debug/disposable.txt'\n\n # first point\n result, start_emails = start_emails_result(start, big, out)\n emails_from_big = start_for_multi(big)\n spamtrap, disposable = spamtrap_disposable(spam, disp)\n\n # second point prepare thread\n if len(emails_from_big) > 500000:\n print('multiprocessing was started')\n t = int(len(emails_from_big)/100)\n lost = len(emails_from_big) % 100\n emails_from_big = list(emails_from_big)\n thread = [] # that's it\n start, end = 0, 0\n for i in range(100):\n # try:\n if i == 0:\n data = emails_from_big[0: t]\n thread.append(data)\n start = t\n end = start + t\n elif i == 10:\n data = emails_from_big[start: start+lost+1]\n thread.append(data)\n\n else:\n data = emails_from_big[start: end]\n thread.append(data)\n start, end = end, end+t\n\n # second point start here\n # multiprocessing start here\n manager = Manager()\n DD = manager.list()\n SL = manager.Value('i', 0)\n FE = manager.list()\n for e, lines in enumerate(thread):\n p = multiprocessing.Process(target=flow, args=(e, start_emails,\n big, out, True,\n lines, DD, spamtrap,\n disposable, SL, FE,))\n p.start()\n p.join()\n DATA.append(DD)\n SAVED_LINE_COUNT = SL.value\n FOUND_EMAILS = set(FE)\n print('multiprocessing was ended')\n\n # one flow\n else:\n flow(header=True, start_emails=start_emails, big=big, out=out,\n multi=False, lines=None, DD=None, spamtrap=spamtrap, disposable=disposable)\n\n # third point\n\n screen = results(result, SAVED_LINE_COUNT, FOUND_EMAILS, out)\n print(screen)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"86622199","text":"from __future__ import division, absolute_import, print_function\n\nimport os\nimport re\nimport sys\nimport time\nimport shutil\nimport inspect\nimport numbers\nimport warnings\nfrom itertools import chain\nfrom functools import wraps\nfrom collections import OrderedDict, defaultdict, Mapping\nfrom contextlib import contextmanager\nfrom abc import ABCMeta, abstractmethod\nfrom six.moves import zip, range, cPickle\nfrom six import add_metaclass, types, string_types\n\nimport numpy as np\n\nfrom odin import backend as K\nfrom odin.config import randint\nfrom odin.utils import (as_tuple, as_list, uuid, cache_memory, is_number,\n is_string, is_path, is_primitives, ctext,\n flatten_list, get_all_files, is_pickleable,\n FuncDesc, dummy_formatter, type_path,\n get_module_from_path, wprint)\nfrom odin.backend.role import (add_roles, has_roles, Parameter, Weight, Bias,\n TrainableParameter, NNOpOutput)\nfrom odin.nnet.base_desc import VariableDesc\n\nimport tensorflow as tf\nfrom tensorflow.python.ops import init_ops\n\n# ===========================================================================\n# Other helpers\n# ===========================================================================\ndef _get_vars_footprint(vars):\n return ';'.join([v.name for v in vars])\n\n# ===========================================================================\n# Global NNOp manager\n# ===========================================================================\ndef get_all_nnops(scope=None, op_type=None):\n \"\"\" Return a dictionary of (name, nnops) for all created NNOp \"\"\"\n allops = list(NNOp._ALL_NNOPS.values())\n # ====== matching the name scope ====== #\n if scope is not None:\n if not is_string(scope):\n scope = scope.name\n allops = [o for o in allops if o.name[:len(scope)] == scope]\n # ====== matching the NNOp type ====== #\n if op_type is not None:\n op_type = [i for i in as_tuple(op_type)\n if is_string(op_type) or issubclass(op_type, NNOp)]\n allops = [o for o in allops\n if any(o.__class__.__name__ == t if is_string(t)\n else isinstance(o, t)\n for t in op_type)]\n # ====== sorted by created time (earlier first) ====== #\n allops = sorted(allops, key=lambda x: x.timestamp,\n reverse=False)\n return allops\n\ndef _assign_new_nnop(nnop):\n if not isinstance(nnop, NNOp):\n raise ValueError(\"The new assigned NNOp must be instance of odin.nnet.NNOp \"\n \", but the given object has type: %s\" %\n str(type(nnop)))\n name = nnop.name\n if not nnop.is_initialized:\n raise RuntimeError(\"Given NNOp with name: '%s' has not been initialized\"\n % name)\n if name in NNOp._ALL_NNOPS:\n raise RuntimeError(\"Cannot created NNOp with duplicated name, another NNOp \"\n \"of type: %s, and name: '%s' has already existed\" %\n (type(NNOp._ALL_NNOPS[name]), name))\n NNOp._ALL_NNOPS[name] = nnop\n\n# ===========================================================================\n# Arguments scope\n# ===========================================================================\n__ARGS_SCOPE_STACK = [defaultdict(dict)]\n\ndef get_args_scope():\n return __ARGS_SCOPE_STACK[-1].copy()\n\n@contextmanager\ndef args_scope(*ops_kwargs, **kwargs):\n \"\"\"Stores the default arguments for the given set of applied_nnops.\n\n For usage, please see examples at top of the file.\n\n Parameters\n ----------\n ops_kwargs : series of list or tuple\n Contain the mapping from (`list_or_single_NNOp`, `**kwargs`)\n - The `list_or_single_NNOp` can be represented by string (name\n of a specific NNOp, or name the NNOp class), class (instance\n of NNOp), object (instance of any class inherited NNOp),\n list or tuple (which is the list of all above option).\n - `**kwargs` is list or dictionary containing the tuple of\n (keyword, value) that will define the defaults for each op in\n the listed ops\n kwargs : **kwargs\n default keywoard arguments for all given `NNOp` in `ops_kwargs`\n\n Return\n ------\n the current_scope, which is a dictionary of {op: {arg: value}}\n\n Raises\n ------\n TypeError: if list_ops is not a list or a tuple.\n ValueError: if any op in list_ops has not be decorated with @add_arg_scope.\n\n Note\n ----\n if the name scope is given, an incremental ID is generated for\n duplicated NNOp instead of UUID.\n \"\"\"\n new_scope = defaultdict(dict)\n for ops, kw in ops_kwargs:\n if isinstance(kw, (tuple, list)):\n kw = dict(kw)\n if not isinstance(ops, (tuple, list)):\n ops = [ops]\n for o in ops:\n new_scope[o].update(kw)\n # ====== update Arguments Scope ====== #\n # copy prevous scopes\n args_scope = defaultdict(dict)\n for i, j in __ARGS_SCOPE_STACK[-1].items():\n args_scope[i] = j.copy()\n # update new scopes\n for op, kw in new_scope.items():\n args_scope[op].update(kw)\n # add the default kwargs\n for kw in args_scope.values():\n kw.update(kwargs)\n __ARGS_SCOPE_STACK.append(args_scope)\n # ====== return the scope ====== #\n yield None\n # ====== reset everything ====== #\n __ARGS_SCOPE_STACK.pop()\n\n# ===========================================================================\n# NNOp scope\n# ===========================================================================\n# each element is a list [scope_name, current_id]\n_NNOP_SCOPE_STACK = []\n\ndef get_nnop_scope():\n # each element is a list [scope_name, current_id]\n if len(_NNOP_SCOPE_STACK) == 0:\n return ['', uuid()]\n return _NNOP_SCOPE_STACK[-1]\n\n@contextmanager\ndef nnop_context(scope, reuse=None):\n \"\"\" A more generalized version of `tensorflow.variable_scope`,\n this function will also set the NNOp scope so any NNOp created within\n given scope will be affected\n\n Parameters\n ----------\n scope: string\n the name of current scope, new NNOp will be created as \"scope/name\"\n reuse: bool\n whether reuse variables for tensorflow.variable_scope\n\n Example\n -------\n >>> X = K.variable(x, name='x')\n >>> with N.nnop_scope(scope='s1'):\n ... f1 = N.Dense(8)\n ... f1(X)\n ... with N.nnop_scope(scope='s2'):\n ... f2 = N.Dense(25)\n ... f2(X)\n ... with N.nnop_scope(scope='s1', prefix='S'):\n ... f3 = N.Dense(12)\n ... f3(X)\n >>> with N.nnop_scope(scope='s1/s2', prefix='S'):\n ... f4 = N.Dense(num_units=13)\n ... f4(X)\n >>> # f1: s1/Dense_0\n >>> # f2: s1/s2/Dense_0\n >>> # f3: s1/s2/Dense_S0\n >>> # f4 == f3\n >>> print(N.get_all_nnops(scope='s1/s2')) # contains 2 NNOp\n >>> print(N.get_all_nnops(scope='s1')) # contains 3 NNOp\n \"\"\"\n if not is_string(scope) or len(scope) == 0:\n raise ValueError(\"`scope` must be string type, length > 0.\")\n # ====== prepare Name Scope ====== #object\n curr_scope, curr_opID = get_nnop_scope()\n # NO duplicate scope\n if scope not in curr_scope:\n curr_scope = scope if len(curr_scope) == 0 else \\\n curr_scope + '/' + scope\n # name scope\n _NNOP_SCOPE_STACK.append([curr_scope, 0])\n # ====== return the scope ====== #\n var_scope = tf.get_variable_scope().name\n # NO repeating the scope in variable scope\n if any(s == scope for s in var_scope.split('/')): # this may cause error\n yield curr_scope\n else:\n with tf.variable_scope(scope, reuse=reuse):\n yield curr_scope\n # ====== reset everything ====== #\n _NNOP_SCOPE_STACK.pop()\n\n# ===========================================================================\n# Main Ops\n# ===========================================================================\nclass _NNOp_Meta(ABCMeta):\n \"\"\" This meta-class ensure the NNOp argument scope is applied\n\n Note\n ----\n you can only modify the arguments and kwarguments using __call__\n from MetaClass, not __new__ of instance class.\n \"\"\"\n def __new__(mcs, name, bases, class_dict):\n private = {'T', 'apply', '__call__', '__getstate__', '__setstate__',\n '__getnewargs__', 'get', 'get_variable_nnop', '__setattr__',\n 'input_shape', 'placeholders', 'last_output', 'apply'}\n if name != 'NNOp':\n for attr in private:\n if attr in class_dict:\n raise RuntimeError(\"[Class:%s]The behavior of NNOp is \"\n \"restricted to ensure properly operations, the following \"\n \"methods or properties cannot be override: '%s'\" %\n (ctext(name, 'red'), ctext(attr, 'yellow')))\n return super().__new__(mcs, name, bases, class_dict)\n\n def __call__(clazz, *args, **kwargs):\n assert issubclass(clazz, NNOp), \\\n \"NNOpMeta should only be used for NNOp subclass\"\n # getting the default arguments to check user intentionally override\n # default argument.\n sign = inspect.signature(clazz.__init__)\n # ignore the self argument\n default_args = OrderedDict([(n, p.default)\n for i, (n, p) in enumerate(sign.parameters.items())\n if i > 0 and\n p.kind not in (inspect.Parameter.VAR_POSITIONAL,\n inspect.Parameter.VAR_KEYWORD)])\n # ====== update the current argument scope ====== #\n # get current scope\n key_name = [clazz, str(clazz), clazz.__name__]\n current_scope = get_args_scope()\n for n in key_name:\n if n in current_scope:\n default_args.update(current_scope[n])\n # ====== update user specified args and kwargs ====== #\n # update the new arguments into default arguments\n new_kwargs = OrderedDict([\n (name, args[i]) if i < len(args) else (name, default)\n for i, (name, default) in enumerate(default_args.items())])\n new_kwargs.update(kwargs)\n # ====== create new instance and __init__ if necessary ====== #\n # This will call NNOp.__new__ to create an instance of NNOP,\n # if it found a duplicated NNOp pre-defined, it will return\n # the defined NNOp instead.\n op = clazz.__new__(clazz, *[], **new_kwargs)\n if not hasattr(op, '_name'):\n raise ValueError(\"NNOp must be given a name when initialized.\")\n # check if op already initialized\n if op.name not in NNOp._ALL_NNOPS:\n clazz.__init__(op, *[], **new_kwargs)\n return op\n\n@add_metaclass(_NNOp_Meta)\nclass NNOp(NNOpOutput):\n \"\"\" Basics of all Neural Network operators\n\n Properties\n ----------\n name: str\n identity of the operator, this name is the scope for its operator\n and should be unique.\n\n T: NNOp\n transpose operator of this one (NOTE: some ops does not support\n transpose and raise NotImplementedError)\n\n parameters: list of variables\n list of all parameters associated with this operator scope\n\n Abstract\n --------\n _apply(self, X, **kwargs): resulted variables\n apply take a list of variables and custom parameters to compute\n output variables\n _initialize(self, **kwargs):\n create parameters\n\n Override\n --------\n _transpose(self): NNOp\n return another NNOp which is transposed version of this ops\n\n Note\n ----\n All NNOp are pickle-able!\n You must use: protocol=cPickle.HIGHEST_PROTOCOL when dump NNOp.\n if NNOp is applied to a list of inputs, it will process each input seperated.\n \"\"\"\n _ALL_NNOPS = {}\n\n @classmethod\n def search(clazz, name, path=None, prefix='model'):\n \"\"\" This method search for any objects decorated or instance\n of given NNOp\n from given `path` with all script have given `prefix`\n\n Parameters\n ----------\n name : string\n specific name of finding object\n\n path : {string, list of string}\n single folder or list of folder (or file) to search\n for the desire module\n\n prefix : string\n prefix for filtering .py file\n \"\"\"\n # ====== check path ====== #\n if path is None:\n possible_path = ['.', './models', './model', './.models', './.model']\n script_path = os.path.dirname(sys.argv[0])\n path = [os.path.join(script_path, p) for p in possible_path]\n path = [p for p in path if os.path.exists(p) and os.path.isdir(p)]\n elif not isinstance(path, (tuple, list)):\n path = [path]\n if len(path) == 0:\n raise ValueError(\"Cannot find any available directory that contain the \"\n \"model script.\")\n # ====== search for model ====== #\n all_errors = {}\n for p in path:\n model_func, errors = get_module_from_path(name, path=p, prefix=prefix,\n return_error=True)\n all_errors.update(errors)\n model_func = [f for f in model_func\n if isinstance(f, clazz)]\n if len(model_func) == 0:\n print(\n ctext(\"The following Exception happened during loading the modules:\",\n 'lightred'))\n for fpath, error in all_errors.items():\n print(\" \", fpath, \":\", ctext(error, 'red'))\n raise ValueError(\"Cannot find any model creator function with name='%s' \"\n \"at paths='%s'\" % (name, '; '.join(path)))\n return model_func[0]\n\n def __new__(clazz, *args, **kwargs):\n \"\"\" This __new__ ensures no NNOp with duplicated name and type is\n created, hence, if it found a duplicated one, it will return the\n duplicated \"\"\"\n # ====== cPickle call __new__ ====== #\n if len(args) == 1 and len(kwargs) == 0 and \\\n (is_string(args[0]) and '[__name__]' in args[0]):\n name = args[0].replace('[__name__]', '')\n # Found predefined NNOP\n if name in NNOp._ALL_NNOPS:\n instance = NNOp._ALL_NNOPS[name]\n if not isinstance(instance, clazz):\n raise RuntimeError(\"Found duplicated NNOp with type: '%s', \"\n \"which is different from pickled type: '%s'\" %\n (type(instance), clazz))\n return instance\n # just create new instance\n return super(NNOp, clazz).__new__(clazz)\n # ====== For first time create instance ====== #\n # update Op name if it is None\n name = kwargs.get('name', None)\n op_scope = get_nnop_scope()\n # ====== special case Lambda op ====== #\n if clazz == Lambda:\n func = kwargs['func']\n assert inspect.isfunction(func) or inspect.ismethod(func),\\\n \"func for odin.nnop.base.Lambda must be a callable function or method\"\n full_path = [i\n for i in func.__qualname__.split('.')\n if '<locals>' not in i]\n func_scope = full_path[:-1]\n func_name = full_path[-1]\n if name is None:\n name = func_name + '_' + str(op_scope[1])\n else:\n name = name\n # ====== general case ====== #\n else:\n # automatic generate name\n if name is None:\n name = clazz.__name__ + '_' + str(op_scope[1])\n # regulation for the NNOp name\n elif is_string(name):\n if '/' in name or ':' in name:\n raise ValueError(\"NNOp cannot contain '\\\\' or ':', given name is: %s\" % name)\n # exception no support for given type\n else:\n raise ValueError(\"`name` for NNOp must be string, function, but given \"\n \"`name` with type: %s\" % name)\n # ====== add the scope ====== #\n # add scope to name\n if len(op_scope[0]) > 0:\n name = op_scope[0] + '/' + name\n op_scope[1] += 1\n # ====== check duplicated Op name ====== #\n if name in NNOp._ALL_NNOPS:\n old_clazz = NNOp._ALL_NNOPS[name].__class__\n if clazz != old_clazz:\n raise RuntimeError(\"Found predefined NNOp with type: %s, but \"\n \"the new NNOp has type: %s\" % (old_clazz, clazz))\n return NNOp._ALL_NNOPS[name]\n # ====== allocate new Op ====== #\n created_time = time.time()\n new_op = super(NNOp, clazz).__new__(clazz)\n new_op._name = name\n new_op._timestamp = created_time\n # this store spontaneous args and kwargs feed to apply()\n new_op._current_args = ()\n new_op._current_kwargs = {}\n # all save-able attributes of NNOp store here\n new_op._save_states = {'_name': name,\n '_timestamp': created_time}\n return new_op\n\n def __init__(self, **kwargs):\n # mapping: name -> VariableDesc, or Primitives\n self._kwargs_desc = OrderedDict()\n # mapping: ','.join(id(tensor)) -> output\n self._cache_outputs = {}\n self._last_input_footprint = ''\n self._transpose_ops = None\n self._is_initialized = False\n # mapping: variable_name -> (tensorflow_name, 'tensor' or 'variable')\n self._variable_info = OrderedDict()\n # special flags to detect if cPickle called with protocol >= 2\n self._new_args_called = False\n # this is special tricks, the unpickled ops stay useless\n # until its variables are restored, but if we restore the\n # variable right away, it create a session and prevent\n # any possibility of running tensorflow with multiprocessing\n # => store the _restore_vars_path for later, and restore\n # the variable when the NNOp is actually in used.\n self._set_restore_info(None, False)\n\n # ==================== variable restoring ==================== #\n def _set_restore_info(self, vars_path, delete_after):\n self._restore_vars_path = vars_path\n self._delete_vars_folder = bool(delete_after)\n return self\n\n def _restore_variables(self):\n \"\"\" This method can be called anywhere to make sure\n the variable related to this NNOp is restored after\n pickling.\n \"\"\"\n if hasattr(self, '_restore_vars_path') and \\\n self._restore_vars_path is not None:\n folder_path = os.path.dirname(self._restore_vars_path)\n if os.path.exists(folder_path):\n K.restore_variables(self._restore_vars_path)\n # delete cached folder if necessary\n if self._delete_vars_folder:\n shutil.rmtree(folder_path)\n else:\n wprint(\"NNOp: '%s' cannot restore variables from path: '%s'\"\n (self.name, folder_path))\n # reset info\n self._set_restore_info(None, False)\n\n # ==================== pickling method ==================== #\n def __getstate__(self):\n if not self._new_args_called:\n raise RuntimeError(\n \"You must use argument `protocol=cPickle.HIGHEST_PROTOCOL` \"\n \"when using `pickle` or `cPickle` to be able pickling NNOp.\")\n self._new_args_called = False\n # add nnops here so all related NNOps are saved\n return self._save_states, self.nnops\n\n def __setstate__(self, states):\n # ====== default attribute ====== #\n self._current_args = ()\n self._current_kwargs = {}\n self._cache_outputs = {}\n # ====== save states ====== #\n self._save_states, nnops = states\n for key, val in self._save_states.items():\n setattr(self, key, val)\n # ====== check exist NNOp ====== #\n if self.name not in NNOp._ALL_NNOPS:\n _assign_new_nnop(self)\n elif NNOp._ALL_NNOPS[self.name] != self:\n raise RuntimeError(\"Mismatch NNOp, two NNOps with the same name \"\n \"are initizlied:\\n%s\\nis different from:\\n%s\" %\n (str(NNOp._ALL_NNOPS[self.name]), str(self)))\n\n def __getnewargs__(self):\n self._new_args_called = True\n return ('[__name__]' + self.name,)\n\n # ==================== properties ==================== #\n @property\n def save_states(self):\n \"\"\" Save state is dictionary of attribute name -> object\n those will be saved during pickling\n\n Note\n ----\n This property return a copy of the dictionary, any\n modification won't take effect on NNOp\n \"\"\"\n return dict(self._save_states)\n\n def get(self, name, nnop=False):\n \"\"\"\"Simple shortcut for getting defined Variable, or NNOp\n within the scope of this `NNOp`\n\n Parameters\n ----------\n name : string\n the name, or part of the name of the `Variable` or `NNOp`\n nnop : bool\n if you want to get a `NNOp` with given name instead of\n `Variable`\n \"\"\"\n # ====== get variable ====== #\n if not nnop:\n if isinstance(name, bytes):\n name = str(name, 'utf-8')\n elif not is_string(name):\n raise ValueError(\"`name` must be string.\")\n if name not in self._variable_info:\n raise ValueError(\"Variable with name: '%s' hasn't been created.\" % name)\n return self.get_variable_nnop(name=name)\n # ====== nnop ====== #\n for op in self.nnops:\n if name == op.name:\n return op\n raise ValueError(\"Cannot find `NNOp` with name: '%s'\" % name)\n\n @cache_memory\n def get_variable_nnop(self, name, shape=None, initializer=None, roles=[]):\n \"\"\" Initialize and return the Variable or NNOp with given description\n\n Parameters\n ----------\n name: str\n name for the variable\n shape: tuple, list\n expected shape for given variable\n initializer: variable, numpy.ndarray, function\n specification for initializing the weights, if a function\n is given, the arguments must contain `shape`\n roles: `odin.backend.role.Role`\n categories of this variable\n \"\"\"\n self._restore_variables() # restore variable first\n if name in self.__dict__:\n raise RuntimeError(\"name='%s' has been defined in dictionary of \"\n \"NNOp: '%s', type: %s\" %\n (name, self.name, self.__class__.__name__))\n if shape is not None:\n # convert to tuple if needed\n shape = as_tuple(shape)\n if any(d <= 0 or d is None for d in shape):\n raise ValueError((\n \"Cannot create param with a non-positive shape dimension. \"\n \"Tried to create param with shape=%r, name=%r\") %\n (shape, name))\n #####################################\n # 1. looking for Defined variable.\n if initializer is None and shape is None:\n if name not in self._variable_info:\n raise ValueError(\"Cannot find variable with name: %s for NNOps \"\n \"with name: %s\" % (name, self.name))\n var_name, t = self._variable_info[name]\n # get variable\n if t == 'variable':\n var = K.get_all_variables(full_name=var_name)\n if len(var) == 0:\n raise RuntimeError(\"Cannot find variable with name: %s\" % var_name)\n var = var[0]\n # get tensor\n elif t == 'tensor':\n name, footprint = var_name\n op = K.get_all_operations(footprint=footprint)\n if len(op) == 0:\n raise RuntimeError(\"Cannot find any Op with given footprint: %s\" % footprint)\n var = op[0]._outputs[int(name.split(':')[-1])]\n # get nnops, use current args and kwargs for initialization\n elif t == 'nnop':\n var = var_name(*self._current_args, **self._current_kwargs)\n # only care about the first variable\n return add_roles(var, roles)\n #####################################\n # 2. initializing function.\n create_new_var = False\n if is_string(initializer):\n var = K.get_all_variables(name=initializer)\n if len(var) == 0:\n var = K.get_all_tensors(name=initializer)\n if len(var) == 0:\n raise ValueError(\"Cannot find any variable or tensor with name: \"\n \"'%s' for the initializer.\" % initializer)\n var = var[0]\n # is instance of NNOp\n elif isinstance(initializer, NNOp):\n var = initializer\n # is a callable\n elif hasattr(initializer, '__call__'):\n var = initializer(shape)\n if isinstance(var, np.ndarray) or\\\n isinstance(initializer, init_ops.Initializer):\n create_new_var = True\n # is a scalar\n elif is_number(initializer):\n var = np.full(shape=shape, fill_value=initializer, dtype='float32')\n create_new_var = True\n # numpy array\n elif isinstance(initializer, np.ndarray):\n var = initializer\n create_new_var = True\n # actual tensor\n else:\n var = initializer\n #####################################\n # 3. Numpy ndarray.\n if create_new_var:\n var = K.variable(var, shape=shape, name=name)\n self._variable_info[name] = (var.name, 'variable')\n #####################################\n # 4. Shared variable, just check the shape.\n elif K.is_variable(var):\n _shape = var.shape.as_list()\n if shape is not None and tuple(shape) != tuple(_shape):\n raise Exception('Require variable with shape=%s, but was given different '\n 'shape=%s, name:%s.' %\n (str(shape), str(_shape), str(name)))\n self._variable_info[name] = (var.name, 'variable')\n #####################################\n # 5. expression, we can only check number of dimension.\n elif K.is_tensor(var):\n # We cannot check the shape here, Tensor (even shared\n # variables) do not have a fixed compile-time shape. We can check the\n # dimensionality though.\n # Note that we cannot assign a name here. We could assign to the\n # `name` attribute of the variable, but the user may have already\n # named the variable and we don't want to override this.\n if shape is not None and var.shape.ndims != len(shape):\n raise Exception(\"parameter with name=%s has %d dimensions, should be \"\n \"%d\" % (name, var.shape.ndims, len(shape)))\n self._variable_info[name] = ((var.name, K.get_operation_footprint(var.op)),\n 'tensor')\n elif isinstance(var, NNOp):\n self._variable_info[name] = (var, 'nnop')\n #####################################\n # 6. Exception.\n else:\n print(initializer)\n raise RuntimeError(\"cannot initialize parameters \"\n \"(name:%s - shape:%s - roles: %s): \"\n \"the `initializer` is not a numpy array, \"\n \"a Tensor expression, a call-able, \"\n \"or variable name as string (given type: %s)\" %\n (name, shape, roles, str(type(initializer))))\n # ====== assign annotations ====== #\n if K.is_tensor(var):\n return add_roles(var, roles)\n elif isinstance(var, NNOp):\n return var\n else:\n raise ValueError(\"Unsupport for variable type: %s\" %\n type(var).__name__)\n\n @property\n def name(self):\n return self._name\n\n @property\n def timestamp(self):\n return self._timestamp\n\n @property\n def T(self):\n \"\"\" Return new ops which is transpose of this ops \"\"\"\n if not self.is_initialized:\n raise RuntimeError(\"NNOp with name:'%s' has not been initialized, \"\n \"call the Op on any input to first initialize input information.\"\n % self.name)\n if self._transpose_ops is None:\n self._transpose_ops = self._transpose()\n if not isinstance(self._transpose_ops, NNOp):\n raise ValueError(\"The _transposed method must return NNOp.\"\n \"but the returned object has type=%s\" %\n str(type(self._transpose_ops)))\n # hard-fix the name of transpose NNOp\n self._transpose_ops._name = self.name + '_T'\n # this is very brain twisted\n self._transpose_ops._transpose_ops = self\n return self._transpose_ops\n\n @property\n def variables(self):\n \"\"\" Get all variables related to this Op, which include:\n\n - Initialized Variables\n - Variables belong to related NNOp within this Op.\n - Variables belong to related Tensor within this Op.\n - Variables within the scope of this NNOp.\n\n Note\n ----\n initialize all variables (basically, all Variables\n within this NNOp scope are initialized when you call\n `NNOp.variables`.\n \"\"\"\n # ====== # restore variable first ====== #\n self._restore_variables()\n # ====== get all variables ====== #\n global_vars = {v.name: v for v in K.get_all_variables()}\n all_vars = []\n tensors = []\n for alias, (name, vtype) in self._variable_info.items():\n if vtype == 'variable':\n all_vars.append(global_vars[name])\n elif vtype == 'tensor':\n tensors.append(self.get_variable_nnop(alias))\n elif vtype == 'nnop':\n all_vars += name.variables\n # all variables from tensor\n all_vars += K.ComputationGraph(tensors).variables\n # all variables from NNOp\n for op in self.nnops:\n all_vars += op.variables\n # all variables within the scope\n all_vars += K.get_all_variables(scope=self.name)\n all_vars = tuple(sorted(set(all_vars), key=lambda x: x.name))\n # exception ignore variable with name IsTraining__\n all_vars = [v for v in all_vars if 'IsTraining__' not in v.name]\n return all_vars\n\n @property\n def nb_variables(self):\n n = 0\n for p in self.variables:\n n += np.prod(p.shape.as_list()).astype('int32')\n return n\n\n @property\n def parameters(self):\n \"\"\" return all TensorVariables which have the PARAMETER role\"\"\"\n return [i for i in self.variables if has_roles(i, Parameter)]\n\n @property\n def trainable_parameters(self):\n \"\"\" return all TensorVariables which have the TrainableParameter role\"\"\"\n return [i for i in self.variables if has_roles(i, TrainableParameter)]\n\n @property\n def nb_parameters(self):\n n = 0\n for p in self.parameters:\n n += np.prod(p.shape.as_list()).astype('int32')\n return n\n\n @property\n def is_initialized(self):\n return self._is_initialized\n\n @property\n def variable_info(self):\n return dict(self._variable_info)\n\n @property\n def nnops(self):\n \"\"\" Return all NNOp belong to\n * the initialization of this Op\n * or within the scope of this Op.\n \"\"\"\n ops = []\n for name, (var, vtype) in self._variable_info.items():\n if vtype == 'nnop':\n ops.append(var)\n ops += get_all_nnops(scope=self.name)\n # make sure all the nested NNOp has the same _restore_vars_path\n # TODO: this is not good idea, if nested NNOp also restore the\n # variables, it will restore variables multiple times.\n # if hasattr(self, '_restore_vars_path') and \\\n # self._restore_vars_path is not None:\n # for o in ops:\n # if not hasattr(o, '_restore_vars_path') or \\\n # o._restore_vars_path is None:\n # o._restore_vars_path = self._restore_vars_path\n # o._delete_vars_folder = self._delete_vars_folder\n # ====== remove duplicate NNOp ====== #\n final_ops = []\n for o in ops:\n if o is not self and o not in final_ops:\n final_ops.append(o)\n return final_ops\n\n @property\n def placeholders(self):\n \"\"\" Create list of placeholder to represent inputs of this NNOp\n \"\"\"\n x = [i.placeholder for i in self._kwargs_desc.values()\n if isinstance(i, VariableDesc)]\n return x[0] if len(x) == 1 else x\n\n def set_placeholder(self, name, plh):\n return self._kwargs_desc[name].set_placeholder(plh)\n\n @property\n def last_output(self):\n if self._last_input_footprint not in self._cache_outputs:\n raise RuntimeError(\"This NNOp has not been called, and contains \"\n \"no information about outputs.\")\n return self._cache_outputs[self._last_input_footprint]\n\n @property\n def input_shape(self):\n \"\"\"NOTE: this input shape is only inferred from last inputs to\n this NNOp,\n since the input argument can has default argument, this input\n shape can change after everytime you call the NNOp\"\"\"\n x = [tuple(i.shape.as_list())\n for i in as_tuple(self.placeholders)]\n return x[0] if len(x) == 1 else x\n\n @property\n def input_shape_map(self):\n return {k: tuple(v.placeholder.shape.as_list())\n for k, v in self._kwargs_desc.items()\n if isinstance(v, VariableDesc)}\n\n @property\n def output_shape(self):\n \"\"\"NOTE: this input shape is only inferred from last inputs to\n this NNOp,\n since the input argument can has default argument, this input\n shape can change after everytime you call the NNOp\"\"\"\n output = self.last_output\n extract_shape = lambda x: tuple(x.shape.as_list()) \\\n if hasattr(x, 'get_shape') else \\\n (x.shape if hasattr(x, 'shape') else ())\n if isinstance(output, (tuple, list)):\n return [extract_shape(o) for o in output]\n elif isinstance(output, Mapping):\n return OrderedDict([(name, extract_shape(o))\n for name, o in output.items()])\n return extract_shape(output)\n\n def __setattr__(self, name, value):\n # this record all assigned attribute to pickle them later\n # check hasattr to prevent recursive loop at the beginning before\n # __init__ is called\n if hasattr(self, '_save_states'):\n if name not in ('_save_states', '_cache_outputs',\n '_current_args', '_current_kwargs',\n '_last_input_footprint'):\n if is_primitives(value, inc_ndarray=True,\n exception_types=[NNOp, FuncDesc]) or \\\n (hasattr(value, '__call__') and is_pickleable(value)):\n self._save_states[name] = value\n return super(NNOp, self).__setattr__(name, value)\n\n # ==================== abstract method ==================== #\n def _initialize(self):\n \"\"\" This function is only called once, for the first time you\n apply this Ops\n \"\"\"\n return None\n\n @abstractmethod\n def _apply(self, X, **kwargs):\n raise NotImplementedError\n\n def _transpose(self):\n raise NotImplementedError\n\n # ==================== interaction method ==================== #\n def _check_input_arg(self, x, name):\n \"\"\"Validate input argument to `apply` function\n\n Parameters\n ----------\n x : {tensor, primitive}\n given symbol for the argument\n name : string\n name of the argument\n\n Return\n ------\n tuple of (VariableDesc, raw_data)\n VariableDesc: can be None if only given a primitive data types\n raw_data: can be None if only give VariableDesc\n \"\"\"\n desc = None\n data = None\n # ====== if given tensor, use the provided tensor ====== #\n if K.is_tensor(x) or isinstance(x, VariableDesc):\n desc = x if isinstance(x, VariableDesc) else\\\n VariableDesc(shape=x, name=x.name.split(':')[0])\n # keywords argument\n if name not in self._kwargs_desc:\n self._kwargs_desc[name] = desc\n curr_desc = self._kwargs_desc[name]\n # validating\n if isinstance(curr_desc, VariableDesc) and not curr_desc.is_equal(desc):\n raise ValueError(\"Found stored argument with description: '%s', given new \"\n \"argument with description: '%s'\" % (str(curr_desc), str(desc)))\n # overriding primitive\n else:\n self._kwargs_desc[name] = desc\n # ====== if given raw data, use saved tensor with new data ====== #\n elif isinstance(x, np.ndarray):\n # keywords\n if name not in self._kwargs_desc:\n self._kwargs_desc[name] = VariableDesc(\n shape=x.shape, dtype=x.dtype,\n name='VarArg%d' % int(name[1:]) if '.' == name[0] else name)\n desc = self._kwargs_desc[name]\n # validating\n if desc.shape[1:] != x.shape[1:] or \\\n np.dtype(desc.dtype) != np.dtype(x.dtype):\n raise ValueError(\"NNOp has input description: '%s', given \"\n \"ndarray: shape=%s dtype=%s\" %\n (str(desc), x.shape, x.dtype))\n # set data\n data = x\n # ====== primitive, keep it simple ====== #\n elif is_primitives(x, inc_ndarray=False):\n self._kwargs_desc[name] = x\n desc = x\n # ====== Uknown input, ERROR ====== #\n else:\n raise ValueError(\"The input argument for NNOp can be: \"\n \"`Tensor`, `odin.nnet.VariableDesc`, and primitive types\"\n \" (string, number, boolean, None, numpy.ndarray, numpy.generic).\"\n \" But the given type is: name='%s' : value=`%s`)\" %\n (name, str(x)))\n return (desc, data)\n\n def apply(self, *args, **kwargs):\n # ====== restore variable first ====== #\n self._restore_variables()\n # ====== self.name can contain Model varable scope, hence,\n # remove the scope here ====== #\n op_name = self.name.split('/')[-1]\n with nnop_context(scope=op_name, reuse=self.is_initialized):\n # ====== processing argument information ====== #\n # auto omit `self` argument\n sign = inspect.signature(self._apply)\n arg_name = []\n default_kwargs = {}\n inc_var_pos = False\n inc_var_key = False\n for n, p in sign.parameters.items():\n if p.kind == inspect.Parameter.VAR_POSITIONAL:\n inc_var_pos = True\n elif p.kind == inspect.Parameter.VAR_KEYWORD:\n inc_var_key = True\n else:\n arg_name.append(n)\n if p.default != inspect.Parameter.empty:\n default_kwargs[n] = p.default\n num_args = len(arg_name)\n # adding kwargs_new in Order\n kwargs_new = OrderedDict()\n # varargs arguments is named with '.' at the beginning\n pos_name = ['.%d' % i for i in range(len(args) - num_args)] if inc_var_pos else []\n # kwargs name\n key_name = [name for name in kwargs.keys() if name not in arg_name] if inc_var_key else []\n # get all positional arguments\n for idx, name in enumerate(arg_name + pos_name + key_name):\n if idx < len(args):\n x = args[idx]\n elif name in kwargs:\n x = kwargs[name]\n elif name in default_kwargs:\n x = default_kwargs[name]\n else: # not specified, use saved arguments\n # wprint('Cannot find argument at index: %d, name: %s' % (idx, name))\n continue\n # validate and record name to self._kwargs_desc\n kwargs_new[name] = self._check_input_arg(x=x, name=name)\n # kwargs now contains: arg_name -> (VariableDesc, ndarray(or None))\n kwargs = kwargs_new\n # add missing slot from _kwargs_desc\n for name, var in self._kwargs_desc.items():\n if name not in kwargs:\n kwargs[name] = (var, None)\n # ====== create footprint for unique arguments identification ====== #\n # footprint created by concat argument name and its\n # object python ID (primitive arugment using str)\n footprint = ''\n # positional argument\n for name, (desc, dat) in sorted(kwargs.items(),\n key=lambda x: x[0]):\n footprint += name + ':'\n if isinstance(desc, VariableDesc): # Tensor types\n desc = desc.placeholder\n footprint += type_path(desc) + '_' + str(id(desc))\n else: # primitive types\n footprint += type_path(desc) + '_' + str(desc)\n footprint += '|'\n # ====== convert all information to new op args and kwargs ====== #\n # store current arguments\n self._current_args = []\n included_names = []\n # positional args\n for name in arg_name:\n desc, dat = kwargs[name]\n self._current_args.append(desc if is_primitives(desc, inc_ndarray=False) else\n desc.placeholder)\n included_names.append(name)\n # varargs\n for name in sorted([i for i in kwargs.keys() if '.' == i[0]],\n key=lambda x: int(x[1:])):\n desc, dat = kwargs[name]\n self._current_args.append(desc if is_primitives(desc, inc_ndarray=False) else\n desc.placeholder)\n included_names.append(name)\n # kwargs\n self._current_kwargs = {\n name: desc if is_primitives(desc, inc_ndarray=False) else desc.placeholder\n for name, (desc, dat) in kwargs.items()\n if name not in included_names}\n given_data = {desc.placeholder: dat\n for name, (desc, dat) in kwargs.items()\n if isinstance(desc, VariableDesc) and dat is not None}\n # ====== initialize first ====== #\n if not self._is_initialized:\n # call NNOp initialize\n self._initialize()\n self._is_initialized = True\n # only assign new NNOp if it is initialized\n _assign_new_nnop(self)\n # ====== calculate and return outputs ====== #\n # automatically restore all variable within this NNOp scope\n self._restore_variables()\n # Recall cached output\n if footprint in self._cache_outputs:\n y = self._cache_outputs[footprint]\n else: # First time generate output given footprint\n y = self._apply(*self._current_args, **self._current_kwargs)\n # all roles to all outputs\n y = add_roles(variables=y, roles=self.__class__)\n # record cahced return\n self._cache_outputs[footprint] = y\n # check if op_data given, then evaluate to get the results.\n if len(given_data) > 0:\n # only need to make sure all variables initialized\n # if we need to evaluate some expressions.\n K.initialize_all_variables()\n y = K.eval(y, feed_dict=given_data)\n # ====== reset the current information ====== #\n self._current_args = ()\n self._current_kwargs = {}\n self._last_input_footprint = footprint\n return y\n\n def __call__(self, *args, **kwargs):\n return self.apply(*args, **kwargs)\n\n def __str__(self):\n # ====== get all attrs ====== #\n all_attrs = dir(self)\n padding = ' '\n print_attrs = {}\n for name in all_attrs:\n if '_' != name[0] and (len(name) >= 2 and '__' != name[:2]) and\\\n 'name' != name and 'is_initialized' != name:\n try:\n attr = getattr(self, name)\n except Exception:\n continue\n # check print-able type\n if is_primitives(attr, inc_ndarray=True) or \\\n (hasattr(attr, '__call__') and not inspect.ismethod(attr)):\n print_attrs[name] = attr\n print_attrs = sorted(print_attrs.items(), key=lambda x: x[0])\n # ====== format the output ====== #\n ops_format = '<%s, name: %s, init: %s>\\n'\n ops_format = ops_format % (ctext(self.__class__.__name__, 'cyan'),\n ctext(self.name, 'MAGENTA'),\n self._is_initialized)\n for i, j in print_attrs:\n if isinstance(j, NNOp): # special format for NNOp\n s = '\\n' + '\\n'.join([2 * padding + line\n for line in str(j).split('\\n')])\n else: # other attributes\n s = dummy_formatter(j)\n ops_format += padding + \"%s: %s\\n\" % (ctext(i, 'yellow'), s)\n # ====== print tensor ====== #\n for name, (var, vtype) in self._variable_info.items():\n if vtype != 'tensor':\n continue\n v = self.get(name)\n roles = K.role.get_roles(v)\n ops_format += padding + \"(Tensor)%s shape=%s, type=%s\\n, role=%s\\n\" % \\\n (ctext(v.name.split(':')[0], 'yellow'),\n ctext(tuple(v.shape.as_list()), 'yellow'),\n ctext(v.dtype.base_dtype.name, 'yellow'),\n ctext(';'.join(roles), 'yellow'))\n # ====== print Variable ====== #\n for var in self.variables:\n name = var.name.split(':')[0]\n vtype = type(var).__name__\n shape = tuple(var.shape.as_list())\n roles = K.role.get_roles(var)\n dtype = var.dtype.base_dtype.name\n ops_format += padding + \"(%s)%s shape=%s, type=%s, role=%s\\n\" % \\\n (vtype, ctext(name, 'yellow'),\n ctext(shape, 'yellow'), ctext(dtype, 'yellow'),\n ctext(';'.join(roles), 'yellow'))\n # ====== print NNOps ====== #\n for op in self.nnops:\n name = op.name\n otype = type(op).__name__\n ops_format += padding + '(NNOp)%s type=%s, inshape=%s\\n' % \\\n (ctext(name, 'yellow'),\n ctext(otype, 'yellow'),\n ctext(op.input_shape, 'yellow'))\n # ====== Input info ====== #\n for key, arg in self._kwargs_desc.items():\n if isinstance(arg, VariableDesc):\n arg = str(arg)\n else:\n arg = 'type:%s, value:%s' % (ctext(type_path(arg), 'cyan'),\n dummy_formatter(arg))\n name = ctext('[%s]' % key, 'yellow')\n ops_format += padding + name + arg + '\\n'\n return ops_format[:-1]\n\n # ==================== Slicing ==================== #\n def __getitem__(self, key):\n return NNSliceOp(self, key)\n\n\n_PRIMITIVE_TYPES = (tuple, list, dict, string_types, type(True),\n types.FunctionType, numbers.Number, type(None),\n init_ops.Initializer, NNOp, VariableDesc, type)\n\n# ===========================================================================\n# Helper\n# ===========================================================================\ndef _prepend_scope_nnop_tree(scope, op, parent=None):\n \"\"\" Add scope to the left of all uninitialized NNOp and its children\n\n This must be called at initialization, not during applying the NNOp\n \"\"\"\n _ = op.name.split('/')\n op_name = _[-1]\n op_scope = _[:-1]\n op_children = op.nnops\n # ====== merge the scope ====== #\n scope = scope.split('/')\n final_scope = []\n # re-organize the scope of the new NNOp\n # - No duplicate scope\n # - prioritize scope of parent NNOp appeared first\n for s in scope + op_scope:\n if s not in final_scope:\n final_scope += [s]\n # no empty scope\n op_scope = '/'.join([i for i in final_scope if len(i) > 0])\n # ====== modification is possible ====== #\n if not op.is_initialized:\n new_name = op_scope + '/' + op_name\n # check duplicated NNOp already defined and initialized\n if new_name in NNOp._ALL_NNOPS:\n new_op = NNOp._ALL_NNOPS[new_name]\n if type(new_op) != type(op):\n raise RuntimeError(\"NNOp of type %s with name '%s' already defined,\"\n \"but given new NNOp with type %s\" % (type(new_op), new_name, op))\n op = new_op\n # if `parent` is provided, modify parent NNOp list as well\n if parent is not None:\n parent._variable_info[op_name] = (new_op, 'nnop')\n # otherwise, just modify the name of newly created NNOp\n else:\n op._name = new_name\n # ====== NNOp already initialized, no change ====== #\n else:\n pass\n # ====== modify the children NNOp as well ====== #\n for o in op_children:\n _prepend_scope_nnop_tree(op_scope, o, parent=op)\n return op\n\nclass Container(NNOp):\n \"\"\" Container is NNOp that contain other NNOp \"\"\"\n\n def __init__(self, **kwargs):\n super(Container, self).__init__(**kwargs)\n self.debug = 0\n\n def set_debug(self, debug_mode):\n \"\"\"\n Parameters\n ----------\n debug_mode : {0, 1, 2}\n 0 - turn of logging\n 1 - print minimal logging\n 2 - print detail logging of each NNOp\n \"\"\"\n self.debug = int(debug_mode)\n return self\n\n def set_nnops(self, ops):\n # remove None values\n if isinstance(ops, (tuple, list)):\n ops = [o for o in ops if o is not None]\n ops = flatten_list(ops, level=None)\n ops = list(as_tuple(ops, t=NNOp))\n\n # add new NNOp using it name and ignore the scope\n for o in ops:\n # modify the name and scope\n o = _prepend_scope_nnop_tree(scope=self.name, op=o)\n # store the new NNOp\n self.get_variable_nnop(name=o.name.split('/')[-1], initializer=o)\n # final assignment\n self._apply_ops = ops\n return self\n\n @contextmanager\n def _debug_mode(self, *args, **kwargs):\n args_desc = [tuple(x.shape.as_list()) if hasattr(x, 'get_shape') else str(x)\n for x in self._current_args]\n kwargs_desc = {\n k: tuple(v.shape.as_list()) if hasattr(v, 'get_shape') else str(v)\n for k, v in self._current_kwargs.items()}\n # ====== print debug ====== #\n if self.debug > 0:\n print('**************** Start: %s ****************' %\n ctext(self.name, 'cyan'))\n print(\"First input:\", ctext(str(args_desc) + ' ' + str(kwargs_desc), 'yellow'))\n # ====== running ====== #\n self._debug_ops = []\n yield\n # ====== print each op ====== #\n if len(self._debug_ops) > 0:\n type_format = '%-' + str(max(len(type(o).__name__) for o in self._debug_ops)) + 's'\n name_format = '%-' + str(max(len(o.name) for o in self._debug_ops)) + 's'\n for op in self._debug_ops:\n if self.debug == 1:\n print('[' + type_format % op.__class__.__name__ + ']',\n ctext(name_format % op.name, 'cyan'),\n \"-> %s\" % ctext(op.output_shape, 'yellow'))\n elif self.debug >= 2:\n print(str(op))\n # ====== ending and return ====== #\n if self.debug > 0:\n print('**************** End: %s ****************' %\n ctext(self.name, 'cyan'))\n\n def _print_op(self, op):\n # print after finish the op at each step\n self._debug_ops.append(op)\n\nclass Lambda(NNOp):\n\n \"\"\"\n Parameters\n ----------\n func : callable\n main lambda function\n\n \"\"\"\n\n def __init__(self, func, name=None):\n super(Lambda, self).__init__()\n # check main function\n self.set_function(func, is_transpose=False)\n self.set_function(func, is_transpose=True)\n\n def set_function(self, func, is_transpose=False):\n if not hasattr(func, '__call__'):\n raise ValueError(\"func must be call-able for Lambda.\")\n if not isinstance(func, FuncDesc):\n func = FuncDesc(func)\n if is_transpose:\n self._funcT = func\n else:\n self._func = func\n return self\n\n def _initialize(self):\n pass\n\n def _apply(self, *args, **kwargs):\n # ====== update additional specialized variable for this NNOp ====== #\n for name in self._variable_info.keys():\n if name not in kwargs:\n kwargs[name] = self.get(name)\n return self._func(*args, **kwargs)\n\n def _transpose(self):\n return Lambda(name=self._funcT)\n\nclass NNSliceOp(NNOp):\n\n def __init__(self, ops, slice):\n if not isinstance(ops, NNOp):\n raise ValueError('ops must be instance of NNOp, but was given argument '\n 'has %s' % str(type(ops)))\n super(NNSliceOp, self).__init__()\n self._ops = ops\n if not isinstance(slice, (tuple, list)):\n slice = [slice]\n self.slice = slice\n\n def _apply(self, X, **kwargs):\n y = self._ops.apply(X, **kwargs)\n return_list = True if isinstance(y, (tuple, list)) else False\n # apply slice and calculate the shape\n output = [i[self.slice] for i in as_tuple(y)]\n # return output\n if return_list:\n return output\n return output[0]\n\n def __str__(self):\n ops_format = '<ops: %s, name: %s, init: %s, slice: %s>'\n return ops_format % (self._ops.__class__.__name__, self._ops.name,\n self._ops.is_initialized, str(self.slice))\n\n# ===========================================================================\n# Simple ops\n# ===========================================================================\nclass Dense(NNOp):\n\n def __init__(self, num_units,\n W_init=init_ops.glorot_uniform_initializer(seed=randint()),\n b_init=init_ops.constant_initializer(0),\n activation=K.linear,\n **kwargs):\n super(Dense, self).__init__(**kwargs)\n self.activation = (K.linear if activation is None else activation)\n self.W_init = W_init\n self.b_init = b_init\n self.num_units = num_units\n\n # ==================== abstract methods ==================== #\n def _transpose(self):\n # create the new dense\n return Dense(num_units=self.input_shape[-1],\n W_init=Lambda(func=tf.transpose,\n var_init={'a': self.get('W')}),\n b_init=None if self.b_init is None else 0.,\n activation=self.activation)\n\n def _initialize(self):\n input_shape = self.input_shape\n shape = (input_shape[-1], self.num_units)\n self.get_variable_nnop(name='W', shape=shape, initializer=self.W_init,\n roles=Weight)\n if self.b_init is not None:\n self.get_variable_nnop(initializer=self.b_init,\n shape=(self.num_units,), name='b', roles=Bias)\n\n def _apply(self, X):\n # calculate projection\n activation = K.dot(X, self.get('W'))\n # add the bias\n if self.b_init is not None:\n activation = activation + self.get('b')\n # Nonlinearity might change the shape of activation\n return self.activation(activation)\n","sub_path":"odin/nnet/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":51606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"244430383","text":"import math\n\nn = int(input())\na = list(range(n + 1))\na.remove(0)\na.remove(1)\nfor i in range(2, int(math.sqrt(n)) + 1):\n if i not in a:\n continue\n for j in range(i * i, n + 1, i):\n if j in a:\n a.remove(j)\n\nfor i in a:\n print(i)\n","sub_path":"lec06-list2/J.py","file_name":"J.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"604814046","text":"\nimport os\nimport numpy as np\nfrom imageio import imread, imwrite\nimport matplotlib.pyplot as plt\n\nplate = \"00263\"\nsrc_tv = \"D:\\\\Datasets\\\\demo_plates_4_projs\\\\input-TV\\\\plate_\"+plate\nsrc_red = \"C:\\\\Users\\\\Visielab\\\\PycharmProjects\\\\3DCNN-public\\\\results-UNET3D-4-projs\\\\plate_\"+plate\nsrc_dred = \"C:\\\\Users\\\\Visielab\\\\PycharmProjects\\\\3DCNN-public\\\\results-DENSE-UNET3D-4-projs\\\\plate_\"+plate\ndebug = False\nx = 61\n\n#plate 05299 x=41\n#plate 05233 x=41\n#plate 05233 x=61\n#plate 06690 x = 61\n\ngt = np.zeros((16,128,128))\ntv = np.zeros((16,128,128))\nsirt = np.zeros((16,128,128))\nred = np.zeros((16,128,128))\ndred = np.zeros((16,128,128))\n\nk = 0\nfor file in os.listdir(src_red+\"\\\\gt\\\\\"):\n gt[k,:,:] = imread(src_red+\"\\\\gt\\\\\"+file)\n k = k + 1\n\nk = 0\nfor file in os.listdir(src_tv):\n tv[k+3,:,:] = imread(src_tv+\"\\\\\"+file)\n k = k + 1\n\nk = 0\nfor file in os.listdir(src_red+\"\\\\input\\\\\"):\n sirt[k,:,:] = imread(src_red+\"\\\\input\\\\\"+file)\n k = k + 1\n\nk = 0\nfor file in os.listdir(src_red+\"\\\\pred\\\\\"):\n red[k,:,:] = imread(src_red+\"\\\\pred\\\\\"+file)\n k = k + 1\n\nk = 0\nfor file in os.listdir(src_dred+\"\\\\pred\\\\\"):\n dred[k,:,:] = imread(src_dred+\"\\\\pred\\\\\"+file)\n k = k + 1\n\n\nif debug:\n plt.figure(\"GT\")\n plt.imshow(gt[:,:,x], cmap=\"gray\")\n plt.figure(\"SIRT\")\n plt.imshow(sirt[:,:,x], cmap=\"gray\")\n plt.figure(\"RED\")\n plt.imshow(red[:,:,x], cmap=\"gray\")\n plt.figure(\"DRED\")\n plt.imshow(dred[:, :, x], cmap=\"gray\")\n plt.figure(\"TV\")\n plt.imshow(tv[:, :, x], cmap=\"gray\")\n plt.show()\nelse:\n imwrite(\"gt_{}_{}.png\".format(plate,x), gt[:,:,x])\n imwrite(\"sirt_{}_{}.png\".format(plate, x), sirt[:, :, x])\n imwrite(\"red_{}_{}.png\".format(plate, x), red[:, :, x])\n imwrite(\"dred_{}_{}.png\".format(plate, x), dred[:, :, x])\n imwrite(\"tv_{}_{}.png\".format(plate, x), tv[:, :, x])","sub_path":"visualize_results.py","file_name":"visualize_results.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"221242545","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport logging\n\nfrom tornado.httpclient import AsyncHTTPClient\nfrom tornado.concurrent import TracebackFuture\nfrom tornado.ioloop import IOLoop\nfrom functools import partial\n\n\nRETRY_START_TIMEOUT = int(os.environ.get('RETRY_START_TIMEOUT', '1'))\nMAX_RETRY_TIMEOUT = int(os.environ.get('MAX_RETRY_TIMEOUT', '30'))\nMAX_RETRIES = int(os.environ.get('MAX_RETRIES', '30'))\n\n\nclass RetryClient(object):\n RETRY_HTTP_ERROR_CODES = (500, 502, 503, 504)\n\n def __init__(self, http_client=None, max_retries=MAX_RETRIES,\n max_retry_timeout=MAX_RETRY_TIMEOUT,\n retry_start_timeout=RETRY_START_TIMEOUT):\n\n if http_client:\n self.http_client = http_client\n else:\n self.http_client = AsyncHTTPClient()\n\n self.logger = logging.getLogger('RetryClient')\n\n self.max_retries = max_retries\n self.max_retry_timeout = max_retry_timeout\n self.retry_start_timeout = retry_start_timeout\n\n def fetch(self, request, *args, **kwargs):\n return http_retry(\n self.http_client,\n request,\n retry_wait=self.retry_start_timeout,\n attempts=self.max_retries\n )\n\n\ndef http_retry(\n client, request,\n raise_error=True, attempts=5,\n retry_wait=1, **kwargs):\n attempt = 1\n future = TracebackFuture()\n ioloop = IOLoop.current()\n\n def _do_request(attempt):\n http_future = client.fetch(request, raise_error=False, **kwargs)\n http_future.add_done_callback(partial(handle_response, attempt))\n\n def handle_response(attempt, future_response):\n attempt += 1\n result = future_response.result()\n if result.error and\\\n attempt <= 5 and\\\n result.code >= 500 and\\\n result.code <= 599:\n logging.error(result.error)\n logging.error(result.body)\n return ioloop.call_later(retry_wait, lambda: _do_request(attempt))\n else:\n if raise_error and result.error:\n return future.set_exception(result.error)\n future.set_result(result)\n\n _do_request(attempt)\n return future\n","sub_path":"tornado_retry_client/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"645767872","text":"size = int(input())\narray = []\narray = input().split()\ndef fastsort(size, array):\n mid = int(size/2)\n left = []\n right = []\n ans = \"\"\n if len(array) > 1:\n for i in range(0, size):\n if i != mid:\n if int(array[i]) >= int(array[mid]):\n right.append(array[i])\n else:\n left.append(array[i])\n ans += str(fastsort(len(left), left))\n ans += \" \"\n ans += str(array[mid])\n ans += \" \"\n ans += str(fastsort(len(right), right))\n ans += \" \"\n return ans\n elif len(array) == 1:\n ans += str(array[0])\n return ans\n else:\n return \"\"\nprint(fastsort(size,array))\n","sub_path":"Python/Quicksort.py","file_name":"Quicksort.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"20246148","text":"import getopt\nimport sys\n\nimport data_frame_processing\nimport file_reading\nimport utils\n\n\ndef main(argv):\n # Leo los argumentos que se pasaron por cmdline\n try:\n opciones, argumentos = getopt.getopt(argv, 'hi:o:', ['help', 'in=', 'out='])\n except getopt.GetoptError:\n print\n 'FineFodReview.py -i <infile> -o <outfile>'\n sys.exit(2)\n\n files = {}\n for o, a in opciones:\n if o in ('-h', '--help'):\n print\n \"fine_food_review.py -i <infile> -o <outfile>\"\n sys.exit()\n elif o in ('-i', '--in'):\n files['inputFile'] = a\n elif o in ('-o', '--out'):\n files['outputFile'] = a\n\n data_frame_train = file_reading.leer_archivo(files['inputFile'], utils.header_train)\n data_frame_processing.procesar_data_frame(data_frame_train)\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n\n\n# Obtener estructuras con datos relevantes\n\n# Procesar datos relevantes\n\n# Generar archivo de salida\n","sub_path":"fine_food_review.py","file_name":"fine_food_review.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"161558760","text":"import pandas as pd\n\ndf = pd.read_csv(\"stock_data.csv\")\nprint(df)\n\n#Removes header\nprint(\"====\")\ndf = pd.read_csv(\"stock_data.csv\", skiprows=1)\nprint(df)\n\n#Removes header\nprint(\"XXXX\")\ndf = pd.read_csv(\"stock_data.csv\", header=1)\nprint(df)\n\n#New column headers and also removes index\ndf = pd.read_csv(\"stock_data.csv\", header=None, names = [\"ticker\",\"eps\",\"revenue\",\"people\"])\nprint(df)\n\n#Display just 2 rows\ndf = pd.read_csv(\"stock_data.csv\", nrows=2)\nprint(df)\n\n#Identify NaN\ndf = pd.read_csv(\"stock_data.csv\", na_values=[\"n.a.\", \"not available\"])\nprint(df)\n\n#Identify NaN per column\ndf = pd.read_csv(\"stock_data.csv\", na_values={\n 'eps': ['not available'],\n 'revenue': [-1],\n 'people': ['not available','n.a.']\n })\nprint(df)\n\n#Write to a file, no index\ndf.to_csv(\"new.csv\", index=False)\n#Write to a file, no header\ndf.to_csv(\"new.csv\",header=False)\n#Write to a file, just 2 columns\ndf.to_csv(\"new.csv\", columns=[\"tickers\",\"price\"], index=False)\n\ndf = pd.read_excel(\"stock_data.xlsx\",\"Sheet1\")\nprint(df)\n\ndef convert_people_cell(cell):\n if cell==\"n.a.\":\n return 'Sam Walton'\n return cell\n\ndef convert_price_cell(cell):\n if cell==\"n.a.\":\n return 50\n return cell\n \ndf = pd.read_excel(\"stock_data.xlsx\",\"Sheet1\", converters= {\n 'people': convert_people_cell,\n 'price': convert_price_cell\n })\nprint(df)\n\ndf.to_excel(\"new.xlsx\", sheet_name=\"stocks\", index=False, startrow=2, startcol=1)\n\ndf_stocks = pd.DataFrame({\n 'tickers': ['GOOGL', 'WMT', 'MSFT'],\n 'price': [845, 65, 64 ],\n 'pe': [30.37, 14.26, 30.97],\n 'eps': [27.82, 4.61, 2.12]\n})\n\ndf_weather = pd.DataFrame({\n 'day': ['1/1/2017','1/2/2017','1/3/2017'],\n 'temperature': [32,35,28],\n 'event': ['Rain', 'Sunny', 'Snow']\n})\n\nwith pd.ExcelWriter('stocks_weather.xlsx') as writer:\n df_stocks.to_excel(writer, sheet_name=\"stocks\")\n df_weather.to_excel(writer, sheet_name=\"weather\")","sub_path":"workspace/pandas/4_read_write_to_excel/4_read_writeto_excel.py","file_name":"4_read_writeto_excel.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"542444636","text":"import numpy as np\r\nimport matplotlib as mpl\r\nmpl.use(\"Agg\")\r\nimport matplotlib.pyplot as plt\r\nimport math\r\n\r\n# Parameters\r\ncontent = 'g' # g (gas) or s (stars)\r\nvelocity = 't' # t (tangential) or r (radial)\r\ntime = 3.0 # in Gyr\r\nwidth = 10 # width of velocity bins in km/s\r\n\r\n\r\ndef velocity_distribution(galaxy_name, content, velocity, time):\r\n columns = (0, 1, 2, 3, 4, 5, 6) # x, y, z, vx, vy, vz, m\r\n zlim = 5 # +/- lim in z in kpc\r\n rlim = 20 # lim of radius of disc in kpc\r\n\r\n dumps, times = np.loadtxt(\"/home/humar50/RING/RUNS/\" + str(galaxy_name) + \"/DUMPS/\" + str(galaxy_name)\r\n + \"/tzstep.dat\", skiprows=1, usecols=(0, 1), unpack=True)\r\n index = times.tolist().index(time)\r\n dump = str(int(dumps[index]))\r\n while len(dump) != 3:\r\n dump = '0' + dump # dump must be of format 000.\r\n\r\n filePath = \"/home/humar50/RING/RUNS/\" + str(galaxy_name) + \"/DUMPS/\" + str(galaxy_name)\r\n\r\n if content == 'g':\r\n fileName = filePath + \"/g000\" + dump + \"r\"\r\n title = \"Gas particles at \" + str(time) + \" Gyr\"\r\n ylabel = \"Gas mass fraction [-]\"\r\n if velocity == 't':\r\n xlabel = \"Tangential velocity [km/s]\"\r\n elif velocity == 'r':\r\n xlabel = \"Radial velocity [km/s]\"\r\n elif content == 's':\r\n fileName = filePath + \"/s000\" + dump + \"r\"\r\n title = \"Star particles at \" + str(time) + \" Gyr\"\r\n ylabel = \"Stellar mass fraction [-]\"\r\n if velocity == 't':\r\n xlabel = \"Tangential velocity [km/s]\"\r\n elif velocity == 'r':\r\n xlabel = \"Radial velocity [km/s]\"\r\n\r\n # Read files\r\n rx, ry, rz, rvx, rvy, rvz, rm = np.loadtxt(fileName, usecols=columns, unpack=True)\r\n\r\n # Exclude particles in halo and outside of a 20 kpc radius\r\n x, y, z, vx, vy, vz, m = [], [], [], [], [], [], []\r\n for i in range(0, len(rx)):\r\n radius = np.sqrt((rx[i])**2 + (ry[i])**2)\r\n if (-zlim <= rz[i] <= zlim) and (radius < rlim):\r\n x.append(rx[i]), y.append(ry[i]), z.append(rz[i]), vx.append(rvx[i]), vy.append(rvy[i]),\r\n vz.append(rvz[i]), m.append(rm[i])\r\n else:\r\n continue\r\n\r\n # Compute tangential and radial velocities\r\n v_list = [] # list that will contain the tangential or radial velocity of all particles\r\n if velocity == 't':\r\n for i in range(0, len(m)):\r\n d = np.sqrt((x[i])**2 + (y[i])**2)\r\n vt = (x[i]*vy[i] - y[i]*vx[i])/d\r\n v_list.append(vt)\r\n elif velocity == 'r':\r\n for i in range(0, len(m)):\r\n d = np.sqrt((x[i])**2 + (y[i])**2)\r\n vr = (x[i]*vx[i] + y[i]*vy[i])/d\r\n v_list.append(vr)\r\n\r\n # Get the velocity bins\r\n v_min, v_max = min(v_list), max(v_list)\r\n v_min, v_max = math.floor(v_min), math.ceil(v_max)\r\n bin_number = int(round((v_max - v_min) / width))\r\n v_bins = np.linspace(v_min, v_max, num=bin_number+1, endpoint=False)\r\n\r\n # Compute total particle mass in each velocity bin\r\n total_mass = []\r\n for bin_no in range(0, len(v_bins)):\r\n bin_mass = 0 # initialization of mass of particles in bin\r\n if bin_no == 0:\r\n continue\r\n else:\r\n for i in range(0, len(m)):\r\n if v_bins[bin_no-1] <= v_list[i] < v_bins[bin_no]:\r\n bin_mass += m[i]\r\n else:\r\n continue\r\n\r\n total_mass.append(bin_mass)\r\n\r\n # Compute mass fraction in each velocity bin\r\n mass_fraction = []\r\n mass_galaxy = 0\r\n for i in range(0, len(m)):\r\n mass_galaxy += m[i]\r\n\r\n for i in range(0, len(total_mass)):\r\n mass_fraction.append(total_mass[i]/mass_galaxy)\r\n\r\n return v_bins[0:-1], mass_fraction, title, xlabel, ylabel\r\n\r\n\r\n# Plot\r\ngalaxy_names = ['I', 'Af_v1', 'Ar_v1', 'As_v1']\r\nfig = plt.figure()\r\nax = fig.add_subplot(111)\r\npicName = \"\"\r\nfor name in galaxy_names:\r\n v, mass, title, xlabel, ylabel = velocity_distribution(name, content, velocity, time)\r\n ax.step(v, mass, label='Run ' + name)\r\n picName += (name + \"-\")\r\n\r\nax.set_title(title)\r\nax.set_xlabel(xlabel)\r\nax.set_ylabel(ylabel)\r\nplt.legend()\r\nfig.tight_layout()\r\n\r\n# Save figure\r\nplt.savefig(picName + content + \"_\" + velocity + \"_velocity_distribution_\" + str(time) + \"_Gyr.png\", dpi=500)\r\n# plt.show()\r\n","sub_path":"velocity_distribution_comparison.py","file_name":"velocity_distribution_comparison.py","file_ext":"py","file_size_in_byte":4333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"408124281","text":"import hashlib\nimport time\n\nimport boto3\nimport json\n\nfrom typing import Any, List, Dict\n\nimport pydgraph\nfrom pydgraph import DgraphClient, DgraphClientStub\n\n\ndef parse_s3_event(event) -> str:\n # Retrieve body of sns message\n # Decode json body of sns message\n print('event is {}'.format(event))\n msg = json.loads(event['body'])['Message']\n msg = json.loads(msg)\n\n record = msg['Records'][0]\n\n bucket = record['s3']['bucket']['name']\n key = record['s3']['object']['key']\n return download_s3_file(bucket, key)\n\n\ndef download_s3_file(bucket, key) -> str:\n key = key.replace(\"%3D\", \"=\")\n print('Downloading s3 file from: {} {}'.format(bucket, key))\n s3 = boto3.resource('s3')\n obj = s3.Object(bucket, key)\n return obj.get()['Body'].read()\n\n\nclass NodeCopier(object):\n\n def __init__(self, engagement_key: str, mg_client: DgraphClient, eg_client: DgraphClient):\n self.engagement_key = engagement_key\n self.mg_client = mg_client\n self.eg_client = eg_client\n\n @staticmethod\n def upsert(client: DgraphClient, node_key: str, props: Dict[str, str]):\n query = \"\"\"\n query q0($a: string)\n {\n q0(func: eq(node_key, $a))\n {\n uid,\n expand(_all_)\n }\n }\n \"\"\"\n\n txn = client.txn(read_only=False)\n\n try:\n res = json.loads(txn.query(query, variables={'$a': node_key}).json)\n node = res['q0']\n\n if not node:\n node = props\n else:\n node = {**props, **node[0]}\n\n res = txn.mutate(set_obj=node, commit_now=True)\n uids = res.uids\n print(uids)\n uid = uids['blank-0']\n finally:\n txn.discard()\n\n return uid\n\n def copy_node(self, node_uid: str) -> str:\n print('Copying node: {}'.format(node_uid))\n query = \"\"\"\n query q0($a: string)\n {\n q0(func: uid($a))\n {\n expand(_all_)\n }\n }\n \"\"\"\n\n res = json.loads(self.mg_client.query(query, variables={'$a': node_uid}).json)\n\n # We assume the node exists in the master graph\n node = res['q0'][0]\n\n # Prep node for upsert into engagement\n node.pop('uid', None)\n node['engagement_key'] = str(self.engagement_key)\n\n # Insert node into engagement-graph\n return NodeCopier.upsert(self.eg_client, node['node_key'], node)\n\n def copy_edge(self, from_uid: str, edge_name: str, to_uid: str):\n mut = {\n 'uid': from_uid,\n edge_name: {'uid': to_uid}\n }\n\n print('mutating')\n res = self.eg_client.txn(read_only=False).mutate(set_obj=mut, commit_now=True)\n print('edge mutation result is: {}'.format(res))\n\n\ndef create_process_schema(eg_client: DgraphClient):\n schema = \\\n 'node_key: string @index(hash) .\\n' +\\\n 'engagement_key: string @index(hash) .\\n' +\\\n 'children: uid @reverse .\\n' +\\\n 'pid: int @index(int) .\\n'\n\n op = pydgraph.Operation(schema=schema)\n eg_client.alter(op)\n\n\ndef get_engagement_key(label: str, uids: List[str]) -> str:\n bucket = int(time.time()) - (int(time.time()) % 7200)\n hasher = hashlib.sha1(label)\n hasher.update(str(bucket).encode())\n [hasher.update(str(uid).encode()) for uid in sorted(uids)]\n\n return str(hasher.hexdigest())\n\n\n# We need to whitelist by taking the uids, sorting, and hashing with the alert name\n# For now, we 'throttle' by hour, but this should be customizable later\ndef should_throttle(engagement_key: str, dgraph_client: DgraphClient) -> bool:\n query = \"\"\"\n query q0($a: string)\n {\n q0(func: eq(engagement_key, $a), first: 1)\n {\n uid,\n }\n }\n \"\"\"\n\n res = json.loads(dgraph_client.query(query, variables={'$a': engagement_key}).json)\n if res['q0']:\n return True\n return False\n\n\ndef lambda_handler(events: Any, context: Any) -> None:\n mg_client = DgraphClient(DgraphClientStub('db.mastergraph:9080'))\n eg_client = DgraphClient(DgraphClientStub('db.engagementgraph:9080'))\n\n create_process_schema(eg_client)\n\n uid_map = {}\n for event in events['Records']:\n print('Copying engagement')\n data = parse_s3_event(event)\n incident_graph = json.loads(data)\n\n label = incident_graph['label'].encode('utf-8')\n node_refs = incident_graph['node_refs']\n edges = incident_graph['edges']\n\n engagement_key = get_engagement_key(label, [n['uid'] for n in node_refs])\n\n if should_throttle(engagement_key, eg_client):\n print('Throttling: {}'.format(engagement_key))\n continue\n\n print('Creating engagement: {}'.format(engagement_key))\n copier = NodeCopier(engagement_key, mg_client, eg_client)\n\n print('node_refs: {}'.format(node_refs))\n print('edges: {}'.format(edges))\n for node_ref in node_refs:\n new_uid = copier.copy_node(node_ref['uid'])\n uid_map[node_ref['uid']] = new_uid\n print('new_uid: {}'.format(new_uid))\n for edge in edges:\n copier.copy_edge(uid_map[edge[0]], edge[1], uid_map[edge[2]])\n print('Copied engagement successfully')\n\n print('Engagement creation was successful')\n\n\n","sub_path":"engagement-creator/src/engagement-creator.py","file_name":"engagement-creator.py","file_ext":"py","file_size_in_byte":5448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"528506965","text":"import random\n\nfrom typing import List, Tuple\n\nfrom .problem import Problem\nfrom.right_triangle_diagram import RightAngleDiagram, RightAngleThetaVertex\nfrom .trig_defs import RightAngleTrigFunction, RightAngleTrigSide\n\nclass RightAngleProblem(Problem):\n def __init__(self):\n Problem.__init__(self)\n\n def __repr__(self):\n return str.format(\"Right Angle Problem ({}): {}\", self.level, self.prompt)\n\n\ndef _get_triple() -> Tuple[int, int, int]:\n a = random.randint(3, 15) # a < 3 results in b = 0. This is not a triangle\n\n if a % 2 == 0:\n b = ((a / 2) ** 2) - 1\n c = b + 2\n else:\n b = (a ** 2 - 1) / 2\n c = b + 1\n\n return int(a), int(b), int(c)\n\n\ndef _get_steps_level1(trig_func: RightAngleTrigFunction, adjacent: str, hypotenuse: str, opposite: str) -> List[str]:\n if trig_func == RightAngleTrigFunction.Sin:\n return [\n \"Identify opposite side: {}.\".format(opposite),\n \"Identify hypotenuse: {}.\".format(hypotenuse),\n \"Divide opposite ({}) / hypotenuse ({}).\".format(opposite, hypotenuse)\n ]\n elif trig_func == RightAngleTrigFunction.Cos:\n return [\n \"Identify adjacent side: {}.\".format(adjacent),\n \"Identify hypotenuse: {}.\".format(hypotenuse),\n \"Divide adjacent ({}) / hypotenuse ({}).\".format(adjacent, hypotenuse)\n ]\n elif trig_func == RightAngleTrigFunction.Tan:\n return [\n \"Identify opposite side: {}.\".format(opposite),\n \"Identify adjacent side: {}.\".format(adjacent),\n \"Divide opposite ({}) / adjacent ({}).\".format(opposite, adjacent)\n ]\n elif trig_func == RightAngleTrigFunction.Sec:\n return [\n \"Identify hypotenuse: {}.\".format(hypotenuse),\n \"Identify adjacent side: {}.\".format(adjacent),\n \"Divide hypotenuse ({}) / adjacent ({}).\".format(hypotenuse, adjacent)\n ]\n elif trig_func == RightAngleTrigFunction.Csc:\n return [\n \"Identify hypotenuse: {}.\".format(hypotenuse),\n \"Identify opposite side: {}.\".format(opposite),\n \"Divide hypotenuse ({}) / adjacent ({}).\".format(hypotenuse, opposite)\n ]\n elif trig_func == RightAngleTrigFunction.Cot:\n return [\n \"Identify adjacent side: {}.\".format(adjacent),\n \"Identify opposite side: {}.\".format(opposite),\n \"Divide adjacent ({}) / opposite ({}).\".format(adjacent, opposite)\n ]\n\n return []\n\n\ndef _get_steps_level2(trig_func: RightAngleTrigFunction, missing_side: RightAngleTrigSide,\n adjacent: str, hypotenuse: str, opposite: str) ->List[str]:\n\n level1_steps = _get_steps_level1(trig_func, adjacent, hypotenuse, opposite)\n\n if _side_needed(trig_func, missing_side):\n steps: List[str] = []\n\n if missing_side == RightAngleTrigSide.Hypotenuse:\n steps.append(\"Calculate missing hypotenuse side: C² = {}² + {}².\".format(opposite, adjacent))\n elif missing_side == RightAngleTrigSide.Opposite:\n steps.append(\"Calculate missing opposite side: {}² = A² + {}².\".format(hypotenuse, adjacent))\n else:\n steps.append(\"Calculate missing adjacent side: {}² = {}² + B².\".format(hypotenuse, opposite))\n\n return steps + level1_steps\n else:\n return level1_steps\n\n\ndef _get_answer(trig_func: RightAngleTrigFunction, adjacent: str, hypotenuse: str, opposite: str) -> str:\n if trig_func == RightAngleTrigFunction.Sin:\n return \"{}/{}\".format(opposite, hypotenuse)\n elif trig_func == RightAngleTrigFunction.Cos:\n return \"{}/{}\".format(adjacent, hypotenuse)\n elif trig_func == RightAngleTrigFunction.Tan:\n return \"{}/{}\".format(opposite, adjacent)\n elif trig_func == RightAngleTrigFunction.Sec:\n return \"{}/{}\".format(hypotenuse, adjacent)\n elif trig_func == RightAngleTrigFunction.Csc:\n return \"{}/{}\".format(hypotenuse, opposite)\n elif trig_func == RightAngleTrigFunction.Cot:\n return \"{}/{}\".format(adjacent, opposite)\n\n return \"\"\n\n\ndef _side_needed(trig_func: RightAngleTrigFunction, triangle_side: RightAngleTrigSide) -> bool:\n if trig_func == RightAngleTrigFunction.Sin:\n return triangle_side != RightAngleTrigSide.Adjacent\n elif trig_func == RightAngleTrigFunction.Cos:\n return triangle_side != RightAngleTrigSide.Opposite\n elif trig_func == RightAngleTrigFunction.Tan:\n return triangle_side != RightAngleTrigSide.Hypotenuse\n elif trig_func == RightAngleTrigFunction.Sec:\n return triangle_side != RightAngleTrigSide.Opposite\n elif trig_func == RightAngleTrigFunction.Csc:\n return triangle_side != RightAngleTrigSide.Adjacent\n elif trig_func == RightAngleTrigFunction.Cot:\n return triangle_side != RightAngleTrigSide.Hypotenuse\n\n return False\n\n\ndef gen_right_angle_problem(level: int = 1) -> RightAngleProblem:\n \"\"\"Creates a new Right Angle Trigonometry Problem\n Keyword arguments:\n level -- the difficulty level of this problem.\n level 1: Right triangle measurements are a Pythagorean Triple\n Level 2: Hypotenuse value not given\n Level 3: Random side value not given\n \"\"\"\n\n if level < 1 or level > 3:\n raise ValueError(\"right angle problems must be level 1 - 3\")\n\n a, b, c = _get_triple()\n\n scale = 150.0\n min_side_length = 35.0\n\n a_value = max((a / c) * scale, min_side_length)\n b_value = max((b / c) * scale, min_side_length)\n\n if random.randint(0, 1) == 1:\n theta_vertex = RightAngleThetaVertex.VertexB\n else:\n theta_vertex = RightAngleThetaVertex.VertexC\n\n trig_function = RightAngleTrigFunction(random.randint(RightAngleTrigFunction.Sin.value, RightAngleTrigFunction.Cot.value))\n\n labels = str(a), str(b), str(c)\n\n problem_data = RightAngleDiagram(a_value, b_value, random.randint(0, 360), theta_vertex)\n problem_data.a_label = labels[0]\n problem_data.b_label = labels[1]\n problem_data.c_label = labels[2]\n problem_data.reposition()\n\n if theta_vertex == RightAngleThetaVertex.VertexB:\n adjacent = labels[0]\n hypotenuse = labels[2]\n opposite = labels[1]\n else:\n adjacent = labels[1]\n hypotenuse = labels[2]\n opposite = labels[0]\n\n if level == 1:\n missing_side = RightAngleTrigSide.Nil\n elif level == 2:\n missing_side = RightAngleTrigSide.Hypotenuse\n else:\n missing_side = RightAngleTrigSide(random.randint(RightAngleTrigSide.Opposite.value, RightAngleTrigSide.Hypotenuse.value))\n\n if missing_side == RightAngleTrigSide.Hypotenuse:\n problem_data.c_label = None\n elif theta_vertex == RightAngleThetaVertex.VertexB:\n if missing_side == RightAngleTrigSide.Adjacent:\n problem_data.a_label = None\n elif missing_side == RightAngleTrigSide.Opposite:\n problem_data.b_label = None\n elif theta_vertex == RightAngleThetaVertex.VertexC:\n if missing_side == RightAngleTrigSide.Adjacent:\n problem_data.b_label = None\n elif missing_side == RightAngleTrigSide.Opposite:\n problem_data.a_label = None\n\n p = RightAngleProblem()\n p.level = level\n p.prompt = \"Find {} θ\".format(trig_function.name)\n p.answer = _get_answer(trig_function, adjacent, hypotenuse, opposite)\n p.diagram = problem_data.generate_diagram_svg()\n\n if level == 1:\n p.steps = _get_steps_level1(trig_function, adjacent, hypotenuse, opposite)\n else:\n p.steps = _get_steps_level2(trig_function, missing_side, adjacent, hypotenuse, opposite)\n\n return p\n\n","sub_path":"venv/Lib/site-packages/mathproblem/right_angle.py","file_name":"right_angle.py","file_ext":"py","file_size_in_byte":7700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"169187362","text":"# ONLY EDIT FUNCTIONS MARKED CLEARLY FOR EDITING\n\nimport numpy as np\n\ndef question03(numNodes, edgeList):\n # modify and then return the variable below\n from sets import Set \n nodeElememts = Set([i[0] for i in edgeList])\n edgeElements = Set([i[1] for i in edgeList])\n \n if nodeElememts.intersection(edgeElements)==Set([]):\n answer = len(edgeElements)-len(nodeElememts)\n else:\n answer = len(edgeList)-len(nodeElememts.intersection(edgeElements))\n return answer\n","sub_path":"q3.py","file_name":"q3.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"395916521","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nver1.xx 畳み込み積分&積分発火型\nver2.xx 積分発火型\nver3.xx ver2にGUIを実装\nv5.00 ホジキンハクスレー+ノイズ型\n\"\"\"\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar\nfrom PyQt4 import QtGui, QtCore\nfrom matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.figure import Figure\nimport random\nimport time\nfrom neuron5 import Neuron5\n\nclass Main(QtGui.QWidget):\n deltatime = 0.001\n phightime = 0.002\n numneu = 10\n vth = -55\n vrm = -70\n tau = 0.01\n phigh = 10\n e_syn = 0\n def_w = 0.7\n sigmoid_gain = 0.3\n ab_refacttime = 0.005\n ab_weak = 0.05\n simtime = 10\n \n def __init__(self, parent=None):\n super(Main, self).__init__()\n \n #GUI\n numneuLabel = QtGui.QLabel('ニューロン数')\n vthLabel = QtGui.QLabel('スレッショルド電圧[mV]')\n vrmLabel = QtGui.QLabel('静止膜電位[mV]')\n tauLabel = QtGui.QLabel('時定数[t]')\n deltatimeLabel = QtGui.QLabel('単位時間[t]')\n phighLabel = QtGui.QLabel('発火時電圧[mV]')\n phightimeLabel = QtGui.QLabel('発火時間[t]')\n e_synLabel = QtGui.QLabel('シナプス逆転電位')\n def_wLabel = QtGui.QLabel('シナプス結合荷重(初期値)')\n sigmoid_gainLabel = QtGui.QLabel('シグモイドゲイン')\n ab_refacttimeLabel = QtGui.QLabel('不応期時間[t]')\n ab_weakLabel = QtGui.QLabel('不応期時の上がりにくさ[0~1]')\n simtimeLabel = QtGui.QLabel('シミュレーション時間[t]')\n\n self.numneuEdit = QtGui.QLineEdit()\n self.vthEdit = QtGui.QLineEdit()\n self.vrmEdit = QtGui.QLineEdit() \n self.tauEdit = QtGui.QLineEdit()\n self.deltatimeEdit = QtGui.QLineEdit()\n self.phighEdit = QtGui.QLineEdit()\n self.phightimeEdit = QtGui.QLineEdit() \n self.e_synEdit = QtGui.QLineEdit()\n self.def_wEdit = QtGui.QLineEdit()\n self.sigmoid_gainEdit = QtGui.QLineEdit()\n self.ab_refacttimeEdit = QtGui.QLineEdit()\n self.ab_weakEdit = QtGui.QLineEdit()\n self.simtimeEdit = QtGui.QLineEdit()\n \n self.numneuEdit.setText(str(Main.numneu))\n self.vthEdit.setText(str(Main.vth))\n self.vrmEdit.setText(str(Main.vrm))\n self.tauEdit.setText(str(Main.tau))\n self.deltatimeEdit.setText(str(Main.deltatime))\n self.phighEdit.setText(str(Main.phigh))\n self.phightimeEdit.setText(str(Main.phightime))\n self.e_synEdit.setText(str(Main.e_syn))\n self.def_wEdit.setText(str(Main.def_w))\n self.sigmoid_gainEdit.setText(str(Main.sigmoid_gain))\n self.ab_refacttimeEdit.setText(str(Main.ab_refacttime))\n self.ab_weakEdit.setText(str(Main.ab_weak))\n self.simtimeEdit.setText(str(Main.simtime))\n\n startBtn = QtGui.QPushButton('START')\n saveBtn = QtGui.QPushButton('SAVE')\n\n grid = QtGui.QHBoxLayout()\n \n self.groupBox = QtGui.QGroupBox(\"パラメータ設定\")\n vbox = QtGui.QVBoxLayout()\n\n layout1 = QtGui.QHBoxLayout()\n layout1.addWidget(numneuLabel)\n layout1.addWidget(self.numneuEdit)\n layout2 = QtGui.QHBoxLayout()\n layout2.addWidget(vthLabel)\n layout2.addWidget(self.vthEdit)\n layout3 = QtGui.QHBoxLayout()\n layout3.addWidget(vrmLabel)\n layout3.addWidget(self.vrmEdit)\n layout4 = QtGui.QHBoxLayout()\n layout4.addWidget(tauLabel)\n layout4.addWidget(self.tauEdit)\n layout5 = QtGui.QHBoxLayout()\n layout5.addWidget(deltatimeLabel)\n layout5.addWidget(self.deltatimeEdit)\n layout6 = QtGui.QHBoxLayout()\n layout6.addWidget(phighLabel)\n layout6.addWidget(self.phighEdit)\n layout7 = QtGui.QHBoxLayout()\n layout7.addWidget(phightimeLabel)\n layout7.addWidget(self.phightimeEdit)\n layout8 = QtGui.QHBoxLayout() \n layout8.addWidget(e_synLabel)\n layout8.addWidget(self.e_synEdit)\n layout9 = QtGui.QHBoxLayout() \n layout9.addWidget(def_wLabel)\n layout9.addWidget(self.def_wEdit)\n layout10 = QtGui.QHBoxLayout()\n layout10.addWidget(sigmoid_gainLabel)\n layout10.addWidget(self.sigmoid_gainEdit)\n layout11 = QtGui.QHBoxLayout() \n layout11.addWidget(ab_refacttimeLabel)\n layout11.addWidget(self.ab_refacttimeEdit)\n layout12 = QtGui.QHBoxLayout()\n layout12.addWidget(ab_weakLabel)\n layout12.addWidget(self.ab_weakEdit)\n layout13 = QtGui.QHBoxLayout()\n layout13.addWidget(simtimeLabel)\n layout13.addWidget(self.simtimeEdit)\n layout14 = QtGui.QVBoxLayout()\n layout14.addWidget(startBtn)\n layout14.addWidget(saveBtn)\n \n vbox.addLayout(layout1)\n vbox.addLayout(layout2)\n vbox.addLayout(layout3)\n vbox.addLayout(layout4)\n vbox.addLayout(layout5)\n vbox.addLayout(layout6) \n vbox.addLayout(layout7)\n vbox.addLayout(layout8)\n vbox.addLayout(layout9)\n vbox.addLayout(layout10)\n vbox.addLayout(layout11)\n vbox.addLayout(layout12)\n vbox.addLayout(layout13)\n vbox.addLayout(layout14)\n \n self.groupBox.setLayout(vbox)\n grid.addWidget(self.groupBox)\n\n self.groupBox2 = QtGui.QGroupBox(\"プロット\")\n mainbox = QtGui.QVBoxLayout() \n \n #ニューロン作成\n self.neuron1 = Neuron4(int(self.numneuEdit.text()),\n float(self.vthEdit.text()),\n float(self.vrmEdit.text()),\n float(self.tauEdit.text()), \n float(self.deltatimeEdit.text()), \n float(self.phightimeEdit.text()), \n float(self.phighEdit.text()),\n float(self.e_synEdit.text()), \n float(self.def_wEdit.text()), \n float(self.sigmoid_gainEdit.text()), \n float(self.ab_refacttimeEdit.text()), \n float(self.ab_weakEdit.text()),\n float(self.simtimeEdit.text()))\n \n #シナプス結合荷重(0.8)\n w = np.ones((Main.numneu, Main.numneu)) * Main.def_w\n for i in range(0, Main.numneu):\n w[i][i] = 0\n w[0][0] = 1\n #w[1][1] = 1 \n self.neuron1.set_weight(w)\n \n #タブごとにグラフを作成\n qtab = QtGui.QTabWidget()\n self.tab1 = TabwaveWidget(self.neuron1)\n self.tab2 = TablasterWidget(self.neuron1)\n qtab.addTab(self.tab1, '波形')\n qtab.addTab(self.tab2, 'ラスター') \n \n #スライダー(グラフのズーム・アウト)\n self.sliderh = QtGui.QSlider(QtCore.Qt.Horizontal)\n self.sliderh.setRange(1, 100) \n self.sliderh.setValue(10) \n \n self.sliderv = QtGui.QSlider(QtCore.Qt.Vertical) \n self.sliderv.setRange(1, 100) \n self.sliderv.setValue(10) \n\n hsbox = QtGui.QHBoxLayout()\n hsbox.addWidget(self.sliderh)\n hsbox.setAlignment(self.sliderh, QtCore.Qt.AlignVCenter)\n\n vsbox = QtGui.QVBoxLayout()\n vsbox.addWidget(self.sliderv)\n vsbox.setAlignment(self.sliderv, QtCore.Qt.AlignHCenter) \n \n pltbox = QtGui.QHBoxLayout()\n pltbox.addWidget(qtab)\n pltbox.addLayout(vsbox)\n \n mainbox.addLayout(pltbox)\n mainbox.addLayout(hsbox)\n self.groupBox2.setLayout(mainbox)\n\n #比率調整\n sizePolicy1 = self.groupBox.sizePolicy()\n sizePolicy2 = self.groupBox2.sizePolicy()\n sizePolicy1.setHorizontalStretch(2)\n sizePolicy2.setHorizontalStretch(7)\n self.groupBox.setSizePolicy(sizePolicy1)\n self.groupBox2.setSizePolicy(sizePolicy2)\n\n grid.addWidget(self.groupBox2) \n self.setLayout(grid) \n\n #***シグナル***\n startBtn.clicked.connect(self.start_simulation)\n saveBtn.clicked.connect(self.save_settings)\n self.sliderh.valueChanged.connect(self.on_slideh) \n self.sliderv.valueChanged.connect(self.on_slidev)\n self.sliderh.sliderReleased.connect(self.slidend)\n self.sliderv.sliderReleased.connect(self.slidend)\n \n #ウィンドウ調整 \n self.setGeometry(300, 300, 350, 300)\n self.setWindowTitle('にゅうろん!') \n self.resize(3000, 1800) \n #最前面\n self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) \n self.show()\n \n #***以下スロット***\n #スタートボタン\n def start_simulation(self):\n \n #データ設定\n self.neuron1.set_neuron_palameter(int(self.numneuEdit.text()),\n float(self.vthEdit.text()),\n float(self.vrmEdit.text()),\n float(self.tauEdit.text()), \n float(self.deltatimeEdit.text()), \n float(self.phightimeEdit.text()), \n float(self.phighEdit.text()),\n float(self.e_synEdit.text()), \n float(self.def_wEdit.text()), \n float(self.sigmoid_gainEdit.text()), \n float(self.ab_refacttimeEdit.text()), \n float(self.ab_weakEdit.text()),\n float(self.simtimeEdit.text()))\n \n w = np.ones((self.neuron1.numneu, self.neuron1.numneu)) * float(self.def_wEdit.text())\n for i in range(0, self.neuron1.numneu):\n w[i][i] = 0\n w[0][0] = 1\n #w[1][1] = 1 \n self.neuron1.set_weight(w) \n \n self.tab1.replot(self.neuron1)\n self.tab2.replot(self.neuron1)\n \n #figure横サイズ\n def on_slideh(self):\n self.tab1.fig.set_figwidth(float(self.sliderh.value()))\n\n #キャンバス上にFigureを再セットしないとスクロールバーの長さが変更されない \n self.tab1.canvas = FigureCanvas(self.tab1.fig)\n self.tab1.scroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)\n self.tab1.scroll.setWidget(self.tab1.canvas)\n\n #ツールバーも再セット \n self.tab1.navi_toolbar.setVisible(False) \n self.tab1.layout.removeWidget(self.tab1.navi_toolbar) \n self.tab1.navi_toolbar = NavigationToolbar(self.tab1.canvas, self)\n \n \n #figure縦サイズ\n def on_slidev(self):\n self.tab1.fig.set_figheight(float(self.sliderv.value()))\n \n #キャンバス上にFigureを再セットしないとスクロールバーの長さが変更されない \n self.tab1.canvas = FigureCanvas(self.tab1.fig)\n self.tab1.scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)\n self.tab1.scroll.setWidget(self.tab1.canvas)\n \n #ツールバーも再セット\n self.tab1.navi_toolbar.setVisible(False)\n self.tab1.layout.removeWidget(self.tab1.navi_toolbar) \n self.tab1.navi_toolbar = NavigationToolbar(self.tab1.canvas, self)\n\n #スライドバー開放時にツールバーを再セット\n def slidend(self):\n self.tab1.layout.addWidget(self.tab1.navi_toolbar)\n \n \n def save_settings(self):\n print(\"てすと\") \n \n\n#波形表示 \nclass TabwaveWidget(QtGui.QWidget):\n\n #初期描画\n def __init__(self, neuron):\n super().__init__() \n self.plot(neuron)\n \n #グラフをタブにセット \n self.canvas = FigureCanvas(self.fig)\n self.navi_toolbar = NavigationToolbar(self.canvas, self)\n self.layout = QtGui.QVBoxLayout()\n self.scroll = QtGui.QScrollArea()\n self.scroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)\n self.scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)\n self.scroll.setWidget(self.canvas) \n self.layout.addWidget(self.scroll)\n self.layout.addWidget(self.navi_toolbar)\n self.setLayout(self.layout)\n \n #グラフを更新する場合\n def replot(self, neuron):\n self.layout.removeWidget(self.navi_toolbar) \n plt.close()\n self.layout.removeWidget(self.scroll)\n self.plot(neuron)\n \n #再セット\n if neuron.numneu < 11:\n self.canvas = FigureCanvas(self.fig)\n self.navi_toolbar = NavigationToolbar(self.canvas, self)\n self.scroll = QtGui.QScrollArea()\n self.scroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)\n self.scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)\n self.scroll.setWidget(self.canvas) \n self.layout.addWidget(self.scroll) \n self.layout.addWidget(self.navi_toolbar)\n \n #メイン処理\n def plot(self, neuron):\n \n self.fig, self.ax = plt.subplots(nrows = neuron.numneu, figsize=(16, 32))\n \n #軸\n self.t = np.arange(0, (neuron.simtime*neuron.deltatime), neuron.deltatime)\n self.vplt = np.ones((neuron.numneu, np.size(self.t))) * (-70) \n\n #グラフ設定\n for i in range(0, neuron.numneu):\n if neuron.numneu == 1:\n self.ax.set_xlim((self.t.min(), self.t.max()))\n self.ax.set_ylim(neuron.vrm[0]-20, neuron.phigh[0]+10)\n self.ax.grid(which='major',color='thistle',linestyle='-')\n self.ax.spines[\"top\"].set_color(\"indigo\")\n self.ax.spines[\"bottom\"].set_color(\"indigo\")\n self.ax.spines[\"left\"].set_color(\"indigo\")\n self.ax.spines[\"right\"].set_color(\"indigo\")\n\n else: \n self.ax[i].set_xlim((self.t.min(), self.t.max()))\n self.ax[i].set_ylim(neuron.vrm[0]-20, neuron.phigh[0]+10)\n self.ax[i].grid(which='major',color='thistle',linestyle='-')\n self.ax[i].spines[\"top\"].set_color(\"indigo\")\n self.ax[i].spines[\"bottom\"].set_color(\"indigo\")\n self.ax[i].spines[\"left\"].set_color(\"indigo\")\n self.ax[i].spines[\"right\"].set_color(\"indigo\")\n \n self.fig.tight_layout()\n self.fig.subplots_adjust(left=0.05, bottom=0.03)\n\n self.fig.text(0.5, 0.01, 'time [t]', fontsize=16, ha='center', va='center') \n self.fig.text(0.01, 0.5, 'membrane potential [mV]', fontsize=16, ha='center', va='center', rotation='vertical') \n self.fig.patch.set_facecolor('whitesmoke') \n \n #初期化\n self.lines = []\n for i in range(0, neuron.numneu):\n self.lines.append([])\n if neuron.numneu == 1:\n self.lines, = self.ax.plot(neuron.tmhist, neuron.vin[i], color=\"indigo\")\n else:\n self.lines[i], = self.ax[i].plot(neuron.tmhist, neuron.vin[i], color=\"indigo\")\n \n #信号伝達 \n self.start_time = time.time()\n for i in range(0, np.size(self.t)): \n neuron.propagation()\n self.elapsed_time = time.time() - self.start_time\n print(\"elapsed_time:{0}\".format(self.elapsed_time) + \"[sec]\") \n \n #プロット\n if neuron.numneu < 11:\n for i in range(0, neuron.numneu): \n base = np.ones(np.size(neuron.tmhist)) * (-100) \n if neuron.numneu == 1:\n self.lines.set_data(neuron.tmhist, self.neuron.vin)\n self.ax.fill_between(neuron.tmhist, self.neuron.vin, base, facecolor=\"thistle\", alpha=0.2) \n else:\n self.lines[i].set_data(neuron.tmhist, neuron.vin[i]) \n self.ax[i].fill_between(neuron.tmhist, neuron.vin[i], base, facecolor=\"thistle\", alpha=0.2) \n \n\n \n#ラスター表示\nclass TablasterWidget(QtGui.QWidget):\n \n #初期描画\n def __init__(self, neuron):\n super().__init__() \n self.plot(neuron)\n \n #グラフをタブにセット \n self.canvas = FigureCanvas(self.fig)\n self.navi_toolbar = NavigationToolbar(self.canvas, self)\n self.layout = QtGui.QVBoxLayout() \n self.layout.addWidget(self.canvas)\n self.layout.addWidget(self.navi_toolbar)\n self.setLayout(self.layout)\n \n #グラフを更新する場合\n def replot(self, neuron):\n self.layout.removeWidget(self.navi_toolbar) \n plt.close()\n self.layout.removeWidget(self.canvas)\n self.plot(neuron)\n \n #再セット\n self.canvas = FigureCanvas(self.fig)\n self.navi_toolbar = NavigationToolbar(self.canvas, self)\n self.layout.addWidget(self.canvas) \n self.layout.addWidget(self.navi_toolbar)\n\n #メイン処理\n def plot(self, neuron):\n \n self.fig, self.ax = plt.subplots(nrows = 1, figsize=(10, 15))\n self.t = np.arange(0, (neuron.simtime*neuron.deltatime), neuron.deltatime) \n\n #グラフ設定\n self.ax.set_xlabel(\"time[s]\") \n self.ax.set_ylabel(\"Neuron\")\n self.ax.set_title(\"raster plot\")\n self.ax.set_yticks(np.arange(0, (neuron.numneu + 1), 1.0))\n self.ax.set_xlim((self.t.min(), self.t.max()))\n self.ax.set_ylim([0, neuron.numneu + 1])\n self.ax.grid(which='major',color='thistle',linestyle='-')\n self.ax.spines[\"top\"].set_color(\"indigo\")\n self.ax.spines[\"bottom\"].set_color(\"indigo\")\n self.ax.spines[\"left\"].set_color(\"indigo\")\n self.ax.spines[\"right\"].set_color(\"indigo\")\n self.fig.patch.set_facecolor('whitesmoke') \n\n #棒作成\n for i in range(0, neuron.numneu):\n for j in range(0, np.size(self.t)):\n if neuron.raster[i][j] != 0:\n self.ax.vlines(self.t[j], neuron.raster[i][j] - 0.49, neuron.raster[i][j] + 0.49, \"indigo\")\n \ndef main():\n app = QtGui.QApplication(sys.argv)\n app.setFont(QtGui.QFont(\"Yu Gothic UI\"))\n main = Main()\n sys.exit(app.exec_())\n \nif __name__ == '__main__':\n main()\n","sub_path":"old/neuron5/main5.py","file_name":"main5.py","file_ext":"py","file_size_in_byte":18797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"649225179","text":"# Copyright 2014-present PlatformIO <contact@platformio.org>\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\nfrom platformio import exception, util\nfrom platformio.managers.platform import PlatformBase\n\n\nclass Linux_armPlatform(PlatformBase):\n\n @property\n def packages(self):\n packages = PlatformBase.packages.fget(self)\n if (\"darwin_x86_64\" not in util.get_systype() and\n \"toolchain-gccarmlinuxgnueabi\" in packages):\n del packages['toolchain-gccarmlinuxgnueabi']\n if (\"darwin_x86_64\" in util.get_systype() and\n \"toolchain-gcc-linaro-arm-linux-gnueabihf\" in packages):\n del packages['toolchain-gcc-linaro-arm-linux-gnueabihf']\n if (\"linux_arm\" in util.get_systype() and\n \"tool-linux_arm\" in packages):\n del packages['tool-linux_arm']\n return packages\n\n def configure_default_packages(self, variables, targets):\n if (\"wiringpi\" in variables.get(\"pioframework\") and\n \"linux_arm\" not in util.get_systype()):\n raise exception.PlatformioException(\n \"PlatformIO temporary does not support cross-compilation \"\n \"for WiringPi framework. Please run PlatformIO directly on \"\n \"Raspberry Pi\")\n\n return PlatformBase.configure_default_packages(self, variables,\n targets)\n","sub_path":"platform.py","file_name":"platform.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"311608340","text":"#------------------------------------------------------------------------------\n# Copyright (c) 2011, Enthought, Inc.\n# All rights reserved.\n#------------------------------------------------------------------------------\nfrom abc import ABCMeta, abstractmethod\nfrom weakref import ref\n\nfrom traits.api import HasTraits, Disallow\n\nfrom .byteplay import (\n CALL_FUNCTION, ROT_THREE, LOAD_CONST, LOAD_ATTR, ROT_TWO, BUILD_TUPLE, \n UNPACK_SEQUENCE, POP_TOP, DUP_TOP,\n)\nfrom .signaling import Signal\n\n\n#------------------------------------------------------------------------------\n# Abstract Monitor\n#------------------------------------------------------------------------------\nclass AbstractMonitor(object):\n \"\"\" An abstract base class which defines the api for implementing \n an expression monitor. \n\n An expression Monitor is responsible for generating bytecode which\n will be inserted into a Python expression and which inspects the\n Python stack during the evaluation to determine if it is appropriate\n to attach some form of notifier to the constiuents. If a notifier is \n warranted, it should make the appropriate connections to emit the\n expression_changed signal when the expression has changed.\n\n \"\"\"\n __metaclass__ = ABCMeta\n\n #: A signal which is emitted when the expression has changed.\n expression_changed = Signal()\n\n @abstractmethod\n def get_insertion_code(self, code_list):\n \"\"\" Generates the byteplay code operations to be inserted into \n the expression code object in order to monitor execution.\n\n Parameters\n ----------\n code_list : list of (op_code, op_arg)\n The list of byteplay code operations for the expression.\n If no code need be generated, an empty list should be \n returned.\n\n Returns\n -------\n result : list of (insertion_idx, code_ops)\n A list of 2-tuples where the first item is an integer index\n into the original code_list and the second item is the list\n of byteplay code operations to insert into the final code.\n\n Notes\n -----\n The generated instertion code *must* have a net-zero effect on \n the Python stack. This means that the inserted code should leave\n the stack exactly the way it found it. If this is not maintained,\n then random exceptions and/or crashes *will* result.\n\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def reset(self):\n \"\"\" Unhook any previously connected notifiers. This method is \n called by the owner expression when notifiers should be removed.\n\n \"\"\"\n raise NotImplementedError\n\n\n#------------------------------------------------------------------------------\n# Abstract Attribute Monitor\n#------------------------------------------------------------------------------\nclass AbstractAttributeMonitor(AbstractMonitor):\n \"\"\" An abstract monitor which monitors the expression evaluation for \n attribute access and calls a method with the object and attribute \n which is being accessed.\n \n \"\"\"\n def get_insertion_code(self, code_list):\n \"\"\" Generates the byteplay code operations to be inserted into \n the expression code object to monitor attribute accesses. When\n an attribute access occurs, the 'monitor_attribute' method will \n be called with the object and attribute name as arguments.\n\n \"\"\"\n # A weak closure which is injected into the stack to call the\n # monitor method upon attribute access.\n def code_binder(obj, attr, selfref=ref(self)):\n this = selfref()\n if this is not None:\n this.monitor_attribute(obj, attr)\n \n # The list of code segments that will be inserted into the\n # new bytecode for the expression.\n insertion_code = []\n\n for idx, (op, op_arg) in enumerate(code_list):\n # This bit of code is injected between the object on TOS\n # and its pending attribute access. The TOS obj is duped,\n # the rotated above the binder code. The attr is loaded,\n # and the binder is called with the object and attr. The\n # return value of the binder is discarded. This leaves the\n # original TOS and pending attribute access to continue on\n # as normal\n if op == LOAD_ATTR:\n code = [\n (DUP_TOP, None),\n (LOAD_CONST, code_binder),\n (ROT_TWO, None),\n (LOAD_CONST, op_arg),\n (CALL_FUNCTION, 0x0002),\n (POP_TOP, None),\n ]\n insertion_code.append((idx, code))\n\n return insertion_code\n\n @abstractmethod\n def monitor_attribute(self, obj, attr):\n \"\"\" Hooks up any necessary monitors for the given object and \n attribute. \n\n Parameters\n ----------\n obj : object\n The object on which the attribute access is being performed.\n \n attr : string\n The name of the attribute which is being accessed on the\n object.\n \n \"\"\"\n raise NotImplementedError\n\n \n#------------------------------------------------------------------------------\n# Abstract Call Monitor\n#------------------------------------------------------------------------------\nclass AbstractCallMonitor(AbstractMonitor):\n \"\"\" An abstract monitor which monitors the expression evaluation for \n function calls and calls a method with the object and arguments which\n are being called.\n \n \"\"\"\n def get_insertion_code(self, code_list):\n \"\"\" Generates the byteplay code operations to be inserted into \n the expression code object to monitor function calls. When an\n attribute access occurs, the 'monitor_function' method will be \n called with the object, args, and kwargs.\n\n \"\"\"\n # A weak closure which is injected into the stack to call the\n # monitor method on function call.\n def code_binder(func_obj, arg_tuple, arg_spec, selfref=ref(self)):\n this = selfref()\n if this is not None:\n nargs = arg_spec & 0xFF\n args = arg_tuple[:nargs]\n kwargs = dict(zip(arg_tuple[nargs::2], arg_tuple[nargs+1::2]))\n this.monitor_function(func_obj, args, kwargs)\n # The UNPACK_SEQUENCE op_codes which will unpack these \n # return values will unpack things onto the stack in the\n # reverse of how they are provided. So, we pre-reverse them\n # so they come out in the right order.\n return (tuple(reversed(arg_tuple)), func_obj)\n \n # The list of code segments that will be inserted into the\n # new bytecode for the expression.\n insertion_code = []\n\n for idx, (op, op_arg) in enumerate(code_list):\n # This bit of code is injected just before a function call\n # is performed. The arguments on the stack are packed into\n # tuple. The code binder is then pushed onto the stack and\n # rotated under the func_obj and arg_tuple. The arg spec\n # is then loaded and the code binder is invoked. The return \n # value of the code binder is the original func_obj and \n # arg_tuple. This return tuple is unpacked, and then the \n # arg_tuple is unpacked and the function call proceeds as \n # normal.\n if op == CALL_FUNCTION:\n # This computes the number of objects on the stack \n # between TOS and the object being called. Only the\n # last 16bits of the op_arg are signifcant. The lowest\n # 8 are the number of positional args on the stack,\n # the upper 8 is the number of kwargs. For kwargs, the\n # number of items on the stack is twice this number \n # since the values on the stack alternate name, value.\n n_stack_args = (op_arg & 0xFF) + 2 * ((op_arg >> 8) & 0xFF)\n code = [\n (BUILD_TUPLE, n_stack_args),\n (LOAD_CONST, code_binder),\n (ROT_THREE, None),\n (LOAD_CONST, op_arg),\n (CALL_FUNCTION, 0x0003),\n (UNPACK_SEQUENCE, 2),\n (UNPACK_SEQUENCE, n_stack_args),\n ]\n insertion_code.append((idx, code))\n \n # TODO - CALL_FUNCTION_VAR, CALL_FUNCTION_KW, CALL_FUNCTION_VAR_KW\n\n return insertion_code\n \n @abstractmethod\n def monitor_function(self, func_obj, args, kwargs):\n \"\"\" Hooks up any necessary monitors for the given function object\n and the args and kwargs with which it is being called.\n\n Parameters\n ----------\n func_obj : callable object\n The function-like object which is being called.\n \n args : tuple\n The arguments being passed to the function.\n\n kwargs : dict\n The keyword arguments being passed to the function.\n \n \"\"\"\n raise NotImplementedError\n\n\n#------------------------------------------------------------------------------\n# Trait Notification Handler\n#------------------------------------------------------------------------------\nclass _TraitNotificationHandler(object):\n \"\"\" A thin class which makes it easier to manage the lifetime of \n a trait notifier.\n\n \"\"\"\n def __init__(self, parent, obj, attr):\n \"\"\" Initialize a TraitNotificationHandler.\n\n Parameters\n ----------\n parent : AbstractMonitor\n The AbstractMonitor instance which is the parent of this\n handler. Only a weak reference to the parent is kept.\n\n obj : HasTraits\n The HasTraits instance on which we are attaching a listener.\n \n attr : string\n The trait attribute on the object to which we should listen.\n\n \"\"\"\n self._parent_ref = ref(parent)\n obj.on_trait_change(self.notify, attr)\n\n def notify(self):\n \"\"\" The trait change callback which will emit the expression\n changed signal on the parent.\n\n \"\"\"\n parent = self._parent_ref()\n if parent is not None:\n parent.expression_changed()\n\n\n#------------------------------------------------------------------------------\n# Trait Handler Mixin\n#------------------------------------------------------------------------------\nclass TraitHandlerMixin(object):\n \"\"\" A mixin class which adds the common binding code for the trait\n monitor classes below.\n\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(TraitHandlerMixin, self).__init__(*args, **kwargs)\n # A dictionary which holds the notification handlers. A key\n # in the dictionary is an (obj_id, attr) tuple and the value\n # is the notification handler for that pair. The object id \n # is used to avoid ref cycles and potential hashing issues.\n self._handlers = {}\n\n def reset(self):\n \"\"\" Clears the existing handlers which results in the notifiers\n being destroyed.\n\n \"\"\"\n self._handlers.clear()\n\n def do_binding(self, obj, attr):\n \"\"\" Hooks up a notifier to the object attribute pair if the \n object is a HasTraits instance and the attribute refers to \n a valid trait on the object.\n\n \"\"\"\n # Don't hook up multiple identifiers to the same object/attr\n # pair. Use the id of the object to prevent an accidental ref\n # cycle to the object.\n handlers = self._handlers\n key = (id(obj), attr)\n if key in handlers:\n return\n \n if isinstance(obj, HasTraits):\n # Only hook up a notifier if the attribute access refers to\n # a proper trait. We check for Disallow trait types since \n # those can be returned by instances of HasStrictTraits\n trait = obj.trait(attr)\n if trait is not None and trait.trait_type is not Disallow:\n handler = _TraitNotificationHandler(self, obj, attr)\n handlers[key] = handler\n\n\n#------------------------------------------------------------------------------\n# Trait Attribute Monitor\n#------------------------------------------------------------------------------\nclass TraitAttributeMonitor(TraitHandlerMixin, AbstractAttributeMonitor):\n \"\"\" An AbstractAttributeMonitor implementation which binds listeners\n to trait attributes on HasTraits classes.\n\n \"\"\"\n def monitor_attribute(self, obj, attr):\n \"\"\" Hooks up any necessary trait change notifiers for the given\n object and attribute. \n\n Parameters\n ----------\n obj : object\n The object on which the attribute access is being performed.\n \n attr : string\n The name of the attribute which is being accessed on the\n object.\n \n \"\"\"\n self.do_binding(obj, attr)\n\n\n#------------------------------------------------------------------------------\n# Trait Getattr Monitor\n#------------------------------------------------------------------------------\nclass TraitGetattrMonitor(TraitHandlerMixin, AbstractCallMonitor):\n \"\"\" An AbstractCallMonitor implementation which binds listeners to\n trait attributes on HasTraits classes which are accessed through a\n call to the builtin getattr.\n\n \"\"\"\n def monitor_function(self, func_obj, args, kwargs):\n \"\"\" Hooks up any necessary trait change notifiers for the given\n call to getattr\n\n Parameters\n ----------\n func_obj : callable object\n The function-like object which is being called. If this is\n not the builtin getattr, or if the call spec is invalid for\n getattr, this method is a no-op.\n \n args : tuple\n The arguments being passed to the function.\n\n kwargs : dict\n The keyword arguments being passed to the function.\n \n \"\"\"\n n_args = len(args)\n if func_obj is not getattr or n_args < 2 or n_args > 3 or kwargs:\n return\n \n obj, attr = args[0], args[1]\n if not isinstance(attr, basestring):\n return\n \n self.do_binding(obj, attr)\n\n","sub_path":"enaml/core/monitors.py","file_name":"monitors.py","file_ext":"py","file_size_in_byte":14537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"89086172","text":"import tkinter as tk\nfrom tkinter import filedialog\nfrom functools import partial\nfrom res import Loader, Projector, Resources\nimport os\nfrom os.path import dirname, abspath\nfrom PIL import Image, ImageTk, ImageEnhance\nfrom matplotlib import pyplot as plt\nimport numpy as np\nfrom reconstruct import Builder\nfrom glob import glob\nimport threading\nfrom queue import Queue\nimport editor\n\n\n\n\n\n\ndef test(tekst):\n print(\"Wywołano funkcję {}\".format(tekst))\n\n# class SplashWindow:\n# def __init__(self, master, screen_width, screen_height, logo_width, logo_height):\n# self.screen_width = screen_width\n# self.screen_height = screen_height\n# self.logo_width = logo_width\n# self.logo_height = logo_height\n# master.overrideredirect(True)\n#\n# x = (screen_width / 2) - (logo_width / 2)\n# y = (screen_height / 2) - (logo_height / 2)\n#\n# master.geometry(\"%dx%d+%d+%d\" % (logo_width, logo_height, x, y))\n# image = ImageTk.PhotoImage(Image.open(\"resources/logo.png\").resize((logo_width, logo_height)))\n# canvas = tk.Canvas(master, height=logo_height, width=logo_width, bg=\"white\")\n# canvas.create_image(screen_width / 2, screen_height / 2, image=image)\n# canvas.pack()\n# # show the splash screen for 5000 milliseconds then destroy\n# master.after(5000, master.destroy)\n\nclass Window:\n def __init__(self,master,width,height,x,y):\n self.width = width\n self.height = height\n self.x = x\n self.y = y\n self.frames = {}\n self.load = Loader()\n self.display = Projector()\n master.geometry(\"%dx%d+%d+%d\" % (width, height, x, y))\n\n self.container = tk.Frame(master)\n self.container.pack(side=\"top\", fill=\"both\", expand=True)\n self.container.grid_rowconfigure(0,weight=1)\n self.container.grid_columnconfigure(0,weight=1)\n\n for F in (StartPage, WorkPage, AboutPage):\n frame = F(self.container,self)\n self.frames[F] = frame\n frame.grid(row=0,column=0,sticky=\"nsew\")\n\n\n menu_bar = tk.Menu(master)\n\n file = tk.Menu(menu_bar, tearoff=0)\n file.add_command(label=\"Nowy projekt\", command=partial(test, \"Nowy\"))\n file.add_command(label=\"Otwórz plik\", command=partial(self.workPageController, self.container,\"file\"))\n file.add_command(label=\"Otwórz folder z plikami\", command=partial(self.workPageController, self.container,\"Folder\"))\n file.add_separator()\n file.add_command(label=\"Wyjdź\", command=master.destroy)\n menu_bar.add_cascade(label=\"Plik\", menu=file)\n\n edit = tk.Menu(menu_bar, tearoff=0)\n edit.add_command(label=\"Cofnij\", command=partial(test, \"Cofnij\"))\n edit.add_command(label=\"Ponów\", command=partial(test, \"Ponów\"))\n menu_bar.add_cascade(label=\"Edytuj\", menu=edit)\n\n help = tk.Menu(menu_bar, tearoff=0)\n help.add_command(label=\"Dokumentacja\", command=partial(test, \"Dokumentacja\"))\n help.add_command(label=\"O programie\", command=partial(self.show_page, AboutPage))\n menu_bar.add_cascade(label=\"Pomoc\", menu=help)\n\n master.config(menu=menu_bar)\n self.show_page(StartPage)\n\n def show_page(self,page):\n\n frame = self.frames[page]\n frame.tkraise()\n\n\n def workPageController(self,container,browse):\n editor = Editor()\n q = Queue()\n if self.frames[WorkPage] is not None:\n self.frames[WorkPage].destroy()\n frame = WorkPage(container,self,editor)\n self.frames[WorkPage] = frame\n\n frame.grid(row=0,column=0,sticky=\"nsew\")\n if (browse==\"file\"):\n file, ext = self.file_browse(container)\n editor.image = file\n editor.ext = ext\n else:\n file = self.path_browse(container)\n build = Builder(tk.fileName)\n th_build = threading.Thread(target=build.start, args=(file, q))\n th_build.start()\n th_build.join()\n self.array = q.get()\n self.frames[WorkPage].uploadedImageBox()\n self.show_page(WorkPage)\n\n def file_browse(self,master):\n tk.fileName = filedialog.askopenfilename(filetypes=((\"MIRAX files\",\".mrxs\"),(\"DICOM files\",\".dcm\"),(\"TIFF files\",(\".tif\",\".tiff\")),(\"All files\",\"*.*\")))\n ext = os.path.splitext(tk.fileName)[-1].lower()\n\n print(\"Typ tego workpage image_box to: {}\".format(type(self.frames[WorkPage].image_box)))\n if tk.fileName:\n if ext == \".tif\" or ext == \".tiff\":\n file=self.load.loadTIFF(tk.fileName)\n self.display.displayTIFF(master, file, self.frames[WorkPage].image_box)\n elif ext == \".dcm\":\n self.load.loadDICOM(tk.fileName)\n elif ext == \".mrxs\":\n file = self.load.loadMIRAX(tk.fileName,master)\n self.display.displayMIRAX(master,file,self.frames[WorkPage].image_box,tk.fileName)\n else:\n self.load.loadDICOM(tk.fileName)\n print(\"Nie rozpoznawany format danych\")\n return file,ext\n\n def path_browse(self,master):\n self.frames[WorkPage].waitImageBox()\n print(\"Path browse wystartowal\")\n tk.fileName = filedialog.askdirectory()\n g = glob(tk.fileName + '/*.dcm')\n slices = self.load.loadDICOM(tk.fileName)\n return slices\n\n\nclass StartPage(tk.Frame):\n\n def __init__(self,master,controller):\n tk.Frame.__init__(self, master)\n logo_png = ImageTk.PhotoImage(Resources.logo.resize((900, 250), Image.ANTIALIAS))\n logo = tk.Label(self, image=logo_png)\n logo.logo_png = logo_png\n logo.place(relx=0.5, rely=0.5, anchor=tk.CENTER)\n\nclass WorkPage(tk.Frame):\n def __init__(self,master, controller,editor=None):\n tk.Frame.__init__(self,master)\n self.image_box = tk.Frame(self)\n self.image_box.place(relwidth=0.8, relheight=1, relx=0.2, rely=0.5, anchor=\"w\")\n\n self.func_box = tk.Frame(self)\n self.func_box.place(relwidth=0.2, relheight=1, relx=0, rely=0)\n\n HU_label = tk.Label(self.func_box, text=\"Poziom HU\")\n HU_value = tk.IntVar()\n HU_scale = tk.Scale(self.func_box, from_=-1000, to=1000, length=300, tickinterval=10, orient=tk.HORIZONTAL,\n variable=HU_value)\n HU_label.pack()\n HU_scale.pack()\n\n contrast_label = tk.Label(self.func_box, text=\"Kontrast\")\n contrast_value=tk.IntVar()\n contrast_scale = tk.Scale(self.func_box, from_=-10, to=10, length=300, tickinterval=10, orient=tk.HORIZONTAL, variable=contrast_value)\n\n contrast_label.pack()\n contrast_scale.pack()\n\n brightness_label = tk.Label(self.func_box, text=\"Jasność\")\n brightness_value = tk.IntVar()\n brightness_scale = tk.Scale(self.func_box, from_=-20, to=20, length=300, tickinterval=10,orient=tk.HORIZONTAL, variable=brightness_value)\n\n brightness_label.pack()\n brightness_scale.pack()\n\n apply_button = tk.Button(self.func_box, text=\"Generuj obraz 3D\", command=partial(self.apply, editor,brightness_value,contrast_value, HU_value,master,controller))\n\n apply_button.pack()\n print(type(self.func_box))\n print(self.func_box.__class__)\n\n def apply(self,editor,brightness,contrast,HU,master,controller):\n HU = HU.get()\n brightness = brightness.get()\n contrast = contrast.get()\n self.resetImageBox()\n display = Projector()\n display.display3D(controller.array,HU)\n #editor.edit(contrast,brightness,HU, self.image_box)\n\n def resetImageBox(self):\n if self.image_box is not None:\n self.image_box.destroy()\n self.image_box = tk.Frame(self)\n self.image_box.place(relwidth=0.8, relheight=1, relx=0.2, rely=0.5, anchor=\"w\")\n\n def waitImageBox(self):\n self.resetImageBox()\n logo_png = ImageTk.PhotoImage(Resources.logo.resize((720, 200), Image.ANTIALIAS))\n logo = tk.Label(self.image_box, image=logo_png)\n logo.logo_png = logo_png\n logo.pack()\n\n text = tk.Label(self.image_box, text=Resources.wait, font=(\"Calibri\", 20))\n text.pack()\n def uploadedImageBox(self):\n self.resetImageBox()\n logo_png = ImageTk.PhotoImage(Resources.logo.resize((720, 200), Image.ANTIALIAS))\n logo = tk.Label(self.image_box, image=logo_png)\n logo.logo_png = logo_png\n logo.pack()\n\n text = tk.Label(self.image_box, text=Resources.uploaded, font=(\"Calibri\", 20))\n text.pack()\n\n\nclass AboutPage(tk.Frame):\n\n def __init__(self, master, controller):\n tk.Frame.__init__(self, master)\n about_box = tk.Frame(self)\n about_box.pack()\n logo_png = ImageTk.PhotoImage(Resources.logo.resize((720, 200), Image.ANTIALIAS))\n logo = tk.Label(about_box, image=logo_png)\n logo.logo_png = logo_png\n logo.pack()\n\n text = tk.Label(about_box, text=Resources.about, font=(\"Calibri\", 20))\n text.pack()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":9074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"128030996","text":"from service_utils import main, PythonService\nimport os\n\npath=os.path.split(__file__)[0]\n\nclass ZKECOADMSService(PythonService):\n _svc_name_ = \"ZKECOWEBService\"\n _svc_display_name_ = \"ZKECO Web Service\"\n _svc_deps_ = []\n path = path\n cmd_and_args=[\"svr8000.pyc\", ]\n def stop_fun(self, process):\n os.system(\"\"\"taskkill /IM nginx.exe /F\"\"\")\n\nif __name__=='__main__':\n main(ZKECOADMSService)\n","sub_path":"zkeco-core/adms/bak_services/ServiceADMS.py","file_name":"ServiceADMS.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"46967006","text":"import unittest\n\nimport torch\n\nfrom util.multimodal_dataset import MultimodalDataset\nfrom util.text_encoder_interface import CharEmbedTransform\n\n\nclass MyTestCase(unittest.TestCase):\n def test_something(self):\n sentence = \"A quick call\"\n doc_length = 350\n char_embedding_transform = CharEmbedTransform(doc_length)\n char_encoder = MultimodalDataset._basic_char_encoder(doc_length, lambda x, y: None)\n encoding1 = char_embedding_transform(sentence)\n encoding2 = char_encoder(sentence)\n \n self.assertEqual(torch.all(torch.eq(encoding2, encoding1)).item(), True)\n ...\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"util/unittest/text_encoding_test.py","file_name":"text_encoding_test.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"500465921","text":"class Solution:\n def removeDuplicateLetters(self, s: str) -> str:\n # Store last index of each char which will help to determine whether the char has a duplicate or not.\n lastIndex = {}\n for index, ch in enumerate(s):\n lastIndex[ch] = index\n stack = []\n for index, ch in enumerate(s):\n # Check while top of stack occurs further also and is greater than ch then pop it and push ch\n if ch not in stack:\n while stack and stack[-1] > ch and lastIndex[stack[-1]] > index:\n stack.pop()\n stack.append(ch)\n return ''.join(stack)\n","sub_path":"RemoveDuplicateLetters/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"516618746","text":"#!/usr/bin/env python3\nimport Adafruit_DHT\nimport time\nimport os\nimport sys\nimport socket\nimport systemd.daemon\nfrom influxdb import InfluxDBClient\n\nserverIp = os.environ.get('INFLUX_SERVER_IP', '192.168.1.128')\nprint('Env: serverIp ', serverIp)\nserverPort = os.environ.get('INFLUX_SERVER_PORT', 8086)\nprint('Env: serverPort ', serverPort)\nserverDatabase = os.environ.get('INFLUX_SERVER_DATABASE', 'external')\nprint('Env: serverDatabase ', serverDatabase)\n\nclient = InfluxDBClient(host=serverIp, port=serverPort,\n database=serverDatabase)\n\nlocation = os.environ.get('LOCATION', '')\nif location is '':\n sys.exit('Missing location')\n\n\nhostname = socket.gethostname()\n\n# Notify systemd that we're done loading.\nsystemd.daemon.notify('READY=1')\n\n\nDHT_SENSOR = Adafruit_DHT.DHT22\nDHT_PIN = 2\n\nwhile True:\n try:\n tags = {}\n metrics = {}\n\n tags['hostname'] = hostname\n tags['location'] = location\n\n metrics['tags'] = tags\n metrics['measurement'] = 'ambient_temperature'\n\n humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)\n if humidity is not None and temperature is not None:\n\n fields = {}\n fields['humidity'] = humidity\n fields['temperature'] = temperature\n metrics['fields'] = fields\n\n client.write_points([metrics])\n print(metrics)\n except RuntimeError as error:\n print(error.args[0])\n\n time.sleep(10)\n","sub_path":"apps/ambient_temperature/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"565490477","text":"import copy\nimport sys\nfrom helpers.AoCHelper import *\nfrom helpers.GlobalVariables import *\n\nsys.setrecursionlimit(5000)\n\ninput_lines = [list(i) for i in read_input_lines('day11/day11input1.txt')]\n\n\ndef process_seats(seats, neighbour_limit, immediate_neighbour):\n new_configuration = copy.deepcopy(seats)\n\n for i in range(len(seats)):\n for j in range(len(seats[0])):\n seat_status = new_configuration[i][j]\n\n if new_configuration == '.':\n new_configuration[i][j] = seat_status\n continue\n\n adjacent_people = list(filter(lambda x: x == '#', get_neighbours(i, j, seats, all_directions,\n immediate_neighbour, ['.'])))\n\n if seat_status == 'L' and len(adjacent_people) == 0:\n new_configuration[i][j] = '#'\n elif seat_status == '#' and len(adjacent_people) >= neighbour_limit:\n new_configuration[i][j] = 'L'\n else:\n new_configuration[i][j] = seat_status\n\n return new_configuration\n\n\ndef find_stable_configuration(initial_configuration, neighbour_limit, immediate_neighbour):\n initial_seats = initial_configuration\n updated_seats = process_seats(initial_configuration, neighbour_limit, immediate_neighbour)\n\n while not min([i == j for i, j in zip(initial_seats, updated_seats)]):\n initial_seats = updated_seats\n updated_seats = process_seats(initial_seats, neighbour_limit, immediate_neighbour)\n\n return updated_seats\n\n\n# Part 1\ntaken_seats = sum([seat_row.count('#') for seat_row in find_stable_configuration(input_lines, 4, True)])\nassert taken_seats == 2263\nprint(\"Part 1: \" + str(taken_seats))\n\n# Part 2\ntaken_seats = sum([seat_row.count('#') for seat_row in find_stable_configuration(input_lines, 5, False)])\nassert taken_seats == 2002\nprint(\"Part 2: \" + str(taken_seats))\n","sub_path":"Day11.py","file_name":"Day11.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"599675115","text":"#!/usr/bin/env python\r\n# -*- coding: UTF-8 -*-\r\n\r\n#\r\n# crop face from all picture in specific directory in every second\r\n#\r\n# usage: \r\n#\r\n\r\nfrom __future__ import print_function\r\nimport argparse\r\nimport datetime\r\nimport json\r\nimport multiprocessing\r\nimport threading\r\n\r\n \r\nimport cv2\r\nimport os\r\nimport sys\r\nimport glob\r\nimport random\r\nimport time\r\nimport shutil\r\nimport dlib\r\nfrom skimage import io\r\n\r\nfrom PIL import Image\r\n\r\n\r\nimport six\r\n#import six.moves.cPickle as pickle\r\nfrom six.moves import queue\r\n\r\nimport chainer\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport math\r\nimport chainer.functions as F\r\nimport chainer.links as L\r\nfrom chainer.links import caffe\r\nfrom matplotlib.ticker import * \r\nfrom chainer import serializers\r\nimport nin\r\n\r\n\r\nparser = argparse.ArgumentParser(\r\n description='Image inspection using chainer')\r\nparser.add_argument('--moved','-i', default= 'twipic', help='Path to inspection image file')\r\nparser.add_argument('--eval','-s', default= 'evl', help='Path to inspection image file')\r\nparser.add_argument('--dist','-d', default= 'face', help='Path to inspection image file')\r\nparser.add_argument('--csp','-c', default= 'csp_face', help='Path to inspection image file')\r\nparser.add_argument('--model','-m',default='model', help='Path to model file')\r\nparser.add_argument('--mean', default='mean.npy',help='Path to the mean file (computed by compute_mean.py)')\r\nargs = parser.parse_args()\r\n\r\n\r\nimg_path = args.moved\r\ndist_path = args.dist\r\ndetect_path = args.csp\r\norigin_path = args.moved\r\norigin_2_path = args.eval\r\norigin_3_path = args.dist\r\nexist_file = [r.split('/')[-1] for r in glob.glob('csp_face/*')]\r\n\r\n\r\n\r\n\r\n\r\ndef cut_face(origin_path,exist_file):\r\n\r\n\r\n # 各画像の処理\r\n img_path = args.moved\r\n eval_path = args.eval \r\n dist_path = args.dist\r\n detect_path = args.csp\r\n detector = dlib.get_frontal_face_detector()\r\n img_path_list = glob.glob(origin_path + \"/*\")\r\n eval_path_list = glob.glob(origin_2_path + \"/*\")\r\n detect_path_list = glob.glob(detect_path + \"/*\")\r\n\r\n check_list =np.array(exist_file)\r\n\r\n\r\n \r\n for img_path in img_path_list :\r\n\r\n\r\n base_name = os.path.basename(img_path)\r\n name,ext = os.path.splitext(base_name)\r\n if (ext != '.jpg') and (ext != '.jpeg') and (ext != '.png'):\r\n print('not a picture', end='') \r\n\r\n\r\n \r\n if base_name in check_list:\r\n os.remove(img_path)\r\n print(\"exist\")\r\n delete(origin_2_path,origin_3_path,eval_path,dist_path)\r\n break\r\n else:\r\n print(img_path) \r\n \r\n\r\n img_src = cv2.imread(img_path, 1)\r\n \r\n #顔判定\r\n dets = detector(img_src)\r\n\r\n\r\n \r\n\r\n for i, d in enumerate(dets):\r\n print(\"Detection {}: Left: {} Top: {} Right: {} Bottom: {}\".format(\r\n i, d.left(), d.top(), d.right(), d.bottom()))\r\n\r\n\r\n # 顔があった場合\r\n if len(dets) > 0:\r\n i = 0\r\n for d in dets:\r\n face_core = img_src[d.top() :d.bottom(), d.left():d.right()]\r\n width = img_src.shape[:1]\r\n file_name = name + \"_\" + str(i) + ext\r\n if d.top() < 0 or d.left() < 0 or d.right() > width:\r\n shutil.move(img_path,dist_path)\r\n delete(origin_2_path,origin_3_path,eval_path,dist_path)\r\n\r\n \r\n face_resized = cv2.resize(face_core, (256,256))\r\n cv2.imwrite(file_name, face_resized)\r\n i += 1 \r\n shutil.move(file_name,dist_path)\r\n\r\n \r\n\r\n shutil.move(img_path,eval_path)\r\n read_cut(origin_3_path,origin_2_path,eval_path,detect_path,center=True, flip=False)\r\n\r\n\r\n else:\r\n shutil.move(img_path, eval_path)\r\n croping(origin_2_path,eval_path,name,ext)\r\n break\r\n \r\n\r\ndef read_cut(origin_3_path,origin_2_path,eval_path,detect_path,center=True, flip=False):\r\n\r\n mean_image = np.load(args.mean)\r\n model = nin.NIN()\r\n serializers.load_hdf5(\"csp.model\", model)\r\n model.to_cpu()\r\n\r\n eval_path_list = glob.glob(origin_2_path + \"/*\")\r\n dist_path_list = glob.glob(origin_3_path + \"/*\")\r\n cropwidth = 256 - model.insize\r\n\r\n count = 0\r\n\r\n print (\"read_image\")\r\n\r\n\r\n\r\n for dist_path in dist_path_list:\r\n print (dist_path)\r\n\r\n img_3 = np.asarray(Image.open(dist_path)).transpose(2, 0, 1)\r\n \r\n if center:\r\n top = left = cropwidth / 2\r\n\r\n else:\r\n top = random.randint(0, cropwidth - 1)\r\n left = random.randint(0, cropwidth - 1)\r\n\r\n \r\n bottom = model.insize + top\r\n right = model.insize + left\r\n img_3 = img_3[:, top:bottom, left:right].astype(np.float32)\r\n img_3-= mean_image[:, top:bottom, left:right]\r\n img_3 /= 255\r\n print (\"/read_image\")\r\n\r\n img_face = img_3\r\n \r\n x = np.ndarray(\r\n (1, 3, model.insize, model.insize), dtype=np.float32)\r\n x[0]=img_face\r\n x = chainer.Variable(np.asarray(x), volatile='on')\r\n\r\n score = predict(model,x)\r\n #score=cuda.to_cpu(score.data)\r\n\r\n categories = np.loadtxt(\"labels.txt\", str, delimiter=\"\\t\")\r\n\r\n top_k = 20\r\n prediction = zip(score.data[0].tolist(), categories)\r\n prediction.sort(cmp=lambda x, y: cmp(x[0], y[0]), reverse=True)\r\n\r\n for rank, (score, name) in enumerate(prediction[:top_k], start=1):\r\n\r\n if rank == 1:\r\n\r\n print('#%d | %s | %4.1f%%' % (rank, name, score*100))\r\n\r\n if name == 'Black':\r\n \r\n count += 1 \r\n \r\n elif name == 'Blown':\r\n \r\n count += 1\r\n \r\n elif name == 'Green':\r\n \r\n count += 1 \r\n \r\n elif name == 'Navy':\r\n \r\n count += 1 \r\n \r\n\r\n elif name == 'Blue':\r\n \r\n count += 1 \r\n \r\n\r\n elif name == 'Orange':\r\n \r\n count += 1 \r\n \r\n\r\n elif name == 'Pink':\r\n \r\n count += 1 \r\n \r\n elif name == 'Purple':\r\n \r\n count += 1 \r\n \r\n elif name == 'Red':\r\n \r\n count += 1 \r\n \r\n elif name == 'White':\r\n \r\n count += 1 \r\n \r\n\r\n elif name == 'Yellow':\r\n \r\n count += 1 \r\n \r\n \r\n else:\r\n print(count)\r\n \r\n\r\n if count >= 1 :\r\n for dist_path in dist_path_list:\r\n os.remove(dist_path)\r\n for eval_path in eval_path_list:\r\n shutil.move(eval_path,detect_path)\r\n\r\n cut_face(origin_path,exist_file)\r\n\r\n\r\n else:\r\n delete(origin_2_path,origin_3_path,eval_path,dist_path)\r\n\r\n\r\n\r\ndef croping(origin_2_path,eval_path,name,ext):\r\n\r\n i = 0\r\n\r\n x = 0\r\n y = 0\r\n\r\n eval_path_list = glob.glob(origin_2_path + \"/*\")\r\n\r\n for eval_path in eval_path_list:\r\n\r\n print (eval_path)\r\n img2 = cv2.imread(eval_path,1) \r\n\r\n width,height,channels = img2.shape[:3]\r\n\r\n h_stride = height/10\r\n w_stride = width/10\r\n\r\n #縦長の画像処理\r\n\r\n if height < 640 or width < 640:\r\n \r\n delete(origin_2_path,origin_3_path,eval_path,dist_path)\r\n\r\n else:\r\n\r\n if height >= width:\r\n\r\n\r\n while (x + w_stride) <= width and (y + h_stride) <= height:\r\n\r\n clp = img2[x:x+384, y:y+384]\r\n resized = cv2.resize(clp, (256,256))\r\n\r\n file_name1 = name + \"_\" + str(i) + ext\r\n cv2.imwrite(file_name1, resized)\r\n shutil.move(file_name1, dist_path)\r\n\r\n i += 1\r\n x += w_stride\r\n\r\n \r\n if (x + 384) > width and (y + 384) <height:\r\n\r\n\r\n clp = img2[width-384:width, y+h_stride:y+h_stride+384] \r\n resized = cv2.resize(clp, (256,256))\r\n file_name2 = name + \"_\" + str(i) + ext\r\n cv2.imwrite(file_name2, resized)\r\n shutil.move(file_name2, dist_path)\r\n\r\n i += 1\r\n x = 0\r\n y += h_stride\r\n\r\n if i < 20:\r\n\r\n delete(origin_2_path,origin_3_path,eval_path,dist_path)\r\n\r\n\r\n \r\n #横長の画像��理\r\n else:\r\n\r\n while (y + h_stride) <= height and (x + w_stride) <= width:\r\n\r\n clp = img2[x:x+384, y:y+384] \r\n resized = cv2.resize(clp, (256,256))\r\n\r\n file_name3 = name + \"_\" + str(i) + ext\r\n cv2.imwrite(file_name3, resized)\r\n shutil.move(file_name3, dist_path)\r\n\r\n i += 1\r\n y += h_stride\r\n\r\n\r\n if (y + 384) > height and (x + 384) < width:\r\n \r\n \r\n clp = img2[x:x+256, height-256:height]\r\n resized = cv2.resize(clp, (256,256))\r\n file_name4 = name + \"_\" + str(i) + ext\r\n cv2.imwrite(file_name4, resized)\r\n shutil.move(file_name4, dist_path)\r\n \r\n i += 1 \r\n y = 0\r\n x += w_stride\r\n\r\n if i < 20:\r\n\r\n delete(origin_2_path,origin_3_path,eval_path,dist_path)\r\n \r\n read_image(origin_3_path, origin_2_path,eval_path,detect_path,center=True, flip=False)\r\n\r\n\r\n\r\ndef delete(origin_2_path,origin_3_path,eval_path,dist_path):\r\n\r\n\r\n eval_path_list = glob.glob(origin_2_path + \"/*\")\r\n dist_path_list = glob.glob(origin_3_path + \"/*\")\r\n\r\n for eval_path in eval_path_list:\r\n base_name = os.path.basename(dist_path)\r\n os.remove(eval_path)\r\n\r\n for dist_path in dist_path_list:\r\n os.remove(dist_path)\r\n\r\n cut_face(origin_path,exist_file)\r\n\r\n\r\n\r\ndef read_image(origin_3_path, origin_2_path,eval_path,detect_path,center=True, flip=False):\r\n\r\n mean_image = np.load(args.mean)\r\n model = nin.NIN()\r\n serializers.load_hdf5(\"csp.model\", model)\r\n model.to_cpu()\r\n\r\n eval_path_list = glob.glob(origin_2_path + \"/*\")\r\n dist_path_list = glob.glob(origin_3_path + \"/*\")\r\n\r\n cropwidth = 256 - model.insize\r\n\r\n count = 1\r\n loop = 1\r\n\r\n for dist_path in dist_path_list:\r\n print (dist_path)\r\n\r\n img_3 = np.asarray(Image.open(dist_path)).transpose(2, 0, 1)\r\n \r\n if center:\r\n top = left = cropwidth / 2\r\n\r\n else:\r\n top = random.randint(0, cropwidth - 1)\r\n left = random.randint(0, cropwidth - 1)\r\n\r\n\r\n bottom = model.insize + top\r\n right = model.insize + left\r\n img_3 = img_3[:, top:bottom, left:right].astype(np.float32)\r\n img_3-= mean_image[:, top:bottom, left:right]\r\n img_3 /= 255\r\n \r\n img_face = img_3\r\n x = np.ndarray(\r\n (1, 3, model.insize, model.insize), dtype=np.float32)\r\n x[0]=img_face\r\n x = chainer.Variable(np.asarray(x), volatile='on')\r\n\r\n score = predict(model,x)\r\n #score=cuda.to_cpu(score.data)\r\n\r\n categories = np.loadtxt(\"labels.txt\", str, delimiter=\"\\t\")\r\n\r\n top_k = 20\r\n prediction = zip(score.data[0].tolist(), categories)\r\n prediction.sort(cmp=lambda x, y: cmp(x[0], y[0]), reverse=True)\r\n\r\n \r\n\r\n for rank, (score, name) in enumerate(prediction[:top_k], start=1): \r\n\r\n if rank == 1:\r\n\r\n print('#%d | %s | %4.1f%%' % (rank, name, score*100))\r\n\r\n if score*100 >= 40:\r\n \r\n\r\n if name == 'Black':\r\n \r\n count += 1 \r\n \r\n elif name == 'Blown':\r\n \r\n count += 1\r\n \r\n elif name == 'Green':\r\n \r\n count += 1 \r\n \r\n elif name == 'Navy':\r\n \r\n count += 1 \r\n \r\n elif name == 'Orange':\r\n \r\n count += 1 \r\n \r\n elif name == 'Pink':\r\n \r\n count += 1 \r\n \r\n elif name == 'Purple':\r\n \r\n count += 1 \r\n \r\n\r\n elif name == 'Blue':\r\n \r\n count += 1 \r\n \r\n elif name == 'Red':\r\n \r\n count += 1 \r\n \r\n elif name == 'White':\r\n \r\n count += 1 \r\n \r\n elif name == 'Yellow':\r\n \r\n count += 1 \r\n \r\n \r\n else:\r\n print(count)\r\n\r\n loop += 1\r\n\r\n if (loop/count) >= 10:\r\n\r\n delete(origin_2_path,origin_3_path,eval_path,dist_path)\r\n\r\n break\r\n\r\n if count >= 4 :\r\n\r\n for dist_path in dist_path_list:\r\n os.remove(dist_path)\r\n for eval_path in eval_path_list: \r\n shutil.move(eval_path,detect_path)\r\n break\r\n \r\n\r\n cut_face(origin_path,exist_file)\r\n \r\n\r\n\r\ndef predict(net, x):\r\n h = F.max_pooling_2d(F.relu(net.mlpconv1(x)), 3, stride=2)\r\n h = F.max_pooling_2d(F.relu(net.mlpconv2(h)), 3, stride=2)\r\n h = F.max_pooling_2d(F.relu(net.mlpconv3(h)), 3, stride=2)\r\n h = net.mlpconv4(F.dropout(h, train=net.train))\r\n h = F.reshape(F.average_pooling_2d(h, 6), (x.data.shape[0], 1000))\r\n return F.softmax(h)\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n cut_face(origin_path,exist_file)\r\n\r\n","sub_path":"croping_detect.py","file_name":"croping_detect.py","file_ext":"py","file_size_in_byte":14660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"217933282","text":"# Камень, ножницы, бумага, ящерица, Спок\n\n# Теперь Тимур и Руслан играют в игру Камень, ножницы, бумага, ящерица, Спок.\n# Помогите ребятам вновь бросить честный жребий и определить, кто будет делать следующий модуль в новом курсе.\n\n# Формат входных данных\n# На вход программе подаются две строки текста, содержащие по одному слову из перечня \"камень\", \"ножницы\", \"бумага\", \"ящерица\" или \"Спок\".\n# На первой строке записан выбор Тимура, на второй – выбор Руслана.\n\n# Формат выходных данных\n# Программа должна вывести результат жеребьёвки: кто победил - Тимур или Руслан, или они сыграли вничью.\n\n# Примечание\n# Правила игры стандартные: ножницы режут бумагу. Бумага заворачивает камень.\n# Камень давит ящерицу, а ящерица травит Спока, в то время как Спок ломает ножницы,\n# которые, в свою очередь, отрезают голову ящерице, которая ест бумагу, на которой улики против Спока.\n# Спок испаряет камень, а камень, разумеется, затупляет ножницы.\n\n\nwinners = {\n 'камень' : ['ножницы', 'ящерица'],\n 'ножницы': ['бумага' , 'ящерица'],\n 'бумага' : ['камень' , 'Спок'],\n 'ящерица': ['бумага' , 'Спок'],\n 'Спок' : ['ножницы', 'камень'], \n}\n\n\ntimur = input()\nruslan = input()\n\nif timur == ruslan:\n print('ничья')\nelse:\n print('Тимур' if ruslan in winners[timur] else 'Руслан')\n","sub_path":"BEEGEEK. Python generation. Advanced/2.2/s06_SSPLS.py","file_name":"s06_SSPLS.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"636668494","text":"import re\n\n# 保留字\nreserveWord = [\"if\", \"else\", \"for\", \"int\", \"while\", \"int\",\"write\", \"read\"];\n\n# 先区分单双分解符来确定是否需要多取一个字符\ndelimiter = ['=','+','-','*','/','(',')',';','{','}',':',',',';',';','<','>','!']\n\nsingleDelimiter = ['(',')',';','{','}']\n\ndoubleDelimiter = ['>=','<=','!=','==']\n\n# 然后在和运算符对比,区分运算符和分解符\noperator = ['+','-','*','/','=','<','>','>=','<=','!=','==']\n\n\n\n# 过滤掉单行注释和换行符\ndef filterOrigin(str):\n filterstr = re.sub(r'\\/\\*[\\s\\S]*\\*\\/|\\/\\/.*','',str)\n filterstr = filterstr.replace('\\n','')\n filterstr = filterstr.replace('\\t','')\n return filterstr\n\n# 保存总错误\n\n\n# 处理多行注释和不合法的注释 \ndef cleanComment(strLines):\n global errorSum\n errorSum = 0\n for str in strLines:\n # 记录第一个/*出现在第几行的第几列\n startIndexCol = str.find('/*')\n if startIndexCol>=0:\n startIndexRow = strLines.index(str)\n strLines[startIndexRow] = strLines[startIndexRow][0:startIndexCol]\n print(strLines[startIndexRow])\n \n # '/*' 记录成功后往后匹配 '*/',然后记录出现行列\n for index in range(startIndexRow,len(strLines)):\n endIndexCol = strLines[index].find('*/')\n if endIndexCol>=0:\n # */是往后取值,拿到的是*的位置,所以需要+2\n endIndexCol+=2\n endIndexRow = index\n endRowLen = len(strLines[endIndexRow])\n strLines[endIndexRow] = strLines[endIndexRow][endIndexCol:endRowLen+1]\n print(strLines[endIndexRow])\n # 跨越行的/* */之间的内容置空,不能删除,控制总行数不变,不然影响遍历序列\n for i in range(startIndexRow+1,endIndexRow):\n strLines[i] = ''\n # 寻找到'*/'执行相关操作后需要打断循环,从下一行字符开始遍历\n break\n # 当最后一行还未找到'*/'则为不合法的注释\n elif index==len(strLines)-1:\n endIndexRow = len(strLines)\n # 置空未闭合的'/*'后面的一切行,包括最后一行 \n # startIndexRow+1是因为,本行要被截取有效的部分\n for i in range(startIndexRow+1,endIndexRow):\n strLines[i] = ''\n errorSum+=1\n print(\"在第{}行发生词法错误,错误信息:注释不合法\".format(startIndexRow+1))\n \n \n \n \n \n# 全局变量,保存token\ntokenList = []\n\n\n\n# 读取文件为一个字符串\nwith open('origin.txt', 'r') as fileReader:\n strOrigin = fileReader.readlines()\n print(type(strOrigin))\n strLines = list(map(filterOrigin,strOrigin))\n print(strLines)\n\ncleanComment(strLines)\n\nindex = 0\n\n# 按行读取\nfor str in strLines:\n index = index + 1\n # 字符串转为列表\n strList = list(str)\n while len(strList):\n char = strList.pop(0)\n \n # 分析保留字与标识符\n if char.isalpha():\n token = {\n \"type\":\"标识符\", \n \"name\":\"\"\n }\n token['name'] += char\n \n # 这里没有判断一行只有一个字母或者数字的情况,如果有则可以直接跳过该行,提示语法错误 \n # 循环读取下一个字符,当下一个字符非字母数字终止或者,栈空终止读入\n if len(strList):\n char = strList.pop(0)\n \n while char.isalnum():\n token['name'] += char\n if len(strList):\n char = strList.pop(0)\n else:\n break\n \n # while 循环被不是字母数字的打断,就会多出栈一个非数字和字母的,这里需要重新入栈\n if not char.isalnum():\n strList = [char]+strList\n\n # 判断字符类型 \n if token['name'] in reserveWord:\n token['type'] = '保留字'\n else:\n token['type'] = '标识符'\n # 保存到全局变量里\n token['line'] = index\n tokenList.append(token)\n \n # 分析无符号整数 算法与上一步类似 \n elif char.isdigit():\n token = {\n \"type\":\"\",\n \"name\":\"\"\n }\n token['name'] += char\n char = strList.pop(0)\n while char.isdigit():\n token['name'] += char\n if len(strList):\n char = strList.pop(0)\n else:\n break\n \n if not char.isdigit():\n strList = [char]+strList\n \n token['type'] = '无符号整数'\n token['line'] = index\n tokenList.append(token)\n \n\n \n elif char in singleDelimiter:\n token = {\n \"type\":'分界符',\n \"name\":char\n }\n token['line'] = index\n tokenList.append(token)\n # 判断单分解符和多分界符\n elif (char in operator) or char == '!':\n token = {\n \"type\":'',\n \"name\":''\n }\n if len(strList):\n # 暂时取值,并未出栈\n char2 = strList[0]\n doubleChar = char+char2\n if doubleChar in operator:\n # 双分界符多出栈一个\n char = strList.pop(0)\n # 进一步分类,判断运算符\n isOperator = doubleChar in operator\n # python三目运算 有点不一样\n token['type'] = '运算符'\n token['name'] = doubleChar\n elif char in operator:\n token['type'] = '运算符'\n token['name'] = char\n\n else:\n errorSum+=1\n print(\"在第{}行发生词法错误,错误信息:{}不合法\".format(index,char))\n continue\n elif char in operator:\n token['type'] = '运算符'\n token['name'] = char\n else:\n errorSum+=1\n print(\"在第{}行发生词法错误,错误信息:{}不合法\".format(index,char))\n continue\n token['line'] = index \n tokenList.append(token)\n \n # 判断错误代码\n elif char!=' ':\n errorSum+=1\n print(\"在第{}行发生词法错误,错误信息:{}未知符号\".format(index,char))\n\nwith open('lex.txt', 'w',encoding='utf-8') as writer:\n for token in tokenList:\n if token['type'] == '标识符':\n writer.writelines('{} {} {}\\n'.format(token['line'],'ID',token['name']))\n elif token['type'] == '保留字' or token['type'] == '运算符':\n writer.writelines('{} {} {}\\n'.format(token['line'],token['name'],token['name']))\n elif token['type'] == '无符号整数':\n writer.writelines('{} {} {}\\n'.format(token['line'],'NUM',token['name']))\n elif token['type'] == '分界符':\n writer.writelines('{} {} {}\\n'.format(token['line'],token['name'],token['name']))\n \nprint(\"总共发生了{}次词法错误\".format(errorSum)) \nprint(tokenList)\n \n","sub_path":"Parsing/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":7798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"489423425","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nJonathan McDonagh - 20074520\r\n\"\"\"\r\n\r\n\r\n#1) import in the necessary libraries to run cluster analysis and graph the results\r\n#imports \r\nimport pandas as pd\r\nimport numpy\r\nimport matplotlib.pylab as plt\r\nfrom pandas import Series, DataFrame\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn import preprocessing\r\nfrom sklearn.cluster import KMeans\r\n\r\n\r\n#2) load the data file gapmminder.csv into your data frame\r\n#load dataset from the csv file in the dataframe called nesarc_data\r\ngapminder_data = pd.read_csv('gapminder.csv', low_memory=False)\r\n\r\n\r\n#set PANDAS to show all columns in Data frame\r\npd.set_option('display.max_columns', None)\r\n\r\n#set PANDAS to show all rows in Data frame\r\npd.set_option('display.max_rows', None)\r\n\r\n#upper-case all DataFrame column names\r\ngapminder_data.columns = map(str.upper, gapminder_data.columns)\r\n\r\n\r\n#3) check for empty values and replace with NaN, convert each column to a number\r\n#replace blanks with Nan\r\ngapminder_data['INCOMEPERPERSON'] = gapminder_data['INCOMEPERPERSON'].replace(\" \", numpy.NaN)\r\ngapminder_data['FEMALEEMPLOYRATE'] = gapminder_data['FEMALEEMPLOYRATE'].replace(\" \", numpy.NaN)\r\ngapminder_data['INTERNETUSERATE'] = gapminder_data['INTERNETUSERATE'].replace(\" \", numpy.NaN)\r\ngapminder_data['LIFEEXPECTANCY'] = gapminder_data['LIFEEXPECTANCY'].replace(\" \", numpy.NaN)\r\ngapminder_data['ALCCONSUMPTION'] = gapminder_data['ALCCONSUMPTION'].replace(\" \", numpy.NaN)\r\ngapminder_data['URBANRATE'] = gapminder_data['URBANRATE'].replace(\" \", numpy.NaN)\r\n\r\n#converting strings to numeric data for better output\r\ngapminder_data['INCOMEPERPERSON'] = pd.to_numeric(gapminder_data['INCOMEPERPERSON'],errors='ignore')\r\ngapminder_data['FEMALEEMPLOYRATE'] = pd.to_numeric(gapminder_data['FEMALEEMPLOYRATE'],errors='ignore')\r\ngapminder_data['INTERNETUSERATE'] = pd.to_numeric(gapminder_data['INTERNETUSERATE'],errors='ignore')\r\ngapminder_data['LIFEEXPECTANCY'] = pd.to_numeric(gapminder_data['LIFEEXPECTANCY'],errors='ignore')\r\ngapminder_data['ALCCONSUMPTION'] = pd.to_numeric(gapminder_data['ALCCONSUMPTION'],errors='ignore')\r\ngapminder_data['URBANRATE'] = pd.to_numeric(gapminder_data['URBANRATE'],errors='ignore')\r\n\r\ndata_clean = gapminder_data.dropna()\r\n\r\n\r\n#4) subset the data\r\n#subset clustering variables\r\ncluster=data_clean[['INCOMEPERPERSON','FEMALEEMPLOYRATE','INTERNETUSERATE','LIFEEXPECTANCY','ALCCONSUMPTION',\r\n'URBANRATE']]\r\ncluster.describe()\r\n\r\n\r\n#5) standardize all of the variables\r\n#standardize clustering variables to have mean=0 and sd=1\r\nclustervar=cluster.copy()\r\nclustervar['INCOMEPERPERSON']=preprocessing.scale(clustervar['INCOMEPERPERSON'].astype('float64'))\r\nclustervar['FEMALEEMPLOYRATE']=preprocessing.scale(clustervar['FEMALEEMPLOYRATE'].astype('float64'))\r\nclustervar['INTERNETUSERATE']=preprocessing.scale(clustervar['INTERNETUSERATE'].astype('float64'))\r\nclustervar['LIFEEXPECTANCY']=preprocessing.scale(clustervar['LIFEEXPECTANCY'].astype('float64'))\r\nclustervar['ALCCONSUMPTION']=preprocessing.scale(clustervar['ALCCONSUMPTION'].astype('float64'))\r\nclustervar['URBANRATE']=preprocessing.scale(clustervar['URBANRATE'].astype('float64'))\r\n\r\n\r\n#6) split the data into train and test sets\r\nclus_train, clus_test = train_test_split(clustervar, test_size=.3, random_state=123)\r\n\r\n\r\n#7) cluster analysis using K-means for 1-9 clusters\r\n# k-means cluster analysis for 1-9 clusters\r\nfrom scipy.spatial.distance import cdist\r\nclusters=range(1,10)\r\nmeandist=[]\r\n\r\nfor k in clusters:\r\n model=KMeans(n_clusters=k)\r\n model.fit(clus_train)\r\n clusassign=model.predict(clus_train)\r\n meandist.append(sum(numpy.min(cdist(clus_train, model.cluster_centers_, 'euclidean'), axis=1))\r\n / clus_train.shape[0])\r\n \r\n cdist(clus_train, model.cluster_centers_, 'euclidean')\r\n \r\n \r\n#8) plot the curve and determine how many is the fewest clusters that provides a low average distance\r\nplt.plot(clusters, meandist)\r\nplt.xlabel('Number of clusters')\r\nplt.ylabel('Average distance')\r\nplt.title('Selecting k with the Elbow Method')\r\n'''\r\nHere in the plot curve above we can see a couple of bends at the line at \r\ntwo clusters and at four clusters. What we can see here in the plot \r\nabove is that the elbow shows where the average distance value might \r\nbe leveling off.\r\n'''\r\n\r\n\r\n#9) cluster solution for the number of clusters you consider appropriate based on the elbow curve\r\nmodel3=KMeans(n_clusters=3)\r\nmodel3.fit(clus_train)\r\nclusassign=model3.predict(clus_train)\r\n\r\nfrom sklearn.decomposition import PCA\r\npca_2 = PCA(2)\r\nplot_columns = pca_2.fit_transform(clus_train)\r\nplt.scatter(x=plot_columns[:,0], y=plot_columns[:,1], c=model3.labels_,)\r\nplt.xlabel('Canonical variable 1')\r\nplt.ylabel('Canonical variable 2')\r\nplt.title('Scatterplot of Canonical Variables for 3 Clusters')\r\nplt.show()\r\n'''\r\nIn this scatter plot above we can see that the three clusters are spaced \r\napart showing us they're not densely packed, meaning that the observations \r\nwithin the cluster are pretty low correlated with each other.\r\nWe can also see that they appear to not have much overlap meaning that there\r\nis very good separation between these clusters.\r\nThey also have a high cluster variance. \r\n'''\r\n","sub_path":"CA2/lab09_ca.py","file_name":"lab09_ca.py","file_ext":"py","file_size_in_byte":5210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"276733313","text":"from json import dumps\n\nkomputer = {\n 'kolor' : 'czarny',\n 'procesor' : 'intel',\n 'marka' : 'acer',\n 'karta graficzna' : 'geforce',\n 'cena' : 3000 \n}\n\nnew_text = dumps(komputer)\n\nwith open('komputer.json','w') as file:\n file.write(new_text)","sub_path":"08-DataStructures/08.20..py","file_name":"08.20..py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"585366135","text":"#!/usr/bin/env python\n\"\"\"NDG Security test harness for authorisation middleware used to secure an\napplication\n\nNERC DataGrid Project\n\"\"\"\n__author__ = \"P J Kershaw\"\n__date__ = \"20/11/08\"\n__copyright__ = \"(C) 2009 Science and Technology Facilities Council\"\n__license__ = \"BSD - See top-level directory for LICENSE file\"\n__contact__ = \"Philip.Kershaw@stfc.ac.uk\"\n__revision__ = \"$Id: securedapp.py 7861 2011-01-31 13:48:11Z pjkersha $\"\nimport optparse \nfrom os import path\nfrom ndg.security.server.utils.paste_utils import PasteDeployAppServer\n\nINI_FILENAME = 'securedapp.ini'\n \n# To start run \n# $ paster serve services.ini \n#\n# or run this file as a script. For options:\n# $ ./securedapp.py -h\nif __name__ == '__main__': \n cfgFilePath = path.join(path.dirname(path.abspath(__file__)), INI_FILENAME)\n \n parser = optparse.OptionParser()\n parser.add_option(\"-p\",\n \"--port\",\n dest=\"port\",\n default=7080,\n type='int',\n help=\"port number to run under\")\n\n parser.add_option(\"-c\",\n \"--conf\",\n dest=\"configFilePath\",\n default=cfgFilePath,\n help=\"Configuration file path\")\n \n opt = parser.parse_args()[0]\n\n server = PasteDeployAppServer(cfgFilePath=opt.configFilePath, \n port=opt.port) \n server.start()","sub_path":"ndg/security/server/paster_templates/securedapp/securedapp.py","file_name":"securedapp.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"203952209","text":"\nclass Node(object):\n def __init__(self, val, children):\n self.val = val\n self.children = children\n\nclass Solution(object):\n def levelOrder(self, root):\n \"\"\"\n :type root: Node\n :rtype: List[List[int]]\n \"\"\"\n result = []\n\n def bfs(node, level):\n if node:\n if len(result) == level:\n result.append([])\n result[level].append(node.val)\n if node.children:\n for oneK in node.children:\n bfs(oneK, level + 1)\n\n bfs(root, 0)\n return result\n\n\ns = Solution()\na1 = Node(1, None)\na2 = Node(2, None)\na3 = Node(3, None)\na4 = Node(4, None)\na5 = Node(5, None)\na6 = Node(6, None)\na1.children = [a2, a3, a4]\na3.children = [a5, a6]\nprint(s.levelOrder(a1))","sub_path":"python/429_levelOrder.py","file_name":"429_levelOrder.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"581292542","text":"# based on https://github.com/adafruit/Adafruit_Python_DHT/blob/master/examples/AdafruitDHT.py\n\nimport Adafruit_DHT\nimport time\nfrom datetime import datetime\nimport csv\n\ndef dataUpdate(file, data):\n f = open(file, \"a\")\n writer = csv.writer(f)\n writer.writerow(data)\n f.close()\n\n# Sensor\nsensor = Adafruit_DHT.DHT11\n\n# GPIO4.\npin = 4\n\ninit_text = [\"Time\", \"Temperature (C)\", \"Humidity (%)\"]\nformat_text = \"| {0:<10} | {1:<15} | {2:<13} |\"\nprint(format_text.format(*init_text))\n\nfile = \"DHT_results.csv\"\n\ndataUpdate(file, init_text)\nwhile True:\n try:\n humidity, temperature = Adafruit_DHT.read(sensor, pin)\n\n if humidity is not None and temperature is not None:\n date = datetime.now().strftime(\"%H:%M:%S\")\n res = [date, temperature, humidity]\n print(format_text.format(*res))\n\n dataUpdate(file, res)\n time.sleep(1)\n except KeyboardInterrupt:\n break\n\nexit()\n","sub_path":"humidity_sensor/humidity.py","file_name":"humidity.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"175993458","text":"from bs4 import BeautifulSoup\r\nimport requests\r\nimport pandas as pd\r\n\r\nres = requests.get('https://news.naver.com/')\r\nsoup = BeautifulSoup(res.text,'html.parser')\r\n\r\ntitle = soup.select_one('#container > div.main_aside > div > div.section.section_wide > h4 > a')\r\n\r\n정치 = []\r\n경제 = []\r\n사회 = []\r\n생활문화 = []\r\n세계 = []\r\n과학 = []\r\nfor li in soup.select('#ranking_100 > ul > li'):\r\n 정치.append(li.a.text)\r\n\r\n\r\nfor li in soup.select('#ranking_101 > ul > li'):\r\n 경제.append(li.a.text)\r\n\r\n\r\nfor li in soup.select('#ranking_102 > ul > li'):\r\n 사회.append(li.a.text)\r\n\r\n\r\nfor li in soup.select('#ranking_103 > ul > li'):\r\n 생활문화.append(li.a.text)\r\n\r\n\r\nfor li in soup.select('#ranking_104 > ul > li'):\r\n 세계.append(li.a.text)\r\n\r\n\r\nfor li in soup.select('#ranking_105 > ul > li'):\r\n 과학.append(li.a.text)\r\n\r\ndf = pd.DataFrame(정치,columns=['정치'])\r\ndf.to_csv('naver_newsList.xlsx',index=False,encoding='cp949')\r\ndf2 = pd.DataFrame(경제,columns=['경제'])\r\ndf2.to_csv('naver_newsList.xlsx',index=False,mode='a',encoding='cp949')\r\ndf2 = pd.DataFrame(사회,columns=['사회'])\r\ndf2.to_csv('naver_newsList.xlsx',index=False,mode='a',encoding='cp949')\r\ndf2 = pd.DataFrame(생활문화,columns=['생활/문화'])\r\ndf2.to_csv('naver_newsList.xlsx',index=False,mode='a',encoding='cp949')\r\ndf2 = pd.DataFrame(세계,columns=['세계'])\r\ndf2.to_csv('naver_newsList.xlsx',index=False,mode='a',encoding='cp949')\r\ndf2 = pd.DataFrame(과학,columns=['IT/과학'])\r\ndf2.to_csv('naver_newsList.xlsx',index=False,mode='a',encoding='cp949')\r\n\r\n\r\n\r\n","sub_path":"Data/NewsData_Naver.py","file_name":"NewsData_Naver.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"652008345","text":"import discord\nimport asyncio\nfrom discord.ext import commands\n\nclass General:\n # General purpose commands, these are meant to be further organised in other modules, if needed\n #__slots__: ('bot', 'current_game', 'current_status')\n bot = None\n current_game = None\n current_status = None\n\n def __init__(self, bot):\n self.bot = bot\n self.current_game = ''\n self.current_status = ''\n \n #Command to change the status\n @commands.command(name=\"status\",pass_context=True)\n @commands.is_owner()\n async def change_status(self, ctx, arg=\"noarg\"):\n options = {\"on\": discord.Status.online,\n \"online\": discord.Status.online,\n \"off\": discord.Status.invisible,\n \"offline\": discord.Status.invisible,\n \"invisible\": discord.Status.invisible,\n \"dnd\": discord.Status.dnd,\n \"away\": discord.Status.idle,\n \"idle\": discord.Status.idle}\n arg = arg.strip()\n if arg in options:\n bot = self.bot # Why doesn't this work directly with self.bot.change_presence\n self.current_status = options[arg]\n await bot.change_presence(status=self.current_status,activity=discord.Game(self.current_game))\n await ctx.send(\"Status changed\")\n else:\n raise commands.BadArgument\n\n @change_status.error\n async def change_status_error(self, ctx, error):\n if isinstance(error, commands.NotOwner):\n msg = \"You're not the bot owner\"\n await ctx.send(msg)\n if isinstance(error, commands.BadArgument):\n msg = \"That status is invalid\"\n await ctx.send(msg)\n\n #Command to change currently playing game\n @commands.command(name=\"activity\",pass_context=True)\n @commands.is_owner()\n async def change_activity(self, ctx, *, arg=\"noarg\"):\n arg = arg.strip()\n if arg != \"noarg\":\n self.current_game = arg\n bot = self.bot\n await bot.change_presence(status=self.current_status,activity=discord.Game(self.current_game))\n await ctx.send(\"Activity changed\")\n else:\n self.current_game = ''\n bot = self.bot\n await bot.change_presence(status=self.current_status,activity=None)\n await ctx.send(\"Activity changed\")\n\n @change_activity.error\n async def change_activity_error(self, ctx, error):\n if isinstance(error, commands.NotOwner):\n msg = \"You're not the bot owner\"\n await ctx.send(msg)\n if isinstance(error, commands.BadArgument):\n msg = \"That activity is invalid\"\n await ctx.send(msg)\n\n @commands.command(name=\"members\",pass_context=True)\n @commands.has_permissions(manage_guild=True)\n async def members(self, ctx):\n server= ctx.guild\n x = server.members\n F = open('members.txt', 'wb')\n for member in x:\n linha = member.name + '\\r\\n'\n F.write(linha.encode(\"utf-8\"))\n F.close()\n msg = 'Members\\' list is ready'\n await ctx.send(msg, file=discord.File('members.txt', 'members.txt'))\n\n @members.error\n async def members_error(self, ctx, error):\n if isinstance(error, commands.MissingPermissions):\n msg = \"You're not an admin\"\n await ctx.send(msg)\n\ndef setup(bot):\n bot.add_cog(General(bot))","sub_path":"modules/general.py","file_name":"general.py","file_ext":"py","file_size_in_byte":3450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"419281485","text":"import ministack\nimport time\n\npos = ministack.getPlayerPosition(\"xiaozhan\")\nx, y, z = pos.x, pos.y, pos.z\n\nfor x in range(100):\n ministack.setPlayerPosition(\"xiaozhan\", x, 0, 0)\n ministack.say(x)\n time.sleep(1)\n","sub_path":"矿石探测器/for.py","file_name":"for.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"389789049","text":"import numpy as np\nimport pandas as pd\nfrom scipy.spatial import distance\nimport itertools\n\nuse_tfs = True\n\nf = open('data/muscleTFStuff/muscle_tfs.txt', 'r')\ntf = f.read().splitlines()\nf.close()\n\nmuscles = ['bwm_anterior', 'bwm_far_posterior', 'bwm_head_row_1', 'bwm_head_row_2', 'bwm_posterior']\nbins = ['270_330', '330_390', '390_450', '450_510', '510_580', '580_650', 'gt_650']\n\ngenes = pd.read_csv('data/geneAndTimeData/bwm_csv/bwm_anterior_time_bins.csv', index_col=0, skiprows=lambda x:x not in [0]).columns.tolist()\n\nidx = []\n\nfor i, v in enumerate(genes):\n if v in tf:\n idx.append(i+1)\n\nidx.insert(0,0)\n\nif not use_tfs:\n idx = list(range(len(genes)))\n\ndf_dict = {}\nfor muscle in muscles:\n df_dict[muscle] = pd.read_csv('data/geneAndTimeData/bwm_csv/' + muscle + '_time_bins.csv', index_col=0, usecols=idx)\n df_dict[muscle] = df_dict[muscle].drop('mean')\n\n\nfor bin in bins:\n result = pd.DataFrame(index = muscles, columns = muscles)\n\n for a, b in itertools.combinations(muscles, 2):\n dist = distance.jensenshannon(df_dict[a].loc[bin], df_dict[b].loc[bin])\n result.at[a,b] = dist\n\n print(result)\n outfile = 'js_distance/across_cells/' + bin + '_distance.csv' if not use_tfs else 'js_distance/across_cells/tf_' + bin + '_distance.csv'\n result.to_csv(outfile)","sub_path":"js_distance/distance_across_cells.py","file_name":"distance_across_cells.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"353292193","text":"from tools.requests_tool import get_html\nfrom spider import download_novel_xiaoshuodaquan,download_novel_duquanben,download_novel_xinbiquge,download_novel_aszw6,download_novel_biquwu,download_novel_booktext\n\n\n\ndef test_downloadNovel(novel,url,capterUrl):\n html=get_html(url,encoding=novel.encoding)\n author=novel.get_author(html)\n print(\"作者\",author)\n novelName = novel.get_novel_name(html)\n print(\"小说名\",novelName)\n coverurl = novel.get_cover_url(html)\n print(\"封面链接\",coverurl)\n isEnd =novel.get_isEnd(html)\n print(\"���结标志\",isEnd)\n intro = novel.get_intro(html)\n print(\"简介:\",intro)\n capName,capters=novel.get_capters(html)\n print(\"章节名字典\",capName)\n print(\"章节序号字典\",capters)\n html=get_html(capterUrl,encoding=novel.encoding)\n capterContent=novel.get_one_capter(html)\n for line in capterContent:\n print(line)\ndef test_save_novel(novel):\n novel.start_download()\n\n\ndef test_shushu8():\n # url = \"https://www.xiaoshuodaquan.com/shenguizhaolai/\"\n # capterUrl = \"https://www.xiaoshuodaquan.com/shenguizhaolai/1\"\n # novel = download_novel_shushu8.DownloadNoveShushu8(url)\n # test_downloadNovel(novel, url, capterUrl)\n # test_save_novel(novel)\n url=\"https://www.xiaoshuodaquan.com/zhenwukuangshen/\"\n # url=\"https://www.xiaoshuodaquan.com/emodezhaohuanshi/\"\n novel=download_novel_xiaoshuodaquan.DownloadNoveShushu8(url)\n test_save_novel(novel)\ndef test_quanben():\n url = \"https://www.duquanben.com/xiaoshuo/9/9456/\"\n capterUrl = \"https://www.duquanben.com/xiaoshuo/9/9456/13410890.html\"\n novel = download_novel_duquanben.DownloadNovelDuQuanBen(url)\n # test_downloadNovel(novel, url, capterUrl)\n test_save_novel(novel)\n\ndef test_xinbiquge6():\n url = \"https://www.xsbiquge.com/77_77067/\"\n url = \"http://www.biquge6.com/89_89122/\"\n url = \"https://www.xsbiquge.com/89_89107/\"\n url = \"https://www.xsbiquge.com/66_66175/\"\n capterUrl = \"https://www.xsbiquge.com/77_77067/248583.html\"\n novel = download_novel_xinbiquge.DownloadNovelXinBiQuGe6(url)\n # test_downloadNovel(novel, url, capterUrl)\n test_save_novel(novel)\ndef test_aszw6():\n url = \"https://www.aszw6.com/book/57/57219/\"\n capterUrl = \"https://www.aszw6.com/book/57/57219/12231980.html\"\n novel = download_novel_aszw6.DownloadNovelASZW6(url)\n test_downloadNovel(novel, url, capterUrl)\n # test_save_novel(novel)\n\ndef test_biquwu():\n url = \"https://www.biquwu.cc/biquge/16_16462/\"\n # url = \"https://www.81zw.org/book/38563/\"\n capterUrl = \"https://www.biquwu.cc/biquge/16_16462/c4781947.html\"\n novel = download_novel_biquwu.DownloadNovelBiQuWu(url)\n # test_downloadNovel(novel, url, capterUrl)\n test_save_novel(novel)\n\n\ndef test_textbook():\n url = \"https://www.booktxt.net/5_5512/\"\n url = \"https://www.booktxt.net/5_5871/\"\n # capterUrl = \"https://www.booktxt.net/5_5512/2990481.html\"\n novel = download_novel_booktext.DownloadNovelBooktext(url)\n # test_downloadNovel(novel, url, capterUrl)\n test_save_novel(novel)\n\n\n\n\n\nif __name__ == '__main__':\n\n # test_xinbiquge6()\n test_textbook()","sub_path":"test/spider/test_novels.py","file_name":"test_novels.py","file_ext":"py","file_size_in_byte":3149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"477990549","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport numpy as np\n\nfrom scipy.special import logsumexp\nfrom sklearn.svm import SVC\n\n\nclass pbrff(object):\n def __init__(self, beta=1, K=100, gamma=1, pctLandmarks=None,\n n_landmarks=None, C=1, randomState=None):\n self.pctLandmarks = pctLandmarks\n self.n_landmarks = n_landmarks\n self.C = C\n self.randomState = randomState\n\n self.K = K\n self.beta = beta\n self.gamma = gamma\n\n def select_landmarks(self, X, y):\n if self.n_landmarks is None:\n self.n_landmarks = int(len(y)*self.pctLandmarks)\n idxsLandmaks = self.randomState.choice(len(X), self.n_landmarks,\n replace=True)\n self.landmarks_X = X[idxsLandmaks, :]\n self.landmarks_y = y[idxsLandmaks]\n\n def transform_cos(self, omega, delta):\n return np.cos(np.dot(delta, omega))\n\n def fit(self, X, y):\n self.select_landmarks(X, y)\n\n self.n, self.d = X.shape\n\n # Compute loss for a given number of Fourier features per landmarks.\n # Randomly sampling Omega from the Fourier distribution\n self.Omega = self.randomState.randn(self.n_landmarks,\n self.d, self.K) * (\n 2*self.gamma)**0.5\n loss = []\n # Computing loss for each landmarks\n for i in range(self.n_landmarks):\n transformed_X = self.transform_cos(self.Omega[i],\n X - self.landmarks_X[i])\n lambda_y = -np.ones(self.n)\n lambda_y[y == self.landmarks_y[i]] = 1\n\n landmark_loss = lambda_y @ transformed_X\n\n # For the random method, case where X_i == landmark needs to be\n # substracted\n landmark_loss = (landmark_loss - 1) / (self.n - 1)\n\n landmark_loss = (1 - landmark_loss) / 2\n loss.append(landmark_loss)\n loss = np.array(loss)\n\n # Compute pseudo-posterior Q distribution over the Fourier features.\n # Computing t\n to = self.beta * self.n**0.5\n # Computing Q\n self.Q = -to*loss - logsumexp(-to*loss, axis=1).reshape(-1, 1)\n self.Q = np.exp(self.Q)\n\n self.clf = SVC(kernel=\"linear\", C=self.C, max_iter=1e4,\n random_state=np.random.RandomState(1))\n self.clf.fit(self.transform(X), y)\n\n def transform(self, X):\n mapped_X = []\n for i in range(self.n_landmarks):\n transformed_X = self.transform_cos(self.Omega[i],\n X - self.landmarks_X[i])\n mapped_X.append(np.sum(transformed_X * self.Q[i], 1))\n return np.array(mapped_X).T\n\n def predict(self, X):\n return self.clf.predict(self.transform(X))\n","sub_path":"experiment-latex-array-results/pbrff.py","file_name":"pbrff.py","file_ext":"py","file_size_in_byte":2892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"370458719","text":"#! /usr/bin/env python3\n# coding: UTF-8\n\n\"\"\" Food views :\nindex, result, detail, favorites, mentions_legal \"\"\"\n\n\n# imports\nfrom django.shortcuts import render\nfrom django.contrib.auth import logout, get_user_model\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nfrom requests.exceptions import ConnectionError\nfrom food.classes import database\nfrom food.models import Food\nfrom account.forms import Account\n\n\ndef index(request):\n \"\"\" index view :\n insert data in the database if database is empty,\n logout the user and display the index page (home) \"\"\"\n\n # USER'S DISCONNECTION AND DISPLAY THE INDEX PAGE\n # if the user clicks on the logout logo\n if request.method == 'POST':\n disconnection = request.POST.get('disconnection', 'False')\n if request.user.is_authenticated and disconnection == 'True':\n logout(request)\n context = {'message': \"Vous êtes déconnecté.\"}\n return render(request, 'food/index.html', context)\n\n # USER'S DEACTIVATION AND DISPLAY THE INDEX PAGE\n # if the user clicks on the button \"supprimer mon compte\"\n delete_account = request.POST.get('delete_account', 'False')\n if delete_account == 'True':\n user = request.user\n logout(request)\n user.is_active = False\n user.save()\n context = {'message': \"Votre compte a bien été supprimé.\"}\n return render(request, 'food/index.html', context)\n\n # INSERT DATA IF THE DATABASE IS EMPTY\n # DISPLAY THE INDEX PAGE\n try:\n bdd = database.Database()\n bdd.insert_data()\n return render(request, 'food/index.html')\n except ConnectionError:\n context = {'message': \"Problème de connexion\"}\n return render(request, 'food/index.html', context)\n\n\ndef result(request):\n \"\"\" result view :\n display the food data in the result page,\n if there is no result\n display an error message in the index page,\n add id of the favorites food in the context because\n if the user has already registered the food,\n we will not display the floppy logo,\n save the food selected by the user \"\"\"\n\n if request.method == 'POST':\n # SAVE FOOD SELECTED BY THE USER\n # if user is authenticated\n save_id_food = request.POST.get('id', None)\n if save_id_food and request.user.is_authenticated:\n id_user = request.user.id\n food = Food.objects.get(id=save_id_food)\n user = get_user_model()\n user = user.objects.get(id=id_user)\n food.favorites.add(user)\n\n if save_id_food is None:\n # get the name food searched\n food = request.POST.get('search')\n request.session['food'] = food\n\n # DISPLAY THE INDEX PAGE WITH AN ERROR MESSAGE\n # if there is no food searched\n if not food:\n context = {'message': \"Vous n'avez rien demandé\"}\n return render(request, 'food/index.html', context)\n\n context = {'search': food}\n\n # get the categorie of the food searched\n re_food = '^.*'+food+'.*$'\n re_food = re_food.replace(' ', '.*')\n re_food = r'{}'.format(re_food)\n name = Food.objects.filter(name__iregex=re_food)[:1]\n categorie_food = name.values_list('categorie')\n\n # DISPLAY THE RESULT PAGE\n # DISPLAY THE RESULT ON PAGE 1\n # if there is food searched\n # and if the categorie exists\n if categorie_food:\n\n # get data of all foods of the same categorie\n # ordered by nutrition grade\n categorie_food = categorie_food[0]\n data = Food.objects.filter(categorie=categorie_food)\n foods_data = data.order_by('nutrition_grade')\n\n # use paginator :\n # display of page 1 of result\n paginator = Paginator(foods_data, 18, orphans=4)\n page = request.GET.get('page')\n try:\n foods_data = paginator.get_page(page)\n except PageNotAnInteger:\n foods_data = paginator.page(1)\n except EmptyPage:\n foods_data = paginator.page(paginator.num_pages)\n context['foods_data'] = foods_data\n\n # DOES NOT DISPLAY THE FLOPPY LOGO\n # if the user has already registered the food\n if request.user.is_authenticated:\n # get the favorites foods id\n user = get_user_model()\n favorites_id = []\n id_user = request.user.id\n for elt in user(id=id_user).food_set.values_list('id'):\n favorites_id.append(elt[0])\n context['favorites_id'] = favorites_id\n else:\n context['favorites_id'] = []\n\n return render(request, 'food/result.html', context)\n\n # DISPLAY THE INDEX PAGE WITH AN ERROR MESSAGE\n # if there is food searched\n # but that the categorie don't exists\n else:\n context = {\"message\": \"Pas de résultat pour l'aliment {}.\".format(food)}\n return render(request, 'food/index.html', context)\n\n # DISPLAY THE RESULT PAGE\n # DISPLAY THE RESULT ON SEVERAL PAGES : page > 1\n if 'food' in request.session:\n food = request.session['food']\n context = {'search': food}\n\n # get data of all foods of the same categorie\n list_food = food.split()\n for word in list_food:\n name = Food.objects.filter(name__icontains=word)[:1]\n categorie_food = name.values_list('categorie')\n categorie_food = categorie_food[0]\n data = Food.objects.filter(categorie=categorie_food)\n foods_data = data.order_by('nutrition_grade')\n\n # use paginator :\n # display of pages > 1 of result\n paginator = Paginator(foods_data, 18, orphans=4)\n page = request.GET.get('page')\n try:\n foods_data = paginator.get_page(page)\n except PageNotAnInteger:\n foods_data = paginator.page(1)\n except EmptyPage:\n foods_data = paginator.page(paginator.num_pages)\n context['foods_data'] = foods_data\n\n # DOES NOT DISPLAY THE FLOPPY LOGO\n # if the user has already registered the food\n if request.user.is_authenticated:\n # get the favorites foods id\n user = get_user_model()\n favorites_id = []\n id_user = request.user.id\n for elt in user(id=id_user).food_set.values_list('id'):\n favorites_id.append(elt[0])\n context['favorites_id'] = favorites_id\n else:\n context['favorites_id'] = []\n\n return render(request, 'food/result.html', context)\n\n\ndef detail(request):\n \"\"\" detail view :\n get the data of the food selected by the user\n and display the detail page \"\"\"\n\n # DISPLAY THE DETAIL PAGE\n # get id of the food selected\n id_food = request.POST.get('id_food', None)\n\n # get the data of the food selected\n food = Food.objects.values_list('name', 'nutrition_grade', 'url_picture',\n 'link', 'energy', 'proteins', 'fat',\n 'carbohydrates', 'sugars', 'fiber', 'sodium')\n food_data = food.get(id=id_food)\n context = {}\n name_data = ('name', 'nutrition_grade', 'url_picture', 'link', 'energy', 'proteins', 'fat',\n 'carbohydrates', 'sugars', 'fiber', 'sodium')\n for i, elt in enumerate(name_data):\n context[elt] = food_data[i]\n\n return render(request, 'food/detail.html', context)\n\n\ndef favorites(request):\n \"\"\" favorites view :\n get the favorites food data of the user\n and display the favorites page,\n delete the favorite food selected by the user \"\"\"\n\n # DELETE THE FOOD SELECTED BY THE USER\n if request.method == 'POST' and request.user.is_authenticated:\n id_food = request.POST.get('id', None)\n id_user = request.user.id\n food = Food.objects.get(id=id_food)\n user = get_user_model()\n user = user.objects.get(id=id_user)\n food.favorites.remove(user)\n\n # RETURN TO THE ACCESS_ACCOUNT PAGE\n # if user is not authenticated\n if not request.user.is_authenticated:\n form = Account()\n message = [\"Veuillez vous connecter pour accéder à vos favoris.\"]\n context = {'form': form, 'message': message, 'color': 'red'}\n return render(request, 'account/access_account.html', context)\n\n # DISPLAY THE FAVORITES PAGE\n # if user is authenticated\n # get the favorites food data\n user = get_user_model()\n id_user = request.user.id\n data = user(id=id_user).food_set.all()\n context = {'data': data}\n\n return render(request, 'food/favorites.html', context)\n\n\ndef mentions_legal(request):\n \"\"\" mentions_legal view :\n display the mentions_legal page \"\"\"\n return render(request, 'food/mentions_legal.html')\n","sub_path":"food/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"359438067","text":"# same as script 14, but with the smaller dqn and returning the average q values\n\n\nimport sys\nimport os\n\nlucas_path = os.environ['LUCAS_PATH']\nsys.path.insert(1, lucas_path)\n\nfrom general import general as gen\nfrom devices.devices import node, base_station, mobile_user, d2d_user, d2d_node_type\nfrom pathloss import pathloss\nfrom plots.plots import plot_positions, plot_spectral_effs\nfrom q_learning.environments.completeEnvironment import CompleteEnvironment\nfrom dqn.agents.dqnAgent import ExternalDQNAgent\nfrom dqn.externalDQNFramework import ExternalDQNFramework\nfrom dqn.replayMemory import ReplayMemory\nfrom dqn.dqn import DQN\nfrom q_learning.q_table import DistributedQTable\nfrom q_learning import rewards\nfrom parameters.parameters import EnvironmentParameters, TrainingParameters, DQNAgentParameters, LearningParameters\nfrom typing import List\nfrom matplotlib import pyplot as plt\n\nimport torch\nimport math\nimport numpy as np\nimport os\nimport pickle\n\nn_mues = 1 # number of mues\nn_d2d = 2 # number of d2d pairs\nn_rb = n_mues # number of RBs\nbs_radius = 500 # bs radius in m\n\nrb_bandwidth = 180*1e3 # rb bandwidth in Hz\nd2d_pair_distance = 50 # d2d pair distance in m\np_max = 23 # max tx power in dBm\nnoise_power = -116 # noise power per RB in dBm\nbs_gain = 17 # macro bs antenna gain in dBi\nuser_gain = 4 # user antenna gain in dBi\nsinr_threshold_train = 6 # mue sinr threshold in dB for training\nsinr_threshold_mue = 6 # true mue sinr threshold in dB\nmue_margin = .5e4\n\n# conversions from dB to pow\np_max = p_max - 30\np_max = gen.db_to_power(p_max)\nnoise_power = noise_power - 30\nnoise_power = gen.db_to_power(noise_power)\nbs_gain = gen.db_to_power(bs_gain)\nuser_gain = gen.db_to_power(user_gain)\nsinr_threshold_train = gen.db_to_power(sinr_threshold_train)\n\n# q-learning parameters\nSTEPS_PER_EPISODE = 100\nEPSILON_MIN = 0.05\n# MAX_NUM_STEPS = 50\n# EPSILON_DECAY = 0.4045*1e-4 # super long training\n# EPSILON_DECAY = 0.809*1e-4 # long training\n# EPSILON_DECAY = 0.809*1e-4 # medium training\n# EPSILON_DECAY = 3.236*1e-4 # medium training\nEPSILON_DECAY = 8.09*1e-4 # short training\n# EPSILON_DECAY = 4.045*1e-4 # short training\n# MAX_NUM_EPISODES = 40000 # super long training\n# MAX_NUM_EPISODES = 20000 # long training\n# MAX_NUM_EPISODES = 5000 # medium training\nMAX_NUM_EPISODES = 2000 # short training\nALPHA = 0.05 # Learning rate\nGAMMA = 0.98 # Discount factor\n# C = 8000 # C constant for the improved reward function\nC = 80 # C constant for the improved reward function\nTARGET_UPDATE = 10\n\n# more parameters\nenv_params = EnvironmentParameters(rb_bandwidth, d2d_pair_distance, p_max, noise_power, bs_gain, user_gain, sinr_threshold_train,\n n_mues, n_d2d, n_rb, bs_radius, c_param=C, mue_margin=mue_margin)\ntrain_params = TrainingParameters(MAX_NUM_EPISODES, STEPS_PER_EPISODE)\nagent_params = DQNAgentParameters(EPSILON_MIN, EPSILON_DECAY, 1, 512, GAMMA)\n\nextFramework = ExternalDQNFramework(agent_params)\n# actions = [i*p_max/10/1000 for i in range(21)] # worst\n# actions = [i*0.80*p_max/10/1000 for i in range(21)] # best histogram\nactions = [i*0.82*p_max/5/1000 for i in range(5)] # best result\nagents = [ExternalDQNAgent(agent_params, actions) for i in range(n_d2d)] # 1 agent per d2d tx\nreward_function = rewards.dis_reward_tensor2\nenvironment = CompleteEnvironment(env_params, reward_function, early_stop=1e-6, tolerance=10)\n\n\n# training function\n# TODO: colocar agente e d2d_device na mesma classe? fazer propriedade d2d_device no agente?\ndef train(agents: List[ExternalDQNAgent], framework: ExternalDQNFramework, env: CompleteEnvironment, params: TrainingParameters):\n counts = np.zeros(len(agents))\n awaits = list()\n await_steps = [2,3,4]\n for a in agents:\n awaits.append(np.random.choice(await_steps))\n a.set_action(torch.tensor(0).long().cuda(), a.actions[0])\n best_reward = 1e-16\n device = torch.device('cuda')\n rewards_bag = list()\n for episode in range(params.max_episodes):\n # TODO: atualmente redistribuo os usuarios aleatoriamente a cada episodio. Isto é o melhor há se fazer? \n # Simular deslocamento dos usuários?\n env.build_scenario(agents)\n done = False\n obs = [env.get_state(a) for a in agents] \n total_reward = 0.0\n i = 0\n bag = list()\n while not done:\n if i >= params.steps_per_episode:\n break\n else:\n actions = torch.zeros([len(agents)], device=device)\n for j, agent in enumerate(agents):\n if counts[j] < awaits[j]:\n counts[j] += 1\n else:\n agent.get_action(framework, obs[j])\n actions[j] = agent.action_index \n counts[j] = 0\n awaits[j] = np.random.choice(await_steps)\n # for j, agent in enumerate(agents):\n # actions[j] = agent.get_action(obs[j]) \n next_obs, rewards, done = env.step(agents) \n i += 1\n for j, agent in enumerate(agents):\n framework.replay_memory.push(obs[j], actions[j], next_obs[j], rewards[j])\n framework.learn()\n obs = next_obs\n total_reward += torch.sum(rewards) \n bag.append(total_reward.item()) \n obs = next_obs\n if episode % TARGET_UPDATE == 0:\n framework.target_net.load_state_dict(framework.policy_net.state_dict())\n if total_reward > best_reward:\n best_reward = total_reward\n print(\"Episode#:{} sum reward:{} best_sum_reward:{} eps:{}\".format(episode,\n total_reward, best_reward, agents[0].epsilon))\n rewards_bag.append(np.average(bag))\n \n \n # Return the trained policy\n # policies = [np.argmax(q.table, axis=1) for q in q_tables]\n return rewards_bag\n\n \n# SCRIPT EXEC\n# training\n# train(agents, environment, train_params)\nrewards = train(agents, extFramework, environment, train_params)\n# rewards = rb_bandwidth*rewards\n\ncwd = os.getcwd()\n\nfilename = gen.path_leaf(__file__)\nfilename = filename.split('.')[0]\nfilename_model = filename\nfilename = f'{lucas_path}/data/{filename}.pickle'\ntorch.save(ext_framework.policy_net.state_dict(), f'{filename_model}.pt')\nwith open(filename, 'wb') as f:\n pickle.dump(spectral_effs, f)\n\nplt.figure(1)\nplt.plot(extFramework.bag, '.')\nplt.xlabel('Iterations')\nplt.ylabel('Average Q-Values')\n\nplt.figure(2)\nplt.plot(rewards, '.')\n\nplt.show()\n\n# filename = gen.path_leaf(__file__) \n# filename = filename.split('.')[0]\n# np.save(f'{lucas_path}/models/{filename}', learned_policies)\n\n# testing\n# t_env = CompleteEnvironment(env_params, reward_function)\n# t_agents = [DQNAgent(agent_params, actions) for i in range(n_d2d)] # 1 agent per d2d tx\n# total_reward, mue_spectral_effs, d2d_spectral_effs = test(t_agents, environment, learned_policies, 5, 100)\n\n# plots\n# mue_spectral_effs = np.array(mue_spectral_effs)\n# mue_spectral_effs = np.reshape(mue_spectral_effs, np.prod(mue_spectral_effs.shape))\n\n# d2d_spectral_effs = np.array(d2d_spectral_effs)\n# d2d_spectral_effs = np.reshape(d2d_spectral_effs, np.prod(d2d_spectral_effs.shape))\n\n# threshold_eff = np.log2(1 + sinr_threshold_train) * np.ones(len(mue_spectral_effs))\n\n# plt.figure(1)\n# plt.plot(list(range(len(d2d_spectral_effs))), d2d_spectral_effs, '.',label='D2D')\n# plt.plot(list(range(len(mue_spectral_effs))), mue_spectral_effs, '.',label='MUE')\n# plt.plot(list(range(len(mue_spectral_effs))), threshold_eff, label='Threshold') \n# plt.title('Spectral efficiencies')\n# plt.legend()\n# plt.show()\n\n\n","sub_path":"scripts_dql/script19.py","file_name":"script19.py","file_ext":"py","file_size_in_byte":7848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"258259469","text":"import sys\r\n\r\nnum = int(sys.argv[1])\r\n\r\nif num <= 0:\r\n sys.exit('Por favor, introduzca un valor positivo.')\r\n\r\nelse:\r\n for value in range(2, num):\r\n if num % value == 0:\r\n print ('No es primo!')\r\n break\r\n else:\r\n print ('Es primo!')\r\n","sub_path":"ut2/a3/program1.py","file_name":"program1.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"591842671","text":"from collections import Counter\nfrom textblob import TextBlob as tb\nimport codecs\nimport math\nimport sys\nimport time\n\n# Get cosine similarity of two vectors\ndef getCos(vec1, vec2):\n all_values = set(vec1.keys()) & (set(vec2.keys()))\n numerator = sum([vec1[key] * vec2[key] for key in all_values])\n sum1 = sum([vec1[key] ** 2 for key in vec1.keys()])\n sum2 = sum([vec2[key] ** 2 for key in vec2.keys()])\n denominator = math.sqrt(sum1) * math.sqrt(sum2)\n if not denominator:\n return 0.0\n else:\n return float(numerator) / denominator\n\n# convert word list to vectors\ndef text_to_vector(text):\n return Counter(text.words)\n\n\nif __name__ == '__main__':\n if len(sys.argv) != 3:\n print('Usage: python similarity.py text.txt description.txt')\n sys.exit(1)\n\n text1 = codecs.open(sys.argv[1], 'r', encoding='utf-8',\n errors='ignore').read()\n text2 = codecs.open(sys.argv[2], 'r', encoding='utf-8',\n errors='ignore').read()\n\n start_time = time.time()\n\n vector1 = text_to_vector(tb(text1))\n vector2 = text_to_vector(tb(text2))\n cos = getCos(vector1, vector2)\n\n print(\"Cosine Similarity between %s and %s: %f\" % (sys.argv[1], sys.argv[2], cos))\n print(\"Running time: %s seconds\" % (time.time() - start_time))\n","sub_path":"similarity.py","file_name":"similarity.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"588397774","text":"import numpy as np\nimport csv\nfrom sklearn.cross_validation import cross_val_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import svm\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.externals import joblib\n\n\nclass KeyStrokeManager():\n\n featureName = ['accelerationMagnitudes', 'totalNumberOfDeletions', \\\n 'gyroMagnitudes', 'interTapDistances', \\\n 'tapDurations', 'userId']\n emotions = {'Happy': 0, 'Neutral': 1, 'Calm': 1, 'Sad': 2, \\\n 'Angry': 3, 'Anxious': 4}\n uids = {'acsalu': 0, 'co273': 1, 'jean': 2}\n m_path = 'pkl/'\n\n\n def __init__(self, data):\n self.model = None\n self.features = KeyStrokeManager.parseFeature(data)\n self.labels = list(map(lambda x: KeyStrokeManager.emotions[x.emotion]\\\n , data))\n\n\n @classmethod\n def parseFeature(cls, data, normalize=True):\n [accMag, ttlNODel, gyro, intTapDist, tapDur, uid] = \\\n [[getattr(d, feature) for d in data] for feature in cls.featureName]\n\n aveAccMag, stdAccMag = \\\n [np.mean(a) for a in accMag], [np.std(a) for a in accMag]\n aveGyro, stdGyro = \\\n [np.mean(g) for g in gyro], [np.std(g) for g in gyro]\n aveIntTapDist, stdIntTapDist = \\\n [np.mean(i) for i in intTapDist], [np.std(i) for i in intTapDist]\n aveTapDur, stdTapDur = \\\n [np.mean(t) for t in tapDur], [np.std(t) for t in tapDur]\n uidFea = list(map(lambda x: cls.uids[x], uid))\n\n if normalize:\n features = list(map(cls.normalize, \\\n [aveAccMag, stdAccMag, aveGyro, stdGyro, \\\n aveIntTapDist, stdIntTapDist, \\\n aveTapDur, stdTapDur, uidFea]))\n else:\n features = [aveAccMag, stdAccMag, aveGyro, stdGyro, \\\n aveIntTapDist, stdIntTapDist, \\\n aveTapDur, stdTapDur, uidFea]\n\n return np.array(features).T\n\n\n def normalize(feature):\n std = np.std(feature)\n mean = np.mean(feature)\n if std == 0:\n return feature - mean\n return (feature - mean) / std\n\n\n def saveParams(self, path):\n means = np.mean(self.features, axis=0)\n stds = np.std(self.features, axis=0)\n with open(path, 'w') as csvfile:\n writer = csv.writer(csvfile, delimiter=',')\n for idx in range(len(self.features[0])):\n m, s = means[idx], stds[idx]\n writer.writerow([m, s])\n\n\n def logisticRegression(self):\n self.model = LogisticRegression()\n\n\n def svm(self):\n self.model = svm.SVC()\n\n\n def naiveBayes(self):\n self.model = GaussianNB()\n\n\n def randomForest(self):\n self.model = RandomForestClassifier()\n\n\n def crossValidScore(self):\n return cross_val_score(self.model, self.features, self.labels).mean()\n\n\n def saveModel(self, path):\n self.model.fit(self.features, self.labels)\n joblib.dump(self.model, path, protocol=2) \n","sub_path":"manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":3138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"106302343","text":"# Import Necessary Libraries\n\nimport cv2\nimport time\n\nimport numpy as np\nimport pandas as pd\n\nimport torch\nimport torch.nn as nn\n\nfrom tqdm import tqdm\n\nimport albumentations as A\nfrom albumentations.pytorch.transforms import ToTensorV2\n\nfrom efficientnet_pytorch import EfficientNet\n\nfrom sklearn.model_selection import KFold\n\nfrom sklearn.metrics import roc_auc_score\n\nfrom torch.utils.data import Dataset\nfrom torch.utils.data.sampler import SequentialSampler\n\n# Load Data\n\ndf_1=pd.read_csv(\"./train.csv\")\ndf_2=pd.read_csv(\"./train2.csv\")\nsample = pd.read_csv('./sample_submission.csv', index_col='image_name')\n\ndf_3=df_1.append(df_2)\ndi = {0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,10:10,11:11,12:12,13:13,14:14,15:0,16:1,17:2,18:3,19:4,20:5,21:6,22:7,23:8,24:9,25:10,26:11,27:12,28:13,29:14}\n\ndf_3 = df_3.replace({'tfrecord':di})\ndf_3 = df_3[df_3.patient_id!=-1]\n\nimg_dir=\"./\"\n\ndf_test = pd.read_csv('test.csv')\n\n# Data Loader\n\ndef onehot(size, target):\n vec = torch.zeros(size, dtype=torch.float32)\n vec[target] = 1.\n return vec\n\nclass DatasetRetriever(Dataset):\n\n def __init__(self, image_ids, labels=None, validation_img_dir=None, test_img_dir=None, transforms=None):\n super().__init__()\n self.image_ids = image_ids\n self.labels = labels\n self.transforms = transforms\n self.validation_img_dir = validation_img_dir\n self.test_img_dir = test_img_dir\n\n def __getitem__(self, idx: int):\n \n if self.validation_img_dir is not None:\n\n image_id = self.image_ids[idx]\n image = cv2.imread(f'{self.validation_img_dir}/{image_id}.jpg', cv2.IMREAD_COLOR)\n image = image.astype(np.float32) / 255.0\n label = self.labels[idx]\n\n if self.transforms:\n sample = {'image': image}\n sample = self.transforms(**sample)\n image = sample['image']\n\n target = onehot(2, label)\n return image, target\n \n if self.test_img_dir is not None:\n image_id = self.image_ids[idx]\n image = cv2.imread(f'{self.test_img_dir}/{image_id}.jpg', cv2.IMREAD_COLOR)\n image = image.astype(np.float32) / 255.0\n \n if self.transforms:\n sample = {'image': image}\n sample = self.transforms(**sample)\n image = sample['image']\n\n return image\n\n def __len__(self) -> int:\n return self.image_ids.shape[0]\n\n def get_labels(self):\n return list(self.labels)\n\n# Augmentations\n\ndef train_augmentaions(image_size=384):\n return A.Compose([\n A.Resize(height=image_size, width=image_size, p=1),\n \n A.RandomSizedCrop(\n min_max_height=(np.floor(image_size*0.8), np.floor(image_size*0.8)), \n height=image_size, \n width=image_size, \n p=0.5), # 20% of height and width to be reduced\n \n A.RandomRotate90(p=0.5),\n A.HorizontalFlip(p=0.5),\n A.VerticalFlip(p=0.5),\n A.CoarseDropout(max_holes=8, max_width=64, max_height=64, fill_value=0, p=0.5),\n ToTensorV2(p=1.0), \n ], p=1.0)\n\ndef validation_augmentations(image_size=384):\n return A.Compose([\n A.Resize(height=image_size, width=image_size, p=1.0),\n ToTensorV2(p=1.0),\n ], p=1.0)\n\n# EfficientNet Model\n\ndef Net(model_name):\n model = EfficientNet.from_pretrained(f'efficientnet-{model_name}')\n model._fc = nn.Linear(in_features=model._fc.in_features, out_features=2, bias=True)\n return model\n\ndef get_model(efficient_net, fold_number, image_size=384, model_weight_path='./'):\n model = Net(efficient_net).cuda()\n model_state_dict = torch.load(f\"{model_weight_path}/{image_size}_{efficient_net}_{fold_number}.pt\")[\"model_state_dict\"]\n model.load_state_dict(model_state_dict)\n return model\n\n# Engine\n\nclass Prediction:\n def __init__(self, model, val_img_len, tta=11):\n self.model=model\n self.model.eval()\n \n self.oof_pred = np.zeros((val_img_len, ))\n self.oof_tar = np.zeros((val_img_len, ))\n self.oof_fold = np.zeros((val_img_len, ))\n \n self.test_pred = np.zeros((len(sample),)) \n \n self.tta = tta\n \n def predict(self, validation_loader, test_loader, fold_number):\n with torch.no_grad():\n for i in range(self.tta):\n \n print(\"Calculating OOF...\")\n \n for steps,(images, targets) in enumerate(tqdm(validation_loader)):\n images = images.cuda()\n pred = self.model(images) \n pred = nn.functional.softmax(pred, dim=1).data.cpu().numpy()[:,1]\n\n self.oof_pred[steps*32: (steps+1)*32] += pred\n self.oof_tar[steps*32: (steps+1)*32] = targets[:,1]\n self.oof_fold[steps*32: (steps+1)*32] = fold_number\n \n print(\"{} TTA performed on OOF prediction..\".format(i+1))\n \n print(\"Predicting for Test Data...\")\n \n for steps,images in enumerate(tqdm(test_loader)):\n images = images.cuda()\n pred = self.model(images) \n pred = nn.functional.softmax(pred, dim=1).data.cpu().numpy()[:,1]\n \n self.test_pred[steps*32: (steps+1)*32] += pred\n print(\"{} TTA performed on Test Data..\".format(i+1)) \n\n self.oof_pred /= self.tta\n self.test_pred /= self.tta\n print(\"Predictions calculated with TTA...\")\n \n return self.oof_pred, self.oof_tar, self.test_pred, self.oof_fold\n\n# Connector\n\ndef predict_fold(efficient_net, validation_img_dir, test_img_dir, model_weight_path, image_size=512):\n \n test_pred = np.empty((5, len(sample)))\n test = []\n oof_pred = []\n oof_tar = []\n oof_names = []\n oof_folds = []\n \n skf = KFold(n_splits=5,shuffle=True,random_state=42)\n for fold_number,(_,idxV) in enumerate(skf.split(np.arange(15))):\n \n print(\"Current Fold : {}\".format(fold_number))\n \n X_val_id = df_3.loc[(df_3.tfrecord.isin(idxV)) & (df_3.patient_id!=-1)].index.values\n X_val_label = df_3.loc[(df_3.tfrecord.isin(idxV)) & (df_3.patient_id!=-1)].target.values\n\n valid_gen = DatasetRetriever(\n image_ids=X_val_id,\n labels=X_val_label,\n validation_img_dir=validation_img_dir,\n test_img_dir = None,\n transforms=train_augmentaions(image_size=image_size),\n )\n\n val_img_len = valid_gen.__len__()\n\n test_gen = DatasetRetriever(\n image_ids=sample.index.values,\n validation_img_dir = None,\n test_img_dir=test_img_dir,\n transforms=train_augmentaions(image_size=image_size),\n )\n\n validation_loader = torch.utils.data.DataLoader(\n valid_gen, \n batch_size=32,\n num_workers=4,\n shuffle=False,\n sampler=SequentialSampler(valid_gen),\n pin_memory=False,\n )\n\n test_loader = torch.utils.data.DataLoader(\n test_gen, \n batch_size=32, \n shuffle=False, \n num_workers=4,\n sampler=SequentialSampler(test_gen)\n )\n\n model = get_model(efficient_net, fold_number, image_size, model_weight_path)\n\n prediction = Prediction(model = model, val_img_len = val_img_len)\n\n fold_oof_pred, fold_oof_tar, fold_test_pred, folds = prediction.predict(validation_loader, test_loader, fold_number)\n \n oof_pred.append(fold_oof_pred)\n oof_tar.append(fold_oof_tar)\n oof_names.append(X_val_id)\n oof_folds.append(folds)\n test_pred[fold_number, : ] = fold_test_pred\n \n test[:] = test_pred.mean(axis=0)\n \n oof = np.concatenate(oof_pred)\n true = np.concatenate(oof_tar)\n names = np.concatenate(oof_names)\n folds_total = np.concatenate([oof_folds])\n auc = roc_auc_score(true,oof)\n \n return (oof, true, names, auc, folds_total, test)\n\n# File Generation\n\ndef make_prediction_and_save(model_name='b5', image_size=512, validation_img_dir='./', test_img_dir='./', model_weight_path='./'):\n \n oof, true, names, auc, folds_total, test = predict_fold(efficient_net=model_name, validation_img_dir=validation_img_dir, test_img_dir=test_img_dir, model_weight_path=model_weight_path, image_size=image_size)\n \n print('Overall OOF AUC with TTA = %.3f'%auc)\n\n a=[]\n for i in range(len(folds_total)):\n a.extend(folds_total[i])\n\n sample = pd.read_csv('./sample_submission.csv')\n sample.target=test\n\n df_oof = pd.DataFrame(dict(\n image_name = names, target=true, pred = oof, folds=a))\n\n df_oof.to_csv(f'{\"./\"}/{model_name}_{image_size}_oof.csv',index=False)\n sample.to_csv(f'{\"./\"}/{model_name}_{image_size}_test.csv',index=False)\n\nmake_prediction_and_save(model_name='b5', image_size=512)","sub_path":"src/prediction.py","file_name":"prediction.py","file_ext":"py","file_size_in_byte":9077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"264710523","text":"# Problem No.: 11409\r\n# Solver: Jinmin Goh\r\n# Date: 20220830\r\n# URL: https://www.acmicpc.net/problem/11409\r\n\r\nimport sys\r\n\r\ndef solve(graph, capacity, flow, cost, s, t):\r\n ret = 0\r\n cnt = 0\r\n while True:\r\n parent = [-1 for _ in range(810)]\r\n distance = [10 ** 9 for _ in range(810)]\r\n in_queue = [False for _ in range(810)]\r\n queue = [s]\r\n distance[s] = 0\r\n in_queue[s] = True\r\n while queue:\r\n temp = []\r\n for curr in queue:\r\n in_queue[curr] = False\r\n for next in graph[curr]:\r\n if capacity[curr][next] - flow[curr][next] > 0 and distance[next] > distance[curr] + cost[curr][next]:\r\n distance[next] = distance[curr] + cost[curr][next]\r\n parent[next] = curr\r\n if in_queue[next] == False:\r\n in_queue[next] = True\r\n temp.append(next)\r\n queue = temp\r\n if parent[t] == -1:\r\n break\r\n val = 10 ** 9\r\n curr = t\r\n while curr != s:\r\n val = min(val, capacity[parent[curr]][curr] - flow[parent[curr]][curr])\r\n curr = parent[curr]\r\n curr = t\r\n while curr != s:\r\n ret += val * cost[parent[curr]][curr]\r\n flow[parent[curr]][curr] += val\r\n flow[curr][parent[curr]] -= val\r\n curr = parent[curr]\r\n cnt += 1\r\n return (cnt, ret)\r\n\r\ndef main():\r\n graph = [[] for _ in range(810)]\r\n capacity = [[0 for _ in range(810)] for _ in range(810)]\r\n flow = [[0 for _ in range(810)] for _ in range(810)]\r\n cost = [[0 for _ in range(810)] for _ in range(810)]\r\n n, m = map(int, sys.stdin.readline().split()) \r\n for i in range(1, m + 1):\r\n graph[i + 400].append(801)\r\n graph[801].append(i + 400)\r\n capacity[i + 400][801] = 1\r\n for i in range(1, n + 1):\r\n graph[i].append(0)\r\n graph[0].append(i)\r\n capacity[0][i] = 1\r\n temp = list(map(int, sys.stdin.readline().split()))\r\n for j in range(temp[0]):\r\n a, c = temp[2 * j + 1], temp[2 * (j + 1)]\r\n graph[i].append(a + 400)\r\n graph[a + 400].append(i)\r\n cost[i][a + 400] = -c\r\n cost[a + 400][i] = c\r\n capacity[i][a + 400] = 1\r\n total_flow, total_cost = solve(graph, capacity, flow, cost, 0, 801)\r\n print(total_flow)\r\n print(-total_cost)\r\n return\r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"Solved/11409/11409.py","file_name":"11409.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"292278540","text":"from PyQt5.QtCore import pyqtSlot, pyqtSignal\nfrom PyQt5.QtWidgets import QMessageBox, QApplication, QDialog\n\nfrom diy.delaydialog.delaydialogui import Ui_Dialog\n\n\nclass DELAYDialog(QDialog, Ui_Dialog):\n delay_confirm = pyqtSignal(int)\n\n def __init__(self, parent=None):\n super(DELAYDialog, self).__init__(parent)\n self.setupUi(self)\n self.et_delay_s.setFocus()\n\n @pyqtSlot()\n def on_btn_delay_cancel_clicked(self):\n self.close()\n\n @pyqtSlot()\n def on_btn_delay_insert_clicked(self):\n val_s = self.et_delay_s.text()\n if val_s:\n self.delay_confirm.emit(int(val_s))\n self.close()\n else:\n QMessageBox.information(self, '提示', '请填入非零延时秒数')\n\n def closeEvent(self, QCloseEvent):\n self.et_delay_s.clear()\n\n\nif __name__ == '__main__':\n import sys\n\n app = QApplication(sys.argv)\n ui = DELAYDialog()\n ui.show()\n sys.exit(app.exec_())\n","sub_path":"diy/delaydialog/delaydialog.py","file_name":"delaydialog.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"162329813","text":"def compute(a, b, c):\n y = (b**2) - (4 * a * c)\n\n if y > 0:\n x1, x2 = (-b + (y ** 0.5)) / (2 * a), (-b - (y ** 0.5)) / (2 * a)\n # 可以一口氣賦值給兩個變數\n return x1, x2\n\n else:\n return 'Your equation has no root', None\n\n\na = eval(input())\nb = eval(input())\nc = eval(input())\nm, n = compute(a, b, c)\n\nif n == None:\n print(m)\nelse:\n print('{}, {}'.format(m, n))","sub_path":"_5_function/506/reference_solution.py","file_name":"reference_solution.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"271434713","text":"#email cs110classwork.cs.binghamton.edu\ndef sum_of_squares(xs):\n '''\n Computes the sum of the squares of nums in the list\n assumes all elements in list are integers\n args: list\n return: sum of squared nums\n '''\n sum = 0\n for i in xs:\n sum += i**2\n return sum\n\ndef main():\n a = [1, 2, 3]\n print(sum_of_squares(a))\n a.append(\"apple\"), a.append(76), a.insert(2, \"cat\"), a.insert(0, 99)\n accum = 0\n print(\"Number of instances of 76: \" + str(a.count(76)))\n a.remove(76)\n a[a.index(\"apple\")] = \"orange\"\n #for i in range(len(a)):\n # if a[i] == \"apple\":\n # a[i] = \"orange\"\n\n print(a)\nmain()\n","sub_path":"cs110/notes/CW10-18.py","file_name":"CW10-18.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"372156794","text":"import functools\nimport time\nimport math\nimport copy\n\nfrom discord.ext import commands\nimport discord\n\nfrom utils.flags import parse_flags\nfrom utils.image import Image as WandImage\nfrom utils.image import Color\n\n\nclass Imaging:\n \"\"\"\n This cog adds image manipulation functionality for both GIFs and static images.\n \"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n self.valid_effect_names = {}\n self.image_cache = {}\n\n async def on_ready(self):\n for command in self.bot.commands:\n if command.cog_name == \"Imaging\":\n if command.name not in [\"effect\", \"effects\", \"ascii\"]:\n aliases = command.aliases.copy()\n aliases.append(command.name)\n self.valid_effect_names.update({command.name: aliases})\n self.image_cache.update({command.name: {}})\n if command.name in [\"ascii\"]:\n self.image_cache.update({command.name: {}})\n\n async def on_member_update(self, before, after):\n if before.avatar_url != after.avatar_url:\n for members in self.image_cache.values():\n try:\n members.pop(after.id)\n except KeyError:\n pass\n\n async def _in_cache(self, command, member: discord.User):\n command_cache = self.image_cache[command.name]\n if member.id in command_cache.keys():\n return True\n return False\n\n async def _add_to_cache(self, command, member: discord.User, file):\n command_cache = self.image_cache[command.name]\n command_cache.update({member.id: {\"avatar_url\": member.avatar_url, \"file\": file}})\n\n async def _pull_from_cache(self, command, member: discord.User):\n return copy.deepcopy(self.image_cache[command.name][member.id][\"file\"])\n\n async def _image_function_on_link(self, link: str, image_function, *args):\n start = time.perf_counter()\n\n image = await WandImage.from_link(link)\n\n file, _, b_io = await self._image_function(image, image_function, *args)\n\n end = time.perf_counter()\n duration = round((end - start) * 1000, 2)\n\n return file, duration, b_io\n\n async def _image_function(self, image: WandImage, image_function, *args):\n start = time.perf_counter()\n\n executor = functools.partial(image_function, image)\n if args:\n executor = functools.partial(image_function, image, *args)\n\n file, b_io = await self.bot.loop.run_in_executor(None, executor)\n\n end = time.perf_counter()\n duration = round((end - start) * 1000, 2)\n\n return file, duration, b_io\n\n @staticmethod\n def _deepfry(image: WandImage):\n \"\"\"\n Deepfry an image.\n :param image:\n :return:\n \"\"\"\n with image:\n if image.format != \"jpeg\":\n image.format = \"jpeg\"\n image.compression_quality = 2\n image.modulate(saturation=700)\n ret = image.to_discord_file(\"deep-fry.png\")\n b_io = image.to_bytes_io()\n\n return ret, b_io\n\n @staticmethod\n def _thonk(image: WandImage):\n \"\"\"\n Add the thonk hand image on top of the provided image.\n :param image:\n :return:\n \"\"\"\n with WandImage(filename=\"assets/thonk_hand.png\") as thonk:\n with image:\n thonk.resize(image.width, image.height)\n image.composite(thonk, 0, 0)\n ret = image.to_discord_file(\"thonk.png\")\n b_io = image.to_bytes_io()\n\n return ret, b_io\n\n @staticmethod\n def _wasted(image: WandImage):\n \"\"\"\n Add the wasted image on top of the provided image.\n :param image:\n :return:\n \"\"\"\n with WandImage(filename=\"assets/wasted.png\") as wasted:\n with image:\n wasted.resize(image.width, image.height)\n image.composite(wasted, 0, 0)\n ret = image.to_discord_file(\"wasted.png\")\n b_io = image.to_bytes_io()\n\n return ret, b_io\n\n @staticmethod\n def _ascii(image: WandImage, inverted: bool = False, brightness: int = 100, size: int = 62):\n \"\"\"\n Converts image into an ascii art string.\n :param image: The :class WandImage: to convert to ascii.\n :param inverted: A :type bool: determining whether or not to invert.\n :param brightness: A :type int: determining the brightness.\n :param size: A :type int: determining the size.\n :return: A :type str: containing the art.\n \"\"\"\n with image:\n if inverted:\n image.negate()\n if brightness is not 100:\n image.modulate(brightness=brightness)\n if size > 62:\n size = 62\n if size < 0:\n size = 2\n size = int(math.ceil(size / 2.) * 2)\n\n image.sample(size, int(size / 2))\n\n ascii_art = \"```\"\n\n for row in image:\n ascii_art += \"\\n\"\n for col in row:\n with Color(str(col)) as c:\n ascii_art += c.ascii_character\n\n ascii_art += \"```\"\n\n return ascii_art, ascii_art\n\n @staticmethod\n def _magic(image: WandImage):\n \"\"\"\n Content aware scale an image. Made for use with _magic_command.\n :param image:\n :return discord.File:\n \"\"\"\n # overly content-aware-scale it\n with image:\n image.liquid_rescale(\n width=int(image.width * 0.5),\n height=int(image.height * 0.5),\n delta_x=1,\n rigidity=0\n )\n image.liquid_rescale(\n width=int(image.width * 1.5),\n height=int(image.height * 1.5),\n delta_x=2,\n rigidity=0\n )\n\n image.resize(256, 256)\n\n ret = image.to_discord_file(\"magik.png\")\n b_io = image.to_bytes_io()\n\n return ret, b_io\n\n @staticmethod\n def _invert(image: WandImage):\n \"\"\"\n Invert an image. Made for use with _invert_command.\n :param image:\n :return discord.File:\n \"\"\"\n with image:\n image.negate()\n ret = image.to_discord_file(filename=\"inverted.png\")\n b_io = image.to_bytes_io()\n\n return ret, b_io\n\n # Everything from here on is a command.\n # Commands are named with _name_command\n\n @staticmethod\n def _expand(image: WandImage):\n \"\"\"\n Expand an image using a bit of seam-carving.\n :param image:\n :return discord.File:\n \"\"\"\n with image:\n image.liquid_rescale(int(image.width * 0.5), image.height)\n image.liquid_rescale(int(image.width * 3.5), image.height, delta_x=1)\n ret = image.to_discord_file(\"expand_dong.png\")\n b_io = image.to_bytes_io()\n\n return ret, b_io\n\n @commands.command(\n name=\"magic\",\n aliases=[\n 'magick',\n 'magik'\n ]\n )\n @commands.cooldown(\n rate=1,\n per=20,\n type=commands.BucketType.user\n )\n async def _magic_command(self, ctx, member: discord.Member = None):\n \"\"\"\n Content aware scale, also known as magic, a member's profile picture.\n If the member parameter is not fulfilled, the selected member will be you.\n \"\"\"\n if member is None:\n member = ctx.author\n\n if await self._in_cache(ctx.command, member):\n await ctx.message.add_reaction(self.bot.loading_emoji)\n\n b_io = await self._pull_from_cache(ctx.command, member)\n\n await ctx.send(f\"*0ms*\", file=discord.File(b_io, filename=\"deepfry.png\"))\n\n return await ctx.message.remove_reaction(self.bot.loading_emoji, ctx.me)\n\n await ctx.message.add_reaction(self.bot.loading_emoji)\n\n file, duration, b_io = await self._image_function_on_link(\n member.avatar_url_as(format=\"jpeg\", size=512),\n self._magic\n )\n\n await self._add_to_cache(ctx.command, member, b_io)\n\n await ctx.send(f\"*{duration}ms*\", file=file)\n\n await ctx.message.remove_reaction(self.bot.loading_emoji, ctx.me)\n\n @commands.command(\n name=\"invert\",\n aliases=[\n 'negate'\n ]\n )\n @commands.cooldown(\n rate=1,\n per=6,\n type=commands.BucketType.user\n )\n async def _invert_command(self, ctx, member: discord.Member = None):\n \"\"\"\n Invert a member's profile picture.\n If the member parameter is not fulfilled, the selected member will be you.\n \"\"\"\n if member is None:\n member = ctx.author\n\n if await self._in_cache(ctx.command, member):\n await ctx.message.add_reaction(self.bot.loading_emoji)\n\n b_io = await self._pull_from_cache(ctx.command, member)\n\n await ctx.send(f\"*0ms*\", file=discord.File(b_io, filename=\"deepfry.png\"))\n\n return await ctx.message.remove_reaction(self.bot.loading_emoji, ctx.me)\n\n await ctx.message.add_reaction(self.bot.loading_emoji)\n\n file, duration, b_io = await self._image_function_on_link(\n member.avatar_url_as(format=\"jpeg\", size=512),\n self._invert\n )\n\n await self._add_to_cache(ctx.command, member, b_io)\n\n await ctx.send(f\"*{duration}ms*\", file=file)\n\n await ctx.message.remove_reaction(self.bot.loading_emoji, ctx.me)\n\n @commands.command(\n name=\"ascii\",\n aliases=[\n \"asciify\",\n \"asciiart\"\n ]\n )\n async def _ascii_command(self, ctx, member: discord.Member = None, *flags: commands.clean_content):\n \"\"\"\n Convert a member's avatar into ascii art.\n If the member parameter is not fulfilled, it will select you.\n Optional Flags:\n -i , --invert Invert the image.\n -b=100, --brightness=100 Change the brightness of the starting image.\n -s=62, --size=62 Change the size of the ascii art. Min is 2 max is 62.\n Example Flag Usage:\n ascii [member] -i --brightness=100 -s=62\n \"\"\"\n if member is None:\n member = ctx.author\n\n await ctx.message.add_reaction(self.bot.loading_emoji)\n\n invert = False\n brightness = 100\n size = 62\n\n flags = parse_flags(flags)\n\n if flags is not None:\n if \"i\" in flags.keys():\n invert = flags[\"i\"]\n if \"invert\" in flags.keys():\n invert = flags[\"invert\"]\n\n if \"b\" in flags.keys():\n brightness = flags[\"b\"]\n if \"brightness\" in flags.keys():\n brightness = flags[\"brightness\"]\n\n if brightness > 300:\n raise commands.BadArgument(\"A passed flag was invalid.\\nThe maximum value for brightness is 300.\")\n elif brightness < 0:\n raise commands.BadArgument(\"A passed flag was invalid.\\nThe minimum value for brightness is 0.\")\n\n if \"s\" in flags.keys():\n size = flags[\"s\"]\n if \"size\" in flags.keys():\n size = flags[\"size\"]\n\n if type(size) is not int:\n raise commands.BadArgument(\"A passed flag was invalid.\\nThe size flag is an whole number.\")\n elif size > 62:\n raise commands.BadArgument(\"A passed flag was invalid.\\nThe maximum value for size is 62.\")\n elif size < 2:\n raise commands.BadArgument(\"A passed flag was invalid.\\nThe minimum value for size is 2.\")\n\n ascii_art, duration, _ = await self._image_function_on_link(\n member.avatar_url_as(format=\"png\", size=64), self._ascii, invert, brightness, size\n )\n\n await ctx.send(f\"*{duration}ms*\\n{ascii_art}\")\n\n await ctx.message.remove_reaction(self.bot.loading_emoji, ctx.me)\n\n @commands.command(\n name=\"expand\",\n aliases=[\n 'expnd',\n 'expanddong'\n ]\n )\n @commands.cooldown(\n rate=1,\n per=20,\n type=commands.BucketType.user\n )\n async def _expand_command(self, ctx, member: discord.Member = None):\n \"\"\"\n Expand a member's profile picture.\n If the member parameter is not fulfilled, the selected member will be you.\n \"\"\"\n if member is None:\n member = ctx.author\n\n if await self._in_cache(ctx.command, member):\n await ctx.message.add_reaction(self.bot.loading_emoji)\n\n b_io = await self._pull_from_cache(ctx.command, member)\n\n await ctx.send(f\"*0ms*\", file=discord.File(b_io, filename=\"deepfry.png\"))\n\n return await ctx.message.remove_reaction(self.bot.loading_emoji, ctx.me)\n\n await ctx.message.add_reaction(self.bot.loading_emoji)\n\n file, duration, b_io = await self._image_function_on_link(\n member.avatar_url_as(format=\"jpeg\", size=512),\n self._expand\n )\n\n await self._add_to_cache(ctx.command, member, b_io)\n\n await ctx.send(f\"*{duration}ms*\", file=file)\n\n await ctx.message.remove_reaction(self.bot.loading_emoji, ctx.me)\n\n @commands.command(\n name=\"wasted\",\n aliases=[\n 'gta',\n 'gtawasted'\n ]\n )\n @commands.cooldown(\n rate=1,\n per=20,\n type=commands.BucketType.user\n )\n async def _wasted_command(self, ctx, member: discord.Member = None):\n \"\"\"\n Add a gta wasted picture to a member's profile picture.\n If the member parameter is not fulfilled, the selected member will be you.\n \"\"\"\n if member is None:\n member = ctx.author\n\n if await self._in_cache(ctx.command, member):\n await ctx.message.add_reaction(self.bot.loading_emoji)\n\n b_io = await self._pull_from_cache(ctx.command, member)\n\n await ctx.send(f\"*0ms*\", file=discord.File(b_io, filename=\"deepfry.png\"))\n\n return await ctx.message.remove_reaction(self.bot.loading_emoji, ctx.me)\n\n await ctx.message.add_reaction(self.bot.loading_emoji)\n\n file, duration, b_io = await self._image_function_on_link(\n member.avatar_url_as(format=\"jpeg\", size=512),\n self._wasted\n )\n\n await self._add_to_cache(ctx.command, member, b_io)\n\n await ctx.send(f\"*{duration}ms*\", file=file)\n\n await ctx.message.remove_reaction(self.bot.loading_emoji, ctx.me)\n\n @commands.command(\n name=\"thonk\",\n aliases=[\n 'thonkify',\n 'thonking',\n 'think',\n 'thinkify',\n 'thinking'\n ]\n )\n @commands.cooldown(\n rate=1,\n per=20,\n type=commands.BucketType.user\n )\n async def _thonk_command(self, ctx, member: discord.Member = None):\n \"\"\"\n Add a thonk hand to a member's profile picture.\n If the member parameter is not fulfilled, the selected member will be you.\n \"\"\"\n if member is None:\n member = ctx.author\n\n if await self._in_cache(ctx.command, member):\n await ctx.message.add_reaction(self.bot.loading_emoji)\n\n b_io = await self._pull_from_cache(ctx.command, member)\n\n await ctx.send(f\"*0ms*\", file=discord.File(b_io, filename=\"deepfry.png\"))\n\n return await ctx.message.remove_reaction(self.bot.loading_emoji, ctx.me)\n\n await ctx.message.add_reaction(self.bot.loading_emoji)\n\n file, duration, b_io = await self._image_function_on_link(\n member.avatar_url_as(format=\"jpeg\", size=512),\n self._thonk\n )\n\n await self._add_to_cache(ctx.command, member, b_io)\n\n await ctx.send(f\"*{duration}ms*\", file=file)\n\n await ctx.message.remove_reaction(self.bot.loading_emoji, ctx.me)\n\n @commands.command(\n name=\"deepfry\",\n aliases=[\n \"deep-fry\",\n \"deepfryer\"\n ]\n )\n @commands.cooldown(\n rate=1,\n per=20,\n type=commands.BucketType.user\n )\n async def _deep_fry_command(self, ctx, member: discord.Member = None):\n \"\"\"\n Deepfry a member's profile picture.\n If the member parameter is not fulfilled, the selected member will be you.\n \"\"\"\n if member is None:\n member = ctx.author\n\n if await self._in_cache(ctx.command, member):\n await ctx.message.add_reaction(self.bot.loading_emoji)\n\n b_io = await self._pull_from_cache(ctx.command, member)\n\n await ctx.send(f\"*0ms*\", file=discord.File(b_io, filename=\"deepfry.png\"))\n\n return await ctx.message.remove_reaction(self.bot.loading_emoji, ctx.me)\n\n await ctx.message.add_reaction(self.bot.loading_emoji)\n\n file, duration, b_io = await self._image_function_on_link(member.avatar_url_as(format=\"jpeg\", size=512),\n self._deepfry)\n\n await self._add_to_cache(ctx.command, member, b_io)\n\n await ctx.send(f\"*{duration}ms*\", file=file)\n\n await ctx.message.remove_reaction(self.bot.loading_emoji, ctx.me)\n\n @commands.command(\n name=\"effect\",\n aliases=[\n \"edit\",\n \"stack\"\n ]\n )\n async def _effect_stack_command(self, ctx, member: discord.Member, *effect_names):\n \"\"\"\n This command allows you to stack multiple image effects, all the effects found in the other commands, \\\non to one image.\n The list of args can be found by replacing the member argument with the command effects. If the member you are \\\ntrying to select uses one of those reserved terms, just tag them or use their user id.\n \"\"\"\n await ctx.message.add_reaction(self.bot.loading_emoji)\n\n effects = []\n\n for effect_name in effect_names:\n effect_name = effect_name.lower()\n\n if effect_name in self.valid_effect_names[\"magic\"]:\n effects.append(self._magic)\n elif effect_name in self.valid_effect_names[\"invert\"]:\n effects.append(self._invert)\n elif effect_name in self.valid_effect_names[\"expand\"]:\n effects.append(self._expand)\n elif effect_name in self.valid_effect_names[\"wasted\"]:\n effects.append(self._wasted)\n elif effect_name in self.valid_effect_names[\"thonk\"]:\n effects.append(self._thonk)\n elif effect_name in self.valid_effect_names[\"deepfry\"]:\n effects.append(self._deepfry)\n else:\n raise commands.BadArgument(\n f\"I couldn't find an effect by the name \\\"{effect_name}\\\". Use effect list for a list of effects\")\n\n non_checked_effects = effects\n effects = []\n\n for i in non_checked_effects:\n if i not in effects:\n effects.append(i)\n\n total_ms = 0\n\n for i, effect in enumerate(effects):\n if i == 0:\n image = await WandImage.from_link(member.avatar_url_as(format=\"png\", size=256))\n b_io, ms, _ = await self._image_function(image, effect)\n image = await WandImage.from_bytes_io(b_io.fp)\n total_ms += ms\n\n file = image.to_discord_file(\"stacked_effects.png\")\n\n await ctx.send(f\"*{total_ms}*\", file=file)\n\n await ctx.message.remove_reaction(self.bot.loading_emoji, ctx.me)\n\n @commands.command(name=\"effects\")\n async def _effect_stack_list_command(self, ctx):\n \"\"\"\n List the effects that can be used in the effect command. All effects are also valid command names.\n \"\"\"\n\n await ctx.send(\n f\"Valid effects are *{', '.join(effect for effect in self.valid_effect_names.keys())}*.\"\n )\n\n\ndef setup(bot):\n bot.add_cog(Imaging(bot))\n","sub_path":"Zane/cogs/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":20029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"180486243","text":"# 实例004:这天第几天\n# 题目 输入某年某月某日,判断这一天是这一年的第几天?\nif __name__ == '__main__':\n # method1\n def date_to_days(date):\n days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n y, m, d = map(int, date.split(\"-\"))\n total = 0\n for i in range(0, m-1):\n total += days[i]\n if (y % 4 == 0 and y % 100 != 0 or y % 400 == 0) and i == 1:\n total += 1\n return total + d\n\n date = input(\"请输入日期,例:2020-10-21:\")\n t = date_to_days(date)\n print(\"{}是这一年的第{}天\".format(date, t))\n","sub_path":"exercise_004.py","file_name":"exercise_004.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"265267314","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# Copyright 2011-2014, cybeliak\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\"\"\" Voice Info DiskRes \"\"\"\n__author__ = \"cybeliak\"\n\nfrom ..lib.common import *\n\nclass VoiceInfo(nz.DiskRes):\n ttype = 'voiceinfo'\n tracked_files = {\n \"param.json\": -1,\n \"wav.scp\": -1,\n \"length.ark.gz\": -1, # Auto\n \"segments\": 1, # Optional\n }\n expected_params = [\"samprate\", \"havesegments\",\n \"nutt\", \"totallen\", \"avglen\"]\n\n def get_cmd_key(self):\n if self.param[\"havesegments\"]:\n return self.get_cmd_seg()\n else:\n return self.get_cmd_scp()\n\n def get_cmd_scp(self):\n if \"cmdscp\" in self.param:\n cmd = self.param[\"cmdscp\"]\n else:\n cmd = \"cat '%s/wav.scp'\" % (self.root)\n if not self.param[\"havesegments\"]:\n cmd = \"%s %s\" % (cmd, self.get_trans())\n return cmd\n\n def get_cmd_seg(self):\n if not self.param[\"havesegments\"]:\n return \"\"\n\n if \"cmdseg\" in self.param:\n cmd = self.param[\"cmdseg\"]\n else:\n cmd = \"cat '%s/segments'\" % (self.root)\n cmd = \"%s %s\" % (cmd, self.get_trans(\"seg\"))\n return cmd\n\n def get_cmd_len(self):\n if \"cmdlen\" in self.param:\n cmd = self.param[\"cmdlen\"]\n else:\n cmd = \"gunzip -c '%s/length.ark.gz'\" % (self.root)\n cmd = \"%s %s\" % (cmd, self.get_trans(target=\"len\"))\n return cmd\n\n def get_trans(self, target=\"scp\"):\n if \"trans%s\" % (target) in self.param:\n trans = self.param[\"trans%s\" % (target)]\n else:\n trans = \"\"\n return trans\n\n def get_aggregator_wav(self):\n if \"cmdwav\" in self.param:\n cmd = self.param[\"cmdwav\"]\n else:\n if self.param[\"havesegments\"]:\n cmd = r\"| extract-segments scp,s,cs:<(%s) - ark:-\" \\\n % (self.get_cmd_scp())\n else:\n cmd = r\"| wav-copy scp,s,cs:- ark:-\"\n return cmd\n\n @nz.hook('post_process')\n def calculate_length(self):\n if op.isfile(self['length.ark.gz']) or hasattr(self, \"is_descriptor\"):\n return\n if self.param[\"havesegments\"]:\n self.pm.run(r\"\"\"#!bash\n %@[r.get_cmd_seg]\n | gawk '{{printf \"%s %.4f\\n\", $1, $4-$3;}}'\n | gzip -nc > %[f.length.ark.gz]\n \"\"\")\n else:\n self.pm.run(r\"\"\"#!bash\n %@[r.get_cmd_scp]\n %@[r.get_aggregator_wav]\n | wav-to-duration ark,o,s,cs:- ark,t:-\n | gzip -nc > %[f.length.ark.gz]\n \"\"\")\n\n @nz.hook('post_process', after=calculate_length)\n def calculate_average(self):\n if hasattr(self, \"is_descriptor\"):\n return\n if 'totallen' not in self.param:\n nutt, totallen = self.pm.getoutput(r\"\"\"#!bash\n %@[r.get_cmd_len]\n | stat_from_length_ark.sh 2\n \"\"\").strip().split(\",\")\n nutt, totallen = int(nutt), float(totallen)\n self.param.update({\n 'nutt': nutt,\n 'totallen': totallen,\n })\n if 'avglen' not in self.param:\n self.param.update({\n 'avglen': self.param[\"totallen\"] / self.param[\"nutt\"],\n })\n\n @nz.hook(\"is_valid\")\n def check_key_ok(self):\n if hasattr(self, \"is_descriptor\"):\n return\n if self.param[\"nutt\"] > 500000: # This will clog up the memory\n return\n if not ag.lib.kaldi.check_key_sorted(self.get_cmd_len(), self.pm):\n raise RuntimeError(\"key mismatch between sorted and unsorted version\")\n if self.param[\"havesegments\"]:\n if not ag.lib.kaldi.check_key_match(self.get_cmd_len(), self.get_cmd_seg(), self.pm):\n raise RuntimeError(\"key mismatch between length.ark and segments\")\n else:\n if not ag.lib.kaldi.check_key_match(self.get_cmd_len(), self.get_cmd_scp(), self.pm):\n raise RuntimeError(\"key mismatch between length.ark and wav.scp\")\n\nclass VoiceDescriptor(VoiceInfo, nzbuiltin.DescriptorBase):\n ttype = 'voiceinfo'\n expected_params = [\"samprate\", \"havesegments\", \"nutt\"] + [\"cmdscp\", \"cmdseg\", \"cmdlen\", \"transscp\", \"transseg\", \"translen\"]\n tracked_files = {\n \"param.json\": 2, # Required, but not going to do chksum\n }\n\n @nz.hook('post_process', before=VoiceInfo.calculate_length)\n def merge_cmds(self):\n for key in (\"cmdscp\", \"cmdlen\", \"cmdseg\"):\n self.param[key] = ag.lib.kaldi.merge_commands(self.param[key], \"gunzip -c\")\n self.param[key] = ag.lib.kaldi.merge_commands(self.param[key], \"cat\")\n","sub_path":"AsiyahGashmi/things/voice_info.py","file_name":"voice_info.py","file_ext":"py","file_size_in_byte":5349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"63012738","text":"import tempfile\nfrom unittest import mock\n\nfrom airline_demo.pipelines import local_parquet_io_manager\nfrom airline_demo.resources import DbInfo\nfrom airline_demo.solids import load_data_to_database_from_spark\nfrom dagster import (\n ModeDefinition,\n OutputDefinition,\n ResourceDefinition,\n execute_pipeline,\n fs_io_manager,\n pipeline,\n solid,\n)\nfrom dagster.core.definitions.no_step_launcher import no_step_launcher\nfrom dagster.utils import file_relative_path\nfrom dagster_pyspark import pyspark_resource\n\n\ndef test_airline_demo_load_df():\n db_info_mock = DbInfo(\n engine=mock.MagicMock(),\n url=\"url\",\n jdbc_url=\"url\",\n dialect=\"dialect\",\n load_table=mock.MagicMock(),\n host=\"host\",\n db_name=\"db_name\",\n )\n\n @solid(\n required_resource_keys={\"pyspark\"},\n output_defs=[OutputDefinition(io_manager_key=\"pyspark_io_manager\")],\n )\n def emit_mock(context):\n return context.resources.pyspark.spark_session.read.csv(\n file_relative_path(__file__, \"../data/test.csv\")\n )\n\n @pipeline(\n mode_defs=[\n ModeDefinition(\n resource_defs={\n \"db_info\": ResourceDefinition.hardcoded_resource(db_info_mock),\n \"pyspark\": pyspark_resource,\n \"pyspark_step_launcher\": no_step_launcher,\n \"pyspark_io_manager\": local_parquet_io_manager,\n \"io_manager\": fs_io_manager,\n }\n )\n ]\n )\n def load_df_test():\n load_data_to_database_from_spark(emit_mock())\n\n with tempfile.TemporaryDirectory() as temp_dir:\n solid_result = execute_pipeline(\n load_df_test,\n run_config={\n \"solids\": {\"load_data_to_database_from_spark\": {\"config\": {\"table_name\": \"foo\"}}},\n \"resources\": {\n \"io_manager\": {\"config\": {\"base_dir\": temp_dir}},\n \"pyspark_io_manager\": {\"config\": {\"base_dir\": temp_dir}},\n },\n },\n ).result_for_solid(\"load_data_to_database_from_spark\")\n\n assert solid_result.success\n mats = solid_result.materializations_during_compute\n assert len(mats) == 1\n mat = mats[0]\n assert len(mat.metadata_entries) == 2\n entries = {me.label: me for me in mat.metadata_entries}\n assert entries[\"Host\"].entry_data.text == \"host\"\n assert entries[\"Db\"].entry_data.text == \"db_name\"\n","sub_path":"examples/airline_demo/airline_demo_tests/unit_tests/test_load_data_from_spark.py","file_name":"test_load_data_from_spark.py","file_ext":"py","file_size_in_byte":2516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"21370699","text":"# coding=utf-8\nimport random\nimport sys\nfrom importlib import reload\n\nfrom framework.file.file_driver import load_json_file\nfrom games.settings import path_to_cities_json\n\nreload(sys)\n# sys.setdefaultencoding('utf8')\n\n\nclass Goroda:\n def __init__(self):\n self.previous_cities_list = []\n self.cities_list = load_json_file(path_to_cities_json)\n\n @staticmethod\n def start_play():\n rules = u\"Кратикие правила:\\n\" \\\n u\"Если захочешь сдаться напиши \\\"Сдаюсь\\\"\\n\" \\\n u\"Для просмотра истории городов напиши \\\"Ис��ория\\\"\\n\"\n start_message = u\"{border}Готов к игре, сегодня играем в Города.\\n\" \\\n u\"{border}{rules}{border}\" \\\n u\"Что ж, рискни смельчак!!!\\n\" \\\n u\"Гость начинает и проигрывает:\\n\".format(border=u'***********************\\n', rules=rules)\n return start_message\n\n def my_turn(self, opponent_city):\n my_city = self.get_city(opponent_city)\n if not my_city:\n return False, u\"Мои поздравления, ты выиграл!!!!\"\n else:\n self.previous_cities_list.append(my_city)\n return True, u\"Мой ход - {}\\nТвой ход, человек:\".format(my_city)\n\n def check_enemy_turn(self, opponent_city):\n\n if opponent_city == u\"Сдаюсь\":\n return 2, u\"Вухахахахаха, лузер!!!\"\n\n if opponent_city == u\"История\":\n return self._get_game_history()\n\n if not self.previous_cities_list:\n return self._check_city_in_city_list(opponent_city)\n\n previous_city = self.previous_cities_list[-1]\n check, answer = self.check_city(opponent_city, previous_city)\n if check:\n self.previous_cities_list.append(opponent_city)\n\n return check, answer\n\n def _get_game_history(self):\n history = u\"\"\n if self.previous_cities_list:\n history += u\"Вот лог нашей игры:\\n----------------------\\n\"\n for loop, city in enumerate(self.previous_cities_list):\n history_item = u\"Мегамашина: - {}\\n\" if loop % 2 == 0 else u\"Человек: - {}\\n\"\n history += history_item.format(city)\n history += u\"----------------------\"\n return False, history\n\n def get_random_city(self):\n key = random.choice(self.cities_list.keys())\n city = random.choice(self.cities_list[key])\n self.cities_list[key].remove(city)\n return city\n\n def get_city(self, previous_city_name):\n last_letter = self.get_last_letter(previous_city_name)\n cities = self.cities_list[unicode(last_letter)]\n if not cities:\n return None\n city = random.choice(cities)\n cities.remove(city)\n self.cities_list[unicode(last_letter)] = cities\n return city\n\n def check_city(self, city_name, previous_city):\n start_letter = unicode(city_name)[:1].upper()\n previous_city_letter = self.get_last_letter(previous_city)\n answer = u\"\"\n if start_letter == previous_city_letter:\n if city_name in self.previous_cities_list:\n answer += u\"Этот город уже был, тебе город на \\'{}\\'\".format(previous_city_letter)\n answer += u\"для вывода списка городов напиши \\'История\\'\"\n return False, answer\n return self._check_city_in_city_list(city_name)\n else:\n return False, u\"Этот город не подходит, тебе город на \\\"{}\\\"\".format(previous_city_letter)\n\n def _check_city_in_city_list(self, city):\n start_letter = unicode(city)[:1].upper()\n cities = self.cities_list[unicode(start_letter)]\n if city in cities:\n cities.remove(city)\n self.cities_list[start_letter] = cities\n return True, u\"Ваш город подходит!\\n\"\n else:\n return False, u'Я незнаю такого города, попробуй другой'\n\n @staticmethod\n def get_last_letter(city_name):\n last_letter = unicode(city_name)[-1:].upper()\n\n if last_letter == u'Ё':\n last_letter = u'Е'\n elif last_letter == u'Й':\n last_letter = u'И'\n elif last_letter == u'Ь':\n last_letter = unicode(city_name)[-2::2].upper()\n elif last_letter == u'Ы':\n last_letter = unicode(city_name)[-2::2].upper()\n\n return last_letter\n\n # def run_game(self):\n # my_city = self.get_random_city()\n #\n # output_message = u''\n #\n # print u\"начнем с {}\".format(my_city)\n # output_message += u\"Твой ход:\\n\"\n # while True:\n # if my_city not in self.previous_cities_list:\n # self.previous_cities_list.append(my_city)\n #\n # opponent_city = raw_input()\n #\n # if opponent_city == u\"Сдаюсь\":\n # print u\"Вухахахахаха, лузер!!!\"\n # return None\n #\n # if opponent_city == u\"История\":\n # print u\"Вот лог нашей игры:\\n----------------------\"\n # s = u\"\"\n # for loop, city in enumerate(self.previous_cities_list):\n # usr = u\"Мегамашина: - {}\\n\" if loop % 2 == 0 else u\"Человек: - {}\\n\"\n # s += usr.format(city)\n # print s + u\"----------------------\"\n # return None\n #\n # check = self.check_city(opponent_city, my_city)\n # if check:\n # self.previous_cities_list.append(opponent_city)\n # my_city = self.get_city(opponent_city)\n # if not my_city:\n # print u\"Мои поздравления, ты выиграл!!!!\"\n # print u\"Принимается, тогда мой ход - {}\\nТвой ход, человек:\".format(my_city)\n # else:\n # print u\"Такого говорда нету, попробуй еще раз\"\n#\n# if __name__ == \"__main__\":\n# rv = Goroda()\n# rv.start_play()\n","sub_path":"games/goroda.py","file_name":"goroda.py","file_ext":"py","file_size_in_byte":6596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"438166320","text":"from elapsedtimer import ElapsedTimer\nfrom urllib.parse import urlparse\nimport warnings\nimport asyncio\nimport aiohttp\nimport sys, os\nfrom pathlib import Path\nimport importlib.util\n\nmodule_spec = importlib.util.spec_from_file_location(\n'Importing', str(Path(__file__).parent)+'/Importing.py'\n\t)\nobj_module = importlib.util.module_from_spec(module_spec)\nmodule_spec.loader.exec_module(obj_module)\nImport=obj_module.Import\n\ndef main():\n\t'''\n\tThe @Import decorator allows you to pass a \n\tdictionary with modules to the \"modules\" parameter \n\tof the \"def main(modules)\" function'''\n\t@Import\n\tdef Main(modules):\n\n\t\twarnings.filterwarnings(\"ignore\", category=RuntimeWarning)\n\n\t\t'''\n\t\tBefore you can !run a module! using its !specification!, \n\t\tyou must create a reference to it in the form of a variable.'''\n\t\tSearch=modules['Search'].Search\n\t\tGraph_parse=modules['Graph'].Graph_parse\n\t\tInput=modules['Input'].Input\n\t\tResults=modules['Results'].Results\n\t\tWelcome=modules['Welcome'].Welcome\n\t\t\n\t\t'''\n\t\tThis function(Welcome) imports the greeting - program logo, \n\t\tand also includes support for the ANSI standard for output \n\t\tin the running Windows/Linux console.'''\n\t\tWelcome()\n\n\t\t'''\n\t\tUsed for user input, links, and specific parameters.'''\n\t\tDict_values=Input()\n\n\t\t# URL for our web-crawler.\n\t\tURL=Dict_values['url']\n\t\t\n\t\tPath_directory=None\n\n\t\tif 'Path' in Dict_values:\n\t\t\tPath_directory=Dict_values['Path']\n\n\t\tobj1=Search(URL,Path_directory)\n\t\tobj1.Lis_foun_lin.append((obj1.Base_URL,'get'))\n\n\t\t# The main branch of the program.\n\t\tasync def run_coroutines():\n\n\t\t\tnonlocal obj1\n\n\t\t\ttasks=[]\n\n\t\t\twork_queue = asyncio.Queue()\n\n\t\t\tfor link in obj1.Lis_foun_lin:\n\n\t\t\t\tawait work_queue.put(link)\n\n\t\t\t\ttask = asyncio.ensure_future(\n\n\t\t\t\t\tobj1.searching_links(work_queue)\n\t\t\t\t)\n\n\t\t\t\ttasks.append(task)\n\n\t\t\t\tfor i in tasks:\n\n\t\t\t\t\tawait i\n\t\t\t\t\n\t\ttry:\n\t\t\tet=ElapsedTimer()\n\t\t\t\n\t\t\tet.start()\n\t\t\tloop_2=asyncio.get_event_loop()\n\t\t\tloop_2.run_until_complete(run_coroutines())\n\t\t\tet.stop()\n\n\t\t\tobj1.Create_Sitemap()\n\t\t\tobj1.Map.Site_map_close()\n\t\t\tcounter=obj1.get_counter()\n\t\t\tResults(counter, et.elapsed, obj1.Netloc, obj1.Map.Path_File_XML)\n\t\t\tgraph=Graph_parse(obj1.Netloc, obj1.All_links, Dict_values)\n\t\t\t\n\t\texcept KeyboardInterrupt:\n\t\t\tet.stop()\n\t\t\tobj1.Create_Sitemap()\n\t\t\tobj1.Map.Site_map_close()\n\t\t\tprint('\\n\\n\\033[38;5;196mStop execution, exit the program.\\033[0m')\n\t\t\tcounter=obj1.get_counter()\n\t\t\tResults(counter,et.elapsed,obj1.Netloc,obj1.Map.Path_File_XML)\t\t\n\t\t\tgraph=Graph_parse(obj1.Netloc,obj1.All_links,Dict_values)\n\t\t\tsys.exit(0)\n\n\t\texcept aiohttp.client_exceptions.ClientPayloadError as error:\n\t\t\tprint('\\n\\n\\033[31mThe program was interrupted by an error.\\033[0m')\n\t\t\tprint(f'\\n\\n\\033[38;5;{error}\\033[0m')\n\t\t\tsys.exit(0)\n\t\t\t\t\n\t\texcept OSError as os_error:\n\t\t\tprint(f'\\n\\033[38;5;196m{os_error}\\033[0m')\n\n\t\texcept ConnectionResetError as connect_error:\n\t\t\tprint(f'\\n\\033[38;5;196m{connect_error}')\n\n\t\texcept aiohttp.client_exceptions.ClientConnectorError as aio_error:\n\t\t\tprint(f'\\n\\033[38;5;196m{aio_error}\\033[0m')\n\n\t\texcept SystemExit:\n\t\t\tsys.exit(0)\n\n\t\nif __name__ == '__main__':\n\tmain()\n","sub_path":"src/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":3098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"403177650","text":"import json\r\nimport shelve\r\nimport numpy as np\r\n\r\nclass Network(object):\r\n\r\n def __init__(self, sizes):\r\n \"\"\"The list ``sizes`` contains the number of neurons in the\r\n respective layers of the network. For example, if the list\r\n was [2, 3, 1] then it would be a three-layer network, with the\r\n first layer containing 2 neurons, the second layer 3 neurons,\r\n and the third layer 1 neuron. The biases and weights for the\r\n network are initialized randomly, using a Gaussian\r\n distribution with mean 0, and variance 1. Note that the first\r\n layer is assumed to be an input layer, and by convention we\r\n won't set any biases for those neurons, since biases are only\r\n ever used in computing the outputs from later layers.\"\"\"\r\n self.num_layers = len(sizes)\r\n self.sizes = sizes\r\n self.biases = [np.random.randn(y, 1) for y in sizes[1:]]\r\n self.weights = [np.random.randn(y, x)\r\n for x, y in zip(sizes[:-1], sizes[1:])]\r\n\r\n def feedforward(self, a):\r\n \"\"\"Return the output of the network if ``a`` is input.\"\"\"\r\n for b, w in zip(self.biases, self.weights):\r\n a = sigmoid(np.dot(w, a)+b)\r\n return a\r\n\r\n def SGD(self, training_data, epochs, mini_batch_size, eta,\r\n test_data=None):\r\n \"\"\"Train the neural network using mini-batch stochastic\r\n gradient descent. The ``training_data`` is a list of tuples\r\n ``(x, y)`` representing the training inputs and the desired\r\n outputs. The other non-optional parameters are\r\n self-explanatory. If ``test_data`` is provided then the\r\n network will be evaluated against the test data after each\r\n epoch, and partial progress printed out. This is useful for\r\n tracking progress, but slows things down substantially.\"\"\"\r\n if test_data: n_test = len(test_data)\r\n n = len(training_data)\r\n for j in range(epochs):\r\n random.shuffle(training_data)\r\n mini_batches = [\r\n training_data[k:k+mini_batch_size]\r\n for k in range(0, n, mini_batch_size)]\r\n for mini_batch in mini_batches:\r\n self.update_mini_batch(mini_batch, eta)\r\n if test_data:\r\n print (\"Epoch {0}: {1} / {2}\".format(\r\n j, self.evaluate(test_data), n_test))\r\n else:\r\n print (\"Epoch {0} complete\".format(j))\r\n import shelve\r\n learning_results = shelve.open('../output')\r\n learning_results['weight_end'] = [i for i in self.weights]\r\n learning_results['bias_end'] = [i for i in self.biases]\r\n learning_results.close()\r\n\r\n\r\n def update_mini_batch(self, mini_batch, eta):\r\n \"\"\"Update the network's weights and biases by applying\r\n gradient descent using backpropagation to a single mini batch.\r\n The ``mini_batch`` is a list of tuples ``(x, y)``, and ``eta``\r\n is the learning rate.\"\"\"\r\n nabla_b = [np.zeros(b.shape) for b in self.biases]\r\n nabla_w = [np.zeros(w.shape) for w in self.weights]\r\n for x, y in mini_batch:\r\n delta_nabla_b, delta_nabla_w = self.backprop(x, y)\r\n nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]\r\n nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)]\r\n self.weights = [w-(eta/len(mini_batch))*nw\r\n for w, nw in zip(self.weights, nabla_w)]\r\n self.biases = [b-(eta/len(mini_batch))*nb\r\n for b, nb in zip(self.biases, nabla_b)]\r\n\r\n def backprop(self, x, y):\r\n \"\"\"Return a tuple ``(nabla_b, nabla_w)`` representing the\r\n gradient for the cost function C_x. ``nabla_b`` and\r\n ``nabla_w`` are layer-by-layer lists of numpy arrays, similar\r\n to ``self.biases`` and ``self.weights``.\"\"\"\r\n nabla_b = [np.zeros(b.shape) for b in self.biases]\r\n nabla_w = [np.zeros(w.shape) for w in self.weights]\r\n # feedforward\r\n activation = x\r\n activations = [x] # list to store all the activations, layer by layer\r\n zs = [] # list to store all the z vectors, layer by layer\r\n for b, w in zip(self.biases, self.weights):\r\n z = np.dot(w, activation)+b\r\n zs.append(z)\r\n activation = sigmoid(z)\r\n activations.append(activation)\r\n # backward pass\r\n delta = self.cost_derivative(activations[-1], y) * \\\r\n sigmoid_prime(zs[-1])\r\n nabla_b[-1] = delta\r\n nabla_w[-1] = np.dot(delta, activations[-2].transpose())\r\n # Note that the variable l in the loop below is used a little\r\n # differently to the notation in Chapter 2 of the book. Here,\r\n # l = 1 means the last layer of neurons, l = 2 is the\r\n # second-last layer, and so on. It's a renumbering of the\r\n # scheme in the book, used here to take advantage of the fact\r\n # that Python can use negative indices in lists.\r\n for l in range(2, self.num_layers):\r\n z = zs[-l]\r\n sp = sigmoid_prime(z)\r\n delta = np.dot(self.weights[-l+1].transpose(), delta) * sp\r\n nabla_b[-l] = delta\r\n nabla_w[-l] = np.dot(delta, activations[-l-1].transpose())\r\n return (nabla_b, nabla_w)\r\n\r\n def evaluate(self, test_data):\r\n \"\"\"Return the number of test inputs for which the neural\r\n network outputs the correct result. Note that the neural\r\n network's output is assumed to be the index of whichever\r\n neuron in the final layer has the highest activation.\"\"\"\r\n test_results = [(np.argmax(self.feedforward(x)), y)\r\n for (x, y) in test_data]\r\n return sum(int(x == y) for (x, y) in test_results)\r\n\r\n def cost_derivative(self, output_activations, y):\r\n \"\"\"Return the vector of partial derivatives \\partial C_x /\r\n \\partial a for the output activations.\"\"\"\r\n return (output_activations-y)\r\n\r\n#### Miscellaneous functions\r\ndef sigmoid(z):\r\n \"\"\"The sigmoid function.\"\"\"\r\n return 1.0/(1.0+np.exp(-z))\r\n\r\ndef sigmoid_prime(z):\r\n \"\"\"Derivative of the sigmoid function.\"\"\"\r\n return sigmoid(z)*(1-sigmoid(z))\r\ndef procstep(grid,color_num,action):\r\n x0 = action['x0']\r\n y0 = action['y0']\r\n x1 = action['x1']\r\n y1 = action['y1']\r\n if x0<0:\r\n return 0\r\n grid[x1][y1] = color_num\r\n if abs(x0-x1)>1 or abs(y0-y1)>1:\r\n grid[x0][y0] = 0\r\n for i in range(-1,2):\r\n for j in range(-1,2):\r\n if (i==0 and j==0) or x1+i<0 or x1+i>6 or y1+j<0 or y1+j>6:\r\n continue\r\n if grid[x1+i][y1+j] == -color_num:\r\n grid[x1+i][y1+j] = color_num\r\n\r\ndef action_pos():\r\n count = 0\r\n action_pos_dict = {}\r\n for i in range(7):\r\n for j in range(7):\r\n for a in range(-2,3):\r\n for b in range(-2,3):\r\n if (a==0 and b==0) or i+a<0 or i+a>=7 or j+b<0 or j+b>=7:\r\n continue\r\n action = {}\r\n action['x0'] = i+a\r\n action['y0'] = j+b\r\n action['x1'] = i\r\n action['y1'] = j\r\n action_pos_dict[count] = action\r\n count += 1\r\n return action_pos_dict\r\n\r\n\r\n\r\n\r\nstring = json.loads(input())\r\nresponses = string['responses']\r\nrequests = string['requests']\r\nif requests[0]['x0'] < 0:\r\n botColor = 1\r\n #netData = shelve.open('./data/blackData')\r\n netData = shelve.open('E:/blackData')\r\nelse:\r\n botColor = -1\r\n #netData = shelve.open('./data/whiteData')\r\n netData = shelve.open('E:/whiteData')\r\n\r\nnetWork = Network([49, 100, 200, 792])\r\nnetWork.weights = netData['weights']\r\nnetWork.biases = netData['biaes']\r\nstate = np.zeros((7,7))\r\nstate[0][0],state[6][6],state[0][6],state[6][0] = 1,1,-1,-1\r\nfor op1, op2 in zip(requests,responses):\r\n procstep(state,-botColor,op1)\r\n procstep(state,botColor,op2)\r\nprocstep(state,-botColor,requests.pop())\r\nprint(state)\r\ninputArray = state.reshape((49,1)).copy()\r\noutArray = netWork.feedforward(inputArray)\r\naction_pos_dict = action_pos()\r\nbestValue = -10000.0\r\nret = {}\r\nfor i in range(len(action_pos_dict)):\r\n action = action_pos_dict[i]\r\n x0 = action['x0']\r\n y0 = action['y0']\r\n x1 = action['x1']\r\n y1 = action['y1']\r\n if state[x0][y0] == botColor and state[x1][y1] == 0:\r\n value = outArray[i][0]\r\n if value > bestValue:\r\n bestValue = value\r\n ret['response'] = action\r\nret['debug'] = bestValue\r\nout = json.dumps(ret)\r\nprint(out)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"test for botzone.py","file_name":"test for botzone.py","file_ext":"py","file_size_in_byte":8698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"342263900","text":"\"\"\" Code for loading data. \"\"\"\nimport numpy as np\nimport os\nimport random\nimport tensorflow as tf\n\nfrom tensorflow.python.platform import flags\nfrom utils import get_images\nimport scipy.io as sio\n\nFLAGS = flags.FLAGS\n\nclass DataGenerator(object):\n \"\"\"\n Data Generator capable of generating batches of sinusoid or Omniglot data.\n A \"class\" is considered a class of omniglot digits or a particular sinusoid function.\n \"\"\"\n def __init__(self, num_samples_per_class, batch_size, datasource, rect_truncated=False, config={}):\n \"\"\"\n Args:\n num_samples_per_class: num samples to generate per class in one batch\n batch_size: size of meta batch size (e.g. number of functions)\n \"\"\"\n self.batch_size = batch_size\n self.num_samples_per_class = num_samples_per_class\n self.num_classes = 1 # by default 1 (only relevant for classification problems)\n self.rect_truncated = rect_truncated\n self.testing_size = 100\n if datasource == 'sinusoid':\n self.amp_range = config.get('amp_range', [0.1, 5.0])\n self.phase_range = config.get('phase_range', [0, np.pi])\n self.input_range = config.get('input_range', [-5.0, 5.0])\n self.dim_input = 1\n self.dim_output = 1\n self.generate = self.generate_sinusoid_batch\n elif datasource == 'ball':\n # 'm1': m1, 'm2': m2, 'cr': cr\n self.m_range = config.get('m_range', [1.0, 10.0]) # m1 and m2\n self.cr_range = config.get('cr_range', [0.0, 1.0])\n self.vel_range = config.get('vel_range', [-10.0, 10.0]) # range of input velocity\n self.N_range = config.get('N_range', [1.0, 10.0]) # range of input radius (ball sizes)\n self.dim_input = 6\n self.dim_output = 4\n self.generate = self.generate_ball_batch\n elif datasource == 'ball_file':\n # 'm1': m1, 'm2': m2, 'cr': cr\n self.dim_input = 14\n self.dim_output = 4\n self.generate = self.generate_training_ball_from_file\n self.generate_test = self.generate_testing_ball_from_file\n self.ball_generator = self.ball_file_generator(batch_size)\n self.mat_contents = sio.loadmat('training_circles_v1.mat')\n self.num_total_task = 5000\n self.input_data = np.transpose(self.mat_contents['In']).reshape((self.num_total_task, 40, 14))\n self.output_data = np.transpose(self.mat_contents['Out']).reshape((self.num_total_task, 40, 4))\n self.meta_data = np.transpose(self.mat_contents['Meta']).reshape((self.num_total_task, 40, 3))\n elif datasource == 'rect_file':\n # 'm1': m1, 'm2': m2, 'cr': cr\n\n self.generate = self.generate_ball_from_rect\n self.rect_generator = self.rect_file_generator(batch_size)\n self.mat_contents = sio.loadmat('training_rects_v2.mat')\n self.num_total_task = 10000\n\n self.input_data = np.transpose(self.mat_contents['In']).reshape((self.num_total_task, 50, 16))\n self.output_data = np.transpose(self.mat_contents['Out']).reshape((self.num_total_task, 50, 6))\n self.meta_data = np.transpose(self.mat_contents['Meta']).reshape((self.num_total_task, 50, 3))\n if self.rect_truncated:\n self.input_data = np.delete(self.input_data, [12, 13, 14, 15], axis=2)\n self.output_data = np.delete(self.output_data, [0, 3], axis=2)\n self.dim_output = 4\n self.dim_input = 12\n else:\n self.dim_output = 6\n self.dim_input = 16\n\n else:\n raise ValueError('Unrecognized data source')\n\n def generate_sinusoid_batch(self, train=True, input_idx=None):\n # Note train arg is not used (but it is used for omniglot method.\n # input_idx is used during qualitative testing --the number of examples used for the grad update\n amp = np.random.uniform(self.amp_range[0], self.amp_range[1], [self.batch_size])\n phase = np.random.uniform(self.phase_range[0], self.phase_range[1], [self.batch_size])\n outputs = np.zeros([self.batch_size, self.num_samples_per_class, self.dim_output])\n init_inputs = np.zeros([self.batch_size, self.num_samples_per_class, self.dim_input])\n for func in range(self.batch_size):\n init_inputs[func] = np.random.uniform(self.input_range[0], self.input_range[1], [self.num_samples_per_class, 1])\n if input_idx is not None:\n init_inputs[:,input_idx:,0] = np.linspace(self.input_range[0], self.input_range[1], num=self.num_samples_per_class-input_idx, retstep=False)\n outputs[func] = amp[func] * np.sin(init_inputs[func]-phase[func])\n return init_inputs, outputs#, amp, phase\n\n def generate_ball_batch(self, m1=None, m2=None, cr=None, N_norm=None, batch_size=None, num_samples_per_class=None):\n # Note train arg is not used.\n\n if not batch_size: batch_size = self.batch_size\n if not num_samples_per_class: num_samples_per_class = self.num_samples_per_class\n\n xs = np.zeros([batch_size, num_samples_per_class, self.dim_input])\n ys = np.zeros([batch_size, num_samples_per_class, self.dim_output])\n\n\n for i in range(batch_size):\n self.g_batch(m1, m2, cr, N_norm, batch_size, num_samples_per_class, xs, ys, i)\n return xs, ys\n\n\n def g_batch(self,m1, m2, cr, N_norm, batch_size, num_samples_per_class, xs, ys, i):\n # for each task (different m1, m2, cr (coefficient of restitution))\n if m1 is None: m1 = np.random.uniform(self.m_range[0], self.m_range[1])\n if m2 is None: m2 = np.random.uniform(self.m_range[0], self.m_range[1])\n if cr is None: cr = np.random.uniform(self.cr_range[0], self.cr_range[1])\n if N_norm is None: N_norm = np.random.uniform(self.N_range[0], self.N_range[1])\n\n for j in range(num_samples_per_class):\n u1 = np.random.uniform(self.vel_range[0], self.vel_range[1], (2, 1))\n u2 = np.random.uniform(self.vel_range[0], self.vel_range[1], (2, 1))\n\n theta_N = np.random.rand() * 2 * np.pi\n Nx = N_norm * np.cos(theta_N)\n Ny = N_norm * np.sin(theta_N)\n\n # J is the transform from standard 2D coordinate to the coordinate where +x-axis is N direction\n # i.e., J will transform standard v vector to (v_normal, v_tangential)\n J = np.array([[np.cos(theta_N), np.sin(theta_N)], [-np.sin(theta_N), np.cos(theta_N)]])\n Ju1 = J.dot(u1)\n Ju2 = J.dot(u2)\n (u1N, u1T) = tuple(Ju1)\n (u2N, u2T) = tuple(Ju2)\n\n if u1N - u2N <= 0:\n v1N = u1N\n v2N = u2N\n else:\n v1N = (m1 * u1N + m2 * u2N + m2 * cr * (u2N - u1N)) / (m1 + m2)\n v2N = (m1 * u1N + m2 * u2N + m1 * cr * (u1N - u2N)) / (m1 + m2)\n\n # transform back to standard coordinate\n v1 = J.T.dot(np.array([v1N, u1T]).reshape(-1, 1))\n v2 = J.T.dot(np.array([v2N, u2T]).reshape(-1, 1))\n\n cur_x = np.concatenate((u1.reshape(-1), u2.reshape(-1), np.array([Nx, Ny])))\n xs[i, j, :] = cur_x\n cur_y = np.concatenate((v1.reshape(-1), v2.reshape(-1)))\n ys[i, j, :] = cur_y\n\n def ball_file_generator(self, num_task):\n num_train_total_tasks = self.num_total_task - self.testing_size\n ind_array = np.arange(0, num_train_total_tasks, 1)\n\n current_i = 0\n while 1:\n if current_i + num_task > num_train_total_tasks:\n np.random.shuffle(ind_array)\n current_i = 0\n\n batch_indexes = ind_array[current_i:current_i + num_task]\n current_i = current_i + num_task\n yield (self.input_data[batch_indexes], self.output_data[batch_indexes],\n self.meta_data[batch_indexes])\n\n def rect_file_generator(self, num_task):\n\n num_train_total_tasks = self.num_total_task - self.testing_size\n ind_array = np.arange(0, num_train_total_tasks, 1)\n current_i = 0\n while 1:\n if current_i + num_task > num_train_total_tasks:\n np.random.shuffle(ind_array)\n current_i = 0\n\n batch_indexes = ind_array[current_i:current_i + num_task]\n current_i = current_i + num_task\n\n yield (self.input_data[batch_indexes], self.output_data[batch_indexes],\n self.meta_data[batch_indexes])\n\n def generate_training_ball_from_file(self):\n return next(self.ball_generator)\n\n def generate_testing_ball_from_file(self):\n # index = np.random.choice(range(self.num_total_task - self.testing_size,\n # self.num_total_task), 1)\n # return self.input_data[index], self.output_data[index], self.meta_data[index]\n index = np.random.choice(range(0,\n self.num_total_task-self.testing_size), 1)\n return self.input_data[index], self.output_data[index], self.meta_data[index]\n\n def generate_ball_from_rect(self):\n return next(self.rect_generator)\n\n def generate_testing_rect_from_file(self):\n index = np.random.choice(range(self.num_total_task - self.testing_size,\n self.num_total_task), 1)\n return self.input_data[index], self.output_data[index], self.meta_data[index]\n","sub_path":"dg.py","file_name":"dg.py","file_ext":"py","file_size_in_byte":9539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"560814895","text":"\"\"\"\nReferences:\n https://github.com/lohriialo/photoshop-scripting-python/blob/master/ActiveLayer.py\n\n\"\"\"\nimport photoshop as ps\n\napp = ps.Application()\n\nif len(app.documents) < 1:\n docRef = app.documents.add()\nelse:\n docRef = app.activeDocument\n\nif len(docRef.layers) < 2:\n docRef.artLayers.add()\n\nactiveLayerName = docRef.activeLayer.name\nSetLayerName = ''\nif docRef.activeLayer.name != app.activeDocument.layers.item(len(docRef.layers)).name:\n docRef.activeLayer = docRef.layers.item(len(docRef.layers))\nelse:\n docRef.activeLayer = docRef.layers.item(1)\n","sub_path":"examples/set_active_layer.py","file_name":"set_active_layer.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"590994200","text":"from utils.decoration import watcher\n\nswitch = False\n\n\n@watcher(switch=switch)\ndef count_common_parts_num(modules_a, modules_b):\n \"\"\"\n count the number of pairs simultaneously joined together\n :param modules_a: dict\n :param modules_b: dict\n :return: float\n \"\"\"\n result = 0\n\n for a_module in modules_a.values():\n for b_module in modules_b.values():\n intersection_length = len(a_module.intersection(b_module))\n if intersection_length > 1:\n result += intersection_length * (intersection_length - 1) / 2\n return result\n\n\n@watcher(switch=switch)\ndef count_combinations(module=None, modules=None):\n \"\"\"\n count combinations of module or modules\n :param module: set\n :param modules: dict\n :return: float\n \"\"\"\n assert isinstance(module, set) or isinstance(modules, dict)\n result = 0\n\n if module:\n length = len(module)\n result = length * (length - 1) / 2\n else:\n for module in modules.values():\n length = len(module)\n result += length * (length - 1) / 2\n\n return result\n\n\n@watcher(switch=switch)\ndef count_Jaccard_index(modules_a, modules_b):\n \"\"\"\n count Jaccard index of modules_a and modules_b\n :param modules_a: dict\n :param modules_b: dict\n :return: float\n \"\"\"\n r = count_common_parts_num(modules_a, modules_b)\n u_v_2r = count_combinations(modules=modules_a) + count_combinations(modules=modules_b)\n\n return r / (u_v_2r - r)\n\n\nif __name__ == '__main__':\n pass\n # import networkx as nx\n #\n # graph = nx.karate_club_graph()\n #\n # a_modules = {0: {0, 1, 2, 3, 7, 9, 11, 12, 13, 17, 19, 21}, 1: {4, 5, 6, 10, 16},\n # 2: {8, 14, 15, 18, 20, 22, 23, 26, 27, 29, 30, 32, 33}, 3: {24, 25, 28, 31}}\n # b_modules = {0: {0, 1, 3, 7, 12, 13, 17, 19, 21}, 1: {2, 24, 25, 27, 28, 31}, 2: {4, 5, 6, 10, 16},\n # 3: {32, 33, 8, 14, 15, 18, 20, 22, 23, 26, 29, 30}, 4: {9}, 5: {11}}\n #\n # # print(count_semblance(a_modules, b_modules))\n # # The result should be: 118.0, 287.0 and 0.6982248520710059\n # print(count_Jaccard_index(a_modules, b_modules))\n","sub_path":"algorithm/similarity/similarity.py","file_name":"similarity.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"307941036","text":"from flask import Flask, request, jsonify, Response\n\napp = Flask(__name__)\n@app.route(\"/\")\n\ndef testView():\n ret = '{\"data\": \"JSON string example\"}'\n\n resp = Response(response=ret,\n status=200,\n mimetype=\"application/json\")\n\n return resp\n\napp.run(host= '0.0.0.0')\n","sub_path":"foo.py","file_name":"foo.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"206900847","text":"#!/usr/bin/python\n\nimport sys\n\n'''\nMapper de MaxTemp\nRealizado por Javier Galvez\n'''\n\n# Para cada medida recibida calculamos los pares <anyo, temperatura>\nfor linea in sys.stdin:\n linea = linea.strip()\n anyo , mes , temp = linea.split(\"-\", 2)\n print(\"%s-%s\\t%s\" % (anyo, mes, temp) )\n","sub_path":"Unidad2/Hadoop/Ejemplos/3.TempMaxMonth/mapper.py","file_name":"mapper.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"584283695","text":"#!/usr/bin/env python\nfrom flask import Flask, abort, session, request, url_for, flash, render_template, jsonify, Response, get_flashed_messages, Markup\nfrom flask.ext.session import Session\nfrom uuid import uuid4\nfrom api_classes import Organization\nfrom api_classes import Buildings\nfrom api_classes import Meters\nfrom api_classes import get_authorization_url\nfrom api_classes import get_access_token\nfrom bos_credentials import get_bos_cradentials\n#from api_classes import MtrData\nfrom pandas import DataFrame\nimport datetime\nimport requests\nimport pprint\nimport requests.auth\n\nimport json\nimport pygal\nimport sys\nimport re\n\n#-------------------------Client OAuth Credentials---------------------\n\n\n\n\napp = Flask(__name__)\n@app.route('/')\ndef homepage():\n return render_template('index.html')\n \n \n@app.route('/authorize/', methods=['POST', 'GET'])\ndef authorize():\n url = get_authorization_url()\n session['authorization_url'] = url\n text = '<a href=\"%s\">Authenticate with BuildingOS</a>'\n return text % url\n \n\n@app.route('/callback')\ndef bos_callback():\n error = request.args.get('error', '')\n if error:\n return \"Error: \" + error\n code = request.args.get('code')\n response = get_access_token(code)\n try:\n token = response.json()['access_token']\n except KeyError:\n with open('/users/malcolmmonroe/desktop/error_log.txt') as file:\n file.write(\"Invalid JSON - Token Error: %s. @ %s\" % (str(e), datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S')))\n file.close()\n\n session['token'] = token\n return render_template('orgentry.html')\n \n \n@app.route('/getBldgs/', methods=['POST', 'GET'])\ndef getBldgs():\n try:\n organization_id = request.form['orgid']\n except Exception as e:\n with open('/users/malcolmmonroe/desktop/error_log.txt') as file:\n file.write(\"User Input - Organization ID. Error: %s. @ %s\" % (str(e), datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S')))\n file.close()\n\n number_checkout = re.match('^[0-9]{1,7}$', organization_id)\n if number_checkout:\n session['OrganizationID'] = organization_id\n organization = Organization(session.get('token'))\n data = organization.get_organization_metadata(session.get('OrganizationID'))\n return str(data)\n '''organization = Organization(session.get('org_id'), session.get('token'))\n organization_data = organization.get_organization_data()\n building_data = organization.get_organization_building_data()\n organization_name = organization_data['data']['name']\n building_urls = organization_data['data']['buildings']\n session['buildingData'] = building_data\n building_names = [building_data[building]['name'] for building in range(len(building_data))]\n return render_template('qaparams.html', organizationName=organization_name, buildingUrls=building_urls, buildingNames=building_names)'''\n\n else:\n message = Markup(\"Please provide a valid organization id.\")\n flash(message)\n return render_template('orgentry.html')\n #assert False, building_list'''\n\n \n\n\n'''@app.route('/getMeters/', methods=['POST', 'GET'])\ndef getMeters():\n building_urls = request.form.getlist('building_list')\n if building_urls:\n building = Buildings(building_urls, session.get('token'))\n building_data =building.get_building_data()\n buildings_list = []\n session['BuildingData'] = building_data\n return render_template('meterpage.html', building_data=building_data)\n\n else:\n return \"Something is wrong\"'''\n \n\n\n\n'''@app.route('/getData/', methods=['POST', 'GET'])\ndef getData():\n return render_template('test_template.html')\n meter_url_parameters = request.form.getlist('meters')\n meter_data_list = []\n url = meter_url_parameters[-1]\n start_date = meter_url_parameters[0]\n start_time = meter_url_parameters[1]\n end_date = meter_url_parameters[2]\n end_time = meter_url_parameters[3]\n user_end_date = \"%sT%s:00\" % (end_date, end_time)\n reading_resolution = meter_url_parameters[4]\n meter_url = \"%s/data?start=%sT%s:00-00:00&end=%sT%s:00-00:00&resolution=%s&order=asc\" %(url, start_date, start_time, end_date, end_time, reading_resolution)\n meter = Meters(meter_url, session.get('token'))\n meter_response = meter.get_meter_response()\n meter_units = meter_response['meta']['units']['value']['displayName']\n meter_resolution = meter_response['meta']['resolution']['displayName']\n meter_metadata = {'meta': {'units': meter_units, 'resolution': meter_resolution}}\n meter_metadata_obj = json.dumps(meter_metadata)\n meter_readings = meter.get_meter_readings(user_end_date)\n building_data = session.get('BuildingData')\n #return str(building_dict)\n return render_template('graphic.html', building_data=building_data, meter_readings=meter_readings, meter_metadata=meter_metadata, number_pings=str(session.get('pings')))'''\n\n\n\n\n\n\nif __name__ == '__main__':\n app.secret_key=':F\\x030\\x1fS\\x1fw\\x84i\\x93\\xb6\\x8d\\x89l=eA/\\xf3\\xc1\\x076\\x90'\n app.run(debug=True, port=8080)\n\n\n\n\n\n","sub_path":"python_oauth_demo.py","file_name":"python_oauth_demo.py","file_ext":"py","file_size_in_byte":5152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"512600746","text":"import os\nimport numpy as np\nimport cv2\nimport json\n\nfiles = os.listdir('/Users/wurunmin/Desktop/sal_instance/pre-mask')\nwith open('/Users/wurunmin/Desktop/sal_instance/test.json','r') as f:\n nums = json.load(f)\n\n\n\ndef best(pd, ms):\n dist = 10000\n bb = np.zeros(3)\n ind = 0\n\n for j in range(len(ms)):\n i = ms[j]\n #print(pd.shape)\n dd = np.sqrt(np.sum(np.square(1.03*pd - i)))\n if dd < dist:\n dist = dd\n # print(dist)\n bb = i\n ind = j\n return bb,ind\n\nmmap = 0\nmap_1 = 0\nmap_2 = 0\nfor file in files:\n map = 0\n\n if file[-3:] == 'png':\n pre = cv2.imread('/Users/wurunmin/Desktop/sal_instance/results/' + file)\n gt = cv2.imread('/Users/wurunmin/Desktop/sal_instance/new/test/new_gt/' + file)\n gt = cv2.resize(gt,(64,64))\n n = nums[file]\n scores = []\n scores.append((0, 0, 0))\n scores.append((180,180,180))\n scores2 = []\n scores2.append((0, 0, 0))\n cal_pre = []\n cal_gt = []\n for i in range(n):\n cal_pre.append(np.zeros((64,64)))\n pp = np.zeros(3)\n center = cv2.imread('/Users/wurunmin/Desktop/sal_instance/new/test/ins_ct_gs/'+file[:-4]+'_'+str(i+1)+'.png',0)/255.\n center = cv2.resize(center,(64,64))\n #center2 = np.zeros(center.shape)\n #center2[center>0]=1\n pp[0] = np.sum(center*pre[:,:,0])/np.sum(center)\n pp[1] = np.sum(center*pre[:,:,1])/np.sum(center)\n pp[2] = np.sum(center*pre[:,:,2])/np.sum(center)\n #print(pp)\n scores.append(pp)\n pp[0] = np.sum(center * gt[:, :, 0]) / np.sum(center)\n pp[1] = np.sum(center * gt[:, :, 1]) / np.sum(center)\n pp[2] = np.sum(center * gt[:, :, 2]) / np.sum(center)\n #print(pp)\n scores2.append(pp)\n\n print('/Users/wurunmin/Desktop/sal_instance/results/' + file)\n\n # gt2 = cv2.resize(gt, (pre.shape[1], pre.shape[0]))\n # gs = cv2.imread('/Users/wurunmin/Desktop/sal_instance/center2_gs/'+file)\n ###compute every center in pre\n # pre=cv2.resize(pre,(gt.shape[1],gt.shape[0]))\n # cv2.imwrite('/Users/wurunmin/Desktop/sal_instance/new_pre/' + file, pre)\n\n\n print(file, len(scores))\n for i in range(64):\n for j in range(64):\n\n #if sum(pre[i, j, :]) > 500:\n # pre[i, j, :] = gt2[i, j, :]\n pre[i, j, :],ind = best(pre[i, j, :], scores)\n #print(ind)\n if ind==1:\n pre[i, j, :] =gt[i,j,:]\n elif ind!=0:\n pre[i,j,:]=scores2[ind-1]\n pre[i, j, :], ind = best(pre[i, j, :], scores2)\n if ind!=0:\n cal_pre[ind-1][i,j] = 1\n for i in range(n):\n ins_gt = cv2.imread('/Users/wurunmin/Desktop/sal_instance/new/test/inss/'+file[:-4]+'_'+str(i+1)+'.png',0)\n ins_gt = cv2.resize(ins_gt,(64,64))/255.\n #ins_gt[ins_gt>0]=1\n #cv2.imshow('',ins_gt*255)\n #cv2.waitKey()\n #cv2.imshow('',cal_pre[i]*255)\n #cv2.waitKey()\n U = ins_gt+cal_pre[i]\n U[U>0]=1\n I = ins_gt*cal_pre[i]\n #cv2.imshow('I', I * 255)\n #cv2.waitKey()\n #cv2.imshow('U', U * 255)\n #cv2.waitKey()\n #print(U.shape,I.shape)\n #print(np.sum(I),np.sum(U))\n ap = np.sum(I)/np.sum(U)\n print(i,ap)\n map+=ap/n\n if map>0.5:\n map_1+=1\n if map>0.7:\n map_2+=1\n\n\n print(map)\n print('/Users/wurunmin/Desktop/sal_instance/new_pre/' + file,n)\n cv2.imwrite('/Users/wurunmin/Desktop/sal_instance/new_pre/' + file, pre)\n mmap+= map/183\nprint(mmap,map_1/183,map_2/183)\n","sub_path":"eval_mAP.py","file_name":"eval_mAP.py","file_ext":"py","file_size_in_byte":3894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"29861558","text":"import logging\nimport string\nimport os\n# from collections import Counter\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport pylab\npylab.rcParams['figure.figsize'] = (25.0, 10.0)\nfrom collections import Counter, defaultdict\nimport pandas as pd\n\nfrom read import map_to_precursors\nfrom utils import safe_dirs\n\nfrom seqcluster.html import HTML\nfrom seqcluster import templates\n\nlogger = logging.getLogger('html')\n\n\ndef _get_link(c):\n \"\"\"Gives html link tag for cluster link information\"\"\"\n return \"<a href=%s/maps.html>%s</a>\" % (c, c)\n\n\ndef _get_ann(dbs, features):\n \"\"\"\n Gives format to annotation for html table output\n \"\"\"\n value = \"\"\n for db, feature in zip(dbs, features):\n value += db + \":\" + feature\n return value\n\n\ndef make_profile(data, out_dir, args):\n \"\"\"\n Make html for each cluster\n \"\"\"\n main_table = []\n header = ['id', 'ann']\n html_file = os.path.join(out_dir, \"index.html\")\n for c in data[0]:\n logger.debug(\"creating cluser: {}\".format(c))\n safe_dirs(os.path.join(out_dir, c))\n valid, ann = _single_cluster(c, data, os.path.join(out_dir, c, \"maps.tsv\"), args)\n if valid:\n main_table.append([_get_link(c), _get_ann(valid, ann)])\n\n main_html = HTML.table(main_table, header_row=header, attribs={'id': 'keywords'})\n html_template = os.path.normpath(os.path.join(os.path.dirname(os.path.realpath(templates.__file__)), \"main\"))\n content = open(html_template).read()\n data = {'main': main_html}\n out_content = string.Template(content).safe_substitute(data)\n with open(html_file, 'w') as out_handle:\n print >>out_handle, out_content\n\n\ndef _expand(dat, counts, start, end):\n \"\"\"\n expand the same counts from start to end\n \"\"\"\n for pos in range(start, end):\n dat[pos] += counts\n return dat\n\n\ndef _convert_to_df(in_file):\n \"\"\"\n convert data frame into table with pandas\n \"\"\"\n dat = Counter()\n with open(in_file) as in_handle:\n for line in in_handle:\n cols = line.strip().split(\" \")\n counts = float(cols[1].replace(\"cx\", \"\"))\n dat = _expand(dat, counts, int(cols[4]), int(cols[5]))\n dat = {'positions': dat.keys(), 'expression': dat.values()}\n df = pd.DataFrame(data=dat, columns=dat.keys())\n df.set_index('positions', inplace=True)\n return df\n\n\ndef _make_html(c, html_file, figure_file, prefix):\n \"\"\"\n create html from template, adding figure,\n annotation and sequences counts\n \"\"\"\n ann = defaultdict(list)\n seqs_table = []\n\n src_img = \"<img src=\\\"%s\\\" width=\\\"800\\\" height=\\\"350\\\" />\" % os.path.basename(figure_file)\n coor_list = [\" \".join(map(str, l)) for l in c['loci']]\n coor_html = HTML.list(coor_list)\n\n for pos in c['ann']:\n for db in pos:\n ann[db] += list(pos[db])\n logger.debug(ann)\n\n valid = [l for l in c['valid']]\n ann_list = [\", \".join(list(set(ann[feature]))) for feature in ann if feature in valid]\n ann_html = HTML.list(ann_list)\n\n seqs = [s.values()[0] for s in c['seqs']]\n freq = [map(float, s.values()[0].values()) for s in c['freq']]\n header = ['seq'] + c['freq'][0].values()[0].keys()\n for s, f in zip(seqs, freq):\n f = map(round, f)\n seqs_table.append([s] + map(str, f))\n seqs_html = HTML.table(seqs_table,\n header_row=header, attribs={'id': 'keywords'})\n # seqs_html = seqs_html.replace(\"TABLE\", \"TABLE id=\\\"keywords\\\"\")\n\n html_template = os.path.normpath(os.path.join(os.path.dirname(os.path.realpath(templates.__file__)), \"cluster\"))\n content = open(html_template).read()\n data = {'profile': src_img,\n 'loci': coor_html,\n 'annotation': ann_html,\n 'table': seqs_html}\n out_content = string.Template(content).safe_substitute(data)\n with open(html_file, 'w') as out_handle:\n print >>out_handle, out_content\n\n return valid, ann_list\n\n\ndef _single_cluster(c, data, out_file, args):\n \"\"\"\n Map sequences on precursors and create\n expression profile\n \"\"\"\n valid, ann = 0, 0\n figure_file = out_file.replace(\".tsv\", \".png\")\n html_file = out_file.replace(\".tsv\", \".html\")\n prefix = os.path.dirname(out_file)\n names = [round(sum(s.values()[0].values())) for s in data[0][c]['freq']]\n seqs = [s.values()[0] for s in data[0][c]['seqs']]\n\n loci = data[0][c]['loci']\n\n if loci[0][3] - loci[0][2] > 500:\n logger.info(\"locus bigger > 500 nt, skipping: %s\" % loci)\n return valid, ann\n logger.debug(\"map all sequences to all loci %s \" % loci)\n map_to_precursors(seqs, names, {loci[0][0]: [loci[0][0:5]]}, out_file, args)\n # map_sequences_w_bowtie(sequences, precursors)\n\n logger.debug(\"plot sequences on loci\")\n df = _convert_to_df(out_file)\n if not df.empty:\n plot = df.plot()\n plot.set_ylabel('Normalized expression', fontsize=25)\n plot.set_xlabel('Position', fontsize=25)\n plot.tick_params(axis='both', which='major', labelsize=20)\n plot.tick_params(axis='both', which='minor', labelsize=20)\n plot.get_figure().savefig(figure_file)\n valid, ann = _make_html(data[0][c], html_file, figure_file, prefix)\n\n return valid, ann\n","sub_path":"seqcluster/libs/report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":5231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"295882689","text":"#!/usr/bin/env python\n\nfrom igdb_api_python.igdb import igdb\nimport sys\nimport random\n\nigdb = igdb(\"a3a100cec5fd39c002aad011e85d2dea\")\n\ndef gameslist_genres(genres):\n\tfor i in range(len(genres)):\n\t\tresult = igdb.genres({\n\t\t\t'ids': genres[i],\n\t\t\t'fields': 'games',\n\t\t\t})\n\t\tgameslist = []\n\t\tfor game in result.body:\n\t\t\tgameslist.append(game['games'])\n\t\tgameslist = gameslist[0]\n\t\treturn(gameslist)\n\n\ndef ids(fav1, fav2, fav3):\n\tfavgames = [fav1, fav2, fav3]\n\tid = []\n\tresult = igdb.games({\n\t\t'search': fav1,\n\t\t'fields': 'id',\n\t\t})\n\tfor game in result.body:\n\t\tid.append(game['id'])\n\t\tbreak\n\n\tresult1 = igdb.games({\n\t\t'search': fav2,\n\t\t'fields': 'id',\n\t\t})\n\tfor game in result1.body:\n\t\tid.append(game['id'])\n\t\tbreak\n\n\tresult2 = igdb.games({\n\t\t'search': fav3,\n\t\t'fields': 'id',\n\t\t})\n\tfor game in result2.body:\n\t\tid.append(game['id'])\n\t\tbreak\n\n\treturn(id)\n\t\ndef genres(fav1, fav2, fav3, id):\n\tid = ids(fav1, fav2, fav3)\n\tk = 0\n\tgenre = []\n\tfor i in range(3):\n\t\ttry:\n\t\t\tresult = igdb.games({\n\t\t\t'ids': id[i],\n\t\t\t'fields': 'genres',\n\t\t\t})\n\t\t\tfor game in result.body:\n\t\t\t\tgenre.append(game['genres'])\n\t\texcept:\n\t\t\tk += 1\n\t\t\tprint(\"Unable to complete: \" + str(id[i]))\n\tgenres = []\n\tfor elem in genre:\n\t\tfor j in range (len(elem)):\n\t\t\tif elem[j] not in genres:\n\t\t\t\tgenres.append(elem[j])\n\treturn(genres)\n\ndef keywords(id):\n\tk = 0\n\tkeys = []\n\tfor i in range(3):\n\t\ttry:\n\t\t\tresult = igdb.games({\n\t\t\t'ids': id[i],\n\t\t\t'fields': 'keywords',\n\t\t\t})\n\t\t\tfor game in result.body:\n\t\t\t\tkeys.append(game['keywords'])\n\t\texcept:\n\t\t\tk += 1\n\t\t\tprint(\"Unable to complete: \" + str(id[i]))\n\tkeys1 = []\n\tfor elem in keys:\n\t\tfor j in range (len(elem)):\n\t\t\tif elem[j] not in keys1:\n\t\t\t\tkeys1.append(elem[j])\n\trandom.shuffle(keys1)\n\treturn(keys1[0:4])\n\ndef gameslist_keywords(gameslist, keywords):\n\tfor i in range(len(keywords)):\n\t\tresult = igdb.keywords({\n\t\t\t'ids': keywords[i],\n\t\t\t'fields': 'games',\n\t\t\t})\n\t\tkeylist = []\n\t\tfor game in result.body:\n\t\t\tkeylist.append(game['games'])\n\t\tkeylist = keylist[0]\n\t\treturn(keylist)\n\ndef compare_gameslist(gameslist1, gameslist2):\n\tgameslist3 = []\n\tfor elem in gameslist1:\n\t\tif elem in gameslist2:\n\t\t\tif elem not in gameslist3:\n\t\t\t\tgameslist3.append(elem)\n\treturn(gameslist3)\n\ndef finalgames(gameslist):\n\t#gameslist1 = gameslist[0:len(gameslist):len(gameslist)//4]\n\trandom.shuffle(gameslist)\n\tgameslist = gameslist[0:5]\n\t#gameslist1.append(gameslist[1:2])\n\t#gameslist1.append(gameslist[((len(gameslist)//2)-1), len(gameslist)//2])\n\t#gameslist1.append(gameslist[len(gameslist)-2, len(gameslist)-1])\n\t#gameslist1.append(gameslist[((len(gameslist)//3)-1), len(gameslist)//3])\n\t#gameslist1.append(gameslist[((len(gameslist)//4)-1), len(gameslist)//4])\n\tresult = igdb.games ({\n\t\t\"ids\": gameslist,\n\t\t\"fields\": \"name\"\n\t\t})\n\tgnames = []\n\tfor gamename in result.body:\n\t\tgnames.append(gamename[\"name\"])\n\treturn(gnames)\n\n\ndef main(fav1, fav2, fav3):\n\tid = ids(fav1, fav2, fav3)\n\tgenres1 = genres(fav1, fav2, fav3, id)\n\tkeys = keywords(id)\n\tgameslist1 = gameslist_genres(genres1)\n\tgameslist2 = gameslist_keywords(gameslist1, keys)\n\tgameslist3 = compare_gameslist(gameslist1, gameslist2)\n\tfinalgnames = finalgames(gameslist3)\n\tprint (\"\")\n\tfor game in finalgnames:\n\t\tprint(game)\n\nmain(sys.argv[1], sys.argv[2], sys.argv[3])\n","sub_path":"Archive/gametime.py","file_name":"gametime.py","file_ext":"py","file_size_in_byte":3215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"91065573","text":"from fractions import Fraction\nfrom typing import Sequence\nfrom operator import add, sub, mul, truediv\nfrom math import modf\n\nimport click\n\noperators_map = {\"+\": add, \"-\": sub, \"*\": mul, \"/\": truediv}\n\n\nclass OperandSintaxError(Exception):\n pass\n\n\n@click.command()\ndef cli() -> None:\n operation = click.prompt(text=\"?\", prompt_suffix=\" \")\n\n try:\n left_operand, operator, right_operand = operation.split()\n except Exception:\n click.echo(\n f\"\\nInvalid input sintax.\\n\\nExpected: operand1 operator operand2\\nGot: {operation}\"\n )\n return\n\n try:\n left_operand_number = get_operand_number(left_operand)\n right_operand_number = get_operand_number(right_operand)\n except (ValueError, OperandSintaxError):\n click.echo(\n f\"\\nInvalid operand sintax.\\n\\nExpected: whole_fraction\\nGot:\\n\\tOperand 1: {left_operand}\\n\\tOperand 2: {right_operand}\"\n )\n return\n\n result_number = operators_map[operator](left_operand_number, right_operand_number)\n\n click.echo(f\"= {get_number_string(result_number)}\")\n\n\ndef get_number_string(number: float) -> str:\n number_fraction, number_whole = modf(number)\n\n if number_whole and number_fraction:\n return f\"{int(number_whole)}_{Fraction(number_fraction)}\"\n\n return str(int(number_whole) or number_fraction and Fraction(number_fraction))\n\n\ndef get_operand_number(operand: str) -> float:\n operand_whole, operand_fraction = split_operand(operand)\n\n if operand_fraction:\n if \"/\" not in operand_fraction:\n raise OperandSintaxError()\n\n numerator, denominator = operand_fraction.split(\"/\")\n operand_fraction_number = int(numerator) / int(denominator)\n\n if operand_whole:\n return int(operand_whole) + operand_fraction_number\n\n return operand_fraction_number\n elif operand_whole:\n return int(operand_whole)\n else:\n raise OperandSintaxError()\n\n\ndef split_operand(operand: str) -> Sequence[str]:\n parts = operand.split(\"_\")\n\n if len(parts) == 1:\n if \"/\" in parts[0]:\n return (\"\", parts[0])\n\n return (parts[0], \"\")\n elif len(parts) == 2:\n return parts\n else:\n raise OperandSintaxError()\n","sub_path":"calculator/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":2252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"385760039","text":"# Copyright (C) 2018 Garth N. Wells\r\n#\r\n# SPDX-License-Identifier: MIT\r\n\"\"\"This module contains a collection of functions related to\r\ngeographical data.\r\n\r\n\r\n\"\"\"\r\n\r\nimport numpy as np\r\n\r\nfrom haversine import haversine\r\n # distance between two geographic coordinates \r\n\r\nfrom floodsystem.utils import sorted_by_key\r\n\r\ndef stations_by_distance(stations, p):\r\n \"\"\"Function to sort stations distance from a coordinate\"\"\"\r\n sdlist = [] # List store all the station and distance with p\r\n distance = 0\r\n for station in stations: # Loop for all the stations\r\n cord = station.coord # Coordinate of the station\r\n distance = haversine(p,cord) # Use function to get the distance\r\n sdlist.append((station.name,distance)) # Add Tuple to the List\r\n return sorted_by_key(sdlist,1) # Return the sorted list\r\n\r\ndef stations_by_distance_with_town(stations, p): \r\n \"\"\"function for doing 1B demonstration program\"\"\"\r\n sdlist = [] # List store all the station and distance with p\r\n distance = 0\r\n for station in stations: # Loop for all the stations\r\n cord = station.coord # Coordinate of the station\r\n distance = haversine(p,cord) # Use function to get the distance\r\n town = station.town\r\n sdlist.append(((station.name,town),distance)) # Add Tuple to the List\r\n return sorted_by_key(sdlist,1) # Return the sorted list\r\n\r\ndef stations_within_radius(stations, centre, r):\r\n \"\"\"Helps identify stations with the specified radius\"\"\"\r\n if stations is not None and centre is not None and r >0:\r\n slist = [] # List that will be returned\r\n c_lat = centre[0] # latitude coordinate of center\r\n c_long = centre[1] # longitude coordinate of center\r\n\r\n for station in stations: # Loop to check all the stations\r\n\r\n coord = station.coord # Coordinate of the stations\r\n pos_lat = coord[0] # X coordinate of station\r\n pos_long = coord[1] # Y coordinate of station\r\n det_lat = np.radians(pos_lat-c_lat)\r\n det_long = np.radians(pos_long-c_long)\r\n\r\n a = np.power(np.sin(det_lat/2),2) + (np.cos(np.radians(pos_lat))*np.cos(np.radians(c_lat))*np.power(np.sin(det_long/2),2))\r\n c = 2*np.arctan2(np.power(a,0.5), np.power((1-a),0.5))\r\n\r\n radius = 6371*c # distance between the two coordinates\r\n if r > radius: # if the distance is less than radius then it lies in the circle\r\n slist.append(station.name) # Adding the station to the list\r\n return slist # returning the list\r\n\r\n else:\r\n print(\"Please check if input parameters are not Null values\")\r\n\r\ndef rivers_with_station(stations):\r\n \"\"\"Function to get all the river monitored in a set\"\"\"\r\n riverset = set() # river set\r\n for station in stations:\r\n riverset.add(station.river)\r\n return riverset\r\n\r\ndef stations_by_river(stations):\r\n \"\"\"Function to get a dictionary that maps stations by river\"\"\"\r\n riverDictionary = {} # get an empty set of dictionary for rivers \r\n riverList = list(rivers_with_station(stations)) # transfer sets to a list of stations\r\n for river in riverList: # outside for loop for river\r\n temp = [] #initiate temporary list for all station names on a river\r\n for station in stations: # inside loop iterate for all stations\r\n if river == station.river: # check if the river matches the one we wants\r\n temp.append(station.name) # if true added to the temporary list\r\n temp = sorted(temp) # sorted the temporary list\r\n riverDictionary.update({river : temp}) # Update the dictionary\r\n return riverDictionary\r\n\r\ndef rivers_by_station_number(stations, N):\r\n \"\"\"Gives N rivers with maximum station and rivers with same no of stations are counted as one\"\"\"\r\n dictionary = {} # A dictionary will store how many rivers have how many stations\r\n slist = [] # List to be returned\r\n unique_river = set() # store the unique rivers - to not get an error - adding a new key to dic\r\n\r\n for station in stations: # Loop to check all the stations\r\n river = station.river # Get the river name\r\n\r\n if river in unique_river: # Check if river in the set\r\n dictionary[river] += 1 # Increasing Frequency\r\n\r\n else:\r\n unique_river.add(river)\r\n dictionary[river] = 1 # Increasing Frequency\r\n\r\n sorted_list = sorted((dictionary.items()), key=lambda dictionary: dictionary[1], reverse=True) # Sorting the dic val in reverse\r\n\r\n sorted_list = [tuple(item) for item in sorted_list] # Converting to request return type\r\n\r\n val_max = sorted_list[0][1] # River with maximum station\r\n\r\n# Loop to append the N- largest rivers in the return list\r\n\r\n num = 0\r\n i = 0\r\n\r\n while num <= N and i< len(sorted_list):\r\n if N-num != 0:\r\n slist.append(sorted_list[i])\r\n i += 1\r\n num +=1\r\n else:\r\n if slist[-1][1] == sorted_list[i][1]:\r\n slist.append(sorted_list[i])\r\n i += 1\r\n\r\n else:\r\n break\r\n\r\n\r\n\r\n\r\n return slist\r\n\r\n","sub_path":"partia-flood-warning-system/floodsystem/geo.py","file_name":"geo.py","file_ext":"py","file_size_in_byte":5179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"516468531","text":"'''Sort bash history'''\n\n# [ Imports ]\n# [ -Python- ]\nimport sys\nimport os.path\n\n# [ Argument Parsing ]\nhist_file_path = sys.argv[-1]\n\n\n# [ Helpers ]\ndef is_timestamp_line(line):\n if line.startswith('#'):\n try:\n int(line[1:])\n return True\n except (TypeError, ValueError):\n pass\n return False\n\n\n# [ Main ]\n# Safety check\nif not os.path.isfile(hist_file_path):\n print(\"{} cannot sort {}: it is not a regular file.\".format(sys.argv[0], hist_file_path))\n exit(1)\n\n# Save off modification time\nmtime = os.path.getmtime(hist_file_path)\n# Get the current history\nwith open(hist_file_path) as hist_file:\n lines = hist_file.readlines()\n# Build sortable history list\nsortable = []\nfor index, line in enumerate(lines):\n if not is_timestamp_line(line):\n timestamp_index = index - 1\n if timestamp_index >= 0 and is_timestamp_line(lines[timestamp_index]):\n # preceeded by a timestamp line. Make a new object.\n sortable.append({\n \"ts\": lines[timestamp_index],\n \"commands\": [line]\n })\n elif sortable:\n # no timestamp, but a prior command had one\n sortable[-1][\"commands\"].append(line)\n else:\n # no timestamp, first command in history\n sortable.append({\n \"ts\": \"#0\\n\",\n \"commands\": [line]\n })\n# Sort\nsortable.sort(key=lambda i: i[\"ts\"])\n# Build new string\nnew_lines = []\nfor item in sortable:\n new_lines.append(item[\"ts\"])\n for command in item[\"commands\"]:\n new_lines.append(command)\n# Lines are getting lost and I don't know where. Guard against that here.\nfor line in lines:\n if not is_timestamp_line(line):\n if line not in new_lines:\n sys.stderr.write(\"{} deduplicated {} incorrectly. New file is missing '{}'. Not writing new file.\\n\".format(\n sys.argv[0], hist_file_path, line\n ))\n exit(1)\n# Guard a little against file access issues:\nnew_mtime = os.path.getmtime(hist_file_path)\nif mtime == new_mtime:\n with open(hist_file_path, 'w') as hist_file:\n hist_file.write(''.join(new_lines))\nelse:\n print(\"{} cannot sort {}: file has changed since last read.\".format(sys.argv[0], hist_file_path))\n exit(1)\n","sub_path":"plugins/history/history_sort.py","file_name":"history_sort.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"316352140","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: yanickdupuisbinette\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\n\nfrom joblib import load\n\nfrom keras.models import load_model\n\npreprocess = load('preprocess.pkl')\nclassifier = load_model('best_model.h5')\n\n###### PREDICT\n\nXnew = pd.DataFrame(data={\n 'CreditScore': [600], \n 'Geography': ['France'], \n 'Gender': ['Male'],\n 'Age': [40],\n 'Tenure': [3],\n 'Balance': [60000],\n 'NumOfProducts': [2],\n 'HasCrCard': [1],\n 'IsActiveMember': [1],\n 'EstimatedSalary': [50000]})\n\nXnew = preprocess.transform(Xnew)\n#\nXnew = np.delete(Xnew, [0,3], 1)\n\nnew_prediction = classifier.predict(Xnew)\n\nnew_prediction = (new_prediction > 0.5)\n\nprint(new_prediction)","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"48103780","text":"import requests\nimport schedule\nimport time\n\nurl = 'https://c.y.qq.com/soso/fcgi-bin/client_search_cp?new_json=1&catZhida=1&w=Riders%20On%20The%20Storm&format=json&aggr=1&cr=1'\n\nproxy = 'http://221.182.133.230:3129'\nproxies = {\n 'http': proxy,\n 'https': proxy\n}\nget = requests.get(url=url, proxies=proxies)\nprint(get.content)\n","sub_path":"MGMusicSpider/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"421746012","text":"from django.core.management.base import BaseCommand, CommandError\nfrom bs4 import BeautifulSoup\nimport requests\nimport json\nimport re\nimport urllib\nimport datetime\nfrom django.conf import settings\nfrom PIL import Image \nimport io\nimport imagehash\nfrom frontpage.models import Tag, RetailItem, Category\n\nfrom selenium import webdriver\n\n\nfrom finder.models import ItemCategory, Brand, FashionImage, FashionItem, Designer\n\n\"\"\"\nManagement command to get images from J.Crew site\n\"\"\"\n\n\ndef get_soup(url):\n\tresponse = requests.get(url)\n\tsoup = BeautifulSoup(response.text, 'html.parser')\n\treturn soup\n\n\ndef get_links(url):\n\t\"\"\"return dictionary of links to visit on jcrew page with corresponding category\"\"\"\n\tlinks_list = {}\n\tbase_url = 'https://www.jcrew.com/womens-clothing.jsp'\n\tcategories_to_discard = ['J.CREW X PIERRE LE-TAN', '#SHINYPONIES', 'sleepwear', 'swim', 'scarves, hats & gloves', 'jewelry', 'fine jewelry', 'home & gifts', 'accessories', 'special swim sizes']\n\tsoup = get_soup(url)\n\tlinks = soup.find_all('p', class_='leftNavCat')\n\tfor link in links:\n\t\tif 'href' in str(link.a):\n\t\t\tlink_text = link.a.text \n\t\t\tlink_href = link.a['href']\n\t\t\tlinks_list[link_text] = link_href\n\treturn links_list\n\ndef get_items(url, category):\n\t\"\"\"return dict with item ids and corresponding product names\"\"\"\n\tcurrent_category = category\n\tsoup = get_soup(url)\n\titems = soup.find_all('table')\n\tfor item in items:\n\t\titem_entry = item.find('img')\n\t\t#print(item_name)\n\t\tif item_entry:\n\t\t\tsize = (299,299)\n\t\t\t\n\t\t\titem_name = \"J.Crew \" + str(item_entry.get('alt'))\n\t\t\tprint(item_name)\n\t\t\t\n\t\t\titem_name_tags = item_name.split()\n\t\t\tall_tags = []\n\t\t\tfor tag in item_name_tags:\n\t\t\t\tprint(tag)\n\t\t\t\tnew_tag = Tag.objects.get_or_create(tag_name=tag)[0]\n\t\t\t\tall_tags.append(new_tag)\n\t\t\titem_name = item_name.replace('/', '')\n\t\t\timage_url = item_entry.get('src')\n\t\t\tif str(image_url).startswith('https://'):\n\t\t\t\tresponse = requests.get(image_url)\n\t\t\t\ttry:\n\t\t\t\t\timg = Image.open(io.BytesIO(response.content))\n\t\t\t\texcept OSError:\n\t\t\t\t\timg = None\n\t\t\t\t\tprint(\"problem opening url{}\".format(additional_image))\n\t\t\t\tif img:\n\t\t\t\t\timg.thumbnail(size, Image.ANTIALIAS)\n\t\t\t\t\tw1 = str(imagehash.whash(img))\n\t\t\t\t\ttree_hash = bin(int.from_bytes(w1.encode(), 'big'))[2:]\n\t\t\t\t\tnew_item = RetailItem.objects.get_or_create(brand='JCrew', item_name=item_name, image_tree_hash=tree_hash, image=image_url)[0]\n\t\t\t\t\tfor tag in all_tags:\n\t\t\t\t\t\tnew_item.tags.add(tag)\n\t\t\telse:\n\t\t\t\tpass\n\treturn\n\n\n\nclass Command(BaseCommand):\n\tdef handle(self, *args, **options):\n\t\turl = 'https://www.jcrew.com/womens-clothing.jsp'\n\t\tlinks = get_links(url)\n\t\tprint(links)\n\t\tfor link in links.items():\n\t\t\tget_items(link[1], link[0])\t\n\t\t\n\n\n\t\t\n\n\n\n\n\n\n\n\n\n","sub_path":"finder/management/commands/jcrew.py","file_name":"jcrew.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"73754308","text":"import pandas as pd\n\nclass Layer:\n _PARAM_LIST = [\"usage\", \"layer\", \"thickness\", \"zloc\", \"material\"]\n\n def __init__(self, param):\n self.param = param\n self._validate()\n\n self.usage = param[\"usage\"]\n self.layer = param[\"layer\"]\n self.thickness = param[\"thickness\"]\n self.zloc = param[\"zloc\"]\n self.material = param[\"material\"]\n\n def _validate(self):\n for i in self._PARAM_LIST:\n if not i in self.param:\n raise ValueError(\"{} is not defined\".format(i))\n\n\nclass ConductorLayer(Layer):\n def __init__(self, param):\n Layer.__init__(self, param)\n\n\nclass DielectricLayer(Layer):\n def __init__(self, param):\n Layer.__init__(self, param)\n\n\nclass Stackup:\n BOARD_THICKNESS = 0\n def __init__(self, fname):\n self.layers = {}\n self.layer_count = 0\n\n self.load_stackup(fname)\n\n def load_stackup(self, fname):\n df = pd.read_csv(fname)\n param = {}\n vloc = 0\n\n for r, val in df.iterrows():\n param[\"zloc\"] = vloc\n param[\"usage\"] = val[\"usage\"]\n param[\"layer\"] = val[\"layer\"]\n param[\"thickness\"] = val[\"thickness\"]\n param[\"material\"] = val[\"material\"]\n print(param)\n self.layers[r] = Layer(param)\n vloc += val[\"thickness\"]\n self.layer_count += 1\n self.layer_count = (self.layer_count + 1) // 2\n self.BOARD_THICKNESS = vloc\n\n\n def _check(self):\n for i, j in self.layers.items():\n print(i, j.usage, j.layer, j.thickness, j.zloc, j.material)\n\ndef debug():\n param = {\"thickness\":\"0.05\",\n \"zloc\":\"0\"}\n fname = \"stackup.csv\"\n debug = Stackup(fname)\n debug._check()\n\n\n\nif __name__==\"__main__\":\n debug()\n\n","sub_path":"util/stackup_manager.py","file_name":"stackup_manager.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"443835078","text":"# --------------------------------------\r\n# CSCI 127, Lab 7 |\r\n# June 20, 2019 |\r\n# Timothy Bender |\r\n# --------------------------------------\r\n#the comma and space character are treated differently because the dictionary\r\n#key created from the ascii file is is \"comma\" for comma and for space it is \"space\".\r\n#The other keys are simply their characters\r\ndef create_dictionary(f):\r\n f = open(f, \"r\")\r\n encodings = {}\r\n for i in f:\r\n values = i.split()\r\n for t in values:\r\n values_2 = t.split(\",\")\r\n if encodings.get(values_2[1],-1) == -1:\r\n encodings[values_2[1]] = values_2[0]\r\n f.close()\r\n return encodings\r\n\r\ndef translate(sen, encodings, t):\r\n f = open(t, \"w\")\r\n for i in sen:\r\n if i == \" \":\r\n f.write(i + \" \" + encodings[\"space\"] + \"\\n\")\r\n elif i == \",\":\r\n f.write(i + \" \" + encodings[\"comma\"] + \"\\n\")\r\n elif encodings.get(i,-1) == -1:\r\n f.write(i +\" UNKNOWN \\n\")\r\n else:\r\n f.write(i + \" \" + encodings[i] + \"\\n\")\r\n \r\n f.close()\r\n# --------------------------------------\r\n\r\ndef main():\r\n dictionary = create_dictionary(\"ascii-codes.csv\")\r\n sentence = \"Buck lived at a big house in the sun-kissed Santa Clara Valley. Judge Miller's place, it was called!\"\r\n translate(sentence, dictionary, \"output-1.txt\")\r\n sentence = \"Bozeman, MT 59717\"\r\n translate(sentence, dictionary, \"output-2.txt\")\r\n sentence = \"The value is ~$25.00\"\r\n translate(sentence, dictionary, \"output-3.txt\")\r\n\r\n# --------------------------------------\r\n\r\nmain()\r\n","sub_path":"Labs/Timothy-Bender-Lab6.py","file_name":"Timothy-Bender-Lab6.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"562605854","text":"import numpy as np\nimport pandas as pd\nimport time\nfrom datetime import datetime\nfrom instrument import _AgilentN9020A_spectrum\nfrom instrument import _E36312A_power\nfrom instrument import _Agilent34410A_multimeter\nfrom HCI import HCI_For_Serial\n\n# LAN INFORMATION\nSPEC_TCPIP = 'TCPIP::192.168.190.22::INSTR'\nMETER_TCPIP = 'TCPIP::192.168.190.31::inst0::INSTR'\nPWR_TCPIP = 'TCPIP::192.168.190.87::inst0::INSTR'\n\n# BOARD INFORMATION\nBoardNum = '1号线#打线板_2'\n\n# ENVIRONMENT\nTemp = '25℃'\n\n# CONDITIONS\nStartMHz = 2402\nStopMHz = 2480 + 2\nSamplesNum = int((StopMHz - StartMHz) / 2)\nStartACW = 0\nStopACW = 256\nStepACW = 2\nSamplesAcwNum = int((StopACW - StartACW) / 2)\n\n\nclass TxPowerDef:\n TX_NEG20_DBM = 0\n TX_NEG5_DBM = 1\n TX_0_DBM = 2\n TX_5_DBM = 3\n TX_7_DBM = 4\n TX_10_DBM = 5\n\n\nclass VcoPowerDef:\n LDO_VCO_850mV = 0\n LDO_VCO_900mV = 1\n LDO_VCO_950mV = 2\n LDO_VCO_1000mV = 3\n LDO_VCO_1050mV = 4\n LDO_VCO_1100mV = 5\n LDO_VCO_1150mV = 6\n LDO_VCO_1200mV = 7\n\n\nclass LdoActDef:\n LDO_ACT_1300mV = 0\n LDO_ACT_1250mV = 1\n LDO_ACT_1200mV = 2\n LDO_ACT_1150mV = 3\n LDO_ACT_1100mV = 4\n LDO_ACT_1050mV = 5\n LDO_ACT_1000mV = 6\n LDO_ACT_950mV = 7\n\n\nclass LdoRfDef:\n LDO_RF_850mV = 0\n LDO_RF_900mV = 1\n LDO_RF_950mV = 2\n LDO_RF_1000mV = 3\n LDO_RF_1050mV = 4\n LDO_RF_1100mV = 5\n LDO_RF_1150mV = 6\n LDO_RF_1200mV = 7\n\n\nclass Result_data:\n fre_index = np.array(np.zeros(1 * SamplesNum))\n ReadPowerDBM = np.array(np.zeros(1 * SamplesNum))\n VddRFCurrentMA = np.array(np.zeros(1 * SamplesNum))\n ACW = np.array(np.zeros(1 * SamplesAcwNum))\n LdoAct = np.array(np.zeros(1 * 7))\n\n\nresult_data = Result_data()\n\n\nclass HCI_para:\n PORT = 'COM3'\n BPS = 115200\n\n\nclass PA_Test:\n def __init__(self):\n self.MXD2670 = None\n self.CUR = None\n self.PWR = None\n self.SPEC = None\n self.DATA = Result_data()\n self.ACW = 0\n self.OutputPowerDBM = 0\n self.VddRfCurrentMA = 0\n\n def PA_channel_current_test_init(self):\n # spectrum init\n self.SPEC = _AgilentN9020A_spectrum.Agilent_MXA_N9020A\n self.SPEC.spectrum_init(self=self.SPEC, TCPIP=SPEC_TCPIP)\n self.SPEC.identity(self=self.SPEC)\n self.SPEC.getInitialParamsAgilent(self=self.SPEC)\n self.SPEC.setSpanMHz(self=self.SPEC, span=1)\n self.SPEC.setCentralFreqMHz(self=self.SPEC, centralFreq=2440)\n time.sleep(0.5)\n print('spectrum init success')\n\n # power supply init\n self.PWR = _E36312A_power.Waveform\n self.PWR.power_init(self=self.PWR, TCPIP=PWR_TCPIP)\n self.PWR.set_ch1_voltage(self=self.PWR, vol=1.3, cur=0.5)\n self.PWR.power_ch1_on(self=self.PWR)\n print('power supply init success')\n\n # meter init\n self.CUR = _Agilent34410A_multimeter.Multimeter\n self.CUR.meter_init(self=self.CUR, TCPIP=METER_TCPIP)\n self.CUR.config_to_dci_mode(self=self.CUR)\n print('meter init success')\n\n # device init\n self.MXD2670 = HCI_For_Serial.HCI_Serial\n self.MXD2670.HCI_serial_port_refresh(self=self.MXD2670)\n self.MXD2670.HCI_port_init(self=self.MXD2670, port=HCI_para.PORT, bps=HCI_para.BPS, timeout=2)\n print('device init success')\n\n def PA_channel_current(self, ChFreqMHz, ACW, VDD_RF, LdoVco=[VcoPowerDef], TxPwr=[TxPowerDef], LdoRf=[LdoRfDef]):\n self.OutputPowerDBM = 0\n self.VddRfCurrentMA = 0\n self.PWR.set_ch1_voltage(self=self.PWR, vol=VDD_RF, cur=0.5)\n time.sleep(0.1)\n\n self.MXD2670.HCI_single_tone(self=self.MXD2670, freqMHz=ChFreqMHz, powerSel=TxPwr)\n TxGainSel = 0\n if TxPwr == TxPowerDef.TX_10_DBM:\n TxGainSel = HCI_For_Serial.TxGainTabIdxDef.TX_GAIN_5\n if TxPwr == TxPowerDef.TX_7_DBM:\n TxGainSel = HCI_For_Serial.TxGainTabIdxDef.TX_GAIN_4\n if TxPwr == TxPowerDef.TX_5_DBM:\n TxGainSel = HCI_For_Serial.TxGainTabIdxDef.TX_GAIN_3\n if TxPwr == TxPowerDef.TX_0_DBM:\n TxGainSel = HCI_For_Serial.TxGainTabIdxDef.TX_GAIN_2\n if TxPwr == TxPowerDef.TX_NEG5_DBM:\n TxGainSel = HCI_For_Serial.TxGainTabIdxDef.TX_GAIN_1\n if TxPwr == TxPowerDef.TX_NEG20_DBM:\n TxGainSel = HCI_For_Serial.TxGainTabIdxDef.TX_GAIN_0\n\n self.MXD2670.HCI_vco_ldo_voltage(self=self.MXD2670, powerSel=LdoVco)\n self.MXD2670.HCI_ldo_rf_voltage(self=self.MXD2670, ldoRf=LdoRf)\n self.MXD2670.HCI_tx_pa_acw_config(self=self.MXD2670, AcwVal=ACW, TxGainSel=TxGainSel)\n # print('read ACW', self.MXD2670.HCI_read_reg(self=self.MXD2670, reg_addr=0x40008148))\n time.sleep(0.1)\n self.SPEC.setCentralFreqMHz(self=self.SPEC, centralFreq=ChFreqMHz)\n time.sleep(0.3)\n self.OutputPowerDBM = self.SPEC.getMaxFreqPower(self=self.SPEC)\n # print(self.OutputPowerDBM)\n # time.sleep(0.5)\n self.VddRfCurrentMA = self.CUR.get_current_mA(self=self.CUR)\n\n # print(self.VddRfCurrentMA)\n return [self.OutputPowerDBM, self.VddRfCurrentMA]\n\n def PA_test_end(self):\n self.PWR.power_ch1_off(self=self.PWR)\n self.PWR.close(self=self.PWR)\n self.CUR.close(self=self.CUR)\n self.SPEC.disconnect(self=self.SPEC)\n\n\nif __name__ == \"__main__\":\n TempList = []\n PA = PA_Test\n\n PA.PA_channel_current_test_init(self=PA)\n\n ########## VMD ##########\n DATA = Result_data()\n result_data = Result_data()\n count = 0\n for FreqMHzIdx in range(StartMHz, StopMHz, 2):\n # HCI_single_tone(self=PA, freqMHz=FreqMHzIdx, powerSel=[TxPowerDef])\n TempList = PA.PA_channel_current(self=PA, ChFreqMHz=FreqMHzIdx, ACW=255, VDD_RF=1.3 + 0.12,\n LdoVco=HCI_For_Serial.VcoPowerDef.LDO_VCO_900mV,\n LdoRf=HCI_For_Serial.LdoRfDef.LDO_RF_1200mV,\n TxPwr=HCI_For_Serial.TxPowerDef.TX_10_DBM)\n print('ChannelFreq:', FreqMHzIdx,\n 'OutputPower:', '{:.2f}'.format(TempList[0]), 'dBm ', 'RFCurrent:',\n '{:.2f}'.format(TempList[1]), 'mA')\n DATA.fre_index[count] = FreqMHzIdx\n DATA.ReadPowerDBM[count] = round(TempList[0], 2)\n DATA.VddRFCurrentMA[count] = round(TempList[1], 2)\n count += 1\n # print('ChannelFreq:', DATA.fre_index,\n # 'OutputPower:', DATA.ReadPowerDBM, 'dBm ', 'RFCurrent:',\n # DATA.VddRFCurrentMA, 'mA')\n\n # time.sleep(0.2)\n\n PA.PA_test_end(self=PA)\n\n OUTPUT_path = 'D:\\\\'\n OUTPUT_end = BoardNum\n OUTPUT_form = '.xlsx'\n writer = pd.ExcelWriter(\n OUTPUT_path + datetime.now().strftime(\n 'PA_VMD_TxPwr_Current_' + Temp + '_' + '_%Y-%b-%d-%H-%M-%S') + OUTPUT_end + OUTPUT_form)\n\n fre_index = np.linspace(StartMHz, StopMHz, SamplesNum)\n # WRITER_DATA_INDEX = {'Frequence\\n(Mhz)': DATA.fre_index}\n WRITER_DATA_POWER = {'Tx_Power\\n(Mhz)': DATA.ReadPowerDBM}\n WRITER_DATA_CURRENT = {'RF_Current\\n(deg)': DATA.VddRFCurrentMA}\n\n # ALL_DATA = dict(**WRITER_DATA_INDEX, **WRITER_DATA_POWER, **WRITER_DATA_CURRENT)\n ALL_DATA = dict(**WRITER_DATA_POWER, **WRITER_DATA_CURRENT)\n # print(ALL_DATA)\n\n result_data = pd.DataFrame(ALL_DATA)\n result_data.to_excel(writer, 'Tx_Power', float_format='%.5f')\n writer.save()\n writer.close()\n\n ########## LP ##########\n DATA2 = Result_data()\n result_data2 = Result_data()\n PA.PA_channel_current_test_init(self=PA)\n\n count = 0\n for FreqMHzIdx in range(StartMHz, StopMHz, 2):\n\n TempList = PA.PA_channel_current(self=PA, ChFreqMHz=FreqMHzIdx, ACW=255, VDD_RF=1.3 + 0.12,\n LdoVco=HCI_For_Serial.VcoPowerDef.LDO_VCO_900mV,\n LdoRf=HCI_For_Serial.LdoRfDef.LDO_RF_1200mV,\n TxPwr=HCI_For_Serial.TxPowerDef.TX_0_DBM)\n print('ChannelFreq:', FreqMHzIdx,\n 'OutputPower:', '{:.2f}'.format(TempList[0]), 'dBm ', 'RFCurrent:',\n '{:.2f}'.format(TempList[1]), 'mA')\n DATA2.fre_index[count] = FreqMHzIdx\n DATA2.ReadPowerDBM[count] = round(TempList[0], 2)\n DATA2.VddRFCurrentMA[count] = round(TempList[1], 2)\n count += 1\n # print('ChannelFreq:', DATA.fre_index,\n # 'OutputPower:', DATA.ReadPowerDBM, 'dBm ', 'RFCurrent:',\n # DATA.VddRFCurrentMA, 'mA')\n\n # time.sleep(0.2)\n\n PA.PA_test_end(self=PA)\n\n OUTPUT_path2 = 'D:\\\\'\n OUTPUT_end2 = BoardNum\n OUTPUT_form2 = '.xlsx'\n writer2 = pd.ExcelWriter(\n OUTPUT_path2 + datetime.now().strftime(\n 'PA_LP_TxPwr_Current_' + Temp + '_' + '_%Y-%b-%d-%H-%M-%S') + OUTPUT_end2 + OUTPUT_form2)\n\n fre_index = np.linspace(StartMHz, StopMHz, SamplesNum)\n # WRITER_DATA_INDEX = {'Frequence\\n(Mhz)': DATA.fre_index}\n WRITER_DATA_POWER2 = {'Tx_Power\\n(Mhz)': DATA2.ReadPowerDBM}\n WRITER_DATA_CURRENT2 = {'RF_Current\\n(deg)': DATA2.VddRFCurrentMA}\n\n # ALL_DATA = dict(**WRITER_DATA_INDEX, **WRITER_DATA_POWER, **WRITER_DATA_CURRENT)\n ALL_DATA2 = dict(**WRITER_DATA_POWER2, **WRITER_DATA_CURRENT2)\n # print(ALL_DATA)\n\n result_data2 = pd.DataFrame(ALL_DATA2)\n result_data2.to_excel(writer2, 'Tx_Power', float_format='%.5f')\n writer2.save()\n writer2.close()\n\n","sub_path":"python/RF Test script_221102/Test Projects/PA_Channel_Power.py","file_name":"PA_Channel_Power.py","file_ext":"py","file_size_in_byte":9363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"255461569","text":"# SEG-GRAD-CAM visualization (from https://arxiv.org/pdf/2002.11434.pdf)\n# strongly inspired from https://www.pyimagesearch.com/2020/03/09/grad-cam-visualize-class-activation-maps-with-keras-tensorflow-and-deep-learning/\nfrom tensorflow.keras.models import Model\nimport tensorflow as tf\nimport numpy as np\nimport cv2\n\n\nclass SegGradCam:\n def __init__(self, model, class_id, layer_name=None):\n self.model = model\n self.class_id = class_id\n self.layer_name = layer_name\n\n if self.layer_name is None:\n self.layer_name = self.find_default_layer()\n\n def find_default_layer(self):\n \"\"\"\n Tries to find the final conv layer (called if the layer_name parameter is not provided)\n \"\"\"\n for layer in reversed(self.model.layers):\n # check to see if the layer has a 4D output\n if len(layer.output_shape) == 4:\n return layer.name\n # otherwise, we could not find a 4D layer so the GradCAM\n # algorithm cannot be applied\n raise ValueError(\"Could not find 4D layer. Cannot apply GradCAM.\")\n\n def compute_heatmap(self, image, eps=1e-8):\n \"\"\"\n Computes the heatmap by grad CAM\n \"\"\"\n\n # construct the grad model\n grad_model = Model(\n inputs=[self.model.inputs],\n outputs=[\n self.model.get_layer(self.layer_name).output,\n self.model.output\n ]\n )\n\n with tf.GradientTape() as tape:\n inputs = tf.cast(image, tf.float32)\n (conv_outputs, predictions) = grad_model(inputs)\n\n # retrieve the sum of logits for the mentioned class\n filtered_logits = predictions[:, :, :, self.class_id]\n loss = tf.reduce_sum(filtered_logits)\n\n grads = tape.gradient(loss, conv_outputs)\n\n # compute guided gradients\n positive_conv_outputs = tf.cast(conv_outputs > 0, \"float32\")\n positive_grads = tf.cast(grads > 0, \"float32\")\n guided_grads = positive_conv_outputs * positive_grads * grads\n\n # remove batch dimension (useless here because there is only 1 image)\n conv_outputs = conv_outputs[0]\n guided_grads = guided_grads[0]\n\n # compute weights (see eq in paper)\n weights = tf.reduce_mean(guided_grads, axis=(0, 1))\n\n # compute grad CAM\n mul = tf.multiply(weights, conv_outputs)\n cam = tf.math.reduce_sum(mul, axis=-1)\n\n # image dimensions\n (W, H) = (image.shape[2], image.shape[1])\n heatmap = cv2.resize(cam.numpy(), (W, H))\n\n numer = heatmap - np.min(heatmap)\n denom = (heatmap.max() - heatmap.min()) + eps\n heatmap = numer / denom\n heatmap = (heatmap * 255).astype(\"uint8\")\n\n return heatmap\n\n def overlay_heatmap(self, heatmap, image, alpha=0.5, colormap=cv2.COLORMAP_JET):\n # apply the supplied color map to the heatmap and then\n # overlay the heatmap on the input image\n heatmap = cv2.applyColorMap(heatmap, colormap)\n\n # change float32 image into uint8\n image *= 255\n image = image.astype(np.uint8)\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n\n output = cv2.addWeighted(image, alpha, heatmap, 1 - alpha, 0)\n # return a 2-tuple of the color mapped heatmap and the output,\n # overlaid image\n return (heatmap, output)\n","sub_path":"utils/seg_grad_cam.py","file_name":"seg_grad_cam.py","file_ext":"py","file_size_in_byte":3404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"369628762","text":"def crop_coordinate_mapping(input, pad=0, overwrite_file=True, path_output=None):\n \"\"\"\n Crops a padded coordinate mapping. The output file can either overwrite the input file or a new\n file is created with a suffix in a defined output directory.\n Inputs:\n *input: input file.\n *pad: image padding size.\n *overwrite_file: output file overwrites input file.\n *path_output: path where output is saved if input file is not overwritten.\n\n created by Daniel Haenelt\n Date created: 21-11-2018 \n Last modified: 22-01-2020\n \"\"\"\n import os\n import numpy as np\n import nibabel as nb\n from lib.io.get_filename import get_filename\n\n # define output folder\n if path_output is not None:\n if not os.path.exists(path_output):\n os.makedirs(path_output)\n\n # get input path and file name\n path, file, ext = get_filename(input)\n\n # load data\n data_img = nb.load(input)\n data_array = data_img.get_fdata()\n\n # get matrix size\n x_size = np.size(data_array,0)\n y_size = np.size(data_array,1)\n z_size = np.size(data_array,2)\n\n # crop image matrix\n data_array = data_array[pad:x_size-pad,pad:y_size-pad,pad:z_size-pad,:]\n\n # write cropped coordinate mapping\n output = nb.Nifti1Image(data_array, data_img.affine, data_img.header)\n output.set_data_dtype(np.float)\n\n # write coordinate mapping for each time point\n if overwrite_file is True:\n os.remove(input)\n nb.save(output, input)\n else:\n fileOUT = os.path.join(path_output, file+'_crop'+ext)\n nb.save(output,fileOUT)\n","sub_path":"lib/cmap/crop_coordinate_mapping.py","file_name":"crop_coordinate_mapping.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"251614855","text":"\"\"\"\nforms.py for form_boat_parade\n\"\"\"\n\nfrom django import forms\n\nfrom crispy_forms.helper import FormHelper\n\nfrom .models import Registration\n\n\nclass BoatParadeForm(forms.ModelForm):\n \"\"\"form for renewing membership\"\"\"\n\n class Meta:\n model = Registration\n fields = ('name',\n 'street',\n 'city',\n 'state',\n 'zip',\n 'home_phone',\n 'other_phone',\n 'email',\n 'boat_type',\n 'boat_length_in_feet'\n )\n","sub_path":"my_site/form_boat_parade/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"111702218","text":"from configs.pruning import get_prune_args\nfrom models.networks.convolutional.wide_resnet import *\nfrom models.networks.compress.prune.fischer import *\nfrom models.networks.convolutional.densenet import *\nimport torch.utils.model_zoo as model_zoo\nfrom torchvision import transforms\nimport torchvision\nimport torch\nimport time\nimport os\n\n\nargs = get_prune_args()\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = args.GPU\n\ndevice = torch.device(\"cuda:%s\" % '0' if torch.cuda.is_available() else \"cpu\")\n\n\nif args.net == 'res':\n model = WideResNet(args.depth, args.width, mask=args.mask)\nelif args.net =='dense':\n model = DenseNet(args.growth, args.depth, args.transition_rate, 10, True, mask=args.mask)\n\nmodel.load_state_dict(torch.load('checkpoints/%s.t7' % args.base_model,\n map_location='cpu')['state_dict'], strict=True)\n\n\nif args.resume:\n state = torch.load('checkpoints/%s.t7' % args.resume_ckpt, map_location=args.map_loc)\n model.load_state_dict(state, model_type=args.net)\n error_history = state['error_history']\n prune_history = state['prune_history']\n flop_history = state['flop_history']\n param_history = state['param_history']\n start_epoch = state['epoch']\n\nelse:\n error_history = []\n prune_history = []\n param_history = []\n start_epoch = 0\n\nmodel.to(device)\n\nnormMean = [0.49139968, 0.48215827, 0.44653124]\nnormStd = [0.24703233, 0.24348505, 0.26158768]\nnormTransform = transforms.Normalize(normMean, normStd)\n\nprint('==> Preparing data..')\nnum_classes = 10\n\ntransform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normTransform\n])\n\ntransform_val = transforms.Compose([\n transforms.ToTensor(),\n normTransform\n\n])\n\ntrainset = torchvision.datasets.CIFAR10(root=args.data_loc,\n train=True, download=True, transform=transform_train)\nvalset = torchvision.datasets.CIFAR10(root=args.data_loc,\n train=False, download=True, transform=transform_val)\n\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=args.batch_size, shuffle=True,\n num_workers=args.workers,\n pin_memory=False)\nvalloader = torch.utils.data.DataLoader(valset, batch_size=50, shuffle=False,\n num_workers=args.workers,\n pin_memory=False)\n\nprune_count = 0\npruner = Pruner()\npruner.prune_history = prune_history\n\nNO_STEPS = args.prune_every\n\n\ndef finetune():\n batch_time = AverageMeter()\n data_time = AverageMeter()\n losses = AverageMeter()\n top1 = AverageMeter()\n top5 = AverageMeter()\n\n # switch to train mode\n model.train()\n\n end = time.time()\n\n dataiter = iter(trainloader)\n\n for i in range(0, NO_STEPS):\n\n try:\n input, target = dataiter.next()\n except StopIteration:\n dataiter = iter(trainloader)\n input, target = dataiter.next()\n\n # measure data loading time\n data_time.update(time.time() - end)\n\n input, target = input.to(device), target.to(device)\n\n # compute output\n output = model(input)\n\n loss = criterion(output, target)\n\n # measure accuracy and record loss\n err1, err5 = get_error(output.detach(), target, topk=(1, 5))\n\n losses.update(loss.item(), input.size(0))\n top1.update(err1.item(), input.size(0))\n top5.update(err5.item(), input.size(0))\n\n # compute gradient and do SGD step\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n if i % args.print_freq == 0:\n print('Prunepoch: [{0}][{1}/{2}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Data {data_time.val:.3f} ({data_time.avg:.3f})\\t'\n 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'\n 'Error@1 {top1.val:.3f} ({top1.avg:.3f})\\t'\n 'Error@5 {top5.val:.3f} ({top5.avg:.3f})'.format(\n epoch, i, NO_STEPS, batch_time=batch_time,\n data_time=data_time, loss=losses, top1=top1, top5=top5))\n\n\ndef prune():\n print('Pruning')\n if args.random is False:\n if args.l1_prune is False:\n print('fisher compress')\n pruner.fisher_prune(model, prune_every=args.prune_every)\n else:\n print('l1 compress')\n pruner.l1_prune(model, prune_every=args.prune_every)\n else:\n print('random compress')\n pruner.random_prune(model, )\n\n\ndef freeze_resnet(model, layer_to_freeze):\n \"\"\"\n layer_to_freeze should either be a list of ints\n or a list of name of parameters\n \"\"\"\n ct = 0\n for child in model.children():\n ct += 1\n if ct < 7:\n for name, param in child.named_parameters():\n if name in layer_to_freeze:\n param.requires_grad = False\n\n\ndef validate():\n global error_history\n\n batch_time = AverageMeter()\n data_time = AverageMeter()\n\n losses = AverageMeter()\n top1 = AverageMeter()\n top5 = AverageMeter()\n\n # switch to evaluate mode\n model.eval()\n\n end = time.time()\n\n for i, (input, target) in enumerate(valloader):\n\n # measure data loading time\n data_time.update(time.time() - end)\n\n input, target = input.to(device), target.to(device)\n\n # compute output\n output = model(input)\n\n loss = criterion(output, target)\n\n # measure accuracy and record loss\n err1, err5 = get_error(output.detach(), target, topk=(1, 5))\n\n losses.update(loss.item(), input.size(0))\n top1.update(err1.item(), input.size(0))\n top5.update(err5.item(), input.size(0))\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n if i % args.print_freq == 0:\n print('Test: [{0}/{1}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'\n 'Error@1 {top1.val:.3f} ({top1.avg:.3f})\\t'\n 'Error@5 {top5.val:.3f} ({top5.avg:.3f})'.format(\n i, len(valloader), batch_time=batch_time, loss=losses,\n top1=top1, top5=top5))\n\n print(' * Error@1 {top1.avg:.3f} Error@5 {top5.avg:.3f}'\n .format(top1=top1, top5=top5))\n\n # Record Top 1 for CIFAR\n error_history.append(top1.avg)\n\n\nif __name__ == '__main__':\n\n criterion = nn.CrossEntropyLoss()\n\n optimizer = torch.optim.SGD([v for v in model.parameters() if v.requires_grad],\n lr=args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay)\n\n for epoch in range(start_epoch, args.no_epochs):\n\n print('Epoch %d:' % epoch)\n print('Learning rate is %s' % [v['lr'] for v in optimizer.param_groups][0])\n\n # finetune for one epoch\n finetune()\n # # evaluate on validation set\n if epoch != 0 and ((epoch % args.val_every == 0) or (epoch + 1 == args.no_epochs)): # Save at last epoch!\n validate()\n\n # Error history is recorded in validate(). Record params here\n no_params = pruner.get_cost(model) + model.fixed_params\n param_history.append(no_params)\n\n # Save before compress\n if epoch != 0 and ((epoch % args.save_every == 0) or (epoch + 1 == args.no_epochs)): #\n filename = 'checkpoints/%s_%d_prunes.t7' % (args.save_file, epoch)\n save_checkpoint({\n 'epoch': epoch + 1,\n 'state_dict': model.state_dict(),\n 'error_history': error_history,\n 'param_history': param_history,\n 'prune_history': pruner.prune_history,\n }, filename=filename)\n\n ## Prune\n prune()","sub_path":"prune/resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":8043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"19100703","text":"import json\n\ndata = [\n {\"name\": \"Argotia\",\n \"latitude\": 43.2590929,\n \"longitude\": -2.9244257,\n \"address\": \"Plaza Nueva, 48005 Bilbao, Vizcaya, Spain\"},\n {\"name\": \"Sorginzulo\",\n \"latitude\": 43.259387,\n \"longitude\": -2.9233905,\n \"address\": \"Plaza Nueva, 12, 48005 Bilbao, BI, Spain\"}\n]\n\nwith open('data/bilbao_restaurants2.json', 'w') as file:\n file.write(json.dumps(data, indent=4))\n","sub_path":"dummy.py","file_name":"dummy.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"495988306","text":"import paho.mqtt.client as mqtt\nimport json, time, random\nfrom datetime import datetime\nfrom time import sleep\n\n# Paramètres de connexion à compléter\n# Nom du groupe sans espaces avec la nomenclature WEB2 ou WEB3\n# Exemple : WEB2-GROUPE3\n\n# Login et mot de passe du groupe\n\n\nGROUPNAME = \"GROUPE7\"\n\nMQTT_USERNAME = \"GROUPE7\"\nMQTT_PASSWORD = \"64459019\"\nMQTT_BROKER = \"hetic.arcplex.fr\"\n# un ID différent par Node\nNODE_ID = [\n \"12345678\",\n \"7654321\",\n \"1274555678\",\n \"7654931\",\n \"845217199\",\n \"741852963\",\n \"12342255678\",\n \"7622554321\",\n \"127455777\",\n \"7652254931\",\n \"999999\",\n \"4444555\",\n]\n\n# ID du sensor\nSENSOR_ID_1 = 126\nSENSOR_ID_2 = 133\nSENSOR_ID_3 = 109\n\n\n# Type de donnée renvoyée : Random 0 ou 1\nVALMIN = 28\nVALMAX = 29\n\nclient = mqtt.Client(\"client\")\nclient.username_pw_set(username=MQTT_USERNAME, password=MQTT_PASSWORD)\nclient.connect(MQTT_BROKER)\n\n\ndef run(condition):\n while datetime.now().minute not in {0, 3, 8, 15, 23, 30, 35, 40, 45, 50, 55}:\n sleep(1)\n\n def task():\n for node in NODE_ID:\n MQTT_TOPIC = GROUPNAME + \"/\" + node + \"/\" + str(SENSOR_ID_1)\n MQTT_MSG = json.dumps(\n {\n \"source_address\": node,\n \"sensor_id\": SENSOR_ID_1,\n \"tx_time_ms_epoch\": int(time.time()),\n \"data\": {\"value\": round(random.uniform(0, 100), 2)},\n }\n )\n\n client.publish(MQTT_TOPIC, MQTT_MSG)\n print(\"MQTT Mis à jour - Node %s Timestamp : %s\" % (node, int(time.time())))\n MQTT_TOPIC = GROUPNAME + \"/\" + node + \"/\" + str(SENSOR_ID_2)\n MQTT_MSG = json.dumps(\n {\n \"source_address\": node,\n \"sensor_id\": SENSOR_ID_2,\n \"tx_time_ms_epoch\": int(time.time()),\n \"data\": {\"value\": round(random.uniform(0, 50), 2)},\n }\n )\n\n client.publish(MQTT_TOPIC, MQTT_MSG)\n print(\"MQTT Mis à jour - Node %s Timestamp : %s\" % (node, int(time.time())))\n MQTT_TOPIC = GROUPNAME + \"/\" + node + \"/\" + str(SENSOR_ID_3)\n MQTT_MSG = json.dumps(\n {\n \"source_address\": node,\n \"sensor_id\": SENSOR_ID_3,\n \"tx_time_ms_epoch\": int(time.time()),\n \"data\": {\"value\": round(random.uniform(0, 65535), 2)},\n }\n )\n\n client.publish(MQTT_TOPIC, MQTT_MSG)\n print(\"MQTT Mis à jour - Node %s Timestamp : %s\" % (node, int(time.time())))\n\n task()\n while condition == True:\n sleep(60 * 15)\n task()\n\n\nrun(True)\n","sub_path":"HETIC_B.py","file_name":"HETIC_B.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"478059214","text":"\"\"\"Helpful utilities for feature engineering\"\"\"\nfrom __future__ import absolute_import\nimport numpy as np\nimport mjolnir.spark\nfrom pyspark import SparkContext\nfrom pyspark.ml.feature import QuantileDiscretizer\nfrom pyspark.ml.linalg import Vectors, VectorUDT\nfrom pyspark.sql import functions as F\nimport pyspark.sql.types\n\n\ndef append_features(df, *cols):\n \"\"\"Append features from columns to the features vector.\n\n Parameters\n ----------\n df : pyspark.sql.DataFrame\n cols : list of str\n\n Returns\n -------\n pyspark.sql.DataFrame\n \"\"\"\n def add_features(feat, *other):\n raw = feat.toArray()\n return Vectors.dense(np.append(raw, list(map(float, other))))\n add_features_udf = F.udf(add_features, VectorUDT())\n new_feat_list = df.schema['features'].metadata['features'] + cols\n return df.withColumn('features', mjolnir.spark.add_meta(\n df._sc, add_features_udf('features', *cols), {'features': new_feat_list}))\n\n\ndef zero_features(df, *feature_names):\n \"\"\"Zero out features in the feature vector.\n\n Parameters\n ----------\n df : pyspark.sql.DataFrame\n feature_names : list of str\n\n Returns\n -------\n pyspark.sql.DataFrame\n \"\"\"\n features = df.schema['features'].metadata['features']\n idxs = [features.index(name) for name in feature_names]\n\n def zero_features(feat):\n raw = feat.toArray()\n for idx in idxs:\n raw[idx] = 0.\n return Vectors.dense(raw)\n zero_features_udf = F.udf(zero_features, VectorUDT())\n return df.withColumn('features', mjolnir.spark.add_meta(\n df._sc, zero_features_udf('features'), {'features': features}))\n\n\ndef explode_features(df, features=None):\n \"\"\"Convert feature vector into individual columns\n\n Parameters\n ----------\n df : pyspark.sql.DataFrame\n features : list of str or None\n\n Returns\n -------\n pyspark.sql.DataFrame\n \"\"\"\n if features is None:\n features = df.schema['features'].metadata['features']\n\n def extract_feature(features, idx):\n return float(features[idx])\n extract_feature_udf = F.udf(extract_feature, pyspark.sql.types.FloatType())\n cols = [extract_feature_udf('features', F.lit(idx)).alias(name) for idx, name in enumerate(features)]\n return df.select('*', *cols)\n\n\ndef quantiles(df, input_col):\n try:\n qds = QuantileDiscretizer(\n # 254 is used so the 255th can be inf\n numBuckets=254, inputCol=input_col, outputCol='bucketed',\n relativeError=1./2550, handleInvalid='error')\n return qds.fit(df).getSplits()\n except Exception as e:\n print(e)\n raise\n\n\ndef select_features(sc, df, all_features, n_features, pool, n_partitions=None, algo='mrmr'):\n \"\"\"Select a set of features from a dataframe\n\n Parameters\n ----------\n sc : pyspark.SparkContext\n df : pyspark.sql.DataFrame\n For reasonable performance this should be read from disk\n in parquet format so stages can pull a single column instead\n of the whole dataset.\n all_features : list of str\n List of columns in df to select from in the same order as\n stored in the 'features' column vector.\n n_features : int\n The number of features to select\n pool : multiprocessing.dummy.Pool\n algo : str\n The algorithm to use in InfoThSelector\n\n Returns\n -------\n list of str\n \"\"\"\n if n_features >= len(all_features):\n # Requested more features than we have, return them all\n return all_features\n\n if n_partitions is None:\n # The lib suggests we should have no more than 1 partition\n # per feature, and ideally less. 3 is arbitrary.\n features_per_partition = 3\n n_partitions = int(len(all_features)/features_per_partition)\n\n # InfoThSelector expects a double\n df = df.select(F.col('label').cast('double').alias('label'), 'features', *all_features)\n # TODO: QuantileDiscretizer in spark 2.2 can do multiple columns\n # at once instead of mapping over the list of features.\n df_quant = df.coalesce(10)\n quants = pool.map(lambda f: quantiles(df_quant, f), all_features)\n max_bin = max(len(x) for x in quants)\n # Build up an array that indicates the split positions\n # for the discretizer\n j_quants = SparkContext._gateway.new_array(\n sc._jvm.float, len(quants), max_bin)\n for i, q in enumerate(quants):\n for j, value in enumerate(q):\n j_quants[i][j] = value\n for j in range(max_bin - len(q)):\n j_quants[i][j] = float('inf')\n\n # Use this discretizer instead of bucketizer returned by\n # QuantileDiscretizer because it does all features together as a vector\n # which we need for InfoThSelector. Could potentially replace with\n # QuantileDiscretizer multi-column and vector assembler in spark 2.2\n discretizer = (\n sc._jvm.org.apache.spark.ml.feature.DiscretizerModel(\"???\", j_quants)\n .setInputCol(\"features\")\n .setOutputCol(\"features\"))\n j_df_discretized = discretizer.transform(df._jdf)\n\n selector = (\n sc._jvm.org.apache.spark.ml.feature.InfoThSelector()\n .setSelectCriterion(algo)\n # TODO: How should this be set? On our largest datasets this is ~40M\n # per partition and everything seems to work reasonably. On the smaller\n # ones this results in 500kB partitions and we probably waste a bunch\n # of orchestration time.\n .setNPartitions(n_partitions)\n .setNumTopFeatures(n_features)\n .setFeaturesCol(\"features\"))\n selector_model = selector.fit(j_df_discretized)\n selected_features = list(selector_model.selectedFeatures())\n return [all_features[i] for i in selected_features]\n","sub_path":"mjolnir/feature_engineering.py","file_name":"feature_engineering.py","file_ext":"py","file_size_in_byte":5737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"106646081","text":"from django_codemod.visitors import (\n HttpUrlQuotePlusTransformer,\n HttpUrlQuoteTransformer,\n HttpUrlUnQuotePlusTransformer,\n HttpUrlUnQuoteTransformer,\n IsSafeUrlTransformer,\n)\nfrom tests.visitors.base import BaseVisitorTest\n\n\nclass TestHttpUrlQuoteTransformer(BaseVisitorTest):\n\n transformer = HttpUrlQuoteTransformer\n\n def test_simple_substitution(self) -> None:\n before = \"\"\"\n from django.utils.http import urlquote\n\n result = urlquote(content)\n \"\"\"\n after = \"\"\"\n from urllib.parse import quote\n\n result = quote(content)\n \"\"\"\n self.assertCodemod(before, after)\n\n\nclass TestHttpUrlQuotePlusTransformer(BaseVisitorTest):\n\n transformer = HttpUrlQuotePlusTransformer\n\n def test_simple_substitution(self) -> None:\n before = \"\"\"\n from django.utils.http import urlquote_plus\n\n result = urlquote_plus(content)\n \"\"\"\n after = \"\"\"\n from urllib.parse import quote_plus\n\n result = quote_plus(content)\n \"\"\"\n self.assertCodemod(before, after)\n\n\nclass TestHttpUrlUnQuoteTransformer(BaseVisitorTest):\n\n transformer = HttpUrlUnQuoteTransformer\n\n def test_simple_substitution(self) -> None:\n before = \"\"\"\n from django.utils.http import urlunquote\n\n result = urlunquote(content)\n \"\"\"\n after = \"\"\"\n from urllib.parse import unquote\n\n result = unquote(content)\n \"\"\"\n self.assertCodemod(before, after)\n\n\nclass TestHttpUrlUnQuotePlusTransformer(BaseVisitorTest):\n\n transformer = HttpUrlUnQuotePlusTransformer\n\n def test_simple_substitution(self) -> None:\n before = \"\"\"\n from django.utils.http import urlunquote_plus\n\n result = urlunquote_plus(content)\n \"\"\"\n after = \"\"\"\n from urllib.parse import unquote_plus\n\n result = unquote_plus(content)\n \"\"\"\n self.assertCodemod(before, after)\n\n\nclass TestIsSafeUrlTransformer(BaseVisitorTest):\n\n transformer = IsSafeUrlTransformer\n\n def test_simple_substitution(self) -> None:\n before = \"\"\"\n from django.utils.http import is_safe_url\n\n result = is_safe_url('http://test.com/some-path', None)\n \"\"\"\n after = \"\"\"\n from django.utils.http import url_has_allowed_host_and_scheme\n\n result = url_has_allowed_host_and_scheme('http://test.com/some-path', None)\n \"\"\"\n self.assertCodemod(before, after)\n","sub_path":"tests/visitors/test_http.py","file_name":"test_http.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"503741377","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport string \n\ndef decisao(palavra, resto):\n\t\"\"\"retorna a decisão de qual botão desarma a bomba\"\"\"\n\tif(resto == 11):\n\t\treturn \"Encontrado! O botão \"+palavra[0]+\" desarma a bomba!\"\n\telse:\n\t\treturn \"O botão \"+palavra[0]+\" oferece perigo\"\n\ndef calculo(palavras, somatorio):\n\t\"\"\" Retorna o resto da divisão do código pela cor \"\"\"\n\treturn decisao(palavras,somatorio[1]%somatorio[0])\n\ndef tabela_traducao():\n\t\"\"\"Gera a tabela de tradução\"\"\"\n\treturn {j:i+1 for i,j in enumerate(string.ascii_uppercase)}\n\t\ndef somatorio_traducao(valores):\n\t\"\"\"Traduz e retorna somatório\"\"\"\n\titens = tabela_traducao()\n\tsomatorio = []\n\tpalavras = valores.split()\n\t\n\tfor unidade in palavras:\n\t\tsomatorio.append(sum([itens[i] for i in unidade]))\n\treturn calculo(palavras, somatorio)\n\t\nif __name__ == \"__main__\":\n\tprint(somatorio_traducao('VERMELHO IAJNLITLUNAYDHFAA'))\n\tprint(somatorio_traducao('AZUL EFDLUMHBNDRRTM'))\n\tprint(somatorio_traducao('VERDE ZTRAHDSICFQH'))\n\tprint(somatorio_traducao('AMARELO QPSKXDLPWFLAAKHY'))\n","sub_path":"escolha_botao.py","file_name":"escolha_botao.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"431977157","text":"#!/usr/bin/env python3\n\n\nimport pygame\nfrom arena import *\nfrom pacman import *\nfrom pacman_map import *\n\narena = Checker(232, 300)\n#contBiscotti = 0\nfor x, y, w, h in walls_pos:\n Wall(arena, x, y, w, h)\nfor x, y in cookies_pos:\n #contBiscotti+=1\n Cookie(arena, x, y)\nfor x, y in powers_pos:\n #contBiscotti+=1 #perché quando il pacman mangia un powercookie ottiene 2 punti\n Power(arena, x, y)\n##\n##print(contBiscotti)\n\npacman = PacMan(arena, 112, 184)\nGhost(arena, 112, 88, 0, 64, -1, -2)\nGhost(arena, 112, 88, 0, 80, 240, -1)\nGhost(arena, 112, 88, 0, 96, -1, 280)\nGhost(arena, 112, 88, 0, 112, 240, 280)\n\npygame.init()\npygame.mixer.init()\n\n##myfont = pygame.font.SysFont(\"monospace\", 15)\nmyfont = pygame.font.Font(\"crackman-front.ttf\",16)\n\nclock = pygame.time.Clock()\nscreen = pygame.display.set_mode(arena.size())\nbackground = pygame.image.load('pacman_background.png')\nsprites = pygame.image.load('pacman_sprites.png')\n\ncherry = False\npunteggioCasuale= randrange(50,300)\n#print(punteggioCasuale)\ni = 0\nplaying = True\nwhile playing:\n for e in pygame.event.get():\n if e.type == pygame.QUIT:\n playing = False \n elif e.type == pygame.KEYDOWN:\n if e.key == pygame.K_UP:\n pacman.go_up()\n elif e.key == pygame.K_DOWN:\n pacman.go_down()\n elif e.key == pygame.K_LEFT:\n pacman.go_left()\n elif e.key == pygame.K_RIGHT:\n pacman.go_right()\n elif e.type == pygame.KEYUP:\n pacman.stay()\n\n arena.move_all() # Game logic\n\n screen.blit(background, (0, 0))\n for a in arena.actors():\n if not isinstance(a, Wall):\n x, y, w, h = a.rect()\n xs, ys = a.symbol()\n screen.blit(sprites, (x, y), area=(xs, ys, w, h))\n\n # clean the box belove the game-screen\n pygame.draw.rect(screen, (0, 0, 0), (0, 256, 232, 40))\n # render text\n punteggio = myfont.render(\"Punteggio: \"+str(pacman._punteggio), True, (255,255,0))\n screen.blit(punteggio, (10, 260))\n \n vite = myfont.render(\"Vite: \"+str(pacman._vite), True, (255,255,0))\n screen.blit(vite, (150,260))\n \n # power rimanente per il pacman, che può mangiare i fantasmi\n if pacman._power > 0:\n pygame.draw.rect (screen, (255, 255, 0), (1, 278, pacman._power, 10))\n \n for a in arena._actors: \n if isinstance(a,Ghost):\n pygame.draw.rect (screen, (255, 0, 255), (1, 290, a._movement, 5))\n \n \n if pacman._punteggio >= punteggioCasuale and cherry==False:\n cherry = True\n Cherry(arena,112,88)\n \n #if pacman._biscottiMangiati>=contBiscotti:\n if arena.check_win()==True:\n pygame.draw.rect(screen, (0, 0, 0), (0, 100, 232, 60))\n sconfitta = myfont.render(\"HAI VINTO!\", True, (255,255,0))\n screen.blit(sconfitta,(60, 120))\n playing = False\n\n if pacman._vite == 0:\n #if arena.check_lose()==True:\n pygame.draw.rect(screen, (0, 0, 0), (0, 100, 232, 60))\n sconfitta = myfont.render(\"HAI PERSO!\", True, (255,255,0))\n screen.blit(sconfitta,(60, 120))\n playing = False\n \n pygame.display.flip()\n #così come nel pacman reale la musica iniziale si sente tutta e dopo si può cominciare a giocare\n## if i==0:\n## pygame.mixer.music.load(\"SFX_Pacman/Pacman Opening Song.mp3\")\n## pygame.mixer.music.play()\n## i+=1\n## while pygame.mixer.music.get_busy()==True:\n## pygame.event.wait()\n clock.tick(30)\n \npygame.quit()\n\n","sub_path":"pacman_game.py","file_name":"pacman_game.py","file_ext":"py","file_size_in_byte":3844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"171384698","text":"import cv2\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nimport base64\n\ndef cv_img_2_tf_img(img):\n img_cv = cv2.imencode('.jpg', img)[1]\n data_encode = np.array(img_cv)\n str_encode = data_encode.tobytes()\n img_tf = tf.image.decode_jpeg(str_encode, channels=0)\n return img_tf\n\ndef main():\n model = keras.models.load_model('./python/CNNModle/driver_model_new.h5')\n # print(model.summary())\n while True:\n lines = input() ### This's for multiple input from node\n lineL = lines.split(\",\")\n num = lineL[0]\n lines = lineL[1]\n lines = base64.b64decode(lines)\n lines = np.frombuffer(lines, dtype=\"uint8\").reshape(-1,1)\n ### reconstruct image as an numpy array\n frame = cv2.imdecode(lines, cv2.IMREAD_UNCHANGED)\n ### resize to tf format\n frame = cv2.resize(frame, (400, 600))\n tf_img = cv_img_2_tf_img(frame)\n tf_img = tf.keras.preprocessing.image.img_to_array(tf_img)\n tf_img = tf_img / 255.0 # normalize\n tf_img = np.expand_dims(tf_img, axis=0)\n result = model.predict(tf_img)\n score = result[0][1]/(result[0][0]+result[0][1])\n outMsg = f'\"inputID\":{num},\"score\":{score}'\n outMsg = \"{\"+outMsg+\"}\"\n print(outMsg)\n # 第一個數字為正常,第二個數字為疲勞\n # if np.argmax(result) == 0:\n # print('normal person')\n # else:\n # print('tired person')\n\nif __name__==\"__main__\":\n main()","sub_path":"python/CNNModle/nodeFatigueDetectByImg.py","file_name":"nodeFatigueDetectByImg.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"179746382","text":"import os, sys\n\nfname = input(\"Enter your file name : \")\nif os.path.isfile(fname):\n f = open(fname, \"r+\")\n print(\"file exist\")\n\nelse:\n\n print(\"file doesnot exist\")\n sys.exit()\nlc = 0\nwc = 0\ncc = 0\nfor line in f:\n lc += 1\n words = line.split()\n\n wc += len(words)\n cc += len(line)\nprint(cc, wc, lc)\n","sub_path":"files/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"420670101","text":"import csv\r\n#import sys\r\n\r\n\r\ndef main():\r\n\tc_name = \"\"\r\n\r\n\r\n\tcompanycsv = open('company_info.csv','r')\r\n\tc_info_with_names_itr = open('company_info_with_names.csv','w')\r\n\twith open('constituents.csv', 'r') as companylist:\r\n\t companylist_itr = csv.reader(companylist)\r\n\t companycsv_itr = csv.reader(companycsv)\r\n\t next(companylist_itr) # Skip the header row/// Symbol -- Name -- Sector\r\n\t for row in companycsv_itr:\r\n\t \tfor item in companylist_itr:\r\n\t \t#\ty+=1\r\n\t \t\tif item[0] == row[1]: # if the ticker IDs match\r\n\t \t\t\tc_name = item[1]\t# set c_uuid to that company UUID\r\n\t \t\t\tbreak\r\n\t \tc_info_with_names_itr.write(\"{},{},{}\\n\".format(row[0], row[1], c_name))\r\n\r\n\r\n\tcompanycsv.close()\r\n\tc_info_with_names_itr.close()\r\n\tcompanylist.close()\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n\tmain()","sub_path":"data_simfin parsing/Adding Company Names/MatchCompanyNametoData.py","file_name":"MatchCompanyNametoData.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"345071429","text":"#!/usr/bin/python3\n\n\"\"\"\nRoot module for the build-order tool.\n\"\"\"\n\nimport devpipeline_core.resolve\n\n\n# For some reason, setup.py can't find this in the build_order moudle. Move it\n# back when I figure out why.\ndef _print_list(targets, components, tasks):\n def _make_print_fn():\n if len(tasks) > 1:\n return lambda component_task: \"{}.{}\".format(\n component_task[0], component_task[1]\n )\n return lambda component_task: component_task[0]\n\n dm = devpipeline_core.resolve.calculate_dependencies(targets, components, tasks)\n build_order = []\n task_queue = dm.get_queue()\n print_fn = _make_print_fn()\n for component_tasks in task_queue:\n for component_task in component_tasks:\n build_order.append(print_fn(component_task))\n task_queue.resolve(component_task)\n print(build_order)\n\n\n_LIST_TOOL = (_print_list, \"Print a sequential order of components.\")\n","sub_path":"lib/devpipeline_buildorder/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"156742152","text":"def memoized(f):\n import functools\n cachedResults = dict()\n @functools.wraps(f)\n def wrapper(*args):\n if args not in cachedResults:\n cachedResults[args] = f(*args)\n return cachedResults[args]\n return wrapper\n\n@memoized\ndef fib(n):\n if n == 0: return 0\n elif n == 1: return 1\n else: return fib(n-1) + fib(n-2)\n\ndef Problem_2():\n # Answer: 4613732\n sum = 0\n i = 0\n while fib(i) < 4000000:\n if fib(i) % 2 == 0:\n sum += fib(i)\n i += 1\n return sum\n\nprint(Problem_2())\n","sub_path":"002.py","file_name":"002.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"83821662","text":"word1 = \"abcde\"\nword2 = \"abc\"\nret = 0\ncur1 = 0\ncur2 = 0\nwhile(len(word1) < len(word2)):\n #需要增加元素\n while(word1[cur1] == word2[cur2]):\n cur1 += 1\n cur2 += 1\n if cur1 == len(word1):\n cur1 -= 1\n word1 = word1[0:cur1] + word2[cur2] + word1[cur1:]\n ret += 1\nwhile(len(word1) > len(word2)):\n #需要删除元素\n while(word1[cur1] == word2[cur2]):\n cur1 += 1\n cur2 += 1\n if cur2 == len(word2):\n cur2 -= 1\n word1 = word1[0:cur1] + word1[cur1 + 1:]\n ret += 1\n## 进行替换\nfor i in range(len(word1)):\n if word1[i] == word2[i]:\n continue\n else:\n word1[i] == word2[i]\n ret += 1\nprint(ret)\n","sub_path":"hard/72.编辑距离.py","file_name":"72.编辑距离.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"609261364","text":"\r\nfrom surprise import Dataset\r\nfrom surprise import Reader\r\nfrom surprise import accuracy\r\nfrom surprise.model_selection import KFold\r\n#cross_validate() 是被调用的外部接口,fit_and_score() 是在 cross_validate() 中被调用的。\r\n #输入有算法对象,数据集,需要测量的指标,交叉验证的次数等。它对输入的数据 data,分成 cv 份,然后每次选择其中一份作为测试集,其余的作为训练集。在数据集划分完后,对它们分别调用 fit_and_score(),去进行算法拟合。\r\n #对数据集的划分不是静态全部划分完,然后分别在数据集上进行训练和验证,而是利用输入的 data 构造一个生成器,每次抛出一组划分完的结果。\r\n #对 fit_and_score() 函数,它对输入的算法在输入的训练集上进行拟合,然后在输入的测试集上进行验证,再计算需要的指标。\r\nfrom surprise.model_selection import cross_validate\r\nimport pandas as pd\r\nnews = pd.read_csv('ratings.csv')\r\nprint(news.head)\r\n\r\n# 数据读取\r\nreader = Reader(line_format='user item rating timestamp', sep=',', skip_lines=1)\r\ndata = Dataset.load_from_file('./ratings.csv', reader=reader)\r\ntrain_set = data.build_full_trainset()\r\n\r\n\r\nfrom surprise import KNNWithZScore\r\nalgo=KNNWithZScore(k=50, sim_options={'user_based': False, 'verbose': 'True'})\r\nalgo.fit(train_set)\r\nuid=str(196)\r\niid=str(332)\r\npred=algo.predict(uid,iid,r_ui=4,verbose=True)\r\n\r\nkf=KFold(n_splits=3)\r\nfor trainset,testset in kf.split(data):\r\n algo.fit(trainset)\r\n predictions=algo.test(testset)\r\n #计算RMSE,AME\r\n accuracy.rmse(predictions,verbose=True)\r\n accuracy.mae(predictions,verbose=True)\r\n\r\n\r\n### 使用协同过滤正态分布 User based\r\nfrom surprise import KNNWithZScore\r\nalgo = KNNWithZScore(k=50, sim_options={'user_based': False, 'verbose': 'True'})\r\nperf = cross_validate(algo, data, measures=['RMSE', 'MAE'], cv=3)\r\nprint(\"KNNWithZScore Results:\",perf)\r\nprint(\"-\"*118)\r\n\r\n### 使用协同过滤正态分布 Item based\r\nfrom surprise import KNNWithZScore\r\nalgo = KNNWithZScore(k=50, sim_options={'user_based': True, 'verbose': 'True'})\r\nperf = cross_validate(algo, data, measures=['RMSE', 'MAE'], cv=3)\r\nprint(\"KNNWithZScore Results:\",perf)\r\nprint(\"-\"*118)\r\n\r\n### 使用基础版协同过滤\r\nfrom surprise import KNNBasic\r\nalgo = KNNBasic(k=50, sim_options={'user_based': False, 'verbose': 'True'})\r\nperf = cross_validate(algo, data, measures=['RMSE', 'MAE'], cv=3)\r\nprint(\"KNNBasic Results:\",perf)\r\nprint(\"-\"*118)\r\n\r\n### 使用均值协同过滤\r\nfrom surprise import KNNWithMeans\r\nalgo = KNNWithMeans(k=50, sim_options={'user_based': False, 'verbose': 'True'})\r\nperf = cross_validate(algo, data, measures=['RMSE', 'MAE'], cv=3)\r\nprint(\"KNNWithMeans Results:\",perf)\r\nprint(\"-\"*118)\r\n\r\n### 使用协同过滤baseline\r\nfrom surprise import KNNBaseline\r\nalgo = KNNBaseline(k=50, sim_options={'user_based': False, 'verbose': 'True'})\r\nperf = cross_validate(algo, data, measures=['RMSE', 'MAE'], cv=3)\r\nprint(\"KNNBaseline Results:\",perf)\r\nprint(\"-\"*118)\r\n","sub_path":"CF KNNBV01.py","file_name":"CF KNNBV01.py","file_ext":"py","file_size_in_byte":3069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"603964512","text":"import scrapy\nimport re\nfrom scrapy.loader import ItemLoader\nfrom sports_collectors.items import BaseballPlayerItem\n\nclass BaseballPlayerSpider(scrapy.Spider):\n name = \"baseball\"\n\n def start_requests(self):\n urls = []\n alphabets = [chr(ord('A')+i) for i in range(26)]\n start = 'https://www.baseball-reference.com/players/{}/'\n\n for l in alphabets:\n urls.append(start.format(l))\n\n for url in urls:\n yield scrapy.Request(url=url, callback=self.parse)\n\n def parse(self, response):\n il = ItemLoader(item=BaseballPlayerItem(), response=response)\n il.add_xpath('name', '//div[@id=\"div_players\"]/p/a/text()')\n il.add_value('playertype', 'baseball')\n il.add_xpath('pos', '//div[@id=\"div_players\"]/p/text()', re='\\([\\w]*[-\\w]*\\)')\n il.add_xpath('year', '//div[@id=\"div_players\"]/p/text()', re='[\\d]{4}-[\\d]{4}')\n return il.load_item()\n","sub_path":"data/collectors/sports_collectors/sports_collectors/spiders/BaseballPlayerSpider.py","file_name":"BaseballPlayerSpider.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"223527747","text":"## sudoku\n## js 5.11.2006\n\nfrom string import *\n\nfrom numarray import *\n\n\n## Sudoku as a search problem\n## state is a 9x9 numarray, values ranging from 0 to 9 included\n## 0 indicates an empty field\n## position is an index in range 0..8, 0..8\n## the dictionary used contains the used values for each position\n\ndef int0(c):\n if c in digits:\n return int(c)\n else:\n return 0\n\n\nclass SudokuProblem(SearchProblem):\n def __init__(self, input):\n ## contains used digits for each entry (i, j)\n self.__used = [[[] for i in range(9)] for j in range(9)]\n\n ## The constructor accepts\n ## a) a list of 81 characters: - or an integer between 1 and 9 or\n ## b) a string representing 81 integers (separators being blank and newline)\n if type(input) is NumArray:\n self.__state = array(input)\n elif type(input) is StringType:\n tmp = [int0(c) for c in split(input)]\n self.__state = array(tmp)\n self.__state.shape = 9, 9\n\n def row(self, i): ## 0 <= i <= 2\n return self.__state[i, :]\n\n def col(self, j): ## 0 <= j <= 2\n return self.__state[:, j]\n\n def box(self, i, j): ## 0 <= i, j <= 2\n return self.__state[i * 3: (i + 1) * 3, j * 3: (j + 1) * 3]\n\n def ok(self):\n for n in range(1, 10):\n for i in range(9): ## check columns and rows\n if list(self.col(i)).count(n) > 1:\n return False\n if list(self.row(i)).count(n) > 1:\n return False\n for i in range(3): ## check boxes\n for j in range(3):\n a = array(self.box(i, j))\n a.ravel()\n if list(a).count(n) > 1:\n return False\n return True\n\n def gotSolution(self):\n for n in range(1, 10):\n for i in range(9): ## check columns and rows\n if list(self.col(i)).count(n) != 1:\n return False\n if list(self.row(i)).count(n) != 1:\n return False\n for i in range(3): ## check boxes\n for j in range(3):\n a = array(self.box(i, j))\n a.ravel()\n if list(a).count(n) != 1:\n return False\n return True\n\n def candidates(self, i, j):\n ## returns all candidate values at position i, j\n ## if that position is empty, else return the empty set.\n ## candidate values = {1, ..10} - row - column - box\n if self.__state[i, j] == 0:\n a = array(self.box(i / 3, j / 3))\n a.ravel()\n return set(range(1, 10)) \\\n - set(self.row(i)) \\\n - set(self.col(j)) \\\n - set(list(a)) \\\n - set(self.__used[i][j])\n else:\n return set()\n\n def next(self):\n ## next returns a step\n ## a step ist a tuple (i, j, value)\n ## the position is the one with the smallest number of candidates\n ## the value is an arbitrary admissible value for that position\n\n m0 = 10\n for i in range(9):\n for j in range(9):\n if self.__state[i, j] != 0: ## consider only empty fields\n continue\n c = self.candidates(i, j)\n if len(c) == 0:\n raise StopIteration ## dead end\n if len(c) < m0:\n c0, i0, j0, m0 = c, i, j, len(c)\n\n if 0 < m0 < 10: ## candidate found\n return i0, j0, c0.pop()\n else:\n raise StopIteration ## no candidate left\n\n def __iter__(self):\n return self\n\n def getState(self):\n return array(self.__state)\n\n def doStep(self, step):\n i, j, val = step\n self.__state[i][j] = val\n if self.__used[i][j]:\n self.__used[i][j].pop()\n\n def undoStep(self, step):\n i, j, val = step\n self.__state[i][j] = 0\n self.__used[i][j].append(val)\n\n def __str__(self):\n s = \"\"\n for i in range(9):\n if i % 3 == 0 and i > 0:\n s += \"\\n\"\n for j in range(9):\n if j % 3 == 0 and j > 0:\n s += \" \"\n c = str(self.__state[i, j])\n if c == '0':\n c = '-'\n s = s + c + ' '\n\n s += \"\\n\"\n return s\n","sub_path":"samples/src/search/sudoku_.py","file_name":"sudoku_.py","file_ext":"py","file_size_in_byte":4482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"184159616","text":"\nfrom flask import Flask\nfrom functools import wraps\nfrom flask import request\nimport json\n\napp = Flask(__name__)\n\nwith open('alm_asset_get_FCH152270M8') as alm_file:\n alm_asset_responses = {'FCH152270M8': json.load(alm_file)}\n\nwith open('alm_asset_put_0605de470ff84200d76bee68b1050e9a') as alm_file:\n alm_put_responses = {'0605de470ff84200d76bee68b1050e9a': json.load(alm_file)}\n\nwith open('cmdb_ci_server_get_FCH152270M8') as cmdb_file:\n cmdb_ci_server_responses = {'FCH152270M8': json.load(cmdb_file)}\n\nwith open('cmdb_ci_server_put_0605de470ff84200d76bee68b1050e9a') as cmdb_file:\n cmdb_ci_server_put_responses = {'0605de470ff84200d76bee68b1050e9a': json.load(cmdb_file)}\n\n\nresponse_type = {'Content-Type': 'application/json;charset=UTF-8'}\n\n\ndef check_auth(username, password):\n \"\"\"This function is called to check if a username /\n password combination is valid.\n \"\"\"\n return username == 'admin' and password == 'secret'\n\n\ndef authenticate():\n \"\"\"Sends a 401 response that enables basic auth\"\"\"\n return json.dumps({\"error\": {\"{detail\": \"Required to provide Auth information\", \"message\": \"User Not Authenticated\"},\n \"status\": \"failure\"}), 401, {'WWW-Authenticate': 'BASIC realm=\"Service-now\"',\n 'Content-Type': 'application/json;charset=UTF-8'}\n\n\ndef requires_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n auth = request.authorization\n if not auth or not check_auth(auth.username, auth.password):\n return authenticate()\n return f(*args, **kwargs)\n return decorated\n\n\n@app.route('/api/now/table/alm_asset')\n@requires_auth\ndef alm_get():\n try:\n if \"sysparm_limit\" in request.args:\n limit = int(request.args['sysparm_limit'])\n assert limit == 1\n data = alm_asset_responses[alm_asset_responses.keys()[0]]\n else:\n serial_number = request.args['sysparm_query'].split('=')[1]\n data = alm_asset_responses[serial_number]\n return json.dumps(data), 200, response_type\n except KeyError:\n return json.dumps({'result': []}), 200, response_type\n\n\n@app.route('/api/now/table/cmdb_ci_server')\n@requires_auth\ndef cmdb_get():\n try:\n serial_number = request.args['sysparm_query'].split('=')[1]\n data = cmdb_ci_server_responses[serial_number]\n return json.dumps(data), 200, response_type\n except KeyError:\n return json.dumps({'result': []}), 200, response_type\n\n\n@app.route('/api/now/table/cmdb_ci_server/<serial_number>', methods=['PUT'])\n@requires_auth\ndef cmdb_put(serial_number):\n try:\n data = cmdb_ci_server_put_responses[serial_number]\n return json.dumps(data), 200, response_type\n except KeyError:\n return json.dumps({\"error\": {\"detail\": \"Record doesn't exist or ACL restricts the record retrieval\",\n \"message\": \"No Record found\"}, \"status\": \"failure\"}), 404, response_type\n\n\n@app.route('/api/now/table/alm_asset/<serial_number>', methods=['PUT'])\n@requires_auth\ndef alm_put(serial_number):\n try:\n data = alm_put_responses[serial_number]\n return json.dumps(data), 200, response_type\n except KeyError:\n return json.dumps({\"error\": {\"detail\": \"Record doesn't exist or ACL restricts the record retrieval\",\n \"message\": \"No Record found\"}, \"status\": \"failure\"}), 404, response_type\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=443, ssl_context='adhoc')\n","sub_path":"ci/mock-servers/sn-mock/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"205595487","text":"# coding:utf-8\n\nimport sys\n\ndef solver(nums):\n nums.sort()\n start = 1 \n for n in nums:\n if n >= 1:\n if n - start != 0:\n return start\n \n start += 1 \n \n return start\n\ndef inputs():\n n = int(sys.stdin.readline().strip())\n nums = list(map(int, sys.stdin.readline().strip().split()))\n \n ret = solver(nums)\n \n print(ret)\n \ndef test():\n nums = [3,4,-1,1]\n\n ret = solver(nums)\n print(ret)\n\nif __name__ == '__main__':\n test()","sub_path":"LeetCode/otherQuestion/瓜子二手车/Q1.py","file_name":"Q1.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"884859","text":"import argparse\n\nimport numpy as np\nimport os\nimport torch\nimport torch.nn as nn\nfrom PIL import Image\nfrom os.path import basename\nfrom os.path import splitext\nfrom torch.autograd import Variable\nfrom torchvision import transforms\nfrom torchvision.utils import save_image\n\nimport net\nfrom function import adaptive_instance_normalization\nimport time\n\n\ndef test_transform():\n return transforms.Compose(\n [transforms.Scale((512, 512)), transforms.ToTensor()])\n\n\ndef style_transfer(vgg, decoder, content, style, alpha=1.0):\n assert (0.0 <= alpha <= 1.0)\n content_f = vgg(content)\n style_f = vgg(style)\n feat = adaptive_instance_normalization(content_f, style_f)\n feat = feat * alpha + content_f * (1 - alpha)\n return decoder(feat)\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--content_dir', type=str, required=True,\n help='Directory path to a batch of content images')\nparser.add_argument('--style_dir', type=str, required=True,\n help='Directory path to a batch of style images')\nparser.add_argument('--vgg', type=str, default='models/vgg_normalised.pth')\nparser.add_argument('--decoder', type=str, required=True)\nparser.add_argument('--batch_size', type=int, default=32)\nparser.add_argument('--image_per_content', type=int, default=10)\nparser.add_argument('--save_ext', default='.jpg',\n help='The extension name of the output image')\nparser.add_argument('--output', type=str, default='output',\n help='Directory to save the output image(s)')\nparser.add_argument('--alpha', type=float, default=1.0,\n help='The weight that controls the degree of \\\n stylization. Should be between 0 and 1')\nargs = parser.parse_args()\n\ncontent_paths = [os.path.join(args.content_dir, f) for f in\n os.listdir(args.content_dir)]\nstyle_paths = [os.path.join(args.style_dir, f) for f in\n os.listdir(args.style_dir)]\n\nif not os.path.exists(args.output):\n os.mkdir(args.output)\n\ndecoder = net.decoder\nvgg = net.vgg\n\ndecoder.eval()\nvgg.eval()\n\ndecoder.load_state_dict(torch.load(args.decoder))\nvgg.load_state_dict(torch.load(args.vgg))\nvgg = nn.Sequential(*list(vgg.children())[:31])\n\nvgg.cuda()\ndecoder.cuda()\n\ncontent_tf = test_transform()\nstyle_tf = test_transform()\n\nN_style = len(style_paths)\n\ntotal_time = 0\nfor cnt, content_path in enumerate(content_paths):\n # one content image, N style image\n style_inds_cands = np.random.randint(low=0, high=N_style - 1,\n size=args.image_per_content)\n i = 0\n while True:\n inds = style_inds_cands[i * args.batch_size:(i + 1) * args.batch_size]\n style = torch.stack(\n [style_tf(Image.open(style_paths[ind]).convert('RGB')) for ind in\n inds])\n content = content_tf(Image.open(content_path)) \\\n .unsqueeze(0).expand_as(style)\n output = style_transfer(vgg, decoder,\n Variable(content.cuda(), volatile=True),\n Variable(style.cuda(), volatile=True),\n args.alpha).data\n output = output.cpu()\n for j, ind in enumerate(inds):\n output_name = '{:s}/{:s}_{:s}{:s}'.format(\n args.output,\n splitext(basename(content_path))[0],\n splitext(basename(style_paths[ind]))[0], args.save_ext)\n save_image(output[j], output_name)\n i += 1\n if i * args.batch_size > len(style_inds_cands):\n break\n if cnt > 0 and cnt % 10 == 0:\n print(cnt, time.time() - total_time)\n total_time = time.time()\n","sub_path":"generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":3705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"208288260","text":"import argparse\nimport sys\nimport re\n\n\ndef comparison(params, st2):\n st1 = params.pattern\n if params.ignore_case:\n st1 = st1.lower()\n st2 = st2.lower()\n st1 = st1.replace('*','\\w*')\n st1 = st1.replace('?','.')\n if st1 in st2:\n res = True\n else:\n if st1.replace('\\w*','')==\"\":\n res = True\n else:\n if st1.replace('.','')==\"\":\n if len(st1) <= len(st2):\n res = True\n else:\n res = False\n else:\n if re.search(st1,st2) is None:\n res = False\n else:\n res = True\n if params.invert:\n if res:\n return False\n else:\n return True\n else:\n return res\n\n\ndef output_test(line,params,lines):\n if params.line_number is True:\n nomer = lines.index(line) + 1\n nomer = str(nomer)\n if comparison(params,line):\n result = nomer + ':' + line\n else:\n result = nomer + '-' + line\n output(result)\n else:\n output(line)\n\n\ndef output(line):\n print(line)\n\n\ndef grep(lines,params):\n kol = 0\n next_print = 0\n buffer = []\n buffer_count = max(params.context,params.before_context)\n\n for line in lines:\n if params.count:\n line = line.rstrip()\n if comparison(params,line):\n kol += 1\n else:\n line = line.rstrip()\n if comparison(params,line):\n if params.after_context or params.context:\n next_print = max(params.after_context,params.context)\n if params.before_context or params.context:\n buffer.reverse()\n for out in buffer:\n if out != 0:\n output_test(out,params,lines)\n buffer.clear()\n output_test(line,params,lines)\n\n else:\n if next_print != 0:\n output_test(line,params,lines)\n next_print -= 1\n line = 0\n if buffer_count != 0:\n if len(buffer) >= buffer_count:\n buffer.insert(0,line)\n buffer.pop()\n else:\n buffer.insert(0,line)\n if params.count:\n kol = str(kol)\n output_test(kol,params,lines)\n\ndef parse_args(args):\n parser = argparse.ArgumentParser(description='This is a simple grep on python')\n parser.add_argument(\n '-v',\n action=\"store_true\",\n dest=\"invert\",\n default=False,\n help='Selected lines are those not matching pattern.')\n parser.add_argument(\n '-i',\n action=\"store_true\",\n dest=\"ignore_case\",\n default=False,\n help='Perform case insensitive matching.')\n parser.add_argument(\n '-c',\n action=\"store_true\",\n dest=\"count\",\n default=False,\n help='Only a count of selected lines is written to standard output.')\n parser.add_argument(\n '-n',\n action=\"store_true\",\n dest=\"line_number\",\n default=False,\n help='Each output line is preceded by its relative line number in the file, starting at line 1.')\n parser.add_argument(\n '-C',\n action=\"store\",\n dest=\"context\",\n type=int,\n default=0,\n help='Print num lines of leading and trailing context surrounding each match.')\n parser.add_argument(\n '-B',\n action=\"store\",\n dest=\"before_context\",\n type=int,\n default=0,\n help='Print num lines of trailing context after each match')\n parser.add_argument(\n '-A',\n action=\"store\",\n dest=\"after_context\",\n type=int,\n default=0,\n help='Print num lines of leading context before each match.')\n parser.add_argument('pattern',action=\"store\",help='Search pattern. Can contain magic symbols: ?*')\n return parser.parse_args(args)\n\n\ndef main():\n params = parse_args(sys.argv[1:])\n grep(sys.stdin.readlines(),params)\n\n\nif __name__=='__main__':\n main()\n\n","sub_path":"grep.py","file_name":"grep.py","file_ext":"py","file_size_in_byte":4225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"110556481","text":"import numpy as np\nimport pandas as pd\nimport datetime\nimport heapq\nfrom math import pi\nfrom operator import itemgetter\n\nfrom bokeh.layouts import column, row\nfrom bokeh.plotting import figure\nfrom bokeh.models import ColumnDataSource, HoverTool, Select, Panel, Slider\n\nfrom scripts.plot_style import style\n\n\ndef misc_stats_tab(convoStats, convoSelection):\n conversationTitles = sorted([x.title for x in convoStats])\n\n def make_sentiment_dataset(convoTitle):\n convo = next((x for x in convoStats if x.title == convoTitle))\n\n xdataSentiment = sorted([pd.to_datetime(x)\n for x in convo.dailySentiments.keys()])\n ydataSentiment = [convo.dailySentiments[x]\n for x in convo.dailySentiments.keys()]\n\n return ColumnDataSource(data={'date': xdataSentiment, 'sentiment': ydataSentiment})\n\n def make_common_words_dataset(convoTitle, minLen=0):\n convo = next((x for x in convoStats if x.title == convoTitle))\n\n top_words = heapq.nlargest(20, filter(\n lambda x: len(x[0]) >= minLen, convo.wordFrequencies.items()), key=itemgetter(1))\n\n xdata_top_words, ydata_top_words = zip(*reversed(top_words))\n return ColumnDataSource(data={'word': xdata_top_words, 'count': ydata_top_words})\n\n def make_sentiment_plot(src):\n p = figure(plot_width=550, plot_height=550, title='Daily VADER sentiment', y_range=(-1, 1),\n x_axis_type='datetime', x_axis_label='Date', y_axis_label='Sentiment value')\n\n p.line(x='date', y='sentiment', source=src,\n line_width=2, color='green')\n hover = HoverTool(tooltips=[('Sentiment value', '@sentiment'),\n ('Date', '@date{%F}')],\n formatters={'@date': 'datetime'},\n mode='vline') # vline means that tooltip will be shown when mouse is in a vertical line above glyph\n p.add_tools(hover)\n\n return p\n\n def make_common_words_plot(src, minLen=0):\n p = figure(plot_width=550, plot_height=550, title=f'Most common words with len >= {minLen}',\n toolbar_location=None, y_range=src.data['word'], x_axis_label='Number of occurrences', y_axis_label='Words')\n\n p.hbar(y='word', right='count', height=0.9, source=src,\n fill_alpha=0.7, hover_fill_color='green', hover_fill_alpha=1.0)\n\n # p.xaxis.major_label_orientation = rotation\n p.grid.grid_line_alpha = 0\n p.outline_line_alpha = 0\n\n hover = HoverTool(\n tooltips=[('Word', '@word'), ('No. of occurrences', '@count')])\n p.add_tools(hover)\n\n return p\n\n def on_conversation_changed(attr, oldValue, newValue):\n newSentimentSrc = make_sentiment_dataset(newValue)\n sentimentSrc.data.update(newSentimentSrc.data)\n\n newCommonWordsSrc = make_common_words_dataset(\n newValue, wordLengthSlider.value)\n plotRow.children = [sentimentPlot, make_common_words_plot(\n newCommonWordsSrc, wordLengthSlider.value)]\n\n def on_word_length_changed(attr, oldValue, newValue):\n newCommonWordsSrc = make_common_words_dataset(\n convoSelection.value, newValue)\n plotRow.children = [sentimentPlot, make_common_words_plot(\n newCommonWordsSrc, newValue)]\n\n convoSelection.on_change('value', on_conversation_changed)\n\n initialWordLength = 5\n wordLengthSlider = Slider(title='Min word length for common words',\n start=0, end=10, value=initialWordLength, step=1)\n wordLengthSlider.on_change('value_throttled', on_word_length_changed)\n\n sentimentSrc = make_sentiment_dataset(conversationTitles[0])\n sentimentPlot = make_sentiment_plot(sentimentSrc)\n\n commonWordsSrc = make_common_words_dataset(\n conversationTitles[0], initialWordLength)\n commonWordsPlot = make_common_words_plot(commonWordsSrc, initialWordLength)\n\n plotRow = row(sentimentPlot, commonWordsPlot)\n layout = column(row(convoSelection, wordLengthSlider), plotRow)\n tab = Panel(child=layout, title='Misc statistics')\n\n return tab\n","sub_path":"fbmessages/scripts/misc_stats.py","file_name":"misc_stats.py","file_ext":"py","file_size_in_byte":4156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"285887010","text":"\"\"\"\nRFG Search API helper utility\n\"\"\"\nimport csv\nimport os.path\nimport os\nimport datetime\nimport requests\nimport json\n\nUTF_8 = 'utf-8'\n\ndef to_unicode(value):\n \"\"\"Create str character to unicode for python 2.7\"\"\"\n if value and type(value) == 'str':\n return u''.join(value).encode(UTF_8)\n else:\n return value\n\nclass ParserException(Exception):\n \"\"\"Custom exception for search term parser\"\"\"\n def __init__(self, *args, **kwargs):\n Exception.__init__(self, *args, **kwargs)\n\nclass LoaderException(Exception):\n \"\"\"Custom exception for loading csv file\"\"\"\n def __init__(self, *args, **kwargs):\n Exception.__init__(self, *args, **kwargs)\n\nclass ApiSearchTermFetcher(object):\n \"\"\"\n Class for fetching search result based on term.\n Parameters:\n url: api endpoint\n token: client-code\n search_type: [rossette, concise, and broad]\n num_rows: max number of results to be returned, default to 50\n \"\"\"\n def __init__(self, url, token, search_type, num_rows=50):\n self.url = url\n self.token = token\n self.search_type = search_type\n self.num_rows = num_rows\n\n def fetch(self, search_term):\n \"\"\" Fetch result via search term \"\"\"\n start = datetime.datetime.now()\n response = requests.get(self.url\n , params={\n \"searchSetting\":self.search_type\n , \"search_term\":search_term\n , \"rows\":self.num_rows}\n , headers={\"Accept\" : \"application/json\", \"Client-Code\" : self.token})\n end = datetime.datetime.now()\n date_diff = end - start\n datetime.timedelta(0, 4, 316543)\n return {\"response_time\" : str(date_diff.microseconds/100000.0), \"response\" : response}\n\nclass SearchApiParser(object):\n \"\"\"Parser for search api\"\"\"\n def __init__(self, fetcher):\n self.fetcher = fetcher\n\n def parse(self, search_term):\n \"\"\"Parse search term, raise ParserException if response is not parseable\"\"\"\n if not search_term:\n return SearchApiParser.empty_result(search_term, 'Ignoring searchterm')\n response = self.fetcher.fetch(search_term)\n parsed_response = {}\n if not 'response' in response:\n message = \"Something went wrong while fetching {}. \".format(search_term)\n raise ParserException(message)\n response_json = response['response'].json()\n if response['response'].ok and self.__is_response_parseable(response_json):\n results = response_json['payload']['search_result']\n parsed_result = []\n for result in results:\n parsed_result.append({\n 'score':result['score'],\n 'id': result['id'],\n 'type': result['type'],\n 'primary_names' : [to_unicode(primary_name['full_name'])\n for primary_name in result['primary_name']],\n 'aliases' : [to_unicode(alias['full_name']) for alias in result['other_name']]\n })\n parsed_response['search_term'] = to_unicode(search_term)\n parsed_response['hits'] = len(results)\n parsed_response['response_time'] = response['response_time']\n parsed_response['results'] = parsed_result\n parsed_response['remarks'] = ''\n return parsed_response\n else:\n return SearchApiParser.empty_result(search_term, response['response'].text)\n\n @staticmethod\n def empty_result(search_term, message):\n \"\"\" Create empty parsed results\"\"\"\n return {\"search_term\": to_unicode(search_term),\n \"hits\":\"N/A\",\n \"response_time\":0,\n \"results\":[{'score':0, 'id':'N/A', 'type':'N/A', 'primary_names':[], 'aliases':[]}],\n \"remarks\":message}\n\n def __is_response_parseable(self, results):\n return 'payload' in results or 'search_result' in results['payload']\n\nclass Loader(object):\n \"\"\"\n Fetch searchterms on a csv file.\n Param: csv file\n Param: delimiter, default delimiter is comma (,)\n \"\"\"\n def __init__(self, csv_file, delimiter=','):\n self.csv = csv_file\n self.delimiter = delimiter\n\n def load(self):\n \"\"\"\n Fetch all terms on a csv file as a list data type.\n \"\"\"\n if os.path.exists(self.csv) and os.access(self.csv, os.R_OK):\n search_terms = []\n with open(self.csv) as file_handler:\n reader = csv.DictReader(file_handler, delimiter=self.delimiter)\n for line in reader:\n search_terms.append(unicode(line.values()[0], UTF_8))\n return search_terms\n else:\n message = \"Cannot load csv file {}, see if this file exists.\".format(self.csv)\n raise LoaderException(message)","sub_path":"search-util/search_helper/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":4872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"369481586","text":"import os\nimport cv2\nimport numpy as np\nimport types\n\nclass chunk():\n def __init__(self, video_root, video_filename, value_loader_config):\n self.file = os.path.join(video_root, video_filename)\n\n # Add the value loader\n self.value_loader = None\n if \"delimited_filename\" in value_loader_config:\n self.value_loader = value_loader_delimited_filename(video_filename, value_loader_config[\"delimited_filename\"])\n\n # Calculate the chunk length\n self.reader = cv2.VideoCapture(self.file)\n self.num_frames = int(self.reader.get(cv2.CAP_PROP_FRAME_COUNT))\n print(\"'%s': %i frames found.\" % (self.file,self.num_frames))\n\n self.width = None\n self.height = None\n if self.reader.isOpened() and self.num_frames > 0:\n self.reader.set(1, 0)\n ret, first_frame = self.reader.read()\n if ret == True:\n self.width = np.shape(first_frame)[1]\n self.height = np.shape(first_frame)[0]\n\n def length(self):\n return self.num_frames\n \n def get_frame(self, index):\n data = {}\n\n # Load the camera frame\n if self.reader.isOpened():\n self.reader.set(1, index)\n ret, frame = self.reader.read()\n if ret == True and frame is not None:\n data[\"frame\"] = frame\n\n # Load and merge the associated values\n values = self.value_loader.get_values(index)\n for name, value in values.items():\n data[name] = value\n\n return data\n\nclass value_loader_delimited_filename():\n def __init__(self, filename, value_loader_config):\n # Parse the filename according to the config as the value\n tokens = filename.split(\".\")[0].split( value_loader_config[\"delimiter\"] )\n self.values = {}\n for name, indices in value_loader_config[\"token_load\"].items():\n if type(indices) is not list:\n indices = [indices]\n \n items = []\n for index in indices:\n items.append( tokens[index] )\n \n # Add this named value\n self.values[name] = items\n\n def get_values(self, index):\n # Constant set of values depending on filename\n return self.values","sub_path":"Code/RawDataProcessing/chunk.py","file_name":"chunk.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"601704058","text":"game_over = False\nsize = 3\nboard = [[0 for x in range(size)] for y in range(size)]\ndef print_board():\n\tfor i in range(len(board)):\n\t\tprint(board[i])\n\treturn board\ndef check_win():\n\tglobal game_over\n\tif board[row][0]==board[row][1]==board[row][2]== turn:\n\t\tprint('player {} you win!!!'.format(turn))\n\t\tgame_over = True\n\telif board[0][col]==board[1][col]==board[2][col]== turn:\n\t\tprint('player {} you win!!!'.format(turn))\n\t\tgame_over = True\n\telif board[0][0] == board[1][1] == board[2][2] == turn:\n\t\tprint('player {} you win!!!'.format(turn))\n\t\tgame_over = True\n\telif board[2][0] == board[1][1] == board[0][2] == turn:\n\t\tprint('player {} you win!!!'.format(turn))\n\t\tgame_over = True\n\t\t\t\t\nturn = 0\nprint_board()\nwhile not game_over:\n\ttry:\n\t\tif turn == 0:\n\t\t\trow = int(input('player 1 select your row: ')) - 1\n\t\t\tcol = int(input('player 1 select your collum: ')) - 1\n\t\telse:\n\t\t\trow = int(input('player 2 select your row: ')) -1\n\t\t\tcol = int(input('player 2 select your collum: ')) -1\n\t\tif board[row][col] == 0:\n\t\t\tturn += 1\n\t\t\tboard[row][col] = turn\n\t\t\tcheck_win()\n\t\t\tprint_board()\n\t\t\tturn %= 2\n\t\telse:\n\t\t\tprint(\"you can't chose that spot please try again\")\n\texcept IndexError:\n\t\tprint('please type a interger from 1-3')\n\texcept ValueError:\n\t\tprint('please type a interger from 1-3')\n","sub_path":"Tic.py","file_name":"Tic.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"486057366","text":"import csv\n\ndef initialize_output_file():\n output_file = open('scraped_data.js', 'w')\n output_file.write('function get_scraped_data_array() {')\n output_file.write(\"\\n \\t var data = new Array();\\n\")\n return output_file\n\ndef convert_csv_to_js_array(year, out_file):\n year_string = \"\\t data[\" + str(year) + \"]\"\n out_file.write(year_string + \"= new Array();\\n\")\n with open('ScrapedSongs/' + str(year) + '.csv', 'rb') as csv_file:\n lines = csv.reader(csv_file, delimiter=',', quotechar='\"')\n count = 0\n for row in lines:\n row[0] = row[1]\n row[1] = row[2]\n row[2] = row[3] #\"PVi8bJFIac8\" #\"0hiUuL5uTKc\"#\"S-sJp1FfG7Q\" # #\n del row[3]\n row = [\"\\\"\" + row_item + \"\\\"\" for row_item in row]\n inner_data = ', '.join(row)\n out_file.write(year_string + \"[\" + str(count) + \"] = \" + \"[\" + inner_data + \"];\\n\")\n count += 1\n\ndef close_output_file(file):\n file.write('\\t return data;')\n file.write('\\n }')\n file.close()\n\ndef convert_mutliple_csvs(start_year, end_year):\n out_file = initialize_output_file()\n for cur_year in range(start_year, end_year+1):\n convert_csv_to_js_array(cur_year, out_file)\n close_output_file(out_file)\n\nif __name__ == '__main__':\n convert_mutliple_csvs(1995, 1995)","sub_path":"CSVtoJSArray.py","file_name":"CSVtoJSArray.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"153389922","text":"#! /usr/bin/python3\n\nimport formation, hero\n\nformations = formation.available_formation()\nheros = hero.available_hero()\n\ndef make_team(file_name, frm, hero):\n\tassert(frm < len(formations))\n\tassert(len(hero) == 5)\n\tfor h in hero:\n\t\tassert(h < len(heros))\n\twith open(file_name, 'w') as of:\n\t\tm = formation.int_to_formation(formations[frm])\n\t\tof.write(\"load_pos(%d, %d, %d, %d, %d)\\n\" % tuple(m))\n\t\th = list()\n\t\tfor he in hero:\n\t\t\th.append(heros[he])\n\t\tof.write(\"load_hero('%s', '%s', '%s', '%s', '%s')\\n\" % tuple(h))\n\ndef auto_make_team(frm, hero):\n\tfilename = \"team/{0:0{1}x}\".format(frm,2)\n\tfor h in hero:\n\t\tfilename += \"{0:0{1}x}\".format(h,2)\n\tfilename += \".lua\"\n\tmake_team(filename, frm, hero)\n","sub_path":"team.py","file_name":"team.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"612913654","text":"from openpyxl import load_workbook\nfrom openpyxl.cell import get_column_letter\nfrom datetime import date\n\nwb1 = load_workbook(\"RP-HRBI-MGRPT-WAAG_Non-Confidential.xlsx\")\nws = wb1.get_sheet_by_name('WAAG All employee Non-Confident')\nnew_sheet = wb1.create_sheet(1, \"Employee List\")\n\n# need to keep the data from line 9\nstart_from = 9\ni = 0\nuseful_fields = (1, 2, 3, 4, 5, 7, 8, 10, 11, 15, 25, 26, 29, 37, 39, 42, 56, 57, 58, 59, 66)\nfor row in ws.iter_rows():\n i += 1\n if i >= start_from:\n new_col = 0\n for index in useful_fields:\n new_col += 1\n coordinate = '%s%s' % (get_column_letter(new_col), i-start_from+1)\n new_sheet[coordinate] = ws.cell(row=i, column=index).value\n\nwb1.remove_sheet(ws)\ntoday = date.today()\nfilename = \"Exmployee List \" + today.strftime(\"%b %Y\") + \" - J Guo.xlsx\"\n\nwb1.save(filename)\n","sub_path":"generate_employee_list.py","file_name":"generate_employee_list.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"507414925","text":"import csv\n\n#Detector, Descriptor, Average number of Keypoints per frame, Average number of Matched Keypoints per consecutive frames, \n#Average Detector speed per frame, Average Descriptor speed per frame\n\ninfile = \"../build/out.txt\"\nfirst_line = True\noutfile = \"../writeup.csv\"\nn_frames = 10\n\nwith open(infile, 'r') as f, open(outfile, 'w') as out_f:\n for line in f.readlines():\n line = line.rstrip('\\n')\n if 'detector:' in line and 'descriptor:' in line:\n if first_line:\n header = \"Detector, Descriptor, Average number of Keypoints in ROI per frame, Average number of Matched Keypoints in ROI per consecutive frames, \" \\\n \"Average Detector speed per frame (ms), Average Descriptor speed per frame(ms)\\n\"\n out_f.write(header)\n first_line = False\n else:\n avg_detection_time /= n_frames\n avg_description_time /= n_frames\n avg_num_key_points_roi /= n_frames\n avg_matched_keypoints /= n_frames-1\n out_line = ', '.join([detector, descriptor, str(avg_num_key_points_roi), str(avg_matched_keypoints), str(avg_detection_time), str(avg_description_time)])\n out_f.write(out_line + '\\n')\n words = line.split(' ')\n detector = words[1]\n descriptor = words[3]\n avg_num_keypoints = 0\n avg_detection_time = 0\n avg_description_time = 0\n avg_num_key_points_roi = 0\n avg_matched_keypoints = 0\n\n elif 'detection with n=' in line:\n start = line.find('n=')\n start = start+2\n end = line.find(\" keypoints\")\n end = end\n avg_num_keypoints += int(line[start:end])\n start = line.find(' in ')\n start = start + 4\n end = line.find(' ms')\n avg_detection_time += float(line[start:end])\n elif 'descriptor extraction' in line:\n start = line.find(' in ')\n start +=4\n end = line.find( 'ms')\n avg_description_time += float(line[start:end])\n elif 'ROI' in line:\n start = line.find('ROI: ')\n start = start + 5\n avg_num_key_points_roi += int(line[start: ])\n elif 'matched keypoints:' in line:\n start = line.find('keypoints:')\n start = start + len('keypoints:')\n avg_matched_keypoints += int(line[start: ])","sub_path":"scripts/parse_run_output.py","file_name":"parse_run_output.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"464808385","text":"from django.shortcuts import render_to_response, HttpResponse, render\nfrom django.views.generic import TemplateView\nfrom django.template import RequestContext\nfrom django.conf import settings\nfrom .models import *\nfrom Location.models import municipality\nfrom engineer.models import engineer\nimport json\n\n\nclass housingR(TemplateView):\n template_name = 'register.html'\n\n def get(self, request, *args, **kwargs):\n municipio = municipality.objects.all().order_by('name')\n ingeniero = engineer.objects.all().order_by('name')\n return render_to_response(self.template_name, locals(), context_instance=RequestContext(request))\n\n def post(self, request, *args, **kwargs):\n municipio = municipality.objects.all().order_by('name')\n ingeniero = engineer.objects.all().order_by('name')\n is_post = True\n try:\n\n vivienda = housing(\n id_o=request.POST['ido'],\n name=request.POST['name'],\n parish_id=request.POST['parroquia'],\n housing=request.POST['nviviendas'],\n description=request.POST['descripcion'],\n engineer_id=request.POST['ingeniero']\n )\n vivienda.save()\n calse = 'success'\n message = \"guardado exitoso\"\n except:\n calse = 'danger'\n message = \"fallo al guardar\"\n return render_to_response(self.template_name, locals(), context_instance=RequestContext(request))\n\n\nclass housingL(TemplateView):\n template_name = 'listaViv.html'\n\n def get(self, request, *args, **kwargs):\n viviendas=housing.objects.all().order_by('name')\n return render_to_response(self.template_name, locals(), context_instance=RequestContext(request))\n\n\nclass housingU(TemplateView):\n template_name = 'actualizarH.html'\n \n def get(self, request, slug, *args, **kwargs ):\n ingeniero = engineer.objects.all().order_by('name')\n municipio = municipality.objects.all().order_by('name')\n return render_to_response(self.template_name, locals(), context_instance=RequestContext(request))\n\n\ndef getHousingplus(request):\n parroquia = housing.objects.all()\n dic={}\n inf={}\n lis=[]\n for x in parroquia:\n info = infohousing.objects.filter(housing=x.id)\n ifo=[]\n for i in info:\n inf={\n \"nhousing\":i.Nhousing,\n \"description\":i.description,\n \"engineer\": {\n \"name\": i.engineer.name,\n \"ci\":i.engineer.ci,\n \"civ\":i.engineer.civ,\n },\n }\n ifo.append(inf)\n dic={\n \"slug\":x.slug,\n \"id\":x.id,\n \"id_o\": x.id_o,\n \"name\": x.name,\n \"parish\": x.parish.name,\n \"municipality\": x.parish.municipality.name,\n \"information\" : ifo,\n }\n lis.append(dic)\n \n\n \n result = json.dumps(lis,indent=4, ensure_ascii=False,sort_keys=True)\n return HttpResponse(result, content_type='application/json; charset=utf-8')\n\n\ndef getHousing(request, housing_slug):\n parroquia = housing.objects.filter(slug=housing_slug)\n info = infohousing.objects.filter(housing=parroquia)\n dic={}\n inf={}\n lis=[]\n ifo=[]\n for x in parroquia:\n dic={\n \"id\": x.id,\n \"name\": x.name,\n \"parish\": x.parish.name,\n \"info\" : ifo,\n }\n lis.append(dic)\n for i in info:\n inf={\n \"description\":i.description,\n \"engineer\": {\n \"name\": i.engineer.name,\n \"ci\":i.engineer.ci,\n \"civ\":i.engineer.civ,\n },\n }\n ifo.append(inf)\n\n \n result = json.dumps(lis,indent=4, ensure_ascii=False,sort_keys=True)\n return HttpResponse(result, content_type='application/json; charset=utf-8')\n\n\n","sub_path":"housing/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"210107756","text":"# Create a method that decrypts reversed-order.txt\n\nfile_name_global = \"reversed-order.txt\"\n\n\ndef reversed_order(file_name):\n try:\n read_in = open(file_name_global, 'r')\n text = read_in.readlines()\n print(text)\n string = \"\"\n for i in range(len(text) - 1, - 1, - 1):\n string += text[i]\n print(string)\n except IOError:\n print(\"Unable to write file: single-chars.txt\")\n\n\nreversed_order(file_name_global)\n ","sub_path":"week-03/day-01/reversed_order.py","file_name":"reversed_order.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"605841187","text":"import sys\nsys.path.append('../newspaper')\n\nfrom newspaper import Article\nimport requests\nfrom bs4 import BeautifulSoup as bs\nimport re\nfrom tagfy import tagfy\nfrom crawler import crawler\nfrom newslog import crawlerlog\n\nclass crawlerUol(crawler):\n\n\tdef __init__(self):\n\t\tcrawler.__init__(self)\n\n\n\tdef proccess(self):\n\t\tfor url in self.urls:\n\t\t\tprint(\"Endereço principal -> \", url[0])\n\t\t\tprint(\"\")\n\n\t\t\tcrLog = crawlerlog()\n\t\t\tcrLog.openFile(\"log/uol/\"+url[1]+\"log.txt\")\n\n\t\t\tp = requests.get(url[0])\n\t\t\ts = bs(p.content, 'html.parser')\n\n\t\t\tnewslist = s.find_all('li')\n\n\t\t\tfor singlenews in newslist:\n\t\t\t\tlink = singlenews.find_all('a', {'class':re.compile(r\"click:m_economia_noticias\" )})\n\t\t\t\tif len(link) > 0:\n\t\t\t\t\tnewsurl = link[0]['href']\n\t\t\t\t\tarticle = Article(newsurl)\n\t\t\t\t\tarticle.download()\n\t\t\t\t\tarticle.parse()\n\t\t\t\t\tprint(\"Data de publicacao: \", article.publish_date)\n\t\t\t\t\tprint(\"Titulo: \", article.title)\n\t\t\t\t\tprint(\"Link: \", newsurl)\n\t\t\t\t\tprint(\"\")\n\t\t\t\t\t\n\t\t\t\t\tif not crLog.oldNews(article.title):\n\t\t\t\t\t\tself.save([article.publish_date, \n\t\t\t\t\t\t\t\t\t\t\tnewsurl,\n\t\t\t\t\t\t\t\t\t\t\turl[0],\n\t\t\t\t\t\t\t\t\t\t\turl[1],\n\t\t\t\t\t\t\t\t\t\t\tarticle.title,\n\t\t\t\t\t\t\t\t\t\t\tarticle.text,\n\t\t\t\t\t\t\t\t\t\t\tarticle.authors,\n\t\t\t\t\t\t\t\t\t\t\ttagfy(article.title),\n\t\t\t\t\t\t\t\t\t\t\t\"uol\"\n\t\t\t\t\t\t\t\t\t\t\t])\n\t\t\tcrLog.closeFile()\n\n\n\n\tdef run(self):\n\n\t\turls = [['https://economia.uol.com.br/noticias/afp/', 'afp'],\n\t\t\t\t['https://economia.uol.com.br/noticias/ansa/', 'ansa'],\n\t\t\t\t['https://economia.uol.com.br/noticias/bbc/', 'bbc'],\n\t\t\t\t['https://economia.uol.com.br/noticias/bloomberg/', 'bloomberg'],\n\t\t\t\t['https://economia.uol.com.br/noticias/estadao-conteudo/', 'estadao'],\n\t\t\t\t['https://economia.uol.com.br/noticias/EFE/', 'efe'],\n\t\t\t\t['https://economia.uol.com.br/noticias/reuters/', 'reuters'],\n\t\t\t\t['https://economia.uol.com.br/noticias/valor-online/', 'valor']\n\t\t\t\t]\n\n\t\tself.setUrl(urls)\n\n\t\tprint('---------------------------------------------')\n\t\tprint(\"uol.com.br\")\n\t\tprint('---------------------------------------------')\n\n\t\tself.proccess()\n\t\tself.commit()\n\t\t\n\t\tprint('---------------------------------------------')\n\n\n\t\n\n\n\t\n\n","sub_path":"crawlers/uol.py","file_name":"uol.py","file_ext":"py","file_size_in_byte":2075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"577857352","text":"# Mortgage Calculator - Calculate the monthly payments\n# of a fixed term mortgage over given Nth terms\n# at a given interest rate. Also figure out how long\n# it will take the user to pay back the loan.\n#\n# M = P [ r( 1 + r )^n / (( 1 + r )^n) - 1)]\n# M = Monthly payment\n# P = principal\n# r = interest rate\n# n = loan term\n# Psuedo code for mortgage calculator:\n#\n# Enter the principal balance\n# Enter the interest rate\n# 10, 15, or 30 year mortgage\n# Error check both entries to ensure no characters are entered\n# Also ensure positive number\n#\n# Use formula to calculate\n# Reprompt user for another calculation\n# Error check the reprompt\n# Use the rerun function\n\nimport math\n\n\ndef calculate_mortgage():\n\n # Had to convert this back into a float because it was never converted in the check function.\n # Same will be done for other variables\n principal = calculate_principal()\n\n rate = calculate_rate()\n\n term = calculate_term()\n\n print(principal, rate, term)\n\n monthly = principal * ((rate * math.pow(1+rate, term)) / (math.pow(1+rate, term) - 1))\n\n print(\"\\nYou're monthly payment is $%.2f\" % monthly)\n\n rerun()\n\n\ndef calculate_principal():\n principal = input(\"\\nEnter the principal balance: \")\n try:\n float(principal)\n # Returning a float here because its easier than reassigning the variable in the main clause\n return float(principal)\n\n except ValueError:\n print(\"\\nNot an integer\")\n calculate_principal()\n\n\ndef calculate_rate():\n rate = input(\"\\nEnter the interest rate: \")\n try:\n rate = float(rate)\n return float(rate/100/12)\n\n except ValueError:\n print(\"\\nNot an integer.\")\n calculate_rate()\n\n\ndef calculate_term():\n term = input(\"\\nEnter the length of the term in years: \")\n try:\n term = float(term)\n return float(term*12)\n\n except ValueError:\n print(\"\\nNot an integer.\")\n calculate_term()\n\n\ndef rerun():\n\n rerun_answer = input(\"\\nDo you want to run this again? (y or n)\")\n\n rerun_answer = rerun_answer.upper().replace(\" \", \"\")\n\n if rerun_answer == 'Y':\n\n calculate_mortgage()\n\n elif rerun_answer == 'N':\n\n exit()\n\n elif rerun_answer != 'Y' or 'N':\n\n print(\"\\nYou did not enter a valid answer choice.\")\n\n rerun()\n\n\ncalculate_mortgage()\n","sub_path":"Mortgage Calculator Scratch.py","file_name":"Mortgage Calculator Scratch.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"98471788","text":"\"\"\" CS4277/CS5477 Lab 1: Fun with Homographies.\nSee accompanying Jupyter notebook (lab1.ipynb) for instructions.\n\nName: <Your Name here>\nEmail: <username>@u.nus.edu\nStudent ID: A0123456X\n\nName2: <Name of second member, if any>\nEmail2: <username>@u.nus.edu\nStudent ID: A0123456X\n\"\"\"\n\nimport cv2\nimport numpy as np\nimport math\nfrom math import floor, ceil\nimport random\n\n\nnp.set_printoptions(precision=6)\n_COLOR_RED = (255, 0, 0)\n_COLOR_GREEN = (0, 255, 0)\n_COLOR_BLUE = (0, 0, 255)\n\n\n\"\"\"Helper functions: You should not have to touch the following functions.\n\"\"\"\ndef load_image(im_path):\n \"\"\"Loads image and converts to RGB format\n\n Args:\n im_path (str): Path to image\n\n Returns:\n im (np.ndarray): Loaded image (H, W, 3), of type np.uint8.\n \"\"\"\n im = cv2.imread(im_path)\n im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)\n return im\n\n\ndef draw_matches(im1, im2, im1_pts, im2_pts, inlier_mask=None):\n \"\"\"Generates a image line correspondences\n\n Args:\n im1 (np.ndarray): Image 1\n im2 (np.ndarray): Image 2\n im1_pts (np.ndarray): Nx2 array containing points in image 1\n im2_pts (np.ndarray): Nx2 array containing corresponding points in\n image 2\n inlier_mask (np.ndarray): If provided, inlier correspondences marked\n with True will be drawn in green, others will be in red.\n\n Returns:\n\n \"\"\"\n height1, width1 = im1.shape[:2]\n height2, width2 = im2.shape[:2]\n canvas_height = max(height1, height2)\n canvas_width = width1 + width2\n\n canvas = np.zeros((canvas_height, canvas_width, 3), im1.dtype)\n canvas[:height1, :width1, :] = im1\n canvas[:height2, width1:width1+width2, :] = im2\n\n im2_pts_adj = im2_pts.copy()\n im2_pts_adj[:, 0] += width1\n\n if inlier_mask is None:\n inlier_mask = np.ones(im1_pts.shape[0], dtype=np.bool)\n\n # Converts all to integer for plotting\n im1_pts = im1_pts.astype(np.int32)\n im2_pts_adj = im2_pts_adj.astype(np.int32)\n\n # Draw points\n all_pts = np.concatenate([im1_pts, im2_pts_adj], axis=0)\n for pt in all_pts:\n cv2.circle(canvas, (pt[0], pt[1]), 4, _COLOR_BLUE, 2)\n\n # Draw lines\n for i in range(im1_pts.shape[0]):\n pt1 = tuple(im1_pts[i, :])\n pt2 = tuple(im2_pts_adj[i, :])\n color = _COLOR_GREEN if inlier_mask[i] else _COLOR_RED\n cv2.line(canvas, pt1, pt2, color, 2)\n\n return canvas\n\n\ndef matches2pairs(matches, kp1, kp2):\n \"\"\"Converts OpenCV's DMatch to point pairs\n\n Args:\n matches (list): List of DMatches from OpenCV's matcher\n kp1 (list): List of cv2.KeyPoint from OpenCV's detector for image 1 (query)\n kp2 (list): List of cv2.KeyPoint from OpenCV's detector for image 2 (train)\n\n Returns:\n pts1, pts2: Nx2 array containing corresponding coordinates for both images\n \"\"\"\n\n pts1, pts2 = [], []\n for m in matches:\n pts1.append(kp1[m.queryIdx].pt)\n pts2.append(kp2[m.trainIdx].pt)\n\n pts1 = np.stack(pts1, axis=0)\n pts2 = np.stack(pts2, axis=0)\n\n return pts1, pts2\n\n\n\"\"\"Functions to be implemented\n\"\"\"\n\n\n# Part 1(a)\ndef to_coordinates(homo_coordinates):\n coordinates = np.zeros((homo_coordinates.shape[0], 2))\n for i in range(homo_coordinates.shape[0]):\n coordinates[i, 0] = homo_coordinates[i, 0] / homo_coordinates[i, 2]\n coordinates[i, 1] = homo_coordinates[i, 1] / homo_coordinates[i, 2]\n return coordinates\n\n\ndef to_homogenous(input_pts):\n to_add = np.ones(len(input_pts)).reshape((1, len(input_pts)))\n homogenous_pts = np.concatenate((input_pts, to_add.T), axis=1)\n return homogenous_pts\n\n\ndef transform_homography(src, h_matrix):\n \"\"\"Performs the perspective transformation of coordinates\n\n Args:\n src (np.ndarray): Coordinates of points to transform (N,2)\n h_matrix (np.ndarray): Homography matrix (3,3)\n\n Returns:\n transformed (np.ndarray): Transformed coordinates (N,2)\n\n Prohibited functions:\n cv2.perspectiveTransform()\n\n \"\"\"\n src = to_homogenous(src)\n transformed = h_matrix.dot(src.T).T\n transformed = to_coordinates(transformed)\n return transformed\n\n\ndef calc_centroid(points):\n x=0\n y=0\n for point in points:\n x += point[0]\n y += point[1]\n return (x/len(points), y/len(points))\n\n\ndef calculateDistance(x, y):\n dist = math.sqrt((x[1] - y[1])**2 + (x[0] - y[0])**2)\n return dist\n\n\ndef calc_S(points):\n centroid = calc_centroid(points)\n total_distance = 0\n for point in points:\n total_distance += calculateDistance(centroid, point)\n mean_distance = total_distance/len(points)\n return math.sqrt(2)/mean_distance\n\n\ndef calc_T(points):\n s = calc_S(points)\n c_x, c_y = calc_centroid(points)\n T = np.array([[s, 0, -s*c_x], [0, s, -s*c_y], [0, 0, 1]])\n return T\n\n\ndef calc_sub_a(src_points, dst_points):\n sub_a = np.zeros((2, 9))\n sub_a[0, 3:6] = -dst_points[2]*src_points\n sub_a[0, 6:9] = dst_points[1]*src_points\n sub_a[1, 0:3] = dst_points[2]*src_points\n sub_a[1, 6:9] = -dst_points[0]*src_points\n return sub_a\n\n\ndef compute_homography(src1, dst1):\n \"\"\"Calculates the perspective transform from at least 4 points of\n corresponding points using the **Normalized** Direct Linear Transformation\n method.\n\n Args:\n src (np.ndarray): Coordinates of points in the first image (N,2)\n dst (np.ndarray): Corresponding coordinates of points in the second\n image (N,2)\n\n Returns:\n h_matrix (np.ndarray): The required 3x3 transformation matrix H.\n\n Prohibited functions:\n cv2.findHomography(), cv2.getPerspectiveTransform(),\n np.linalg.solve(), np.linalg.lstsq()\n \"\"\"\n\n Trans = calc_T(src1)\n Trans_prime = calc_T(dst1)\n\n scr1_transformed = transform_homography(src1, Trans)\n dst1_transformed = transform_homography(dst1, Trans_prime)\n\n scr1_transformed = to_homogenous(scr1_transformed)\n dst1_transformed = to_homogenous(dst1_transformed)\n\n a = np.zeros((len(src1) * 2, 9))\n for i in range(len(src1)):\n a[i * 2:i * 2 + 2] = calc_sub_a(scr1_transformed[i], dst1_transformed[i])\n\n u, s, vh = np.linalg.svd(a)\n h_dlt = vh[-1]\n h_dlt = h_dlt.reshape((3, 3))\n h_dlt = np.linalg.inv(Trans_prime).dot(h_dlt).dot(Trans)\n h_dlt = h_dlt / h_dlt[-1, -1]\n\n return h_dlt\n\n\n# Part 2\n\ndef warp_image(template, original, homo):\n \"\"\"Applies perspective transformation to source image to warp it onto the\n destination (background) image\n\n Args:\n src (np.ndarray): Source image to be warped\n dst (np.ndarray): Background image to warp template onto\n h_matrix (np.ndarray): Warps coordinates from src to the dst, i.e.\n x_{dst} = h_matrix * x_{src},\n where x_{src}, x_{dst} are the homogeneous\n coordinates in I_{src} and I_{dst} respectively\n\n Returns:\n dst (np.ndarray): Source image warped onto destination image\n\n Prohibited functions:\n cv2.warpPerspective()\n \"\"\"\n original = original.copy() # deep copy to avoid overwriting the original image\n\n output_coordinates = np.zeros((2, original.shape[0] * original.shape[1]))\n for i in range(original.shape[0] * original.shape[1]):\n output_coordinates[0, i] = i // original.shape[0]\n output_coordinates[1, i] = i % original.shape[0]\n output_homo = to_homogenous(output_coordinates.T).T\n homo_inv = np.linalg.inv(homo)\n corresponding_coordinates = to_coordinates(homo_inv.dot(output_homo).T).T\n modified = np.array(original)\n for i in range(original.shape[0] * original.shape[1]):\n template_row = int(corresponding_coordinates[1, i])\n template_col = int(corresponding_coordinates[0, i])\n if template_row >= template.shape[0] or template_row < 0 or template_col >= template.shape[1] or template_col < 0:\n continue\n modified_row = int(output_coordinates[1, i])\n modified_col = int(output_coordinates[0, i])\n modified[modified_row, modified_col] = template[template_row, template_col]\n return modified\n\n\ndef warp_images_all(images, h_matrices):\n \"\"\"Warps all images onto a black canvas.\n\n Note: We implemented this function for you, but it'll be useful to note\n the necessary steps\n 1. Compute the bounds of each of the images (which can be negative)\n 2. Computes the necessary size of the canvas\n 3. Adjust all the homography matrices to the canvas bounds\n 4. Warp images\n\n Requires:\n transform_homography(), warp_image()\n\n Args:\n images (List[np.ndarray]): List of images to warp\n h_matrices (List[np.ndarray]): List of homography matrices\n\n Returns:\n stitched (np.ndarray): Stitched images\n \"\"\"\n assert len(images) == len(h_matrices) and len(images) > 0\n num_images = len(images)\n\n corners_transformed = []\n for i in range(num_images):\n h, w = images[i].shape[:2]\n bounds = np.array([[0.0, 0.0], [w, 0.0], [w, h], [0.0, h]])\n transformed_bounds = transform_homography(bounds, h_matrices[i])\n corners_transformed.append(transformed_bounds)\n corners_transformed = np.concatenate(corners_transformed, axis=0)\n\n # Compute required canvas size\n min_x, min_y = np.min(corners_transformed, axis=0)\n max_x, max_y = np.max(corners_transformed, axis=0)\n\n min_x, min_y = floor(min_x), floor(min_y)\n\n max_x, max_y = ceil(max_x), ceil(max_y)\n\n canvas = np.zeros((max_y-min_y, max_x-min_x, 3), images[0].dtype)\n\n for i in range(num_images):\n # adjust homography matrices\n trans_mat = np.array([[1.0, 0.0, -min_x],\n [0.0, 1.0, -min_y],\n [0.0, 0.0, 1.0]], h_matrices[i].dtype)\n h_adjusted = trans_mat @ h_matrices[i]\n\n # Warp\n canvas = warp_image(images[i], canvas, h_adjusted)\n\n return canvas\n\n\n# Part 3\ndef compute_homography_error(src, dst, homography):\n \"\"\"Compute the squared bidirectional pixel reprojection error for\n provided correspondences\n\n Args:\n src (np.ndarray): Coordinates of points in the first image (N,2)\n dst (np.ndarray): Corresponding coordinates of points in the second\n image (N,2)\n homography (np.ndarray): Homography matrix that transforms src to dst.\n\n Returns:\n err (np.ndarray): Array of size (N, ) containing the error d for each\n correspondence, computed as:\n d(x,x') = ||x - inv(H)x'||^2 + ||x' - Hx||^2,\n where ||a|| denotes the l2 norm (euclidean distance) of vector a.\n \"\"\"\n d = np.zeros(src.shape[0], np.float64)\n\n for i in range(src.shape[0]):\n homography_inv = np.linalg.inv(homography)\n error_1 = pow(calculateDistance(src[i], transform_homography(dst[i].reshape(1, 2), homography_inv).reshape(2)), 2)\n error_2 = pow(calculateDistance(dst[i], transform_homography(src[i].reshape(1, 2), homography).reshape(2)), 2)\n total_error = error_1 + error_2\n d[i] = total_error\n\n\n return d\n\n\ndef compute_homography_ransac(src, dst, thresh=16.0, num_tries=200):\n \"\"\"Calculates the perspective transform from at least 4 points of\n corresponding points in a robust manner using RANSAC. After RANSAC, all the\n inlier correspondences will be used to re-estimate the homography matrix.\n\n Args:\n src (np.ndarray): Coordinates of points in the first image (N,2)\n dst (np.ndarray): Corresponding coordinates of points in the second\n image (N,2)\n thresh (float): Maximum allowed squared bidirectional pixel reprojection\n error to treat a point pair as an inlier (default: 16.0). Pixel\n reprojection error is computed as:\n d(x,x') = ||x - inv(H)x'||^2 + ||x' - Hx||^2,\n where ||a|| denotes the l2 norm (euclidean distance) of vector a.\n num_tries (int): Number of trials for RANSAC\n\n Returns:\n h_matrix (np.ndarray): The required 3x3 transformation matrix H.\n mask (np.ndarraay): Output mask with dtype np.bool where 1 indicates\n inliers\n\n Prohibited functions:\n cv2.findHomography()\n \"\"\"\n\n \"\"\" YOUR CODE STARTS HERE \"\"\"\n best_indexes = []\n best_counter = 0\n for i in range(num_tries):\n counter = 0\n set_of_src = []\n set_of_dst = []\n indexes = random.sample(range(0, len(src)), 4)\n for index in indexes:\n set_of_src.append(src[index])\n set_of_dst.append(dst[index])\n\n h_hypothesis = compute_homography(set_of_src, set_of_dst)\n errors = compute_homography_error(src, dst, h_hypothesis)\n for i, error in enumerate(errors):\n if error < thresh:\n counter += 1\n if counter > best_counter:\n best_indexes = indexes\n best_counter = counter\n set_of_src = []\n set_of_dst = []\n for index in best_indexes:\n set_of_src.append(src[index])\n set_of_dst.append(dst[index])\n h_hypothesis = compute_homography(set_of_src, set_of_dst)\n errors = compute_homography_error(src, dst, h_hypothesis)\n set_of_src = []\n set_of_dst = []\n mask = np.zeros(src.shape[0], dtype=np.bool)\n for i, error in enumerate(errors):\n if error < thresh:\n set_of_src.append(src[i])\n set_of_dst.append(dst[i])\n mask[i] = 1\n h_hypothesis = compute_homography(set_of_src, set_of_dst)\n\n \"\"\" YOUR CODE ENDS HERE \"\"\"\n\n return h_hypothesis, mask\n\n\n# Part 4\ndef concatenate_homographies(pairwise_h_matrices, ref):\n \"\"\"Transforms pairwise relative transformations to absolute transformations.\n\n Args:\n pairwise_h_matrices (list): List of N-1 pairwise homographies, the i'th\n matrix maps points in the i'th image to the (i+1)'th image, e.g..\n x_1 = H[0] * x_0\n ref (int): Reference image to warp all images towards.\n\n Returns:\n abs_h_matrices (list): List of N homographies. abs_H[i] warps points\n in the i'th image to the reference image. abs_H[ref] should be the\n identity transformation.\n \"\"\"\n\n abs_h_matrices = []\n num_images = len(pairwise_h_matrices) + 1\n assert ref < num_images\n\n # abs_h_matrices.append(pairwise_h_matrices[0])\n # abs_h_matrices.append(np.identity(3))\n # abs_h_matrices.append(np.linalg.inv(pairwise_h_matrices[1]))\n # abs_h_matrices.append(np.linalg.inv(pairwise_h_matrices[1]).dot(np.linalg.inv(pairwise_h_matrices[2])))\n for i in range(len(pairwise_h_matrices) + 1):\n to_add = np.identity(3)\n if i == ref - 1:\n abs_h_matrices.append(np.identity(3))\n if i < ref - 1:\n for ii in range(i, ref-1):\n to_add = pairwise_h_matrices[ii].dot(to_add)\n abs_h_matrices.append(to_add)\n if i > ref - 1:\n for ii in range(i, ref - 1, -1):\n to_add = np.linalg.inv(pairwise_h_matrices[ii-1]).dot(to_add)\n abs_h_matrices.append(to_add)\n\n return abs_h_matrices\n","sub_path":"lab1/lab1-old.py","file_name":"lab1-old.py","file_ext":"py","file_size_in_byte":15112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"554692892","text":"#!/usr/bin/python3\n\"\"\"Reviews module\"\"\"\nfrom api.v1.views import app_views\nfrom flask import jsonify, abort, make_response, request\nfrom models import storage\nfrom os import environ\nfrom models.place import Place\nfrom models.amenity import Amenity\n\n\n@app_views.route('/places/<place_id>/amenities', methods=['GET'],\n strict_slashes=False)\ndef all_place_amenities(place_id):\n \"\"\"Returns all amenities from a place object\"\"\"\n places = storage.get(Place, place_id)\n if not places:\n abort(404)\n amenities = []\n if environ.get('HBNB_TYPE_STORAGE') == \"db\":\n for value in places.amenities:\n amenities.append(value.to_dict())\n else:\n for value in places.amenity_ids:\n amenities.append(storage.get(Amenity, value).to_dict())\n return jsonify(amenities)\n\n\n@app_views.route('/places/<place_id>/amenities/<amenity_id>',\n methods=['DELETE'], strict_slashes=False)\ndef delete_place_amenity(place_id, amenity_id):\n \"\"\"Deletes an amenity objects by id\"\"\"\n place = storage.get(Place, place_id)\n if not place:\n abort(404)\n amenity = storage.get(Amenity, amenity_id)\n if not amenity:\n abort(404)\n if environ.get('HBNB_TYPE_STORAGE') == \"db\":\n if amenity not in place.amenities:\n abort(404)\n place.amenities.remove(amenity)\n else:\n if amenity_id not in place.amenity_ids:\n abort(404)\n place.amenity_ids.remove(amenity_id)\n place.save()\n return jsonify({}), 200\n\n\n@app_views.route('/places/<place_id>/amenities/<amenity_id>', methods=['POST'],\n strict_slashes=False)\ndef creates_place_amenity(place_id, amenity_id):\n \"\"\" Creates an amenity object \"\"\"\n place = storage.get(Place, place_id)\n if not place:\n abort(404)\n amenity = storage.get(Amenity, amenity_id)\n if not amenity:\n abort(404)\n if environ.get('HBNB_TYPE_STORAGE') == \"db\":\n if amenity in place.amenities:\n return jsonify(amenity.to_dict()), 200\n else:\n place.amenities.append(amenity)\n else:\n if amenity_id in place.amenity_ids:\n return jsonify(amenity.to_dict()), 200\n else:\n place.amenity_ids.append(amenity)\n place.save()\n return jsonify(amenity.to_dict()), 201\n","sub_path":"api/v1/views/places_amenities.py","file_name":"places_amenities.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"588815651","text":"# -*- coding: utf-8 -*-\nr\"\"\"\nUndirected graphs\n\nThis module implements functions and operations involving undirected\ngraphs.\n\n{INDEX_OF_METHODS}\n\nAUTHORS:\n\n- Robert L. Miller (2006-10-22): initial version\n\n- William Stein (2006-12-05): Editing\n\n- Robert L. Miller (2007-01-13): refactoring, adjusting for\n NetworkX-0.33, fixed plotting bugs (2007-01-23): basic tutorial,\n edge labels, loops, multiple edges and arcs (2007-02-07): graph6\n and sparse6 formats, matrix input\n\n- Emily Kirkmann (2007-02-11): added graph_border option to plot\n and show\n\n- Robert L. Miller (2007-02-12): vertex color-maps, graph\n boundaries, graph6 helper functions in Cython\n\n- Robert L. Miller Sage Days 3 (2007-02-17-21): 3d plotting in\n Tachyon\n\n- Robert L. Miller (2007-02-25): display a partition\n\n- Robert L. Miller (2007-02-28): associate arbitrary objects to\n vertices, edge and arc label display (in 2d), edge coloring\n\n- Robert L. Miller (2007-03-21): Automorphism group, isomorphism\n check, canonical label\n\n- Robert L. Miller (2007-06-07-09): NetworkX function wrapping\n\n- Michael W. Hansen (2007-06-09): Topological sort generation\n\n- Emily Kirkman, Robert L. Miller Sage Days 4: Finished wrapping\n NetworkX\n\n- Emily Kirkman (2007-07-21): Genus (including circular planar,\n all embeddings and all planar embeddings), all paths, interior\n paths\n\n- Bobby Moretti (2007-08-12): fixed up plotting of graphs with\n edge colors differentiated by label\n\n- Jason Grout (2007-09-25): Added functions, bug fixes, and\n general enhancements\n\n- Robert L. Miller (Sage Days 7): Edge labeled graph isomorphism\n\n- Tom Boothby (Sage Days 7): Miscellaneous awesomeness\n\n- Tom Boothby (2008-01-09): Added graphviz output\n\n- David Joyner (2009-2): Fixed docstring bug related to GAP.\n\n- Stephen Hartke (2009-07-26): Fixed bug in blocks_and_cut_vertices()\n that caused an incorrect result when the vertex 0 was a cut vertex.\n\n- Stephen Hartke (2009-08-22): Fixed bug in blocks_and_cut_vertices()\n where the list of cut_vertices is not treated as a set.\n\n- Anders Jonsson (2009-10-10): Counting of spanning trees and out-trees added.\n\n- Nathann Cohen (2009-09) : Cliquer, Connectivity, Flows\n and everything that uses Linear Programming\n and class numerical.MIP\n\n- Nicolas M. Thiery (2010-02): graph layout code refactoring, dot2tex/graphviz interface\n\n- David Coudert (2012-04) : Reduction rules in vertex_cover.\n\n- Birk Eisermann (2012-06): added recognition of weakly chordal graphs and\n long-hole-free / long-antihole-free graphs\n\n- Alexandre P. Zuge (2013-07): added join operation.\n\n- Amritanshu Prasad (2014-08): added clique polynomial\n\nGraph Format\n------------\n\nSupported formats\n~~~~~~~~~~~~~~~~~\n\nSage Graphs can be created from a wide range of inputs. A few\nexamples are covered here.\n\n\n- NetworkX dictionary format:\n\n ::\n\n sage: d = {0: [1,4,5], 1: [2,6], 2: [3,7], 3: [4,8], 4: [9], \\\n 5: [7, 8], 6: [8,9], 7: [9]}\n sage: G = Graph(d); G\n Graph on 10 vertices\n sage: G.plot().show() # or G.show()\n\n- A NetworkX graph:\n\n ::\n\n sage: import networkx\n sage: K = networkx.complete_bipartite_graph(12,7)\n sage: G = Graph(K)\n sage: G.degree()\n [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 12, 12, 12, 12, 12, 12, 12]\n\n- graph6 or sparse6 format:\n\n ::\n\n sage: s = ':I`AKGsaOs`cI]Gb~'\n sage: G = Graph(s, sparse=True); G\n Looped multi-graph on 10 vertices\n sage: G.plot().show() # or G.show()\n\n Note that the ``\\`` character is an escape character in Python, and\n also a character used by graph6 strings:\n\n ::\n\n sage: G = Graph('Ihe\\n@GUA')\n Traceback (most recent call last):\n ...\n RuntimeError: The string (Ihe) seems corrupt: for n = 10, the string is too short.\n\n In Python, the escaped character ``\\`` is represented by ``\\\\``:\n\n ::\n\n sage: G = Graph('Ihe\\\\n@GUA')\n sage: G.plot().show() # or G.show()\n\n- adjacency matrix: In an adjacency matrix, each column and each\n row represent a vertex. If a 1 shows up in row `i`, column\n `j`, there is an edge `(i,j)`.\n\n ::\n\n sage: M = Matrix([(0,1,0,0,1,1,0,0,0,0),(1,0,1,0,0,0,1,0,0,0), \\\n (0,1,0,1,0,0,0,1,0,0), (0,0,1,0,1,0,0,0,1,0),(1,0,0,1,0,0,0,0,0,1), \\\n (1,0,0,0,0,0,0,1,1,0), (0,1,0,0,0,0,0,0,1,1),(0,0,1,0,0,1,0,0,0,1), \\\n (0,0,0,1,0,1,1,0,0,0), (0,0,0,0,1,0,1,1,0,0)])\n sage: M\n [0 1 0 0 1 1 0 0 0 0]\n [1 0 1 0 0 0 1 0 0 0]\n [0 1 0 1 0 0 0 1 0 0]\n [0 0 1 0 1 0 0 0 1 0]\n [1 0 0 1 0 0 0 0 0 1]\n [1 0 0 0 0 0 0 1 1 0]\n [0 1 0 0 0 0 0 0 1 1]\n [0 0 1 0 0 1 0 0 0 1]\n [0 0 0 1 0 1 1 0 0 0]\n [0 0 0 0 1 0 1 1 0 0]\n sage: G = Graph(M); G\n Graph on 10 vertices\n sage: G.plot().show() # or G.show()\n\n- incidence matrix: In an incidence matrix, each row represents a\n vertex and each column represents an edge.\n\n ::\n\n sage: M = Matrix([(-1, 0, 0, 0, 1, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0),\n ....: ( 1,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0),\n ....: ( 0, 1,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 0),\n ....: ( 0, 0, 1,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0),\n ....: ( 0, 0, 0, 1,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1),\n ....: ( 0, 0, 0, 0, 0,-1, 0, 0, 0, 1, 1, 0, 0, 0, 0),\n ....: ( 0, 0, 0, 0, 0, 0, 0, 1,-1, 0, 0, 1, 0, 0, 0),\n ....: ( 0, 0, 0, 0, 0, 1,-1, 0, 0, 0, 0, 0, 1, 0, 0),\n ....: ( 0, 0, 0, 0, 0, 0, 0, 0, 1,-1, 0, 0, 0, 1, 0),\n ....: ( 0, 0, 0, 0, 0, 0, 1,-1, 0, 0, 0, 0, 0, 0, 1)])\n sage: M\n [-1 0 0 0 1 0 0 0 0 0 -1 0 0 0 0]\n [ 1 -1 0 0 0 0 0 0 0 0 0 -1 0 0 0]\n [ 0 1 -1 0 0 0 0 0 0 0 0 0 -1 0 0]\n [ 0 0 1 -1 0 0 0 0 0 0 0 0 0 -1 0]\n [ 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 -1]\n [ 0 0 0 0 0 -1 0 0 0 1 1 0 0 0 0]\n [ 0 0 0 0 0 0 0 1 -1 0 0 1 0 0 0]\n [ 0 0 0 0 0 1 -1 0 0 0 0 0 1 0 0]\n [ 0 0 0 0 0 0 0 0 1 -1 0 0 0 1 0]\n [ 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 1]\n sage: G = Graph(M); G\n Graph on 10 vertices\n sage: G.plot().show() # or G.show()\n sage: DiGraph(matrix(2,[0,0,-1,1]), format=\"incidence_matrix\")\n Traceback (most recent call last):\n ...\n ValueError: There must be two nonzero entries (-1 & 1) per column.\n\n- a list of edges::\n\n sage: g = Graph([(1,3),(3,8),(5,2)])\n sage: g\n Graph on 5 vertices\n\n- an igraph Graph::\n\n sage: import igraph # optional - python_igraph\n sage: g = Graph(igraph.Graph([(1,3),(3,2),(0,2)])) # optional - python_igraph\n sage: g # optional - python_igraph\n Graph on 4 vertices\n\nGenerators\n----------\n\nUse ``graphs(n)`` to iterate through all non-isomorphic graphs of given size::\n\n sage: for g in graphs(4):\n ....: print(g.spectrum())\n [0, 0, 0, 0]\n [1, 0, 0, -1]\n [1.4142135623..., 0, 0, -1.4142135623...]\n [2, 0, -1, -1]\n [1.7320508075..., 0, 0, -1.7320508075...]\n [1, 1, -1, -1]\n [1.6180339887..., 0.6180339887..., -0.6180339887..., -1.6180339887...]\n [2.1700864866..., 0.3111078174..., -1, -1.4811943040...]\n [2, 0, 0, -2]\n [2.5615528128..., 0, -1, -1.5615528128...]\n [3, -1, -1, -1]\n\nSimilarly ``graphs()`` will iterate through all graphs. The complete\ngraph of 4 vertices is of course the smallest graph with chromatic number\nbigger than three::\n\n sage: for g in graphs():\n ....: if g.chromatic_number() > 3:\n ....: break\n sage: g.is_isomorphic(graphs.CompleteGraph(4))\n True\n\nFor some commonly used graphs to play with, type\n\n::\n\n sage: graphs.[tab] # not tested\n\nand hit {tab}. Most of these graphs come with their own custom\nplot, so you can see how people usually visualize these graphs.\n\n::\n\n sage: G = graphs.PetersenGraph()\n sage: G.plot().show() # or G.show()\n sage: G.degree_histogram()\n [0, 0, 0, 10]\n sage: G.adjacency_matrix()\n [0 1 0 0 1 1 0 0 0 0]\n [1 0 1 0 0 0 1 0 0 0]\n [0 1 0 1 0 0 0 1 0 0]\n [0 0 1 0 1 0 0 0 1 0]\n [1 0 0 1 0 0 0 0 0 1]\n [1 0 0 0 0 0 0 1 1 0]\n [0 1 0 0 0 0 0 0 1 1]\n [0 0 1 0 0 1 0 0 0 1]\n [0 0 0 1 0 1 1 0 0 0]\n [0 0 0 0 1 0 1 1 0 0]\n\n::\n\n sage: S = G.subgraph([0,1,2,3])\n sage: S.plot().show() # or S.show()\n sage: S.density()\n 1/2\n\n::\n\n sage: G = GraphQuery(display_cols=['graph6'], num_vertices=7, diameter=5)\n sage: L = G.get_graphs_list()\n sage: graphs_list.show_graphs(L)\n\n.. _Graph:labels:\n\nLabels\n------\n\nEach vertex can have any hashable object as a label. These are\nthings like strings, numbers, and tuples. Each edge is given a\ndefault label of ``None``, but if specified, edges can\nhave any label at all. Edges between vertices `u` and\n`v` are represented typically as ``(u, v, l)``, where\n``l`` is the label for the edge.\n\nNote that vertex labels themselves cannot be mutable items::\n\n sage: M = Matrix( [[0,0],[0,0]] )\n sage: G = Graph({ 0 : { M : None } })\n Traceback (most recent call last):\n ...\n TypeError: mutable matrices are unhashable\n\nHowever, if one wants to define a dictionary, with the same keys\nand arbitrary objects for entries, one can make that association::\n\n sage: d = {0 : graphs.DodecahedralGraph(), 1 : graphs.FlowerSnark(), \\\n 2 : graphs.MoebiusKantorGraph(), 3 : graphs.PetersenGraph() }\n sage: d[2]\n Moebius-Kantor Graph: Graph on 16 vertices\n sage: T = graphs.TetrahedralGraph()\n sage: T.vertices()\n [0, 1, 2, 3]\n sage: T.set_vertices(d)\n sage: T.get_vertex(1)\n Flower Snark: Graph on 20 vertices\n\nDatabase\n--------\n\nThere is a database available for searching for graphs that satisfy\na certain set of parameters, including number of vertices and\nedges, density, maximum and minimum degree, diameter, radius, and\nconnectivity. To see a list of all search parameter keywords broken\ndown by their designated table names, type\n\n::\n\n sage: graph_db_info()\n {...}\n\nFor more details on data types or keyword input, enter\n\n::\n\n sage: GraphQuery? # not tested\n\nThe results of a query can be viewed with the show method, or can be\nviewed individually by iterating through the results:\n\n::\n\n sage: Q = GraphQuery(display_cols=['graph6'],num_vertices=7, diameter=5)\n sage: Q.show()\n Graph6\n --------------------\n F?`po\n F?gqg\n F@?]O\n F@OKg\n F@R@o\n FA_pW\n FEOhW\n FGC{o\n FIAHo\n\nShow each graph as you iterate through the results:\n\n::\n\n sage: for g in Q:\n ....: show(g)\n\nVisualization\n-------------\n\nTo see a graph `G` you are working with, there\nare three main options. You can view the graph in two dimensions via\nmatplotlib with ``show()``. ::\n\n sage: G = graphs.RandomGNP(15,.3)\n sage: G.show()\n\nAnd you can view it in three dimensions via jmol with ``show3d()``. ::\n\n sage: G.show3d()\n\nOr it can be rendered with `\\LaTeX`. This requires the right\nadditions to a standard `\\mbox{\\rm\\TeX}` installation. Then standard\nSage commands, such as ``view(G)`` will display the graph, or\n``latex(G)`` will produce a string suitable for inclusion in a\n`\\LaTeX` document. More details on this are at\nthe :mod:`sage.graphs.graph_latex` module. ::\n\n sage: from sage.graphs.graph_latex import check_tkz_graph\n sage: check_tkz_graph() # random - depends on TeX installation\n sage: latex(G)\n \\begin{tikzpicture}\n ...\n \\end{tikzpicture}\n\nMutability\n----------\n\nGraphs are mutable, and thus unusable as dictionary keys, unless\n``data_structure=\"static_sparse\"`` is used::\n\n sage: G = graphs.PetersenGraph()\n sage: {G:1}[G]\n Traceback (most recent call last):\n ...\n TypeError: This graph is mutable, and thus not hashable. Create an immutable copy by `g.copy(immutable=True)`\n sage: G_immutable = Graph(G, immutable=True)\n sage: G_immutable == G\n True\n sage: {G_immutable:1}[G_immutable]\n 1\n\nMethods\n-------\n\"\"\"\n\n#*****************************************************************************\n# Copyright (C) 2006 - 2007 Robert L. Miller <rlmillster@gmail.com>\n#\n# Distributed under the terms of the GNU General Public License (GPL)\n# http://www.gnu.org/licenses/\n#*****************************************************************************\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nfrom six.moves import range\n\nfrom copy import copy\nfrom sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing\nfrom sage.misc.superseded import deprecation\nfrom sage.rings.integer import Integer\nfrom sage.rings.integer_ring import ZZ\nimport sage.graphs.generic_graph_pyx as generic_graph_pyx\nfrom sage.graphs.generic_graph import GenericGraph\nfrom sage.graphs.digraph import DiGraph\nfrom sage.graphs.independent_sets import IndependentSets\nfrom sage.combinat.combinatorial_map import combinatorial_map\nfrom sage.misc.rest_index_of_methods import doc_index, gen_thematic_rest_table_index\nfrom sage.misc.decorators import rename_keyword\n\nclass Graph(GenericGraph):\n r\"\"\"\n Undirected graph.\n\n A graph is a set of vertices connected by edges. See also the\n :wikipedia:`Wikipedia article on graphs <Graph_(mathematics)>`. For a\n collection of pre-defined graphs, see the\n :mod:`~sage.graphs.graph_generators` module.\n\n A :class:`Graph` object has many methods whose list can be obtained by\n typing ``g.<tab>`` (i.e. hit the 'tab' key) or by reading the documentation\n of :mod:`~sage.graphs.graph`, :mod:`~sage.graphs.generic_graph`, and\n :mod:`~sage.graphs.digraph`.\n\n INPUT:\n\n By default, a :class:`Graph` object is simple (i.e. no *loops* nor *multiple\n edges*) and unweighted. This can be easily tuned with the appropriate flags\n (see below).\n\n - ``data`` -- can be any of the following (see the ``format`` argument):\n\n #. ``Graph()`` -- build a graph on 0 vertices.\n\n #. ``Graph(5)`` -- return an edgeless graph on the 5 vertices 0,...,4.\n\n #. ``Graph([list_of_vertices,list_of_edges])`` -- returns a graph with\n given vertices/edges.\n\n To bypass auto-detection, prefer the more explicit\n ``Graph([V,E],format='vertices_and_edges')``.\n\n #. ``Graph(list_of_edges)`` -- return a graph with a given list of edges\n (see documentation of\n :meth:`~sage.graphs.generic_graph.GenericGraph.add_edges`).\n\n To bypass auto-detection, prefer the more explicit ``Graph(L,\n format='list_of_edges')``.\n\n #. ``Graph({1:[2,3,4],3:[4]})`` -- return a graph by associating to each\n vertex the list of its neighbors.\n\n To bypass auto-detection, prefer the more explicit ``Graph(D,\n format='dict_of_lists')``.\n\n #. ``Graph({1: {2: 'a', 3:'b'} ,3:{2:'c'}})`` -- return a graph by\n associating a list of neighbors to each vertex and providing its edge\n label.\n\n To bypass auto-detection, prefer the more explicit ``Graph(D,\n format='dict_of_dicts')``.\n\n For graphs with multiple edges, you can provide a list of labels\n instead, e.g.: ``Graph({1: {2: ['a1', 'a2'], 3:['b']} ,3:{2:['c']}})``.\n\n #. ``Graph(a_symmetric_matrix)`` -- return a graph with given (weighted)\n adjacency matrix (see documentation of\n :meth:`~sage.graphs.generic_graph.GenericGraph.adjacency_matrix`).\n\n To bypass auto-detection, prefer the more explicit ``Graph(M,\n format='adjacency_matrix')``. To take weights into account, use\n ``format='weighted_adjacency_matrix'`` instead.\n\n #. ``Graph(a_nonsymmetric_matrix)`` -- return a graph with given incidence\n matrix (see documentation of\n :meth:`~sage.graphs.generic_graph.GenericGraph.incidence_matrix`).\n\n To bypass auto-detection, prefer the more explicit ``Graph(M,\n format='incidence_matrix')``.\n\n #. ``Graph([V, f])`` -- return a graph from a vertex set ``V`` and a\n *symmetric* function ``f``. The graph contains an edge `u,v` whenever\n ``f(u,v)`` is ``True``.. Example: ``Graph([ [1..10], lambda x,y:\n abs(x-y).is_square()])``\n\n #. ``Graph(':I`ES@obGkqegW~')`` -- return a graph from a graph6 or sparse6\n string (see documentation of :meth:`graph6_string` or\n :meth:`sparse6_string`).\n\n #. ``Graph(a_seidel_matrix, format='seidel_adjacency_matrix')`` -- return\n a graph with a given Seidel adjacency matrix (see documentation of\n :meth:`seidel_adjacency_matrix`).\n\n #. ``Graph(another_graph)`` -- return a graph from a Sage (di)graph,\n `pygraphviz <https://pygraphviz.github.io/>`__ graph, `NetworkX\n <https://networkx.github.io/>`__ graph, or `igraph\n <http://igraph.org/python/>`__ graph.\n\n - ``pos`` - a positioning dictionary (cf. documentation of\n :meth:`~sage.graphs.generic_graph.GenericGraph.layout`). For example, to\n draw 4 vertices on a square::\n\n {0: [-1,-1],\n 1: [ 1,-1],\n 2: [ 1, 1],\n 3: [-1, 1]}\n\n - ``name`` - (must be an explicitly named parameter,\n i.e., ``name=\"complete\")`` gives the graph a name\n\n - ``loops`` - boolean, whether to allow loops (ignored\n if data is an instance of the ``Graph`` class)\n\n - ``multiedges`` - boolean, whether to allow multiple\n edges (ignored if data is an instance of the ``Graph`` class).\n\n - ``weighted`` - whether graph thinks of itself as weighted or not. See\n :meth:`~sage.graphs.generic_graph.GenericGraph.weighted`.\n\n - ``format`` - if set to ``None`` (default), :class:`Graph` tries to guess\n input's format. To avoid this possibly time-consuming step, one of the\n following values can be specified (see description above): ``\"int\"``,\n ``\"graph6\"``, ``\"sparse6\"``, ``\"rule\"``, ``\"list_of_edges\"``,\n ``\"dict_of_lists\"``, ``\"dict_of_dicts\"``, ``\"adjacency_matrix\"``,\n ``\"weighted_adjacency_matrix\"``, ``\"seidel_adjacency_matrix\"``,\n ``\"incidence_matrix\"``, ``\"NX\"``, ``\"igraph\"``.\n\n - ``sparse`` (boolean) -- ``sparse=True`` is an alias for\n ``data_structure=\"sparse\"``, and ``sparse=False`` is an alias for\n ``data_structure=\"dense\"``.\n\n - ``data_structure`` -- one of the following (for more information, see\n :mod:`~sage.graphs.base.overview`)\n\n * ``\"dense\"`` -- selects the :mod:`~sage.graphs.base.dense_graph`\n backend.\n\n * ``\"sparse\"`` -- selects the :mod:`~sage.graphs.base.sparse_graph`\n backend.\n\n * ``\"static_sparse\"`` -- selects the\n :mod:`~sage.graphs.base.static_sparse_backend` (this backend is faster\n than the sparse backend and smaller in memory, and it is immutable, so\n that the resulting graphs can be used as dictionary keys).\n\n - ``immutable`` (boolean) -- whether to create a immutable graph. Note that\n ``immutable=True`` is actually a shortcut for\n ``data_structure='static_sparse'``. Set to ``False`` by default.\n\n - ``vertex_labels`` - Whether to allow any object as a vertex (slower), or\n only the integers `0,...,n-1`, where `n` is the number of vertices.\n\n - ``convert_empty_dict_labels_to_None`` - this arguments sets\n the default edge labels used by NetworkX (empty dictionaries)\n to be replaced by None, the default Sage edge label. It is\n set to ``True`` iff a NetworkX graph is on the input.\n\n EXAMPLES:\n\n We illustrate the first seven input formats (the other two\n involve packages that are currently not standard in Sage):\n\n #. An integer giving the number of vertices::\n\n sage: g = Graph(5); g\n Graph on 5 vertices\n sage: g.vertices()\n [0, 1, 2, 3, 4]\n sage: g.edges()\n []\n\n #. A dictionary of dictionaries::\n\n sage: g = Graph({0:{1:'x',2:'z',3:'a'}, 2:{5:'out'}}); g\n Graph on 5 vertices\n\n The labels ('x', 'z', 'a', 'out') are labels for edges. For\n example, 'out' is the label for the edge on 2 and 5. Labels can be\n used as weights, if all the labels share some common parent.\n\n ::\n\n sage: a,b,c,d,e,f = sorted(SymmetricGroup(3))\n sage: Graph({b:{d:'c',e:'p'}, c:{d:'p',e:'c'}})\n Graph on 4 vertices\n\n #. A dictionary of lists::\n\n sage: g = Graph({0:[1,2,3], 2:[4]}); g\n Graph on 5 vertices\n\n #. A list of vertices and a function describing adjacencies. Note\n that the list of vertices and the function must be enclosed in a\n list (i.e., [list of vertices, function]).\n\n Construct the Paley graph over GF(13).\n\n ::\n\n sage: g=Graph([GF(13), lambda i,j: i!=j and (i-j).is_square()])\n sage: g.vertices()\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n sage: g.adjacency_matrix()\n [0 1 0 1 1 0 0 0 0 1 1 0 1]\n [1 0 1 0 1 1 0 0 0 0 1 1 0]\n [0 1 0 1 0 1 1 0 0 0 0 1 1]\n [1 0 1 0 1 0 1 1 0 0 0 0 1]\n [1 1 0 1 0 1 0 1 1 0 0 0 0]\n [0 1 1 0 1 0 1 0 1 1 0 0 0]\n [0 0 1 1 0 1 0 1 0 1 1 0 0]\n [0 0 0 1 1 0 1 0 1 0 1 1 0]\n [0 0 0 0 1 1 0 1 0 1 0 1 1]\n [1 0 0 0 0 1 1 0 1 0 1 0 1]\n [1 1 0 0 0 0 1 1 0 1 0 1 0]\n [0 1 1 0 0 0 0 1 1 0 1 0 1]\n [1 0 1 1 0 0 0 0 1 1 0 1 0]\n\n Construct the line graph of a complete graph.\n\n ::\n\n sage: g=graphs.CompleteGraph(4)\n sage: line_graph=Graph([g.edges(labels=false), \\\n lambda i,j: len(set(i).intersection(set(j)))>0], \\\n loops=False)\n sage: line_graph.vertices()\n [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]\n sage: line_graph.adjacency_matrix()\n [0 1 1 1 1 0]\n [1 0 1 1 0 1]\n [1 1 0 0 1 1]\n [1 1 0 0 1 1]\n [1 0 1 1 0 1]\n [0 1 1 1 1 0]\n\n #. A graph6 or sparse6 string: Sage automatically recognizes\n whether a string is in graph6 or sparse6 format::\n\n sage: s = ':I`AKGsaOs`cI]Gb~'\n sage: Graph(s,sparse=True)\n Looped multi-graph on 10 vertices\n\n ::\n\n sage: G = Graph('G?????')\n sage: G = Graph(\"G'?G?C\")\n Traceback (most recent call last):\n ...\n RuntimeError: The string seems corrupt: valid characters are\n ?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\n sage: G = Graph('G??????')\n Traceback (most recent call last):\n ...\n RuntimeError: The string (G??????) seems corrupt: for n = 8, the string is too long.\n\n ::\n\n sage: G = Graph(\":I'AKGsaOs`cI]Gb~\")\n Traceback (most recent call last):\n ...\n RuntimeError: The string seems corrupt: valid characters are\n ?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\n\n There are also list functions to take care of lists of graphs::\n\n sage: s = ':IgMoqoCUOqeb\\n:I`AKGsaOs`cI]Gb~\\n:I`EDOAEQ?PccSsge\\N\\n'\n sage: graphs_list.from_sparse6(s)\n [Looped multi-graph on 10 vertices, Looped multi-graph on 10 vertices, Looped multi-graph on 10 vertices]\n\n #. A Sage matrix:\n Note: If format is not specified, then Sage assumes a symmetric square\n matrix is an adjacency matrix, otherwise an incidence matrix.\n\n - an adjacency matrix::\n\n sage: M = graphs.PetersenGraph().am(); M\n [0 1 0 0 1 1 0 0 0 0]\n [1 0 1 0 0 0 1 0 0 0]\n [0 1 0 1 0 0 0 1 0 0]\n [0 0 1 0 1 0 0 0 1 0]\n [1 0 0 1 0 0 0 0 0 1]\n [1 0 0 0 0 0 0 1 1 0]\n [0 1 0 0 0 0 0 0 1 1]\n [0 0 1 0 0 1 0 0 0 1]\n [0 0 0 1 0 1 1 0 0 0]\n [0 0 0 0 1 0 1 1 0 0]\n sage: Graph(M)\n Graph on 10 vertices\n\n ::\n\n sage: Graph(matrix([[1,2],[2,4]]),loops=True,sparse=True)\n Looped multi-graph on 2 vertices\n\n sage: M = Matrix([[0,1,-1],[1,0,-1/2],[-1,-1/2,0]]); M\n [ 0 1 -1]\n [ 1 0 -1/2]\n [ -1 -1/2 0]\n sage: G = Graph(M,sparse=True); G\n Graph on 3 vertices\n sage: G.weighted()\n True\n\n - an incidence matrix::\n\n sage: M = Matrix(6, [-1,0,0,0,1, 1,-1,0,0,0, 0,1,-1,0,0, 0,0,1,-1,0, 0,0,0,1,-1, 0,0,0,0,0]); M\n [-1 0 0 0 1]\n [ 1 -1 0 0 0]\n [ 0 1 -1 0 0]\n [ 0 0 1 -1 0]\n [ 0 0 0 1 -1]\n [ 0 0 0 0 0]\n sage: Graph(M)\n Graph on 6 vertices\n\n sage: Graph(Matrix([[1],[1],[1]]))\n Traceback (most recent call last):\n ...\n ValueError: There must be one or two nonzero entries per column in an incidence matrix. Got entries [1, 1, 1] in column 0\n sage: Graph(Matrix([[1],[1],[0]]))\n Graph on 3 vertices\n\n sage: M = Matrix([[0,1,-1],[1,0,-1],[-1,-1,0]]); M\n [ 0 1 -1]\n [ 1 0 -1]\n [-1 -1 0]\n sage: Graph(M,sparse=True)\n Graph on 3 vertices\n\n sage: M = Matrix([[0,1,1],[1,0,1],[-1,-1,0]]); M\n [ 0 1 1]\n [ 1 0 1]\n [-1 -1 0]\n sage: Graph(M)\n Traceback (most recent call last):\n ...\n ValueError: There must be one or two nonzero entries per column in an incidence matrix. Got entries [1, 1] in column 2\n\n Check that :trac:`9714` is fixed::\n\n sage: MA = Matrix([[1,2,0], [0,2,0], [0,0,1]])\n sage: GA = Graph(MA, format='adjacency_matrix')\n sage: MI = GA.incidence_matrix(oriented=False)\n sage: MI\n [2 1 1 0 0 0]\n [0 1 1 2 2 0]\n [0 0 0 0 0 2]\n sage: Graph(MI).edges(labels=None)\n [(0, 0), (0, 1), (0, 1), (1, 1), (1, 1), (2, 2)]\n\n sage: M = Matrix([[1], [-1]]); M\n [ 1]\n [-1]\n sage: Graph(M).edges()\n [(0, 1, None)]\n\n #. A Seidel adjacency matrix::\n\n sage: from sage.combinat.matrices.hadamard_matrix import \\\n ....: regular_symmetric_hadamard_matrix_with_constant_diagonal as rshcd\n sage: m=rshcd(16,1)- matrix.identity(16)\n sage: Graph(m,format=\"seidel_adjacency_matrix\").is_strongly_regular(parameters=True)\n (16, 6, 2, 2)\n\n #. a list of edges, or labelled edges::\n\n sage: g = Graph([(1,3),(3,8),(5,2)])\n sage: g\n Graph on 5 vertices\n\n sage: g = Graph([(1,2,\"Peace\"),(7,-9,\"and\"),(77,2, \"Love\")])\n sage: g\n Graph on 5 vertices\n sage: g = Graph([(0, 2, '0'), (0, 2, '1'), (3, 3, '2')], loops=True, multiedges=True)\n sage: g.loops()\n [(3, 3, '2')]\n\n #. A NetworkX MultiGraph::\n\n sage: import networkx\n sage: g = networkx.MultiGraph({0:[1,2,3], 2:[4]})\n sage: Graph(g)\n Graph on 5 vertices\n\n #. A NetworkX graph::\n\n sage: import networkx\n sage: g = networkx.Graph({0:[1,2,3], 2:[4]})\n sage: DiGraph(g)\n Digraph on 5 vertices\n\n #. An igraph Graph (see also\n :meth:`~sage.graphs.generic_graph.GenericGraph.igraph_graph`)::\n\n sage: import igraph # optional - python_igraph\n sage: g = igraph.Graph([(0,1),(0,2)]) # optional - python_igraph\n sage: Graph(g) # optional - python_igraph\n Graph on 3 vertices\n\n If ``vertex_labels`` is ``True``, the names of the vertices are given by\n the vertex attribute ``'name'``, if available::\n\n sage: g = igraph.Graph([(0,1),(0,2)], vertex_attrs={'name':['a','b','c']}) # optional - python_igraph\n sage: Graph(g).vertices() # optional - python_igraph\n ['a', 'b', 'c']\n sage: g = igraph.Graph([(0,1),(0,2)], vertex_attrs={'label':['a','b','c']}) # optional - python_igraph\n sage: Graph(g).vertices() # optional - python_igraph\n [0, 1, 2]\n\n If the igraph Graph has edge attributes, they are used as edge labels::\n\n sage: g = igraph.Graph([(0,1),(0,2)], edge_attrs={'name':['a','b'], 'weight':[1,3]}) # optional - python_igraph\n sage: Graph(g).edges() # optional - python_igraph\n [(0, 1, {'name': 'a', 'weight': 1}), (0, 2, {'name': 'b', 'weight': 3})]\n\n\n When defining an undirected graph from a function ``f``, it is *very*\n important that ``f`` be symmetric. If it is not, anything can happen::\n\n sage: f_sym = lambda x,y : abs(x-y) == 1\n sage: f_nonsym = lambda x,y : (x-y) == 1\n sage: G_sym = Graph([[4,6,1,5,3,7,2,0], f_sym])\n sage: G_sym.is_isomorphic(graphs.PathGraph(8))\n True\n sage: G_nonsym = Graph([[4,6,1,5,3,7,2,0], f_nonsym])\n sage: G_nonsym.size()\n 4\n sage: G_nonsym.is_isomorphic(G_sym)\n False\n\n By default, graphs are mutable and can thus not be used as a dictionary\n key::\n\n sage: G = graphs.PetersenGraph()\n sage: {G:1}[G]\n Traceback (most recent call last):\n ...\n TypeError: This graph is mutable, and thus not hashable. Create an immutable copy by `g.copy(immutable=True)`\n\n When providing the optional arguments ``data_structure=\"static_sparse\"``\n or ``immutable=True`` (both mean the same), then an immutable graph\n results. ::\n\n sage: G_imm = Graph(G, immutable=True)\n sage: H_imm = Graph(G, data_structure='static_sparse')\n sage: G_imm == H_imm == G\n True\n sage: {G_imm:1}[H_imm]\n 1\n\n TESTS::\n\n sage: Graph(4,format=\"HeyHeyHey\")\n Traceback (most recent call last):\n ...\n ValueError: Unknown input format 'HeyHeyHey'\n\n sage: Graph(igraph.Graph(directed=True)) # optional - python_igraph\n Traceback (most recent call last):\n ...\n ValueError: An *undirected* igraph graph was expected. To build an directed graph, call the DiGraph constructor.\n\n sage: m = matrix([[0,-1],[-1,0]])\n sage: Graph(m,format=\"seidel_adjacency_matrix\")\n Graph on 2 vertices\n sage: m[0,1]=1\n sage: Graph(m,format=\"seidel_adjacency_matrix\")\n Traceback (most recent call last):\n ...\n ValueError: Graph's Seidel adjacency matrix must be symmetric\n\n sage: m[0,1]=-1; m[1,1]=1\n sage: Graph(m,format=\"seidel_adjacency_matrix\")\n Traceback (most recent call last):\n ...\n ValueError: Graph's Seidel adjacency matrix must have 0s on the main diagonal\n\n From a a list of vertices and a list of edges::\n\n sage: G = Graph([[1,2,3],[(1,2)]]); G\n Graph on 3 vertices\n sage: G.edges()\n [(1, 2, None)]\n \"\"\"\n _directed = False\n\n def __init__(self, data=None, pos=None, loops=None, format=None,\n weighted=None, implementation='c_graph',\n data_structure=\"sparse\", vertex_labels=True, name=None,\n multiedges=None, convert_empty_dict_labels_to_None=None,\n sparse=True, immutable=False):\n \"\"\"\n TESTS::\n\n sage: G = Graph()\n sage: loads(dumps(G)) == G\n True\n sage: a = matrix(2,2,[1,0,0,1])\n sage: Graph(a).adjacency_matrix() == a\n True\n\n sage: a = matrix(2,2,[2,0,0,1])\n sage: Graph(a,sparse=True).adjacency_matrix() == a\n True\n\n The positions are copied when the graph is built from\n another graph ::\n\n sage: g = graphs.PetersenGraph()\n sage: h = Graph(g)\n sage: g.get_pos() == h.get_pos()\n True\n\n Or from a DiGraph ::\n\n sage: d = DiGraph(g)\n sage: h = Graph(d)\n sage: g.get_pos() == h.get_pos()\n True\n\n Loops are not counted as multiedges (see :trac:`11693`) and edges are\n not counted twice ::\n\n sage: Graph({1:[1]}).num_edges()\n 1\n sage: Graph({1:[2,2]}).num_edges()\n 2\n\n An empty list or dictionary defines a simple graph\n (:trac:`10441` and :trac:`12910`)::\n\n sage: Graph([])\n Graph on 0 vertices\n sage: Graph({})\n Graph on 0 vertices\n sage: # not \"Multi-graph on 0 vertices\"\n\n Verify that the int format works as expected (:trac:`12557`)::\n\n sage: Graph(2).adjacency_matrix()\n [0 0]\n [0 0]\n sage: Graph(3) == Graph(3,format='int')\n True\n\n Problem with weighted adjacency matrix (:trac:`13919`)::\n\n sage: B = {0:{1:2,2:5,3:4},1:{2:2,4:7},2:{3:1,4:4,5:3},3:{5:4},4:{5:1,6:5},5:{6:7}}\n sage: grafo3 = Graph(B,weighted=True)\n sage: matad = grafo3.weighted_adjacency_matrix()\n sage: grafo4 = Graph(matad,format = \"adjacency_matrix\", weighted=True)\n sage: grafo4.shortest_path(0,6,by_weight=True)\n [0, 1, 2, 5, 4, 6]\n\n Graphs returned when setting ``immutable=False`` are mutable::\n\n sage: g = graphs.PetersenGraph()\n sage: g = Graph(g.edges(),immutable=False)\n sage: g.add_edge(\"Hey\", \"Heyyyyyyy\")\n\n And their name is set::\n\n sage: g = graphs.PetersenGraph()\n sage: Graph(g, immutable=True)\n Petersen graph: Graph on 10 vertices\n\n Check error messages for graphs built from incidence matrices (see\n :trac:`18440`)::\n\n sage: Graph(matrix([[-1, 1, 0],[1, 0, 0]]))\n Traceback (most recent call last):\n ...\n ValueError: Column 1 of the (oriented) incidence matrix contains\n only one nonzero value\n sage: Graph(matrix([[1,1],[1,1],[1,0]]))\n Traceback (most recent call last):\n ...\n ValueError: There must be one or two nonzero entries per column in an incidence matrix. Got entries [1, 1, 1] in column 0\n sage: Graph(matrix([[3,1,1],[0,1,1]]))\n Traceback (most recent call last):\n ...\n ValueError: Each column of a non-oriented incidence matrix must sum\n to 2, but column 0 does not\n \"\"\"\n GenericGraph.__init__(self)\n\n from sage.structure.element import is_Matrix\n\n if sparse is False:\n if data_structure != \"sparse\":\n raise ValueError(\"The 'sparse' argument is an alias for \"\n \"'data_structure'. Please do not define both.\")\n data_structure = \"dense\"\n\n # Choice of the backend\n\n if implementation != 'c_graph':\n deprecation(18375,\"The 'implementation' keyword is deprecated, \"\n \"and the graphs has been stored as a 'c_graph'\")\n\n if multiedges or weighted:\n if data_structure == \"dense\":\n raise RuntimeError(\"Multiedge and weighted c_graphs must be sparse.\")\n if immutable:\n data_structure = 'static_sparse'\n\n # If the data structure is static_sparse, we first build a graph\n # using the sparse data structure, then reencode the resulting graph\n # as a static sparse graph.\n from sage.graphs.base.sparse_graph import SparseGraphBackend\n from sage.graphs.base.dense_graph import DenseGraphBackend\n if data_structure in [\"sparse\", \"static_sparse\"]:\n CGB = SparseGraphBackend\n elif data_structure == \"dense\":\n CGB = DenseGraphBackend\n else:\n raise ValueError(\"data_structure must be equal to 'sparse', \"\n \"'static_sparse' or 'dense'\")\n self._backend = CGB(0, directed=False)\n\n if format is None and isinstance(data, str):\n if data.startswith(\">>graph6<<\"):\n data = data[10:]\n format = 'graph6'\n elif data.startswith(\">>sparse6<<\"):\n data = data[11:]\n format = 'sparse6'\n elif data[0] == ':':\n format = 'sparse6'\n else:\n format = 'graph6'\n if format is None and is_Matrix(data):\n if data.is_symmetric():\n format = 'adjacency_matrix'\n else:\n format = 'incidence_matrix'\n if format is None and isinstance(data, Graph):\n format = 'Graph'\n from sage.graphs.all import DiGraph\n if format is None and isinstance(data, DiGraph):\n data = data.to_undirected()\n format = 'Graph'\n if (format is None and\n isinstance(data,list) and\n len(data)>=2 and\n callable(data[1])):\n format = 'rule'\n\n if (format is None and\n isinstance(data,list) and\n len(data) == 2 and\n isinstance(data[0],list) and # a list of two lists, the second of\n isinstance(data[1],list) and # which contains iterables (the edges)\n (not data[1] or callable(getattr(data[1][0],\"__iter__\",None)))):\n format = \"vertices_and_edges\"\n\n if format is None and isinstance(data,dict):\n keys = data.keys()\n if len(keys) == 0: format = 'dict_of_dicts'\n else:\n if isinstance(data[keys[0]], list):\n format = 'dict_of_lists'\n elif isinstance(data[keys[0]], dict):\n format = 'dict_of_dicts'\n if format is None and hasattr(data, 'adj'):\n import networkx\n if isinstance(data, (networkx.DiGraph, networkx.MultiDiGraph)):\n data = data.to_undirected()\n elif isinstance(data, (networkx.Graph, networkx.MultiGraph)):\n format = 'NX'\n\n if (format is None and\n hasattr(data, 'vcount') and\n hasattr(data, 'get_edgelist')):\n try:\n import igraph\n except ImportError:\n raise ImportError(\"The data seems to be a igraph object, but \"+\n \"igraph is not installed in Sage. To install \"+\n \"it, run 'sage -i python_igraph'\")\n if format is None and isinstance(data, igraph.Graph):\n format = 'igraph'\n if format is None and isinstance(data, (int, Integer)):\n format = 'int'\n if format is None and data is None:\n format = 'int'\n data = 0\n\n # Input is a list of edges\n if format is None and isinstance(data,list):\n format = \"list_of_edges\"\n if weighted is None: weighted = False\n num_verts=0\n\n if format is None:\n raise ValueError(\"This input cannot be turned into a graph\")\n\n if format == 'weighted_adjacency_matrix':\n if weighted is False:\n raise ValueError(\"Format was weighted_adjacency_matrix but weighted was False.\")\n if weighted is None: weighted = True\n if multiedges is None: multiedges = False\n format = 'adjacency_matrix'\n\n # At this point, 'format' has been set. We build the graph\n\n if format == 'graph6':\n if weighted is None: weighted = False\n self.allow_loops(loops if loops else False, check=False)\n self.allow_multiple_edges(multiedges if multiedges else False, check=False)\n from .graph_input import from_graph6\n from_graph6(self, data)\n\n elif format == 'sparse6':\n if weighted is None: weighted = False\n self.allow_loops(False if loops is False else True, check=False)\n self.allow_multiple_edges(False if multiedges is False else True, check=False)\n from .graph_input import from_sparse6\n from_sparse6(self, data)\n\n elif format == 'adjacency_matrix':\n from .graph_input import from_adjacency_matrix\n from_adjacency_matrix(self, data, loops=loops, multiedges=multiedges, weighted=weighted)\n\n elif format == 'incidence_matrix':\n from .graph_input import from_incidence_matrix\n from_incidence_matrix(self, data, loops=loops, multiedges=multiedges, weighted=weighted)\n\n elif format == 'seidel_adjacency_matrix':\n multiedges = False\n weighted = False\n loops = False\n self.allow_loops(False)\n self.allow_multiple_edges(False)\n from .graph_input import from_seidel_adjacency_matrix\n from_seidel_adjacency_matrix(self, data)\n elif format == 'Graph':\n if loops is None: loops = data.allows_loops()\n if multiedges is None: multiedges = data.allows_multiple_edges()\n if weighted is None: weighted = data.weighted()\n self.allow_loops(loops, check=False)\n self.allow_multiple_edges(multiedges, check=False)\n if data.get_pos() is not None:\n pos = data.get_pos().copy()\n self.name(data.name())\n self.add_vertices(data.vertex_iterator())\n self.add_edges(data.edge_iterator())\n elif format == 'NX':\n if convert_empty_dict_labels_to_None is not False:\n r = lambda x:None if x=={} else x\n else:\n r = lambda x:x\n if weighted is None:\n if isinstance(data, networkx.Graph):\n weighted = False\n if multiedges is None:\n multiedges = False\n if loops is None:\n loops = False\n else:\n weighted = True\n if multiedges is None:\n multiedges = True\n if loops is None:\n loops = True\n self.allow_loops(loops, check=False)\n self.allow_multiple_edges(multiedges, check=False)\n self.add_vertices(data.nodes())\n self.add_edges((u,v,r(l)) for u,v,l in data.edges_iter(data=True))\n elif format == 'igraph':\n if data.is_directed():\n raise ValueError(\"An *undirected* igraph graph was expected. \"+\n \"To build an directed graph, call the DiGraph \"+\n \"constructor.\")\n\n self.add_vertices(range(data.vcount()))\n self.add_edges([(e.source, e.target, e.attributes()) for e in data.es()])\n\n if vertex_labels and 'name' in data.vertex_attributes():\n vs = data.vs()\n self.relabel({v:vs[v]['name'] for v in self})\n\n elif format == 'rule':\n f = data[1]\n verts = data[0]\n if loops is None: loops = any(f(v,v) for v in verts)\n if weighted is None: weighted = False\n self.allow_loops(loops, check=False)\n self.allow_multiple_edges(True if multiedges else False, check=False)\n from itertools import combinations\n self.add_vertices(verts)\n self.add_edges(e for e in combinations(verts,2) if f(*e))\n self.add_edges((v,v) for v in verts if f(v,v))\n\n elif format == \"vertices_and_edges\":\n self.allow_multiple_edges(bool(multiedges), check=False)\n self.allow_loops(bool(loops), check=False)\n self.add_vertices(data[0])\n self.add_edges(data[1])\n\n elif format == 'dict_of_dicts':\n from .graph_input import from_dict_of_dicts\n from_dict_of_dicts(self, data, loops=loops, multiedges=multiedges, weighted=weighted,\n convert_empty_dict_labels_to_None = False if convert_empty_dict_labels_to_None is None else convert_empty_dict_labels_to_None)\n\n elif format == 'dict_of_lists':\n from .graph_input import from_dict_of_lists\n from_dict_of_lists(self, data, loops=loops, multiedges=multiedges, weighted=weighted)\n\n elif format == 'int':\n self.allow_loops(loops if loops else False, check=False)\n self.allow_multiple_edges(multiedges if multiedges else False, check=False)\n if data<0:\n raise ValueError(\"The number of vertices cannot be strictly negative!\")\n if data:\n self.add_vertices(range(data))\n\n elif format == 'list_of_edges':\n self.allow_multiple_edges(False if multiedges is False else True, check=False)\n self.allow_loops(False if loops is False else True, check=False)\n self.add_edges(data)\n if multiedges is not True and self.has_multiple_edges():\n deprecation(15706, \"You created a graph with multiple edges \"\n \"from a list. Please set 'multiedges' to 'True' \"\n \"when you do so, as in the future the default \"\n \"behaviour will be to ignore those edges\")\n elif multiedges is None:\n self.allow_multiple_edges(False, check=False)\n\n if loops is not True and self.has_loops():\n deprecation(15706, \"You created a graph with loops from a list. \"+\n \"Please set 'loops' to 'True' when you do so, as in \"+\n \"the future the default behaviour will be to ignore \"+\n \"those edges\")\n elif loops is None:\n self.allow_loops(False, check=False)\n else:\n raise ValueError(\"Unknown input format '{}'\".format(format))\n\n if weighted is None: weighted = False\n self._weighted = getattr(self,'_weighted',weighted)\n\n self._pos = pos\n\n if format != 'Graph' or name is not None:\n self.name(name)\n\n if data_structure == \"static_sparse\":\n from sage.graphs.base.static_sparse_backend import StaticSparseBackend\n ib = StaticSparseBackend(self,\n loops = self.allows_loops(),\n multiedges = self.allows_multiple_edges())\n self._backend = ib\n self._immutable = True\n\n ### Formats\n\n @doc_index(\"Basic methods\")\n def graph6_string(self):\n \"\"\"\n Return the graph6 representation of the graph as an ASCII string.\n\n This is only valid for simple (no loops, no multiple edges) graphs\n on at most `2^{18}-1=262143` vertices.\n\n .. NOTE::\n\n As the graph6 format only handles graphs with vertex set\n `\\{0,...,n-1\\}`, a :meth:`relabelled copy\n <sage.graphs.generic_graph.GenericGraph.relabel>` will\n be encoded, if necessary.\n\n .. SEEALSO::\n\n * :meth:`~sage.graphs.digraph.DiGraph.dig6_string` --\n a similar string format for directed graphs\n\n EXAMPLES::\n\n sage: G = graphs.KrackhardtKiteGraph()\n sage: G.graph6_string()\n 'IvUqwK@?G'\n\n TESTS::\n\n sage: Graph().graph6_string()\n '?'\n \"\"\"\n n = self.order()\n if n > 262143:\n raise ValueError('graph6 format supports graphs on 0 to 262143 vertices only.')\n elif self.has_loops() or self.has_multiple_edges():\n raise ValueError('graph6 format supports only simple graphs (no loops, no multiple edges)')\n else:\n return generic_graph_pyx.small_integer_to_graph6(n) + generic_graph_pyx.binary_string_to_graph6(self._bit_vector())\n\n @doc_index(\"Basic methods\")\n def sparse6_string(self):\n r\"\"\"\n Returns the sparse6 representation of the graph as an ASCII string.\n Only valid for undirected graphs on 0 to 262143 vertices, but loops\n and multiple edges are permitted.\n\n .. NOTE::\n\n As the sparse6 format only handles graphs whose vertex set is\n `\\{0,...,n-1\\}`, a :meth:`relabelled copy\n <sage.graphs.generic_graph.GenericGraph.relabel>` of your graph will\n be encoded if necessary.\n\n EXAMPLES::\n\n sage: G = graphs.BullGraph()\n sage: G.sparse6_string()\n ':Da@en'\n\n ::\n\n sage: G = Graph()\n sage: G.sparse6_string()\n ':?'\n\n ::\n\n sage: G = Graph(loops=True, multiedges=True,data_structure=\"sparse\")\n sage: Graph(':?',data_structure=\"sparse\") == G\n True\n\n TEST:\n\n Check that :trac:`18445` is fixed::\n\n sage: Graph(graphs.KneserGraph(5,2).sparse6_string()).size()\n 15\n\n \"\"\"\n n = self.order()\n if n == 0:\n return ':?'\n if n > 262143:\n raise ValueError('sparse6 format supports graphs on 0 to 262143 vertices only.')\n else:\n v_to_int = {v:i for i,v in enumerate(self.vertices())}\n edges = [sorted((v_to_int[u],v_to_int[v])) for u,v in self.edge_iterator(labels=False)]\n edges.sort(key=lambda e: (e[1],e[0])) # reverse lexicographic order\n\n # encode bit vector\n from math import ceil\n from sage.misc.functional import log\n k = int(ceil(log(n,2)))\n v = 0\n i = 0\n m = 0\n s = ''\n while m < len(edges):\n if edges[m][1] > v + 1:\n sp = generic_graph_pyx.int_to_binary_string(edges[m][1])\n sp = '0'*(k-len(sp)) + sp\n s += '1' + sp\n v = edges[m][1]\n elif edges[m][1] == v + 1:\n sp = generic_graph_pyx.int_to_binary_string(edges[m][0])\n sp = '0'*(k-len(sp)) + sp\n s += '1' + sp\n v += 1\n m += 1\n else:\n sp = generic_graph_pyx.int_to_binary_string(edges[m][0])\n sp = '0'*(k-len(sp)) + sp\n s += '0' + sp\n m += 1\n\n # encode s as a 6-string, as in R(x), but padding with 1's\n # pad on the right to make a multiple of 6\n s = s + ( '1' * ((6 - len(s))%6) )\n\n # split into groups of 6, and convert numbers to decimal, adding 63\n six_bits = ''\n for i in range(len(s)//6):\n six_bits += chr( int( s[6*i:6*(i+1)], 2) + 63 )\n return ':' + generic_graph_pyx.small_integer_to_graph6(n) + six_bits\n\n ### Attributes\n\n @combinatorial_map(name=\"partition of connected components\")\n @doc_index(\"Deprecated\")\n def to_partition(self):\n \"\"\"\n Return the partition of connected components of ``self``.\n\n EXAMPLES::\n\n sage: for x in graphs(3): print(x.to_partition())\n doctest:...: DeprecationWarning: Please use G.connected_components_sizes() instead\n See http://trac.sagemath.org/17449 for details.\n [1, 1, 1]\n [2, 1]\n [3]\n [3]\n \"\"\"\n from sage.misc.superseded import deprecation\n deprecation(17449, \"Please use G.connected_components_sizes() instead\")\n\n from sage.combinat.partition import Partition\n return Partition(sorted([len(y) for y in self.connected_components()], reverse=True))\n\n @doc_index(\"Basic methods\")\n def is_directed(self):\n \"\"\"\n Since graph is undirected, returns False.\n\n EXAMPLES::\n\n sage: Graph().is_directed()\n False\n \"\"\"\n return False\n\n @doc_index(\"Connectivity, orientations, trees\")\n def bridges(self):\n r\"\"\"\n Returns a list of the bridges (or cut edges).\n\n A bridge is an edge so that deleting it disconnects the graph.\n\n .. NOTE::\n\n This method assumes the graph is connected.\n\n EXAMPLES::\n\n sage: g = 2*graphs.PetersenGraph()\n sage: g.add_edge(1,10)\n sage: g.is_connected()\n True\n sage: g.bridges()\n [(1, 10, None)]\n \"\"\"\n gs = self.strong_orientation()\n bridges = []\n for scc in gs.strongly_connected_components():\n bridges.extend(gs.edge_boundary(scc))\n return bridges\n\n @doc_index(\"Connectivity, orientations, trees\")\n def spanning_trees(self):\n \"\"\"\n Returns a list of all spanning trees.\n\n If the graph is disconnected, returns the empty list.\n\n Uses the Read-Tarjan backtracking algorithm [RT75]_.\n\n EXAMPLES::\n\n sage: G = Graph([(1,2),(1,2),(1,3),(1,3),(2,3),(1,4)],multiedges=True)\n sage: len(G.spanning_trees())\n 8\n sage: G.spanning_trees_count()\n 8\n sage: G = Graph([(1,2),(2,3),(3,1),(3,4),(4,5),(4,5),(4,6)],multiedges=True)\n sage: len(G.spanning_trees())\n 6\n sage: G.spanning_trees_count()\n 6\n\n .. SEEALSO::\n\n - :meth:`~sage.graphs.generic_graph.GenericGraph.spanning_trees_count`\n -- counts the number of spanning trees.\n\n - :meth:`~sage.graphs.graph.Graph.random_spanning_tree`\n -- returns a random spanning tree.\n\n TESTS:\n\n Works with looped graphs::\n\n sage: g = Graph({i:[i,(i+1)%6] for i in range(6)})\n sage: g.spanning_trees()\n [Graph on 6 vertices,\n Graph on 6 vertices,\n Graph on 6 vertices,\n Graph on 6 vertices,\n Graph on 6 vertices,\n Graph on 6 vertices]\n\n REFERENCES:\n\n .. [RT75] Read, R. C. and Tarjan, R. E.\n Bounds on Backtrack Algorithms for Listing Cycles, Paths, and Spanning Trees\n Networks, Volume 5 (1975), numer 3, pages 237-252.\n \"\"\"\n\n def _recursive_spanning_trees(G,forest):\n \"\"\"\n Returns all the spanning trees of G containing forest\n \"\"\"\n if not G.is_connected():\n return []\n\n if G.size() == forest.size():\n return [forest.copy()]\n else:\n # Pick an edge e from G-forest\n for e in G.edge_iterator(labels=False):\n if not forest.has_edge(e):\n break\n\n # 1) Recursive call with e removed from G\n G.delete_edge(e)\n trees = _recursive_spanning_trees(G,forest)\n G.add_edge(e)\n\n # 2) Recursive call with e include in forest\n #\n # e=xy links the CC (connected component) of forest containing x\n # with the CC containing y. Any other edge which does that\n # cannot be added to forest anymore, and B is the list of them\n c1 = forest.connected_component_containing_vertex(e[0])\n c2 = forest.connected_component_containing_vertex(e[1])\n G.delete_edge(e)\n B = G.edge_boundary(c1,c2,sort=False)\n G.add_edge(e)\n\n # Actual call\n forest.add_edge(e)\n G.delete_edges(B)\n trees.extend(_recursive_spanning_trees(G,forest))\n G.add_edges(B)\n forest.delete_edge(e)\n\n return trees\n\n if self.is_connected() and len(self):\n forest = Graph([])\n forest.add_vertices(self.vertices())\n forest.add_edges(self.bridges())\n return _recursive_spanning_trees(Graph(self,immutable=False,loops=False), forest)\n else:\n return []\n\n ### Properties\n @doc_index(\"Graph properties\")\n def is_tree(self, certificate=False, output='vertex'):\n \"\"\"\n Tests if the graph is a tree\n\n INPUT:\n\n - ``certificate`` (boolean) -- whether to return a certificate. The\n method only returns boolean answers when ``certificate = False``\n (default). When it is set to ``True``, it either answers ``(True,\n None)`` when the graph is a tree and ``(False, cycle)`` when it\n contains a cycle. It returns ``(False, None)`` when the graph is not\n connected.\n\n - ``output`` (``'vertex'`` (default) or ``'edge'``) -- whether the\n certificate is given as a list of vertices or a list of\n edges.\n\n When the certificate cycle is given as a list of edges, the\n edges are given as `(v_i, v_{i+1}, l)` where `v_1, v_2, \\dots,\n v_n` are the vertices of the cycles (in their cyclic order).\n\n EXAMPLES::\n\n sage: all(T.is_tree() for T in graphs.trees(15))\n True\n\n The empty graph is not considered to be a tree::\n\n sage: graphs.EmptyGraph().is_tree()\n False\n\n With certificates::\n\n sage: g = graphs.RandomTree(30)\n sage: g.is_tree(certificate=True)\n (True, None)\n sage: g.add_edge(10,-1)\n sage: g.add_edge(11,-1)\n sage: isit, cycle = g.is_tree(certificate=True)\n sage: isit\n False\n sage: -1 in cycle\n True\n\n One can also ask for the certificate as a list of edges::\n\n sage: g = graphs.CycleGraph(4)\n sage: g.is_tree(certificate=True, output='edge')\n (False, [(3, 2, None), (2, 1, None), (1, 0, None), (0, 3, None)])\n\n This is useful for graphs with multiple edges::\n\n sage: G = Graph([(1, 2, 'a'), (1, 2, 'b')], multiedges=True)\n sage: G.is_tree(certificate=True)\n (False, [1, 2])\n sage: G.is_tree(certificate=True, output='edge')\n (False, [(1, 2, 'a'), (2, 1, 'b')])\n\n TESTS:\n\n :trac:`14434` is fixed::\n\n sage: g = Graph({0:[1,4,5],3:[4,8,9],4:[9],5:[7,8],7:[9]})\n sage: _,cycle = g.is_tree(certificate=True)\n sage: g.size()\n 10\n sage: g.add_cycle(cycle)\n sage: g.size()\n 10\n \"\"\"\n if not output in ['vertex', 'edge']:\n raise ValueError('output must be either vertex or edge')\n\n if self.order() == 0:\n return False\n\n if not self.is_connected():\n return (False, None) if certificate else False\n\n if certificate:\n if self.num_verts() == self.num_edges() + 1:\n return (True, None)\n\n if self.has_multiple_edges():\n if output == 'vertex':\n return (False, list(self.multiple_edges()[0][:2]))\n edge1, edge2 = self.multiple_edges()[:2]\n if edge1[0] != edge2[0]:\n return (False, [edge1, edge2])\n return (False, [edge1, (edge2[1], edge2[0], edge2[2])])\n\n if output == 'edge':\n if self.allows_multiple_edges():\n def vertices_to_edges(x):\n return [(u[0], u[1], self.edge_label(u[0], u[1])[0])\n for u in zip(x, x[1:] + [x[0]])]\n else:\n def vertices_to_edges(x):\n return [(u[0], u[1], self.edge_label(u[0], u[1]))\n for u in zip(x, x[1:] + [x[0]])]\n\n # This code is a depth-first search that looks for a cycle in the\n # graph. We *know* it exists as there are too many edges around.\n n = self.order()\n seen = {}\n u = next(self.vertex_iterator())\n seen[u] = u\n stack = [(u, v) for v in self.neighbor_iterator(u)]\n while stack:\n u, v = stack.pop(-1)\n if v in seen:\n continue\n for w in self.neighbors(v):\n if u == w:\n continue\n elif w in seen:\n cycle = [v, w]\n while u != w:\n cycle.insert(0, u)\n u = seen[u]\n if output == 'vertex':\n return (False, cycle)\n return (False, vertices_to_edges(cycle))\n else:\n stack.append((v, w))\n seen[v] = u\n\n else:\n return self.num_verts() == self.num_edges() + 1\n\n @doc_index(\"Graph properties\")\n def is_forest(self, certificate=False, output='vertex'):\n \"\"\"\n Tests if the graph is a forest, i.e. a disjoint union of trees.\n\n INPUT:\n\n - ``certificate`` (boolean) -- whether to return a certificate. The\n method only returns boolean answers when ``certificate = False``\n (default). When it is set to ``True``, it either answers ``(True,\n None)`` when the graph is a forest and ``(False, cycle)`` when it\n contains a cycle.\n\n - ``output`` (``'vertex'`` (default) or ``'edge'``) -- whether the\n certificate is given as a list of vertices or a list of\n edges.\n\n EXAMPLES::\n\n sage: seven_acre_wood = sum(graphs.trees(7), Graph())\n sage: seven_acre_wood.is_forest()\n True\n\n With certificates::\n\n sage: g = graphs.RandomTree(30)\n sage: g.is_forest(certificate=True)\n (True, None)\n sage: (2*g + graphs.PetersenGraph() + g).is_forest(certificate=True)\n (False, [63, 62, 61, 60, 64])\n \"\"\"\n number_of_connected_components = len(self.connected_components())\n isit = (self.num_verts() ==\n self.num_edges() + number_of_connected_components)\n\n if not certificate:\n return isit\n else:\n if isit:\n return (True, None)\n # The graph contains a cycle, and the user wants to see it.\n\n # No need to copy the graph\n if number_of_connected_components == 1:\n return self.is_tree(certificate=True, output=output)\n\n # We try to find a cycle in each connected component\n for gg in self.connected_components_subgraphs():\n isit, cycle = gg.is_tree(certificate=True, output=output)\n if not isit:\n return (False, cycle)\n\n @doc_index(\"Graph properties\")\n def is_overfull(self):\n r\"\"\"\n Tests whether the current graph is overfull.\n\n A graph `G` on `n` vertices and `m` edges is said to\n be overfull if:\n\n - `n` is odd\n\n - It satisfies `2m > (n-1)\\Delta(G)`, where\n `\\Delta(G)` denotes the maximum degree\n among all vertices in `G`.\n\n An overfull graph must have a chromatic index of `\\Delta(G)+1`.\n\n EXAMPLES:\n\n A complete graph of order `n > 1` is overfull if and only if `n` is\n odd::\n\n sage: graphs.CompleteGraph(6).is_overfull()\n False\n sage: graphs.CompleteGraph(7).is_overfull()\n True\n sage: graphs.CompleteGraph(1).is_overfull()\n False\n\n The claw graph is not overfull::\n\n sage: from sage.graphs.graph_coloring import edge_coloring\n sage: g = graphs.ClawGraph()\n sage: g\n Claw graph: Graph on 4 vertices\n sage: edge_coloring(g, value_only=True)\n 3\n sage: g.is_overfull()\n False\n\n The Holt graph is an example of a overfull graph::\n\n sage: G = graphs.HoltGraph()\n sage: G.is_overfull()\n True\n\n Checking that all complete graphs `K_n` for even `0 \\leq n \\leq 100`\n are not overfull::\n\n sage: def check_overfull_Kn_even(n):\n ... i = 0\n ... while i <= n:\n ... if graphs.CompleteGraph(i).is_overfull():\n ... print(\"A complete graph of even order cannot be overfull.\")\n ... return\n ... i += 2\n ... print(\"Complete graphs of even order up to %s are not overfull.\" % n)\n ...\n sage: check_overfull_Kn_even(100) # long time\n Complete graphs of even order up to 100 are not overfull.\n\n The null graph, i.e. the graph with no vertices, is not overfull::\n\n sage: Graph().is_overfull()\n False\n sage: graphs.CompleteGraph(0).is_overfull()\n False\n\n Checking that all complete graphs `K_n` for odd `1 < n \\leq 100`\n are overfull::\n\n sage: def check_overfull_Kn_odd(n):\n ... i = 3\n ... while i <= n:\n ... if not graphs.CompleteGraph(i).is_overfull():\n ... print(\"A complete graph of odd order > 1 must be overfull.\")\n ... return\n ... i += 2\n ... print(\"Complete graphs of odd order > 1 up to %s are overfull.\" % n)\n ...\n sage: check_overfull_Kn_odd(100) # long time\n Complete graphs of odd order > 1 up to 100 are overfull.\n\n The Petersen Graph, though, is not overfull while\n its chromatic index is `\\Delta+1`::\n\n sage: g = graphs.PetersenGraph()\n sage: g.is_overfull()\n False\n sage: from sage.graphs.graph_coloring import edge_coloring\n sage: max(g.degree()) + 1 == edge_coloring(g, value_only=True)\n True\n \"\"\"\n # # A possible optimized version. But the gain in speed is very little.\n # return bool(self._backend.num_verts() & 1) and ( # odd order n\n # 2 * self._backend.num_edges(self._directed) > #2m > \\Delta(G)*(n-1)\n # max(self.degree()) * (self._backend.num_verts() - 1))\n # unoptimized version\n return (self.order() % 2 == 1) and (\n 2 * self.size() > max(self.degree()) * (self.order() - 1))\n\n @doc_index(\"Graph properties\")\n def is_even_hole_free(self, certificate = False):\n r\"\"\"\n Tests whether ``self`` contains an induced even hole.\n\n A Hole is a cycle of length at least 4 (included). It is said\n to be even (resp. odd) if its length is even (resp. odd).\n\n Even-hole-free graphs always contain a bisimplicial vertex,\n which ensures that their chromatic number is at most twice\n their clique number [ABCHRS08]_.\n\n INPUT:\n\n - ``certificate`` (boolean) -- When ``certificate = False``,\n this method only returns ``True`` or ``False``. If\n ``certificate = True``, the subgraph found is returned\n instead of ``False``.\n\n EXAMPLE:\n\n Is the Petersen Graph even-hole-free ::\n\n sage: g = graphs.PetersenGraph()\n sage: g.is_even_hole_free()\n False\n\n As any chordal graph is hole-free, interval graphs behave the\n same way::\n\n sage: g = graphs.RandomIntervalGraph(20)\n sage: g.is_even_hole_free()\n True\n\n It is clear, though, that a random Bipartite Graph which is\n not a forest has an even hole::\n\n sage: g = graphs.RandomBipartite(10, 10, .5)\n sage: g.is_even_hole_free() and not g.is_forest()\n False\n\n We can check the certificate returned is indeed an even\n cycle::\n\n sage: if not g.is_forest():\n ... cycle = g.is_even_hole_free(certificate = True)\n ... if cycle.order() % 2 == 1:\n ... print(\"Error !\")\n ... if not cycle.is_isomorphic(\n ... graphs.CycleGraph(cycle.order())):\n ... print(\"Error !\")\n ...\n sage: print(\"Everything is Fine !\")\n Everything is Fine !\n\n TESTS:\n\n Bug reported in :trac:`9925`, and fixed by :trac:`9420`::\n\n sage: g = Graph(':SiBFGaCEF_@CE`DEGH`CEFGaCDGaCDEHaDEF`CEH`ABCDEF', loops=False, multiedges=False)\n sage: g.is_even_hole_free()\n False\n sage: g.is_even_hole_free(certificate = True)\n Subgraph of (): Graph on 4 vertices\n\n Making sure there are no other counter-examples around ::\n\n sage: t = lambda x : (Graph(x).is_forest() or\n ... isinstance(Graph(x).is_even_hole_free(certificate = True),Graph))\n sage: all( t(graphs.RandomBipartite(10,10,.5)) for i in range(100) )\n True\n\n REFERENCE:\n\n .. [ABCHRS08] \\L. Addario-Berry, M. Chudnovsky, F. Havet, B. Reed, P. Seymour\n Bisimplicial vertices in even-hole-free graphs\n Journal of Combinatorial Theory, Series B\n vol 98, n.6 pp 1119-1164, 2008\n \"\"\"\n from sage.graphs.graph_generators import GraphGenerators\n\n girth = self.girth()\n\n if girth > self.order():\n start = 4\n\n elif girth % 2 == 0:\n if not certificate:\n return False\n start = girth\n\n else:\n start = girth + 1\n\n while start <= self.order():\n\n\n subgraph = self.subgraph_search(GraphGenerators().CycleGraph(start), induced = True)\n\n if not subgraph is None:\n if certificate:\n return subgraph\n else:\n return False\n\n start = start + 2\n\n return True\n\n @doc_index(\"Graph properties\")\n def is_odd_hole_free(self, certificate = False):\n r\"\"\"\n Tests whether ``self`` contains an induced odd hole.\n\n A Hole is a cycle of length at least 4 (included). It is said\n to be even (resp. odd) if its length is even (resp. odd).\n\n It is interesting to notice that while it is polynomial to\n check whether a graph has an odd hole or an odd antihole [CRST06]_, it is\n not known whether testing for one of these two cases\n independently is polynomial too.\n\n INPUT:\n\n - ``certificate`` (boolean) -- When ``certificate = False``,\n this method only returns ``True`` or ``False``. If\n ``certificate = True``, the subgraph found is returned\n instead of ``False``.\n\n EXAMPLE:\n\n Is the Petersen Graph odd-hole-free ::\n\n sage: g = graphs.PetersenGraph()\n sage: g.is_odd_hole_free()\n False\n\n Which was to be expected, as its girth is 5 ::\n\n sage: g.girth()\n 5\n\n We can check the certificate returned is indeed a 5-cycle::\n\n sage: cycle = g.is_odd_hole_free(certificate = True)\n sage: cycle.is_isomorphic(graphs.CycleGraph(5))\n True\n\n As any chordal graph is hole-free, no interval graph has an odd hole::\n\n sage: g = graphs.RandomIntervalGraph(20)\n sage: g.is_odd_hole_free()\n True\n\n REFERENCES:\n\n .. [CRST06] \\M. Chudnovsky, G. Cornuejols, X. Liu, P. Seymour, K. Vuskovic\n Recognizing berge graphs\n Combinatorica vol 25, n 2, pages 143--186\n 2005\n \"\"\"\n from sage.graphs.graph_generators import GraphGenerators\n\n girth = self.odd_girth()\n\n if girth > self.order():\n return True\n if girth == 3:\n start = 5\n\n else:\n if not certificate:\n return False\n start = girth\n\n while start <= self.order():\n\n subgraph = self.subgraph_search(GraphGenerators().CycleGraph(start), induced = True)\n\n if not subgraph is None:\n if certificate:\n return subgraph\n else:\n return False\n\n start += 2\n\n return True\n\n @doc_index(\"Graph properties\")\n def is_bipartite(self, certificate = False):\n \"\"\"\n Returns ``True`` if graph `G` is bipartite, ``False`` if not.\n\n Traverse the graph G with breadth-first-search and color nodes.\n\n INPUT:\n\n - ``certificate`` -- whether to return a certificate (``False`` by\n default). If set to ``True``, the certificate returned in a proper\n 2-coloring when `G` is bipartite, and an odd cycle otherwise.\n\n EXAMPLES::\n\n sage: graphs.CycleGraph(4).is_bipartite()\n True\n sage: graphs.CycleGraph(5).is_bipartite()\n False\n sage: graphs.RandomBipartite(100,100,0.7).is_bipartite()\n True\n\n A random graph is very rarely bipartite::\n\n sage: g = graphs.PetersenGraph()\n sage: g.is_bipartite()\n False\n sage: false, oddcycle = g.is_bipartite(certificate = True)\n sage: len(oddcycle) % 2\n 1\n \"\"\"\n color = {}\n\n # For any uncolored vertex in the graph (to ensure we do the right job\n # when the graph is not connected !)\n for u in self:\n if u in color:\n continue\n\n # Let us run a BFS starting from u\n queue = [u]\n color[u] = 1\n while queue:\n v = queue.pop(0)\n c = 1-color[v]\n for w in self.neighbor_iterator(v):\n\n # If the vertex has already been colored\n if w in color:\n\n # The graph is not bipartite !\n if color[w] == color[v]:\n\n # Should we return an odd cycle ?\n if certificate:\n\n # We build the first half of the cycle, i.e. a\n # u-w path\n cycle = self.shortest_path(u,w)\n\n # The second half is a v-u path, but there may\n # be common vertices in the two paths. But we\n # can avoid that !\n\n for v in self.shortest_path(v,u):\n if v in cycle:\n return False, cycle[cycle.index(v):]\n else:\n cycle.append(v)\n else:\n return False\n\n # We color a new vertex\n else:\n color[w] = c\n queue.append(w)\n if certificate:\n return True, color\n else:\n return True\n\n @doc_index(\"Graph properties\")\n def is_triangle_free(self, algorithm='bitset'):\n r\"\"\"\n Returns whether ``self`` is triangle-free\n\n INPUT:\n\n - ``algorithm`` -- (default: ``'bitset'``) specifies the algorithm to\n use among:\n\n - ``'matrix'`` -- tests if the trace of the adjacency matrix is\n positive.\n\n - ``'bitset'`` -- encodes adjacencies into bitsets and uses fast\n bitset operations to test if the input graph contains a\n triangle. This method is generally faster than standard matrix\n multiplication.\n\n EXAMPLE:\n\n The Petersen Graph is triangle-free::\n\n sage: g = graphs.PetersenGraph()\n sage: g.is_triangle_free()\n True\n\n or a complete Bipartite Graph::\n\n sage: G = graphs.CompleteBipartiteGraph(5,6)\n sage: G.is_triangle_free(algorithm='matrix')\n True\n sage: G.is_triangle_free(algorithm='bitset')\n True\n\n a tripartite graph, though, contains many triangles::\n\n sage: G = (3 * graphs.CompleteGraph(5)).complement()\n sage: G.is_triangle_free(algorithm='matrix')\n False\n sage: G.is_triangle_free(algorithm='bitset')\n False\n\n TESTS:\n\n Comparison of algorithms::\n\n sage: for i in range(10): # long test\n ... G = graphs.RandomBarabasiAlbert(50,2)\n ... bm = G.is_triangle_free(algorithm='matrix')\n ... bb = G.is_triangle_free(algorithm='bitset')\n ... if bm != bb:\n ... print(\"That's not good!\")\n\n Asking for an unknown algorithm::\n\n sage: g.is_triangle_free(algorithm='tip top')\n Traceback (most recent call last):\n ...\n ValueError: Algorithm 'tip top' not yet implemented. Please contribute.\n \"\"\"\n if algorithm=='bitset':\n from sage.data_structures.bitset import Bitset\n N = self.num_verts()\n map = {}\n i = 0\n B = {}\n for u in self.vertex_iterator():\n map[u] = i\n i += 1\n B[u] = Bitset(capacity=N)\n # map adjacency to bitsets\n for u,v in self.edge_iterator(labels=None):\n B[u].add(map[v])\n B[v].add(map[u])\n # map lengths 2 paths to bitsets\n BB = Bitset(capacity=N)\n for u in self.vertex_iterator():\n BB.clear()\n for v in self.vertex_iterator():\n if B[u]&B[v]:\n BB.add(map[v])\n # search for triangles\n if B[u]&BB:\n return False\n return True\n\n elif algorithm=='matrix':\n return (self.adjacency_matrix()**3).trace() == 0\n\n else:\n raise ValueError(\"Algorithm '%s' not yet implemented. Please contribute.\" %(algorithm))\n\n @doc_index(\"Graph properties\")\n def is_split(self):\n r\"\"\"\n Returns ``True`` if the graph is a Split graph, ``False`` otherwise.\n\n A Graph `G` is said to be a split graph if its vertices `V(G)`\n can be partitioned into two sets `K` and `I` such that the\n vertices of `K` induce a complete graph, and those of `I` are\n an independent set.\n\n There is a simple test to check whether a graph is a split\n graph (see, for instance, the book \"Graph Classes, a survey\"\n [GraphClasses]_ page 203) :\n\n Given the degree sequence `d_1 \\geq ... \\geq d_n` of `G`, a graph\n is a split graph if and only if :\n\n .. MATH::\n\n \\sum_{i=1}^\\omega d_i = \\omega (\\omega - 1) + \\sum_{i=\\omega + 1}^nd_i\n\n where `\\omega = max \\{i:d_i\\geq i-1\\}`.\n\n\n EXAMPLES:\n\n Split graphs are, in particular, chordal graphs. Hence, The Petersen graph\n can not be split::\n\n sage: graphs.PetersenGraph().is_split()\n False\n\n We can easily build some \"random\" split graph by creating a\n complete graph, and adding vertices only connected\n to some random vertices of the clique::\n\n sage: g = graphs.CompleteGraph(10)\n sage: sets = Subsets(Set(range(10)))\n sage: for i in range(10, 25):\n ... g.add_edges([(i,k) for k in sets.random_element()])\n sage: g.is_split()\n True\n\n Another caracterisation of split graph states that a graph is a split graph\n if and only if does not contain the 4-cycle, 5-cycle or 2K_2 as an induced\n subgraph. Hence for the above graph we have::\n\n sage: sum([g.subgraph_search_count(H,induced=True) for H in [graphs.CycleGraph(4),graphs.CycleGraph(5), 2*graphs.CompleteGraph(2)]])\n 0\n\n\n REFERENCES:\n\n .. [GraphClasses] \\A. Brandstadt, VB Le and JP Spinrad\n Graph classes: a survey\n SIAM Monographs on Discrete Mathematics and Applications},\n 1999\n \"\"\"\n self._scream_if_not_simple()\n # our degree sequence is numbered from 0 to n-1, so to avoid\n # any mistake, let's fix it :-)\n degree_sequence = [0] + sorted(self.degree(), reverse = True)\n\n for (i, d) in enumerate(degree_sequence):\n if d >= i - 1:\n omega = i\n else:\n break\n\n left = sum(degree_sequence[:omega + 1])\n right = omega * (omega - 1) + sum(degree_sequence[omega + 1:])\n\n return left == right\n\n @doc_index(\"Algorithmically hard stuff\")\n def treewidth(self,k=None,certificate=False,algorithm=None):\n r\"\"\"\n Computes the tree-width of `G` (and provides a decomposition)\n\n INPUT:\n\n - ``k`` (integer) -- the width to be considered. When ``k`` is an\n integer, the method checks that the graph has treewidth `\\leq k`. If\n ``k`` is ``None`` (default), the method computes the optimal\n tree-width.\n\n - ``certificate`` -- whether to return the tree-decomposition itself.\n\n - ``algorithm`` -- whether to use ``\"sage\"`` or ``\"tdlib\"`` (requires\n the installation of the 'tdlib' package). The default behaviour is to\n use 'tdlib' if it is available, and Sage's own algorithm when it is\n not.\n\n OUTPUT:\n\n ``g.treewidth()`` returns the treewidth of ``g``. When ``k`` is\n specified, it returns ``False`` when no tree-decomposition of width\n `\\leq k` exists or ``True`` otherwise. When ``certificate=True``,\n the tree-decomposition is also returned.\n\n ALGORITHM:\n\n This function virtually explores the graph of all pairs\n ``(vertex_cut,cc)``, where ``vertex_cut`` is a vertex cut of the\n graph of cardinality `\\leq k+1`, and ``connected_component`` is a\n connected component of the graph induced by ``G-vertex_cut``.\n\n We deduce that the pair ``(vertex_cut,cc)`` is feasible with\n tree-width `k` if ``cc`` is empty, or if a vertex ``v`` from\n ``vertex_cut`` can be replaced with a vertex from ``cc``, such that\n the pair ``(vertex_cut+v,cc-v)`` is feasible.\n\n .. NOTE::\n\n The implementation would be much faster if ``cc``, the argument of the\n recursive function, was a bitset. It would also be very nice to not copy\n the graph in order to compute connected components, for this is really a\n waste of time.\n\n .. SEEALSO::\n\n :meth:`~sage.graphs.graph_decompositions.vertex_separation.path_decomposition`\n computes the pathwidth of a graph. See also the\n :mod:`~sage.graphs.graph_decompositions.vertex_separation` module.\n\n EXAMPLES:\n\n The PetersenGraph has treewidth 4::\n\n sage: graphs.PetersenGraph().treewidth()\n 4\n sage: graphs.PetersenGraph().treewidth(certificate=True)\n Tree decomposition: Graph on 6 vertices\n\n The treewidth of a 2d grid is its smallest side::\n\n sage: graphs.Grid2dGraph(2,5).treewidth()\n 2\n sage: graphs.Grid2dGraph(3,5).treewidth()\n 3\n\n TESTS::\n\n sage: g = graphs.PathGraph(3)\n sage: g.treewidth()\n 1\n sage: g = 2*graphs.PathGraph(3)\n sage: g.treewidth()\n 1\n sage: g.treewidth(certificate=True)\n Tree decomposition: Graph on 4 vertices\n sage: g.treewidth(2)\n True\n sage: g.treewidth(1)\n True\n sage: Graph(1).treewidth()\n 0\n sage: Graph(0).treewidth()\n -1\n sage: graphs.PetersenGraph().treewidth(k=2)\n False\n sage: graphs.PetersenGraph().treewidth(k=6)\n True\n sage: graphs.PetersenGraph().treewidth(certificate=True).is_tree()\n True\n sage: graphs.PetersenGraph().treewidth(k=3,certificate=True)\n False\n sage: graphs.PetersenGraph().treewidth(k=4,certificate=True)\n Tree decomposition: Graph on 6 vertices\n\n All edges do appear (:trac:`17893`)::\n\n sage: from itertools import combinations\n sage: g = graphs.PathGraph(10)\n sage: td = g.treewidth(certificate=True)\n sage: for bag in td:\n ....: g.delete_edges(list(combinations(bag,2)))\n sage: g.size()\n 0\n\n :trac:`19358`::\n\n sage: g = Graph()\n sage: for i in range(3):\n ....: for j in range(2):\n ....: g.add_path([i,(i,j),(i+1)%3])\n sage: g.treewidth()\n 2\n\n Trivially true::\n\n sage: graphs.PetersenGraph().treewidth(k=35)\n True\n sage: graphs.PetersenGraph().treewidth(k=35,certificate=True)\n Tree decomposition: Graph on 1 vertex\n\n Bad input:\n\n sage: graphs.PetersenGraph().treewidth(k=-3)\n Traceback (most recent call last):\n ...\n ValueError: k(=-3) must be a nonnegative integer\n \"\"\"\n g = self\n\n # Check Input\n if algorithm is None:\n try:\n import sage.graphs.graph_decompositions.tdlib as tdlib\n algorithm = \"tdlib\"\n except ImportError:\n algorithm = \"sage\"\n elif (algorithm != \"sage\" and\n algorithm != \"tdlib\"):\n raise ValueError(\"'algorithm' must be equal to 'tdlib', 'sage', or None\")\n\n if k is not None and k<0:\n raise ValueError(\"k(={}) must be a nonnegative integer\".format(k))\n\n # Stupid cases\n if g.order() == 0:\n if certificate: return Graph()\n elif k is None: return -1\n else: return True\n\n if k is not None and k >= g.order()-1:\n if certificate:\n return Graph({sage.sets.set.Set(g.vertices()):[]},\n name=\"Tree decomposition\")\n return True\n\n # TDLIB\n if algorithm == 'tdlib':\n try:\n import sage.graphs.graph_decompositions.tdlib as tdlib\n except ImportError:\n from sage.misc.package import PackageNotFoundError\n raise PackageNotFoundError(\"tdlib\")\n\n T = tdlib.treedecomposition_exact(g, -1 if k is None else k)\n width = tdlib.get_width(T)\n\n if certificate:\n return T if (k is None or width <= k) else False\n elif k is None:\n return width\n else:\n return (width <= k)\n\n # Disconnected cases\n if not g.is_connected():\n if certificate is False:\n if k is None:\n return max(cc.treewidth() for cc in g.connected_components_subgraphs())\n else:\n return all(cc.treewidth(k) for cc in g.connected_components_subgraphs())\n else:\n return Graph(sum([cc.treewidth(certificate=True).edges(labels=False)\n for cc in g.connected_components_subgraphs()],[]),\n name=\"Tree decomposition\")\n\n # Forcing k to be defined\n if k is None:\n for i in range(max(0,g.clique_number()-1,min(g.degree())),\n g.order()+1):\n ans = g.treewidth(k=i, certificate=certificate)\n if ans:\n return ans if certificate else i\n\n # This is the recursion described in the method's documentation. All\n # computations are cached, and depends on the pair ``cut,\n # connected_component`` only.\n #\n # It returns either a boolean or the corresponding tree-decomposition, as a\n # list of edges between vertex cuts (as it is done for the complete\n # tree-decomposition at the end of the main function.\n from sage.misc.cachefunc import cached_function\n @cached_function\n def rec(cut,cc):\n # Easy cases\n if len(cut) > k:\n return False\n if len(cc)+len(cut) <= k+1:\n return [(cut,cut.union(cc))] if certificate else True\n\n # We explore all possible extensions of the cut\n for v in cc:\n\n # New cuts and connected components, with v respectively added and\n # removed\n cutv = cut.union([v])\n ccv = cc.difference([v])\n\n # The values returned by the recursive calls.\n sons = []\n\n # Removing v may have disconnected cc. We iterate on its connected\n # components\n for cci in g.subgraph(ccv).connected_components():\n\n # The recursive subcalls. We remove on-the-fly the vertices from\n # the cut which play no role in separating the connected\n # component from the rest of the graph.\n reduced_cut = frozenset([x for x in cutv if any(xx in cci for xx in g.neighbors(x))])\n son = rec(reduced_cut,frozenset(cci))\n if son is False:\n break\n\n if certificate:\n sons.extend(son)\n sons.append((cut,cutv))\n sons.append((cutv,reduced_cut))\n\n # Weird Python syntax which is useful once in a lifetime : if break\n # was never called in the loop above, we return \"sons\".\n else:\n return sons if certificate else True\n\n return False\n\n # Main call to rec function, i.e. rec({v},V-{v})\n V = g.vertices()\n v = frozenset([V.pop(0)])\n TD = rec(v,frozenset(V))\n\n if TD is False:\n return False\n\n if not certificate:\n return True\n\n # Building the Tree-Decomposition graph. Its vertices are cuts of the\n # decomposition, and there is an edge from a cut C1 to a cut C2 if C2 is an\n # immediate subcall of C1\n from sage.sets.set import Set\n G = Graph(name=\"Tree decomposition\")\n G.add_edges([(Set(x),Set(y)) for x,y in TD])\n\n # The Tree-Decomposition contains a lot of useless nodes.\n #\n # We merge all edges between two sets S,S' where S is a subset of S'\n changed = True\n while changed:\n changed=False\n for v in G.vertices():\n for u in G.neighbors(v):\n if u.issuperset(v):\n G.merge_vertices([u,v]) # the new vertex is named 'u'\n changed = True\n break\n\n return G\n\n @doc_index(\"Algorithmically hard stuff\")\n def is_perfect(self, certificate = False):\n r\"\"\"\n Tests whether the graph is perfect.\n\n A graph `G` is said to be perfect if `\\chi(H)=\\omega(H)` hold\n for any induced subgraph `H\\subseteq_i G` (and so for `G`\n itself, too), where `\\chi(H)` represents the chromatic number\n of `H`, and `\\omega(H)` its clique number. The Strong Perfect\n Graph Theorem [SPGT]_ gives another characterization of\n perfect graphs:\n\n A graph is perfect if and only if it contains no odd hole\n (cycle on an odd number `k` of vertices, `k>3`) nor any odd\n antihole (complement of a hole) as an induced subgraph.\n\n INPUT:\n\n - ``certificate`` (boolean) -- whether to return\n a certificate (default : ``False``)\n\n OUTPUT:\n\n When ``certificate = False``, this function returns\n a boolean value. When ``certificate = True``, it returns\n a subgraph of ``self`` isomorphic to an odd hole or an odd\n antihole if any, and ``None`` otherwise.\n\n EXAMPLE:\n\n A Bipartite Graph is always perfect ::\n\n sage: g = graphs.RandomBipartite(8,4,.5)\n sage: g.is_perfect()\n True\n\n So is the line graph of a bipartite graph::\n\n sage: g = graphs.RandomBipartite(4,3,0.7)\n sage: g.line_graph().is_perfect() # long time\n True\n\n As well as the Cartesian product of two complete graphs::\n\n sage: g = graphs.CompleteGraph(3).cartesian_product(graphs.CompleteGraph(3))\n sage: g.is_perfect()\n True\n\n Interval Graphs, which are chordal graphs, too ::\n\n sage: g = graphs.RandomIntervalGraph(7)\n sage: g.is_perfect()\n True\n\n The PetersenGraph, which is triangle-free and\n has chromatic number 3 is obviously not perfect::\n\n sage: g = graphs.PetersenGraph()\n sage: g.is_perfect()\n False\n\n We can obtain an induced 5-cycle as a certificate::\n\n sage: g.is_perfect(certificate = True)\n Subgraph of (Petersen graph): Graph on 5 vertices\n\n TEST:\n\n Check that :trac:`13546` has been fixed::\n\n sage: Graph(':FgGE@I@GxGs', loops=False, multiedges=False).is_perfect()\n False\n sage: g = Graph({0: [2, 3, 4, 5],\n ... 1: [3, 4, 5, 6],\n ... 2: [0, 4, 5, 6],\n ... 3: [0, 1, 5, 6],\n ... 4: [0, 1, 2, 6],\n ... 5: [0, 1, 2, 3],\n ... 6: [1, 2, 3, 4]})\n sage: g.is_perfect()\n False\n\n REFERENCES:\n\n .. [SPGT] \\M. Chudnovsky, N. Robertson, P. Seymour, R. Thomas.\n The strong perfect graph theorem\n Annals of Mathematics\n vol 164, number 1, pages 51--230\n 2006\n\n TESTS::\n\n sage: Graph(':Ab').is_perfect()\n Traceback (most recent call last):\n ...\n ValueError: This method is only defined for simple graphs, and yours is not one of them !\n sage: g = Graph()\n sage: g.allow_loops(True)\n sage: g.add_edge(0,0)\n sage: g.edges()\n [(0, 0, None)]\n sage: g.is_perfect()\n Traceback (most recent call last):\n ...\n ValueError: This method is only defined for simple graphs, and yours is not one of them !\n\n \"\"\"\n\n if self.has_multiple_edges() or self.has_loops():\n raise ValueError(\"This method is only defined for simple graphs,\"\n \" and yours is not one of them !\")\n if self.is_bipartite():\n\n return True if not certificate else None\n\n self_complement = self.complement()\n\n self_complement.remove_loops()\n self_complement.remove_multiple_edges()\n\n if self_complement.is_bipartite():\n return True if not certificate else None\n\n answer = self.is_odd_hole_free(certificate = certificate)\n if not (answer is True):\n return answer\n\n return self_complement.is_odd_hole_free(certificate = certificate)\n\n @doc_index(\"Graph properties\")\n def odd_girth(self):\n r\"\"\"\n Returns the odd girth of self.\n\n The odd girth of a graph is defined as the smallest cycle of odd length.\n\n OUTPUT:\n\n The odd girth of ``self``.\n\n EXAMPLES:\n\n The McGee graph has girth 7 and therefore its odd girth is 7 as well. ::\n\n sage: G = graphs.McGeeGraph()\n sage: G.odd_girth()\n 7\n\n Any complete graph on more than 2 vertices contains a triangle and has\n thus odd girth 3. ::\n\n sage: G = graphs.CompleteGraph(10)\n sage: G.odd_girth()\n 3\n\n Every bipartite graph has no odd cycles and consequently odd girth of\n infinity. ::\n\n sage: G = graphs.CompleteBipartiteGraph(100,100)\n sage: G.odd_girth()\n +Infinity\n\n .. SEEALSO::\n\n * :meth:`~sage.graphs.generic_graph.GenericGraph.girth` -- computes\n the girth of a graph.\n\n REFERENCES:\n\n The property relating the odd girth to the coefficients of the\n characteristic polynomial is an old result from algebraic graph theory\n see\n\n .. [Har62] Harary, F (1962). The determinant of the adjacency matrix of\n a graph, SIAM Review 4, 202-210\n\n .. [Biggs93] Biggs, N. L. Algebraic Graph Theory, 2nd ed. Cambridge,\n England: Cambridge University Press, pp. 45, 1993.\n\n TESTS::\n\n sage: graphs.CycleGraph(5).odd_girth()\n 5\n sage: graphs.CycleGraph(11).odd_girth()\n 11\n \"\"\"\n ch = ((self.am()).charpoly()).coefficients(sparse=False)\n n = self.order()\n\n for i in range(n-1,-1,-2):\n if ch[i] != 0:\n return n-i\n\n from sage.rings.infinity import Infinity\n\n return Infinity\n\n @doc_index(\"Graph properties\")\n def is_edge_transitive(self):\n \"\"\"\n Returns true if self is an edge transitive graph.\n\n A graph is edge-transitive if its automorphism group acts transitively\n on its edge set.\n\n Equivalently, if there exists for any pair of edges `uv,u'v'\\in E(G)` an\n automorphism `\\phi` of `G` such that `\\phi(uv)=u'v'` (note this does not\n necessarily mean that `\\phi(u)=u'` and `\\phi(v)=v'`).\n\n See :wikipedia:`the wikipedia article on edge-transitive graphs\n <Edge-transitive_graph>` for more information.\n\n .. SEEALSO::\n\n - :meth:`~Graph.is_arc_transitive`\n - :meth:`~Graph.is_half_transitive`\n - :meth:`~Graph.is_semi_symmetric`\n\n EXAMPLES::\n\n sage: P = graphs.PetersenGraph()\n sage: P.is_edge_transitive()\n True\n sage: C = graphs.CubeGraph(3)\n sage: C.is_edge_transitive()\n True\n sage: G = graphs.GrayGraph()\n sage: G.is_edge_transitive()\n True\n sage: P = graphs.PathGraph(4)\n sage: P.is_edge_transitive()\n False\n \"\"\"\n from sage.interfaces.gap import gap\n\n if self.size() == 0:\n return True\n\n A = self.automorphism_group()\n e = next(self.edge_iterator(labels=False))\n e = [A._domain_to_gap[e[0]], A._domain_to_gap[e[1]]]\n\n return gap(\"OrbitLength(\"+str(A._gap_())+\",Set(\" + str(e) + \"),OnSets);\") == self.size()\n\n @doc_index(\"Graph properties\")\n def is_arc_transitive(self):\n \"\"\"\n Returns true if self is an arc-transitive graph\n\n A graph is arc-transitive if its automorphism group acts transitively on\n its pairs of adjacent vertices.\n\n Equivalently, if there exists for any pair of edges `uv,u'v'\\in E(G)` an\n automorphism `\\phi_1` of `G` such that `\\phi_1(u)=u'` and\n `\\phi_1(v)=v'`, as well as another automorphism `\\phi_2` of `G` such\n that `\\phi_2(u)=v'` and `\\phi_2(v)=u'`\n\n See :wikipedia:`the wikipedia article on arc-transitive graphs\n <arc-transitive_graph>` for more information.\n\n .. SEEALSO::\n\n - :meth:`~Graph.is_edge_transitive`\n - :meth:`~Graph.is_half_transitive`\n - :meth:`~Graph.is_semi_symmetric`\n\n EXAMPLES::\n\n sage: P = graphs.PetersenGraph()\n sage: P.is_arc_transitive()\n True\n sage: G = graphs.GrayGraph()\n sage: G.is_arc_transitive()\n False\n \"\"\"\n\n from sage.interfaces.gap import gap\n\n if self.size() == 0:\n return True\n\n A = self.automorphism_group()\n e = next(self.edge_iterator(labels=False))\n e = [A._domain_to_gap[e[0]], A._domain_to_gap[e[1]]]\n\n return gap(\"OrbitLength(\"+str(A._gap_())+\",Set(\" + str(e) + \"),OnTuples);\") == 2*self.size()\n\n @doc_index(\"Graph properties\")\n def is_half_transitive(self):\n \"\"\"\n Returns true if self is a half-transitive graph.\n\n A graph is half-transitive if it is both vertex and edge transitive\n but not arc-transitive.\n\n See :wikipedia:`the wikipedia article on half-transitive graphs\n <half-transitive_graph>` for more information.\n\n .. SEEALSO::\n\n - :meth:`~Graph.is_edge_transitive`\n - :meth:`~Graph.is_arc_transitive`\n - :meth:`~Graph.is_semi_symmetric`\n\n EXAMPLES:\n\n The Petersen Graph is not half-transitive::\n\n sage: P = graphs.PetersenGraph()\n sage: P.is_half_transitive()\n False\n\n The smallest half-transitive graph is the Holt Graph::\n\n sage: H = graphs.HoltGraph()\n sage: H.is_half_transitive()\n True\n \"\"\"\n\n # A half-transitive graph always has only vertices of even degree\n if not all(d%2 == 0 for d in self.degree_iterator()):\n return False\n\n return (self.is_edge_transitive() and\n self.is_vertex_transitive() and\n not self.is_arc_transitive())\n\n @doc_index(\"Graph properties\")\n def is_semi_symmetric(self):\n \"\"\"\n Returns true if self is semi-symmetric.\n\n A graph is semi-symmetric if it is regular, edge-transitve but not\n vertex-transitive.\n\n See :wikipedia:`the wikipedia article on semi-symmetric graphs\n <Semi-symmetric_graph>` for more information.\n\n .. SEEALSO::\n\n - :meth:`~Graph.is_edge_transitive`\n - :meth:`~Graph.is_arc_transitive`\n - :meth:`~Graph.is_half_transitive`\n\n EXAMPLES:\n\n The Petersen graph is not semi-symmetric::\n\n sage: P = graphs.PetersenGraph()\n sage: P.is_semi_symmetric()\n False\n\n The Gray graph is the smallest possible cubic semi-symmetric graph::\n\n sage: G = graphs.GrayGraph()\n sage: G.is_semi_symmetric()\n True\n\n Another well known semi-symmetric graph is the Ljubljana graph::\n\n sage: L = graphs.LjubljanaGraph()\n sage: L.is_semi_symmetric()\n True\n \"\"\"\n # A semi-symmetric graph is always bipartite\n if not self.is_bipartite():\n return False\n\n return (self.is_regular() and\n self.is_edge_transitive() and not\n self.is_vertex_transitive())\n\n @doc_index(\"Connectivity, orientations, trees\")\n def degree_constrained_subgraph(self, bounds=None, solver=None, verbose=0):\n r\"\"\"\n Returns a degree-constrained subgraph.\n\n Given a graph `G` and two functions `f, g:V(G)\\rightarrow \\mathbb Z`\n such that `f \\leq g`, a degree-constrained subgraph in `G` is\n a subgraph `G' \\subseteq G` such that for any vertex `v \\in G`,\n `f(v) \\leq d_{G'}(v) \\leq g(v)`.\n\n INPUT:\n\n - ``bounds`` -- (default: ``None``) Two possibilities:\n\n - A dictionary whose keys are the vertices, and values a pair of\n real values ``(min,max)`` corresponding to the values\n `(f(v),g(v))`.\n\n - A function associating to each vertex a pair of\n real values ``(min,max)`` corresponding to the values\n `(f(v),g(v))`.\n\n\n - ``solver`` -- (default: ``None``) Specify a Linear Program (LP)\n solver to be used. If set to ``None``, the default one is used. For\n more information on LP solvers and which default solver is used, see\n the method\n :meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>`\n of the class\n :class:`MixedIntegerLinearProgram <sage.numerical.mip.MixedIntegerLinearProgram>`.\n\n - ``verbose`` -- integer (default: ``0``). Sets the level of\n verbosity. Set to 0 by default, which means quiet.\n\n OUTPUT:\n\n - When a solution exists, this method outputs the degree-constained\n subgraph as a Graph object.\n\n - When no solution exists, returns ``False``.\n\n .. NOTE::\n\n - This algorithm computes the degree-constrained subgraph of minimum weight.\n - If the graph's edges are weighted, these are taken into account.\n - This problem can be solved in polynomial time.\n\n EXAMPLES:\n\n Is there a perfect matching in an even cycle? ::\n\n sage: g = graphs.CycleGraph(6)\n sage: bounds = lambda x: [1,1]\n sage: m = g.degree_constrained_subgraph(bounds=bounds)\n sage: m.size()\n 3\n \"\"\"\n self._scream_if_not_simple()\n from sage.numerical.mip import MixedIntegerLinearProgram, MIPSolverException\n\n p = MixedIntegerLinearProgram(maximization=False, solver=solver)\n b = p.new_variable(binary=True)\n\n reorder = lambda x,y: (x,y) if x<y else (y,x)\n\n if bounds is None:\n raise ValueError(\"The `bounds` keyword can not be equal to None\")\n elif isinstance(bounds,dict):\n f_bounds = lambda x: bounds[x]\n else:\n f_bounds = bounds\n\n\n if self.weighted():\n from sage.rings.real_mpfr import RR\n weight = lambda x: x if x in RR else 1\n else:\n weight = lambda x: 1\n\n for v in self:\n minimum,maximum = f_bounds(v)\n p.add_constraint(p.sum( b[reorder(x,y)]*weight(l) for x,y,l in self.edges_incident(v)), min=minimum, max=maximum)\n\n p.set_objective(p.sum( b[reorder(x,y)]*weight(l) for x,y,l in self.edge_iterator()))\n\n try:\n p.solve(log=verbose)\n g = copy(self)\n b = p.get_values(b)\n g.delete_edges([(x,y) for x,y,_ in g.edge_iterator() if b[reorder(x,y)] < 0.5])\n return g\n\n\n except MIPSolverException:\n return False\n\n\n ### Orientations\n\n @doc_index(\"Connectivity, orientations, trees\")\n def strong_orientation(self):\n r\"\"\"\n Returns a strongly connected orientation of the current graph.\n\n An orientation of an undirected graph is a digraph obtained by giving an\n unique direction to each of its edges. An orientation is said to be\n strong if there is a directed path between each pair of vertices. See\n also the :wikipedia:`Strongly_connected_component`.\n\n If the graph is 2-edge-connected, a strongly connected orientation\n can be found in linear time. If the given graph is not 2-connected,\n the orientation returned will ensure that each 2-connected component\n has a strongly connected orientation.\n\n OUTPUT:\n\n A digraph representing an orientation of the current graph.\n\n .. NOTE::\n\n - This method assumes the graph is connected.\n - This algorithm works in O(m).\n\n EXAMPLE:\n\n For a 2-regular graph, a strong orientation gives to each vertex\n an out-degree equal to 1::\n\n sage: g = graphs.CycleGraph(5)\n sage: g.strong_orientation().out_degree()\n [1, 1, 1, 1, 1]\n\n The Petersen Graph is 2-edge connected. It then has a strongly\n connected orientation::\n\n sage: g = graphs.PetersenGraph()\n sage: o = g.strong_orientation()\n sage: len(o.strongly_connected_components())\n 1\n\n The same goes for the CubeGraph in any dimension ::\n\n sage: all(len(graphs.CubeGraph(i).strong_orientation().strongly_connected_components()) == 1 for i in range(2,6))\n True\n\n A multigraph also has a strong orientation ::\n\n sage: g = Graph([(1,2),(1,2)],multiedges=True)\n sage: g.strong_orientation()\n Multi-digraph on 2 vertices\n\n \"\"\"\n from sage.graphs.all import DiGraph\n d = DiGraph(multiedges=self.allows_multiple_edges())\n\n id = {}\n i = 0\n\n # The algorithm works through a depth-first search. Any edge\n # used in the depth-first search is oriented in the direction\n # in which it has been used. All the other edges are oriented\n # backward\n\n v = next(self.vertex_iterator())\n seen = {}\n i=1\n\n # Time at which the vertices have been discovered\n seen[v] = i\n\n # indicates the stack of edges to explore\n next_ = self.edges_incident(v)\n\n while next_:\n e = next_.pop(-1)\n # We assume e[0] to be a `seen` vertex\n e = e if seen.get(e[0],False) is not False else (e[1],e[0],e[2])\n\n # If we discovered a new vertex\n if seen.get(e[1],False) is False:\n d.add_edge(e)\n next_.extend([ee for ee in self.edges_incident(e[1]) if (((e[0],e[1]) != (ee[0],ee[1])) and ((e[0],e[1]) != (ee[1],ee[0])))])\n i+=1\n seen[e[1]]=i\n\n # Else, we orient the edges backward\n else:\n if seen[e[0]] < seen[e[1]]:\n d.add_edge((e[1],e[0],e[2]))\n else:\n d.add_edge(e)\n\n # Case of multiple edges. If another edge has already been inserted, we add the new one\n # in the opposite direction.\n tmp = None\n for e in self.multiple_edges():\n if tmp == (e[0],e[1]):\n if d.has_edge(e[0],e[1]):\n d.add_edge(e[1],e[0],e[2])\n else:\n d.add_edge(e)\n tmp = (e[0],e[1])\n\n return d\n\n @doc_index(\"Connectivity, orientations, trees\")\n def minimum_outdegree_orientation(self, use_edge_labels=False, solver=None, verbose=0):\n r\"\"\"\n Returns an orientation of ``self`` with the smallest possible maximum\n outdegree.\n\n Given a Graph `G`, it is polynomial to compute an orientation\n `D` of the edges of `G` such that the maximum out-degree in\n `D` is minimized. This problem, though, is NP-complete in the\n weighted case [AMOZ06]_.\n\n INPUT:\n\n - ``use_edge_labels`` -- boolean (default: ``False``)\n\n - When set to ``True``, uses edge labels as weights to\n compute the orientation and assumes a weight of `1`\n when there is no value available for a given edge.\n\n - When set to ``False`` (default), gives a weight of 1\n to all the edges.\n\n - ``solver`` -- (default: ``None``) Specify a Linear Program (LP)\n solver to be used. If set to ``None``, the default one is used. For\n more information on LP solvers and which default solver is used, see\n the method\n :meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>`\n of the class\n :class:`MixedIntegerLinearProgram <sage.numerical.mip.MixedIntegerLinearProgram>`.\n\n - ``verbose`` -- integer (default: ``0``). Sets the level of\n verbosity. Set to 0 by default, which means quiet.\n\n EXAMPLE:\n\n Given a complete bipartite graph `K_{n,m}`, the maximum out-degree\n of an optimal orientation is `\\left\\lceil \\frac {nm} {n+m}\\right\\rceil`::\n\n sage: g = graphs.CompleteBipartiteGraph(3,4)\n sage: o = g.minimum_outdegree_orientation()\n sage: max(o.out_degree()) == ceil((4*3)/(3+4))\n True\n\n REFERENCES:\n\n .. [AMOZ06] Asahiro, Y. and Miyano, E. and Ono, H. and Zenmyo, K.\n Graph orientation algorithms to minimize the maximum outdegree\n Proceedings of the 12th Computing: The Australasian Theory Symposium\n Volume 51, page 20\n Australian Computer Society, Inc. 2006\n \"\"\"\n self._scream_if_not_simple()\n if self.is_directed():\n raise ValueError(\"Cannot compute an orientation of a DiGraph. \"+\\\n \"Please convert it to a Graph if you really mean it.\")\n\n if use_edge_labels:\n from sage.rings.real_mpfr import RR\n weight = lambda u,v : self.edge_label(u,v) if self.edge_label(u,v) in RR else 1\n else:\n weight = lambda u,v : 1\n\n from sage.numerical.mip import MixedIntegerLinearProgram\n\n p = MixedIntegerLinearProgram(maximization=False, solver=solver)\n\n # The orientation of an edge is boolean\n # and indicates whether the edge uv\n # with u<v goes from u to v ( equal to 0 )\n # or from v to u ( equal to 1)\n orientation = p.new_variable(binary=True)\n\n degree = p.new_variable(nonnegative=True)\n\n # Whether an edge adjacent to a vertex u counts\n # positively or negatively\n outgoing = lambda u,v,variable : (1-variable) if u>v else variable\n\n for u in self:\n p.add_constraint(p.sum(weight(u,v)*outgoing(u,v,orientation[min(u,v),max(u,v)]) for v in self.neighbors(u))-degree['max'], max=0)\n\n p.set_objective(degree['max'])\n\n p.solve(log=verbose)\n\n orientation = p.get_values(orientation)\n\n # All the edges from self are doubled in O\n # ( one in each direction )\n from sage.graphs.digraph import DiGraph\n O = DiGraph(self)\n\n # Builds the list of edges that should be removed\n edges=[]\n\n for u,v in self.edge_iterator(labels=None):\n # assumes u<v\n if u>v:\n u,v=v,u\n\n if orientation[min(u,v),max(u,v)] == 1:\n edges.append((max(u,v),min(u,v)))\n else:\n edges.append((min(u,v),max(u,v)))\n\n O.delete_edges(edges)\n\n return O\n\n @doc_index(\"Connectivity, orientations, trees\")\n def bounded_outdegree_orientation(self, bound):\n r\"\"\"\n Computes an orientation of ``self`` such that every vertex `v`\n has out-degree less than `b(v)`\n\n INPUT:\n\n - ``bound`` -- Maximum bound on the out-degree. Can be of\n three different types :\n\n * An integer `k`. In this case, computes an orientation\n whose maximum out-degree is less than `k`.\n\n * A dictionary associating to each vertex its associated\n maximum out-degree.\n\n * A function associating to each vertex its associated\n maximum out-degree.\n\n OUTPUT:\n\n A DiGraph representing the orientation if it exists. A\n ``ValueError`` exception is raised otherwise.\n\n ALGORITHM:\n\n The problem is solved through a maximum flow :\n\n Given a graph `G`, we create a ``DiGraph`` `D` defined on\n `E(G)\\cup V(G)\\cup \\{s,t\\}`. We then link `s` to all of `V(G)`\n (these edges having a capacity equal to the bound associated\n to each element of `V(G)`), and all the elements of `E(G)` to\n `t` . We then link each `v \\in V(G)` to each of its incident\n edges in `G`. A maximum integer flow of value `|E(G)|`\n corresponds to an admissible orientation of `G`. Otherwise,\n none exists.\n\n EXAMPLES:\n\n There is always an orientation of a graph `G` such that a\n vertex `v` has out-degree at most `\\lceil \\frac {d(v)} 2\n \\rceil`::\n\n sage: g = graphs.RandomGNP(40, .4)\n sage: b = lambda v : ceil(g.degree(v)/2)\n sage: D = g.bounded_outdegree_orientation(b)\n sage: all( D.out_degree(v) <= b(v) for v in g )\n True\n\n\n Chvatal's graph, being 4-regular, can be oriented in such a\n way that its maximum out-degree is 2::\n\n sage: g = graphs.ChvatalGraph()\n sage: D = g.bounded_outdegree_orientation(2)\n sage: max(D.out_degree())\n 2\n\n For any graph `G`, it is possible to compute an orientation\n such that the maximum out-degree is at most the maximum\n average degree of `G` divided by 2. Anything less, though, is\n impossible.\n\n sage: g = graphs.RandomGNP(40, .4)\n sage: mad = g.maximum_average_degree()\n\n Hence this is possible ::\n\n sage: d = g.bounded_outdegree_orientation(ceil(mad/2))\n\n While this is not::\n\n sage: try:\n ... g.bounded_outdegree_orientation(ceil(mad/2-1))\n ... print(\"Error\")\n ... except ValueError:\n ... pass\n\n TESTS:\n\n As previously for random graphs, but more intensively::\n\n sage: for i in range(30): # long time (up to 6s on sage.math, 2012)\n ... g = graphs.RandomGNP(40, .4)\n ... b = lambda v : ceil(g.degree(v)/2)\n ... D = g.bounded_outdegree_orientation(b)\n ... if not (\n ... all( D.out_degree(v) <= b(v) for v in g ) or\n ... D.size() != g.size()):\n ... print(\"Something wrong happened\")\n\n \"\"\"\n self._scream_if_not_simple()\n from sage.graphs.all import DiGraph\n n = self.order()\n\n if n == 0:\n return DiGraph()\n\n vertices = self.vertices()\n vertices_id = dict((y, x) for x,y in enumerate(vertices))\n\n b = {}\n\n\n # Checking the input type. We make a dictionary out of it\n if isinstance(bound, dict):\n b = bound\n else:\n try:\n b = dict(zip(vertices,map(bound, vertices)))\n\n except TypeError:\n b = dict(zip(vertices, [bound]*n))\n\n d = DiGraph()\n\n # Adding the edges (s,v) and ((u,v),t)\n d.add_edges( ('s', vertices_id[v], b[v]) for v in vertices)\n\n d.add_edges( ((vertices_id[u], vertices_id[v]), 't', 1)\n for (u,v) in self.edges(labels=None) )\n\n # each v is linked to its incident edges\n\n for u,v in self.edges(labels = None):\n u,v = vertices_id[u], vertices_id[v]\n d.add_edge(u, (u,v), 1)\n d.add_edge(v, (u,v), 1)\n\n # Solving the maximum flow\n value, flow = d.flow('s','t', value_only = False, integer = True, use_edge_labels = True)\n\n if value != self.size():\n raise ValueError(\"No orientation exists for the given bound\")\n\n D = DiGraph()\n D.add_vertices(vertices)\n\n # The flow graph may not contain all the vertices, if they are\n # not part of the flow...\n\n for u in [x for x in range(n) if x in flow]:\n\n for (uu,vv) in flow.neighbors_out(u):\n v = vv if vv != u else uu\n D.add_edge(vertices[u], vertices[v])\n\n # I do not like when a method destroys the embedding ;-)\n\n D.set_pos(self.get_pos())\n\n return D\n\n @doc_index(\"Connectivity, orientations, trees\")\n def orientations(self, implementation='c_graph', data_structure=None, sparse=None):\n r\"\"\"\n Return an iterator over orientations of ``self``.\n\n An *orientation* of an undirected graph is a directed\n graph such that every edge is assigned a direction.\n Hence there are `2^s` oriented digraphs for a simple\n graph with `s` edges.\n\n INPUT:\n\n - ``data_structure`` -- one of ``\"sparse\"``, ``\"static_sparse\"``, or\n ``\"dense\"``; see the documentation of :class:`Graph` or\n :class:`DiGraph`; default is the data structure of ``self``\n\n - ``sparse`` -- (optional) boolean; ``sparse=True`` is an alias for\n ``data_structure=\"sparse\"``, and ``sparse=False`` is an alias for\n ``data_structure=\"dense\"``\n\n .. WARNING::\n\n This always considers mutliple edges of graphs as\n distinguishable, and hence, may have repeated digraphs.\n\n EXAMPLES::\n\n sage: G = Graph([[1,2,3], [(1, 2, 'a'), (1, 3, 'b')]], format='vertices_and_edges')\n sage: it = G.orientations()\n sage: D = next(it)\n sage: D.edges()\n [(1, 2, 'a'), (1, 3, 'b')]\n sage: D = next(it)\n sage: D.edges()\n [(1, 2, 'a'), (3, 1, 'b')]\n\n TESTS::\n\n sage: G = Graph()\n sage: D = [g for g in G.orientations()]\n sage: len(D)\n 1\n sage: D[0]\n Digraph on 0 vertices\n\n sage: G = Graph(5)\n sage: it = G.orientations()\n sage: D = next(it)\n sage: D.size()\n 0\n\n sage: G = Graph([[1,2,'a'], [1,2,'b']], multiedges=True)\n sage: len(list(G.orientations()))\n 4\n\n sage: G = Graph([[1,2], [1,1]], loops=True)\n sage: len(list(G.orientations()))\n 2\n\n sage: G = Graph([[1,2],[2,3]])\n sage: next(G.orientations())\n Digraph on 3 vertices\n sage: G = graphs.PetersenGraph()\n sage: next(G.orientations())\n An orientation of Petersen graph: Digraph on 10 vertices\n \"\"\"\n if sparse is not None:\n if data_structure is not None:\n raise ValueError(\"cannot specify both 'sparse' and 'data_structure'\")\n data_structure = \"sparse\" if sparse else \"dense\"\n if data_structure is None:\n from sage.graphs.base.dense_graph import DenseGraphBackend\n from sage.graphs.base.sparse_graph import SparseGraphBackend\n if isinstance(self._backend, DenseGraphBackend):\n data_structure = \"dense\"\n elif isinstance(self._backend, SparseGraphBackend):\n data_structure = \"sparse\"\n else:\n data_structure = \"static_sparse\"\n\n name = self.name()\n if name != '':\n name = 'An orientation of ' + name\n\n if self.num_edges() == 0:\n D = DiGraph(name=name,\n pos=self._pos,\n multiedges=self.allows_multiple_edges(),\n loops=self.allows_loops(),\n implementation=implementation,\n data_structure=data_structure)\n if hasattr(self, '_embedding'):\n D._embedding = copy(self._embedding)\n yield D\n return\n\n from itertools import product\n E = [[(u,v,label), (v,u,label)] if u != v else [(u,v,label)]\n for u,v,label in self.edges()]\n verts = self.vertices()\n for edges in product(*E):\n D = DiGraph(data=[verts, edges],\n format='vertices_and_edges',\n name=name,\n pos=self._pos,\n multiedges=self.allows_multiple_edges(),\n loops=self.allows_loops(),\n implementation=implementation,\n data_structure=data_structure)\n if hasattr(self, '_embedding'):\n D._embedding = copy(self._embedding)\n yield D\n\n ### Coloring\n\n @doc_index(\"Basic methods\")\n def bipartite_color(self):\n \"\"\"\n Returns a dictionary with vertices as the keys and the color class\n as the values. Fails with an error if the graph is not bipartite.\n\n EXAMPLES::\n\n sage: graphs.CycleGraph(4).bipartite_color()\n {0: 1, 1: 0, 2: 1, 3: 0}\n sage: graphs.CycleGraph(5).bipartite_color()\n Traceback (most recent call last):\n ...\n RuntimeError: Graph is not bipartite.\n \"\"\"\n isit, certificate = self.is_bipartite(certificate = True)\n\n if isit:\n return certificate\n else:\n raise RuntimeError(\"Graph is not bipartite.\")\n\n @doc_index(\"Basic methods\")\n def bipartite_sets(self):\n \"\"\"\n Returns `(X,Y)` where `X` and `Y` are the nodes in each bipartite set of\n graph `G`. Fails with an error if graph is not bipartite.\n\n EXAMPLES::\n\n sage: graphs.CycleGraph(4).bipartite_sets()\n ({0, 2}, {1, 3})\n sage: graphs.CycleGraph(5).bipartite_sets()\n Traceback (most recent call last):\n ...\n RuntimeError: Graph is not bipartite.\n \"\"\"\n color = self.bipartite_color()\n left = set([])\n right = set([])\n\n for u,s in color.iteritems():\n if s:\n left.add(u)\n else:\n right.add(u)\n\n return left, right\n\n @doc_index(\"Algorithmically hard stuff\")\n def chromatic_number(self, algorithm=\"DLX\", verbose = 0):\n r\"\"\"\n Returns the minimal number of colors needed to color the vertices\n of the graph `G`.\n\n INPUT:\n\n - ``algorithm`` -- Select an algorithm from the following supported\n algorithms:\n\n - If ``algorithm=\"DLX\"`` (default), the chromatic number is\n computed using the dancing link algorithm. It is\n inefficient speedwise to compute the chromatic number through\n the dancing link algorithm because this algorithm computes\n *all* the possible colorings to check that one exists.\n\n - If ``algorithm=\"CP\"``, the chromatic number is computed\n using the coefficients of the chromatic polynomial. Again, this\n method is inefficient in terms of speed and it only useful for\n small graphs.\n\n - If ``algorithm=\"MILP\"``, the chromatic number is computed using a\n mixed integer linear program. The performance of this implementation\n is affected by whether optional MILP solvers have been installed\n (see the :mod:`MILP module <sage.numerical.mip>`, or Sage's tutorial\n on Linear Programming).\n\n - ``verbose`` -- integer (default: ``0``). Sets the level of verbosity\n for the MILP algorithm. Its default value is 0, which means *quiet*.\n\n .. SEEALSO::\n\n For more functions related to graph coloring, see the\n module :mod:`sage.graphs.graph_coloring`.\n\n EXAMPLES::\n\n sage: G = Graph({0: [1, 2, 3], 1: [2]})\n sage: G.chromatic_number(algorithm=\"DLX\")\n 3\n sage: G.chromatic_number(algorithm=\"MILP\")\n 3\n sage: G.chromatic_number(algorithm=\"CP\")\n 3\n\n A bipartite graph has (by definition) chromatic number 2::\n\n sage: graphs.RandomBipartite(50,50,0.7).chromatic_number()\n 2\n\n A complete multipartite graph with k parts has chromatic number k::\n\n sage: all(graphs.CompleteMultipartiteGraph([5]*i).chromatic_number() == i for i in range(2,5))\n True\n\n The complete graph has the largest chromatic number from all the graphs\n of order n. Namely its chromatic number is n::\n\n sage: all(graphs.CompleteGraph(i).chromatic_number() == i for i in range(10))\n True\n\n The Kneser graph with parameters (n,2) for n > 3 has chromatic number n-2::\n\n sage: all(graphs.KneserGraph(i,2).chromatic_number() == i-2 for i in range(4,6))\n True\n\n A snark has chromatic index 4 hence its line graph has chromatic number 4::\n\n sage: graphs.FlowerSnark().line_graph().chromatic_number()\n 4\n\n TESTS::\n\n sage: G = Graph({0: [1, 2, 3], 1: [2]})\n sage: G.chromatic_number(algorithm=\"foo\")\n Traceback (most recent call last):\n ...\n ValueError: The 'algorithm' keyword must be set to either 'DLX', 'MILP' or 'CP'.\n \"\"\"\n self._scream_if_not_simple(allow_multiple_edges=True)\n # default built-in algorithm; bad performance\n if algorithm == \"DLX\":\n from sage.graphs.graph_coloring import chromatic_number\n return chromatic_number(self)\n # Algorithm with good performance, but requires an optional\n # package: choose any of GLPK or CBC.\n elif algorithm == \"MILP\":\n from sage.graphs.graph_coloring import vertex_coloring\n return vertex_coloring(self, value_only=True, verbose = verbose)\n # another algorithm with bad performance; only good for small graphs\n elif algorithm == \"CP\":\n f = self.chromatic_polynomial()\n i = 0\n while f(i) == 0:\n i += 1\n return i\n else:\n raise ValueError(\"The 'algorithm' keyword must be set to either 'DLX', 'MILP' or 'CP'.\")\n\n @doc_index(\"Algorithmically hard stuff\")\n def coloring(self, algorithm=\"DLX\", hex_colors=False, verbose = 0):\n r\"\"\"\n Returns the first (optimal) proper vertex-coloring found.\n\n INPUT:\n\n - ``algorithm`` -- Select an algorithm from the following supported\n algorithms:\n\n - If ``algorithm=\"DLX\"`` (default), the coloring is computed using the\n dancing link algorithm.\n\n - If ``algorithm=\"MILP\"``, the coloring is computed using a mixed\n integer linear program. The performance of this implementation is\n affected by whether optional MILP solvers have been installed (see\n the :mod:`MILP module <sage.numerical.mip>`).\n\n - ``hex_colors`` -- (default: ``False``) if ``True``, return a\n dictionary which can easily be used for plotting.\n\n - ``verbose`` -- integer (default: ``0``). Sets the level of verbosity\n for the MILP algorithm. Its default value is 0, which means *quiet*.\n\n .. SEEALSO::\n\n For more functions related to graph coloring, see the\n module :mod:`sage.graphs.graph_coloring`.\n\n EXAMPLES::\n\n sage: G = Graph(\"Fooba\")\n sage: P = G.coloring(algorithm=\"MILP\"); P\n [[2, 1, 3], [0, 6, 5], [4]]\n sage: P = G.coloring(algorithm=\"DLX\"); P\n [[1, 2, 3], [0, 5, 6], [4]]\n sage: G.plot(partition=P)\n Graphics object consisting of 16 graphics primitives\n sage: H = G.coloring(hex_colors=True, algorithm=\"MILP\")\n sage: for c in sorted(H.keys()):\n ....: print(\"{} {}\".format(c, H[c]))\n #0000ff [4]\n #00ff00 [0, 6, 5]\n #ff0000 [2, 1, 3]\n sage: H = G.coloring(hex_colors=True, algorithm=\"DLX\")\n sage: for c in sorted(H.keys()):\n ....: print(\"{} {}\".format(c, H[c]))\n #0000ff [4]\n #00ff00 [1, 2, 3]\n #ff0000 [0, 5, 6]\n sage: G.plot(vertex_colors=H)\n Graphics object consisting of 16 graphics primitives\n\n .. PLOT::\n\n g = Graph(\"Fooba\")\n sphinx_plot(g.plot(partition=g.coloring()))\n\n TESTS::\n\n sage: G.coloring(algorithm=\"foo\")\n Traceback (most recent call last):\n ...\n ValueError: The 'algorithm' keyword must be set to either 'DLX' or 'MILP'.\n \"\"\"\n self._scream_if_not_simple(allow_multiple_edges=True)\n if algorithm == \"MILP\":\n from sage.graphs.graph_coloring import vertex_coloring\n return vertex_coloring(self, hex_colors=hex_colors, verbose = verbose)\n elif algorithm == \"DLX\":\n from sage.graphs.graph_coloring import first_coloring\n return first_coloring(self, hex_colors=hex_colors)\n else:\n raise ValueError(\"The 'algorithm' keyword must be set to either 'DLX' or 'MILP'.\")\n\n @doc_index(\"Algorithmically hard stuff\")\n def chromatic_symmetric_function(self, R=None):\n r\"\"\"\n Return the chromatic symmetric function of ``self``.\n\n Let `G` be a graph. The chromatic symmetric function `X_G` was\n described in [Stanley95]_, specifically Theorem 2.5 states that\n\n .. MATH::\n\n X_G = \\sum_{F \\subseteq E(G)} (-1)^{|F|} p_{\\lambda(F)},\n\n where `\\lambda(F)` is the partition of the sizes of the connected\n components of the subgraph induced by the edges `F` and `p_{\\mu}`\n is the powersum symmetric function.\n\n INPUT:\n\n - ``R`` -- (optional) the base ring for the symmetric functions;\n this uses `\\ZZ` by default\n\n EXAMPLES::\n\n sage: s = SymmetricFunctions(ZZ).s()\n sage: G = graphs.CycleGraph(5)\n sage: XG = G.chromatic_symmetric_function(); XG\n p[1, 1, 1, 1, 1] - 5*p[2, 1, 1, 1] + 5*p[2, 2, 1]\n + 5*p[3, 1, 1] - 5*p[3, 2] - 5*p[4, 1] + 4*p[5]\n sage: s(XG)\n 30*s[1, 1, 1, 1, 1] + 10*s[2, 1, 1, 1] + 10*s[2, 2, 1]\n\n Not all graphs have a positive Schur expansion::\n\n sage: G = graphs.ClawGraph()\n sage: XG = G.chromatic_symmetric_function(); XG\n p[1, 1, 1, 1] - 3*p[2, 1, 1] + 3*p[3, 1] - p[4]\n sage: s(XG)\n 8*s[1, 1, 1, 1] + 5*s[2, 1, 1] - s[2, 2] + s[3, 1]\n\n We show that given a triangle `\\{e_1, e_2, e_3\\}`, we have\n `X_G = X_{G - e_1} + X_{G - e_2} - X_{G - e_1 - e_2}`::\n\n sage: G = Graph([[1,2],[1,3],[2,3]])\n sage: XG = G.chromatic_symmetric_function()\n sage: G1 = copy(G)\n sage: G1.delete_edge([1,2])\n sage: XG1 = G1.chromatic_symmetric_function()\n sage: G2 = copy(G)\n sage: G2.delete_edge([1,3])\n sage: XG2 = G2.chromatic_symmetric_function()\n sage: G3 = copy(G1)\n sage: G3.delete_edge([1,3])\n sage: XG3 = G3.chromatic_symmetric_function()\n sage: XG == XG1 + XG2 - XG3\n True\n\n REFERENCES:\n\n .. [Stanley95] \\R. P. Stanley, *A symmetric function generalization\n of the chromatic polynomial of a graph*, Adv. Math., ***111***\n no.1 (1995), 166-194.\n \"\"\"\n from sage.combinat.sf.sf import SymmetricFunctions\n from sage.combinat.partition import _Partitions\n from sage.misc.misc import powerset\n if R is None:\n R = ZZ\n p = SymmetricFunctions(R).p()\n ret = p.zero()\n for F in powerset(self.edges()):\n la = _Partitions(self.subgraph(edges=F).connected_components_sizes())\n ret += (-1)**len(F) * p[la]\n return ret\n\n @doc_index(\"Algorithmically hard stuff\")\n def chromatic_quasisymmetric_function(self, t=None, R=None):\n r\"\"\"\n Return the chromatic quasisymmetric function of ``self``.\n\n Let `G` be a graph whose vertex set is totally ordered. The\n chromatic quasisymmetric function `X_G(t)` was first\n described in [SW12]_. We use the equivalent definition\n given in [BC15]_:\n\n .. MATH::\n\n X_G(t) = \\sum_{\\sigma=(\\sigma_1,\\ldots,\\sigma_n)}\n t^{\\operatorname{asc}(\\sigma)}\n M_{|\\sigma_1|,\\ldots,|\\sigma_n|},\n\n where we sum over all ordered set partitions of the vertex\n set of `G` such that each block `\\sigma_i` is an independent\n (i.e., stable) set of `G`, and where\n `\\operatorname{asc}(\\sigma)` denotes the number of edges\n `\\{u, v\\}` of `G` such that `u < v` and `v` appears in a\n later part of `\\sigma` than `u`.\n\n INPUT:\n\n - ``t`` -- (optional) the parameter `t`; uses the variable `t`\n in `\\ZZ[t]` by default\n - ``R`` -- (optional) the base ring for the quasisymmetric\n functions; uses the parent of `t` by default\n\n EXAMPLES::\n\n sage: G = Graph([[1,2,3], [[1,3], [2,3]]])\n sage: G.chromatic_quasisymmetric_function()\n (2*t^2+2*t+2)*M[1, 1, 1] + M[1, 2] + t^2*M[2, 1]\n sage: G = graphs.PathGraph(4)\n sage: XG = G.chromatic_quasisymmetric_function(); XG\n (t^3+11*t^2+11*t+1)*M[1, 1, 1, 1] + (3*t^2+3*t)*M[1, 1, 2]\n + (3*t^2+3*t)*M[1, 2, 1] + (3*t^2+3*t)*M[2, 1, 1]\n + (t^2+t)*M[2, 2]\n sage: XG.to_symmetric_function()\n (t^3+11*t^2+11*t+1)*m[1, 1, 1, 1] + (3*t^2+3*t)*m[2, 1, 1]\n + (t^2+t)*m[2, 2]\n sage: G = graphs.CompleteGraph(4)\n sage: G.chromatic_quasisymmetric_function()\n (t^6+3*t^5+5*t^4+6*t^3+5*t^2+3*t+1)*M[1, 1, 1, 1]\n\n Not all chromatic quasisymmetric functions are symmetric::\n\n sage: G = Graph([[1,2], [1,5], [3,4], [3,5]])\n sage: G.chromatic_quasisymmetric_function().is_symmetric()\n False\n\n We check that at `t = 1`, we recover the usual chromatic\n symmetric function::\n\n sage: p = SymmetricFunctions(QQ).p()\n sage: G = graphs.CycleGraph(5)\n sage: XG = G.chromatic_quasisymmetric_function(t=1); XG\n 120*M[1, 1, 1, 1, 1] + 30*M[1, 1, 1, 2] + 30*M[1, 1, 2, 1]\n + 30*M[1, 2, 1, 1] + 10*M[1, 2, 2] + 30*M[2, 1, 1, 1]\n + 10*M[2, 1, 2] + 10*M[2, 2, 1]\n sage: p(XG.to_symmetric_function())\n p[1, 1, 1, 1, 1] - 5*p[2, 1, 1, 1] + 5*p[2, 2, 1]\n + 5*p[3, 1, 1] - 5*p[3, 2] - 5*p[4, 1] + 4*p[5]\n\n sage: G = graphs.ClawGraph()\n sage: XG = G.chromatic_quasisymmetric_function(t=1); XG\n 24*M[1, 1, 1, 1] + 6*M[1, 1, 2] + 6*M[1, 2, 1] + M[1, 3]\n + 6*M[2, 1, 1] + M[3, 1]\n sage: p(XG.to_symmetric_function())\n p[1, 1, 1, 1] - 3*p[2, 1, 1] + 3*p[3, 1] - p[4]\n\n REFERENCES:\n\n .. [SW12] John Shareshian and Michelle Wachs.\n *Chromatic quasisymmetric functions and Hessenberg varieties*.\n Configuration Spaces. CRM Series. Scuola Normale Superiore.\n (2012) pp. 433-460.\n http://www.math.miami.edu/~wachs/papers/chrom.pdf\n\n .. [BC15] Patrick Brosnan and Timothy Y. Chow.\n *Unit interval orders and the dot action on the cohomology\n of regular semisimple Hessenberg varieties*.\n (2015) :arxiv:`1511.00773v1`.\n \"\"\"\n from sage.combinat.ncsf_qsym.qsym import QuasiSymmetricFunctions\n from sage.combinat.composition import Compositions\n from sage.combinat.set_partition_ordered import OrderedSetPartitions\n if t is None:\n t = ZZ['t'].gen()\n if R is None:\n R = t.parent()\n M = QuasiSymmetricFunctions(R).M()\n ret = M.zero()\n V = self.vertices()\n def asc(sigma):\n stat = 0\n for i, s in enumerate(sigma):\n for u in s:\n stat += sum(1 for p in sigma[i+1:] for v in p\n if v > u and self.has_edge(u, v))\n return stat\n for sigma in OrderedSetPartitions(V):\n if any(not self.is_independent_set(s) for s in sigma):\n continue\n ret += M.term(sigma.to_composition(), t**asc(sigma))\n return ret\n\n @doc_index(\"Leftovers\")\n def matching(self, value_only=False, algorithm=\"Edmonds\", use_edge_labels=True, solver=None, verbose=0):\n r\"\"\"\n Returns a maximum weighted matching of the graph\n represented by the list of its edges. For more information, see the\n `Wikipedia article on matchings\n <http://en.wikipedia.org/wiki/Matching_%28graph_theory%29>`_.\n\n Given a graph `G` such that each edge `e` has a weight `w_e`,\n a maximum matching is a subset `S` of the edges of `G` of\n maximum weight such that no two edges of `S` are incident\n with each other.\n\n As an optimization problem, it can be expressed as:\n\n .. math::\n\n \\mbox{Maximize : }&\\sum_{e\\in G.edges()} w_e b_e\\\\\n \\mbox{Such that : }&\\forall v \\in G, \\sum_{(u,v)\\in G.edges()} b_{(u,v)}\\leq 1\\\\\n &\\forall x\\in G, b_x\\mbox{ is a binary variable}\n\n INPUT:\n\n - ``value_only`` -- boolean (default: ``False``). When set to\n ``True``, only the cardinal (or the weight) of the matching is\n returned.\n\n - ``algorithm`` -- string (default: ``\"Edmonds\"``)\n\n - ``\"Edmonds\"`` selects Edmonds' algorithm as implemented in NetworkX\n\n - ``\"LP\"`` uses a Linear Program formulation of the matching problem\n\n - ``use_edge_labels`` -- boolean (default: ``False``)\n\n - When set to ``True``, computes a weighted matching where each edge\n is weighted by its label. (If an edge has no label, `1` is assumed.)\n\n - When set to ``False``, each edge has weight `1`.\n\n - ``solver`` -- (default: ``None``) Specify a Linear Program (LP)\n solver to be used. If set to ``None``, the default one is used. For\n more information on LP solvers and which default solver is used, see\n the method\n :meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>`\n of the class\n :class:`MixedIntegerLinearProgram <sage.numerical.mip.MixedIntegerLinearProgram>`.\n\n - ``verbose`` -- integer (default: ``0``). Sets the level of\n verbosity. Set to 0 by default, which means quiet.\n Only useful when ``algorithm == \"LP\"``.\n\n ALGORITHM:\n\n The problem is solved using Edmond's algorithm implemented in\n NetworkX, or using Linear Programming depending on the value of\n ``algorithm``.\n\n EXAMPLES:\n\n Maximum matching in a Pappus Graph::\n\n sage: g = graphs.PappusGraph()\n sage: g.matching(value_only=True)\n 9.0\n\n Same test with the Linear Program formulation::\n\n sage: g = graphs.PappusGraph()\n sage: g.matching(algorithm=\"LP\", value_only=True)\n 9.0\n\n .. PLOT::\n\n g = graphs.PappusGraph()\n sphinx_plot(g.plot(edge_colors={\"red\":g.matching()}))\n\n TESTS:\n\n If ``algorithm`` is set to anything different from ``\"Edmonds\"`` or\n ``\"LP\"``, an exception is raised::\n\n sage: g = graphs.PappusGraph()\n sage: g.matching(algorithm=\"somethingdifferent\")\n Traceback (most recent call last):\n ...\n ValueError: algorithm must be set to either \"Edmonds\" or \"LP\"\n \"\"\"\n self._scream_if_not_simple(allow_loops=True)\n from sage.rings.real_mpfr import RR\n weight = lambda x: x if x in RR else 1\n\n if algorithm == \"Edmonds\":\n import networkx\n if use_edge_labels:\n g = networkx.Graph()\n for u, v, l in self.edges():\n g.add_edge(u, v, attr_dict={\"weight\": weight(l)})\n else:\n g = self.networkx_graph(copy=False)\n d = networkx.max_weight_matching(g)\n if value_only:\n if use_edge_labels:\n return sum(weight(self.edge_label(u, v))\n for u, v in d.iteritems()) * 0.5\n else:\n return Integer(len(d) // 2)\n else:\n return [(u, v, self.edge_label(u, v))\n for u, v in d.iteritems() if u < v]\n\n elif algorithm == \"LP\":\n from sage.numerical.mip import MixedIntegerLinearProgram\n g = self\n # returns the weight of an edge considering it may not be\n # weighted ...\n p = MixedIntegerLinearProgram(maximization=True, solver=solver)\n b = p.new_variable(binary = True)\n p.set_objective(\n p.sum(weight(w) * b[min(u, v),max(u, v)]\n for u, v, w in g.edges()))\n # for any vertex v, there is at most one edge incident to v in\n # the maximum matching\n for v in g.vertex_iterator():\n p.add_constraint(\n p.sum(b[min(u, v),max(u, v)]\n for u in g.neighbors(v)), max=1)\n if value_only:\n if use_edge_labels:\n return p.solve(objective_only=True, log=verbose)\n else:\n return Integer(round(p.solve(objective_only=True, log=verbose)))\n else:\n p.solve(log=verbose)\n b = p.get_values(b)\n return [(u, v, w) for u, v, w in g.edges()\n if b[min(u, v),max(u, v)] == 1]\n\n else:\n raise ValueError('algorithm must be set to either \"Edmonds\" or \"LP\"')\n\n @doc_index(\"Algorithmically hard stuff\")\n def has_homomorphism_to(self, H, core = False, solver = None, verbose = 0):\n r\"\"\"\n Checks whether there is a homomorphism between two graphs.\n\n A homomorphism from a graph `G` to a graph `H` is a function\n `\\phi:V(G)\\mapsto V(H)` such that for any edge `uv \\in E(G)` the pair\n `\\phi(u)\\phi(v)` is an edge of `H`.\n\n Saying that a graph can be `k`-colored is equivalent to saying that it\n has a homomorphism to `K_k`, the complete graph on `k` elements.\n\n For more information, see the `Wikipedia article on graph homomorphisms\n <Graph_homomorphism>`_.\n\n INPUT:\n\n - ``H`` -- the graph to which ``self`` should be sent.\n\n - ``core`` (boolean) -- whether to minimize the size of the mapping's\n image (see note below). This is set to ``False`` by default.\n\n - ``solver`` -- (default: ``None``) Specify a Linear Program (LP)\n solver to be used. If set to ``None``, the default one is used. For\n more information on LP solvers and which default solver is used, see\n the method\n :meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>`\n of the class\n :class:`MixedIntegerLinearProgram <sage.numerical.mip.MixedIntegerLinearProgram>`.\n\n - ``verbose`` -- integer (default: ``0``). Sets the level of\n verbosity. Set to 0 by default, which means quiet.\n\n .. NOTE::\n\n One can compute the core of a graph (with respect to homomorphism)\n with this method ::\n\n sage: g = graphs.CycleGraph(10)\n sage: mapping = g.has_homomorphism_to(g, core = True)\n sage: print(\"The size of the core is {}\".format(len(set(mapping.values()))))\n The size of the core is 2\n\n OUTPUT:\n\n This method returns ``False`` when the homomorphism does not exist, and\n returns the homomorphism otherwise as a dictionary associating a vertex\n of `H` to a vertex of `G`.\n\n EXAMPLE:\n\n Is Petersen's graph 3-colorable::\n\n sage: P = graphs.PetersenGraph()\n sage: P.has_homomorphism_to(graphs.CompleteGraph(3)) is not False\n True\n\n An odd cycle admits a homomorphism to a smaller odd cycle, but not to an\n even cycle::\n\n sage: g = graphs.CycleGraph(9)\n sage: g.has_homomorphism_to(graphs.CycleGraph(5)) is not False\n True\n sage: g.has_homomorphism_to(graphs.CycleGraph(7)) is not False\n True\n sage: g.has_homomorphism_to(graphs.CycleGraph(4)) is not False\n False\n \"\"\"\n self._scream_if_not_simple()\n from sage.numerical.mip import MixedIntegerLinearProgram, MIPSolverException\n p = MixedIntegerLinearProgram(solver=solver, maximization = False)\n b = p.new_variable(binary = True)\n\n # Each vertex has an image\n for ug in self:\n p.add_constraint(p.sum(b[ug,uh] for uh in H) == 1)\n\n nonedges = H.complement().edges(labels = False)\n for ug,vg in self.edges(labels = False):\n # Two adjacent vertices cannot be mapped to the same element\n for uh in H:\n p.add_constraint(b[ug,uh] + b[vg,uh] <= 1)\n\n # Two adjacent vertices cannot be mapped to no adjacent vertices\n for uh,vh in nonedges:\n p.add_constraint(b[ug,uh] + b[vg,vh] <= 1)\n p.add_constraint(b[ug,vh] + b[vg,uh] <= 1)\n\n # Minimize the mapping's size\n if core:\n\n # the value of m is one if the corresponding vertex of h is used.\n m = p.new_variable(nonnegative=True)\n for uh in H:\n for ug in self:\n p.add_constraint(b[ug,uh] <= m[uh])\n\n p.set_objective(p.sum(m[vh] for vh in H))\n\n try:\n p.solve(log = verbose)\n b = p.get_values(b)\n mapping = dict(x[0] for x in b.items() if x[1])\n return mapping\n\n except MIPSolverException:\n return False\n\n @doc_index(\"Leftovers\")\n def fractional_chromatic_index(self, solver = None, verbose_constraints = 0, verbose = 0):\n r\"\"\"\n Computes the fractional chromatic index of ``self``\n\n The fractional chromatic index is a relaxed version of edge-coloring. An\n edge coloring of a graph being actually a covering of its edges into the\n smallest possible number of matchings, the fractional chromatic index of\n a graph `G` is the smallest real value `\\chi_f(G)` such that there\n exists a list of matchings `M_1, ..., M_k` of `G` and coefficients\n `\\alpha_1, ..., \\alpha_k` with the property that each edge is covered by\n the matchings in the following relaxed way\n\n .. MATH::\n\n \\forall e \\in E(G), \\sum_{e \\in M_i} \\alpha_i \\geq 1\n\n For more information, see the `Wikipedia article on fractional coloring\n <http://en.wikipedia.org/wiki/Fractional_coloring>`_.\n\n ALGORITHM:\n\n The fractional chromatic index is computed through Linear Programming\n through its dual. The LP solved by sage is actually:\n\n .. MATH::\n\n \\mbox{Maximize : }&\\sum_{e\\in E(G)} r_{e}\\\\\n \\mbox{Such that : }&\\\\\n &\\forall M\\text{ matching }\\subseteq G, \\sum_{e\\in M}r_{v}\\leq 1\\\\\n\n INPUT:\n\n - ``solver`` -- (default: ``None``) Specify a Linear Program (LP)\n solver to be used. If set to ``None``, the default one is used. For\n more information on LP solvers and which default solver is used, see\n the method\n :meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>`\n of the class\n :class:`MixedIntegerLinearProgram <sage.numerical.mip.MixedIntegerLinearProgram>`.\n\n .. NOTE::\n\n If you want exact results, i.e. a rational number, use\n ``solver=\"PPL\"``. This may be slower, though.\n\n - ``verbose_constraints`` -- whether to display which constraints are\n being generated.\n\n - ``verbose`` -- level of verbosity required from the LP solver\n\n .. NOTE::\n\n This implementation can be improved by computing matchings through a\n LP formulation, and not using the Python implementation of Edmonds'\n algorithm (which requires to copy the graph, etc). It may be more\n efficient to write the matching problem as a LP, as we would then\n just have to update the weights on the edges between each call to\n ``solve`` (and so avoiding the generation of all the constraints).\n\n EXAMPLE:\n\n The fractional chromatic index of a `C_5` is `5/2`::\n\n sage: g = graphs.CycleGraph(5)\n sage: g.fractional_chromatic_index()\n 2.5\n\n With PPL::\n\n sage: g.fractional_chromatic_index(solver=\"PPL\")\n 5/2\n \"\"\"\n self._scream_if_not_simple()\n from sage.numerical.mip import MixedIntegerLinearProgram\n\n g = copy(self)\n p = MixedIntegerLinearProgram(solver=solver, constraint_generation = True)\n\n # One variable per edge\n r = p.new_variable(nonnegative=True)\n R = lambda x,y : r[x,y] if x<y else r[y,x]\n\n # We want to maximize the sum of weights on the edges\n p.set_objective( p.sum( R(u,v) for u,v in g.edges(labels = False)))\n\n # Each edge being by itself a matching, its weight can not be more than\n # 1\n\n for u,v in g.edges(labels = False):\n p.add_constraint( R(u,v), max = 1)\n\n obj = p.solve(log = verbose)\n\n while True:\n\n # Updating the value on the edges of g\n for u,v in g.edges(labels = False):\n g.set_edge_label(u,v,p.get_values(R(u,v)))\n\n # Computing a matching of maximum weight...\n\n matching = g.matching()\n\n # If the maximum matching has weight at most 1, we are done !\n if sum((x[2] for x in matching)) <= 1:\n break\n\n # Otherwise, we add a new constraint\n\n if verbose_constraints:\n print(\"Adding a constraint on matching : {}\".format(matching))\n\n p.add_constraint( p.sum( R(u,v) for u,v,_ in matching), max = 1)\n\n # And solve again\n obj = p.solve(log = verbose)\n\n # Accomplished !\n return obj\n\n @doc_index(\"Leftovers\")\n def maximum_average_degree(self, value_only=True, solver = None, verbose = 0):\n r\"\"\"\n Returns the Maximum Average Degree (MAD) of the current graph.\n\n The Maximum Average Degree (MAD) of a graph is defined as\n the average degree of its densest subgraph. More formally,\n ``Mad(G) = \\max_{H\\subseteq G} Ad(H)``, where `Ad(G)` denotes\n the average degree of `G`.\n\n This can be computed in polynomial time.\n\n INPUT:\n\n - ``value_only`` (boolean) -- ``True`` by default\n\n - If ``value_only=True``, only the numerical\n value of the `MAD` is returned.\n\n - Else, the subgraph of `G` realizing the `MAD`\n is returned.\n\n - ``solver`` -- (default: ``None``) Specify a Linear Program (LP)\n solver to be used. If set to ``None``, the default one is used. For\n more information on LP solvers and which default solver is used, see\n the method\n :meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>`\n of the class\n :class:`MixedIntegerLinearProgram <sage.numerical.mip.MixedIntegerLinearProgram>`.\n\n - ``verbose`` -- integer (default: ``0``). Sets the level of\n verbosity. Set to 0 by default, which means quiet.\n\n EXAMPLES:\n\n In any graph, the `Mad` is always larger than the average\n degree::\n\n sage: g = graphs.RandomGNP(20,.3)\n sage: mad_g = g.maximum_average_degree()\n sage: g.average_degree() <= mad_g\n True\n\n Unlike the average degree, the `Mad` of the disjoint\n union of two graphs is the maximum of the `Mad` of each\n graphs::\n\n sage: h = graphs.RandomGNP(20,.3)\n sage: mad_h = h.maximum_average_degree()\n sage: (g+h).maximum_average_degree() == max(mad_g, mad_h)\n True\n\n The subgraph of a regular graph realizing the maximum\n average degree is always the whole graph ::\n\n sage: g = graphs.CompleteGraph(5)\n sage: mad_g = g.maximum_average_degree(value_only=False)\n sage: g.is_isomorphic(mad_g)\n True\n\n This also works for complete bipartite graphs ::\n\n sage: g = graphs.CompleteBipartiteGraph(3,4)\n sage: mad_g = g.maximum_average_degree(value_only=False)\n sage: g.is_isomorphic(mad_g)\n True\n \"\"\"\n self._scream_if_not_simple()\n g = self\n from sage.numerical.mip import MixedIntegerLinearProgram\n\n p = MixedIntegerLinearProgram(maximization=True, solver = solver)\n\n d = p.new_variable(nonnegative=True)\n one = p.new_variable(nonnegative=True)\n\n # Reorders u and v so that uv and vu are not considered\n # to be different edges\n reorder = lambda u,v : (min(u,v),max(u,v))\n\n for u,v in g.edge_iterator(labels=False):\n p.add_constraint( one[ reorder(u,v) ] - 2*d[u] , max = 0 )\n p.add_constraint( one[ reorder(u,v) ] - 2*d[v] , max = 0 )\n\n p.add_constraint( p.sum(d[v] for v in g), max = 1)\n\n p.set_objective( p.sum( one[reorder(u,v)] for u,v in g.edge_iterator(labels=False)) )\n\n obj = p.solve(log = verbose)\n\n # Paying attention to numerical error :\n # The zero values could be something like 0.000000000001\n # so I can not write l > 0\n # And the non-zero, though they should be equal to\n # 1/(order of the optimal subgraph) may be a bit lower\n\n # setting the minimum to 1/(10 * size of the whole graph )\n # should be safe :-)\n m = 1/(10 *Integer(g.order()))\n g_mad = g.subgraph([v for v,l in p.get_values(d).iteritems() if l>m ])\n\n if value_only:\n return g_mad.average_degree()\n else:\n return g_mad\n\n @doc_index(\"Algorithmically hard stuff\")\n def independent_set_of_representatives(self, family, solver=None, verbose=0):\n r\"\"\"\n Returns an independent set of representatives.\n\n Given a graph `G` and and a family `F=\\{F_i:i\\in [1,...,k]\\}` of\n subsets of ``g.vertices()``, an Independent Set of Representatives\n (ISR) is an assignation of a vertex `v_i\\in F_i` to each set `F_i`\n such that `v_i != v_j` if `i<j` (they are representatives) and the\n set `\\cup_{i}v_i` is an independent set in `G`.\n\n It generalizes, for example, graph coloring and graph list coloring.\n\n (See [AhaBerZiv07]_ for more information.)\n\n INPUT:\n\n - ``family`` -- A list of lists defining the family `F`\n (actually, a Family of subsets of ``G.vertices()``).\n\n - ``solver`` -- (default: ``None``) Specify a Linear Program (LP)\n solver to be used. If set to ``None``, the default one is used. For\n more information on LP solvers and which default solver is used, see\n the method\n :meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>`\n of the class\n :class:`MixedIntegerLinearProgram <sage.numerical.mip.MixedIntegerLinearProgram>`.\n\n - ``verbose`` -- integer (default: ``0``). Sets the level of\n verbosity. Set to 0 by default, which means quiet.\n\n OUTPUT:\n\n - A list whose `i^{\\mbox{th}}` element is the representative of the\n `i^{\\mbox{th}}` element of the ``family`` list. If there is no ISR,\n ``None`` is returned.\n\n EXAMPLES:\n\n For a bipartite graph missing one edge, the solution is as expected::\n\n sage: g = graphs.CompleteBipartiteGraph(3,3)\n sage: g.delete_edge(1,4)\n sage: g.independent_set_of_representatives([[0,1,2],[3,4,5]])\n [1, 4]\n\n The Petersen Graph is 3-colorable, which can be expressed as an\n independent set of representatives problem : take 3 disjoint copies\n of the Petersen Graph, each one representing one color. Then take\n as a partition of the set of vertices the family defined by the three\n copies of each vertex. The ISR of such a family\n defines a 3-coloring::\n\n sage: g = 3 * graphs.PetersenGraph()\n sage: n = g.order()/3\n sage: f = [[i,i+n,i+2*n] for i in range(n)]\n sage: isr = g.independent_set_of_representatives(f)\n sage: c = [floor(i/n) for i in isr]\n sage: color_classes = [[],[],[]]\n sage: for v,i in enumerate(c):\n ... color_classes[i].append(v)\n sage: for classs in color_classes:\n ... g.subgraph(classs).size() == 0\n True\n True\n True\n\n REFERENCE:\n\n .. [AhaBerZiv07] \\R. Aharoni and E. Berger and R. Ziv\n Independent systems of representatives in weighted graphs\n Combinatorica vol 27, num 3, p253--267\n 2007\n\n \"\"\"\n\n from sage.numerical.mip import MixedIntegerLinearProgram\n p=MixedIntegerLinearProgram(solver=solver)\n\n # Boolean variable indicating whether the vertex\n # is the representative of some set\n vertex_taken=p.new_variable(binary=True)\n\n # Boolean variable in two dimension whose first\n # element is a vertex and whose second element\n # is one of the sets given as arguments.\n # When true, indicated that the vertex is the representant\n # of the corresponding set\n\n classss=p.new_variable(binary = True)\n\n # Associates to the vertices the classes\n # to which they belong\n\n lists=dict([(v,[]) for v in self.vertex_iterator()])\n for i,f in enumerate(family):\n [lists[v].append(i) for v in f]\n\n # a classss has exactly one representant\n p.add_constraint(p.sum(classss[v,i] for v in f), max=1, min=1)\n\n # A vertex represents at most one classss (vertex_taken is binary), and\n # vertex_taken[v]==1 if v is the representative of some classss\n\n [p.add_constraint(p.sum(classss[v,i] for i in lists[v]) - vertex_taken[v], max=0) for v in self.vertex_iterator()]\n\n # Two adjacent vertices can not both be representants of a set\n\n for (u,v) in self.edges(labels=None):\n p.add_constraint(vertex_taken[u]+vertex_taken[v],max=1)\n\n p.set_objective(None)\n\n try:\n p.solve(log=verbose)\n except Exception:\n return None\n\n classss=p.get_values(classss)\n\n repr=[]\n for i,f in enumerate(family):\n for v in f:\n if classss[v,i]==1:\n repr.append(v)\n break\n\n return repr\n\n @doc_index(\"Algorithmically hard stuff\")\n def minor(self, H, solver=None, verbose=0):\n r\"\"\"\n Returns the vertices of a minor isomorphic to `H` in the current graph.\n\n We say that a graph `G` has a `H`-minor (or that it has\n a graph isomorphic to `H` as a minor), if for all `h\\in H`,\n there exist disjoint sets `S_h \\subseteq V(G)` such that\n once the vertices of each `S_h` have been merged to create\n a new graph `G'`, this new graph contains `H` as a subgraph.\n\n For more information, see the\n `Wikipedia article on graph minor <http://en.wikipedia.org/wiki/Minor_%28graph_theory%29>`_.\n\n INPUT:\n\n - ``H`` -- The minor to find for in the current graph.\n\n - ``solver`` -- (default: ``None``) Specify a Linear Program (LP)\n solver to be used. If set to ``None``, the default one is used. For\n more information on LP solvers and which default solver is used, see\n the method\n :meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>`\n of the class\n :class:`MixedIntegerLinearProgram <sage.numerical.mip.MixedIntegerLinearProgram>`.\n\n - ``verbose`` -- integer (default: ``0``). Sets the level of\n verbosity. Set to 0 by default, which means quiet.\n\n OUTPUT:\n\n A dictionary associating to each vertex of `H` the set of vertices\n in the current graph representing it.\n\n ALGORITHM:\n\n Mixed Integer Linear Programming\n\n COMPLEXITY:\n\n Theoretically, when `H` is fixed, testing for the existence of\n a `H`-minor is polynomial. The known algorithms are highly\n exponential in `H`, though.\n\n .. NOTE::\n\n This function can be expected to be *very* slow, especially\n where the minor does not exist.\n\n EXAMPLES:\n\n Trying to find a minor isomorphic to `K_4` in\n the `4\\times 4` grid::\n\n sage: g = graphs.GridGraph([4,4])\n sage: h = graphs.CompleteGraph(4)\n sage: L = g.minor(h)\n sage: gg = g.subgraph(flatten(L.values(), max_level = 1))\n sage: _ = [gg.merge_vertices(l) for l in L.values() if len(l)>1]\n sage: gg.is_isomorphic(h)\n True\n\n We can also try to prove this way that the Petersen graph\n is not planar, as it has a `K_5` minor::\n\n sage: g = graphs.PetersenGraph()\n sage: K5_minor = g.minor(graphs.CompleteGraph(5)) # long time\n\n And even a `K_{3,3}` minor::\n\n sage: K33_minor = g.minor(graphs.CompleteBipartiteGraph(3,3)) # long time\n\n (It is much faster to use the linear-time test of\n planarity in this situation, though.)\n\n As there is no cycle in a tree, looking for a `K_3` minor is useless.\n This function will raise an exception in this case::\n\n sage: g = graphs.RandomGNP(20,.5)\n sage: g = g.subgraph(edges = g.min_spanning_tree())\n sage: g.is_tree()\n True\n sage: L = g.minor(graphs.CompleteGraph(3))\n Traceback (most recent call last):\n ...\n ValueError: This graph has no minor isomorphic to H !\n \"\"\"\n self._scream_if_not_simple()\n H._scream_if_not_simple()\n from sage.numerical.mip import MixedIntegerLinearProgram, MIPSolverException\n p = MixedIntegerLinearProgram(solver=solver)\n\n # sorts an edge\n S = lambda x_y: x_y if x_y[0] < x_y[1] else (x_y[1], x_y[0])\n\n # rs = Representative set of a vertex\n # for h in H, v in G is such that rs[h,v] == 1 if and only if v\n # is a representant of h in self\n rs = p.new_variable(binary = True)\n\n for v in self:\n p.add_constraint(p.sum(rs[h,v] for h in H), max = 1)\n\n # We ensure that the set of representatives of a\n # vertex h contains a tree, and thus is connected\n\n # edges represents the edges of the tree\n edges = p.new_variable(binary = True)\n\n # there can be a edge for h between two vertices\n # only if those vertices represent h\n for u,v in self.edges(labels=None):\n for h in H:\n p.add_constraint(edges[h,S((u,v))] - rs[h,u], max = 0 )\n p.add_constraint(edges[h,S((u,v))] - rs[h,v], max = 0 )\n\n # The number of edges of the tree in h is exactly the cardinal\n # of its representative set minus 1\n\n for h in H:\n p.add_constraint(p.sum(edges[h,S(e)] for e in self.edges(labels=None))-p.sum(rs[h,v] for v in self), min=-1, max=-1)\n\n # a tree has no cycle\n epsilon = 1/(5*Integer(self.order()))\n r_edges = p.new_variable(nonnegative=True)\n\n for h in H:\n for u,v in self.edges(labels=None):\n p.add_constraint(r_edges[h,(u,v)] + r_edges[h,(v,u)] - edges[h,S((u,v))], min = 0)\n\n for v in self:\n p.add_constraint(p.sum(r_edges[h,(u,v)] for u in self.neighbors(v)), max = 1-epsilon)\n\n # Once the representative sets are described, we must ensure\n # there are arcs corresponding to those of H between them\n h_edges = p.new_variable(nonnegative=True)\n\n for h1, h2 in H.edges(labels=None):\n\n for v1, v2 in self.edges(labels=None):\n\n p.add_constraint(h_edges[(h1,h2),S((v1,v2))] - rs[h2,v2], max = 0)\n p.add_constraint(h_edges[(h1,h2),S((v1,v2))] - rs[h1,v1], max = 0)\n\n p.add_constraint(h_edges[(h2,h1),S((v1,v2))] - rs[h1,v2], max = 0)\n p.add_constraint(h_edges[(h2,h1),S((v1,v2))] - rs[h2,v1], max = 0)\n\n p.add_constraint(p.sum(h_edges[(h1,h2),S(e)] + h_edges[(h2,h1),S(e)] for e in self.edges(labels=None) ), min = 1)\n\n p.set_objective(None)\n\n try:\n p.solve(log=verbose)\n except MIPSolverException:\n raise ValueError(\"This graph has no minor isomorphic to H !\")\n\n rs = p.get_values(rs)\n\n rs_dict = {}\n for h in H:\n rs_dict[h] = [v for v in self if rs[h,v]==1]\n\n return rs_dict\n\n ### Convexity\n\n @doc_index(\"Algorithmically hard stuff\")\n def convexity_properties(self):\n r\"\"\"\n Returns a ``ConvexityProperties`` object corresponding to ``self``.\n\n This object contains the methods related to convexity in graphs (convex\n hull, hull number) and caches useful information so that it becomes\n comparatively cheaper to compute the convex hull of many different sets\n of the same graph.\n\n .. SEEALSO::\n\n In order to know what can be done through this object, please refer\n to module :mod:`sage.graphs.convexity_properties`.\n\n .. NOTE::\n\n If you want to compute many convex hulls, keep this object in memory\n ! When it is created, it builds a table of useful information to\n compute convex hulls. As a result ::\n\n sage: g = graphs.PetersenGraph()\n sage: g.convexity_properties().hull([1, 3])\n [1, 2, 3]\n sage: g.convexity_properties().hull([3, 7])\n [2, 3, 7]\n\n Is a terrible waste of computations, while ::\n\n sage: g = graphs.PetersenGraph()\n sage: CP = g.convexity_properties()\n sage: CP.hull([1, 3])\n [1, 2, 3]\n sage: CP.hull([3, 7])\n [2, 3, 7]\n\n Makes perfect sense.\n \"\"\"\n from sage.graphs.convexity_properties import ConvexityProperties\n return ConvexityProperties(self)\n\n # Centrality\n @doc_index(\"Distances\")\n def centrality_degree(self, v=None):\n r\"\"\"\n Returns the degree centrality of a vertex.\n\n The degree centrality of a vertex `v` is its degree, divided by\n `|V(G)|-1`. For more information, see the :wikipedia:`Centrality`.\n\n INPUT:\n\n - ``v`` - a vertex. Set to ``None`` (default) to get a dictionary\n associating each vertex with its centrality degree.\n\n .. SEEALSO::\n\n - :meth:`~sage.graphs.generic_graph.GenericGraph.centrality_closeness`\n - :meth:`~sage.graphs.generic_graph.GenericGraph.centrality_betweenness`\n\n EXAMPLES::\n\n sage: (graphs.ChvatalGraph()).centrality_degree()\n {0: 4/11, 1: 4/11, 2: 4/11, 3: 4/11, 4: 4/11, 5: 4/11,\n 6: 4/11, 7: 4/11, 8: 4/11, 9: 4/11, 10: 4/11, 11: 4/11}\n sage: D = graphs.DiamondGraph()\n sage: D.centrality_degree()\n {0: 2/3, 1: 1, 2: 1, 3: 2/3}\n sage: D.centrality_degree(v=1)\n 1\n\n TESTS::\n\n sage: Graph(1).centrality_degree()\n Traceback (most recent call last):\n ...\n ValueError: The centrality degree is not defined on graphs with only one vertex\n \"\"\"\n from sage.rings.integer import Integer\n n_minus_one = Integer(self.order()-1)\n if n_minus_one == 0:\n raise ValueError(\"The centrality degree is not defined \"\n \"on graphs with only one vertex\")\n if v is None:\n return {v:self.degree(v)/n_minus_one for v in self}\n else:\n return self.degree(v)/n_minus_one\n\n ### Constructors\n\n @doc_index(\"Basic methods\")\n def to_directed(self, implementation='c_graph', data_structure=None,\n sparse=None):\n \"\"\"\n Returns a directed version of the graph. A single edge becomes two\n edges, one in each direction.\n\n INPUT:\n\n - ``data_structure`` -- one of ``\"sparse\"``, ``\"static_sparse\"``, or\n ``\"dense\"``. See the documentation of :class:`Graph` or\n :class:`DiGraph`.\n\n - ``sparse`` (boolean) -- ``sparse=True`` is an alias for\n ``data_structure=\"sparse\"``, and ``sparse=False`` is an alias for\n ``data_structure=\"dense\"``.\n\n EXAMPLES::\n\n sage: graphs.PetersenGraph().to_directed()\n Petersen graph: Digraph on 10 vertices\n\n TESTS:\n\n Immutable graphs yield immutable graphs::\n\n sage: Graph([[1, 2]], immutable=True).to_directed()._backend\n <type 'sage.graphs.base.static_sparse_backend.StaticSparseBackend'>\n\n :trac:`17005`::\n\n sage: Graph([[1,2]], immutable=True).to_directed()\n Digraph on 2 vertices\n \"\"\"\n if sparse is not None:\n if data_structure is not None:\n raise ValueError(\"The 'sparse' argument is an alias for \"\n \"'data_structure'. Please do not define both.\")\n data_structure = \"sparse\" if sparse else \"dense\"\n\n if data_structure is None:\n from sage.graphs.base.dense_graph import DenseGraphBackend\n from sage.graphs.base.sparse_graph import SparseGraphBackend\n if isinstance(self._backend, DenseGraphBackend):\n data_structure = \"dense\"\n elif isinstance(self._backend, SparseGraphBackend):\n data_structure = \"sparse\"\n else:\n data_structure = \"static_sparse\"\n from sage.graphs.all import DiGraph\n D = DiGraph(name = self.name(),\n pos = self._pos,\n multiedges = self.allows_multiple_edges(),\n loops = self.allows_loops(),\n implementation = implementation,\n data_structure = (data_structure if data_structure!=\"static_sparse\"\n else \"sparse\")) # we need a mutable copy\n\n D.add_vertices(self.vertex_iterator())\n for u,v,l in self.edge_iterator():\n D.add_edge(u,v,l)\n D.add_edge(v,u,l)\n if hasattr(self, '_embedding'):\n D._embedding = copy(self._embedding)\n D._weighted = self._weighted\n\n if data_structure == \"static_sparse\":\n D = D.copy(data_structure=data_structure)\n\n return D\n\n @doc_index(\"Basic methods\")\n def to_undirected(self):\n \"\"\"\n Since the graph is already undirected, simply returns a copy of\n itself.\n\n EXAMPLES::\n\n sage: graphs.PetersenGraph().to_undirected()\n Petersen graph: Graph on 10 vertices\n \"\"\"\n return self.copy()\n\n @doc_index(\"Basic methods\")\n def join(self, other, verbose_relabel=None, labels=\"pairs\", immutable=None):\n \"\"\"\n Returns the join of ``self`` and ``other``.\n\n INPUT:\n\n - ``verbose_relabel`` - deprecated.\n\n - ``labels`` - (defaults to 'pairs') If set to 'pairs', each\n element ``v`` in the first graph will be named ``(0,v)`` and\n each element ``u`` in ``other`` will be named ``(1,u)`` in\n the result. If set to 'integers', the elements of the result\n will be relabeled with consecutive integers.\n\n - ``immutable`` (boolean) -- whether to create a mutable/immutable\n join. ``immutable=None`` (default) means that the graphs and their\n join will behave the same way.\n\n .. SEEALSO::\n\n * :meth:`~sage.graphs.generic_graph.GenericGraph.union`\n\n * :meth:`~sage.graphs.generic_graph.GenericGraph.disjoint_union`\n\n EXAMPLES::\n\n sage: G = graphs.CycleGraph(3)\n sage: H = Graph(2)\n sage: J = G.join(H); J\n Cycle graph join : Graph on 5 vertices\n sage: J.vertices()\n [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1)]\n sage: J = G.join(H, labels='integers'); J\n Cycle graph join : Graph on 5 vertices\n sage: J.vertices()\n [0, 1, 2, 3, 4]\n sage: J.edges()\n [(0, 1, None), (0, 2, None), (0, 3, None), (0, 4, None), (1, 2, None), (1, 3, None), (1, 4, None), (2, 3, None), (2, 4, None)]\n\n ::\n\n sage: G = Graph(3)\n sage: G.name(\"Graph on 3 vertices\")\n sage: H = Graph(2)\n sage: H.name(\"Graph on 2 vertices\")\n sage: J = G.join(H); J\n Graph on 3 vertices join Graph on 2 vertices: Graph on 5 vertices\n sage: J.vertices()\n [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1)]\n sage: J = G.join(H, labels='integers'); J\n Graph on 3 vertices join Graph on 2 vertices: Graph on 5 vertices\n sage: J.edges()\n [(0, 3, None), (0, 4, None), (1, 3, None), (1, 4, None), (2, 3, None), (2, 4, None)]\n \"\"\"\n if verbose_relabel is not None:\n deprecation(17053, \"Instead of verbose_relabel=True/False use labels='pairs'/'integers'.\")\n if verbose_relabel is True:\n labels=\"pairs\"\n if verbose_relabel is False:\n labels=\"integers\"\n\n G = self.disjoint_union(other, labels=labels, immutable=False)\n if labels==\"integers\":\n G.add_edges((u,v) for u in range(self.order())\n for v in range(self.order(), self.order()+other.order()))\n else:\n G.add_edges(((0,u), (1,v)) for u in self.vertices()\n for v in other.vertices())\n\n G.name('%s join %s'%(self.name(), other.name()))\n\n if immutable is None:\n immutable = self.is_immutable() and other.is_immutable()\n if immutable:\n G = G.copy(immutable=True)\n\n return G\n\n @doc_index(\"Leftovers\")\n def seidel_adjacency_matrix(self, vertices=None):\n r\"\"\"\n Returns the Seidel adjacency matrix of ``self``.\n\n Returns `J-I-2A`, for `A` the (ordinary) :meth:`adjacency\n matrix\n <sage.graphs.generic_graph.GenericGraph.adjacency_matrix>` of\n ``self``, `I` the identity matrix, and `J` the all-1 matrix.\n It is closely related to :meth:`twograph`.\n\n The matrix returned is over the integers. If a different ring is\n desired, use either :meth:`sage.matrix.matrix0.Matrix.change_ring`\n method or :class:`matrix <sage.matrix.constructor.MatrixFactory>` function.\n\n INPUT:\n\n - ``vertices`` (list) -- the ordering of the vertices defining\n how they should appear in the matrix. By default, the\n ordering given by\n :meth:`~sage.graphs.generic_graph.GenericGraph.vertices` is\n used.\n\n EXAMPLES::\n\n sage: G = graphs.CycleGraph(5)\n sage: G = G.disjoint_union(graphs.CompleteGraph(1))\n sage: G.seidel_adjacency_matrix().minpoly()\n x^2 - 5\n \"\"\"\n\n return -self.adjacency_matrix(sparse=False, vertices=vertices)+ \\\n self.complement().adjacency_matrix(sparse=False, \\\n vertices=vertices)\n\n @doc_index(\"Leftovers\")\n def seidel_switching(self, s, inplace=True):\n r\"\"\"\n Returns the Seidel switching of ``self`` w.r.t. subset of vertices ``s``.\n\n Returns the graph obtained by Seidel switching of ``self``\n with respect to the subset of vertices ``s``. This is the graph\n given by Seidel adjacency matrix `DSD`, for `S` the Seidel\n adjacency matrix of ``self``, and `D` the diagonal matrix with -1s\n at positions corresponding to ``s``, and 1s elsewhere.\n\n INPUT:\n\n - ``s`` -- a list of vertices of ``self``\n\n - ``inplace`` (boolean) -- whether to do the modification inplace, or to\n return a copy of the graph after switching.\n\n EXAMPLES::\n\n sage: G = graphs.CycleGraph(5)\n sage: G = G.disjoint_union(graphs.CompleteGraph(1))\n sage: G.seidel_switching([(0,1),(1,0),(0,0)])\n sage: G.seidel_adjacency_matrix().minpoly()\n x^2 - 5\n sage: G.is_connected()\n True\n\n TESTS::\n\n sage: H = G.seidel_switching([1,4,5],inplace=False)\n sage: G.seidel_switching([1,4,5])\n sage: G == H\n True\n \"\"\"\n from itertools import product\n G = self if inplace else copy(self)\n boundary = self.edge_boundary(s)\n G.add_edges(product(s, set(self).difference(s)))\n G.delete_edges(boundary)\n if not inplace:\n return G\n\n @doc_index(\"Leftovers\")\n def twograph(self):\n r\"\"\"\n Returns the two-graph of ``self``\n\n Returns the :class:`two-graph <sage.combinat.designs.twographs.TwoGraph>`\n with the triples\n `T=\\{t \\in \\binom {V}{3} : \\left| \\binom {t}{2} \\cap E \\right| \\text{odd} \\}`\n where `V` and `E` are vertices and edges of ``self``, respectively.\n\n EXAMPLES::\n\n sage: p=graphs.PetersenGraph()\n sage: p.twograph()\n Incidence structure with 10 points and 60 blocks\n sage: p=graphs.chang_graphs()\n sage: T8 = graphs.CompleteGraph(8).line_graph()\n sage: C = T8.seidel_switching([(0,1,None),(2,3,None),(4,5,None),(6,7,None)],inplace=False)\n sage: T8.twograph()==C.twograph()\n True\n sage: T8.is_isomorphic(C)\n False\n\n TESTS::\n\n sage: from sage.combinat.designs.twographs import TwoGraph\n sage: p=graphs.PetersenGraph().twograph()\n sage: TwoGraph(p, check=True)\n Incidence structure with 10 points and 60 blocks\n\n .. SEEALSO::\n\n - :meth:`~sage.combinat.designs.twographs.TwoGraph.descendant`\n -- computes the descendant graph of the two-graph of self at a vertex\n\n - :func:`~sage.combinat.designs.twographs.twograph_descendant`\n -- ditto, but much faster.\n \"\"\"\n from sage.combinat.designs.twographs import TwoGraph\n G = self.relabel(inplace=False)\n T = []\n\n # Triangles\n for x,y,z in G.subgraph_search_iterator(Graph({1:[2,3],2:[3]})):\n if x < y and y < z:\n T.append([x,y,z])\n\n # Triples with just one edge\n for x,y,z in G.subgraph_search_iterator(Graph({1:[2],3:[]}),induced=True):\n if x < y:\n T.append([x,y,z])\n\n T = TwoGraph(T)\n T.relabel({i:v for i,v in enumerate(self.vertices())})\n\n return T\n\n ### Visualization\n\n @doc_index(\"Basic methods\")\n def write_to_eps(self, filename, **options):\n r\"\"\"\n Writes a plot of the graph to ``filename`` in ``eps`` format.\n\n INPUT:\n\n - ``filename`` -- a string\n - ``**options`` -- same layout options as :meth:`.layout`\n\n EXAMPLES::\n\n sage: P = graphs.PetersenGraph()\n sage: P.write_to_eps(tmp_filename(ext='.eps'))\n\n It is relatively simple to include this file in a LaTeX\n document. ``\\usepackage{graphics}`` must appear in the\n preamble, and ``\\includegraphics{filename}`` will include\n the file. To compile the document to ``pdf`` with ``pdflatex`` or ``xelatex``\n the file needs first to be converted to ``pdf``, for example\n with ``ps2pdf filename.eps filename.pdf``.\n \"\"\"\n from sage.graphs.print_graphs import print_graph_eps\n pos = self.layout(**options)\n [xmin, xmax, ymin, ymax] = self._layout_bounding_box(pos)\n for v in pos:\n pos[v] = (1.8*(pos[v][0] - xmin)/(xmax - xmin) - 0.9, 1.8*(pos[v][1] - ymin)/(ymax - ymin) - 0.9)\n if filename[-4:] != '.eps':\n filename += '.eps'\n f = open(filename, 'w')\n f.write( print_graph_eps(self.vertices(), self.edge_iterator(), pos) )\n f.close()\n\n @doc_index(\"Algorithmically hard stuff\")\n def topological_minor(self, H, vertices = False, paths = False, solver=None, verbose=0):\n r\"\"\"\n Returns a topological `H`-minor from ``self`` if one exists.\n\n We say that a graph `G` has a topological `H`-minor (or that\n it has a graph isomorphic to `H` as a topological minor), if\n `G` contains a subdivision of a graph isomorphic to `H` (i.e.\n obtained from `H` through arbitrary subdivision of its edges)\n as a subgraph.\n\n For more information, see the :wikipedia:`Minor_(graph_theory)`.\n\n INPUT:\n\n - ``H`` -- The topological minor to find in the current graph.\n\n - ``solver`` -- (default: ``None``) Specify a Linear Program (LP)\n solver to be used. If set to ``None``, the default one is used. For\n more information on LP solvers and which default solver is used, see\n the method\n :meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>`\n of the class\n :class:`MixedIntegerLinearProgram <sage.numerical.mip.MixedIntegerLinearProgram>`.\n\n - ``verbose`` -- integer (default: ``0``). Sets the level of\n verbosity. Set to 0 by default, which means quiet.\n\n OUTPUT:\n\n The topological `H`-minor found is returned as a subgraph `M`\n of ``self``, such that the vertex `v` of `M` that represents a\n vertex `h\\in H` has ``h`` as a label (see\n :meth:`get_vertex <sage.graphs.generic_graph.GenericGraph.get_vertex>`\n and\n :meth:`set_vertex <sage.graphs.generic_graph.GenericGraph.set_vertex>`),\n and such that every edge of `M` has as a label the edge of `H`\n it (partially) represents.\n\n If no topological minor is found, this method returns\n ``False``.\n\n ALGORITHM:\n\n Mixed Integer Linear Programming.\n\n COMPLEXITY:\n\n Theoretically, when `H` is fixed, testing for the existence of\n a topological `H`-minor is polynomial. The known algorithms\n are highly exponential in `H`, though.\n\n .. NOTE::\n\n This function can be expected to be *very* slow, especially where\n the topological minor does not exist.\n\n (CPLEX seems to be *much* more efficient than GLPK on this kind of\n problem)\n\n EXAMPLES:\n\n Petersen's graph has a topological `K_4`-minor::\n\n sage: g = graphs.PetersenGraph()\n sage: g.topological_minor(graphs.CompleteGraph(4))\n Subgraph of (Petersen graph): Graph on ...\n\n And a topological `K_{3,3}`-minor::\n\n sage: g.topological_minor(graphs.CompleteBipartiteGraph(3,3))\n Subgraph of (Petersen graph): Graph on ...\n\n And of course, a tree has no topological `C_3`-minor::\n\n sage: g = graphs.RandomGNP(15,.3)\n sage: g = g.subgraph(edges = g.min_spanning_tree())\n sage: g.topological_minor(graphs.CycleGraph(3))\n False\n \"\"\"\n self._scream_if_not_simple()\n H._scream_if_not_simple()\n # Useful alias ...\n G = self\n\n from sage.numerical.mip import MixedIntegerLinearProgram, MIPSolverException\n p = MixedIntegerLinearProgram(solver=solver)\n\n # This is an existence problem\n p.set_objective(None)\n\n #######################\n # Vertex representant #\n #######################\n #\n # v_repr[h,g] = 1 if vertex h from H is represented by vertex\n # g from G, 0 otherwise\n\n v_repr = p.new_variable(binary = True)\n\n # Exactly one representant per vertex of H\n for h in H:\n p.add_constraint( p.sum( v_repr[h,g] for g in G), min = 1, max = 1)\n\n # A vertex of G can only represent one vertex of H\n for g in G:\n p.add_constraint( p.sum( v_repr[h,g] for h in H), max = 1)\n\n ###################\n # Is representent #\n ###################\n #\n # is_repr[v] = 1 if v represents some vertex of H\n\n is_repr = p.new_variable(binary = True)\n\n for g in G:\n for h in H:\n p.add_constraint( v_repr[h,g] - is_repr[g], max = 0)\n\n ###################################\n # paths between the representents #\n ###################################\n #\n # For any edge (h1,h2) in H, we have a corresponding path in G\n # between the representants of h1 and h2. Which means there is\n # a flow of intensity 1 from one to the other.\n # We are then writing a flow problem for each edge of H.\n #\n # The variable flow[(h1,h2),(g1,g2)] indicates the amount of\n # flow on the edge (g1,g2) representing the edge (h1,h2).\n\n flow = p.new_variable(binary = True)\n\n # This lambda function returns the balance of flow\n # corresponding to commodity C at vertex v v\n\n flow_in = lambda C, v : p.sum( flow[C,(v,u)] for u in G.neighbors(v) )\n flow_out = lambda C, v : p.sum( flow[C,(u,v)] for u in G.neighbors(v) )\n\n flow_balance = lambda C, v : flow_in(C,v) - flow_out(C,v)\n\n for h1,h2 in H.edges(labels = False):\n\n for v in G:\n\n # The flow balance depends on whether the vertex v is\n # a representant of h1 or h2 in G, or a reprensentant\n # of none\n\n p.add_constraint( flow_balance((h1,h2),v) == v_repr[h1,v] - v_repr[h2,v] )\n\n #############################\n # Internal vertex of a path #\n #############################\n #\n # is_internal[C][g] = 1 if a vertex v from G is located on the\n # path representing the edge (=commodity) C\n\n is_internal = p.new_variable(binary = True)\n\n # When is a vertex internal for a commodity ?\n for C in H.edges(labels = False):\n for g in G:\n p.add_constraint( flow_in(C,g) + flow_out(C,g) - is_internal[C,g], max = 1)\n\n ############################\n # Two paths do not cross ! #\n ############################\n\n # A vertex can only be internal for one commodity, and zero if\n # the vertex is a representent\n\n for g in G:\n p.add_constraint( p.sum( is_internal[C,g] for C in H.edges(labels = False))\n + is_repr[g], max = 1 )\n\n # (The following inequalities are not necessary, but they seem\n # to be of help (the solvers find the answer quicker when they\n # are added)\n\n # The flow on one edge can go in only one direction. Besides,\n # it can belong to at most one commodity and has a maximum\n # intensity of 1.\n\n for g1,g2 in G.edges(labels = None):\n\n p.add_constraint( p.sum( flow[C,(g1,g2)] for C in H.edges(labels = False) )\n + p.sum( flow[C,(g2,g1)] for C in H.edges(labels = False) ),\n max = 1)\n\n\n # Now we can solve the problem itself !\n\n try:\n p.solve(log = verbose)\n\n except MIPSolverException:\n return False\n\n\n minor = G.subgraph(immutable=False)\n\n is_repr = p.get_values(is_repr)\n v_repr = p.get_values(v_repr)\n flow = p.get_values(flow)\n\n for u,v in minor.edges(labels = False):\n used = False\n for C in H.edges(labels = False):\n\n if flow[C,(u,v)] + flow[C,(v,u)] > .5:\n used = True\n minor.set_edge_label(u,v,C)\n break\n if not used:\n minor.delete_edge(u,v)\n\n minor.delete_vertices( [v for v in minor\n if minor.degree(v) == 0 ] )\n\n for g in minor:\n if is_repr[g] > .5:\n for h in H:\n if v_repr[h,v] > .5:\n minor.set_vertex(g,h)\n break\n\n return minor\n\n ### Cliques\n\n @doc_index(\"Clique-related methods\")\n def cliques_maximal(self, algorithm = \"native\"):\n \"\"\"\n Returns the list of all maximal cliques, with each clique represented\n by a list of vertices. A clique is an induced complete subgraph, and a\n maximal clique is one not contained in a larger one.\n\n INPUT:\n\n - ``algorithm`` -- can be set to ``\"native\"`` (default) to use Sage's\n own implementation, or to ``\"NetworkX\"`` to use NetworkX'\n implementation of the Bron and Kerbosch Algorithm [BroKer1973]_.\n\n\n .. NOTE::\n\n This method sorts its output before returning it. If you prefer to\n save the extra time, you can call\n :class:`sage.graphs.independent_sets.IndependentSets` directly.\n\n .. NOTE::\n\n Sage's implementation of the enumeration of *maximal* independent\n sets is not much faster than NetworkX' (expect a 2x speedup), which\n is surprising as it is written in Cython. This being said, the\n algorithm from NetworkX appears to be sligthly different from this\n one, and that would be a good thing to explore if one wants to\n improve the implementation.\n\n ALGORITHM:\n\n This function is based on NetworkX's implementation of the Bron and\n Kerbosch Algorithm [BroKer1973]_.\n\n REFERENCE:\n\n .. [BroKer1973] Coen Bron and Joep Kerbosch. (1973). Algorithm 457:\n Finding All Cliques of an Undirected Graph. Commun. ACM. v\n 16. n 9. pages 575-577. ACM Press. [Online] Available:\n http://www.ram.org/computing/rambin/rambin.html\n\n EXAMPLES::\n\n sage: graphs.ChvatalGraph().cliques_maximal()\n [[0, 1], [0, 4], [0, 6], [0, 9], [1, 2], [1, 5], [1, 7], [2, 3],\n [2, 6], [2, 8], [3, 4], [3, 7], [3, 9], [4, 5], [4, 8], [5, 10],\n [5, 11], [6, 10], [6, 11], [7, 8], [7, 11], [8, 10], [9, 10], [9, 11]]\n sage: G = Graph({0:[1,2,3], 1:[2], 3:[0,1]})\n sage: G.show(figsize=[2,2])\n sage: G.cliques_maximal()\n [[0, 1, 2], [0, 1, 3]]\n sage: C=graphs.PetersenGraph()\n sage: C.cliques_maximal()\n [[0, 1], [0, 4], [0, 5], [1, 2], [1, 6], [2, 3], [2, 7], [3, 4],\n [3, 8], [4, 9], [5, 7], [5, 8], [6, 8], [6, 9], [7, 9]]\n sage: C = Graph('DJ{')\n sage: C.cliques_maximal()\n [[0, 4], [1, 2, 3, 4]]\n\n Comparing the two implementations::\n\n sage: g = graphs.RandomGNP(20,.7)\n sage: s1 = Set(map(Set, g.cliques_maximal(algorithm=\"NetworkX\")))\n sage: s2 = Set(map(Set, g.cliques_maximal(algorithm=\"native\")))\n sage: s1 == s2\n True\n \"\"\"\n if algorithm == \"native\":\n from sage.graphs.independent_sets import IndependentSets\n return sorted(IndependentSets(self, maximal = True, complement = True))\n elif algorithm == \"NetworkX\":\n import networkx\n return sorted(networkx.find_cliques(self.networkx_graph(copy=False)))\n else:\n raise ValueError(\"Algorithm must be equal to 'native' or to 'NetworkX'.\")\n\n @doc_index(\"Clique-related methods\")\n def clique_maximum(self, algorithm=\"Cliquer\"):\n \"\"\"\n Returns the vertex set of a maximal order complete subgraph.\n\n INPUT:\n\n - ``algorithm`` -- the algorithm to be used :\n\n - If ``algorithm = \"Cliquer\"`` (default) - This wraps the C program\n Cliquer [NisOst2003]_.\n\n - If ``algorithm = \"MILP\"``, the problem is solved through a Mixed\n Integer Linear Program.\n\n (see :class:`~sage.numerical.mip.MixedIntegerLinearProgram`)\n\n - If ``algorithm = \"mcqd\"`` - Uses the MCQD solver\n (`<http://www.sicmm.org/~konc/maxclique/>`_). Note that the MCQD\n package must be installed.\n\n .. NOTE::\n\n Currently only implemented for undirected graphs. Use to_undirected\n to convert a digraph to an undirected graph.\n\n ALGORITHM:\n\n This function is based on Cliquer [NisOst2003]_.\n\n EXAMPLES:\n\n Using Cliquer (default)::\n\n sage: C=graphs.PetersenGraph()\n sage: C.clique_maximum()\n [7, 9]\n sage: C = Graph('DJ{')\n sage: C.clique_maximum()\n [1, 2, 3, 4]\n\n Through a Linear Program::\n\n sage: len(C.clique_maximum(algorithm = \"MILP\"))\n 4\n\n TESTS:\n\n Wrong algorithm::\n\n sage: C.clique_maximum(algorithm = \"BFS\")\n Traceback (most recent call last):\n ...\n NotImplementedError: Only 'MILP', 'Cliquer' and 'mcqd' are supported.\n\n \"\"\"\n self._scream_if_not_simple(allow_multiple_edges=True)\n if algorithm==\"Cliquer\":\n from sage.graphs.cliquer import max_clique\n return max_clique(self)\n elif algorithm == \"MILP\":\n return self.complement().independent_set(algorithm = algorithm)\n elif algorithm == \"mcqd\":\n try:\n from sage.graphs.mcqd import mcqd\n except ImportError:\n raise ImportError(\"Please install the mcqd package\")\n return mcqd(self)\n else:\n raise NotImplementedError(\"Only 'MILP', 'Cliquer' and 'mcqd' are supported.\")\n\n @doc_index(\"Clique-related methods\")\n def clique_number(self, algorithm=\"Cliquer\", cliques=None):\n r\"\"\"\n Returns the order of the largest clique of the graph (the clique\n number).\n\n .. NOTE::\n\n Currently only implemented for undirected graphs. Use ``to_undirected``\n to convert a digraph to an undirected graph.\n\n INPUT:\n\n - ``algorithm`` -- the algorithm to be used :\n\n - If ``algorithm = \"Cliquer\"`` - This wraps the C program Cliquer\n [NisOst2003]_.\n\n - If ``algorithm = \"networkx\"`` - This function is based on\n NetworkX's implementation of the Bron and Kerbosch Algorithm\n [BroKer1973]_.\n\n - If ``algorithm = \"MILP\"``, the problem is solved through a Mixed\n Integer Linear Program.\n\n (see :class:`~sage.numerical.mip.MixedIntegerLinearProgram`)\n\n - If ``algorithm = \"mcqd\"`` - Uses the MCQD solver\n (`<http://www.sicmm.org/~konc/maxclique/>`_). Note that the MCQD\n package must be installed.\n\n - ``cliques`` - an optional list of cliques that can be input if\n already computed. Ignored unless ``algorithm==\"networkx\"``.\n\n ALGORITHM:\n\n This function is based on Cliquer [NisOst2003]_ and [BroKer1973]_.\n\n EXAMPLES::\n\n sage: C = Graph('DJ{')\n sage: C.clique_number()\n 4\n sage: G = Graph({0:[1,2,3], 1:[2], 3:[0,1]})\n sage: G.show(figsize=[2,2])\n sage: G.clique_number()\n 3\n\n By definition the clique number of a complete graph is its order::\n\n sage: all(graphs.CompleteGraph(i).clique_number() == i for i in range(1,15))\n True\n\n A non-empty graph without edges has a clique number of 1::\n\n sage: all((i*graphs.CompleteGraph(1)).clique_number() == 1 for i in range(1,15))\n True\n\n A complete multipartite graph with k parts has clique number k::\n\n sage: all((i*graphs.CompleteMultipartiteGraph(i*[5])).clique_number() == i for i in range(1,6))\n True\n\n TESTS::\n\n sage: g = graphs.PetersenGraph()\n sage: g.clique_number(algorithm=\"MILP\")\n 2\n sage: for i in range(10): # optional - mcqd\n ... g = graphs.RandomGNP(15,.5) # optional - mcqd\n ... if g.clique_number() != g.clique_number(algorithm=\"mcqd\"): # optional - mcqd\n ... print(\"This is dead wrong !\") # optional - mcqd\n \"\"\"\n self._scream_if_not_simple(allow_loops=False)\n if algorithm==\"Cliquer\":\n from sage.graphs.cliquer import clique_number\n return clique_number(self)\n elif algorithm==\"networkx\":\n import networkx\n return networkx.graph_clique_number(self.networkx_graph(copy=False),cliques)\n elif algorithm == \"MILP\":\n return len(self.complement().independent_set(algorithm = algorithm))\n elif algorithm == \"mcqd\":\n try:\n from sage.graphs.mcqd import mcqd\n except ImportError:\n raise ImportError(\"Please install the mcqd package\")\n return len(mcqd(self))\n else:\n raise NotImplementedError(\"Only 'networkx' 'MILP' 'Cliquer' and 'mcqd' are supported.\")\n\n @doc_index(\"Clique-related methods\")\n def cliques_number_of(self, vertices=None, cliques=None):\n \"\"\"\n Returns a dictionary of the number of maximal cliques containing each\n vertex, keyed by vertex. (Returns a single value if\n only one input vertex).\n\n .. NOTE::\n\n Currently only implemented for undirected graphs. Use to_undirected\n to convert a digraph to an undirected graph.\n\n INPUT:\n\n - ``vertices`` - the vertices to inspect (default is\n entire graph)\n\n - ``cliques`` - list of cliques (if already\n computed)\n\n\n EXAMPLES::\n\n sage: C = Graph('DJ{')\n sage: C.cliques_number_of()\n {0: 1, 1: 1, 2: 1, 3: 1, 4: 2}\n sage: E = C.cliques_maximal()\n sage: E\n [[0, 4], [1, 2, 3, 4]]\n sage: C.cliques_number_of(cliques=E)\n {0: 1, 1: 1, 2: 1, 3: 1, 4: 2}\n sage: F = graphs.Grid2dGraph(2,3)\n sage: X = F.cliques_number_of()\n sage: for v in sorted(X):\n ....: print(\"{} {}\".format(v, X[v]))\n (0, 0) 2\n (0, 1) 3\n (0, 2) 2\n (1, 0) 2\n (1, 1) 3\n (1, 2) 2\n sage: F.cliques_number_of(vertices=[(0, 1), (1, 2)])\n {(0, 1): 3, (1, 2): 2}\n sage: G = Graph({0:[1,2,3], 1:[2], 3:[0,1]})\n sage: G.show(figsize=[2,2])\n sage: G.cliques_number_of()\n {0: 2, 1: 2, 2: 1, 3: 1}\n \"\"\"\n import networkx\n return networkx.number_of_cliques(self.networkx_graph(copy=False), vertices, cliques)\n\n @doc_index(\"Clique-related methods\")\n def cliques_get_max_clique_graph(self, name=''):\n \"\"\"\n Returns a graph constructed with maximal cliques as vertices, and\n edges between maximal cliques with common members in the original\n graph.\n\n For more information, see the :wikipedia:`Clique_graph`.\n\n .. NOTE::\n\n Currently only implemented for undirected graphs. Use to_undirected\n to convert a digraph to an undirected graph.\n\n INPUT:\n\n - ``name`` - The name of the new graph.\n\n EXAMPLES::\n\n sage: (graphs.ChvatalGraph()).cliques_get_max_clique_graph()\n Graph on 24 vertices\n sage: ((graphs.ChvatalGraph()).cliques_get_max_clique_graph()).show(figsize=[2,2], vertex_size=20, vertex_labels=False)\n sage: G = Graph({0:[1,2,3], 1:[2], 3:[0,1]})\n sage: G.show(figsize=[2,2])\n sage: G.cliques_get_max_clique_graph()\n Graph on 2 vertices\n sage: (G.cliques_get_max_clique_graph()).show(figsize=[2,2])\n \"\"\"\n import networkx\n return Graph(networkx.make_max_clique_graph(self.networkx_graph(copy=False), name=name, create_using=networkx.MultiGraph()))\n\n @doc_index(\"Clique-related methods\")\n def cliques_get_clique_bipartite(self, **kwds):\n \"\"\"\n Returns a bipartite graph constructed such that maximal cliques are the\n right vertices and the left vertices are retained from the given\n graph. Right and left vertices are connected if the bottom vertex\n belongs to the clique represented by a top vertex.\n\n .. NOTE::\n\n Currently only implemented for undirected graphs. Use to_undirected\n to convert a digraph to an undirected graph.\n\n EXAMPLES::\n\n sage: (graphs.ChvatalGraph()).cliques_get_clique_bipartite()\n Bipartite graph on 36 vertices\n sage: ((graphs.ChvatalGraph()).cliques_get_clique_bipartite()).show(figsize=[2,2], vertex_size=20, vertex_labels=False)\n sage: G = Graph({0:[1,2,3], 1:[2], 3:[0,1]})\n sage: G.show(figsize=[2,2])\n sage: G.cliques_get_clique_bipartite()\n Bipartite graph on 6 vertices\n sage: (G.cliques_get_clique_bipartite()).show(figsize=[2,2])\n \"\"\"\n from .bipartite_graph import BipartiteGraph\n import networkx\n return BipartiteGraph(networkx.make_clique_bipartite(self.networkx_graph(copy=False), **kwds))\n\n @doc_index(\"Algorithmically hard stuff\")\n def independent_set(self, algorithm = \"Cliquer\", value_only = False, reduction_rules = True, solver = None, verbosity = 0):\n r\"\"\"\n Returns a maximum independent set.\n\n An independent set of a graph is a set of pairwise non-adjacent\n vertices. A maximum independent set is an independent set of maximum\n cardinality. It induces an empty subgraph.\n\n Equivalently, an independent set is defined as the complement of a\n vertex cover.\n\n For more information, see the\n :wikipedia:`Independent_set_(graph_theory)` and the\n :wikipedia:`Vertex_cover`.\n\n INPUT:\n\n - ``algorithm`` -- the algorithm to be used\n\n * If ``algorithm = \"Cliquer\"`` (default), the problem is solved\n using Cliquer [NisOst2003]_.\n\n (see the :mod:`Cliquer modules <sage.graphs.cliquer>`)\n\n * If ``algorithm = \"MILP\"``, the problem is solved through a Mixed\n Integer Linear Program.\n\n (see :class:`~sage.numerical.mip.MixedIntegerLinearProgram`)\n\n * If ``algorithm = \"mcqd\"`` - Uses the MCQD solver\n (`<http://www.sicmm.org/~konc/maxclique/>`_). Note that the MCQD\n package must be installed.\n\n - ``value_only`` -- boolean (default: ``False``). If set to ``True``,\n only the size of a maximum independent set is returned. Otherwise,\n a maximum independent set is returned as a list of vertices.\n\n - ``reduction_rules`` -- (default: ``True``) Specify if the reductions\n rules from kernelization must be applied as pre-processing or not.\n See [ACFLSS04]_ for more details. Note that depending on the\n instance, it might be faster to disable reduction rules.\n\n - ``solver`` -- (default: ``None``) Specify a Linear Program (LP)\n solver to be used. If set to ``None``, the default one is used. For\n more information on LP solvers and which default solver is used, see\n the method\n :meth:`~sage.numerical.mip.MixedIntegerLinearProgram.solve`\n of the class\n :class:`~sage.numerical.mip.MixedIntegerLinearProgram`.\n\n - ``verbosity`` -- non-negative integer (default: ``0``). Set the level\n of verbosity you want from the linear program solver. Since the\n problem of computing an independent set is `NP`-complete, its solving\n may take some time depending on the graph. A value of 0 means that\n there will be no message printed by the solver. This option is only\n useful if ``algorithm=\"MILP\"``.\n\n .. NOTE::\n\n While Cliquer/MCAD are usually (and by far) the most efficient\n implementations, the MILP formulation sometimes proves faster on\n very \"symmetrical\" graphs.\n\n EXAMPLES:\n\n Using Cliquer::\n\n sage: C = graphs.PetersenGraph()\n sage: C.independent_set()\n [0, 3, 6, 7]\n\n As a linear program::\n\n sage: C = graphs.PetersenGraph()\n sage: len(C.independent_set(algorithm = \"MILP\"))\n 4\n\n .. PLOT::\n\n g = graphs.PetersenGraph()\n sphinx_plot(g.plot(partition=[g.independent_set()]))\n \"\"\"\n my_cover = self.vertex_cover(algorithm=algorithm, value_only=value_only, reduction_rules=reduction_rules, solver=solver, verbosity=verbosity)\n if value_only:\n return self.order() - my_cover\n else:\n return [u for u in self.vertices() if not u in my_cover]\n\n\n @doc_index(\"Algorithmically hard stuff\")\n def vertex_cover(self, algorithm = \"Cliquer\", value_only = False,\n reduction_rules = True, solver = None, verbosity = 0):\n r\"\"\"\n Returns a minimum vertex cover of self represented by a set of vertices.\n\n A minimum vertex cover of a graph is a set `S` of vertices such that\n each edge is incident to at least one element of `S`, and such that `S`\n is of minimum cardinality. For more information, see the\n :wikipedia:`Wikipedia article on vertex cover <Vertex_cover>`.\n\n Equivalently, a vertex cover is defined as the complement of an\n independent set.\n\n As an optimization problem, it can be expressed as follows:\n\n .. MATH::\n\n \\mbox{Minimize : }&\\sum_{v\\in G} b_v\\\\\n \\mbox{Such that : }&\\forall (u,v) \\in G.edges(), b_u+b_v\\geq 1\\\\\n &\\forall x\\in G, b_x\\mbox{ is a binary variable}\n\n INPUT:\n\n - ``algorithm`` -- string (default: ``\"Cliquer\"``). Indicating\n which algorithm to use. It can be one of those two values.\n\n - ``\"Cliquer\"`` will compute a minimum vertex cover\n using the Cliquer package.\n\n - ``\"MILP\"`` will compute a minimum vertex cover through a mixed\n integer linear program.\n\n - If ``algorithm = \"mcqd\"`` - Uses the MCQD solver\n (`<http://www.sicmm.org/~konc/maxclique/>`_). Note that the MCQD\n package must be installed.\n\n - ``value_only`` -- boolean (default: ``False``). If set to ``True``,\n only the size of a minimum vertex cover is returned. Otherwise,\n a minimum vertex cover is returned as a list of vertices.\n\n - ``reduction_rules`` -- (default: ``True``) Specify if the reductions\n rules from kernelization must be applied as pre-processing or not.\n See [ACFLSS04]_ for more details. Note that depending on the\n instance, it might be faster to disable reduction rules.\n\n - ``solver`` -- (default: ``None``) Specify a Linear Program (LP)\n solver to be used. If set to ``None``, the default one is used. For\n more information on LP solvers and which default solver is used, see\n the method\n :meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>`\n of the class\n :class:`MixedIntegerLinearProgram <sage.numerical.mip.MixedIntegerLinearProgram>`.\n\n - ``verbosity`` -- non-negative integer (default: ``0``). Set the level\n of verbosity you want from the linear program solver. Since the\n problem of computing a vertex cover is `NP`-complete, its solving may\n take some time depending on the graph. A value of 0 means that there\n will be no message printed by the solver. This option is only useful\n if ``algorithm=\"MILP\"``.\n\n EXAMPLES:\n\n On the Pappus graph::\n\n sage: g = graphs.PappusGraph()\n sage: g.vertex_cover(value_only=True)\n 9\n\n .. PLOT::\n\n g = graphs.PappusGraph()\n sphinx_plot(g.plot(partition=[g.vertex_cover()]))\n\n TESTS:\n\n The two algorithms should return the same result::\n\n sage: g = graphs.RandomGNP(10,.5)\n sage: vc1 = g.vertex_cover(algorithm=\"MILP\")\n sage: vc2 = g.vertex_cover(algorithm=\"Cliquer\")\n sage: len(vc1) == len(vc2)\n True\n\n The cardinality of the vertex cover is unchanged when reduction rules are used. First for trees::\n\n sage: for i in range(20):\n ... g = graphs.RandomTree(20)\n ... vc1_set = g.vertex_cover()\n ... vc1 = len(vc1_set)\n ... vc2 = g.vertex_cover(value_only = True, reduction_rules = False)\n ... if vc1 != vc2:\n ... print(\"Error :\", vc1, vc2)\n ... print(\"With reduction rules :\", vc1)\n ... print(\"Without reduction rules :\", vc2)\n ... break\n ... g.delete_vertices(vc1_set)\n ... if g.size() != 0:\n ... print(\"This thing is not a vertex cover !\")\n\n Then for random GNP graphs::\n\n sage: for i in range(20):\n ... g = graphs.RandomGNP(50,4/50)\n ... vc1_set = g.vertex_cover()\n ... vc1 = len(vc1_set)\n ... vc2 = g.vertex_cover(value_only = True, reduction_rules = False)\n ... if vc1 != vc2:\n ... print(\"Error :\", vc1, vc2)\n ... print(\"With reduction rules :\", vc1)\n ... print(\"Without reduction rules :\", vc2)\n ... break\n ... g.delete_vertices(vc1_set)\n ... if g.size() != 0:\n ... print(\"This thing is not a vertex cover !\")\n\n Testing mcqd::\n\n sage: graphs.PetersenGraph().vertex_cover(algorithm=\"mcqd\",value_only=True) # optional - mcqd\n 6\n\n Given a wrong algorithm::\n\n sage: graphs.PetersenGraph().vertex_cover(algorithm = \"guess\")\n Traceback (most recent call last):\n ...\n ValueError: The algorithm must be \"Cliquer\" \"MILP\" or \"mcqd\".\n\n REFERENCE:\n\n .. [ACFLSS04] \\F. N. Abu-Khzam, R. L. Collins, M. R. Fellows, M. A.\n Langston, W. H. Suters, and C. T. Symons: Kernelization Algorithm for\n the Vertex Cover Problem: Theory and Experiments. *SIAM ALENEX/ANALCO*\n 2004: 62-69.\n \"\"\"\n self._scream_if_not_simple(allow_multiple_edges=True)\n g = self\n\n ppset = []\n folded_vertices = []\n\n ###################\n # Reduction rules #\n ###################\n\n if reduction_rules:\n # We apply simple reduction rules allowing to identify vertices that\n # belongs to an optimal vertex cover\n\n # We first create manually a copy of the graph to prevent creating\n # multi-edges when merging vertices, if edges have labels (e.g., weights).\n g = copy(self)\n\n degree_at_most_two = set([u for u,du in g.degree(labels = True).items() if du <= 2])\n\n while degree_at_most_two:\n\n u = degree_at_most_two.pop()\n du = g.degree(u)\n\n if du == 0:\n # RULE 1: isolated vertices are not part of the cover. We\n # simply remove them from the graph. The degree of such\n # vertices may have been reduced to 0 while applying other\n # reduction rules\n g.delete_vertex(u)\n\n elif du == 1:\n # RULE 2: If a vertex u has degree 1, we select its neighbor\n # v and remove both u and v from g.\n v = g.neighbors(u)[0]\n ppset.append(v)\n g.delete_vertex(u)\n\n for w in g.neighbors(v):\n if g.degree(w) <= 3:\n # The degree of w will be at most two after the\n # deletion of v\n degree_at_most_two.add(w)\n\n g.delete_vertex(v)\n degree_at_most_two.discard(v)\n\n elif du == 2:\n v,w = g.neighbors(u)\n\n if g.has_edge(v,w):\n # RULE 3: If the neighbors v and w of a degree 2 vertex\n # u are incident, then we select both v and w and remove\n # u, v, and w from g.\n ppset.append(v)\n ppset.append(w)\n g.delete_vertex(u)\n neigh = set(g.neighbors(v) + g.neighbors(w)).difference(set([v,w]))\n g.delete_vertex(v)\n g.delete_vertex(w)\n\n for z in neigh:\n if g.degree(z) <= 2:\n degree_at_most_two.add(z)\n\n else:\n # RULE 4, folded vertices: If the neighbors v and w of a\n # degree 2 vertex u are not incident, then we contract\n # edges (u, v), (u,w). Then, if the solution contains u,\n # we replace it with v and w. Otherwise, we let u in the\n # solution.\n neigh = set(g.neighbors(v) + g.neighbors(w)).difference(set([u,v,w]))\n g.delete_vertex(v)\n g.delete_vertex(w)\n for z in neigh:\n g.add_edge(u,z)\n\n folded_vertices += [(u,v,w)]\n\n if g.degree(u) <= 2:\n degree_at_most_two.add(u)\n\n degree_at_most_two.discard(v)\n degree_at_most_two.discard(w)\n\n\n # RULE 5:\n # TODO: add extra reduction rules\n\n\n ##################\n # Main Algorithm #\n ##################\n\n if g.order() == 0:\n # Reduction rules were sufficients to get the solution\n size_cover_g = 0\n cover_g = []\n\n elif algorithm == \"Cliquer\" or algorithm == \"mcqd\":\n independent = g.complement().clique_maximum(algorithm=algorithm)\n if value_only:\n size_cover_g = g.order() - len(independent)\n else:\n cover_g = [u for u in g.vertices() if not u in independent]\n\n elif algorithm == \"MILP\":\n\n from sage.numerical.mip import MixedIntegerLinearProgram\n p = MixedIntegerLinearProgram(maximization=False, solver=solver)\n b = p.new_variable(binary=True)\n\n # minimizes the number of vertices in the set\n p.set_objective(p.sum(b[v] for v in g.vertices()))\n\n # an edge contains at least one vertex of the minimum vertex cover\n for (u,v) in g.edges(labels=None):\n p.add_constraint(b[u] + b[v], min=1)\n\n if value_only:\n size_cover_g = p.solve(objective_only=True, log=verbosity)\n else:\n p.solve(log=verbosity)\n b = p.get_values(b)\n cover_g = [v for v in g.vertices() if b[v] == 1]\n else:\n raise ValueError(\"The algorithm must be \\\"Cliquer\\\" \\\"MILP\\\" or \\\"mcqd\\\".\")\n\n #########################\n # Returning the results #\n #########################\n\n # We finally reconstruct the solution according the reduction rules\n if value_only:\n return len(ppset) + len(folded_vertices) + size_cover_g\n else:\n # RULES 2 and 3:\n cover_g.extend(ppset)\n # RULE 4:\n folded_vertices.reverse()\n for u,v,w in folded_vertices:\n if u in cover_g:\n cover_g.remove(u)\n cover_g += [v,w]\n else:\n cover_g += [u]\n cover_g.sort()\n return cover_g\n\n @doc_index(\"Clique-related methods\")\n def cliques_vertex_clique_number(self, algorithm=\"cliquer\", vertices=None,\n cliques=None):\n \"\"\"\n Returns a dictionary of sizes of the largest maximal cliques containing\n each vertex, keyed by vertex. (Returns a single value if only one\n input vertex).\n\n .. NOTE::\n\n Currently only implemented for undirected graphs. Use to_undirected\n to convert a digraph to an undirected graph.\n\n INPUT:\n\n - ``algorithm`` - either ``cliquer`` or ``networkx``\n\n - ``cliquer`` - This wraps the C program Cliquer [NisOst2003]_.\n\n - ``networkx`` - This function is based on NetworkX's implementation\n of the Bron and Kerbosch Algorithm [BroKer1973]_.\n\n - ``vertices`` - the vertices to inspect (default is entire graph).\n Ignored unless ``algorithm=='networkx'``.\n\n - ``cliques`` - list of cliques (if already computed). Ignored unless\n ``algorithm=='networkx'``.\n\n EXAMPLES::\n\n sage: C = Graph('DJ{')\n sage: C.cliques_vertex_clique_number()\n {0: 2, 1: 4, 2: 4, 3: 4, 4: 4}\n sage: E = C.cliques_maximal()\n sage: E\n [[0, 4], [1, 2, 3, 4]]\n sage: C.cliques_vertex_clique_number(cliques=E,algorithm=\"networkx\")\n {0: 2, 1: 4, 2: 4, 3: 4, 4: 4}\n sage: F = graphs.Grid2dGraph(2,3)\n sage: X = F.cliques_vertex_clique_number(algorithm=\"networkx\")\n sage: for v in sorted(X):\n ....: print(\"{} {}\".format(v, X[v]))\n (0, 0) 2\n (0, 1) 2\n (0, 2) 2\n (1, 0) 2\n (1, 1) 2\n (1, 2) 2\n sage: F.cliques_vertex_clique_number(vertices=[(0, 1), (1, 2)])\n {(0, 1): 2, (1, 2): 2}\n sage: G = Graph({0:[1,2,3], 1:[2], 3:[0,1]})\n sage: G.show(figsize=[2,2])\n sage: G.cliques_vertex_clique_number()\n {0: 3, 1: 3, 2: 3, 3: 3}\n\n \"\"\"\n\n if algorithm==\"cliquer\":\n from sage.graphs.cliquer import clique_number\n if vertices is None:\n vertices=self\n value={}\n for v in vertices:\n value[v] = 1+clique_number(self.subgraph(self.neighbors(v)))\n self.subgraph(self.neighbors(v)).plot()\n return value\n elif algorithm==\"networkx\":\n import networkx\n return networkx.node_clique_number(self.networkx_graph(copy=False),vertices, cliques)\n else:\n raise NotImplementedError(\"Only 'networkx' and 'cliquer' are supported.\")\n\n @doc_index(\"Clique-related methods\")\n def cliques_containing_vertex(self, vertices=None, cliques=None):\n \"\"\"\n Returns the cliques containing each vertex, represented as a dictionary\n of lists of lists, keyed by vertex. (Returns a single list if only one\n input vertex).\n\n .. NOTE::\n\n Currently only implemented for undirected graphs. Use to_undirected\n to convert a digraph to an undirected graph.\n\n INPUT:\n\n - ``vertices`` - the vertices to inspect (default is\n entire graph)\n\n - ``cliques`` - list of cliques (if already\n computed)\n\n EXAMPLES::\n\n sage: C = Graph('DJ{')\n sage: C.cliques_containing_vertex()\n {0: [[4, 0]], 1: [[4, 1, 2, 3]], 2: [[4, 1, 2, 3]], 3: [[4, 1, 2, 3]], 4: [[4, 0], [4, 1, 2, 3]]}\n sage: E = C.cliques_maximal()\n sage: E\n [[0, 4], [1, 2, 3, 4]]\n sage: C.cliques_containing_vertex(cliques=E)\n {0: [[0, 4]], 1: [[1, 2, 3, 4]], 2: [[1, 2, 3, 4]], 3: [[1, 2, 3, 4]], 4: [[0, 4], [1, 2, 3, 4]]}\n sage: F = graphs.Grid2dGraph(2,3)\n sage: X = F.cliques_containing_vertex()\n sage: for v in sorted(X):\n ....: print(\"{} {}\".format(v, X[v]))\n (0, 0) [[(0, 1), (0, 0)], [(1, 0), (0, 0)]]\n (0, 1) [[(0, 1), (0, 0)], [(0, 1), (0, 2)], [(0, 1), (1, 1)]]\n (0, 2) [[(0, 1), (0, 2)], [(1, 2), (0, 2)]]\n (1, 0) [[(1, 0), (0, 0)], [(1, 0), (1, 1)]]\n (1, 1) [[(0, 1), (1, 1)], [(1, 2), (1, 1)], [(1, 0), (1, 1)]]\n (1, 2) [[(1, 2), (0, 2)], [(1, 2), (1, 1)]]\n sage: F.cliques_containing_vertex(vertices=[(0, 1), (1, 2)])\n {(0, 1): [[(0, 1), (0, 0)], [(0, 1), (0, 2)], [(0, 1), (1, 1)]], (1, 2): [[(1, 2), (0, 2)], [(1, 2), (1, 1)]]}\n sage: G = Graph({0:[1,2,3], 1:[2], 3:[0,1]})\n sage: G.show(figsize=[2,2])\n sage: G.cliques_containing_vertex()\n {0: [[0, 1, 2], [0, 1, 3]], 1: [[0, 1, 2], [0, 1, 3]], 2: [[0, 1, 2]], 3: [[0, 1, 3]]}\n\n \"\"\"\n import networkx\n return networkx.cliques_containing_node(self.networkx_graph(copy=False),vertices, cliques)\n\n @doc_index(\"Clique-related methods\")\n def clique_complex(self):\n \"\"\"\n Returns the clique complex of self. This is the largest simplicial complex on\n the vertices of self whose 1-skeleton is self.\n\n This is only makes sense for undirected simple graphs.\n\n EXAMPLES::\n\n sage: g = Graph({0:[1,2],1:[2],4:[]})\n sage: g.clique_complex()\n Simplicial complex with vertex set (0, 1, 2, 4) and facets {(4,), (0, 1, 2)}\n\n sage: h = Graph({0:[1,2,3,4],1:[2,3,4],2:[3]})\n sage: x = h.clique_complex()\n sage: x\n Simplicial complex with vertex set (0, 1, 2, 3, 4) and facets {(0, 1, 4), (0, 1, 2, 3)}\n sage: i = x.graph()\n sage: i==h\n True\n sage: x==i.clique_complex()\n True\n\n \"\"\"\n if self.is_directed() or self.has_loops() or self.has_multiple_edges():\n raise ValueError(\"Self must be an undirected simple graph to have a clique complex.\")\n import sage.homology.simplicial_complex\n C = sage.homology.simplicial_complex.SimplicialComplex(self.cliques_maximal(), maximality_check=True)\n C._graph = self\n return C\n\n @doc_index(\"Clique-related methods\")\n def clique_polynomial(self, t = None):\n \"\"\"\n Returns the clique polynomial of self.\n\n This is the polynomial where the coefficient of `t^n` is the number of\n cliques in the graph with `n` vertices. The constant term of the\n clique polynomial is always taken to be one.\n\n EXAMPLES::\n\n sage: g = Graph()\n sage: g.clique_polynomial()\n 1\n sage: g = Graph({0:[1]})\n sage: g.clique_polynomial()\n t^2 + 2*t + 1\n sage: g = graphs.CycleGraph(4)\n sage: g.clique_polynomial()\n 4*t^2 + 4*t + 1\n\n \"\"\"\n if t is None:\n R = PolynomialRing(ZZ, 't')\n t = R.gen()\n number_of = [0]*(self.order() + 1)\n for x in IndependentSets(self, complement = True):\n number_of[len(x)] += 1\n return sum(coeff*t**i for i,coeff in enumerate(number_of) if coeff)\n\n ### Miscellaneous\n\n @doc_index(\"Leftovers\")\n def cores(self, k = None, with_labels=False):\n \"\"\"\n Returns the core number for each vertex in an ordered list.\n\n (for homomorphisms cores, see the :meth:`Graph.has_homomorphism_to`\n method)\n\n **DEFINITIONS**\n\n * *K-cores* in graph theory were introduced by Seidman in 1983 and by\n Bollobas in 1984 as a method of (destructively) simplifying graph\n topology to aid in analysis and visualization. They have been more\n recently defined as the following by Batagelj et al:\n\n *Given a graph `G` with vertices set `V` and edges set `E`, the\n `k`-core of `G` is the graph obtained from `G` by recursively removing\n the vertices with degree less than `k`, for as long as there are any.*\n\n This operation can be useful to filter or to study some properties of\n the graphs. For instance, when you compute the 2-core of graph G, you\n are cutting all the vertices which are in a tree part of graph. (A\n tree is a graph with no loops). [WPkcore]_\n\n [PSW1996]_ defines a `k`-core of `G` as the largest subgraph (it is\n unique) of `G` with minimum degree at least `k`.\n\n * Core number of a vertex\n\n The core number of a vertex `v` is the largest integer `k` such that\n `v` belongs to the `k`-core of `G`.\n\n * Degeneracy\n\n The *degeneracy* of a graph `G`, usually denoted `\\delta^*(G)`, is the\n smallest integer `k` such that the graph `G` can be reduced to the\n empty graph by iteratively removing vertices of degree `\\leq\n k`. Equivalently, `\\delta^*(G)=k` if `k` is the smallest integer such\n that the `k`-core of `G` is empty.\n\n **IMPLEMENTATION**\n\n This implementation is based on the NetworkX implementation of\n the algorithm described in [BZ]_.\n\n **INPUT**\n\n - ``k`` (integer)\n\n * If ``k = None`` (default), returns the core number for each vertex.\n\n * If ``k`` is an integer, returns a pair ``(ordering, core)``, where\n ``core`` is the list of vertices in the `k`-core of ``self``, and\n ``ordering`` is an elimination order for the other vertices such\n that each vertex is of degree strictly less than `k` when it is to\n be eliminated from the graph.\n\n - ``with_labels`` (boolean)\n\n * When set to ``False``, and ``k = None``, the method returns a list\n whose `i` th element is the core number of the `i` th vertex. When\n set to ``True``, the method returns a dictionary whose keys are\n vertices, and whose values are the corresponding core numbers.\n\n By default, ``with_labels = False``.\n\n .. SEEALSO::\n\n * Graph cores is also a notion related to graph homomorphisms. For\n this second meaning, see :meth:`Graph.has_homomorphism_to`.\n\n REFERENCE:\n\n .. [WPkcore] K-core. Wikipedia. (2007). [Online] Available:\n :wikipedia:`K-core`\n\n .. [PSW1996] Boris Pittel, Joel Spencer and Nicholas Wormald. Sudden\n Emergence of a Giant k-Core in a Random\n Graph. (1996). J. Combinatorial Theory. Ser B 67. pages\n 111-151. [Online] Available:\n http://cs.nyu.edu/cs/faculty/spencer/papers/k-core.pdf\n\n .. [BZ] Vladimir Batagelj and Matjaz Zaversnik. An `O(m)`\n Algorithm for Cores Decomposition of\n Networks. :arxiv:`cs/0310049v1`.\n\n EXAMPLES::\n\n sage: (graphs.FruchtGraph()).cores()\n [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]\n sage: (graphs.FruchtGraph()).cores(with_labels=True)\n {0: 3, 1: 3, 2: 3, 3: 3, 4: 3, 5: 3, 6: 3, 7: 3, 8: 3, 9: 3, 10: 3, 11: 3}\n sage: a=random_matrix(ZZ,20,x=2,sparse=True, density=.1)\n sage: b=Graph(20)\n sage: b.add_edges(a.nonzero_positions())\n sage: cores=b.cores(with_labels=True); cores\n {0: 3, 1: 3, 2: 3, 3: 3, 4: 2, 5: 2, 6: 3, 7: 1, 8: 3, 9: 3, 10: 3, 11: 3, 12: 3, 13: 3, 14: 2, 15: 3, 16: 3, 17: 3, 18: 3, 19: 3}\n sage: [v for v,c in cores.items() if c>=2] # the vertices in the 2-core\n [0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]\n\n Checking the 2-core of a random lobster is indeed the empty set::\n\n sage: g = graphs.RandomLobster(20,.5,.5)\n sage: ordering, core = g.cores(2)\n sage: len(core) == 0\n True\n \"\"\"\n self._scream_if_not_simple()\n # compute the degrees of each vertex\n degrees=self.degree(labels=True)\n\n # sort vertices by degree. Store in a list and keep track of\n # where a specific degree starts (effectively, the list is\n # sorted by bins).\n verts= sorted( degrees.keys(), key=lambda x: degrees[x])\n bin_boundaries=[0]\n curr_degree=0\n for i,v in enumerate(verts):\n if degrees[v]>curr_degree:\n bin_boundaries.extend([i]*(degrees[v]-curr_degree))\n curr_degree=degrees[v]\n vert_pos = dict((v,pos) for pos,v in enumerate(verts))\n # Set up initial guesses for core and lists of neighbors.\n core= degrees\n nbrs=dict((v,set(self.neighbors(v))) for v in self)\n # form vertex core building up from smallest\n for v in verts:\n\n # If all the vertices have a degree larger than k, we can\n # return our answer if k is not None\n if k is not None and core[v] >= k:\n return verts[:vert_pos[v]], verts[vert_pos[v]:]\n\n for u in nbrs[v]:\n if core[u] > core[v]:\n nbrs[u].remove(v)\n\n # cleverly move u to the end of the next smallest\n # bin (i.e., subtract one from the degree of u).\n # We do this by swapping u with the first vertex\n # in the bin that contains u, then incrementing\n # the bin boundary for the bin that contains u.\n pos=vert_pos[u]\n bin_start=bin_boundaries[core[u]]\n vert_pos[u]=bin_start\n vert_pos[verts[bin_start]]=pos\n verts[bin_start],verts[pos]=verts[pos],verts[bin_start]\n bin_boundaries[core[u]]+=1\n core[u] -= 1\n\n if k is not None:\n return verts, []\n\n if with_labels:\n return core\n else:\n return core.values()\n\n @doc_index(\"Leftovers\")\n def modular_decomposition(self):\n r\"\"\"\n Returns the modular decomposition of the current graph.\n\n .. NOTE::\n\n In order to use this method you must install the\n ``modular_decomposition`` optional package. See\n :mod:`sage.misc.package`.\n\n Crash course on modular decomposition:\n\n A module `M` of a graph `G` is a proper subset of its vertices\n such that for all `u \\in V(G)-M, v,w\\in M` the relation `u\n \\sim v \\Leftrightarrow u \\sim w` holds, where `\\sim` denotes\n the adjacency relation in `G`. Equivalently, `M \\subset V(G)`\n is a module if all its vertices have the same adjacency\n relations with each vertex outside of the module (vertex by\n vertex).\n\n Hence, for a set like a module, it is very easy to encode the\n information of the adjacencies between the vertices inside and\n outside the module -- we can actually add a new vertex `v_M`\n to our graph representing our module `M`, and let `v_M` be\n adjacent to `u\\in V(G)-M` if and only if some `v\\in M` (and\n hence all the vertices contained in the module) is adjacent to\n `u`. We can now independently (and recursively) study the\n structure of our module `M` and the new graph `G-M+\\{v_M\\}`,\n without any loss of information.\n\n Here are two very simple modules :\n\n * A connected component `C` (or the union of some --but\n not all-- of them) of a disconnected graph `G`, for\n instance, is a module, as no vertex of `C` has a\n neighbor outside of it.\n\n * An anticomponent `C` (or the union of some --but not\n all-- of them) of an non-anticonnected graph `G`, for\n the same reason (it is just the complement of the\n previous graph !).\n\n These modules being of special interest, the disjoint union of\n graphs is called a Parallel composition, and the complement of\n a disjoint union is called a Parallel composition. A graph\n whose only modules are singletons is called Prime.\n\n For more information on modular decomposition, in particular\n for an explanation of the terms \"Parallel,\" \"Prime\" and\n \"Serie,\" see the `Wikipedia article on modular decomposition\n <http://en.wikipedia.org/wiki/Modular_decomposition>`_.\n\n You may also be interested in the survey from Michel Habib and\n Christophe Paul entitled \"A survey on Algorithmic aspects of\n modular decomposition\" [HabPau10]_.\n\n OUTPUT:\n\n A pair of two values (recursively encoding the decomposition) :\n\n * The type of the current module :\n\n * ``\"Parallel\"``\n * ``\"Prime\"``\n * ``\"Serie\"``\n\n * The list of submodules (as list of pairs ``(type, list)``,\n recursively...) or the vertex's name if the module is a\n singleton.\n\n EXAMPLES:\n\n The Bull Graph is prime::\n\n sage: graphs.BullGraph().modular_decomposition() # optional -- modular_decomposition\n ('Prime', [3, 4, 0, 1, 2])\n\n The Petersen Graph too::\n\n sage: graphs.PetersenGraph().modular_decomposition() # optional -- modular_decomposition\n ('Prime', [2, 6, 3, 9, 7, 8, 0, 1, 5, 4])\n\n This a clique on 5 vertices with 2 pendant edges, though, has a more\n interesting decomposition ::\n\n sage: g = graphs.CompleteGraph(5)\n sage: g.add_edge(0,5)\n sage: g.add_edge(0,6)\n sage: g.modular_decomposition() # optional -- modular_decomposition\n ('Serie', [0, ('Parallel', [5, ('Serie', [1, 4, 3, 2]), 6])])\n\n ALGORITHM:\n\n This function uses a C implementation of a 2-step algorithm\n implemented by Fabien de Montgolfier [FMDec]_ :\n\n * Computation of a factorizing permutation [HabibViennot1999]_.\n\n * Computation of the tree itself [CapHabMont02]_.\n\n .. SEEALSO::\n\n - :meth:`is_prime` -- Tests whether a graph is prime.\n\n REFERENCE:\n\n .. [FMDec] Fabien de Montgolfier\n http://www.liafa.jussieu.fr/~fm/algos/index.html\n\n .. [HabibViennot1999] Michel Habib, Christiphe Paul, Laurent Viennot\n Partition refinement techniques: An interesting algorithmic tool kit\n International Journal of Foundations of Computer Science\n vol. 10 n2 pp.147--170, 1999\n\n .. [CapHabMont02] \\C. Capelle, M. Habib et F. de Montgolfier\n Graph decomposition and Factorising Permutations\n Discrete Mathematics and Theoretical Computer Sciences, vol 5 no. 1 , 2002.\n\n .. [HabPau10] Michel Habib and Christophe Paul\n A survey of the algorithmic aspects of modular decomposition\n Computer Science Review\n vol 4, number 1, pages 41--59, 2010\n http://www.lirmm.fr/~paul/md-survey.pdf\n \"\"\"\n try:\n from sage.graphs.modular_decomposition import modular_decomposition\n except ImportError:\n raise RuntimeError(\"In order to use this method you must \"\n \"install the modular_decomposition package\")\n\n self._scream_if_not_simple()\n from sage.misc.stopgap import stopgap\n stopgap(\"Graph.modular_decomposition is known to return wrong results\",13744)\n\n D = modular_decomposition(self)\n\n id_label = dict(enumerate(self.vertices()))\n\n relabel = lambda x : (x[0], [relabel(_) for _ in x[1]]) if isinstance(x,tuple) else id_label[x]\n\n return relabel(D)\n\n @doc_index(\"Graph properties\")\n def is_prime(self):\n r\"\"\"\n Tests whether the current graph is prime.\n\n A graph is prime if all its modules are trivial (i.e. empty, all of the\n graph or singletons) -- see :meth:`modular_decomposition`.\n\n .. NOTE::\n\n In order to use this method you must install the\n ``modular_decomposition`` optional package. See\n :mod:`sage.misc.package`.\n\n EXAMPLE:\n\n The Petersen Graph and the Bull Graph are both prime::\n\n sage: graphs.PetersenGraph().is_prime() # optional - modular_decomposition\n True\n sage: graphs.BullGraph().is_prime() # optional - modular_decomposition\n True\n\n Though quite obviously, the disjoint union of them is not::\n\n sage: (graphs.PetersenGraph() + graphs.BullGraph()).is_prime() # optional - modular_decomposition\n False\n \"\"\"\n\n D = self.modular_decomposition()\n\n return D[0] == \"Prime\" and len(D[1]) == self.order()\n\n @rename_keyword(deprecation=19550, method='algorithm')\n def _gomory_hu_tree(self, vertices, algorithm=None):\n r\"\"\"\n Return a Gomory-Hu tree associated to self.\n\n This function is the private counterpart of ``gomory_hu_tree()``,\n with the difference that it has an optional argument\n needed for recursive computations, which the user is not\n interested in defining himself.\n\n See the documentation of ``gomory_hu_tree()`` for more information.\n\n INPUT:\n\n - ``vertices`` - a set of \"real\" vertices, as opposed to the\n fakes one introduced during the computations. This variable is\n useful for the algorithm and for recursion purposes.\n\n - ``algorithm`` -- select the algorithm used by the :meth:`edge_cut`\n method. Refer to its documentation for allowed values and default\n behaviour.\n\n EXAMPLE:\n\n This function is actually tested in ``gomory_hu_tree()``, this\n example is only present to have a doctest coverage of 100%.\n\n sage: g = graphs.PetersenGraph()\n sage: t = g._gomory_hu_tree(frozenset(g.vertices()))\n \"\"\"\n self._scream_if_not_simple()\n\n # Small case, not really a problem ;-)\n if len(vertices) == 1:\n g = Graph()\n g.add_vertices(vertices)\n return g\n\n # Take any two vertices (u,v)\n it = iter(vertices)\n u,v = next(it),next(it)\n\n # Compute a uv min-edge-cut.\n #\n # The graph is split into U,V with u \\in U and v\\in V.\n flow,edges,[U,V] = self.edge_cut(u, v, use_edge_labels=True, vertices=True, algorithm=algorithm)\n\n # One graph for each part of the previous one\n gU,gV = self.subgraph(U, immutable=False), self.subgraph(V, immutable=False)\n\n # A fake vertex fU (resp. fV) to represent U (resp. V)\n fU = frozenset(U)\n fV = frozenset(V)\n\n # Each edge (uu,vv) with uu \\in U and vv\\in V yields:\n # - an edge (uu,fV) in gU\n # - an edge (vv,fU) in gV\n #\n # If the same edge is added several times their capacities add up.\n\n from sage.rings.real_mpfr import RR\n for uu,vv,capacity in edges:\n capacity = capacity if capacity in RR else 1\n\n # Assume uu is in gU\n if uu in V:\n uu,vv = vv,uu\n\n # Create the new edges if necessary\n if not gU.has_edge(uu, fV):\n gU.add_edge(uu, fV, 0)\n if not gV.has_edge(vv, fU):\n gV.add_edge(vv, fU, 0)\n\n # update the capacities\n gU.set_edge_label(uu, fV, gU.edge_label(uu, fV) + capacity)\n gV.set_edge_label(vv, fU, gV.edge_label(vv, fU) + capacity)\n\n # Recursion on each side\n gU_tree = gU._gomory_hu_tree(vertices & frozenset(gU), algorithm=algorithm)\n gV_tree = gV._gomory_hu_tree(vertices & frozenset(gV), algorithm=algorithm)\n\n # Union of the two partial trees\n g = gU_tree.union(gV_tree)\n\n # An edge to connect them, with the appropriate label\n g.add_edge(u, v, flow)\n\n return g\n\n @doc_index(\"Connectivity, orientations, trees\")\n @rename_keyword(deprecation=19550, method='algorithm')\n def gomory_hu_tree(self, algorithm=None):\n r\"\"\"\n Returns a Gomory-Hu tree of self.\n\n Given a tree `T` with labeled edges representing capacities, it is very\n easy to determine the maximum flow between any pair of vertices :\n it is the minimal label on the edges of the unique path between them.\n\n Given a graph `G`, a Gomory-Hu tree `T` of `G` is a tree\n with the same set of vertices, and such that the maximum flow\n between any two vertices is the same in `G` as in `T`. See the\n `Wikipedia article on Gomory-Hu tree <http://en.wikipedia.org/wiki/Gomory%E2%80%93Hu_tree>`_.\n Note that, in general, a graph admits more than one Gomory-Hu tree.\n\n See also 15.4 (Gomory-Hu trees) from [SchrijverCombOpt]_.\n\n INPUT:\n\n - ``algorithm`` -- select the algorithm used by the :meth:`edge_cut`\n method. Refer to its documentation for allowed values and default\n behaviour.\n\n OUTPUT:\n\n A graph with labeled edges\n\n EXAMPLE:\n\n Taking the Petersen graph::\n\n sage: g = graphs.PetersenGraph()\n sage: t = g.gomory_hu_tree()\n\n Obviously, this graph is a tree::\n\n sage: t.is_tree()\n True\n\n Note that if the original graph is not connected, then the\n Gomory-Hu tree is in fact a forest::\n\n sage: (2*g).gomory_hu_tree().is_forest()\n True\n sage: (2*g).gomory_hu_tree().is_connected()\n False\n\n On the other hand, such a tree has lost nothing of the initial\n graph connectedness::\n\n sage: all([ t.flow(u,v) == g.flow(u,v) for u,v in Subsets( g.vertices(), 2 ) ])\n True\n\n Just to make sure, we can check that the same is true for two vertices\n in a random graph::\n\n sage: g = graphs.RandomGNP(20,.3)\n sage: t = g.gomory_hu_tree()\n sage: g.flow(0,1) == t.flow(0,1)\n True\n\n And also the min cut::\n\n sage: g.edge_connectivity() == min(t.edge_labels())\n True\n\n TESTS:\n\n :trac:`16475`::\n\n sage: G = graphs.PetersenGraph()\n sage: for u,v in G.edge_iterator(labels=False):\n ....: G.set_edge_label(u, v, 1)\n sage: for u, v in [(0, 1), (0, 4), (0, 5), (1, 2), (1, 6), (3, 4), (5, 7), (5, 8)]:\n ....: G.set_edge_label(u, v, 2)\n sage: T = G.gomory_hu_tree()\n sage: from itertools import combinations\n sage: for u,v in combinations(G,2):\n ....: assert T.flow(u,v,use_edge_labels=True) == G.flow(u,v,use_edge_labels=True)\n \"\"\"\n if not self.is_connected():\n g = Graph()\n for cc in self.connected_components_subgraphs():\n g = g.union(cc._gomory_hu_tree(frozenset(cc.vertices()), algorithm=algorithm))\n else:\n g = self._gomory_hu_tree(frozenset(self.vertices()), algorithm=algorithm)\n\n if self.get_pos() is not None:\n g.set_pos(dict(self.get_pos()))\n return g\n\n @doc_index(\"Leftovers\")\n def two_factor_petersen(self):\n r\"\"\"\n Returns a decomposition of the graph into 2-factors.\n\n Petersen's 2-factor decomposition theorem asserts that any\n `2r`-regular graph `G` can be decomposed into 2-factors.\n Equivalently, it means that the edges of any `2r`-regular\n graphs can be partitionned in `r` sets `C_1,\\dots,C_r` such\n that for all `i`, the set `C_i` is a disjoint union of cycles\n ( a 2-regular graph ).\n\n As any graph of maximal degree `\\Delta` can be completed into\n a regular graph of degree `2\\lceil\\frac\\Delta 2\\rceil`, this\n result also means that the edges of any graph of degree `\\Delta`\n can be partitionned in `r=2\\lceil\\frac\\Delta 2\\rceil` sets\n `C_1,\\dots,C_r` such that for all `i`, the set `C_i` is a\n graph of maximal degree `2` ( a disjoint union of paths\n and cycles ).\n\n EXAMPLE:\n\n The Complete Graph on `7` vertices is a `6`-regular graph, so it can\n be edge-partitionned into `2`-regular graphs::\n\n sage: g = graphs.CompleteGraph(7)\n sage: classes = g.two_factor_petersen()\n sage: for c in classes:\n ....: gg = Graph()\n ....: gg.add_edges(c)\n ....: print(max(gg.degree())<=2)\n True\n True\n True\n sage: Set(set(classes[0]) | set(classes[1]) | set(classes[2])).cardinality() == g.size()\n True\n\n ::\n\n sage: g = graphs.CirculantGraph(24, [7, 11])\n sage: cl = g.two_factor_petersen()\n sage: g.plot(edge_colors={'black':cl[0], 'red':cl[1]})\n Graphics object consisting of 73 graphics primitives\n\n \"\"\"\n self._scream_if_not_simple()\n d = self.eulerian_orientation()\n\n # This new graph is bipartite, and built the following way :\n #\n # To each vertex v of the digraph are associated two vertices,\n # a sink (-1,v) and a source (1,v)\n # Any edge (u,v) in the digraph is then added as ((-1,u),(1,v))\n\n from sage.graphs.graph import Graph\n g = Graph()\n g.add_edges([((-1,u),(1,v)) for (u,v) in d.edge_iterator(labels=None)])\n\n # This new bipartite graph is now edge_colored\n from sage.graphs.graph_coloring import edge_coloring\n classes = edge_coloring(g)\n\n # The edges in the classes are of the form ((-1,u),(1,v))\n # and have to be translated back to (u,v)\n classes_b = []\n for c in classes:\n classes_b.append([(u,v) for ((uu,u),(vv,v)) in c])\n\n return classes_b\n\n @doc_index(\"Leftovers\")\n def kirchhoff_symanzik_polynomial(self, name='t'):\n \"\"\"\n Return the Kirchhoff-Symanzik polynomial of a graph.\n\n This is a polynomial in variables `t_e` (each of them representing an\n edge of the graph `G`) defined as a sum over all spanning trees:\n\n .. MATH::\n\n \\Psi_G(t) = \\sum_{\\substack{T\\subseteq V \\\\ \\text{a spanning tree}}} \\prod_{e \\\\not\\in E(T)} t_e\n\n This is also called the first Symanzik polynomial or the Kirchhoff\n polynomial.\n\n INPUT:\n\n - ``name``: name of the variables (default: ``'t'``)\n\n OUTPUT:\n\n - a polynomial with integer coefficients\n\n ALGORITHM:\n\n This is computed here using a determinant, as explained in Section\n 3.1 of [Marcolli2009]_.\n\n As an intermediate step, one computes a cycle basis `\\mathcal C` of\n `G` and a rectangular `|\\mathcal C| \\\\times |E(G)|` matrix with\n entries in `\\{-1,0,1\\}`, which describes which edge belong to which\n cycle of `\\mathcal C` and their respective orientations.\n\n More precisely, after fixing an arbitrary orientation for each edge\n `e\\in E(G)` and each cycle `C\\in\\mathcal C`, one gets a sign for\n every incident pair (edge, cycle) which is `1` if the orientation\n coincide and `-1` otherwise.\n\n EXAMPLES:\n\n For the cycle of length 5::\n\n sage: G = graphs.CycleGraph(5)\n sage: G.kirchhoff_symanzik_polynomial()\n t0 + t1 + t2 + t3 + t4\n\n One can use another letter for variables::\n\n sage: G.kirchhoff_symanzik_polynomial(name='u')\n u0 + u1 + u2 + u3 + u4\n\n For the 'coffee bean' graph::\n\n sage: G = Graph([(0,1,'a'),(0,1,'b'),(0,1,'c')],multiedges=True)\n sage: G.kirchhoff_symanzik_polynomial()\n t0*t1 + t0*t2 + t1*t2\n\n For the 'parachute' graph::\n\n sage: G = Graph([(0,2,'a'),(0,2,'b'),(0,1,'c'),(1,2,'d')], multiedges=True)\n sage: G.kirchhoff_symanzik_polynomial()\n t0*t1 + t0*t2 + t1*t2 + t1*t3 + t2*t3\n\n For the complete graph with 4 vertices::\n\n sage: G = graphs.CompleteGraph(4)\n sage: G.kirchhoff_symanzik_polynomial()\n t0*t1*t3 + t0*t2*t3 + t1*t2*t3 + t0*t1*t4 + t0*t2*t4 + t1*t2*t4\n + t1*t3*t4 + t2*t3*t4 + t0*t1*t5 + t0*t2*t5 + t1*t2*t5 + t0*t3*t5\n + t2*t3*t5 + t0*t4*t5 + t1*t4*t5 + t3*t4*t5\n\n REFERENCES:\n\n .. [Marcolli2009] Matilde Marcolli, Feynman Motives, Chapter 3,\n Feynman integrals and algebraic varieties,\n http://www.its.caltech.edu/~matilde/LectureN3.pdf\n\n .. [Brown2011] Francis Brown, Multiple zeta values and periods: From\n moduli spaces to Feynman integrals, in Contemporary Mathematics vol\n 539\n \"\"\"\n from sage.matrix.constructor import matrix\n from sage.rings.integer_ring import ZZ\n from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing\n\n edges = self.edges()\n cycles = self.cycle_basis(output='edge')\n\n edge2int = {e: j for j, e in enumerate(edges)}\n circuit_mtrx = matrix(ZZ, self.size(), len(cycles))\n for i, cycle in enumerate(cycles):\n for edge in cycle:\n if edge in edges:\n circuit_mtrx[edge2int[edge], i] = +1\n else:\n circuit_mtrx[edge2int[(edge[1], edge[0], edge[2])], i] = -1\n\n D = matrix.diagonal(PolynomialRing(ZZ, name, self.size()).gens())\n return (circuit_mtrx.transpose() * D * circuit_mtrx).determinant()\n\n @doc_index(\"Leftovers\")\n def magnitude_function(self):\n \"\"\"\n Return the magnitude function of the graph as a rational function.\n\n This is defined as the sum of all coefficients in the inverse\n of the matrix `Z` whose coefficient `Z_{i,j}` indexed by a\n pair of vertices `(i,j)` is `q^d(i,j)` where `d` is the distance\n function in the graph.\n\n By convention, if the distance from `i` to `j` is infinite\n (for two vertices not path connected) then `Z_{i,j}=0`.\n\n The value of the magnitude function at `q=0` is the\n cardinality of the graph. The magnitude function of a disjoint\n union is the sum of the magnitudes functions of the connected\n components. The magnitude function of a Cartesian product is\n the product of the magnitudes functions of the factors.\n\n EXAMPLES::\n\n sage: g = Graph({1:[], 2:[]})\n sage: g.magnitude_function()\n 2\n\n sage: g = graphs.CycleGraph(4)\n sage: g.magnitude_function()\n 4/(q^2 + 2*q + 1)\n\n sage: g = graphs.CycleGraph(5)\n sage: m = g.magnitude_function(); m\n 5/(2*q^2 + 2*q + 1)\n\n One can expand the magnitude as a power series in `q` as follows::\n\n sage: q = QQ[['q']].gen()\n sage: m(q)\n 5 - 10*q + 10*q^2 - 20*q^4 + 40*q^5 - 40*q^6 + ...\n\n One can also use the substitution `q = exp(-t)` to obtain\n the magnitude function as a function of `t`::\n\n sage: g = graphs.CycleGraph(6)\n sage: m = g.magnitude_function()\n sage: t = var('t')\n sage: m(exp(-t))\n 6/(2*e^(-t) + 2*e^(-2*t) + e^(-3*t) + 1)\n\n TESTS::\n\n sage: g = Graph()\n sage: g.magnitude_function()\n 0\n\n sage: g = Graph({1:[]})\n sage: g.magnitude_function()\n 1\n\n sage: g = graphs.PathGraph(4)\n sage: g.magnitude_function()\n (-2*q + 4)/(q + 1)\n\n REFERENCES:\n\n .. [Lein] Tom Leinster, *The magnitude of metric spaces*.\n Doc. Math. 18 (2013), 857-905.\n \"\"\"\n from sage.matrix.constructor import matrix\n from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing\n from sage.graphs.distances_all_pairs import distances_all_pairs\n\n ring = PolynomialRing(ZZ, 'q')\n q = ring.gen()\n N = self.order()\n if not N:\n return ring.zero()\n dist = distances_all_pairs(self)\n vertices = list(self)\n Z = matrix(ring, N, N, ring.zero())\n for i in range(N):\n Z[i, i] = ring.one()\n for i in range(N):\n for j in range(i):\n dij = dist[vertices[i]][vertices[j]]\n if dij in ZZ:\n Z[i, j] = Z[j, i] = q ** dij\n else:\n Z[i, j] = Z[j, i] = ring.zero()\n return sum(sum(u) for u in ~Z)\n\n @doc_index(\"Leftovers\")\n def ihara_zeta_function_inverse(self):\n \"\"\"\n Compute the inverse of the Ihara zeta function of the graph.\n\n This is a polynomial in one variable with integer coefficients. The\n Ihara zeta function itself is the inverse of this polynomial.\n\n See :wikipedia:`Ihara zeta function`.\n\n ALGORITHM:\n\n This is computed here as the (reversed) characteristic\n polynomial of a square matrix of size twice the number of edges,\n related to the adjacency matrix of the line graph, see for example\n Proposition 9 in [ScottStorm]_ and Def. 4.1 in [Terras]_.\n\n The graph is first replaced by its 2-core, as this does not change\n the Ihara zeta function.\n\n EXAMPLES::\n\n sage: G = graphs.CompleteGraph(4)\n sage: factor(G.ihara_zeta_function_inverse())\n (2*t - 1) * (t + 1)^2 * (t - 1)^3 * (2*t^2 + t + 1)^3\n\n sage: G = graphs.CompleteGraph(5)\n sage: factor(G.ihara_zeta_function_inverse())\n (-1) * (3*t - 1) * (t + 1)^5 * (t - 1)^6 * (3*t^2 + t + 1)^4\n\n sage: G = graphs.PetersenGraph()\n sage: factor(G.ihara_zeta_function_inverse())\n (-1) * (2*t - 1) * (t + 1)^5 * (t - 1)^6 * (2*t^2 + 2*t + 1)^4\n * (2*t^2 - t + 1)^5\n\n sage: G = graphs.RandomTree(10)\n sage: G.ihara_zeta_function_inverse()\n 1\n\n REFERENCES:\n\n .. [HST] Matthew D. Horton, H. M. Stark, and Audrey A. Terras,\n What are zeta functions of graphs and what are they good for?\n in Quantum graphs and their applications, 173-189,\n Contemp. Math., Vol. 415\n\n .. [Terras] Audrey Terras, Zeta functions of graphs: a stroll through\n the garden, Cambridge Studies in Advanced Mathematics, Vol. 128\n\n .. [ScottStorm] Geoffrey Scott and Christopher Storm, The coefficients\n of the Ihara zeta function, Involve (http://msp.org/involve/2008/1-2/involve-v1-n2-p08-p.pdf)\n \"\"\"\n from sage.matrix.constructor import matrix\n\n H = self.subgraph(vertices=self.cores(k=2)[1])\n E = H.edges()\n m = len(E)\n # compute (Hashimoto) edge matrix T\n T = matrix(ZZ, 2 * m, 2 * m, 0)\n for i in range(m):\n for j in range(m):\n if i != j:\n if E[i][1] == E[j][0]: # same orientation\n T[2 * i, 2 * j] = 1\n T[2 * j + 1, 2 * i + 1] = 1\n elif E[i][1] == E[j][1]: # opposite orientation (towards)\n T[2 * i, 2 * j + 1] = 1\n T[2 * j, 2 * i + 1] = 1\n elif E[i][0] == E[j][0]: # opposite orientation (away)\n T[2 * i + 1, 2 * j] = 1\n T[2 * j + 1, 2 * i] = 1\n return T.charpoly('t').reverse()\n\n @doc_index(\"Leftovers\")\n def perfect_matchings(self, labels=False):\n \"\"\"\n Return an interator over all perfect matchings of the graph.\n\n ALGORITHM:\n\n Choose a vertex `v`, then recurse through all edges incident to `v`,\n removing one edge at a time whenever an edge is added to a matching.\n\n INPUT:\n\n - ``labels`` -- boolean (default: ``False``); when ``True``, the\n edges in each perfect matching are triples (containing the label\n as the third element), otherwise the edges are pairs\n\n .. SEEALSO::\n\n :meth:`matching`\n\n EXAMPLES::\n\n sage: G=graphs.GridGraph([2,3])\n sage: list(G.perfect_matchings())\n [[((0, 0), (0, 1)), ((0, 2), (1, 2)), ((1, 0), (1, 1))],\n [((0, 1), (0, 2)), ((1, 1), (1, 2)), ((0, 0), (1, 0))],\n [((0, 1), (1, 1)), ((0, 2), (1, 2)), ((0, 0), (1, 0))]]\n\n sage: G = graphs.CompleteGraph(4)\n sage: list(G.perfect_matchings(labels=True))\n [[(0, 1, None), (2, 3, None)],\n [(0, 2, None), (1, 3, None)],\n [(0, 3, None), (1, 2, None)]]\n\n sage: G = Graph([[1,-1,'a'], [2,-2, 'b'], [1,-2,'x'], [2,-1,'y']])\n sage: list(G.perfect_matchings(labels=True))\n [[(-2, 1, 'x'), (-1, 2, 'y')],\n [(-1, 1, 'a'), (-2, 2, 'b')]]\n\n sage: G = graphs.CompleteGraph(8)\n sage: mpc = G.matching_polynomial().coefficients(sparse=False)[0]\n sage: len(list(G.perfect_matchings())) == mpc\n True\n\n sage: G = graphs.PetersenGraph().copy(immutable=True)\n sage: list(G.perfect_matchings())\n [[(0, 1), (2, 3), (4, 9), (6, 8), (5, 7)],\n [(0, 1), (2, 7), (3, 4), (5, 8), (6, 9)],\n [(0, 4), (1, 2), (3, 8), (6, 9), (5, 7)],\n [(0, 4), (1, 6), (2, 3), (5, 8), (7, 9)],\n [(0, 5), (1, 2), (3, 4), (6, 8), (7, 9)],\n [(0, 5), (1, 6), (2, 7), (3, 8), (4, 9)]]\n\n sage: list(Graph().perfect_matchings())\n [[]]\n\n sage: G = graphs.CompleteGraph(5)\n sage: list(G.perfect_matchings())\n []\n \"\"\"\n if not self:\n yield []\n return\n # if every connected component has an even number of vertices\n if all(len(cc) % 2 == 0 for cc in self.connected_components()):\n v = next(self.vertex_iterator())\n for e in self.edges_incident(v, labels=labels):\n Gp = self.copy(immutable=False)\n Gp.delete_vertices([e[0], e[1]])\n for mat in Gp.perfect_matchings(labels):\n yield [e] + mat\n\n\n# Aliases to functions defined in Cython modules\nimport types\n\nimport sage.graphs.weakly_chordal\nGraph.is_long_hole_free = types.MethodType(sage.graphs.weakly_chordal.is_long_hole_free, None, Graph)\nGraph.is_long_antihole_free = types.MethodType(sage.graphs.weakly_chordal.is_long_antihole_free, None, Graph)\nGraph.is_weakly_chordal = types.MethodType(sage.graphs.weakly_chordal.is_weakly_chordal, None, Graph)\n\nimport sage.graphs.asteroidal_triples\nGraph.is_asteroidal_triple_free = types.MethodType(sage.graphs.asteroidal_triples.is_asteroidal_triple_free, None, Graph)\n\nimport sage.graphs.chrompoly\nGraph.chromatic_polynomial = types.MethodType(sage.graphs.chrompoly.chromatic_polynomial, None, Graph)\n\nimport sage.graphs.graph_decompositions.rankwidth\nGraph.rank_decomposition = types.MethodType(sage.graphs.graph_decompositions.rankwidth.rank_decomposition, None, Graph)\n\nimport sage.graphs.matchpoly\nGraph.matching_polynomial = types.MethodType(sage.graphs.matchpoly.matching_polynomial, None, Graph)\n\nimport sage.graphs.cliquer\nGraph.cliques_maximum = types.MethodType(sage.graphs.cliquer.all_max_clique, None, Graph)\n\nimport sage.graphs.spanning_tree\nGraph.random_spanning_tree = types.MethodType(sage.graphs.spanning_tree.random_spanning_tree, None, Graph)\n\nimport sage.graphs.graph_decompositions.graph_products\nGraph.is_cartesian_product = types.MethodType(sage.graphs.graph_decompositions.graph_products.is_cartesian_product, None, Graph)\n\nimport sage.graphs.distances_all_pairs\nGraph.is_distance_regular = types.MethodType(sage.graphs.distances_all_pairs.is_distance_regular, None, Graph)\n\nimport sage.graphs.base.static_dense_graph\nGraph.is_strongly_regular = types.MethodType(sage.graphs.base.static_dense_graph.is_strongly_regular, None, Graph)\n\n# From Python modules\nimport sage.graphs.line_graph\nGraph.is_line_graph = sage.graphs.line_graph.is_line_graph\n\nfrom sage.graphs.tutte_polynomial import tutte_polynomial\nGraph.tutte_polynomial = tutte_polynomial\n\nfrom sage.graphs.lovasz_theta import lovasz_theta\nGraph.lovasz_theta = lovasz_theta\n\nfrom sage.graphs.partial_cube import is_partial_cube\nGraph.is_partial_cube = is_partial_cube\n\n_additional_categories = {\n Graph.is_long_hole_free : \"Graph properties\",\n Graph.is_long_antihole_free : \"Graph properties\",\n Graph.is_weakly_chordal : \"Graph properties\",\n Graph.is_asteroidal_triple_free : \"Graph properties\",\n Graph.chromatic_polynomial : \"Algorithmically hard stuff\",\n Graph.rank_decomposition : \"Algorithmically hard stuff\",\n Graph.matching_polynomial : \"Algorithmically hard stuff\",\n Graph.cliques_maximum : \"Clique-related methods\",\n Graph.random_spanning_tree : \"Connectivity, orientations, trees\",\n Graph.is_cartesian_product : \"Graph properties\",\n Graph.is_distance_regular : \"Graph properties\",\n Graph.is_strongly_regular : \"Graph properties\",\n Graph.is_line_graph : \"Graph properties\",\n Graph.is_partial_cube : \"Graph properties\",\n Graph.tutte_polynomial : \"Algorithmically hard stuff\",\n Graph.lovasz_theta : \"Leftovers\",\n }\n\n__doc__ = __doc__.replace(\"{INDEX_OF_METHODS}\",gen_thematic_rest_table_index(Graph,_additional_categories))\n","sub_path":"sage/src/sage/graphs/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":264548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"233290738","text":"import numpy as np\nimport scipy.linalg as la\nimport matplotlib.pyplot as plt\nimport time\nimport os\n\n'''QUESTION 1'''\nm = 10\nnum_iterations = 250\nA = np.random.randn(m,m)\nA_symm = ( (A + A.T) / 2 )\ncond = np.linalg.cond(A_symm)\n\n# while cond < 10e-16:\n# A = np.random.randn(m,m)\n# A_symm = ( (A + A.T) / 2 )\n# cond = la.cond(A_symm)\n\napprox_vals = []\napprox_vals_real = []\napprox_vals_imag = []\nerror_vecs = []\nerror_vals = []\n\neigvals_truth, eigvecs_truth = la.eig(A_symm)\neigvals_truth = np.abs(eigvals_truth)\n\nidx = eigvals_truth.argsort()[::-1]\neigvals_truth = eigvals_truth[idx]\neigvecs_truth = eigvecs_truth[:, idx]\n\nmax_eigval_truth = eigvals_truth[0]\nmax_eigvec_truth = eigvecs_truth[:, 0]\n\n# Convergence ratio. If equal to one, power iteration will not converge.\nconvergence_ratio = np.abs(eigvals_truth[1] / eigvals_truth[0])**2\n# convergence_ratio = np.abs(eigvals_truth[1] / eigvals_truth[0])\n\nif convergence_ratio > 0.98:\n print('Does not converge!')\n exit()\n # raise('Input Error')\nelse:\n print('\\nConvergence ratio\\n----------------------\\n', convergence_ratio)\n\n# Power iteration algorithm\n\n# \"first guess\" eigenvector\n# v = np.random.randn(A_symm.shape[1])\nv0 = np.random.rand(A.shape[1])\nv = v0\n\nmax_eigval_approx = v.T @ ( A_symm @ v ) # (1,m) * (m,m) * (m,1) = (1,1)\napprox_vals.append(max_eigval_approx)\n\n\n# normalize first guess\nv = v / la.norm(v)\n\nfor _ in range(num_iterations):\n\n # calculating next eigenvector approximation\n v_next = A_symm @ v # (m,1)\n\n # calculate norm\n v_next_norm = la.norm(v_next, 2)\n\n # normalizing eigenvector approximation\n v = v_next / v_next_norm # (m,1)\n max_eigval_approx = v.T @ ( A_symm @ v ) # (1,m) * (m,m) * (m,1) = (1,1)\n\n # print(max_eigval_approx)\n approx_vals.append(max_eigval_approx)\n approx_vals_real.append(max_eigval_approx.real)\n approx_vals_imag.append(max_eigval_approx.imag)\n # error_vecs.append(la.norm(np.abs(v) - np.abs(max_eigvec_truth), 2))\n # print(max_eigval_approx)\n # print(la.norm(v - max_eigvec_truth, 2))\n # error_vals.append(np.abs(max_eigval_approx) - np.abs(max_eigval_truth))\n\n# print('\\nGround truth max eigvec\\n----------------------\\n', max_eigvec_truth)\n# print(f'\\nApproximate max eigvec after {num_iterations} iterations\\n----------------------\\n', v)\n\nprint('\\nGround truth max eigval\\n----------------------\\n', max_eigval_truth)\nprint(f'\\nApproximate max eigval after {num_iterations} iterations\\n----------------------\\n', max_eigval_approx)\n\n\n# print(max_eig_approx)\n\n# X,Y = np.meshgrid(m,m)\n# plt.plot(error_vecs)\n# # plt.yscale('log')\n# plt.xlabel('Iteration')\n# plt.ylabel('Error')\n# plt.show()\n\n# plt.scatter(approx_vals_real, approx_vals_imag)\n# plt.show()\n#\nplt.plot(np.abs(approx_vals) - np.abs(max_eigval_truth))\n# plt.yscale('log')\nplt.title('Symmetric A, dominant eigenvalue approximation error: power iteration', fontsize=10)\nplt.xlabel('Iteration')\nplt.ylabel('Error')\n# plt.savefig(os.getcwd() + '/hw5q1pd.png', bbox_inches='tight')\nplt.show()\n\n'''Rayleigh Quotient iteration'''\nerr_thresh = 10e-8 # error threshold for eigenvalue approx\n\nprint('\\nA = ')\nprint(A_symm)\n\nrqiter_eigval_approx = []\n\n# v1 = v0 + 4\n# v2 = v0 + 6\n\ndef allUnique(x): # checks for uniqueness\n seen = set()\n return not any(i in seen or seen.add(i) for i in x)\n\ntimeout = time.time() + 60*5 # 5 minutes from now\nwhile len(rqiter_eigval_approx) < m:\n while allUnique(rqiter_eigval_approx) == True:\n\n if time.time() > timeout:\n break\n\n v = np.random.randn(A_symm.shape[1]) # set initial eigenvector guess\n lambda0 = v.T @ A_symm @ v # first eigenvalue approximation\n\n lam = lambda0 # set initial eigenvalue guess\n eigval_guesses = [lam]\n eigvec_guesses = [v]\n # realizations = 10\n # for i in range(m): # isolating different direction of initial guess vector\n # v0 = np.zeros(A_symm.shape[1])\n # v0[i] = 1\n # v = v0 # set initial eigenvector guess\n\n # print('\\n Eigenvectors: ', eigvecs_truth)\n # print('\\nStarting guess v: ', v)\n # print(' ')\n\n print('\\nEigenvalues: ', eigvals_truth)\n print('\\nStarting guess lambda: ', lambda0)\n print(' ')\n\n # print(f'\\ni = 0, lambda = {lambda0}')\n\n for i in range(1, num_iterations):\n B = A_symm - lam*np.eye(m)\n try:\n omega = la.solve(B, v)\n except:\n print(\"Matrix is singular! Converged solution\")\n break\n\n v = omega / la.norm(omega, 2)\n lam = v.T @ ( A_symm @ v )\n # print(f'i = {i}, lambda = {lam}')\n eigval_guesses.append(lam)\n eigvec_guesses.append(v)\n error = np.abs(eigval_guesses[-1] - eigval_guesses[-2])\n\n rqiter_eigval_approx.append(np.round(np.abs(eigval_guesses[-1]), 8))\n print('\\nEigenvalue approximation: ', eigval_guesses[-1])\n\n if allUnique(rqiter_eigval_approx) == False:\n del rqiter_eigval_approx[-1]\n else:\n plt.plot(eigval_guesses)\n # plt.yscale('log')\n plt.title(f'Eigenvalue approximation: Rayleigh Quotient iteration', fontsize=10)\n plt.xlabel('Iteration')\n plt.ylabel('Guess')\n plt.savefig(os.getcwd() + f'/hw5q1pc{len(rqiter_eigval_approx)}.png', bbox_inches='tight')\n plt.show\n\nprint('\\nEigenvalues: ', eigvals_truth)\nprint('\\n Eigenvalue Approximations: ', rqiter_eigval_approx)\n","sub_path":"hw5/hw5q1.py","file_name":"hw5q1.py","file_ext":"py","file_size_in_byte":5523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"622514679","text":"import re\nfrom datetime import time, datetime, timedelta\n\nimport dateutil.parser\nimport requests\nfrom django.conf import settings\nfrom django.db import models\nfrom django.db.models import Avg, Q\nfrom django.urls import reverse\nfrom django_google_maps import fields as map_fields\nfrom imagekit.models import ImageSpecField\nfrom pilkit.processors import ResizeToFill\nfrom rest_framework.exceptions import ValidationError, ParseError\nfrom rest_framework.generics import get_object_or_404\n\nfrom utils.custom_imagefield import CustomImageField\n\nCHOICES_RESTAURANT_TYPE = (\n ('kor', 'Korean'),\n ('chn', 'Chinese'),\n ('jpn', 'Japanese'),\n ('mex', 'Mexican'),\n ('amc', 'American'),\n ('tha', 'Thai'),\n ('med', 'Mediterranean'),\n ('ita', 'Italian'),\n ('vtn', 'Vietnamese'),\n ('spn', 'Spanish'),\n ('ind', 'Indian'),\n ('etc', 'Etc'),\n)\nCHOICES_PRICE = (\n ('c', 'Cheap'),\n ('n', 'Normal'),\n ('e', 'Expensive'),\n ('v', 'Very Expensive'),\n)\nCONVERT_TO_PRICE = {\n 'c': 10000,\n 'n': 15000,\n 'e': 20000,\n 'v': 40000,\n}\nCHOICES_TIME = (\n (time(9, 00, 00), '9시'),\n (time(10, 00, 00), '10시'),\n (time(11, 00, 00), '11시'),\n (time(12, 00, 00), '12시'),\n (time(13, 00, 00), '13시'),\n (time(14, 00, 00), '14시'),\n (time(15, 00, 00), '15시'),\n (time(16, 00, 00), '16시'),\n (time(17, 00, 00), '17시'),\n (time(18, 00, 00), '18시'),\n (time(19, 00, 00), '19시'),\n (time(20, 00, 00), '20시'),\n (time(21, 00, 00), '21시'),\n)\n\nSTAR_RATING = (\n (0, 0),\n (0.5, 0.5),\n (1, 1),\n (1.5, 1.5),\n (2, 2),\n (2.5, 2.5),\n (3, 3),\n (3.5, 3.5),\n (4, 4),\n (4.5, 4.5),\n (5, 5),\n)\n\n\n# 이름 리뷰 평점 즐겨찾기 토글, 소개, 메뉴, 음식 사진, 주소, 전화번호, 영업 시간, 가격대 <\n# 평점 토글, 댓글 <\n# 예약 <\n\nclass Restaurant(models.Model):\n name = models.CharField(max_length=20)\n strip_name = models.CharField(max_length=20, null=False, blank=True)\n address = map_fields.AddressField(max_length=200)\n district = models.CharField(null=False, blank=True, max_length=20)\n geolocation = map_fields.GeoLocationField(max_length=100)\n # fixme 연락처 정규표현식으로 만들기\n contact_number = models.CharField(max_length=11)\n joined_date = models.DateField(auto_now_add=True)\n description = models.TextField()\n restaurant_type = models.CharField(max_length=3, choices=CHOICES_RESTAURANT_TYPE)\n average_price = models.CharField(max_length=1, choices=CHOICES_PRICE)\n main_image = CustomImageField(upload_to='thumbnail', blank=True, default_static_image='testimage/test1.png')\n main_image_thumbnail = ImageSpecField(source='main_image',\n processors=[ResizeToFill(440, 200)],\n format='JPEG',\n options={'quality': 60})\n business_hours = models.CharField(max_length=100)\n star_rate = models.DecimalField(null=False, blank=True, default=0, decimal_places=1, max_digits=2)\n maximum_party = models.PositiveIntegerField()\n owner = models.ForeignKey('accounts.User')\n\n class Meta:\n ordering = (\n '-joined_date',\n 'pk'\n )\n\n def __str__(self):\n return self.name\n\n def save(self, *args, **kwargs):\n if not self.district:\n # Google goecoding에 검색할 parameter값 지정\n params = {\n 'address': self.address,\n 'language': 'ko'\n }\n res = requests.get(settings.GOOGLE_MAPS_API_URL, params=params).json()\n # 반환되는 값에서 구가 들어오는 위치의 값 추출(정상적으로 입력하였을 경우)\n district = res['results'][0]['address_components'][2]['long_name']\n # 정규표현식으로 추출하여 '구'로 끝나는지 값을 찾아 re_district에 저장\n re_district = re.search('\\w{2,3}구', district)\n # None Type일 경우 즉, 정규표현식에서 '구'로 끝나는 값을 찾지 못했을 경우 ValueError를 일으킴\n if re_district is None:\n raise ValueError('구 입력이 정상적이지 않습니다.')\n self.district = re_district.group()\n if not self.strip_name:\n self.strip_name = self.name.replace(' ', '').lower()\n return super().save(*args, **kwargs)\n\n def get_absolute_url(self):\n return reverse('restaurants:detail:restaurant-detail', kwargs={'pk': self.pk})\n\n def get_favorites_count(self):\n return self.favorite_set.count()\n\n # 댓글 작성시 호출됨\n def calculate_goten_star_rate(self):\n queryset = Comment.objects.filter(restaurant=self)\n # 쿼리셋의 aggregation기능을 사용해 평균값을 계산\n star_rate = queryset.aggregate(Avg('star_rate'))\n # aggregation은 딕셔너리 형태로 나오므로 키값을 넣어 value를 star_rate에 넣고 저장\n self.star_rate = star_rate['star_rate__avg']\n self.save()\n\n @classmethod\n def get_filtered_list(cls, filter_fields):\n queryset = cls.objects.all()\n # View에서 받아온 딕셔너리의 Key를 순회\n for filter_field in filter_fields.keys():\n # 딕셔너리를 순회하면서 해당 값의 value가 None객체가 아닐 경우 filter에 추가\n if filter_fields[filter_field] is not None:\n queryset = queryset.filter(**{filter_field: filter_fields[filter_field]})\n # filter된 쿼리셋 반환 필터가 없을경우(Querystring으로 객체를 받아 오지 못한경우) Restaurant.objects.all() 반환\n return queryset\n\n @classmethod\n def get_searched_list(cls, q):\n # 무엇을 검색가능하도록 할지, type은 어떻게 할지 수정 필요\n q = q.replace(\" \", '').lower()\n queryset = cls.objects.filter(\n Q(strip_name__icontains=q) |\n Q(district__icontains=q)\n )\n return queryset\n\n\nclass ImageForRestaurant(models.Model):\n image = CustomImageField(upload_to='restaurant', blank=True, default_static_image='testimage/test1.png')\n restaurant = models.ForeignKey('Restaurant', related_name='images', on_delete=models.CASCADE)\n\n def __str__(self):\n return f'{self.restaurant} - {self.pk}'\n\n\nclass MenuImages(models.Model):\n image = CustomImageField(upload_to='menu', blank=True, default_static_image='testimage/test1.png')\n restaurant = models.ForeignKey('Restaurant', related_name='menu')\n\n\nclass ReservationInfo(models.Model):\n restaurant = models.ForeignKey('Restaurant', related_name='reservation_info', on_delete=models.CASCADE)\n acceptable_size_of_party = models.IntegerField(null=False, blank=True)\n price = models.PositiveIntegerField(null=False, blank=True)\n time = models.TimeField(choices=CHOICES_TIME)\n date = models.DateField()\n\n def __str__(self):\n return f'{self.restaurant} - [{self.date}-{self.time}]'\n\n def save(self, *args, **kwargs):\n if not self.pk:\n if ReservationInfo.objects.filter(restaurant=self.restaurant, time=self.time, date=self.date).count():\n raise ValueError('This ReservationInfo is already exist')\n # acceptable_size_of_party에 값이 없을 경우 자동으로 restaurant.maximum_party에서 값을 받아와서 저장\n if self.acceptable_size_of_party is None:\n self.acceptable_size_of_party = self.restaurant.maximum_party\n self.price = CONVERT_TO_PRICE[self.restaurant.average_price]\n return super().save(*args, **kwargs)\n\n def calculate_price(self, party):\n if party.isdigit() and party <= self.acceptable_size_of_party:\n return self.price * party\n raise ValidationError\n\n # 예약시 호출하여 해당 시간의 허용 가능한 인원수를 수정할수 있게 할 수 있는 메서드생성\n def acceptable_size_of_party_update(self, party):\n if isinstance(party, int):\n self.acceptable_size_of_party -= party\n self.save()\n return True\n raise ValidationError('party가 int 형식이 아닙니다.')\n\n # CheckOpenedTimeView의 get_queryset에서 호출하여 valid한지 검증 valid하지 않을 경우 None 반환\n # fixme 리팩토링 필요\n # @classmethod\n # def check_acceptable_time(cls, res_pk, party, date):\n # restaurant = get_object_or_404(Restaurant, pk=res_pk)\n # # string으로 온 date값을 python에서 사용하는 datetime type으로 파싱 진행\n # # 파싱을 진행하며 잘못된 값이 올 경우 None객체 반환\n # try:\n # parsed_date = dateutil.parser.parse(date)\n # except ValueError:\n # parsed_date = None\n # except TypeError:\n # parsed_date = None\n # try:\n # if date != parsed_date.strftime('%Y-%m-%d'):\n # raise ParseError('date의 형식이 맞지 않습니다.')\n # except AttributeError:\n # raise ParseError('date의 형식이 맞지 않습니다.')\n # # 모든 parameter가 정상적인 경우 필터된 객체를 반환\n # # party가 숫자가 아닌경우, parsed_date가 datetime type이 아닌 경우 None객체를 반환\n # if not party and parsed_date is None:\n # return None\n # # 금일보다 적은 날짜인지 비교를 위해 datetime.now(UTC)에서 9시간을 더 한(한국시간)시간을 불러와 원하는 형식인 YYYY-MM-DD형식으로 변경후 datetime 형태로 다시 파싱\n # # 검색했던 날짜가 파싱된 datetime.now와 비교하여 작은경우(오늘보다 이전인경우) 검색이 되지 않도록 변경\n # now_date = datetime.now() + timedelta(hours=9)\n # parsed_now_date = dateutil.parser.parse(now_date.strftime('%Y-%m-%d'))\n # if parsed_date < parsed_now_date:\n # raise ParseError('date가 오늘보다 이전입니다.')\n # try:\n # party.isdigit()\n # except AttributeError:\n # return None\n #\n # if party and parsed_date:\n # if parsed_date.date() == now_date.date():\n # return cls.objects.filter(\n # restaurant=restaurant,\n # acceptable_size_of_party__gte=party,\n # date=parsed_date,\n # time__hour__gt=now_date.hour,\n # )\n # else:\n # return cls.objects.filter(\n # restaurant=restaurant,\n # acceptable_size_of_party__gte=party,\n # date=parsed_date,\n # )\n # return None\n @classmethod\n def check_acceptable_time(cls, res_pk, date):\n restaurant = get_object_or_404(Restaurant, pk=res_pk)\n # string으로 온 date값을 python에서 사용하는 datetime type으로 파싱 진행\n # 파싱을 진행하며 잘못된 값이 올 경우 None객체 반환\n try:\n parsed_date = dateutil.parser.parse(date)\n except ValueError:\n parsed_date = None\n except TypeError:\n parsed_date = None\n try:\n if date != parsed_date.strftime('%Y-%m-%d'):\n raise ParseError('date의 형식이 맞지 않습니다.')\n except AttributeError:\n raise ParseError('date의 형식이 맞지 않습니다.')\n # 모든 parameter가 정상적인 경우 필터된 객체를 반환\n # party가 숫자가 아닌경우, parsed_date가 datetime type이 아닌 경우 None객체를 반환\n if parsed_date is None:\n return None\n # 금일보다 적은 날짜인지 비교를 위해 datetime.now(UTC)에서 9시간을 더 한(한국시간)시간을 불러와 원하는 형식인 YYYY-MM-DD형식으로 변경후 datetime 형태로 다시 파싱\n # 검색했던 날짜가 파싱된 datetime.now와 비교하여 작은경우(오늘보다 이전인경우) 검색이 되지 않도록 변경\n now_date = datetime.now() + timedelta(hours=9)\n parsed_now_date = dateutil.parser.parse(now_date.strftime('%Y-%m-%d'))\n\n if parsed_date < parsed_now_date:\n raise ParseError('date가 오늘보다 이전입니다.')\n\n if parsed_date:\n if parsed_date.date() == now_date.date():\n return cls.objects.filter(\n restaurant=restaurant,\n date=parsed_date,\n time__hour__gt=now_date.hour,\n )\n else:\n return cls.objects.filter(\n restaurant=restaurant,\n date=parsed_date,\n )\n return None\n\n\nclass Comment(models.Model):\n author = models.ForeignKey('accounts.User')\n restaurant = models.ForeignKey('Restaurant', related_name='comments', on_delete=models.CASCADE)\n star_rate = models.FloatField(choices=STAR_RATING)\n comment = models.CharField(max_length=120)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n class Meta:\n ordering = ('created_at', 'pk')\n\n def __str__(self):\n return f'{self.author.email} - {self.restaurant} [{self.created_at}]'\n","sub_path":"zinzi/restaurants/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":13362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"199565628","text":"import shortuuid\nfrom flask import g, request, jsonify\nfrom flask.views import MethodView\nfrom sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound\n\nfrom mdcs_remote.web import application\nfrom mdcs_remote.models import Control, ControlType, ButtonControl, ColorControl\nfrom mdcs_remote.schema import Control as ControlSchema\nfrom mdcs_remote.schema import ButtonControl as ButtonControlSchema\nfrom mdcs_remote.schema import ColorControl as ColorControlSchema\n\n\nclass ControlList(MethodView):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.schema = ControlSchema()\n self.button_schema = ButtonControlSchema()\n self.color_schema = ColorControlSchema()\n\n def get(self):\n return jsonify(self.schema.dump(g.db.query(Control).all(), many=True).data)\n\n def post(self):\n # create the control\n control_data, errors = self.schema.load(request.json)\n if errors:\n return jsonify(errors), 400\n\n if control_data['type'] == ControlType.BUTTON:\n if 'button' not in control_data:\n return jsonify({'button': [\"Missing data for required field.\"]}), 400\n\n button_data = control_data.pop('button')\n control_data.update(button_data)\n\n control = ButtonControl(**control_data)\n control.uuid = shortuuid.uuid()\n\n elif control_data['type'] == ControlType.COLOR:\n if 'color' not in control_data:\n return jsonify({'color': [\"Missing data for required field.\"]}), 400\n\n color_data = control_data.pop('color')\n control_data.update(color_data)\n\n control = ColorControl(**control_data)\n control.uuid = shortuuid.uuid()\n\n else:\n return \"invalid control type: {0}\".format(control.type.name), 400\n\n g.db.add(control)\n g.db.commit()\n\n # return the newly created instance\n return jsonify(self.schema.dump(control).data)\n\n\nclass ControlDetail(MethodView):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.schema = ControlSchema()\n self.button_schema = ButtonControlSchema()\n self.color_schema = ColorControlSchema()\n\n def dispatch_request(self, uuid):\n try:\n control = g.db.query(Control).filter(Control.uuid == uuid).one()\n\n except NoResultFound:\n return 'control does not exist', 404\n\n except MultipleResultsFound:\n return 'multiple results found', 500\n\n return super().dispatch_request(control)\n\n def get(self, control):\n return jsonify(self.schema.dump(control).data)\n\n def put(self, control):\n updates, errors = self.schema.load(request.json, partial=True)\n if errors:\n return jsonify(errors), 400\n\n # control type can't be changed once it's been created\n updates.pop('type', None)\n\n # pull out specialized control fields and merge into top-level fields\n button_updates = updates.pop('button', {})\n color_updates = updates.pop('color', {})\n\n if control.type == ControlType.BUTTON:\n updates.update(button_updates)\n\n elif control.type == ControlType.COLOR:\n updates.update(color_updates)\n\n # update and save the model\n for field, value in updates.items():\n setattr(control, field, value)\n\n g.db.add(control)\n g.db.commit()\n\n # return the updated instance\n return jsonify(self.schema.dump(control).data)\n\n def delete(self, control):\n g.db.delete(control)\n g.db.commit()\n\n return 'OK', 200\n","sub_path":"pkg/remote/mdcs_remote/views/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":3682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"390211251","text":"# In this problem we need to traverse binary tree level by level. When we see levels in binary tree, we need to think about bfs, because it is its logic: it first traverse all neighbors, before we go deeper. Here we also need to change direction on each level as well. So, algorithm is the following:\n\n# 1. We create queue, where we first put our root.\n# 2. result is to keep final result and direction, equal to 1 or -1 is direction of traverse.\n# 3. Then we start to traverse level by level: if we have k elements in queue currently, we remove them all and put their children instead. We continue to do this until our queue is empty. Meanwile we form level list and then add it to result, using correct direction and change direction after.\n\n# Complexity: \n# time complexity is O(n), where n is number of nodes in our binary tree. \n# Space complexity is also O(n), because our result has this size in the end. If we do not count output as additional space, then it will be O(w), where w is width of tree. It can be reduces to O(1) I think if we traverse levels in different order directly, but it is just not worth it.\n\n\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:\n if not root:\n return []\n \n ans, stack, direction = [], [root], 1\n \n while stack:\n level = []\n \n for i in range(len(stack)):\n node = stack.pop(0)\n level.append(node.val)\n \n if node.left: stack.append(node.left)\n if node.right: stack.append(node.right)\n \n ans.append(level[::direction])\n direction *= -1\n \n return ans\n \n ","sub_path":"july-leetcoding-challenge/D22-BinaryTreeZigzagLevelOrderTraversal.py","file_name":"D22-BinaryTreeZigzagLevelOrderTraversal.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"398373586","text":"import os\nimport json\nfrom datetime import datetime\nfrom io import BytesIO\n\nimport torch\nimport clip\n\nimport httpx\nfrom PIL import Image\nfrom src.elasticsearch import get_prototype_elastic_client\nfrom src.source import yield_source_images, count_source_images\nfrom src.log import get_logger\nfrom tqdm import tqdm\n\n\nlog = get_logger()\nes = get_prototype_elastic_client()\n\n\nwith open(\"data/index_config/images.json\", \"r\", encoding=\"utf-8\") as f:\n index_config = json.load(f)\n\ntodays_date_iso = datetime.today().strftime(\"%Y-%m-%d\")\nindex_name = f\"images-clip-{todays_date_iso}\"\nif es.indices.exists(index=index_name):\n log.info(f\"Deleting index {index_name}\")\n es.indices.delete(index=index_name)\nlog.info(f\"Creating index {index_name}\")\nes.indices.create(index=index_name, **index_config)\n\nlog.info(\"Loading CLIP model\")\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\nmodel_name = os.environ[\"MODEL_NAME\"]\nmodel, preprocessor = clip.load(\n model_name, download_root=\"/data/models\", device=device\n)\n\nprogress_bar = tqdm(\n yield_source_images(pipeline_date=\"2023-03-29\"),\n total=count_source_images(pipeline_date=\"2023-03-29\"),\n)\n\nfor image_data in progress_bar:\n try:\n log.debug(\n f\"Processing image {image_data['id']} \"\n f\"{progress_bar.n}/{progress_bar.total}\"\n )\n progress_bar.set_description(f'Processing {image_data[\"id\"]}')\n\n # get the image\n iiif_url = image_data[\"thumbnail\"][\"url\"]\n thumbnail_url = iiif_url.replace(\n \"info.json\",\n \"full/!400,400/0/default.jpg\",\n )\n thumbnail = httpx.get(thumbnail_url, timeout=30).content\n image = Image.open(BytesIO(thumbnail))\n\n # get the embedding\n image_input = preprocessor(image).unsqueeze(0).to(device)\n with torch.no_grad():\n embedding = model.encode_image(image_input).squeeze(0)\n\n # make sure the embedding is of unit length so that we can use the\n # dot product similarity\n embedding /= embedding.norm(dim=-1, keepdim=True)\n\n # index the image\n document = {\n \"thumbnail_url\": thumbnail_url,\n \"image_id\": image_data[\"id\"],\n \"source_id\": image_data[\"source\"][\"id\"],\n \"title\": image_data[\"source\"][\"title\"],\n \"embedding\": embedding.tolist(),\n }\n\n es.index(index=index_name, document=document, id=image_data[\"id\"])\n except Exception as e:\n log.error(f\"Error processing image {image_data['id']}: {e}\")\n\n progress_bar.update(1)\n","sub_path":"clip-search/pipeline/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"563460408","text":"#!/usr/bin/env python\n\"\"\"\nRemove spaces at the end of every line,\nand make sure there is just one and only one empty line at the end the file.\n\nFor example:\n \"a line with some spaces \\r\\n\" => \"a line with some spaces\\n\"\n\"\"\"\nimport os\nimport re\n\n\nclass ContentException(Exception):\n pass\n\n\ndef rstrip_file(fname, newlines=1):\n try:\n with open(fname) as fp:\n s = fp.read()\n except UnicodeDecodeError:\n with open(fname, encoding=\"utf8\") as fp:\n s = fp.read()\n if not s:\n raise ContentException(\"Empty file.\")\n ss = [line.rstrip() for line in s.rstrip().split(\"\\n\")]\n n = os.linesep\n required = n.join(ss) + n * newlines\n with open(fname, \"rb\") as fp:\n byt = fp.read()\n new_byt = required.encode()\n if byt == new_byt:\n raise ContentException(\"Already meet requirement.\")\n with open(fname, \"wb\") as fp:\n fp.write(new_byt)\n\n\ndef is_hidden(dir_or_file):\n re_hidden = re.compile(r\"\\.\\w\")\n return any(re_hidden.match(i) for i in dir_or_file.split(os.path.sep))\n\n\ndef is_required_file_type(s, required):\n return required == \"*\" or s.endswith(required.rsplit(\".\", 1)[-1])\n\n\ndef main():\n import sys\n from argparse import ArgumentParser\n\n if not sys.argv[1:]:\n print(__doc__.strip())\n print(\"\\nUsage:\")\n print(\"{}{} /path/to/file\".format(\" \" * 4, sys.argv[0]))\n return\n parser = ArgumentParser()\n parser.add_argument(\n \"-R\", \"-r\", action=\"store_true\", help=\"whether to recursive\"\n )\n parser.add_argument(\n \"-t\", \"--type\", default=\"*\", help=\"filter file type(Example: *.py)\"\n )\n parser.add_argument(\n \"-d\", \"--dir\", default=\".\", help=\"the directory path(default:.)\"\n )\n args, unknown = parser.parse_known_args()\n if args.R:\n files = []\n for r, ds, fs in os.walk(args.dir):\n if is_hidden(r):\n continue\n for fn in fs:\n if not is_hidden(fn) and is_required_file_type(fn, args.type):\n files.append(os.path.join(r, fn))\n elif unknown:\n files = [os.path.join(args.dir, f) for f in unknown]\n count_skip = count_rstrip = 0\n for fn in files:\n try:\n rstrip_file(fn)\n except ContentException as e:\n count_skip += 1\n print(\"{}: skip! {}\".format(fn, e))\n else:\n count_rstrip += 1\n print(\"{}: rstriped.\".format(fn))\n print(\"Done! {} skiped, {} rstriped.\".format(count_skip, count_rstrip))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"rstrip.py","file_name":"rstrip.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"549115818","text":"import uuid\nfrom itertools import combinations\nfrom collections import defaultdict\n\n\nclass Keyword(object):\n\n def __init__(self, keyword, ngram_size=2, skip_size=2, early_threshold=3, late_threshold=3, within_range_threshold=3, ignorecase=False):\n if isinstance(keyword, str):\n keyword = {\"keyword_string\": keyword}\n self.name = keyword[\"keyword_string\"]\n self.properties = keyword\n self.early_threshold = early_threshold\n self.late_threshold = len(self.name) - late_threshold - ngram_size\n self.within_range_threshold = within_range_threshold\n keyword_string = self.name\n self.ignorecase = ignorecase\n if ignorecase:\n keyword_string = keyword_string.lower()\n self.ngrams = [(ngram, offset) for ngram, offset in text2skipgrams(keyword_string, ngram_size=ngram_size, skip_size=skip_size)]\n self.ngram_index = defaultdict(list)\n for ngram, offset in self.ngrams:\n self.ngram_index[ngram] += [offset]\n self.index_ngrams()\n self.early_ngrams = {ngram: offset for ngram, offset in self.ngrams if offset < early_threshold}\n self.late_ngrams = {ngram: offset for ngram, offset in self.ngrams if offset > self.late_threshold}\n self.set_within_range()\n\n def index_ngrams(self):\n self.ngram_index = defaultdict(list)\n for ngram, offset in self.ngrams:\n self.ngram_index[ngram] += [offset]\n\n def has_ngram(self, ngram):\n return ngram in self.ngram_index.keys()\n\n def ngram_offsets(self, ngram):\n if not self.has_ngram(ngram):\n return None\n return self.ngram_index[ngram]\n\n def set_within_range(self):\n self.ngram_distance = {}\n for index1 in range(0, len(self.ngrams)-1):\n ngram1, offset1 = self.ngrams[index1]\n for index2 in range(index1+1, len(self.ngrams)):\n ngram2, offset2 = self.ngrams[index2]\n if offset2 - offset1 > self.within_range_threshold:\n continue\n if (ngram1, ngram2) not in self.ngram_distance:\n self.ngram_distance[(ngram1, ngram2)] = offset2 - offset1\n elif self.ngram_distance[(ngram1, ngram2)] > offset2 - offset1:\n self.ngram_distance[(ngram1, ngram2)] = offset2 - offset1\n\n def within_range(self, ngram1, ngram2):\n if not self.has_ngram(ngram1) or not self.has_ngram(ngram2):\n return False\n elif (ngram1, ngram2) not in self.ngram_distance:\n return False\n elif self.ngram_distance[(ngram1, ngram2)] > self.within_range_threshold:\n return False\n else:\n return True\n\n def early_ngram(self, ngram):\n return ngram in self.early_ngrams\n\ndef insert_skips(window, ngram_combinations):\n for combination in ngram_combinations:\n prev_index = 0\n skip_gram = window[0]\n try:\n for index in combination:\n if index - prev_index > 1:\n skip_gram += \"_\"\n skip_gram += window[index]\n prev_index = index\n yield skip_gram\n except IndexError:\n pass\n\ndef text2skipgrams(text, ngram_size=2, skip_size=2):\n indexes = [i for i in range(0,ngram_size+skip_size)]\n ngram_combinations = [combination for combination in combinations(indexes[1:], ngram_size-1)]\n for offset in range(0, len(text)-1):\n window = text[offset:offset+ngram_size+skip_size]\n for skip_gram in insert_skips(window, ngram_combinations):\n yield (skip_gram, offset)\n\nclass PersonName(object):\n\n def __init__(self, person_name_string):\n self.person_name_id = str(uuid.uuid4())\n self.name_string = person_name_string\n self.normalized_name = normalize_person_name(person_name_string)\n self.name_type = \"person_name\"\n self.spelling_variants = []\n self.distractor_terms = []\n\n def to_json(self):\n return {\n \"person_name_id\": self.person_name_id,\n \"name_string\": self.name_string,\n \"normalize_name\": self.normalized_name,\n \"name_type\": self.name_type,\n \"spelling_variants\": self.spelling_variants,\n \"distractor_terms\": self.distractor_terms\n }\n\n def add_spelling_variants(self, spelling_variants):\n for spelling_variant in spelling_variants:\n if spelling_variant not in self.spelling_variants:\n self.spelling_variants += [spelling_variant]\n\n def add_distractor_terms(self, distractor_terms):\n for distractor_term in distractor_terms:\n if distractor_term not in self.distractor_terms:\n self.distractor_terms += [distractor_term]\n\ndef normalize_person_name(person_name_string):\n normalized = person_name_string.title()\n infixes = [\" van \", \" de \", \" der \", \" du \", \" le \", \" la \"]\n for infix in infixes:\n normalized = normalized.replace(infix.title(), infix.lower())\n return normalized\n\n\n\n","sub_path":"republic/fuzzy/fuzzy_keyword.py","file_name":"fuzzy_keyword.py","file_ext":"py","file_size_in_byte":5069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"52177229","text":"#!/usr/bin/env python\n# _*_ coding:utf-8 _*_\nimport psutil\n#CPU信息\ncpu_time = psutil.cpu_times(percpu=True)\ncpu_count = psutil.cpu_count()\n#MEM信息\nmem = psutil.virtual_memory()\nmem_total = mem.total\nmem_free = mem.free\n#print(mem_total,mem_free,\"%.2f%%\" % (mem_free / mem_total * 100 ) )\n#IO信息\n\n\n\nprint(mem_free)","sub_path":"sysmonitor_demo/system.py","file_name":"system.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"501590078","text":"import re\n\nn = int(input())\na = [re.findall(r'\\w+', input()) for i in range(n)]\nN = {a[i][0]: a[i][1:] for i in range(len(a))}\nq = int(input())\nb = [input().split() for i in range(q)]\n\n\ndef find_path(graph, start, end):\n if start == end:\n return True\n if start not in graph.keys():\n return\n for node in graph[start]:\n newpath = find_path(graph, node, end)\n if newpath:\n return True\n return\n\n\nfor i in range(q):\n if find_path(N, b[i][1], b[i][0]):\n print('Yes')\n else:\n print('No')\n","sub_path":"9.py","file_name":"9.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"189470291","text":"import datetime\nimport requests\nimport time\nimport json\nfrom threading import Thread\n\nfrom loguru import logger\nfrom bs4 import BeautifulSoup\nfrom newspaper import Article\n\nimport config\nfrom src import db\n\n\nclass DuplicateNews(Exception):\n pass\n\n\nclass DoesntExistence(Exception):\n pass\n\n\ndef parse_page_custom(link, title=None, text=None, publish_date=None):\n session = db.Session()\n if session.query(db.News).filter(db.News.link == link).first():\n session.close()\n raise DuplicateNews('This link already in database')\n try:\n article = Article(link, language='ru')\n article.download()\n article.parse()\n except Exception as e:\n logger.warning('i cant download the article')\n _article = {\n \"link\": link,\n \"title\": title if title else article.title,\n \"text\": text if text else article.text,\n \"publish_date\": publish_date if publish_date else article.publish_date,\n \"parsed_date\": datetime.datetime.now(),\n }\n session.add(db.News(**_article))\n session.commit()\n session.close()\n logger.info('Page parsed')\n\n\ndef parse_msknews():\n try:\n page = requests.get('http://msk-news.net/').text\n soup = BeautifulSoup(page, \"html.parser\")\n sitehead = soup.find('div', {\"id\": \"menu\"})\n categories = sitehead.find_all('a')\n for category in categories:\n try:\n parse_msknews_category(category['href'])\n except DuplicateNews as e:\n logger.info(e)\n logger.info('Category parsed')\n except DoesntExistence as e:\n logger.warning(e)\n logger.warning('Кончились страницы или блокировка ip')\n logger.info('Category parsed')\n except Exception as e:\n logger.exception(e)\n logger.error('Вероятно на сайте произошло обновление')\n\n\ndef parse_msknews_category(url):\n deep_counter = 0\n response = requests.get(url)\n if response.status_code != 200:\n raise DoesntExistence\n page = response.text\n page_count = 1\n soup = BeautifulSoup(page, \"html.parser\")\n column = soup.find('div', {\"class\": \"col2\"})\n\n while column:\n column = soup.find('div', {\"class\": \"col2\"})\n pages = column.find_all('div', {\"class\": \"post_title\"})\n for element in pages:\n page = element.find('a', {\"class\": \"vh\"})\n deep_counter += 1\n parse_page_custom(page['href'])\n\n column = soup.find('div', {\"class\": \"col2 col2b\"})\n pages = column.find_all('div', {\"class\": \"post_title\"})\n for element in pages:\n page = element.find('a', {\"class\": \"vh\"})\n deep_counter += 1\n parse_page_custom(page['href'])\n\n if page_count <= 100 and deep_counter < config.max_deep_cat:\n pass\n else:\n logger.info('Category parsed')\n break\n page_count += 1\n response = requests.get(url + '/' + str(count))\n if response.status_code != 200:\n raise DoesntExistence\n page = response.text\n soup = BeautifulSoup(page, \"html.parser\")\n\n\ndef parse_msknovosti():\n try:\n response = requests.get('https://msknovosti.ru/')\n if response.status_code != 200:\n raise DoesntExistence\n page = response.text\n soup = BeautifulSoup(page, \"html.parser\")\n sitehead = soup.find('div', {\"class\": \"menu-main-container\"})\n categories = sitehead.find_all('a')\n for category in categories:\n parse_msknovosti_category(category['href'])\n logger.info('Site parsed')\n except DoesntExistence as e:\n logger.warning(e)\n logger.warning('блокировка ip')\n except Exception as e:\n logger.exception(e)\n logger.warning(' Вероятно на сайте произошло обновление')\n\n\ndef parse_msknovosti_category(url):\n count = 1\n deep_counter = 0\n response = requests.get(url)\n if response.status_code != 200:\n raise DoesntExistence\n page = response.text\n soup = BeautifulSoup(page, \"html.parser\")\n element = soup.find('a', {\"class\": \"page-numbers\"})\n maxcount = int(element.find_next_sibling(\"a\").text)\n try:\n while count <= maxcount and deep_counter < config.max_deep_cat:\n count += 1\n column = soup.find_all('div', {\"class\": \"post-card post-card--vertical w-animate\"})\n flag = 0\n for element in column:\n deep_counter += 1\n parse_page_custom(element.find('a')['href'])\n response = requests.get(url + '/page/' + str(count))\n if response.status_code != 200:\n raise DoesntExistence\n page = response.text\n soup = BeautifulSoup(page, \"html.parser\")\n except DuplicateNews as e:\n logger.info(e)\n logger.info('Category parsed')\n except DoesntExistence as e:\n logger.warning(e)\n logger.warning('Кончились страницы или блокировка ip')\n logger.info('Category parsed')\n except Exception as e:\n logger.exception(e)\n logger.error('Вероятно на сайте произошло обновление')\n \n\n\ndef parse_mskiregion():\n try:\n page_num = 1\n deep_counter = 0\n while deep_counter < config.max_deep:\n if page_num == 1:\n link = 'https://msk.inregiontoday.ru/?cat=1'\n else:\n link = f'https://msk.inregiontoday.ru/?cat=1&paged={page_num}'\n response = requests.get(link)\n if response.status_code != 200:\n raise DoesntExistence\n page = response.text\n page_num += 1\n soup = BeautifulSoup(page, \"html.parser\")\n page_counter = 1\n titels = soup.find_all('h2', {\"class\": \"entry-title\"})\n if not titels:\n flag = 1\n else:\n for title in titels:\n deep_counter += 1\n link = title.find('a')\n parse_page_custom(link['href'])\n \n logger.info('Site parsed')\n except DuplicateNews as e:\n logger.info(e)\n logger.info('Site parsed')\n except DoesntExistence as e:\n logger.warning(e)\n logger.warning('Кончились страницы или блокировка ip')\n logger.info('Site parsed')\n except Exception as e:\n logger.exception(e)\n logger.error('Вероятно на сайте произошло обновление')\n\n\ndef convert_date(post_date):\n if ':' in post_date:\n date = datetime.datetime.now().date()\n elif 'Вчера' in post_date:\n date = datetime.date.today() - datetime.timedelta(days=1)\n else:\n date = ''\n for i in post_date:\n if i >= '0' and i <= '9':\n date = date + i\n date = datetime.datetime.strptime(date, \"%d%m%Y\").date()\n return date\n\n\ndef parse_molnet():\n try:\n page_num = 1\n deep_counter = 0\n while deep_counter < config.max_deep:\n if page_num == 1:\n link = 'https://www.molnet.ru/mos/ru/news'\n else:\n link = f'https://www.molnet.ru/mos/ru/news?page={page_num}'\n response = requests.get(link)\n if response.status_code != 200:\n raise DoesntExistence\n page = response.text\n page_num += 1\n soup = BeautifulSoup(page, \"html.parser\")\n page_counter = 1\n column = soup.find('div', {\"class\": \"l-col__inner\"})\n active = column.find('div', {\"class\": \"rubric-prelist news\"})\n if not active:\n raise DoesntExistence\n else:\n links = []\n news = column.find_all('a', {\"class\": \"link-wr\"})\n for element in news:\n post_date = element.find('span',\n {\"class\": \"prelist-date\"}).text\n links.append(['https://www.molnet.ru' + element['href'],\n convert_date(post_date)])\n\n news = column.find_all('li', {\"class\": \"itemlist__item\"})\n for element in news:\n link = element.find('a', {\"class\": \"itemlist__link\"})['href']\n try:\n post_date = element.find('span',\n {\"class\": \"itemlist__date\"}).text\n except Exception as e:\n break\n links.append(['https://www.molnet.ru' + link,\n convert_date(post_date)])\n\n for link in links:\n deep_counter += 1\n parse_page_custom(link[0], publish_date=link[1])\n\n logger.info('Site parsed')\n except DuplicateNews as e:\n logger.info(e)\n logger.info('Site parsed')\n except DoesntExistence as e:\n logger.warning(e)\n logger.warning('Кончились страницы или блокировка ip')\n logger.info('Site parsed')\n except Exception as e:\n logger.exception(e)\n logger.error('Вероятно на сайте произошло обновление')\n\n\ndef parse_moskvatyt():\n try:\n lower_st_date = '20100301'\n now_date = datetime.date.today()\n deep_counter = 0\n page_num = now_date.strftime('%Y%m%d')\n while page_num != lower_st_date and deep_counter < config.max_deep:\n if now_date == datetime.datetime.now().date():\n link = 'https://www.moskva-tyt.ru/news/'\n else:\n link = f'https://www.moskva-tyt.ru/news/{page_num}.html'\n\n response = requests.get(link)\n if response.status_code != 200:\n raise DoesntExistence(f'Page with page: {count} doesnt exist')\n\n page = response.text\n now_date = now_date - datetime.timedelta(days=1)\n page_num = now_date.strftime('%Y%m%d')\n soup = BeautifulSoup(page, \"html.parser\")\n news = soup.find_all('div', {\"class\": \"next\"})\n if not news:\n logger.warning('Something wrong')\n flag = 1\n else:\n for element in news:\n link = element.find('a')\n deep_counter += 1\n moskvatytpage('https://www.moskva-tyt.ru/'+link['href'])\n logger.info('Site parsed')\n except DuplicateNews as e:\n logger.info(e)\n logger.info('Site parsed')\n except DoesntExistence as e:\n logger.warning(e)\n logger.warning('Кончились страницы или блокировка ip')\n logger.info('Site parsed')\n except Exception as e:\n logger.exception(e)\n logger.error('Вероятно на сайте произошло обновление')\n\n\ndef moskvatytpage(link):\n page = requests.get(link).text\n soup = BeautifulSoup(page, \"html.parser\")\n body = soup.find('div', {\"class\": \"text\"})\n text = ''\n elements = body.find_all('p')\n for element in elements:\n text += element.text\n session = db.Session()\n news = session.query(db.News).filter(db.News.link == link).first()\n date = link.strip('https://www.moskva-tyt.ru/news/')[:8]\n date = datetime.datetime.strptime(date, \"%Y%m%d\").date()\n parse_page_custom(link, text=text, publish_date=date)\n session.close()\n\n\ndef parse_mn():\n try:\n deep_counter = 0\n count = 1\n while deep_counter < config.max_deep:\n link = f'https://www.mn.ru/api/v1/articles/more?page_size=5&page={count}'\n response = requests.get(link)\n if response.status_code != 200:\n raise DoesntExistence(f'Page with page: {count} doesnt exist')\n page = response.json()\n count += 1\n for news in page[\"data\"]:\n deep_counter += 1\n date = news[\"attributes\"]['published_at'][:10]\n publish_date = datetime.datetime.strptime(date, \"%Y-%m-%d\").date()\n news_link = 'https://www.mn.ru' + news['links']['self']\n parse_page_custom(link=news_link,\n title=news[\"attributes\"]['title'],\n text=news[\"attributes\"]['description'],\n publish_date=publish_date)\n logger.info('Site parsed')\n except DuplicateNews as e:\n logger.info(e)\n logger.info('Site parsed')\n except DoesntExistence as e:\n logger.warning(e)\n logger.warning('Кончились страницы или блокировка ip')\n logger.info('Site parsed')\n except Exception as e:\n logger.exception(e)\n logger.error('Вероятно на сайте произошло обновление')\n\n\nif __name__ == \"__main__\":\n parser1 = Thread(target=parse_msknews)\n parser2 = Thread(target=parse_msknovosti)\n parser3 = Thread(target=parse_mskiregion)\n parser4 = Thread(target=parse_molnet)\n parser5 = Thread(target=parse_moskvatyt)\n parser6 = Thread(target=parse_mn)\n while True:\n parser1.start()\n parser2.start()\n parser3.start()\n parser4.start()\n parser5.start()\n parser6.start()\n logger.info('Потоки запущены')\n time.sleep(config.delay)\n","sub_path":"parser/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":13665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"578744669","text":"import torch\nimport torchvision.transforms.functional as tt\nimport argparse\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport scripts.models as M\n\ndef extract_arguments():\n \"\"\"defines the arguments the script requires and returns the argparse\n object\"\"\"\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\n 'image_path', type=str,\n help='path to the the image'\n )\n parser.add_argument(\n 'input_size', type=int,\n help='resolution of the degraded image'\n )\n parser.add_argument(\n 'output_size', type=int,\n help='target resolution'\n )\n parser.add_argument(\n 'batch_size', type=int,\n help='batch_size for training'\n )\n return vars(parser.parse_args())\n\ndef extract_image(path:str, in_shape:int, out_shape:int):\n \"\"\"extract the image from the disk, and format for input to the network\"\"\"\n\n #extract image\n image = Image.open(path)\n #perform image transformations\n x = tt.to_tensor(tt.resize(image, (in_shape, in_shape))).unsqueeze(0)\n y = tt.to_tensor(tt.resize(image, (out_shape, out_shape))).unsqueeze(0)\n return (x, y)\n\ndef restore_image(image:torch.tensor):\n \"\"\"the output of the network is not expected to be in a standardized form\n therefore all we must do is convert it back to an image, although it should\n still be normalized\"\"\"\n\n image = image.squeeze()\n image = torch.clamp(image, 0, 1)\n return tt.to_pil_image(image)\n\ndef display_result(result:dict):\n \"\"\"display all the images from the demonstrator\"\"\"\n\n for key in result.keys():\n value = result[key]\n plt.imshow(restore_image(value))\n plt.title(key)\n plt.axis('off')\n plt.show()\n\ndef main():\n\n #parse command line arguments\n arguments = extract_arguments()\n #extract the input\n #construct the demonstrator\n demonstrator = M.Demonstrator(\n None,\n arguments['input_size'],\n arguments['output_size'],\n )\n #extract the recovered images\n (x, y) = extract_image(\n arguments['image_path'],\n arguments['input_size'],\n arguments['output_size'],\n )\n result = demonstrator.recover(x, y)\n display_result(result)\n\nmain()\n","sub_path":"scripts/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"231099506","text":"'''\nThe Jira class in this module is the primary abstraction around the Jira API.\n'''\nimport collections.abc\nimport dataclasses\nimport json\nimport logging\nimport os\nfrom typing import Dict, List, Optional, Set\n\nimport pandas as pd\nfrom peak.util.proxies import LazyProxy\nimport pytz\n\nfrom jira_offline.config import get_cache_filepath, load_config\nfrom jira_offline.exceptions import (EpicNotFound, EstimateFieldUnavailable, JiraApiError,\n JiraNotConfigured, MissingFieldsForNewIssue,\n MultipleTimezoneError, ProjectDoesntExist)\nfrom jira_offline.models import AppConfig, CustomFields, Issue, IssueType, ProjectMeta\nfrom jira_offline.sql_filter import IssueFilter\nfrom jira_offline.utils.api import get as api_get, post as api_post, put as api_put\nfrom jira_offline.utils.convert import jiraapi_object_to_issue\nfrom jira_offline.utils.decorators import auth_retry\n\n\nlogger = logging.getLogger('jira')\n\n\n# Create single Jira object instance for this invocation of the app\n# Made available to all modules via simple python import: `from jira_offline.jira import jira`\njira = LazyProxy(lambda: Jira()) # pylint: disable=unnecessary-lambda\n\n\nclass Jira(collections.abc.MutableMapping):\n _df: pd.DataFrame\n\n filter: IssueFilter\n\n\n def __init__(self):\n self.store = dict()\n\n # Create the underlying storage for persisting Issues\n self._df = pd.DataFrame()\n\n # Load application config without prompting\n self.config: AppConfig = load_config()\n\n # Initialise an empty filter\n self.filter = IssueFilter()\n\n\n def __getitem__(self, key: str) -> Issue:\n series = self._df.loc[key]\n return Issue.from_series(\n series,\n project=self.config.projects[series['project_id']]\n )\n\n def __setitem__(self, key: str, issue: Issue):\n series = issue.to_series()\n self._df.loc[key] = series\n\n def __delitem__(self, key: str):\n self._df.drop(key, inplace=True)\n\n def __iter__(self):\n return (k for k, row in self._df.iterrows())\n\n def __len__(self):\n return len(self._df)\n\n def __contains__(self, key):\n return key in self._df.index\n\n\n @property\n def df(self) -> pd.DataFrame:\n return self.filter.apply()\n\n\n def update(self, issues: List[Issue]): # type: ignore[override] # pylint: disable=arguments-differ\n '''\n Merge another DataFrame of Issues to the store. New issues are appended to the underlying\n DataFrame and existing modified issues are updated in-place.\n\n This method is called during sync with Jira server.\n\n Notably this method _does not_ use the logic in Issue.to_series() for performance reasons;\n it's much faster to build the DataFrame and operate on that, than to process each Issue in a\n tight loop and then create a DataFrame.\n '''\n # Validate all timezones are the same for this DataFrame, as the following tz_convert() call\n # fails when they differ.\n # It's not possible for a single Jira to return issues with multiple different timezones.\n if not all(i.created.tzinfo == issues[0].created.tzinfo for i in issues): # type: ignore[union-attr]\n raise MultipleTimezoneError\n if not all(i.updated.tzinfo == issues[0].updated.tzinfo for i in issues): # type: ignore[union-attr]\n raise MultipleTimezoneError\n\n # Construct a DataFrame from the passed list of Issues\n # also fill any NaNs with blank\n df = pd.DataFrame.from_dict(\n {issue.key:issue.__dict__ for issue in issues},\n orient='index'\n ).fillna('')\n\n # Convert all datetimes to UTC\n for col in ('created', 'updated'):\n df[col] = df[col].dt.tz_convert('UTC')\n\n # Convert the \"project\" object column - which contains ProjectMeta instances -\n # into \"project_key\" - a string column\n df.loc[:, 'project_key'] = [p.key if p else None for p in df['project']]\n\n # Drop columns for fields marked repr=False\n df.drop(\n columns=[f.name for f in dataclasses.fields(Issue) if f.repr is False],\n inplace=True,\n )\n\n # Render diff_to_original as a string for storage in the DataFrame\n df['diff_to_original'] = df['diff_to_original'].apply(json.dumps)\n\n # Add an empty column to for Issue.original\n df['original'] = ''\n\n # Append any new issues\n self._df = pd.concat([ self._df, df[~df.key.isin(self._df.index)] ])\n\n # In-place update for modified issues\n self._df.update(df)\n\n # Let Pandas pick the best datatypes\n self._df = self._df.convert_dtypes()\n\n # write to disk\n self.write_issues()\n\n\n class KeysView(collections.abc.KeysView):\n '''Override KeysView to enable filtering via __iter__'''\n def __init__(self, jira_, filter_):\n self.filter = filter_\n super().__init__(jira_)\n\n def __iter__(self):\n for key in self.filter.apply().index:\n yield key\n\n class ItemsView(collections.abc.ItemsView):\n '''Override ItemsView to enable filtering via __iter__'''\n def __init__(self, jira_, filter_):\n self.filter = filter_\n super().__init__(jira_)\n\n def __iter__(self):\n for key in self.filter.apply().index:\n yield (key, self._mapping[key])\n\n class ValuesView(collections.abc.ValuesView):\n '''Override ValuesView to enable filtering via __iter__'''\n def __init__(self, jira_, filter_):\n self.filter = filter_\n super().__init__(jira_)\n\n def __iter__(self):\n for key in self.filter.apply().index:\n yield self._mapping[key]\n\n def keys(self):\n return Jira.KeysView(self, self.filter)\n\n def items(self):\n return Jira.ItemsView(self, self.filter)\n\n def values(self):\n return Jira.ValuesView(self, self.filter)\n\n\n def load_issues(self) -> None:\n '''\n Load issues from parquet cache file, and store in underlying pandas DataFrame\n '''\n cache_filepath = get_cache_filepath()\n if os.path.exists(cache_filepath) and os.stat(cache_filepath).st_size > 0:\n self._df = pd.read_feather(\n cache_filepath\n ).set_index('key', drop=False).rename_axis(None).convert_dtypes()\n\n # add an empty column to for Issue.original\n self._df['original'] = ''\n\n\n def write_issues(self):\n '''\n Dump issues to parquet cache file\n '''\n # Don't write out the original field, as diff_to_original will recreate it\n df = self._df.drop(columns=['original'])\n\n # convert `set` columns to `list`, as `set` will not serialize via PyArrow when writing\n # to disk\n for col in ('components', 'fix_versions', 'labels'):\n df[col] = df[col].apply(list)\n\n # PyArrow does not like decimals\n df['estimate'] = df['estimate'].astype('string')\n\n cache_filepath = get_cache_filepath()\n df.reset_index(drop=True).to_feather(cache_filepath)\n\n\n @auth_retry()\n def get_project_meta(self, project: ProjectMeta): # pylint: disable=no-self-use\n '''\n Load additional Jira project meta data from Jira's createmeta API\n\n Params:\n project: Jira project object into which we should load additional metadata\n '''\n try:\n params = {'projectKeys': project.key, 'expand': 'projects.issuetypes.fields'}\n data = api_get(project, 'issue/createmeta', params=params)\n if not data.get('projects'):\n raise ProjectDoesntExist(project.key)\n\n # project friendly name\n project.name = data['projects'][0]['name']\n\n issuetypes_: Dict[str, IssueType] = dict()\n priorities_: Set[str] = set()\n\n # extract set of issuetypes, and their priority values returned from the createmeta API\n for x in data['projects'][0]['issuetypes']:\n issuetypes_[x['name']] = IssueType(name=x['name'])\n\n # priority is a project-level setting, which can be extracted from any issue with the\n # \"priority\" field\n if not priorities_ and x['fields'].get('priority'):\n priorities_ = {y['name'] for y in x['fields']['priority']['allowedValues']}\n\n # update project issuetypes & priorities to latest defined on Jira\n project.issuetypes = issuetypes_\n project.priorities = priorities_\n\n custom_fields = CustomFields()\n\n # extract custom fields from the API\n for issuetype in data['projects'][0]['issuetypes']:\n if custom_fields:\n # exit loop when all custom field mappings have been extracted\n break\n\n for field_props in issuetype['fields'].values():\n if not custom_fields.epic_name and field_props['name'] == 'Epic Name':\n custom_fields.epic_name = str(field_props['schema']['customId'])\n elif not custom_fields.epic_ref and field_props['name'] == 'Epic Link':\n custom_fields.epic_ref = str(field_props['schema']['customId'])\n elif not custom_fields.estimate and field_props['name'] == 'Story Points':\n custom_fields.estimate = str(field_props['schema']['customId'])\n elif not custom_fields.estimate and field_props['name'] == 'Acceptance Criteria':\n custom_fields.acceptance_criteria = str(field_props['schema']['customId'])\n\n project.custom_fields = custom_fields\n\n # pull project statuses for issue types\n self._get_project_issue_statuses(project)\n\n # pull project components\n self._get_project_components(project)\n\n # Pull user's configured timezone from their profile and store on the ProjectMeta\n tz = self._get_user_timezone(project)\n if tz is not None:\n project.timezone = pytz.timezone(tz)\n\n except (IndexError, KeyError) as e:\n raise JiraApiError((\n f'Missing or bad project meta returned for {project.key} with error '\n f'\"{e.__class__.__name__}({e})\"'\n ))\n\n\n def _get_user_timezone(self, project: ProjectMeta) -> Optional[str]: # pylint: disable=no-self-use\n '''\n Retrieve user-specific timezone setting\n '''\n data = api_get(project, 'myself')\n return data.get('timeZone')\n\n\n def _get_project_issue_statuses(self, project: ProjectMeta): # pylint: disable=no-self-use\n '''\n Pull valid statuses for each issuetype in this project\n\n Params:\n project: Jira project to query\n '''\n data = api_get(project, f'project/{project.key}/statuses')\n\n for obj in data:\n try:\n issuetype = project.issuetypes[obj['name']]\n issuetype.statuses = {x['name'] for x in obj['statuses']}\n except KeyError:\n logger.debug('Unknown issuetype \"%s\" returned from /project/{project.key}/statuses', obj['name'])\n\n\n def _get_project_components(self, project: ProjectMeta): # pylint: disable=no-self-use\n '''\n Pull set of components for this project\n\n Params:\n project: Jira project to query\n '''\n data = api_get(project, f'project/{project.key}/components')\n project.components = {x['name'] for x in data}\n\n\n def new_issue(self, project: ProjectMeta, fields: dict) -> Issue:\n '''\n Create a new issue on a Jira project via the API\n\n Params:\n project: Properties of the Jira project on which to create new Issue\n fields: JSON-compatible key-value pairs for new Issue\n Returns:\n The new Issue, including the Jira-generated key field\n '''\n if 'key' not in fields or 'issuetype' not in fields or 'summary' not in fields:\n raise MissingFieldsForNewIssue(\n '{} is missing a mandatory field {}'.format(fields['key'], ','.join(fields))\n )\n\n try:\n # key is set by Jira server; remove it\n temp_key = fields['key']\n del fields['key']\n # project_id is application data; remove it\n del fields['project_id']\n\n # create new issue in Jira\n data = api_post(project, 'issue', data={'fields': fields})\n\n # retrieve the freshly minted Jira issue\n new_issue: Issue = self.fetch_issue(project, data['key'])\n\n except JiraApiError as e:\n err: str = 'Failed creating new {} \"{}\" with error \"{}\"'.format(\n fields['issuetype']['name'],\n fields['summary'],\n e.message\n )\n if e.message == 'gh.epic.error.not.found':\n raise EpicNotFound(err)\n if \"Field 'estimate' cannot be set\" in e.message:\n raise EstimateFieldUnavailable(project.key, project.jira_server)\n if 'cannot be set. It is not on the appropriate screen, or unknown.' in e.message:\n raise JiraNotConfigured(project.key, project.jira_server, err)\n\n if new_issue.key is None:\n # This code path is not reachable, as the `key` field is mandatory on the Jira API. This\n # is included to keep the type-checker happy\n raise Exception\n\n # add to self under the new key\n self[new_issue.key] = new_issue\n\n if new_issue.issuetype == 'Epic':\n # relink any issue linked to this epic to the new Jira-generated key\n for linked_issue in [i for i in self.values() if i.epic_ref == temp_key]:\n linked_issue.epic_ref = new_issue.key\n\n # remove the placeholder Issue\n del self[temp_key]\n\n # write changes to disk\n self.write_issues()\n\n return new_issue\n\n\n def update_issue(self, project: ProjectMeta, issue: Issue, fields: dict) -> Optional[Issue]:\n '''\n Update an issue on Jira via the API\n\n Params:\n project: Properties of the Jira project to update\n issue: Issue object to update\n fields: JSON-compatible key-value pairs to write\n '''\n try:\n api_put(project, f'issue/{issue.key}', data={'fields': fields})\n\n # Jira is now updated to match local; synchronize our local reference to the Jira object\n issue.original = issue.serialize()\n\n if issue.key is None:\n # this code path is not possible, as Jira always provides the key field\n # but it keeps the type-checker happy\n raise Exception\n\n self[issue.key] = issue\n return issue\n\n except JiraApiError as e:\n logger.error('Failed updating %s with error \"%s\"', issue.key, e)\n\n return None\n\n\n def fetch_issue(self, project: ProjectMeta, key: str) -> Issue: # pylint: disable=no-self-use\n '''\n Return a single Issue object from the Jira API by key\n\n Params:\n project: Properties of the project pushing issues to\n key: Issue key to lookup on Jira API\n Returns:\n Issue dataclass instance\n '''\n data = api_get(project, f'issue/{key}')\n return jiraapi_object_to_issue(project, data)\n","sub_path":"jira_offline/jira.py","file_name":"jira.py","file_ext":"py","file_size_in_byte":15701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"261109856","text":"# geometric near neighbors access tree module\n\n# to find nearest neighbor : build gnat with build_gnat function, then use query_nneighbor\n\nimport sys\nimport os\nfrom random import shuffle\nimport numpy as np\n\nsys.setrecursionlimit(10000)\n\ndef euclidean_metric(x,y):\n return np.linalg.norm(x-y)\n\n\nclass GNATNode(object):\n\n def __init__(self, center, metric=euclidean_metric, k=10, rmax=0.):\n\n assert len(center)==2 \n\n self.metric = metric # metric used to find the nearest neighbor\n self.center = center # center point of the current node\n self.k = k # degree of the current node = number of (direct) subnodes\n self.free_points = [] # list of points (with index) of the current node that do not belong to any of its subnodes\n self.subnodes = [] # list of (direct) subnodes of the current node\n\n\n def add_points(self, new_points):\n\n if new_points == []:\n return\n\n metric = self.metric\n center = self.center\n\n self.free_points.extend(new_points) # first add new points to free points\n self.split() # then use them to split the current node into k subnodes \n\n\n def split(self):\n\n free_points = self.free_points\n\n if self.subnodes == []:\n k = self.k\n if len(free_points) > 3*k: # if there is not enough points do not build subnodes, leave the new points as free points instead.\n self.subnodes, free_points = choose_subnodes(free_points, self.metric, k) # choose subnodes (split points) according to GNAT approach\n\n if self.subnodes != [] and free_points != []:\n ranges_between_subnodes = initialize_ranges_between_nodes(self.metric, self.subnodes)\n subnodes_points, self.ranges_between_subnodes = partition_and_get_ranges_between_nodes(free_points, self.metric, self.subnodes, ranges_between_subnodes)\n for (points, subnode) in zip(subnodes_points, self.subnodes):\n subnode.add_points(points)\n self.free_points = []\n\n\n def query_nneighbor(self, target, r=1e100):\n \"\"\"Find the nearest neighbor of target.\n\n Returns the idx (in the samples with build_gnat function) of the nearest neighbor, and the distance r to that neighbor.\n \n Works recursively, only looking for a neighbor closer than all previously seen neighbors.\n\n \"\"\"\n\n nneighbor = None\n\n metric = self.metric\n unused_subnodes = []\n\n distance_from_center = metric(target, self.center[0])\n\n if distance_from_center < r:\n nneighbor = self.center\n r = distance_from_center\n\n for free_point in self.free_points:\n distance_from_free_point = metric(target, free_point[0])\n if distance_from_free_point < r:\n nneighbor = free_point\n r = distance_from_free_point\n\n if self.subnodes != []:\n\n for idx, subnodei in enumerate(self.subnodes):\n distance_from_subnode = metric(target, subnodei.center[0])\n\n for jdx, subnodej in enumerate(self.subnodes): \n if idx!= jdx and \\\n min(distance_from_subnode + r, self.ranges_between_subnodes[idx][jdx][1]) < max(distance_from_subnode - r, self.ranges_between_subnodes[idx][jdx][0]):\n \n unused_subnodes.append(jdx)\n\n for idx, subnode in enumerate(self.subnodes):\n\n if idx not in unused_subnodes:\n subnode_nneighbor, subnode_r = subnode.query_nneighbor(target, r)\n\n if subnode_nneighbor is not None:\n assert subnode_r < r\n r = subnode_r\n nneighbor = subnode_nneighbor\n \n return nneighbor, r\n\n\ndef get_distance_from_nodes_and_find_nearest_node(nodes, sample, metric):\n min_r = 1.e1000\n rs = [[] for n in nodes]\n for idx, node in enumerate(nodes):\n r = metric(node.center[0], sample)\n rs[idx] = r \n if r <= min_r:\n min_r = r\n min_idx = idx\n return rs, min_idx\n\n\ndef partition_and_get_ranges_between_nodes(samples, metric, nodes, ranges):\n\n nodes_free_points = [[] for n in nodes]\n\n for [sample, idx_sample] in samples:\n rs, min_idx = get_distance_from_nodes_and_find_nearest_node(nodes, sample, metric)\n for idx, r in enumerate(rs):\n if idx!=min_idx:\n if r<=ranges[idx][min_idx][0]: ranges[idx][min_idx][0] = r\n if r>=ranges[idx][min_idx][1]: ranges[idx][min_idx][1] = r\n nodes_free_points[min_idx].append([sample, idx_sample])\n\n return nodes_free_points, ranges\n\n\ndef initialize_ranges_between_nodes(metric, nodes):\n\n ranges = [[[[],[]] for n in nodes] for m in nodes]\n\n for idx, nodei in enumerate(nodes):\n for jdx, nodej in enumerate(nodes):\n if idx != jdx:\n r = metric(nodei.center[0], nodej.center[0])\n ranges[idx][jdx][0] = r\n ranges[idx][jdx][1] = r\n\n return ranges\n\n\ndef choose_subnodes(samples, metric, k):\n num = len(samples)\n\n num_possible = min(num, 3*k)\n possible_sp = samples[:num_possible]\n rest = samples[num_possible:]\n sp = [possible_sp.pop()]\n for count in xrange(k - 1):\n max_min_r = 0.\n for (pdx, [p, p_idx]) in enumerate(possible_sp):\n min_r = 1.e100\n for [spx, sp_idx] in sp:\n r = metric(p, spx)\n assert isinstance(r, float) \n min_r = min(r, min_r) # compute the minimal distance between the candidate split point p and all split points sp\n if min_r >= max_min_r: # check among candidate split points the one with the greatest minimal distance to the split points \n max_min_r = min_r\n new_pdx = pdx\n new_sp = p\n new_sp_idx = p_idx\n del possible_sp[new_pdx]\n sp.append([new_sp, new_sp_idx])\n rest.extend(possible_sp)\n return [GNATNode(p, metric, k) for p in sp], rest\n\n\ndef build_gnat(samples, frac=1., metric=euclidean_metric, k=5): \n\n # samples = samples used to build gnat\n # frac = fraction of the samples actually used\n # metric = metric used to find neighbors\n # k = number of direct subnodes in gnat (k=4, k=5 looks to be the more efficient value)\n\n samples_idxs = range(len(samples))\n shuffle(samples_idxs)\n samples_idxs = samples_idxs[:int(len(samples)*frac)]\n samples_with_idxs = []\n\n for sample_idx in samples_idxs: samples_with_idxs.append([samples[sample_idx], sample_idx])\n\n root_node = GNATNode(samples_with_idxs[0], metric, k)\n root_node.add_points(samples_with_idxs[1:])\n\n return root_node\n","sub_path":"coord_util/pygnat.py","file_name":"pygnat.py","file_ext":"py","file_size_in_byte":6746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"145819819","text":"from threading import Timer\nfrom titre_wiki.models import TitreWiki\nfrom .models import ArticleWiki\nimport wikipedia\n# from background_task import background\n\nclass UpdateArticle(object):\n\n result = \"\"\n\n def _init_(self):\n self.iteration_count = 0\n self.heartbeat = 60 \n\n @staticmethod\n def add_article(id):\n self.titre_article = TitreWiki.objects.get(pk=id)\n try:\n resume_article = wikipedia.summary(self.titre_article, sentences=4)\n article_ = ArticleWiki()\n article_._state.adding = False\n article_._state.db = 'db_article_wiki'\n article_.content = resume_article\n article_.titre_wiki = id\n article_.save()\n except wikipedia.exceptions.DisambiguationError as e:\n for options in e.options:\n error += options.decode(\"utf-8\",\"ignore\")+'\\n'\n except wikipedia.exceptions.PageError:\n error = \"Aucun message n'a pu être trouvé avec le sujet que vous avez entré!\"\n\n def start_job(self):\n self.add_article(self.iteration_count)\n self.iteration_count += 1\n\n timer = Timer(\n interval=self.heartbeat,\n function=self.start_job,\n )\n\n timer.start()\n\n if self.iteration_count >= 100:\n timer.cancel()\n \n\n# @background(schedule=60)\n# def notify_user():\n# for titre_wiki in TitreWiki().objects.all():\n# titre_wiki_ = TitreWiki.objects.filter(title=titre_wiki_)\n# if not titre_wiki:\n# continue\n\n\n# @app.task\n# def add_aticle_to_db():\n# for titre_wiki in TitreWiki().objects.all():\n# titre_wiki_ = TitreWiki.objects.filter(title=titre_wiki_)\n# if not titre_wiki:\n# continue\n \n# template = Template(REPORT_TEMPLATE)\n \n","sub_path":"article_wiki/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"127684212","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/firstblood/patches/object.py\n# Compiled at: 2018-10-28 14:07:36\n# Size of source mod 2**32: 817 bytes\nimport functools as fn\nfrom .patch import patch, needFlush\n\nclass wrap:\n\n def __init__(self, func, prop=False):\n self.func = func\n self.prop = prop\n\n def __get__(self, this, cls):\n if this is None:\n this = cls\n if self.prop:\n return self.func(this)\n return fn.partial(self.func, this)\n\n\n@needFlush\ndef addMethods():\n patch(object, 'dir', wrap(dir, prop=True))\n patch(object, 'repr', wrap(repr, prop=True))\n patch(object, 'hasattr', wrap(hasattr))\n patch(object, 'getattr', wrap(getattr))\n patch(object, 'setattr', wrap(setattr))\n\n\n@needFlush\ndef patchMethods():\n pass\n\n\n@needFlush\ndef patchAll():\n patchMethods()\n addMethods()\n\n\nif __name__ == '__main__':\n from IPython import embed\n patchAll()\n embed()","sub_path":"pycfiles/firstblood-0.0.1-py3.7/object.cpython-37.py","file_name":"object.cpython-37.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"306629468","text":"__author__ = 'riros <ivanvalenkov@gmail.com> 22.06.17'\nfrom django import forms\nfrom django.utils.translation import ugettext, ugettext_lazy as _\nfrom django.contrib.auth import (\n authenticate, get_user_model, password_validation, login\n)\nfrom django.utils.text import capfirst\n\nfrom cabinet.models import Account\n\nUserModel = get_user_model()\n\n\n# class UsernameField(forms.CharField):\n# def to_python(self, value):\n# return unicodedata.normalize('NFKC', super(UsernameField, self).to_python(value))\n\n\nclass AuthenticationForm(forms.Form):\n \"\"\"\n Base class for authenticating users. Extend this to get a form that accepts\n username/password logins.\n \"\"\"\n accountname = forms.CharField(\n label='Лицевой счет',\n max_length=20,\n empty_value='700125',\n widget=forms.TextInput(attrs={'autofocus': True, 'class': 'form-control'}),\n )\n\n f = forms.CharField(\n label='Фамилия',\n max_length=254,\n widget=forms.TextInput(attrs={'autofocus': True, 'class': 'form-control'}),\n )\n i = forms.CharField(\n label='Имя',\n max_length=254,\n widget=forms.TextInput(attrs={'autofocus': True, 'class': 'form-control'}),\n )\n o = forms.CharField(\n label='Отчество',\n max_length=254,\n required=False,\n widget=forms.TextInput(attrs={'autofocus': True, 'class': 'form-control'}),\n )\n\n # password = forms.CharField(\n # label=_(\"Password\"),\n # strip=False,\n # widget=forms.PasswordInput(attrs={'class': 'form-control'}),\n # )\n\n error_messages = {\n 'invalid_login':\n \"Проверьте введенные данные, возможно Вы сделали ошибку в одном из полей.\"\n \" Данные не чувствительные к регистру.\"\n ,\n 'inactive': _(\"This account is inactive.\"),\n }\n\n def __init__(self, request=None, *args, **kwargs):\n \"\"\"\n The 'request' parameter is set for custom auth use by subclasses.\n The form data comes in via the standard 'data' kwarg.\n \"\"\"\n self.request = request\n self.user_cache = None\n super(AuthenticationForm, self).__init__(*args, **kwargs)\n\n # Set the label for the \"username\" field.\n # self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD)\n # if self.fields['accountname'].label is None:\n # self.fields['accountname'].label = capfirst(self.username_field.verbose_name)\n\n def clean(self):\n # username = self.cleaned_data.get('username')\n # password = self.cleaned_data.get('password')\n accountname = self.cleaned_data.get('accountname')\n f = self.cleaned_data.get('f')\n i = self.cleaned_data.get('i')\n o = self.cleaned_data.get('o')\n # accountname = \"090067\"\n # f = \"Мельникова\"\n # i = \"Анна\"\n # o = \"Ивановна\"\n\n if (accountname is not None):\n\n luser = Account.find_user_from_afio(accountname, f, i, o)\n if luser:\n # luser.is_staff = True\n if luser.last_login is None:\n luser.is_active = True\n luser.save()\n # self.user_cache = authenticate(self.request, username=luser.username)\n # login(self.request, luser)\n self.user_cache = luser\n\n if self.user_cache is None:\n raise forms.ValidationError(\n self.error_messages['invalid_login'],\n code='invalid_login',\n params={'username': accountname},\n )\n else:\n self.confirm_login_allowed(self.user_cache)\n\n return self.cleaned_data\n\n def confirm_login_allowed(self, user):\n \"\"\"\n Controls whether the given User may log in. This is a policy setting,\n independent of end-user authentication. This default behavior is to\n allow login by active users, and reject login by inactive users.\n\n If the given user cannot log in, this method should raise a\n ``forms.ValidationError``.\n\n If the given user may log in, this method should return None.\n \"\"\"\n pass\n # if not user.is_active:\n # raise forms.ValidationError(\n # self.error_messages['inactive'],\n # code='inactive',\n # )\n\n def get_user_id(self):\n if self.user_cache:\n return self.user_cache.id\n return None\n\n def get_user(self):\n return self.user_cache\n","sub_path":"cabinet/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"317453879","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\nimport numpy as np\n\nnp.random.seed(1337) # for reproducibility\n\nimport pandas as pd\nimport codecs\n#from keras.utils.np_utils import to_categorical\nfrom sklearn import preprocessing \nfrom matplotlib import pyplot as plt\nfrom sklearn import metrics\nfrom Multi_label_metrics import ex_based_acc, ex_based_precision, ex_based_recall, ex_based_f1, multi_hamming_loss, exact_match, one_error\n\n# LOAD PREDICTIONS\n\n# The file predictions.txt has one array for each instance, organized in the following way:\n# true label, 3 most probable 4 digit (full-codes) predicted labels, 3 most probable 3 digit (blocks) predicted labels\n\nlabels_pred = np.genfromtxt('pred_full.txt', dtype = 'str')\nlabels_pred_ml = np.array([ line.replace(',','').replace('[','').replace(']','').replace(\"'\",'').rstrip('\\n\\r').split(' ') for line in codecs.open('pred_labels.txt', encoding=\"iso_8859-1\") ])\n\n# labels_cid has the true labels\nlabels_cid = [x[0] for x in labels_pred]\nlabels_cid_ml = np.array([ line.replace(',','').replace('[','').replace(']','').replace(\"'\",'').rstrip('\\n\\r').split(' ') for line in codecs.open('true_labels.txt', encoding=\"iso_8859-1\") ])\n# labels_pred the predicted labels\nlabels_pred = [[x[1],x[2],x[3],x[4],x[5],x[6]] for x in labels_pred]\n\ncid_4 = preprocessing.LabelEncoder()\ncid_3 = preprocessing.LabelEncoder()\ncid_1 = preprocessing.LabelEncoder()\n\n# converting the 4 digit codes (full-codes) to integers\nchar_4 = cid_4.fit([x[:4] for x in labels_cid]+[x[:4] for x in [x[0] for x in labels_pred]])\n# converting the 3 digit codes (blocks) to integers\nchar_3 = cid_3.fit([x[:3] for x in labels_cid]+[x[:3] for x in [x[0] for x in labels_pred]])\n# converting the 1 digit codes (chapters) to integers\nchar_1 = cid_1.fit([x[:1] for x in labels_cid]+[x[:1] for x in [x[0] for x in labels_pred]])\n\n# Integer values for the true labels\ntrue_4 = char_4.transform([x[:4] for x in labels_cid])\ntrue_3 = char_3.transform([x[:3] for x in labels_cid])\ntrue_1 = char_1.transform([x[:1] for x in labels_cid])\n\n# Integer values for the most probable predicted labels (full-code, block and chapter)\npred_4 = char_4.transform([x[:4] for x in [x[0] for x in labels_pred]])\npred_3 = char_3.transform([x[:3] for x in [x[0] for x in labels_pred]])\npred_1 = char_1.transform([x[:1] for x in [x[0] for x in labels_pred]])\n\n# CLASS ACCURACY ANALYSIS\n\nc_labels_cid = [x[:3] for x in labels_cid]\nlabels_cid_ml_b = np.array([[x[:3] for x in line] for line in labels_cid_ml])\n\nc_labels_pred = [x[:3] for x in [x[0] for x in labels_pred]]\nlabels_pred_ml_b = np.array([ line.replace(',','').replace('[','').replace(']','').replace(\"'\",'').rstrip('\\n\\r').split(' ') for line in codecs.open('pred_labels_block.txt', encoding=\"iso_8859-1\") ])\n#%%\ndef icd9_chap(lst):\n c_labels_cid = lst[:]\n for i in range(len(c_labels_cid)):\n if c_labels_cid[i] >= '001' and c_labels_cid[i] <= '139': \n c_labels_cid[i] = 1 \n elif c_labels_cid[i] >= '140' and c_labels_cid[i] <= '239': \n c_labels_cid[i] = 2\n elif c_labels_cid[i] >= '240' and c_labels_cid[i] <= '279': \n c_labels_cid[i] = 3\n elif c_labels_cid[i] >= '280' and c_labels_cid[i] <= '289': \n c_labels_cid[i] = 4\n elif c_labels_cid[i] >= '290' and c_labels_cid[i] <= '319': \n c_labels_cid[i] = 5\n elif c_labels_cid[i] >= '320' and c_labels_cid[i] <= '389': \n c_labels_cid[i] = 6\n elif c_labels_cid[i] >= '390' and c_labels_cid[i] <= '459': \n c_labels_cid[i] = 7\n elif c_labels_cid[i] >= '460' and c_labels_cid[i] <= '519': \n c_labels_cid[i] = 8\n elif c_labels_cid[i] >= '520' and c_labels_cid[i] <= '579': \n c_labels_cid[i] = 9\n elif c_labels_cid[i] >= '580' and c_labels_cid[i] <= '629': \n c_labels_cid[i] = 10\n elif c_labels_cid[i] >= '630' and c_labels_cid[i] <= '679': \n c_labels_cid[i] = 11\n elif c_labels_cid[i] >= '680' and c_labels_cid[i] <= '709': \n c_labels_cid[i] = 12\n elif c_labels_cid[i] >= '710' and c_labels_cid[i] <= '739': \n c_labels_cid[i] = 13\n elif c_labels_cid[i] >= '740' and c_labels_cid[i] <= '759': \n c_labels_cid[i] = 14\n elif c_labels_cid[i] >= '760' and c_labels_cid[i] <= '779': \n c_labels_cid[i] = 15\n elif c_labels_cid[i] >= '780' and c_labels_cid[i] <= '799': \n c_labels_cid[i] = 16\n elif c_labels_cid[i] >= '800' and c_labels_cid[i] <= '999': \n c_labels_cid[i] = 17\n elif c_labels_cid[i] >= 'V01' and c_labels_cid[i] <= 'V91': \n c_labels_cid[i] = 18\n elif c_labels_cid[i] >= 'E000' and c_labels_cid[i] <= 'E999': \n c_labels_cid[i] = 19\n return c_labels_cid\n\nc_labels_cid = icd9_chap(c_labels_cid)\nlabels_cid_ml_c = np.array([icd9_chap(line) for line in labels_cid_ml_b])\n\nc_labels_pred = icd9_chap(c_labels_pred)\nlabels_pred_ml_c = np.array([ line.replace(',','').replace('[','').replace(']','').replace(\"'\",'').rstrip('\\n\\r').split(' ') for line in codecs.open('pred_labels_chap.txt', encoding=\"iso_8859-1\") ])\n\nfor i in range(len(labels_pred_ml_c)):\n if labels_pred_ml_c[i] == ['']: labels_pred_ml_c[i] = [str(c_labels_pred[i])]\n labels_pred_ml_c[i] = list(map(int,labels_pred_ml_c[i]))\n#%% ACCURACY, MACRO-AVERAGED PRECISION RECALL AND F1-SCORE FOR FULL-CODES, BLOCK AND CHAPTER\n\np_per_class = metrics.precision_score(c_labels_cid,c_labels_pred,average=None,labels=list(set(c_labels_cid)))\nr_per_class = metrics.recall_score(c_labels_cid,c_labels_pred,average=None,labels=list(set(c_labels_cid)))\nf1_per_class = metrics.f1_score(c_labels_cid,c_labels_pred,average=None,labels=list(set(c_labels_cid)))\n\nprint('\\n -> SINGLE-LABEL ACCURACY (FULL-CODE): %s' % metrics.accuracy_score(true_4,pred_4))\nprint('\\n -> Precision (FULL-CODE): %s' % metrics.precision_score(true_4,pred_4,average='macro'))\nprint('\\n -> Recall (FULL-CODE): %s' % metrics.recall_score(true_4,pred_4,average='macro'))\nprint('\\n -> F1 (FULL-CODE): %s' % metrics.f1_score(true_4,pred_4,average='macro'))\n\nprint('\\n -> SINGLE-LABEL ACCURACY (BLOCKS): %s' % metrics.accuracy_score(true_3,pred_3))\nprint('\\n -> Precision (BLOCKS): %s' % metrics.precision_score(true_3,pred_3,average='macro'))\nprint('\\n -> Recall (BLOCKS): %s' % metrics.recall_score(true_3,pred_3,average='macro'))\nprint('\\n -> F1 (BLOCKS): %s' % metrics.f1_score(true_3,pred_3,average='macro'))\n\nprint('\\n -> SINGLE-LABEL ACCURACY (CHAPTER): %s' % metrics.accuracy_score(c_labels_cid,c_labels_pred))\nprint('\\n -> Precision (CHAPTER): %s' % metrics.precision_score(c_labels_cid,c_labels_pred,average='macro'))\nprint('\\n -> Recall (CHAPTER): %s' % metrics.recall_score(c_labels_cid,c_labels_pred,average='macro'))\nprint('\\n -> F1 (CHAPTER): %s' % metrics.f1_score(c_labels_cid,c_labels_pred,average='macro'))\n\nprint('\\n -> PRECISION; RECALL; F1 SCORE: ')\nfor i in range(len(f1_per_class)):\n print('\\n | CLASS %s: %s ; %s ; %s' % (list(set(c_labels_cid))[i], p_per_class[i], r_per_class[i], f1_per_class[i]))\n \n#%%\nprint('\\n -> MULTI-LABEL PERFORMANCE METRICS (FULL-CODES):')\nprint('\\n -> Accuracy: %s' % ex_based_acc(labels_cid_ml, labels_pred_ml))\nprint('\\n -> Precision: %s' % ex_based_precision(labels_cid_ml, labels_pred_ml))\nprint('\\n -> Recall: %s' % ex_based_recall(labels_cid_ml, labels_pred_ml))\nprint('\\n -> F1: %s' % ex_based_f1(labels_cid_ml, labels_pred_ml))\nprint('\\n -> Hamming Loss: %s' % multi_hamming_loss(labels_cid_ml, labels_pred_ml))\nprint('\\n -> Exact Match: %s' % exact_match(labels_cid_ml, labels_pred_ml))\nprint('\\n -> One Error: %s' % one_error(labels_cid_ml, labels_pred_ml))\n\nprint('\\n -> MULTI-LABEL PERFORMANCE METRICS (BLOCKS):')\nprint('\\n -> Accuracy: %s' % ex_based_acc(labels_cid_ml_b, labels_pred_ml_b))\nprint('\\n -> Precision: %s' % ex_based_precision(labels_cid_ml_b, labels_pred_ml_b))\nprint('\\n -> Recall: %s' % ex_based_recall(labels_cid_ml_b, labels_pred_ml_b))\nprint('\\n -> F1: %s' % ex_based_f1(labels_cid_ml_b, labels_pred_ml_b))\nprint('\\n -> Hamming Loss: %s' % multi_hamming_loss(labels_cid_ml_b, labels_pred_ml_b))\nprint('\\n -> Exact Match: %s' % exact_match(labels_cid_ml_b, labels_pred_ml_b))\nprint('\\n -> One Error: %s' % one_error(labels_cid_ml_b, labels_pred_ml_b))\n\nprint('\\n -> MULTI-LABEL PERFORMANCE METRICS (CHAPTERS):')\nprint('\\n -> Accuracy: %s' % ex_based_acc(labels_cid_ml_c, labels_pred_ml_c))\nprint('\\n -> Precision: %s' % ex_based_precision(labels_cid_ml_c, labels_pred_ml_c))\nprint('\\n -> Recall: %s' % ex_based_recall(labels_cid_ml_c, labels_pred_ml_c))\nprint('\\n -> F1: %s' % ex_based_f1(labels_cid_ml_c, labels_pred_ml_c))\nprint('\\n -> Hamming Loss: %s' % multi_hamming_loss(labels_cid_ml_c, labels_pred_ml_c))\nprint('\\n -> Exact Match: %s' % exact_match(labels_cid_ml_c, labels_pred_ml_c))\nprint('\\n -> One Error: %s' % one_error(labels_cid_ml_c, labels_pred_ml_c))\n","sub_path":"Performance_evaluation.py","file_name":"Performance_evaluation.py","file_ext":"py","file_size_in_byte":9120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"566663874","text":"#!/usr/bin/env python\nimport rospy\nfrom submarine_msgs_srvs.msg import Detections\n\ndef talker():\n pub = rospy.Publisher('custom_chatter', Detections)\n rospy.init_node('custom_talker', anonymous=True)\n r = rospy.Rate(10) #10hz\n msg = Detections()\n msg.scores = [0, 1, 2, 3]\n msg.boxes = [4, 5, 6, 7]\n msg.classes = [8, 9, 10, 11]\n msg.detected = [12]\n\n while not rospy.is_shutdown():\n rospy.loginfo(msg)\n pub.publish(msg)\n r.sleep()\n \nif __name__ == '__main__':\n try:\n talker()\n except rospy.ROSInterruptException: \n pass\n","sub_path":"src/submarine_msgs_srvs/scripts/testPublisher.py","file_name":"testPublisher.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"147755669","text":"import json\r\nimport math\r\nfrom pprint import pprint\r\nfrom operator import itemgetter\r\n\r\n#parses the json and returns 2 maps plus the ingredient set\r\ndef parse_data(data):\r\n\tcCounts = {}\r\n\tiCounts = {}\r\n\tiTotals = {}\r\n\tfor i in range(len(data)):\r\n\t\tcuisineType = data[i]['cuisine']\r\n\t\tingredients = data[i]['ingredients']\r\n\t\t\r\n\t\t#increments the cuisine count\r\n\t\tif data[i]['cuisine'] in cCounts:\r\n\t\t\tcCounts[data[i]['cuisine']] = cCounts[data[i]['cuisine']] + 1\r\n\t\telse:\r\n\t\t\tcCounts[data[i]['cuisine']] = 1\r\n\t\t\t\r\n\t\t#increments the ingredient count\r\n\t\tfor ingr in ingredients:\r\n\t\t\tif ingr in iTotals:\r\n\t\t\t\tiTotals[ingr] = iTotals[ingr] + 1\r\n\t\t\telse:\r\n\t\t\t\tiTotals[ingr] = 1\r\n\t\t\r\n\t\t#increment the ingredient count\r\n\t\tif cuisineType in iCounts:\r\n\t\t\tfor j in range(len(ingredients)):\r\n\t\t\t\tif ingredients[j] in iCounts[cuisineType]:\r\n\t\t\t\t\tiCounts[cuisineType][ingredients[j]] = iCounts[cuisineType][ingredients[j]] + 1\r\n\t\t\t\telse:\r\n\t\t\t\t\tiCounts[cuisineType][ingredients[j]] = 1\r\n\t\t#Add a new cuisine\r\n\t\telse:\r\n\t\t\tiCounts[cuisineType] = {}\r\n\t\t\tfor j in range(len(ingredients)):\r\n\t\t\t\tiCounts[cuisineType][ingredients[j]] = 1\r\n\t\t\t\t\r\n\treturn (cCounts, iCounts, iTotals)\r\n\r\ndef calculate_cars(iCounts, iTotals, minSupport, minConfidence, rCount):\r\n\tcars = []\r\n\tfor cuisine in iCounts:\r\n\t\tfor ingr in iCounts[cuisine]:\r\n\t\t\tsupport = 1.0 * iCounts[cuisine][ingr] / rCount\r\n\t\t\tconfidence = 1.0 * iCounts[cuisine][ingr] / iTotals[ingr]\r\n\t\t\tif support >= minSupport and confidence >= minConfidence:\r\n\t\t\t\trule = (ingr, cuisine, support, confidence)\r\n\t\t\t\tcars.append(rule)\r\n\t\t\r\n\treturn cars\r\n\r\ndef create_classifier(cars, data, cCounts):\r\n\tclassifier = []\r\n\tnewData = data[:]\r\n\tsortedCars = sorted(cars, key=itemgetter(3,2), reverse=True)\r\n\tfor rule in cars:\r\n\t\tingr, cuisine, support, confidence = rule\r\n\t\ttemp = []\r\n\t\tflag = False\r\n\t\tfor recipe in newData:\r\n\t\t\tif ingr in recipe['ingredients'] and cuisine == recipe['cuisine']:\r\n\t\t\t\ttemp.append(recipe)\r\n\t\t\t\tflag = True\r\n\t\tif flag:\t\t\r\n\t\t\tfor recipe in temp:\r\n\t\t\t\tnewData.remove(recipe)\r\n\t\t\tclassifier.append((ingr,cuisine))\r\n\t\r\n\tprint(\"uncovered\")\r\n\tprint(len(newData))\r\n\t\r\n\tdefault = max(cCounts, key=cCounts.get)\r\n\tif len(newData) != 0:\r\n\t\tx,y,z = parse_data(newData)\r\n\t\tdefault = max(x, key=x.get)\r\n\t\r\n\treturn classifier, default\r\n\t\r\ndef classify(ingredients, classifier, default):\r\n\tfor rule in classifier:\r\n\t\tingr, cuisine = rule\r\n\t\tif ingr in ingredients:\r\n\t\t\treturn cuisine\r\n\treturn default\r\n\t\t\t\r\n#classifies a file\r\ndef main(train, test, out):\r\n\twith open(train) as data_file:\r\n\t\ttrainData = json.load(data_file)\r\n\r\n\twith open(test) as data_file:\r\n\t\ttestData = json.load(data_file)\r\n\t\t\r\n\tcuisineCounts, ingrCounts, ingrTotals = parse_data(trainData)\r\n\tcars = calculate_cars(ingrCounts,ingrTotals,5.0/len(trainData),0.6,len(trainData))\r\n\tclassifier, default = create_classifier(cars, trainData, cuisineCounts)\r\n\t#write to the file\r\n\tf = open(out, \"w\")\r\n\tf.write(\"id,cuisine\\n\")\r\n\tfor recipe in testData:\r\n\t\tid = recipe['id']\r\n\t\tingredients = recipe['ingredients']\r\n\t\tcuisine = classify(ingredients, classifier, default)\r\n\t\tf.write(\"%d,%s\\n\" % (id,cuisine))\r\n\tf.close()\r\n\r\n#everything below this is test code\r\n# with open('train.json') as data_file:\r\n\t# trainData = json.load(data_file)\r\n\r\n# x,y,z = parse_data(trainData)\r\n#c = calculate_cars(y,z,0,0.5,len(trainData))\r\n#d,e = create_classifier(c, trainData, x)\r\n\r\n# def test(sup,con):\r\n\tmain('train40k.json', 'test.json', 'outcba.csv')\r\n\t# c = calculate_cars(y,z,sup,con,len(trainData))\r\n\t# d,e = create_classifier(c, trainData, x)\r\n\r\n#main('train.json', 'test.json', 'outcbafinal.csv')\r\n\t\t","sub_path":"data/external/repositories_2to3/246285/kaggle-whats-cooking-master/cba.py","file_name":"cba.py","file_ext":"py","file_size_in_byte":3579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"553614317","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n\nfrom django.conf.urls import *\nfrom django.views.generic import TemplateView\n\n# main views\nurlpatterns = patterns('oberthmedia.homepage.views.main',\n url(r'^$', 'index', name='index'),\n url(r'^ueber/$', 'about', name='about'),\n url(r'^kontakt/$', 'contact', name='contact'),\n url(r'^agb/$', 'agb', name='agb'),\n url(r'^danke/$', 'contact_success', name='contact_success'),\n url(r'^impressum/$', 'sitenotice', name='sitenotice'),\n url(r'^referenz/(?P<refId>\\d+)/$', 'reference', name='reference'),\n url(r'^js/settings/', 'js_settings', name='js_settings'),\n url(r'^404/', TemplateView.as_view(template_name=\"404.html\")),\n #url(r'^logout/', 'logout_to_index', name='logout_to_index'),\n)\n\n#urlpatterns += patterns('django.contrib.auth.views',\n# url(r'^login/$', 'login', {'template_name': 'homepage/login.html'}, name='login'),\n#)\n","sub_path":"oberthmedia/homepage/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"12209613","text":"#coding=utf-8\nfrom django.conf.urls import url\nimport views\n\nurlpatterns = [\n\n url(r'^register.html/?$', views.register),# 注册\n url(r'^register_post/?$', views.register_post),# 获取内容\n url(r'^register_exist/?$', views.register_exist),\n\n url(r'^login.html/?$', views.login),# 登陆页面\n url(r'^login_handle/?$', views.login_handle),\n url(r'^logout/$',views.logout),# 退出\n\n url(r'^info/?$', views.info),# 用户中心\n url(r'^order(\\d*)/?$', views.order),# 用户订单\n url(r'^site/?$', views.site),# 收货地址\n\n url(r'^order/pay(\\d+)/?$', views.pay),# 收货地址\n]","sub_path":"snocks/sn_user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"582584327","text":"import csv\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom matplotlib.image import imread\r\nfrom matplotlib import pyplot as plt\r\nimport sys\r\nimport os\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.externals import joblib\r\nimport math\r\nfrom sklearn.decomposition import PCA\r\n\r\ndef moving_average(a, n=3):\r\n ret = np.cumsum(a, dtype=float)\r\n ret[n:] = ret[n:] - ret[:-n]\r\n return ret[n - 1:] / n\r\n\r\ndef recognize_number(src_addr,digit_total,numberis):\r\n #print('src_addr is %s'%src_addr)\r\n pre_lost=5#前面去掉10\r\n post_lost=5#后面去掉10\r\n windowsize=10#窗长\r\n hold_position=0\r\n #clf=SVC(gamma='auto',probability=True)\r\n #clf.fit(X_train,y_train)\r\n #joblib.dump(clf, 'cut.model')\r\n #clf=joblib.load('cut.model')#训练好了的SVM切割模型\r\n #src_addr='./bigdata/test/'+'036.csv'\r\n df1=pd.read_csv(src_addr)\r\n df=df1[pre_lost:-post_lost].reset_index(drop=True)\r\n tax=df.ACCx.values\r\n tay=df.ACCy.values\r\n taz=df.ACCz.values\r\n ax=tay\r\n ay=-taz\r\n az=-tax\r\n total_seg=np.zeros((digit_total,3,len(df.ACCx)))\r\n total_seg[0][0][0:len(ax)]=ax\r\n total_seg[0][1][0:len(ay)]=ay\r\n total_seg[0][2][0:len(az)]=az\r\n pca_plot(total_seg,digit_total,numberis)\r\n \r\ndef ownpca(X): # k is the components you want\r\n # mean of each feature\r\n n_samples, n_features = X.shape\r\n mean = np.array([np.mean(X[:, i]) for i in range(n_features)])\r\n # normalization\r\n norm_X = X - mean\r\n # scatter matrix\r\n scatter_matrix = np.dot(np.transpose(norm_X), norm_X)\r\n # Calculate the eigenvectors and eigenvalues\r\n eig_val, eig_vec = np.linalg.eig(scatter_matrix)\r\n\r\n return eig_val, eig_vec\r\n\r\ndef pca_plot(number_segs,digit_total,numberis):\r\n plt.ion()\r\n plt.figure()\r\n MAorder = 7\r\n for curnum in range(digit_total):\r\n # 移动平均处理,下标为0..MAorder-1这部分数据是NaN,不能进行运算的!很麻烦\r\n ax = moving_average(number_segs[curnum][0], MAorder)\r\n az = moving_average(number_segs[curnum][2], MAorder)\r\n ay = moving_average(number_segs[curnum][1], MAorder)\r\n print('len ax is'+' '+str(len(ax)))\r\n # 加速度的积分是速度\r\n vx = np.zeros(len(ax - MAorder + 1))\r\n vz = np.zeros(len(az - MAorder + 1))\r\n vy = np.zeros(len(ay - MAorder + 1))\r\n vx[0] = ax[MAorder - 1] # 不然后面j-1越界了,没有初始值\r\n vz[0] = az[MAorder - 1]\r\n vy[0] = ay[MAorder - 1]\r\n enhancex = ax.mean() # 抵消掉手抖的部分,静止时,测出来x轴自带-0.2左右的加速度,这个值不稳定,用均值代替\r\n enhancez = az.mean() # 同理,抵消z轴上的静态加速度\r\n enhancey = ay.mean()\r\n for j in range(1, len(ax) - MAorder + 1):\r\n vx[j] = vx[j - 1] + ax[j + MAorder - 1] - enhancex # 当前速度=前一刻速度+ (加速度-补偿)\r\n vz[j] = vz[j - 1] + az[j + MAorder - 1] - enhancez # 假设20ms内是匀加速\r\n vy[j] = vy[j - 1] + ay[j + MAorder - 1] - enhancey\r\n\r\n # 位移\r\n sudu = np.transpose(np.vstack((vx, vy, vz)))\r\n\r\n posy = np.zeros(len(vy))\r\n posx = np.zeros(len(vx))\r\n posz = np.zeros(len(vz))\r\n\r\n posx[0] = vx[0] # 不然后面j-1越界了\r\n posz[0] = vz[0]\r\n posy[0] = vy[0]\r\n\r\n for j in range(1, len(vx)):\r\n posx[j] = posx[j - 1] + vx[j] / 2 # 当前位移=前一刻位移+现在速度,假设在20ms内匀速运动\r\n posz[j] = posz[j - 1] + vz[j] / 2\r\n posy[j] = posy[j - 1] + vy[j] / 2\r\n\r\n data = np.transpose(np.vstack((posx, posy, posz)))\r\n e, d = ownpca(data)\r\n minindex = 0\r\n maxindex = 0\r\n midindex = 0\r\n for i in range(0, 3):\r\n #print(e[i])\r\n if e[i] < e[minindex]:\r\n minindex = i\r\n if e[i] > e[maxindex]:\r\n maxindex = i\r\n for i in range(0, 3):\r\n if i != minindex and i != maxindex:\r\n midindex = i\r\n #print(d[:, minindex])\r\n # minv = (d[:, minindex])\r\n minv = np.abs(d[:, minindex])\r\n newx = np.cross(minv, [0, 0, 1])\r\n newy = np.cross(minv, newx)\r\n # newx = d[:, maxindex]\r\n # newy = d[:, midindex]\r\n newz = minv\r\n\r\n newdata = np.linalg.inv(np.transpose(np.vstack((newx, newy, newz))))\r\n\r\n res = np.matmul(data, newdata)\r\n\r\n min0 = min(res[:, 0])\r\n plt.subplot(1,digit_total,curnum+1)\r\n \r\n plt.scatter(-res[:, 1], res[:, 0])\r\n #plt.scatter(-posz,posx)\r\n #plt.scatter(posx,-posz)\r\n plt.axis('off')\r\n plt.show()\r\n plt.title(str(numberis),fontsize=15)\r\n plt.pause(2)\r\n plt.close()\r\n plt.ioff()\r\n\r\n #plt.scatter(-posz,posx)\r\n #plt.show()\r\n\r\nif __name__ == \"__main__\":\r\n #clf=joblib.load('cut.model')#训练好了的SVM切割模型\r\n srcaddr=str(sys.argv[1])\r\n numberis=str(sys.argv[2])\r\n recognize_number(srcaddr,1,numberis)\r\n","sub_path":"2019_08_基于深度学习的移动端空中手写数字识别/final服务器整合_2_22/showsingle_horizon.py","file_name":"showsingle_horizon.py","file_ext":"py","file_size_in_byte":5091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"336288165","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 22 14:33:22 2019\n\n@author: Wilson\n\"\"\"\nfrom keras.models import load_model\nfrom keras.preprocessing import image\nimport numpy as np\n\nimport glob\nimport os\nimport shutil\n\n\n\n\n####################################################\n# Identifying single/multiple images\n##################################################\n\n\ndef rail_image_classifier(images, optimizer='rmsprop'):\n \"\"\"\n images: a single or a list of images with their path (e.g '/home/wilson/'railroad.png')\n optimizer: model optimizer \n \"\"\"\n best_model = load_model('sequential_categorical.h5') \n best_model.compile(loss = 'categorical_crossentropy',\n optimizer = optimizer,\n metrics=['accuracy'])\n \n img_width, img_height = 256, 256 #--- dimensions of our images\n \n for raw_img in images:\n img = image.load_img(raw_img, target_size=(img_width, img_height))\n img = image.img_to_array(img)/255.\n img = np.expand_dims(img, axis=0)\n \n pred = best_model.predict_classes(img)\n \n if pred[0] == 0:\n print(raw_img + ' is' + ' OTHER.') \n elif pred[0] == 1:\n print(raw_img + ' is' + ' RAILROAD.') \n \n return\n \n \nimages = ['other1.png', 'other2.png', 'other3.png', 'other4.png', 'rail1.png', 'rail2.png', \n 'rail3.png', 'rail4.png', 'rail5.png'] \n\n\n\n\n \n##############################################################\n# Separate images into different directory by prediction \n##############################################################\n \ndef railroad_classifier(dir_Dataset, dir_Railroad, dir_Other, filetype='png'):\n \"\"\"\n Collected images are sent to the different directory by their prediction\n \n * dir_dataset: directory path of collected images \n * dir_Railroad: directory path where images predicted as \"railroad\" will be \n * dir_Other: directory path where images predicted as \"other\" will be\n * filetype: image file extension, e.g. .png, jpg...\n \n \"\"\" \n \n ###=== Load the Best CNN model\n best_model = load_model('sequential_categorical.h5')\n best_model.compile(loss='categorical_crossentropy',\n optimizer='rmsprop',\n metrics=['accuracy'])\n\n\n ###=== Classify railroad and other images using CNN model\n img_width, img_height = 256, 256 #--- dimensions of our images\n \n collected_img_path = glob.glob(dir_Dataset + '*' + '.' + filetype)\n \n num_image_classified = 0 \n \n for raw_img in collected_img_path: \n img = image.load_img(raw_img, target_size=(img_width, img_height))\n img = image.img_to_array(img)/255.\n img = np.expand_dims(img, axis=0)\n \n pred = best_model.predict_classes(img)\n \n if pred[0] == 1:\n shutil.move(raw_img, dir_Railroad) \n elif pred[0] == 0:\n shutil.move(raw_img, dir_Other)\n \n num_image_classified += 1\n \n ###=== the number of images processed \n assert num_image_classified == len(collected_img_path), \"all images are classified\"\n print(\"The number of classified images: \" + str(num_image_classified))\n \n return \n \n\n#dir_Dataset = '/home/wilson/Documents/AgileBeat/tile-data_0523/' \n#dir_Railroad = '/home/wilson/Documents/AgileBeat/pred_railroad/'\n#dir_Other = '/home/wilson/Documents/AgileBeat/pred_other/'\n\n","sub_path":"Railroad_Classifier.py","file_name":"Railroad_Classifier.py","file_ext":"py","file_size_in_byte":3434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"45121981","text":"#Matthew Luerman\n#PSet 1\n#8 February 2018\n\nimport math\n\n\nclass Control:\n \"\"\"\n Provides a set of controls which provide useful and common functionality for a given simulated vehicle.\n Speed constraint: 5 <= s <= 10 in m/sec\n Rotational velocity constraint: -pi/4 <= w <= pi/4 in rad/sec\n \"\"\"\n def __init__(self, s, omega):\n \"\"\"Initializes values for class if inputs are valid\"\"\"\n if type(s) not in [int, float]:\n raise TypeError(\"Speed input must be an integer or float\")\n if type(omega) not in [int, float]:\n raise TypeError(\"Omega input must be an integer or float\")\n if not 5 <= s <= 10:\n raise ValueError(\"Speed input must be in range [5, 10] in m/sec\")\n if not -math.pi/4 <= omega <= math.pi/4:\n raise ValueError(\"Rotational velocity input must be in range [-pi/4, pi/4] in rad/sec\")\n self.s = s\n self.omega = omega\n\n def getSpeed(self):\n \"\"\"Returns the current speed value\"\"\"\n return self.s\n\n def getRotVel(self):\n \"\"\"Returns the current rotational velocity value\"\"\"\n return self.omega\n","sub_path":"Control.py","file_name":"Control.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"316395242","text":"# https://root.cern.ch/download/doc/RooFit_Users_Manual_2.91-33.pdf\n\nimport ROOT\n\nc1 = ROOT.TCanvas(\"c1\")\n\n\n\nfileFit = ROOT.TFile.Open(\"signal_bias_silvio/qq/atlas_silvio4/higgsCombineqq_420_lumi-27.637_r-1.362_CaloTrijet2016_atlas_silvio4.MaxLikelihoodFit.mH120.123456.root\")\nfileToys = ROOT.TFile.Open(\"signal_bias_silvio/qq/atlas_silvio4/higgsCombineqq_420_lumi-27.637_r-1.362_CaloTrijet2016_atlas_silvio4.GenerateOnly.mH120.123456.root\")\n\n\n\n\ntoys = fileToys.Get(\"toys\")\ntoy1 = toys.Get(\"toy_1\")\n\ntry:\n w = fileFit.Get(\"w\")\n if w == None:\n w = fileFit.Get(\"wCaloTrijet2016\")\n print(\"\\nWorkSpace:\")\n w.Print()\n print()\nexcept:\n print(\"CANNOT OPEN WORKSPACE!!!\")\n\nprint(\"\\toy5:\")\ntoy1.Print()\nprint()\n\ntry:\n pdf_index = w.cat(\"pdf_index\")\n pdf_index.setIndex(5)\n print(\"#\"*20)\n print(\"#\"*5 + \"I'm selecting\" + pdf_index.getLabel() + \"#\"*5 )\n print(\"#\"*20)\nexcept:\n pass\n\n#try:\n #shapeBkg_CaloTrijet2016_multi_CaloTrijet2016__norm = w.var(\"shapeBkg_CaloTrijet2016_multi_CaloTrijet2016__norm\")\n #shapeBkg_CaloTrijet2016_multi_CaloTrijet2016__norm.setVal(1)\n #shapeBkg_CaloTrijet2016_multi_CaloTrijet2016__norm.setConstant(ROOT.kTrue)\n#except:\n #pass\n\n#try:\n #r = w.var(\"r\")\n #r.setVal(1)\n #r.setConstant(ROOT.kTrue)\n#except:\n #pass\n\n\n#mjj = w.var(\"mjj\")\nth1x = w.var(\"th1x\")\n\nframe = th1x.frame()\n\n\n#data.plotOn(frame)\ntoy1.plotOn(frame)\n\n\n#w.pdf(\"pdf_binCaloTrijet2016\").printCompactTree()\n\n#function = w.pdf(\"pdf_binCaloTrijet2016\")\nfunction = w.pdf(\"pdf_binCaloTrijet2016_nuis\")\n\nfunction.fitTo(toy1,ROOT.RooFit.Range(\"Full\"),ROOT.RooFit.Extended(True),ROOT.RooFit.Offset(True),ROOT.RooFit.Strategy(2),ROOT.RooFit.PrintLevel(0)) \n\n\n#w.var(\"jer\").setConstant(ROOT.kTRUE)\n#w.var(\"jes\").setConstant(ROOT.kTRUE)\n#w.var(\"jer_In\").setConstant(ROOT.kTRUE)\n#w.var(\"jes_In\").setConstant(ROOT.kTRUE)\n#w.var(\"pm1_CaloTrijet2016\").setVal(-620)\n#w.var(\"pm1_CaloTrijet2016\").setVal(-530)\n\nnll = function.createNLL(toy1,ROOT.RooFit.Range(\"Full\"),ROOT.RooFit.Extended(True),ROOT.RooFit.Offset(True))\nm2 = ROOT.RooMinimizer(nll)\nm2.setPrintLevel(2)\nm2.setPrintEvalErrors(2)\nm2.setStrategy(2)\nm2.setMaxFunctionCalls(100000 * 10000)\nm2.setMaxIterations(100000 * 10000)\nmigrad_status = m2.minimize('Minuit2','migrad')\n\n\nc1.SetLogy()\nfunction.plotOn(frame)\nframe.Draw(\"\")\n\n\n#par.isConstant()\n#par.setConstant(ROOT.kTRUE)\n\n\n#r.Print()\n#shapeBkg_CaloTrijet2016_multi_CaloTrijet2016__norm.Print()\n\n\nprint(\"pdf index: \", pdf_index.getIndex() )\npdf_index.Print()\n\nc1.Update()\nc1.Modify()\n","sub_path":"python/PlotFittedToys.py","file_name":"PlotFittedToys.py","file_ext":"py","file_size_in_byte":2532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"519519516","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 19 16:34:04 2018\n\n@author: netzer\n\nGiven a text file (or list) containing card numbers which are already present in the\nDB (this may be a result of the application of card_data_import_check.py), the products in\na card data import file should be deleted before the import into the db is performed.\n\nThis script takes file name, path and the mentioned text file as inputs and deletes\nall the products in the xml containing those card numbers and outputs a cleaned\nversion of the file to be imported.\n\"\"\"\n\n\nfrom XMLs import card_import_xml\nimport os\nimport time\nfrom math import ceil\nimport sys\nfrom xml.etree import ElementTree as ET\n\n\n##################INPUT###############################################################\nxml_path = r\"R:\\ITdep\\Betriebe\\Kartennummern\\CHE\\Productions\\Live\" #path to file which is to be cleaned\nouter_filename = r'ZALL_crd_imp__20190523__000001.xml' #insert name of file to be cleaned\ncheck_results = r'check_result_ZALL_crd_imp__20190523__000001.txt' #insert filename for (new) cleaned file\nbrandp = 'ZALL' #Insert name of Brand Parnter, e.g. 'AMAA', 'GOGG\ncountry = 'CHE' #retailer country abbreviation (DEU,CHE,AUT)\n\n########################either fill in list OR use check_result file ###################################\nf = open(os.path.join(xml_path,check_results), 'r')\ncleaning_list = f.readlines()\ncleaning_list = [numbers.strip() for numbers in cleaning_list]\n#insert list here if text file containing card numbers does not exist:\n#cleaning_list = ['0491699066932000', '0491699066932000', '0491699066932000']\nprods_2b_elim = len(cleaning_list) #Anzahl der Produkte, die aus Import File eliminiert werden sollen\n########################either fill in list OR use check_result file ###################################\n##################INPUT###############################################################\n\n##################STOPWATCH###############################################################\nimport timeit\nstart_time = timeit.default_timer() #start time of computation\n##################STOPWATCH###############################################################\n\n\nxml_file = os.path.join(xml_path,outer_filename)\n\n\ntree = etree.parse(xml_file)\nfile_name, export_date, record_count = (tree.find('header/file_name')).text, (tree.find('header/export_date')).text,(tree.find('header/record_count')).text\nprint(file_name)\nprint(export_date)\nprint(record_count)\n\nproducts = (element for _, element in etree.iterparse(xml_file, tag='card'))\n\n\n######################open new xml and got to \"card\"-tag###################################################\nnewxml = etree.fromstring(card_import_xml)\n\nnew_file_name = newxml.find('header/file_name').text = outer_filename\n\n#new_file_name = newxml.find('header/file_name').text = brandp + '_crd_imp_' + time.strftime(\"%Y%m%d\") +'__' + '000000' + '.xml'\nprint(new_file_name)\n\nnewxml.find('header/export_date').text = time.strftime(\"%Y-%m-%d\")\nprint(newxml.find('header/export_date').text)\n\nnew_record_count = int(record_count) - prods_2b_elim\nnewxml.find('header/record_count').text = str(new_record_count)\nprint(newxml.find('header/record_count').text)\n\ncards = newxml.find('cards')\n######################open new xml and got to \"card\"-tag###################################################\n\ncounter = int(record_count)\n \nwhile counter:\n p = next(products, None) #None is the default value for when the sequence is done\n if p is None:\n\n break\n\n else:\n item = p.findtext('crd_no')\n if item not in cleaning_list:\n \n card = etree.SubElement(cards, 'card') \n crd_no = etree.SubElement(card, 'crd_no')\n crd_no.text = item\n \n ven = etree.SubElement(card, 'ven')\n ven.text = p.findtext('ven')\n \n pen = etree.SubElement(card, 'pen')\n pen.text = p.findtext('pen')\n \n prt = etree.SubElement(card, 'prt')\n prt.text = p.findtext('prt')\n \n brand = etree.SubElement(card, 'brand')\n brand.text = p.findtext('brand')\n \n week = etree.SubElement(card, 'week')\n week.text = time.strftime(\"%W\")\n \n year = etree.SubElement(card, 'year')\n year.text = time.strftime(\"%Y\")\n \n crd_value = etree.SubElement(card, 'crd_value')\n crd_value.text = p.findtext('crd_value')\n \n else:\n print(item + ' eliminated')\n \n counter = counter - 1\n\nno_of_prods = newxml.find('header/record_count').text\nprint('Number of products written into new import file: ' + str(no_of_prods))\nf.close()\n\n\ntree = ET.ElementTree(newxml)\ntree.write(os.path.join(xml_path, '___' + outer_filename), encoding='utf-8', method='xml')\n\n\n##################STOPWATCH###############################################################\nprint('duration: ' + str((timeit.default_timer() - start_time)/60.0) + ' min')\n##################STOPWATCH###############################################################\nprint('a new clean version of the xml is available!')","sub_path":"clean_card_data_import.py","file_name":"clean_card_data_import.py","file_ext":"py","file_size_in_byte":5193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"555801623","text":"import random\nfrom datetime import datetime\n\nimport numpy as np\nimport ray\nfrom ray import tune\nfrom ray.rllib.models import ModelCatalog\nfrom ray.rllib.models.torch.fcnet import FullyConnectedNetwork as TorchFC\nfrom ray.rllib.models.torch.torch_modelv2 import TorchModelV2\nfrom ray.rllib.utils.framework import try_import_torch\n# from environment.flappy_bird.flappy_bird_env import FlappyBirdEnv\nfrom ray.tune import Callback\nfrom ray.tune.registry import register_env\n\ntorch, nn = try_import_torch()\n\n\n# custom_input_space = spaces.Box(low=-np.inf, high=np.inf, shape=(2,), dtype=np.float32)\n\n\nclass TorchCustomModel(TorchModelV2, nn.Module):\n \"\"\"Example of a PyTorch custom model that just delegates to a fc-net.\"\"\"\n\n def __init__(self, obs_space, action_space, num_outputs, model_config, name):\n TorchModelV2.__init__(self, obs_space, action_space, num_outputs, model_config, name)\n nn.Module.__init__(self)\n\n self.torch_sub_model = TorchFC(obs_space, action_space, num_outputs, model_config, name)\n\n def forward(self, input_dict, state, seq_lens):\n # input_dict[\"obs\"] = input_dict[\"obs\"].float()[:, -2:]\n fc_out, _ = self.torch_sub_model(input_dict, state, seq_lens)\n return fc_out, []\n\n def value_function(self):\n return torch.reshape(self.torch_sub_model.value_function(), [-1])\n\n\nclass MyCallback(Callback):\n def on_train_result(self, iteration, trials, trial, result, **info):\n result = info[\"result\"]\n if result[\"episode_reward_mean\"] > 6500:\n phase = 1\n else:\n phase = 0\n trainer = info[\"trainer\"]\n trainer.workers.foreach_worker(\n lambda ev: ev.foreach_env(\n lambda env: env.set_phase(phase)))\n\n\ndef get_PPO_config(seed, use_gpu: float = 1):\n ModelCatalog.register_custom_model(\"my_model\", TorchCustomModel)\n config = {\"env\": \"flappy_bird\", #\n \"model\": {\"custom_model\": \"my_model\", \"fcnet_hiddens\": [64, 64], \"fcnet_activation\": \"relu\"}, # model config,\" \"custom_model\": \"my_model\"\n \"vf_share_layers\": False,\n \"lr\": 5e-4,\n \"num_gpus\": use_gpu,\n \"vf_clip_param\": 100000,\n \"grad_clip\": 2500,\n \"clip_rewards\": 100,\n \"num_workers\": 3, # parallelism\n \"num_envs_per_worker\": 10,\n \"batch_mode\": \"truncate_episodes\",\n \"evaluation_interval\": 10,\n \"evaluation_num_episodes\": 20,\n \"use_gae\": True, #\n \"lambda\": 0.95, # gae lambda param\n \"num_sgd_iter\": 10,\n \"train_batch_size\": 4000,\n \"sgd_minibatch_size\": 1024,\n \"rollout_fragment_length\": 200,\n \"framework\": \"torch\",\n \"horizon\": 1000,\n \"seed\": seed,\n \"evaluation_config\": {\n # Example: overriding env_config, exploration, etc:\n # \"env_config\": {...},\n \"explore\": False\n },\n # \"env_config\": {\"cost_fn\": tune.grid_search([0, 1, 2]),\n # \"tau\": tune.grid_search([0.001, 0.02, 0.005])}\n }\n return config\n\n\ndef env_creator(env_config):\n import flappy_bird_gym\n env = flappy_bird_gym.make(\"FlappyBird-v0\")\n return env\n\n\nif __name__ == \"__main__\":\n seed = 1234\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n ray.init(local_mode=False, include_dashboard=True, log_to_driver=False)\n register_env(\"flappy_bird\", env_creator)\n import flappy_bird_gym\n\n env = flappy_bird_gym.make(\"FlappyBird-v0\")\n config = get_PPO_config(use_gpu=0.5, seed=seed)\n datetime_str = datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")\n tune.run(\n \"PPO\",\n stop={\"info/num_steps_trained\": 2e7, \"episode_reward_mean\": 7950},\n config=config,\n name=f\"tune_PPO_flappy_bird\",\n checkpoint_freq=10,\n checkpoint_at_end=True,\n log_to_file=True,\n callbacks=[MyCallback()],\n # resume=\"PROMPT\",\n verbose=1,\n )\n ray.shutdown()\n","sub_path":"training/ppo/tune/tune_train_PPO_flappy_bird.py","file_name":"tune_train_PPO_flappy_bird.py","file_ext":"py","file_size_in_byte":4128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"382990080","text":"\"\"\"\nThis module implements the visualization for the plot(df) function.\n\"\"\" # pylint: disable=too-many-lines\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Tuple, Union\n\nimport numpy as np\nimport pandas as pd\nfrom bokeh.layouts import row\nfrom bokeh.models import (\n BasicTicker,\n ColorBar,\n ColumnDataSource,\n CustomJSHover,\n Div,\n FactorRange,\n FuncTickFormatter,\n HoverTool,\n LayoutDOM,\n Legend,\n LegendItem,\n LinearColorMapper,\n Panel,\n PrintfTickFormatter,\n Tabs,\n)\nfrom bokeh.plotting import Figure, figure\nfrom bokeh.transform import cumsum, linear_cmap, transform\nfrom bokeh.util.hex import hexbin\nfrom PIL import Image\nfrom scipy.stats import norm\nfrom wordcloud import WordCloud\n\nfrom ..dtypes import Continuous, DateTime, Nominal, is_dtype\nfrom ..intermediate import Intermediate\nfrom ..palette import CATEGORY20, PASTEL1, RDBU, VIRIDIS\n\n__all__ = [\"render\"]\n\n\ndef tweak_figure(\n fig: Figure,\n ptype: Optional[str] = None,\n show_yticks: bool = False,\n max_lbl_len: int = 15,\n) -> None:\n \"\"\"\n Set some common attributes for a figure\n \"\"\"\n fig.axis.major_label_text_font_size = \"9pt\"\n fig.title.text_font_size = \"10pt\"\n fig.axis.minor_tick_line_color = \"white\"\n if ptype in [\"pie\", \"qq\", \"heatmap\"]:\n fig.ygrid.grid_line_color = None\n if ptype in [\"bar\", \"pie\", \"hist\", \"kde\", \"qq\", \"heatmap\", \"line\"]:\n fig.xgrid.grid_line_color = None\n if ptype in [\"bar\", \"hist\", \"line\"] and not show_yticks:\n fig.ygrid.grid_line_color = None\n fig.yaxis.major_label_text_font_size = \"0pt\"\n fig.yaxis.major_tick_line_color = None\n if ptype in [\"bar\", \"nested\", \"stacked\", \"heatmap\", \"box\"]:\n fig.xaxis.major_label_orientation = np.pi / 3\n fig.xaxis.formatter = FuncTickFormatter(\n code=\"\"\"\n if (tick.length > %d) return tick.substring(0, %d-2) + '...';\n else return tick;\n \"\"\"\n % (max_lbl_len, max_lbl_len)\n )\n if ptype in [\"nested\", \"stacked\", \"box\"]:\n fig.xgrid.grid_line_color = None\n if ptype in [\"nested\", \"stacked\"]:\n fig.y_range.start = 0\n fig.x_range.range_padding = 0.03\n if ptype in [\"line\", \"boxnum\"]:\n fig.min_border_right = 20\n fig.xaxis.major_label_standoff = 7\n fig.xaxis.major_label_orientation = 0\n fig.xaxis.major_tick_line_color = None\n\n\ndef _make_title(grp_cnt_stats: Dict[str, int], x: str, y: str) -> str:\n \"\"\"\n Format the title to notify the user of sampled output\n \"\"\"\n x_ttl, y_ttl = None, None\n if f\"{x}_ttl\" in grp_cnt_stats:\n x_ttl = grp_cnt_stats[f\"{x}_ttl\"]\n x_shw = grp_cnt_stats[f\"{x}_shw\"]\n if f\"{y}_ttl\" in grp_cnt_stats:\n y_ttl = grp_cnt_stats[f\"{y}_ttl\"]\n y_shw = grp_cnt_stats[f\"{y}_shw\"]\n if x_ttl and y_ttl:\n if x_ttl > x_shw and y_ttl > y_shw:\n return (\n f\"(top {y_shw} out of {y_ttl}) {y} by (top {x_shw} out of {x_ttl}) {x}\"\n )\n elif x_ttl:\n if x_ttl > x_shw:\n return f\"{y} by (top {x_shw} out of {x_ttl}) {x}\"\n elif y_ttl:\n if y_ttl > y_shw:\n return f\"(top {y_shw} out of {y_ttl}) {y} by {x}\"\n return f\"{y} by {x}\"\n\n\ndef _format_ticks(ticks: List[float]) -> List[str]:\n \"\"\"\n Format the tick values\n \"\"\"\n formatted_ticks = []\n for tick in ticks: # format the tick values\n before, after = f\"{tick:e}\".split(\"e\")\n if float(after) > 1e15 or abs(tick) < 1e4:\n formatted_ticks.append(str(tick))\n continue\n mod_exp = int(after) % 3\n factor = 1 if mod_exp == 0 else 10 if mod_exp == 1 else 100\n value = np.round(float(before) * factor, len(str(before)))\n value = int(value) if value.is_integer() else value\n if abs(tick) >= 1e12:\n formatted_ticks.append(str(value) + \"T\")\n elif abs(tick) >= 1e9:\n formatted_ticks.append(str(value) + \"B\")\n elif abs(tick) >= 1e6:\n formatted_ticks.append(str(value) + \"M\")\n elif abs(tick) >= 1e4:\n formatted_ticks.append(str(value) + \"K\")\n\n return formatted_ticks\n\n\ndef _format_axis(fig: Figure, minv: int, maxv: int, axis: str) -> None:\n \"\"\"\n Format the axis ticks\n \"\"\" # pylint: disable=too-many-locals\n # divisor for 5 ticks (5 results in ticks that are too close together)\n divisor = 4.5\n # interval\n gap = (maxv - minv) / divisor\n # get exponent from scientific notation\n _, after = f\"{gap:.0e}\".split(\"e\")\n # round to this amount\n round_to = -1 * int(after)\n # round the first x tick\n minv = np.round(minv, round_to)\n # round value between ticks\n gap = np.round(gap, round_to)\n\n # make the tick values\n ticks = [float(minv)]\n while max(ticks) + gap < maxv:\n ticks.append(max(ticks) + gap)\n ticks = np.round(ticks, round_to)\n ticks = [int(tick) if tick.is_integer() else tick for tick in ticks]\n formatted_ticks = _format_ticks(ticks)\n\n if axis == \"x\":\n fig.xgrid.ticker = ticks\n fig.xaxis.ticker = ticks\n fig.xaxis.major_label_overrides = dict(zip(ticks, formatted_ticks))\n fig.xaxis.major_label_text_font_size = \"10pt\"\n fig.xaxis.major_label_standoff = 7\n # fig.xaxis.major_label_orientation = 0\n fig.xaxis.major_tick_line_color = None\n elif axis == \"y\":\n fig.ygrid.ticker = ticks\n fig.yaxis.ticker = ticks\n fig.yaxis.major_label_overrides = dict(zip(ticks, formatted_ticks))\n fig.yaxis.major_label_text_font_size = \"10pt\"\n fig.yaxis.major_label_standoff = 5\n\n\ndef _format_bin_intervals(bins_arr: np.ndarray) -> List[str]:\n \"\"\"\n Auxillary function to format bin intervals in a histogram\n \"\"\"\n bins_arr = np.round(bins_arr, 3)\n bins_arr = [int(val) if float(val).is_integer() else val for val in bins_arr]\n intervals = [\n f\"[{bins_arr[i]}, {bins_arr[i + 1]})\" for i in range(len(bins_arr) - 2)\n ]\n intervals.append(f\"[{bins_arr[-2]},{bins_arr[-1]}]\")\n return intervals\n\n\ndef _format_values(key: str, value: Any) -> str:\n\n if not isinstance(value, (int, float)):\n # if value is a time\n return str(value)\n\n if \"Memory\" in key:\n # for memory usage\n ind = 0\n unit = dict(enumerate([\"B\", \"KB\", \"MB\", \"GB\", \"TB\"], 0))\n while value > 1024:\n value /= 1024\n ind += 1\n return f\"{value:.1f} {unit[ind]}\"\n\n if (value * 10) % 10 == 0:\n # if value is int but in a float form with 0 at last digit\n value = int(value)\n if abs(value) >= 1000000:\n return f\"{value:.5g}\"\n elif abs(value) >= 1000000 or abs(value) < 0.001:\n value = f\"{value:.5g}\"\n elif abs(value) >= 1:\n # eliminate trailing zeros\n pre_value = float(f\"{value:.4f}\")\n value = int(pre_value) if (pre_value * 10) % 10 == 0 else pre_value\n elif 0.001 <= abs(value) < 1:\n value = f\"{value:.4g}\"\n else:\n value = str(value)\n\n if \"%\" in key:\n # for percentage, only use digits before notation sign for extreme small number\n value = f\"{float(value):.1%}\"\n return str(value)\n\n\ndef _create_table_row(key: str, value: Union[str, int], highlight: bool = False) -> str:\n \"\"\"\n Create table row for stats panel\n \"\"\"\n template_stats_data = \"\"\"\n <tr style=\"border-bottom: 1px solid;\">\n <th style=\"text-align: left\">{key}</th>\n <td style=\"text-align: left\">{value}</td>\n </tr>\n \"\"\"\n template_stats_data_red = \"\"\"\n <tr style=\"color: #f00; border-bottom: 1px solid;\">\n <th style=\"text-align: left\">{key}</th>\n <td style=\"text-align: left\">{value}</td>\\\n </tr>\n \"\"\"\n return (\n template_stats_data_red.format(key=key, value=value)\n if highlight\n else template_stats_data.format(key=key, value=value)\n )\n\n\ndef _sci_notation_superscript(value: str) -> str:\n \"\"\"\n Strip off character e in scientific notation to a superscript tag\n \"\"\"\n if \"e+\" in value:\n value = value.replace(\"e+\", \"×10<sup>\") + \"</sup>\"\n elif \"e-\" in value:\n value = value.replace(\"e\", \"×10<sup>\") + \"</sup>\"\n return value\n\n\ndef wordcloud_viz(word_cnts: pd.Series, plot_width: int, plot_height: int,) -> Panel:\n \"\"\"\n Visualize the word cloud\n \"\"\" # pylint: disable=unsubscriptable-object\n ellipse_mask = np.array(\n Image.open(f\"{Path(__file__).parent.parent.parent}/assets/ellipse.jpg\")\n )\n wordcloud = WordCloud(\n background_color=\"white\", mask=ellipse_mask, width=800, height=400\n )\n wordcloud.generate_from_frequencies(word_cnts)\n wcimg = wordcloud.to_array().astype(np.uint8)\n alpha = np.full([*wcimg.shape[:2], 1], 255, dtype=np.uint8)\n wcimg = np.concatenate([wcimg, alpha], axis=2)[::-1, :]\n\n fig = figure(\n plot_width=plot_width,\n plot_height=plot_height,\n title=\"Word Cloud\",\n x_range=(0, 1),\n y_range=(0, 1),\n toolbar_location=None,\n )\n fig.image_rgba(image=[wcimg], x=0, y=0, dh=1, dw=1)\n\n fig.axis.visible = False\n fig.grid.visible = False\n return Panel(child=row(fig), title=\"Word Cloud\")\n\n\ndef wordfreq_viz(\n word_cnts: pd.Series,\n nrows: int,\n plot_width: int,\n plot_height: int,\n show_yticks: bool,\n) -> Figure:\n \"\"\"\n Visualize the word frequency bar chart\n \"\"\"\n col = word_cnts.name\n df = word_cnts.to_frame()\n df[\"pct\"] = df[col] / nrows * 100\n\n tooltips = [(\"Word\", \"@index\"), (\"Count\", f\"@{col}\"), (\"Percent\", \"@pct{0.2f}%\")]\n fig = figure(\n plot_width=plot_width,\n plot_height=plot_height,\n title=\"Word Frequencies\",\n toolbar_location=None,\n tools=\"hover\",\n tooltips=tooltips,\n x_range=list(df.index),\n )\n fig.vbar(x=\"index\", top=col, width=0.9, source=df)\n fig.yaxis.axis_label = \"Count\"\n tweak_figure(fig, \"bar\", show_yticks)\n _format_axis(fig, 0, df[col].max(), \"y\")\n return Panel(child=row(fig), title=\"Word Frequencies\")\n\n\ndef bar_viz(\n df: pd.DataFrame,\n ttl_grps: int,\n nrows: int,\n col: str,\n yscale: str,\n plot_width: int,\n plot_height: int,\n show_yticks: bool,\n) -> Figure:\n \"\"\"\n Render a bar chart\n \"\"\"\n # pylint: disable=too-many-arguments\n df[\"pct\"] = df[col] / nrows * 100\n df.index = [str(val) for val in df.index]\n\n tooltips = [(col, \"@index\"), (\"Count\", f\"@{{{col}}}\"), (\"Percent\", \"@pct{0.2f}%\")]\n if show_yticks:\n if len(df) > 10:\n plot_width = 28 * len(df)\n fig = Figure(\n plot_width=plot_width,\n plot_height=plot_height,\n title=col,\n toolbar_location=None,\n tooltips=tooltips,\n tools=\"hover\",\n x_range=list(df.index),\n y_axis_type=yscale,\n )\n fig.vbar(x=\"index\", width=0.9, top=col, bottom=0.01, source=df)\n tweak_figure(fig, \"bar\", show_yticks)\n fig.yaxis.axis_label = \"Count\"\n if ttl_grps > len(df):\n fig.xaxis.axis_label = f\"Top {len(df)} of {ttl_grps} {col}\"\n fig.xaxis.axis_label_standoff = 0\n if show_yticks and yscale == \"linear\":\n _format_axis(fig, 0, df[col].max(), \"y\")\n return fig\n\n\ndef pie_viz(\n df: pd.DataFrame, nrows: int, col: str, plot_width: int, plot_height: int,\n) -> Panel:\n \"\"\"\n Render a pie chart\n \"\"\"\n npresent = df[col].sum()\n if nrows > npresent:\n df = df.append(pd.DataFrame({col: [nrows - npresent]}, index=[\"Others\"]))\n df[\"pct\"] = df[col] / nrows * 100\n df[\"angle\"] = df[col] / npresent * 2 * np.pi\n\n tooltips = [(col, \"@index\"), (\"Count\", f\"@{col}\"), (\"Percent\", \"@pct{0.2f}%\")]\n fig = Figure(\n plot_width=plot_width,\n plot_height=plot_height,\n title=col,\n toolbar_location=None,\n tools=\"hover\",\n tooltips=tooltips,\n )\n color_list = CATEGORY20 * (len(df) // len(CATEGORY20) + 1)\n df[\"colour\"] = color_list[0 : len(df)]\n df.index = df.index.astype(str)\n df.index = df.index.map(lambda x: x[0:13] + \"...\" if len(x) > 13 else x)\n\n pie = fig.wedge(\n x=0,\n y=1,\n radius=0.9,\n start_angle=cumsum(\"angle\", include_zero=True),\n end_angle=cumsum(\"angle\"),\n line_color=\"white\",\n fill_color=\"colour\",\n source=df,\n )\n legend = Legend(items=[LegendItem(label=dict(field=\"index\"), renderers=[pie])])\n legend.label_text_font_size = \"8pt\"\n fig.add_layout(legend, \"right\")\n tweak_figure(fig, \"pie\")\n fig.axis.major_label_text_font_size = \"0pt\"\n fig.axis.major_tick_line_color = None\n return Panel(child=row(fig), title=\"Pie Chart\")\n\n\ndef hist_viz(\n hist: Tuple[np.ndarray, np.ndarray],\n nrows: int,\n col: str,\n yscale: str,\n plot_width: int,\n plot_height: int,\n show_yticks: bool,\n) -> Figure:\n \"\"\"\n Render a histogram\n \"\"\"\n # pylint: disable=too-many-arguments,too-many-locals\n counts, bins = hist\n intvls = _format_bin_intervals(bins)\n df = pd.DataFrame(\n {\n \"intvl\": intvls,\n \"left\": bins[:-1],\n \"right\": bins[1:],\n \"freq\": counts,\n \"pct\": counts / nrows * 100,\n }\n )\n\n tooltips = [(\"Bin\", \"@intvl\"), (\"Frequency\", \"@freq\"), (\"Percent\", \"@pct{0.2f}%\")]\n fig = Figure(\n plot_width=plot_width,\n plot_height=plot_height,\n title=col,\n toolbar_location=None,\n tools=\"\",\n y_axis_type=yscale,\n )\n bottom = 0 if yscale == \"linear\" or df.empty else df[\"freq\"].min() / 2\n fig.quad(\n source=df,\n left=\"left\",\n right=\"right\",\n bottom=bottom,\n alpha=0.5,\n top=\"freq\",\n fill_color=\"#6baed6\",\n )\n hover = HoverTool(tooltips=tooltips, mode=\"vline\",)\n fig.add_tools(hover)\n tweak_figure(fig, \"hist\", show_yticks)\n fig.yaxis.axis_label = \"Frequency\"\n if not df.empty:\n _format_axis(fig, df.iloc[0][\"left\"], df.iloc[-1][\"right\"], \"x\")\n if show_yticks:\n fig.xaxis.axis_label = col\n if yscale == \"linear\":\n _format_axis(fig, 0, df[\"freq\"].max(), \"y\")\n\n return fig\n\n\ndef kde_viz(\n hist: Tuple[np.ndarray, np.ndarray],\n kde: np.ndarray,\n col: str,\n yscale: str,\n plot_width: int,\n plot_height: int,\n) -> Panel:\n \"\"\"\n Render histogram with overlayed kde\n \"\"\"\n # pylint: disable=too-many-arguments, too-many-locals\n dens, bins = hist\n intvls = _format_bin_intervals(bins)\n df = pd.DataFrame(\n {\"intvl\": intvls, \"left\": bins[:-1], \"right\": bins[1:], \"dens\": dens,}\n )\n fig = Figure(\n plot_width=plot_width,\n plot_height=plot_height,\n title=col,\n tools=\"\",\n toolbar_location=None,\n y_axis_type=yscale,\n )\n bottom = 0 if yscale == \"linear\" or df.empty else df[\"dens\"].min() / 2\n hist = fig.quad(\n source=df,\n left=\"left\",\n right=\"right\",\n bottom=bottom,\n alpha=0.5,\n top=\"dens\",\n fill_color=\"#6baed6\",\n )\n hover_hist = HoverTool(\n renderers=[hist],\n tooltips=[(\"Bin\", \"@intvl\"), (\"Density\", \"@dens\")],\n mode=\"vline\",\n )\n pts_rng = np.linspace(df.loc[0, \"left\"], df.loc[len(df) - 1, \"right\"], 1000)\n pdf = kde(pts_rng)\n line = fig.line( # pylint: disable=too-many-function-args\n pts_rng, pdf, line_color=\"#9467bd\", line_width=2, alpha=0.5\n )\n hover_dist = HoverTool(renderers=[line], tooltips=[(\"x\", \"@x\"), (\"y\", \"@y\")])\n fig.add_tools(hover_hist)\n fig.add_tools(hover_dist)\n tweak_figure(fig, \"kde\")\n fig.yaxis.axis_label = \"Density\"\n fig.xaxis.axis_label = col\n _format_axis(fig, df.iloc[0][\"left\"], df.iloc[-1][\"right\"], \"x\")\n if yscale == \"linear\":\n _format_axis(fig, 0, max(df[\"dens\"].max(), pdf.max()), \"y\")\n return Panel(child=fig, title=\"KDE Plot\")\n\n\ndef qqnorm_viz(\n qntls: pd.Series,\n mean: float,\n std: float,\n col: str,\n plot_width: int,\n plot_height: int,\n) -> Panel:\n \"\"\"\n Render a qq plot\n \"\"\"\n # pylint: disable=too-many-arguments\n theory_qntls = norm.ppf(np.linspace(0.01, 0.99, 99), mean, std)\n tooltips = [(\"x\", \"@x\"), (\"y\", \"@y\")]\n fig = Figure(\n plot_width=plot_width,\n plot_height=plot_height,\n title=col,\n tools=\"hover\",\n toolbar_location=None,\n tooltips=tooltips,\n )\n fig.circle(\n x=theory_qntls, y=qntls, size=3, color=CATEGORY20[0],\n )\n vals = np.concatenate((theory_qntls, qntls))\n fig.line(x=[vals.min(), vals.max()], y=[vals.min(), vals.max()], color=\"red\")\n tweak_figure(fig, \"qq\")\n fig.xaxis.axis_label = \"Normal Quantiles\"\n fig.yaxis.axis_label = f\"Quantiles of {col}\"\n _format_axis(fig, vals.min(), vals.max(), \"x\")\n _format_axis(fig, vals.min(), vals.max(), \"y\")\n return Panel(child=fig, title=\"Normal Q-Q Plot\")\n\n\ndef univar_box_viz(\n box_data: Dict[str, Any], col: str, plot_width: int, plot_height: int,\n) -> Panel:\n \"\"\"\n Render a box plot visualization\n \"\"\"\n # pylint: disable=too-many-arguments,too-many-locals,too-many-statements\n otlrs = box_data.pop(\"otlrs\")\n df = pd.DataFrame(box_data, index=[0])\n\n fig = figure(\n plot_width=plot_width,\n plot_height=plot_height,\n title=col,\n toolbar_location=None,\n tools=\"\",\n x_range=list(df[\"grp\"]),\n )\n utail = fig.segment(\n x0=\"grp\", y0=\"uw\", x1=\"grp\", y1=\"q3\", line_color=\"black\", source=df\n )\n ltail = fig.segment(\n x0=\"grp\", y0=\"lw\", x1=\"grp\", y1=\"q1\", line_color=\"black\", source=df\n )\n ubox = fig.vbar(\n x=\"grp\",\n width=0.7,\n top=\"q3\",\n bottom=\"q2\",\n fill_color=CATEGORY20[0],\n line_color=\"black\",\n source=df,\n )\n lbox = fig.vbar(\n x=\"grp\",\n width=0.7,\n top=\"q2\",\n bottom=\"q1\",\n fill_color=CATEGORY20[0],\n line_color=\"black\",\n source=df,\n )\n loww = fig.segment(\n x0=\"x0\", y0=\"lw\", x1=\"x1\", y1=\"lw\", line_color=\"black\", source=df\n )\n upw = fig.segment(x0=\"x0\", y0=\"uw\", x1=\"x1\", y1=\"uw\", line_color=\"black\", source=df)\n if otlrs.any():\n otlrs = np.random.choice(otlrs, size=100)\n otlrs_grp = [col] * len(otlrs)\n circ = fig.circle( # pylint: disable=too-many-function-args\n otlrs_grp,\n otlrs,\n size=3,\n line_color=\"black\",\n color=CATEGORY20[6],\n fill_alpha=0.6,\n )\n fig.add_tools(HoverTool(renderers=[circ], tooltips=[(\"Outlier\", \"@y\")],))\n tooltips = [\n (\"Upper Whisker\", \"@uw\"),\n (\"Upper Quartile\", \"@q3\"),\n (\"Median\", \"@q2\"),\n (\"Lower Quartile\", \"@q1\"),\n (\"Lower Whisker\", \"@lw\"),\n ]\n fig.add_tools(\n HoverTool(\n renderers=[upw, utail, ubox, lbox, ltail, loww],\n tooltips=tooltips,\n point_policy=\"follow_mouse\",\n )\n )\n tweak_figure(fig, \"box\")\n fig.xaxis.major_tick_line_color = None\n fig.xaxis.major_label_text_font_size = \"0pt\"\n fig.yaxis.axis_label = col\n\n minw = otlrs.min() if otlrs.any() else np.nan\n maxw = otlrs.max() if otlrs.any() else np.nan\n _format_axis(fig, min(df[\"lw\"].min(), minw), max(df[\"uw\"].max(), maxw), \"y\")\n\n return Panel(child=fig, title=\"Box Plot\")\n\n\ndef box_viz(\n df: pd.DataFrame,\n outx: List[str],\n outy: List[float],\n x: str,\n plot_width: int,\n plot_height: int,\n y: Optional[str] = None,\n grp_cnt_stats: Optional[Dict[str, int]] = None,\n timeunit: Optional[str] = None,\n) -> Panel:\n \"\"\"\n Render a box plot visualization\n \"\"\"\n # pylint: disable=too-many-arguments,too-many-locals,too-many-statements\n if y:\n width = 0.7 if grp_cnt_stats else 0.93\n title = _make_title(grp_cnt_stats, x, y) if grp_cnt_stats else f\"{y} by {x}\"\n else:\n width = 0.7\n title = f\"{x}\"\n\n if len(df) > 10:\n plot_width = 39 * len(df)\n fig = figure(\n tools=\"\",\n x_range=list(df[\"grp\"]),\n toolbar_location=None,\n title=title,\n plot_width=plot_width,\n plot_height=plot_height,\n )\n utail = fig.segment(\n x0=\"grp\", y0=\"uw\", x1=\"grp\", y1=\"q3\", line_color=\"black\", source=df\n )\n ltail = fig.segment(\n x0=\"grp\", y0=\"lw\", x1=\"grp\", y1=\"q1\", line_color=\"black\", source=df\n )\n ubox = fig.vbar(\n x=\"grp\",\n width=width,\n top=\"q3\",\n bottom=\"q2\",\n fill_color=CATEGORY20[0],\n line_color=\"black\",\n source=df,\n )\n lbox = fig.vbar(\n x=\"grp\",\n width=width,\n top=\"q2\",\n bottom=\"q1\",\n fill_color=CATEGORY20[0],\n line_color=\"black\",\n source=df,\n )\n loww = fig.segment(\n x0=\"x0\", y0=\"lw\", x1=\"x1\", y1=\"lw\", line_color=\"black\", source=df\n )\n upw = fig.segment(x0=\"x0\", y0=\"uw\", x1=\"x1\", y1=\"uw\", line_color=\"black\", source=df)\n if outx:\n circ = fig.circle( # pylint: disable=too-many-function-args\n outx, outy, size=3, line_color=\"black\", color=CATEGORY20[6], fill_alpha=0.6\n )\n fig.add_tools(HoverTool(renderers=[circ], tooltips=[(\"Outlier\", \"@y\")],))\n tooltips = [\n (\"Upper Whisker\", \"@uw\"),\n (\"Upper Quartile\", \"@q3\"),\n (\"Median\", \"@q2\"),\n (\"Lower Quartile\", \"@q1\"),\n (\"Lower Whisker\", \"@lw\"),\n ]\n if grp_cnt_stats is None and y is not None:\n lbl = timeunit if timeunit else \"Bin\"\n tooltips.insert(0, (lbl, \"@grp\"))\n fig.add_tools(\n HoverTool(\n renderers=[upw, utail, ubox, lbox, ltail, loww],\n tooltips=tooltips,\n point_policy=\"follow_mouse\",\n )\n )\n tweak_figure(fig, \"box\")\n if y is None:\n fig.xaxis.major_tick_line_color = None\n fig.xaxis.major_label_text_font_size = \"0pt\"\n fig.xaxis.axis_label = x if y is not None else None\n fig.yaxis.axis_label = x if y is None else y\n\n minw = min(outy) if outy else np.nan\n maxw = max(outy) if outy else np.nan\n _format_axis(fig, min(df[\"lw\"].min(), minw), max(df[\"uw\"].max(), maxw), \"y\")\n\n if not grp_cnt_stats and y and not timeunit: # format categorical axis tick values\n endpts = list(df[\"lb\"]) + [df.iloc[len(df) - 1][\"ub\"]]\n # start by rounding to the length of the largest possible number\n round_to = -len(str(max([abs(ept) for ept in endpts])).split(\",\")[0])\n ticks = np.round(endpts, round_to)\n nticks = len(df) // 5 + 1\n show_ticks = [ticks[i] for i in range(len(ticks)) if i % nticks == 0]\n while len(set(show_ticks)) != len(show_ticks): # round until show ticks unique\n round_to += 1\n ticks = np.round(endpts, round_to)\n show_ticks = [ticks[i] for i in range(len(ticks)) if i % nticks == 0]\n # format the ticks\n ticks = [int(tick) if tick.is_integer() else tick for tick in ticks]\n ticks = _format_ticks(ticks)\n fig.xaxis.ticker = list(range(len(df) + 1))\n fig.xaxis.formatter = FuncTickFormatter( # overide bokeh ticks\n args={\"vals\": ticks, \"mod\": nticks},\n code=\"\"\"\n if (index % mod == 0) return vals[index];\n return \"\";\n \"\"\",\n )\n tweak_figure(fig, \"boxnum\")\n fig.xaxis.major_label_text_font_size = \"10pt\"\n\n if timeunit == \"Week of\":\n fig.xaxis.axis_label = x + \", the week of\"\n\n return Panel(child=row(fig), title=\"Box Plot\")\n\n\ndef line_viz(\n data: Dict[str, Tuple[np.ndarray, np.ndarray, List[str]]],\n x: str,\n y: str,\n yscale: str,\n plot_width: int,\n plot_height: int,\n grp_cnt_stats: Dict[str, int],\n max_lbl_len: int = 15,\n) -> Panel:\n \"\"\"\n Render multi-line chart\n \"\"\"\n # pylint: disable=too-many-arguments,too-many-locals\n grps = list(data.keys())\n palette = CATEGORY20 * (len(grps) // len(CATEGORY20) + 1)\n title = _make_title(grp_cnt_stats, x, y)\n\n fig = figure(\n tools=[],\n title=title,\n toolbar_location=None,\n plot_width=plot_width,\n plot_height=plot_height,\n y_axis_type=yscale,\n )\n\n plot_dict = dict()\n xmin, xmax = np.Inf, -np.Inf\n ymin, ymax = np.Inf, -np.Inf\n for grp, colour in zip(grps, palette):\n ticks = [\n (data[grp][1][i] + data[grp][1][i + 1]) / 2\n for i in range(len(data[grp][1]) - 1)\n ]\n grp_name = (grp[: (max_lbl_len - 1)] + \"...\") if len(grp) > max_lbl_len else grp\n\n source = ColumnDataSource(\n {\"x\": ticks, \"y\": data[grp][0], \"intervals\": data[grp][2]}\n )\n plot_dict[grp_name] = fig.line(x=\"x\", y=\"y\", source=source, color=colour)\n fig.add_tools(\n HoverTool(\n renderers=[plot_dict[grp_name]],\n tooltips=[\n (f\"{x}\", f\"{grp}\"),\n (\"Frequency\", \"@y\"),\n (f\"{y} bin\", \"@intervals\"),\n ],\n mode=\"mouse\",\n )\n )\n xmin, xmax = min(xmin, data[grp][1].min()), max(xmax, data[grp][1].max())\n ymin, ymax = min(ymin, data[grp][0].min()), max(ymax, data[grp][0].max())\n\n legend = Legend(items=[(x, [plot_dict[x]]) for x in plot_dict])\n tweak_figure(fig)\n fig.add_layout(legend, \"right\")\n fig.yaxis.axis_label = \"Frequency\"\n fig.xaxis.axis_label = y\n _format_axis(fig, xmin, xmax, \"x\")\n if yscale == \"linear\":\n _format_axis(fig, ymin, ymax, \"y\")\n\n return Panel(child=row(fig), title=\"Line Chart\")\n\n\ndef scatter_viz(\n df: pd.DataFrame, x: str, y: str, spl_sz: int, plot_width: int, plot_height: int,\n) -> Any:\n \"\"\"\n Render a scatter plot\n \"\"\"\n # pylint: disable=too-many-arguments\n title = f\"{y} by {x}\" if len(df) < spl_sz else f\"{y} by {x} (sample size {spl_sz})\"\n tooltips = [(\"(x,y)\", f\"(@{x}, @{y})\")]\n fig = figure( # pylint: disable=too-many-function-args\n tools=\"hover\",\n title=title,\n toolbar_location=None,\n tooltips=tooltips,\n plot_width=plot_width,\n plot_height=plot_height,\n )\n fig.circle( # pylint: disable=too-many-function-args\n x, y, color=CATEGORY20[0], size=4, name=\"points\", source=df\n )\n tweak_figure(fig)\n fig.xaxis.axis_label = x\n fig.yaxis.axis_label = y\n _format_axis(fig, df[x].min(), df[x].max(), \"x\")\n _format_axis(fig, df[y].min(), df[y].max(), \"y\")\n return Panel(child=fig, title=\"Scatter Plot\")\n\n\ndef hexbin_viz(\n df: pd.DataFrame,\n x: str,\n y: str,\n plot_width: int,\n plot_height: int,\n tile_size: Optional[float] = None,\n) -> Panel:\n \"\"\"\n Render a hexbin plot\n \"\"\"\n # pylint: disable=too-many-arguments,too-many-locals\n xmin, xmax = df[x].min(), df[x].max()\n ymin, ymax = df[y].min(), df[y].max()\n if tile_size is None:\n tile_size = (xmax - xmin) / 25\n title = f\"{y} by {x}\"\n aspect_scale = (ymax - ymin) / (xmax - xmin)\n bins = hexbin(\n x=df[x],\n y=df[y],\n size=tile_size,\n orientation=\"flattop\",\n aspect_scale=aspect_scale,\n )\n fig = figure(\n title=title,\n tools=[],\n match_aspect=False,\n background_fill_color=\"#f5f5f5\",\n toolbar_location=None,\n plot_width=plot_width,\n plot_height=plot_height,\n )\n\n palette = list(reversed(VIRIDIS))\n rend = fig.hex_tile(\n q=\"q\",\n r=\"r\",\n size=tile_size,\n line_color=None,\n source=bins,\n orientation=\"flattop\",\n fill_color=linear_cmap(\n field_name=\"counts\",\n palette=palette,\n low=min(bins.counts),\n high=max(bins.counts),\n ),\n aspect_scale=aspect_scale,\n )\n fig.add_tools(HoverTool(tooltips=[(\"Count\", \"@counts\")], renderers=[rend],))\n mapper = LinearColorMapper(\n palette=palette, low=min(bins.counts), high=max(bins.counts)\n )\n color_bar = ColorBar(color_mapper=mapper, width=8, location=(0, 0))\n color_bar.label_standoff = 8\n fig.add_layout(color_bar, \"right\")\n tweak_figure(fig, \"hex\")\n _format_axis(fig, xmin, xmax, \"x\")\n _format_axis(fig, ymin, ymax, \"y\")\n fig.xaxis.axis_label = x\n fig.yaxis.axis_label = y\n\n return Panel(child=fig, title=\"Hexbin Plot\")\n\n\ndef nested_viz(\n df: pd.DataFrame,\n x: str,\n y: str,\n grp_cnt_stats: Dict[str, int],\n plot_width: int,\n plot_height: int,\n) -> Panel:\n \"\"\"\n Render a nested bar chart\n \"\"\"\n # pylint: disable=too-many-arguments\n data_source = ColumnDataSource(data=df)\n title = _make_title(grp_cnt_stats, x, y)\n plot_width = 19 * len(df) if len(df) > 50 else plot_width\n fig = figure(\n x_range=FactorRange(*df[\"grp_names\"]),\n tools=\"hover\",\n tooltips=[(\"Group\", \"@grp_names\"), (\"Count\", \"@cnt\")],\n toolbar_location=None,\n title=title,\n plot_width=plot_width,\n plot_height=plot_height,\n )\n\n fig.vbar(\n x=\"grp_names\",\n top=\"cnt\",\n width=1,\n source=data_source,\n line_color=\"white\",\n line_width=3,\n )\n tweak_figure(fig, \"nested\")\n fig.yaxis.axis_label = \"Count\"\n fig.xaxis.major_label_orientation = np.pi / 2\n _format_axis(fig, 0, df[\"cnt\"].max(), \"y\")\n return Panel(child=fig, title=\"Nested Bar Chart\")\n\n\ndef stacked_viz(\n df: pd.DataFrame,\n x: str,\n y: str,\n grp_cnt_stats: Dict[str, int],\n plot_width: int,\n plot_height: int,\n timeunit: Optional[str] = None,\n max_lbl_len: int = 15,\n) -> Panel:\n \"\"\"\n Render a stacked bar chart\n \"\"\"\n # pylint: disable=too-many-arguments,too-many-locals\n title = _make_title(grp_cnt_stats, x, y)\n if not timeunit:\n if grp_cnt_stats[f\"{x}_shw\"] > 30:\n plot_width = 32 * grp_cnt_stats[f\"{x}_shw\"]\n else:\n if len(df) > 30:\n plot_width = 32 * len(df)\n\n fig = figure(\n x_range=list(df.index),\n toolbar_location=None,\n title=title,\n tools=[],\n plot_width=plot_width,\n plot_height=plot_height,\n )\n grps = list(df.columns)\n palette = PASTEL1 * (len(grps) // len(PASTEL1) + 1)\n if \"Others\" in grps:\n colours = palette[0 : len(grps) - 1] + (\"#636363\",)\n else:\n colours = palette[0 : len(grps)]\n source = ColumnDataSource(data=df)\n renderers = fig.vbar_stack(\n stackers=grps, x=\"index\", width=0.9, source=source, line_width=1, color=colours,\n )\n grps = [\n (grp[: (max_lbl_len - 1)] + \"...\") if len(grp) > max_lbl_len else grp\n for grp in grps\n ]\n legend_it = [(grp, [rend]) for grp, rend in zip(grps, renderers)]\n legend = Legend(items=legend_it)\n legend.label_text_font_size = \"8pt\"\n fig.add_layout(legend, \"right\")\n if not timeunit:\n tooltips = [(\"Group\", \"@index, $name\"), (\"Percentage\", \"@$name{0.2f}%\")]\n fig.add_tools(HoverTool(tooltips=tooltips))\n fig.yaxis.axis_label = \"Percent\"\n else:\n # below is for having percent and count in the tooltip\n formatter = CustomJSHover(\n args=dict(source=source),\n code=\"\"\"\n const columns = Object.keys(source.data)\n const cur_bar = special_vars.data_x - 0.5\n var ttl_bar = 0\n for (let i = 0; i < columns.length; i++) {\n if (columns[i] != 'index'){\n ttl_bar = ttl_bar + source.data[columns[i]][cur_bar]\n }\n }\n const cur_val = source.data[special_vars.name][cur_bar]\n return (cur_val/ttl_bar * 100).toFixed(2)+'%';\n \"\"\",\n )\n for rend in renderers:\n hover = HoverTool(\n tooltips=[\n (y, \"$name\"),\n (timeunit, \"@index\"),\n (\"Count\", \"@$name\"),\n (\"Percent\", \"@{%s}{custom}\" % rend.name),\n ],\n formatters={\"@{%s}\" % rend.name: formatter},\n renderers=[rend],\n )\n fig.add_tools(hover)\n fig.yaxis.axis_label = \"Count\"\n _format_axis(fig, 0, df.sum(axis=1).max(), \"y\")\n fig.xaxis.axis_label = x\n if timeunit == \"Week of\":\n fig.xaxis.axis_label = x + \", the week of\"\n\n tweak_figure(fig, \"stacked\")\n\n return Panel(child=fig, title=\"Stacked Bar Chart\")\n\n\ndef heatmap_viz(\n df: pd.DataFrame,\n x: str,\n y: str,\n grp_cnt_stats: Dict[str, int],\n plot_width: int,\n plot_height: int,\n max_lbl_len: int = 15,\n) -> Panel:\n \"\"\"\n Render a heatmap\n \"\"\"\n # pylint: disable=too-many-arguments\n title = _make_title(grp_cnt_stats, x, y)\n\n source = ColumnDataSource(data=df)\n palette = RDBU[(len(RDBU) // 2 - 1) :]\n mapper = LinearColorMapper(\n palette=palette, low=df[\"cnt\"].min() - 0.01, high=df[\"cnt\"].max()\n )\n if grp_cnt_stats[f\"{x}_shw\"] > 60:\n plot_width = 16 * grp_cnt_stats[f\"{x}_shw\"]\n if grp_cnt_stats[f\"{y}_shw\"] > 10:\n plot_height = 70 + 18 * grp_cnt_stats[f\"{y}_shw\"]\n fig = figure(\n x_range=list(set(df[\"x\"])),\n y_range=list(set(df[\"y\"])),\n toolbar_location=None,\n tools=[],\n x_axis_location=\"below\",\n title=title,\n plot_width=plot_width,\n plot_height=plot_height,\n )\n\n renderer = fig.rect(\n x=\"x\",\n y=\"y\",\n width=1,\n height=1,\n source=source,\n line_color=None,\n fill_color=transform(\"cnt\", mapper),\n )\n\n color_bar = ColorBar(\n color_mapper=mapper,\n location=(0, 0),\n ticker=BasicTicker(desired_num_ticks=7),\n formatter=PrintfTickFormatter(format=\"%d\"),\n )\n fig.add_tools(\n HoverTool(\n tooltips=[(x, \"@x\"), (y, \"@y\"), (\"Count\", \"@cnt\"),],\n mode=\"mouse\",\n renderers=[renderer],\n )\n )\n fig.add_layout(color_bar, \"right\")\n\n tweak_figure(fig, \"heatmap\")\n fig.yaxis.formatter = FuncTickFormatter(\n code=\"\"\"\n if (tick.length > %d) return tick.substring(0, %d-2) + '...';\n else return tick;\n \"\"\"\n % (max_lbl_len, max_lbl_len)\n )\n return Panel(child=fig, title=\"Heat Map\")\n\n\ndef dt_line_viz(\n df: pd.DataFrame,\n x: str,\n timeunit: str,\n yscale: str,\n plot_width: int,\n plot_height: int,\n show_yticks: bool,\n miss_pct: Optional[float] = None,\n y: Optional[str] = None,\n) -> Figure:\n \"\"\"\n Render a line chart\n \"\"\"\n # pylint: disable=too-many-arguments\n if miss_pct is not None:\n title = f\"{x} ({miss_pct}% missing)\" if miss_pct > 0 else f\"{x}\"\n tooltips = [(timeunit, \"@lbl\"), (\"Frequency\", \"@freq\"), (\"Percent\", \"@pct%\")]\n agg = \"freq\"\n else:\n title = title = f\"{df.columns[1]} of {y} by {x}\"\n agg = f\"{df.columns[1]}\"\n tooltips = [(timeunit, \"@lbl\"), (agg, f\"@{df.columns[1]}\")]\n fig = Figure(\n plot_width=plot_width,\n plot_height=plot_height,\n toolbar_location=None,\n title=title,\n tools=[],\n y_axis_type=yscale,\n x_axis_type=\"datetime\",\n )\n fig.line(\n source=df, x=x, y=agg, line_width=2, line_alpha=0.8, color=\"#7e9ac8\",\n )\n hover = HoverTool(tooltips=tooltips, mode=\"vline\",)\n fig.add_tools(hover)\n\n tweak_figure(fig, \"line\", show_yticks)\n if show_yticks and yscale == \"linear\":\n _format_axis(fig, 0, df[agg].max(), \"y\")\n\n if y:\n fig.yaxis.axis_label = f\"{df.columns[1]} of {y}\"\n fig.xaxis.axis_label = x\n return Panel(child=fig, title=\"Line Chart\")\n\n fig.yaxis.axis_label = \"Frequency\"\n return fig\n\n\ndef dt_multiline_viz(\n data: Dict[str, Tuple[np.ndarray, np.ndarray, List[str]]],\n x: str,\n y: str,\n timeunit: str,\n yscale: str,\n plot_width: int,\n plot_height: int,\n grp_cnt_stats: Dict[str, int],\n max_lbl_len: int = 15,\n z: Optional[str] = None,\n agg: Optional[str] = None,\n) -> Panel:\n \"\"\"\n Render multi-line chart\n \"\"\"\n # pylint: disable=too-many-arguments,too-many-locals\n grps = list(data.keys())\n palette = CATEGORY20 * (len(grps) // len(CATEGORY20) + 1)\n if z is None:\n title = _make_title(grp_cnt_stats, x, y)\n else:\n title = f\"{agg} of {_make_title(grp_cnt_stats, z, y)} over {x}\"\n agg = \"Frequency\" if agg is None else agg\n\n fig = figure(\n tools=[],\n title=title,\n toolbar_location=None,\n plot_width=plot_width,\n plot_height=plot_height,\n y_axis_type=yscale,\n x_axis_type=\"datetime\",\n )\n\n ymin, ymax = np.Inf, -np.Inf\n plot_dict = dict()\n for grp, colour in zip(grps, palette):\n grp_name = (grp[: (max_lbl_len - 1)] + \"...\") if len(grp) > max_lbl_len else grp\n source = ColumnDataSource(\n {\"x\": data[grp][1], \"y\": data[grp][0], \"lbl\": data[grp][2]}\n )\n plot_dict[grp_name] = fig.line(\n x=\"x\", y=\"y\", source=source, color=colour, line_width=1.3\n )\n fig.add_tools(\n HoverTool(\n renderers=[plot_dict[grp_name]],\n tooltips=[(f\"{y}\", f\"{grp}\"), (agg, \"@y\"), (timeunit, \"@lbl\"),],\n mode=\"mouse\",\n )\n )\n ymin, ymax = min(ymin, min(data[grp][0])), max(ymax, max(data[grp][0]))\n\n legend = Legend(items=[(x, [plot_dict[x]]) for x in plot_dict])\n tweak_figure(fig, \"line\", True)\n fig.add_layout(legend, \"right\")\n fig.legend.click_policy = \"hide\"\n fig.yaxis.axis_label = f\"{agg} of {y}\" if z else \"Frequency\"\n fig.xaxis.axis_label = x\n if yscale == \"linear\":\n _format_axis(fig, ymin, ymax, \"y\")\n\n return Panel(child=fig, title=\"Line Chart\")\n\n\ndef stats_viz(stats: Dict[str, Any]) -> Tuple[Dict[str, str], Dict[str, Any]]:\n \"\"\"\n Render statistics information for distribution grid\n \"\"\"\n # pylint: disable=too-many-locals\n nrows, ncols, npresent_cells, nrows_wo_dups, mem_use, dtypes_cnt = stats.values()\n ncells = nrows * ncols\n\n data = {\n \"Number of Variables\": ncols,\n \"Number of Rows\": nrows,\n \"Missing Cells\": float(ncells - npresent_cells),\n \"Missing Cells (%)\": 1 - (npresent_cells / ncells),\n \"Duplicate Rows\": nrows - nrows_wo_dups,\n \"Duplicate Rows (%)\": 1 - (nrows_wo_dups / nrows),\n \"Total Size in Memory\": float(mem_use),\n \"Average Row Size in Memory\": mem_use / nrows,\n }\n return {k: _format_values(k, v) for k, v in data.items()}, dtypes_cnt\n\n\ndef stats_viz_num(data: Dict[str, Any], plot_width: int, plot_height: int,) -> Panel:\n \"\"\"\n Render statistics panel for numerical data\n \"\"\"\n overview = {\n \"Distinct Count\": data[\"nuniq\"],\n \"Unique (%)\": data[\"nuniq\"] / data[\"npres\"],\n \"Missing\": data[\"nrows\"] - data[\"npres\"],\n \"Missing (%)\": 1 - (data[\"npres\"] / data[\"nrows\"]),\n \"Infinite\": (data[\"npres\"] - data[\"nreals\"]),\n \"Infinite (%)\": (data[\"npres\"] - data[\"nreals\"]) / data[\"nrows\"],\n \"Memory Size\": data[\"mem_use\"],\n \"Mean\": data[\"mean\"],\n \"Minimum\": data[\"min\"],\n \"Maximum\": data[\"max\"],\n \"Zeros\": data[\"nzero\"],\n \"Zeros (%)\": data[\"nzero\"] / data[\"nrows\"],\n \"Negatives\": data[\"nneg\"],\n \"Negatives (%)\": data[\"nneg\"] / data[\"nrows\"],\n }\n data[\"qntls\"].index = np.round(data[\"qntls\"].index, 2)\n quantile = {\n \"Minimum\": data[\"min\"],\n \"5-th Percentile\": data[\"qntls\"].loc[0.05],\n \"Q1\": data[\"qntls\"].loc[0.25],\n \"Median\": data[\"qntls\"].loc[0.50],\n \"Q3\": data[\"qntls\"].loc[0.75],\n \"95-th Percentile\": data[\"qntls\"].loc[0.95],\n \"Maximum\": data[\"max\"],\n \"Range\": data[\"max\"] - data[\"min\"],\n \"IQR\": data[\"qntls\"].loc[0.75] - data[\"qntls\"].loc[0.25],\n }\n descriptive = {\n \"Mean\": data[\"mean\"],\n \"Standard Deviation\": data[\"std\"],\n \"Variance\": data[\"std\"] ** 2,\n \"Sum\": data[\"mean\"] * data[\"npres\"],\n \"Skewness\": float(data[\"skew\"]),\n \"Kurtosis\": float(data[\"kurt\"]),\n \"Coefficient of Variation\": data[\"std\"] / data[\"mean\"]\n if data[\"mean\"] != 0\n else np.nan,\n }\n overview = {k: _format_values(k, v) for k, v in overview.items()}\n quantile = {k: _format_values(k, v) for k, v in quantile.items()}\n descriptive = {k: _format_values(k, v) for k, v in descriptive.items()}\n\n ov_content = \"\"\n qs_content = (\n '<h4 style=\"text-align:center; margin:1em auto 0.2em;\">Quantile Statistics</h4>'\n )\n ds_content = '<h4 style=\"text-align:center; margin:1em auto 0.2em;\">Descriptive Statistics</h4>'\n for key, value in overview.items():\n value = _sci_notation_superscript(value)\n if \"Distinct\" in key and float(value) > 50:\n ov_content += _create_table_row(key, value, True)\n elif \"Unique\" in key and float(value.replace(\"%\", \"\")) == 100:\n ov_content += _create_table_row(key, value, True)\n elif (\n any(x in key for x in [\"Missing\", \"Zeros\", \"Infinite\"])\n and float(value.replace(\"%\", \"\")) != 0\n ):\n ov_content += _create_table_row(key, value, True)\n else:\n ov_content += _create_table_row(key, value)\n for key, value in quantile.items():\n value = _sci_notation_superscript(value)\n qs_content += _create_table_row(key, value)\n for key, value in descriptive.items():\n value = _sci_notation_superscript(value)\n if \"Skewness\" in key and float(value) > 20:\n ds_content += _create_table_row(key, value, True)\n else:\n ds_content += _create_table_row(key, value)\n\n ov_content = f\"\"\"\n <h4 style=\"text-align: center; margin:0 auto 0.2em;\">Overview</h4>\n <div style=\"columns: 2\">\n <table style=\"width: 100%; table-layout: auto; font-size:11px;\">\n <tbody>{ov_content}</tbody>\n </table>\n </div>\n \"\"\"\n qs_content = f\"\"\"\n <div style=\"flex: 50%; margin-right: 6px;\">\n <table style=\"width: 100%; table-layout: auto; font-size:11px;\">\n <tbody>{qs_content}</tbody>\n </table>\n </div>\n \"\"\"\n ds_content = f\"\"\"\n <div style=\"flex: 50%; margin-right: 6px;\">\n <table style=\"width: 100%; table-layout: auto; font-size:11px;\">\n <tbody>{ds_content}</tbody>\n </table>\n </div>\n \"\"\"\n container = (\n f'{ov_content}<div style=\"display: flex;\">{qs_content}{ds_content}</div>'\n )\n\n div = Div(\n text=container,\n width=plot_width,\n height=plot_height + 30,\n style={\"width\": \"100%\"},\n )\n return Panel(child=div, title=\"Stats\")\n\n\ndef stats_viz_cat(\n stats: Dict[str, Any],\n len_stats: Dict[str, Any],\n letter_stats: Dict[str, Any],\n plot_width: int,\n plot_height: int,\n) -> Panel:\n \"\"\"\n Render statistics panel for categorical data\n \"\"\"\n # pylint: disable=too-many-locals\n ov_stats = {\n \"Distinct Count\": stats[\"nuniq\"],\n \"Unique (%)\": stats[\"nuniq\"] / stats[\"npres\"],\n \"Missing\": stats[\"nrows\"] - stats[\"npres\"],\n \"Missing (%)\": 1 - stats[\"npres\"] / stats[\"nrows\"],\n \"Memory Size\": stats[\"mem_use\"],\n }\n sampled_rows = (\"1st row\", \"2nd row\", \"3rd row\", \"4th row\", \"5th row\")\n smpl = dict(zip(sampled_rows, stats[\"first_rows\"]))\n\n ov_stats = {k: _format_values(k, v) for k, v in ov_stats.items()}\n len_stats = {k: _format_values(k, v) for k, v in len_stats.items()}\n smpl = {k: f\"{v[:18]}...\" if len(v) > 18 else v for k, v in smpl.items()}\n letter_stats = {k: _format_values(k, v) for k, v in letter_stats.items()}\n\n # pylint: disable=line-too-long\n ov_content = \"\"\n lens_content = \"\"\n smpl_content = \"\"\n ls_content = \"\"\n for key, value in ov_stats.items():\n value = _sci_notation_superscript(value)\n if \"Distinct\" in key and float(value) > 50:\n ov_content += _create_table_row(key, value, True)\n elif \"Unique\" in key and float(value.replace(\"%\", \"\")) == 100:\n ov_content += _create_table_row(key, value, True)\n elif \"Missing\" in key and float(value.replace(\"%\", \"\")) != 0:\n ov_content += _create_table_row(key, value, True)\n else:\n ov_content += _create_table_row(key, value)\n for key, value in len_stats.items():\n lens_content += _create_table_row(key, value)\n for key, value in smpl.items():\n smpl_content += _create_table_row(key, value)\n for key, value in letter_stats.items():\n ls_content += _create_table_row(key, value)\n\n ov_content = f\"\"\"\n <div style=\"grid-area: a;\">\n <h3 style=\"text-align: center;\">Overview</h3>\n <table style=\"width: 100%; table-layout: auto; font-size:11px;\">\n <tbody>{ov_content}</tbody>\n </table>\n </div>\n \"\"\"\n smpl_content = f\"\"\"\n <div style=\"grid-area: b;\">\n <h3 style=\"text-align: center;\">Sample</h3>\n <table style=\"width: 100%; table-layout: auto; font-size:11px;\">\n <tbody>{smpl_content}</tbody>\n </table>\n </div>\n \"\"\"\n ls_content = f\"\"\"\n <div style=\"grid-area: c;\">\n <h3 style=\"text-align: center;\">Letter</h3>\n <table style=\"width: 100%; table-layout: auto; font-size:11px;\">\n <tbody>{ls_content}</tbody>\n </table>\n </div>\n \"\"\"\n lens_content = f\"\"\"\n <div style=\"grid-area: d;\">\n <h3 style=\"text-align: center;\">Length</h3>\n <table style=\"width: 100%; table-layout: auto; font-size:11px;\">\n <tbody>{lens_content}</tbody>\n </table>\n </div>\n \"\"\"\n\n container = f\"\"\"<div style=\"display: grid;grid-template-columns: 1fr 1fr;grid-template-rows: 1fr 1fr;gap: 1px 1px;\n grid-template-areas:\\'a b\\' \\'c d\\';\">\n {ov_content}{smpl_content}{ls_content}{lens_content}</div>\"\"\"\n\n div = Div(\n text=container, width=plot_width, height=plot_height, style={\"width\": \"100%\"}\n )\n return Panel(child=div, title=\"Stats\")\n\n\ndef stats_viz_dt(data: Dict[str, str], plot_width: int, plot_height: int) -> Panel:\n \"\"\"\n Render statistics panel for datetime data\n \"\"\"\n data = {k: _format_values(k, v) for k, v in data.items()}\n ov_content = \"\"\n for key, value in data.items():\n value = _sci_notation_superscript(value)\n if \"Distinct\" in key and float(value) > 50:\n ov_content += _create_table_row(key, value, True)\n elif \"Unique\" in key and float(value.replace(\"%\", \"\")) == 100:\n ov_content += _create_table_row(key, value, True)\n elif \"Missing\" in key and float(value.replace(\"%\", \"\")) != 0:\n ov_content += _create_table_row(key, value, True)\n else:\n ov_content += _create_table_row(key, value)\n ov_content = f\"\"\"\n <h3 style=\"text-align: center;\">Overview</h3>\n <div\">\n <table style=\"width: 100%; table-layout: auto;\">\n <tbody>{ov_content}</tbody>\n </table>\n </div>\n \"\"\"\n div = Div(\n text=ov_content, width=plot_width, height=plot_height, style={\"width\": \"100%\"}\n )\n return Panel(child=div, title=\"Stats\")\n\n\ndef render_distribution_grid(\n itmdt: Intermediate, yscale: str, plot_width: int, plot_height: int\n) -> Dict[\n str,\n Union[\n List[str],\n List[LayoutDOM],\n Tuple[Dict[str, str], Dict[str, str]],\n Dict[int, List[str]],\n ],\n]:\n \"\"\"\n Render plots and dataset stats from plot(df)\n \"\"\" # pylint: disable=too-many-locals\n figs: List[LayoutDOM] = list()\n nrows = itmdt[\"stats\"][\"nrows\"]\n titles: List[str] = []\n for col, dtype, data in itmdt[\"data\"]:\n if is_dtype(dtype, Nominal()):\n df, ttl_grps = data\n fig = bar_viz(\n df, ttl_grps, nrows, col, yscale, plot_width, plot_height, False,\n )\n elif is_dtype(dtype, Continuous()):\n fig = hist_viz(data, nrows, col, yscale, plot_width, plot_height, False)\n figs.append(fig)\n elif is_dtype(dtype, DateTime()):\n df, timeunit, miss_pct = data\n fig = dt_line_viz(\n df, col, timeunit, yscale, plot_width, plot_height, False, miss_pct\n )\n fig.frame_height = plot_height\n titles.append(fig.title.text)\n fig.title.text = \"\"\n figs.append(fig)\n\n return {\n \"layout\": figs,\n \"meta\": titles,\n \"tabledata\": stats_viz(itmdt[\"stats\"]),\n \"column_insights\": itmdt[\"column_insights\"],\n \"overview_insights\": itmdt[\"overview_insights\"],\n }\n\n\ndef render_cat(\n itmdt: Intermediate, yscale: str, plot_width: int, plot_height: int\n) -> Tabs:\n \"\"\"\n Render plots from plot(df, x) when x is a categorical column\n \"\"\"\n # pylint: disable=too-many-locals\n tabs: List[Panel] = []\n col, data = itmdt[\"col\"], itmdt[\"data\"]\n # overview, word length, and charater level statistcs\n stats, len_stats, letter_stats = (\n data[\"stats\"],\n data[\"len_stats\"],\n data[\"letter_stats\"],\n )\n # number of present (not null) rows, and total rows\n nrows, nuniq = data[\"nrows\"], data[\"nuniq\"]\n # categorical statistics\n tabs.append(stats_viz_cat(stats, len_stats, letter_stats, plot_width, plot_height))\n # bar chart and pie chart of the categorical values\n bar_data, pie = data[\"bar\"].to_frame(), data[\"pie\"].to_frame()\n fig = bar_viz(bar_data, nuniq, nrows, col, yscale, plot_width, plot_height, True,)\n tabs.append(Panel(child=row(fig), title=\"Bar Chart\"))\n tabs.append(pie_viz(pie, nrows, col, plot_width, plot_height))\n # word counts and total number of words for the wordcloud and word frequencies bar chart\n word_cnts, nwords, = data[\"word_cnts\"], data[\"nwords\"]\n if nwords > 0:\n tabs.append(wordcloud_viz(word_cnts, plot_width, plot_height))\n tabs.append(wordfreq_viz(word_cnts, nwords, plot_width, plot_height, True))\n # word length histogram\n length_dist = hist_viz(\n data[\"len_hist\"], nrows, \"Word Length\", yscale, plot_width, plot_height, True\n )\n tabs.append(Panel(child=row(length_dist), title=\"Word Length\"))\n tabs = Tabs(tabs=tabs)\n # insights\n nom_insights(data, col)\n # TODO return insights\n return tabs\n\n\ndef nom_insights(data: Dict[str, Any], col: str) -> Dict[str, List[str]]:\n \"\"\"\n Format the insights for plot(df, Nominal())\n \"\"\"\n # pylint: disable=line-too-long\n # insight dictionary, with a list associated with each plot\n ins: Dict[str, List[str]] = {\n \"stat\": [],\n \"bar\": [],\n \"pie\": [],\n \"cloud\": [],\n \"wf\": [],\n \"wl\": [],\n }\n\n ## if cfg.insight.constant_enable:\n if data[\"nuniq\"] == 1:\n ins[\"stat\"].append(f\"{col} has a constant value\")\n\n ## if cfg.insight.high_cardinality_enable:\n if data[\"nuniq\"] > 50: ## cfg.insght.high_cardinality_threshold\n nuniq = data[\"nuniq\"]\n ins[\"stat\"].append(f\"{col} has a high cardinality: {nuniq} distinct values\")\n\n ## if cfg.insight.missing_enable:\n pmiss = round((data[\"nrows\"] - data[\"stats\"][\"npres\"]) / data[\"nrows\"] * 100, 2)\n if pmiss > 1: ## cfg.insight.missing_threshold\n nmiss = data[\"nrows\"] - data[\"stats\"][\"npres\"]\n ins[\"stat\"].append(f\"{col} has {nmiss} ({pmiss}%) missing values\")\n\n ## if cfg.insight.constant_length_enable:\n if data[\"stats\"][\"nuniq\"] == data[\"stats\"][\"npres\"]:\n ins[\"stat\"].append(f\"{col} has all distinct values\")\n\n ## if cfg.insight.evenness_enable:\n if data[\"chisq\"][1] > 0.999: ## cfg.insight.uniform_threshold\n ins[\"bar\"].append(f\"{col} is relatively evenly distributed\")\n\n ## if cfg.insight.outstanding_no1_enable\n factor = data[\"bar\"][0] / data[\"bar\"][1] if len(data[\"bar\"]) > 1 else 0\n if factor > 1.5:\n val1, val2 = data[\"bar\"].index[0], data[\"bar\"].index[1]\n ins[\"bar\"].append(\n f\"The largest value ({val1}) is over {factor} times larger than the second largest value ({val2})\"\n )\n\n ## if cfg.insight.attribution_enable\n if data[\"pie\"][:2].sum() / data[\"nrows\"] > 0.5:\n vals = \", \".join(data[\"pie\"].index[i] for i in range(2))\n ins[\"pie\"].append(f\"The top 2 categories ({vals}) take over 50%\")\n\n ## if cfg.insight.high_word_cardinlaity_enable\n if data[\"nwords\"] > 1000:\n nwords = data[\"nwords\"]\n ins[\"cloud\"].append(f\"{col} contains many words: {nwords} words\")\n\n ## if cfg.insight.outstanding_no1_word_enable\n factor = (\n data[\"word_cnts\"][0] / data[\"word_cnts\"][1] if len(data[\"word_cnts\"]) > 1 else 0\n )\n if factor > 1.5:\n val1, val2 = data[\"word_cnts\"].index[0], data[\"word_cnts\"].index[1]\n ins[\"wf\"].append(\n f\"The largest value ({val1}) is over {factor} times larger than the second largest value ({val2})\"\n )\n\n ## if cfg.insight.constant_word_length_enable\n if data[\"len_stats\"][\"Minimum\"] == data[\"len_stats\"][\"Maximum\"]:\n ins[\"wf\"].append(f\"{col} has words of constant length\")\n\n return ins\n\n\ndef render_num(\n itmdt: Intermediate, yscale: str, plot_width: int, plot_height: int\n) -> Tabs:\n \"\"\"\n Render plots from plot(df, x) when x is a numerical column\n \"\"\"\n col, data = itmdt[\"col\"], itmdt[\"data\"]\n\n tabs: List[Panel] = []\n # numerical statistics\n tabs.append(stats_viz_num(data, plot_width, plot_height))\n # values histogram\n fig = hist_viz(\n data[\"hist\"], data[\"nrows\"], col, yscale, plot_width, plot_height, True,\n )\n tabs.append(Panel(child=fig, title=\"Histogram\"))\n # kde and q-q normal\n if data[\"kde\"] is not None:\n dens, kde = data[\"dens\"], data[\"kde\"]\n tabs.append(kde_viz(dens, kde, col, yscale, plot_width, plot_height))\n if data[\"qntls\"].any():\n qntls, mean, std = data[\"qntls\"], data[\"mean\"], data[\"std\"]\n tabs.append(qqnorm_viz(qntls, mean, std, col, plot_width, plot_height))\n # box plot\n box_data = {\n \"grp\": col,\n \"q1\": data[\"qrtl1\"],\n \"q2\": data[\"qrtl2\"],\n \"q3\": data[\"qrtl3\"],\n \"lw\": data[\"lw\"],\n \"uw\": data[\"uw\"],\n \"otlrs\": data[\"otlrs\"],\n \"x\": 1, # x, x0, and x1 are for plotting the box plot with bokeh\n \"x0\": 0.2,\n \"x1\": 0.8,\n }\n tabs.append(univar_box_viz(box_data, col, plot_width, plot_height))\n tabs = Tabs(tabs=tabs)\n # insights\n cont_insights(data, col)\n # TODO return insights\n return tabs\n\n\ndef cont_insights(data: Dict[str, Any], col: str) -> Dict[str, List[str]]:\n \"\"\"\n Format the insights for plot(df, Continuous())\n \"\"\"\n # insight dictionary with a list associated with each plot\n ins: Dict[str, List[str]] = {\"stat\": [], \"hist\": [], \"qq\": [], \"box\": []}\n\n ## if cfg.insight.infinity_enable:\n pinf = round((data[\"npres\"] - data[\"nreals\"]) / data[\"nrows\"] * 100, 2)\n if pinf > 1: ## cfg.insight.infinity_threshold\n ninf = data[\"npres\"] - data[\"nreals\"]\n ins[\"stat\"].append(f\"{col} has {ninf} ({pinf}%) infinite values\")\n\n ## if cfg.insight.missing_enable:\n pmiss = round((data[\"nrows\"] - data[\"npres\"]) / data[\"nrows\"] * 100, 2)\n if pmiss > 1: ## cfg.insight.missing_threshold\n nmiss = data[\"nrows\"] - data[\"npres\"]\n ins[\"stat\"].append(f\"{col} has {nmiss} ({pmiss}%) missing values\")\n\n ## if cfg.insight.negatives_enable:\n pneg = round(data[\"nneg\"] / data[\"nrows\"] * 100, 2)\n if pneg > 1: ## cfg.insight.negatives_threshold\n nneg = data[\"nneg\"]\n ins[\"stat\"].append(f\"{col} has {nneg} ({pneg}%) negatives\")\n\n ## if cfg.insight.zeros_enable:\n pzero = round(data[\"nzero\"] / data[\"nrows\"] * 100, 2)\n if pzero > 5: ## cfg.insight.zeros_threshold\n nzero = data[\"nzero\"]\n ins[\"stat\"].append(f\"{col} has {nzero} ({pzero}%) zeros\")\n\n ## if cfg.insight.normal_enable:\n if data[\"norm\"][1] > 0.1:\n ins[\"hist\"].append(f\"{col} is normally distributed\")\n\n ## if cfg.insight.uniform_enable:\n if data[\"chisq\"][1] > 0.999: ## cfg.insight.uniform_threshold\n ins[\"hist\"].append(f\"{col} is uniformly distributed\")\n\n ## if cfg.insight.skewed_enable:\n skw = np.round(data[\"skew\"], 4)\n if skw >= 20: ## cfg.insight.skewed_threshold\n ins[\"hist\"].append(f\"{col} is skewed right (\\u03B31 = {skw})\")\n if skw <= -20: ## cfg.insight.skewed_threshold\n ins[\"hist\"].append(f\"{col} is skewed left (\\u03B31 = {skw})\")\n\n ## if cfg.insight.normal_enable:\n if data[\"norm\"][1] <= 0.05:\n pval = data[\"norm\"][1]\n ins[\"qq\"].append(f\"{col} is not normally distributed (p-value {pval})\")\n\n ## if cfg.insight.box_enable\n if data[\"notlrs\"] > 0:\n notlrs = data[\"notlrs\"]\n ins[\"box\"].append(f\"{col} has {notlrs} outliers\")\n\n return ins\n\n\ndef render_dt(\n itmdt: Intermediate, yscale: str, plot_width: int, plot_height: int\n) -> Tabs:\n \"\"\"\n Render plots from plot(df, x) when x is a numerical column\n \"\"\"\n tabs: List[Panel] = []\n osd = itmdt[\"data\"]\n tabs.append(stats_viz_dt(osd, plot_width, plot_height))\n df, timeunit, miss_pct = itmdt[\"line\"]\n fig = dt_line_viz(\n df, itmdt[\"col\"], timeunit, yscale, plot_width, plot_height, True, miss_pct\n )\n tabs.append(Panel(child=fig, title=\"Line Chart\"))\n\n tabs = Tabs(tabs=tabs)\n return tabs\n\n\ndef render_cat_num(\n itmdt: Intermediate, yscale: str, plot_width: int, plot_height: int,\n) -> Tabs:\n \"\"\"\n Render plots from plot(df, x, y) when x is a categorical column\n and y is a numerical column\n \"\"\"\n tabs: List[Panel] = []\n df, outx, outy, grp_cnt_stats = itmdt[\"boxdata\"]\n tabs.append(\n box_viz(\n df,\n outx,\n outy,\n itmdt[\"x\"],\n plot_width,\n plot_height,\n itmdt[\"y\"],\n grp_cnt_stats,\n )\n )\n histdict, grp_cnt_stats = itmdt[\"histdata\"]\n tabs.append(\n line_viz(\n histdict,\n itmdt[\"x\"],\n itmdt[\"y\"],\n yscale,\n plot_width,\n plot_height,\n grp_cnt_stats,\n )\n )\n tabs = Tabs(tabs=tabs)\n return tabs\n\n\ndef render_two_num(\n itmdt: Intermediate,\n plot_width: int,\n plot_height: int,\n tile_size: Optional[float] = None,\n) -> Tabs:\n \"\"\"\n Render plots from plot(df, x, y) when x and y are numerical columns\n \"\"\"\n tabs: List[Panel] = []\n tabs.append(\n scatter_viz(\n itmdt[\"scatdata\"],\n itmdt[\"x\"],\n itmdt[\"y\"],\n itmdt[\"spl_sz\"],\n plot_width,\n plot_height,\n )\n )\n df, outx, outy, _ = itmdt[\"boxdata\"]\n tabs.append(\n box_viz(df, outx, outy, itmdt[\"x\"], plot_width, plot_height, itmdt[\"y\"])\n )\n tabs.append(\n hexbin_viz(\n itmdt[\"hexbindata\"],\n itmdt[\"x\"],\n itmdt[\"y\"],\n plot_width,\n plot_height,\n tile_size,\n )\n )\n tabs = Tabs(tabs=tabs)\n return tabs\n\n\ndef render_two_cat(itmdt: Intermediate, plot_width: int, plot_height: int,) -> Tabs:\n \"\"\"\n Render plots from plot(df, x, y) when x and y are categorical columns\n \"\"\"\n tabs: List[Panel] = []\n df, grp_cnt_stats = itmdt[\"nesteddata\"]\n tabs.append(\n nested_viz(df, itmdt[\"x\"], itmdt[\"y\"], grp_cnt_stats, plot_width, plot_height)\n )\n df, grp_cnt_stats = itmdt[\"stackdata\"]\n tabs.append(\n stacked_viz(df, itmdt[\"x\"], itmdt[\"y\"], grp_cnt_stats, plot_width, plot_height)\n )\n df, grp_cnt_stats = itmdt[\"heatmapdata\"]\n tabs.append(\n heatmap_viz(df, itmdt[\"x\"], itmdt[\"y\"], grp_cnt_stats, plot_width, plot_height)\n )\n tabs = Tabs(tabs=tabs)\n return tabs\n\n\ndef render_dt_num(\n itmdt: Intermediate, yscale: str, plot_width: int, plot_height: int,\n) -> Tabs:\n \"\"\"\n Render plots from plot(df, x, y) when x is dt and y is num\n \"\"\"\n tabs: List[Panel] = []\n linedf, timeunit = itmdt[\"linedata\"]\n tabs.append(\n dt_line_viz(\n linedf,\n itmdt[\"x\"],\n timeunit,\n yscale,\n plot_width,\n plot_height,\n True,\n y=itmdt[\"y\"],\n )\n )\n boxdf, outx, outy, timeunit = itmdt[\"boxdata\"]\n tabs.append(\n box_viz(\n boxdf,\n outx,\n outy,\n itmdt[\"x\"],\n plot_width,\n plot_height,\n itmdt[\"y\"],\n timeunit=timeunit,\n )\n )\n tabs = Tabs(tabs=tabs)\n return tabs\n\n\ndef render_dt_cat(\n itmdt: Intermediate, yscale: str, plot_width: int, plot_height: int,\n) -> Tabs:\n \"\"\"\n Render plots from plot(df, x, y) when x is dt and y is num\n \"\"\"\n tabs: List[Panel] = []\n data, grp_cnt_stats, timeunit = itmdt[\"linedata\"]\n tabs.append(\n dt_multiline_viz(\n data,\n itmdt[\"x\"],\n itmdt[\"y\"],\n timeunit,\n yscale,\n plot_width,\n plot_height,\n grp_cnt_stats,\n )\n )\n df, grp_cnt_stats, timeunit = itmdt[\"stackdata\"]\n tabs.append(\n stacked_viz(\n df, itmdt[\"x\"], itmdt[\"y\"], grp_cnt_stats, plot_width, plot_height, timeunit\n )\n )\n tabs = Tabs(tabs=tabs)\n return tabs\n\n\ndef render_dt_num_cat(\n itmdt: Intermediate, yscale: str, plot_width: int, plot_height: int,\n) -> Tabs:\n \"\"\"\n Render plots from plot(df, x, y) when x is dt and y is num\n \"\"\"\n tabs: List[Panel] = []\n data, grp_cnt_stats, timeunit = itmdt[\"data\"]\n tabs.append(\n dt_multiline_viz(\n data,\n itmdt[\"x\"],\n itmdt[\"y\"],\n timeunit,\n yscale,\n plot_width,\n plot_height,\n grp_cnt_stats,\n z=itmdt[\"z\"],\n agg=itmdt[\"agg\"],\n )\n )\n tabs = Tabs(tabs=tabs)\n return tabs\n\n\ndef render(\n itmdt: Intermediate,\n yscale: str = \"linear\",\n tile_size: Optional[float] = None,\n plot_width_sml: int = 324,\n plot_height_sml: int = 300,\n plot_width_lrg: int = 450,\n plot_height_lrg: int = 400,\n plot_width_wide: int = 972,\n) -> LayoutDOM:\n \"\"\"\n Render a basic plot\n\n Parameters\n ----------\n itmdt\n The Intermediate containing results from the compute function.\n yscale: str, default \"linear\"\n The scale to show on the y axis. Can be \"linear\" or \"log\".\n tile_size\n Size of the tile for the hexbin plot. Measured from the middle\n of a hexagon to its left or right corner.\n plot_width_small: int, default 324\n The width of the small plots\n plot_height_small: int, default 300\n The height of the small plots\n plot_width_large: int, default 450\n The width of the large plots\n plot_height_large: int, default 400\n The height of the large plots\n plot_width_large: int, default 972\n The width of the large plots\n plot_width_wide: int, default 972\n The width of the wide plots\n \"\"\"\n # pylint: disable=too-many-arguments\n if itmdt.visual_type == \"distribution_grid\":\n visual_elem = render_distribution_grid(\n itmdt, yscale, plot_width_sml, plot_height_sml\n )\n elif itmdt.visual_type == \"categorical_column\":\n visual_elem = render_cat(itmdt, yscale, plot_width_lrg, plot_height_lrg)\n elif itmdt.visual_type == \"numerical_column\":\n visual_elem = render_num(itmdt, yscale, plot_width_lrg, plot_height_lrg)\n elif itmdt.visual_type == \"datetime_column\":\n visual_elem = render_dt(itmdt, yscale, plot_width_lrg, plot_height_lrg)\n elif itmdt.visual_type == \"cat_and_num_cols\":\n visual_elem = render_cat_num(itmdt, yscale, plot_width_lrg, plot_height_lrg)\n elif itmdt.visual_type == \"two_num_cols\":\n visual_elem = render_two_num(itmdt, plot_width_lrg, plot_height_lrg, tile_size)\n elif itmdt.visual_type == \"two_cat_cols\":\n visual_elem = render_two_cat(itmdt, plot_width_wide, plot_height_sml)\n elif itmdt.visual_type == \"dt_and_num_cols\":\n visual_elem = render_dt_num(itmdt, yscale, plot_width_lrg, plot_height_lrg)\n elif itmdt.visual_type == \"dt_and_cat_cols\":\n visual_elem = render_dt_cat(itmdt, yscale, plot_width_wide, plot_height_lrg)\n elif itmdt.visual_type == \"dt_cat_num_cols\":\n visual_elem = render_dt_num_cat(itmdt, yscale, plot_width_wide, plot_height_lrg)\n\n return visual_elem\n","sub_path":"dataprep/eda/distribution/render.py","file_name":"render.py","file_ext":"py","file_size_in_byte":64425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"620168361","text":"\"\"\" boxUI.templatetags.boxUI_tags\n\n This module defines the custom template tags used by the BoxUI template.\n\"\"\"\nfrom django import template\n\n#############################################################################\n\n# Define the module-level template.Libary object to use for registering\n# template tags and filters.\n\nregister = template.Library()\n\n#############################################################################\n\nglobal_vars = {} # Maps variable name to value.\n\n#############################################################################\n\nclass SetNode(template.Node):\n \"\"\" A custom template node for implementing the \"set\" template tag.\n \"\"\"\n def __init__(self, variable, value):\n \"\"\" Standard initialiser.\n \"\"\"\n self.variable = variable\n self.value = value\n\n\n def render(self, context):\n \"\"\" Render the \"set\" template tag.\n\n We don't actually return anthing. Instead, we store the given\n value into the given variable.\n \"\"\"\n if self.value.startswith('\"') and self.value.endswith('\"'):\n value = self.value[1:-1]\n elif self.value.startswith(\"'\") and self.value.endswith(\"'\"):\n value = self.value[1:-1]\n else:\n value = self.value\n global_vars[self.variable] = value\n return \"\"\n\n#############################################################################\n\ndef set_parser(parser, token):\n \"\"\" The parser function for the \"set\" template tag.\n \"\"\"\n contents = token.split_contents()\n\n err_msg = \"'%s' tag must be of the form: {%% %s <variable> = <value> %%}\" \\\n % (contents[0], contents[0])\n\n if len(contents) != 4: raise template.TemplateSyntaxError(err_msg)\n if contents[2] != \"=\": raise template.TemplateSyntaxError(err_msg)\n\n return SetNode(contents[1], contents[3])\n\n#############################################################################\n\nclass GetNode(template.Node):\n \"\"\" A custom template node for implementing the \"get\" template tag.\n \"\"\"\n def __init__(self, variable):\n \"\"\" Standard initialiser.\n \"\"\"\n self.variable = variable\n\n\n def render(self, context):\n \"\"\" Render the \"set\" template tag.\n\n We return the value of the given variable.\n \"\"\"\n return global_vars.get(self.variable, \"\")\n\n#############################################################################\n\ndef get_parser(parser, token):\n \"\"\" The parser function for the \"get\" template tag.\n \"\"\"\n contents = token.split_contents()\n\n err_msg = \"'%s' tag must be of the form: {%% %s <variable> %%}\" \\\n % (contents[0], contents[0])\n\n if len(contents) != 2: raise template.TemplateSyntaxError(err_msg)\n\n return GetNode(contents[1])\n\n#############################################################################\n\nclass GetHalfNode(template.Node):\n \"\"\" A custom template node for implementing the \"get_half\" template tag.\n \"\"\"\n def __init__(self, variable):\n \"\"\" Standard initialiser.\n \"\"\"\n self.variable = variable\n\n\n def render(self, context):\n \"\"\" Render the \"set\" template tag.\n\n We return the value of the given variable, divided by 2.\n \"\"\"\n value = global_vars.get(self.variable)\n if value == None:\n return \"0\"\n else:\n try:\n value = float(value)\n except ValueError:\n return \"0\"\n return int(value/2)\n\n#############################################################################\n\ndef get_half_parser(parser, token):\n \"\"\" The parser function for the \"get_half\" template tag.\n \"\"\"\n contents = token.split_contents()\n\n err_msg = \"'%s' tag must be of the form: {%% %s <variable> %%}\" \\\n % (contents[0], contents[0])\n\n if len(contents) != 2: raise template.TemplateSyntaxError(err_msg)\n\n return GetHalfNode(contents[1])\n\n#############################################################################\n\n# Register our custom template tags.\n\nregister.tag('set', set_parser)\nregister.tag('get', get_parser)\nregister.tag('get_half', get_half_parser)\n\n","sub_path":"referenceAPI/boxUI/templatetags/boxUI_tags.py","file_name":"boxUI_tags.py","file_ext":"py","file_size_in_byte":4203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"141372122","text":"def game():\n import random\n desk = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n db = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n player_db = set()\n computer_db = set()\n win_db = [{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {1, 4, 7}, {2, 5, 8}, {3, 6, 9}, {1, 5, 9}, {3, 5, 7}]\n def print_desk():\n for i in desk:\n print(\"\".join(map(str, i)))\n def replace_element(who, sign):\n if who == \"computer\":\n repl_element = random.choice(db)\n db.remove(repl_element)\n else:\n repl_element = int(input(\"Введите положение: \"))\n db.remove(repl_element)\n print(repl_element)\n for i in desk:\n for j in i:\n if j == repl_element:\n if who == \"computer\":\n computer_db.add(j)\n i[i.index(j)] = sign\n else:\n player_db.add(j)\n i[i.index(j)] = sign\n def check_win():\n for i in win_db:\n if player_db == i:\n print(\"Player win\")\n return True\n elif computer_db == i:\n print(\"Computer win\")\n return True\n for i in range(1,9):\n replace_element(\"player\",\"0\")\n print_desk()\n if check_win():\n break\n replace_element(\"computer\", \"X\")\n print_desk()\n if check_win():\n break\ngame()\n","sub_path":"A-dy/tic_tac_toe.py","file_name":"tic_tac_toe.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"440010336","text":"# -*- coding: utf-8 -*-\n\n\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport subprocess\nfrom django.shortcuts import render\nfrom django.views.generic import TemplateView\nfrom collections import defaultdict\nimport os\nubicacionlatex='automata.tex'\n\nOperadores={'+', '?', '*', '|', '.'}\nParentesis={'(',')'}\n\nProblematicos={'+', '?', '*', '|'}\nUnarios={'+', '?', '*'}\ntemporal=''\nnewtexto=''\nerror=0\nnumeroEstados=0\nsymbolos=[]\nestados_aceptacion=[]\nnoEstadosAc=0\nfThompson=[]\nEstados=[]\nestadoInicial=0\nfuncionfinal=[]\n\ndef normales(caracter):\n global temporal\n global newtexto\n global error\n if caracter not in Operadores:\n if temporal=='':\n newtexto=newtexto+caracter\n temporal='.'\n else:\n newtexto=newtexto+caracter+'.'\n temporal='.'\n elif caracter in Unarios:\n if temporal in Problematicos:\n error=1\n elif temporal=='.':\n if newtexto[-1]=='.':\n newtexto=newtexto[:-1]\n newtexto=newtexto+caracter+'.'\n temporal=caracter\n else:\n newtexto=newtexto+caracter\n\ndef convertidor(texto):\n global temporal\n global newtexto\n temporal2=0\n temporal=\"\"\n ora=0\n newtexto=''\n contador_parentesis_iz=0\n agregador=0\n for caracter in texto:\n if temporal2>0:\n if agregador>0:\n if newtexto[-1]=='.':\n newtexto=newtexto[:-1]\n if caracter in Unarios:\n newtexto=newtexto+'|'+caracter\n else:\n newtexto=newtexto+'|'+caracter+'.'\n agregador-=1\n temporal2-=1\n else:\n if caracter in Unarios:\n newtexto=newtexto+'|'+caracter\n else:\n newtexto=newtexto+'|'+caracter+'.'\n agregador-=1\n temporal2-=1\n elif caracter in Unarios:\n newtexto=newtexto+caracter\n temporal2-=1\n temporal=''\n else:\n newtexto=newtexto+caracter+\".\"\n temporal=''\n temporal2-=1\n elif caracter=='|':\n if contador_parentesis_iz>0:\n agregador+=1\n elif ora==0:\n temporal=''\n ora=1\n else:\n temporal=''\n newtexto=newtexto+'|'\n elif caracter=='(':\n temporal=''\n contador_parentesis_iz+=1\n elif caracter==')':\n temporal='.'\n contador_parentesis_iz-=1\n temporal2+=1\n else:\n normales(caracter)\n if ora==1:\n newtexto=newtexto +'|'\n if texto[1] in Operadores:\n error=1\n elif contador_parentesis_iz!=0:\n error=1\n if temporal2>0:\n if agregador>0:\n if newtexto[-1]=='.':\n newtexto=newtexto[:-1]\n newtexto=newtexto+'|'\n agregador-=1\n temporal2-=1\n else:\n newtexto=newtexto+'|'\n agregador-=1\n temporal2-=1\n return newtexto","sub_path":"Progra 2/Proyecto/Principal/InfijoAPostFijo.py","file_name":"InfijoAPostFijo.py","file_ext":"py","file_size_in_byte":3329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"597981161","text":"from Products.Five import BrowserView\nfrom plone.dexterity.browser import edit\n\nfrom collective.instancebehavior import (\n enable_behaviors,\n instance_behaviors_of,\n disable_behaviors,\n)\n\nfrom ..config import SCRIPT_ID_DELIMITER\n\n\nclass FieldView(BrowserView):\n\n def filterusers(self):\n if self.context.field_type == \"NAME\":\n self.request.RESPONSE.setHeader(\n 'content-type', 'application/json; charset=utf-8')\n return self.context.getSettings().getFilteredNames(\n self.request.get('query'))\n\n\nclass EditForm(edit.DefaultEditForm):\n\n def update(self):\n if 'update.field.type' in self.request:\n self._updateFieldType()\n return super(EditForm, self).update()\n\n def _updateFieldType(self):\n # Update the field type. This will force the form to load with the\n # relevant field type settings.\n field_type = self.request['form.widgets.field_type'][0]\n obj = self.getContent()\n obj.field_type = field_type\n\n # Disable, then enable the appropriate behaviors\n existing_behaviors = instance_behaviors_of(obj)\n disable_behaviors(obj, existing_behaviors, [], reindex=False)\n behavior = 'Products.CMFPlomino.fields.%s.I%sField' % (\n field_type.lower(),\n field_type.capitalize(),\n )\n\n # XXX: This doesn't seem to reindex object_provides properly\n enable_behaviors(obj, [behavior, ], [])\n\n # Ignore the context so the form is rendered with values on the request\n self.ignoreContext = True\n\n # cleanup compiled formulas\n obj.cleanFormulaScripts(\n SCRIPT_ID_DELIMITER.join([\n \"field\",\n obj.getPhysicalPath()[-2],\n obj.id\n ])\n )\n\n # re-index\n db = obj.getParentDatabase()\n if obj.to_be_indexed and not db.do_not_reindex:\n db.getIndex().createFieldIndex(\n obj.id,\n obj.field_type,\n indextype=obj.index_type,\n fieldmode=obj.field_mode,\n )\n","sub_path":"src/Products/CMFPlomino/browser/field.py","file_name":"field.py","file_ext":"py","file_size_in_byte":2132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"155148934","text":"import argparse\nimport cv2\nimport imutils\n\nap = argparse.ArgumentParser()\nap.add_argument('-i' ,'--input' ,required = True , help = 'path to the uinput image')\nap.add_argument('-o' ,'--output' ,required = True , help = 'path to the output image')\nargs = vars(ap.parse_args())\n\n#load the input image from the disk\nimage = cv2.imread(args['input'])\n\n#convert the image into gray scale ,blur it and threshold it.\ngray = cv2.cvtColor(image ,cv2.COLOR_BGR2GRAY)\nblurred = cv2.GaussianBlur(gray ,(5,5) ,0)\nthresh = cv2.threshold(blurred ,60 ,255 ,cv2.THRESH_BINARY)[1]\n\n#extract the contours from the image\ncnts = cv2.findContours(thresh.copy() ,cv2.RETR_EXTERNAL ,cv2.CHAIN_APPROX_SIMPLE)\ncnts = imutils.grab_contours(cnts)\n\n#loop over the contours and draw them over the image\nfor c in cnts:\n cv2.drawContours(image ,[c] ,-1 ,(0 ,0 ,255) ,2)\n\n#Display the total number of shapes on the image\ntext = f' I found {len(cnts)} no of shape '\ncv2.putText(image ,text ,(10 ,20) ,cv2.FONT_HERSHEY_SIMPLEX ,0.5 ,(0 ,0 ,255) ,2)\n\n#write the output iamge to the disk\ncv2.imwrite(args['output'] ,image)\n","sub_path":"Image_operations/Contours/shape_counter.py","file_name":"shape_counter.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"207792034","text":"N, M = map(int, input().split())\n\n# 1. 2칸 위, 1칸 오른쪽\n# 2. 1칸 위, 2칸 오른쪽\n# 3. 1칸 아래, 2칸 오른쪽\n# 4. 2칸 아래, 1칸 오른쪽\n\nif N == 1:\n answer = 1\nelif N == 2: # 위 아래로 한 칸씩 이동 가능 > 최대 3번 이동 & 가로로 이동 가능한 경\n answer = min(4, (M-1)//2+1)\nelif M < 7:\n answer = min(4, M)\nelse:\n answer = (2 + (M-5)) + 1 # 2,3 이동 + 2,3이동으로 인한 5칸 제외 + 처음 있던\n\nprint(answer)\n","sub_path":"AHYEON/01.GREEDY/1783_병든나이트.py","file_name":"1783_병든나이트.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"175091015","text":"# PM2.5即時監測顯示器\n\nimport os\nimport tkinter as tk\nimport pandas as pd\n\ndef rbCity(): #點選縣市選項按鈕後處理函式\n global sitelist, listradio\n sitelist.clear() #清除原有測站串列\n for r in listradio: #移除原有測站選項按鈕\n r.destroy()\n n=0\n for c1 in data[\"county\"]: #逐一取出選取縣市的測站\n if(c1 == city.get()):\n sitelist.append(data.iloc[n, 0])\n n += 1 \n sitemake() #建立測站選項按鈕\n rbSite() #顯示PM2.5訊息\n\ndef rbSite(): #點選測站選項按鈕後處理函式\n n = 0\n for s in data.iloc[:, 0]: #逐一取得測站\n if(s == site.get()): #取得點選的測站\n print('s = ', s)\n pm = data.iloc[n, 2] #取得PM2.5的值\n if(pm=='' or pm=='ND'): #如果沒有資料\n result1.set(s + \"站的 PM2.5 值目前無資料!\")\n else: #如果有資料\n if(int(pm) <= 35): #轉換為等級\n grade1 = \"低\"\n elif(int(pm) <= 53):\n grade1 = \"中\"\n elif(int(pm) <= 70):\n grade1 = \"高\"\n else:\n grade1 = \"非常高\"\n result1.set(s + \"站的 PM2.5 值為「\" + str(pm) + \"」:「\" + grade1 + \"」等級\")\n break #找到點選測站就離開迴圈\n n += 1\n \ndef clickRefresh(): #重新讀取資料\n print('你按了 更新資料')\n '''\n global data\n data = pd.read_csv(url)\n rbSite() #更新測站資料\n '''\n\ndef sitemake(): #建立測站選項按鈕\n global sitelist, listradio\n for c1 in sitelist: #逐一建立選項按鈕\n rbtem = tk.Radiobutton(frame2, text=c1, variable=site, value=c1, command = rbSite) #建立選項按鈕\n listradio.append(rbtem) #加入選項按鈕串列\n if(c1==sitelist[0]): #預設選取第1個項目 \n rbtem.select()\n rbtem.pack(side=\"left\") #靠左排列\n\n\n\nfilename = 'C:/_git/vcs/_1.data/______test_files1/__RW/_csv/python_ReadWrite_CSV4_AQX_P_432.csv'\ndata = pd.read_csv(filename)\n\nwindow = tk.Tk()\nwindow.geometry(\"640x270\")\nwindow.title(\"PM2.5 實時監測\")\n\ncity = tk.StringVar() #縣市文字變數\nsite = tk.StringVar() #測站文字變數\nresult1 = tk.StringVar() #訊息文字變數\n\ncitylist = [] #縣市串列\nsitelist = [] #鄉鎮串列\nlistradio = [] #鄉鎮選項按鈕串列\n\n#建立縣市串列\nfor c1 in data[\"county\"]: \n if(c1 not in citylist): #如果串列中無該縣市就將其加入\n print(c1)\n citylist.append(c1)\n \n#建立第1個縣市的測站串列\ncount = 0\nfor c1 in data[\"county\"]: \n if(c1 == citylist[0]): #是第1個縣市的測站\n sitelist.append(data.iloc[count, 0])\n count += 1\n\nlabel1 = tk.Label(window, text = \"縣市:\", pady = 6, fg = \"blue\", font = (\"新細明體\", 12))\nlabel1.pack()\nframe1 = tk.Frame(window) #縣市容器\nframe1.pack()\nfor i in range(0, 3): #3列選項按鈕\n for j in range(0, 8): #每列8個選項按鈕\n n = i * 8 + j #第n個選項按鈕\n if(n < len(citylist)):\n city1 = citylist[n] #取得縣市名稱\n rbtem = tk.Radiobutton(frame1, text = city1, variable = city, value = city1, command = rbCity) #建立選項按鈕\n rbtem.grid(row = i, column = j) #設定選項按鈕位置\n if(n == 0): #選取第1個縣市\n rbtem.select()\n\nlabel2 = tk.Label(window, text = \"測站:\", pady = 6, fg = \"blue\", font = (\"新細明體\", 12))\nlabel2.pack()\nframe2 = tk.Frame(window) #測站容器\nframe2.pack()\n\nsitemake()\n\nbutton1 = tk.Button(window, text = \"更新資料\", font = (\"新細明體\", 12), command = clickRefresh)\nbutton1.pack(pady = 6)\n\nlabel3 = tk.Label(window, textvariable = result1, fg = \"red\", font = (\"新細明體\", 16))\nlabel3.pack(pady = 6)\n\nrbSite() #顯示測站訊息\n\nwindow.mainloop()\n","sub_path":"_4.python/tkinter/_example/tk_ex_array.py","file_name":"tk_ex_array.py","file_ext":"py","file_size_in_byte":3981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"437499826","text":"\n\n#ROUTES FOR PYTHON TO GRAB\n\nPORT = \"8080\"\nODS_PROTOCOL=\"https://\"\nLISTV1 = \"/api/{type}/ls\"\nLISTV2 = \"/api/{type}/ls\"\nMKDIRV1 = \"/api/{type}/mkdir\"\nMKDIRV2 = \"/api/{type}/mkdir\"\nREMOVEV2 = \"/api/{type}/rm\"\nDOWNLOADV2 = \"/api/{type}/download\"\nTRANSFER = \"/api/transferjob\"\nVALIDATE_EMAILV1 = \"/is-email-registered\"\nVALIDATE_EMAILV2 = \"/is-email-registered\"\nAUTHENTICATEV1 = \"/authenticate\"\nAUTHENTICATEV2 = \"/authenticate\"\nCRED_ACCOUNT_REGISTERV2 = \"/api/cred/{type}\"\nCRED_ACCOUNT_DELETE = \"/api/cred/{type}/{credID}\"\n\nCRED_OAUTH_REGISTERV2 = \"/api/oauth\"\nCRED_ACCOUNT_GETV2 = \"/endpoint-cred/{userId}/{type}\"\nCRED_ACCOUNTID_GETV2 = \"/endpoint-cred/{userId}/{type}/{accountId}\"\n","sub_path":"SDK/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"170537462","text":"import collections\nimport string\nfrom szyfrow.support.utilities import sanitise\n\ncorpora = ['shakespeare.txt', 'sherlock-holmes.txt', 'war-and-peace.txt']\ncounts = collections.Counter()\n\nfor corpus in corpora:\n text = sanitise(open('szyfrow/support/' + corpus, 'r').read())\n counts.update(text)\n\nsorted_letters = sorted(counts, key=counts.get, reverse=True)\n\nwith open('szyfrow/support/count_1l.txt', 'w') as f:\n for l in sorted_letters:\n f.write(\"{0}\\t{1}\\n\".format(l, counts[l]))\n \n ","sub_path":"raw_data_processing/lettercount.py","file_name":"lettercount.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"532691762","text":"import csv\nfrom typing import List, Tuple\nfrom collections import deque\n\nclass TreeNode:\n def __init__(self, Type = None, left=None, right=None, notword=None, Notleft=False, Notright = False):\n self.type = Type\n self.left = left\n self.right = right\n self.notleft = Notleft\n self.notright = Notright\n\nclass TweetIndex:\n \n def __init__(self):\n self.list_of_tweets = []\n self.invalid = False\n \n def searchTree(self, node: TreeNode, notlist: list):\n if self.invalid:\n return (\"\", -1)\n if node.type == '&':\n return self.process_and(node, notlist)\n elif node.type == '|':\n return self.process_or(node, notlist)\n elif node.type == '!':\n return self.process_not(node.left)\n elif node.type == 'w':\n return self.search(node.left, notlist)\n \n def process_not(self, node):\n print(node.left.lower())\n return [node.left.lower()]\n \n def process_or(self, node, notlist):\n leftret = self.searchTree(node.left, notlist)\n rightret = self.searchTree(node.right, notlist)\n if leftret[1] > rightret[1]:\n return leftret\n else:\n return rightret\n \n def process_and(self, node, notlist):\n if node.notleft and not node.notright:\n notlist = self.searchTree(node.left, notlist)\n return self.searchTree(node.right, notlist)\n elif node.notright and not node.notleft:\n notlist = self.searchTree(node.right, notlist)\n return self.searchTree(node.left, notlist)\n elif node.notleft and node.notright:\n notlist = self.searchTree(node.left, notlist)\n tweet, stamp = self.searchTree(node.right, notlist)\n notlist[0] += tweet\n notlist[1] += stamp\n return notlist\n else:\n left = self.searchTree(node.left, [])\n right = self.searchTree(node.right, [])\n return (left[0]+right[0], left[1]+right[1])\n \n def constructTree(self, query:str):\n exp_stack = deque([])\n op_stack = deque([])\n splits = query.split(' ')\n splitsCpy = []\n for i in range(len(splits)):\n while splits[i][0] == '!' or splits[i][0] == '(':\n splitsCpy.append(splits[i][0])\n splits[i] = splits[i][1:]\n \n wordidx = len(splits[i])-1\n while splits[i][wordidx] == ')':\n wordidx-=1\n \n splitsCpy.append(splits[i][:wordidx+1])\n for j in range(len(splits[i]) - 1 - wordidx):\n splitsCpy.append(')')\n \n left_p = 0\n for c in splitsCpy:\n if c == '&':\n op_stack.append(c)\n elif c == '|':\n if op_stack:\n if op_stack[-1] == '&' or op_stack[-1] == '!':\n self.invalid = True\n return\n if not len(splitsCpy) == 3 and not left_p > 0:\n self.invalid = True\n return\n op_stack.append(c)\n elif c == '!':\n op_stack.append(c)\n elif c == '(':\n op_stack.append('(')\n left_p += 1\n elif c == ')':\n while not op_stack[-1] == '(':\n op = op_stack.pop()\n right = exp_stack.pop()\n left = exp_stack.pop()\n temp = TreeNode(op, left, right)\n if left.type == '!':\n temp.notleft = True\n elif right.type == '!':\n temp.notright = True\n exp_stack.append(temp)\n op_stack.pop()\n left_p -= 1\n else:\n if op_stack:\n if not op_stack[-1] == '(':\n if op_stack[-1] == '!':\n exp_stack.append(TreeNode(op_stack.pop(), TreeNode('w', c)))\n else:\n exp_stack.append(TreeNode(op_stack.pop(), exp_stack.pop(), TreeNode('w', c)))\n else:\n exp_stack.append(TreeNode('w', c))\n else:\n exp_stack.append(TreeNode('w', c))\n \n while op_stack:\n if op_stack[-1] == '!':\n exp_stack.append(TreeNode(op_stack.pop(), exp_stack.pop()))\n else:\n op = op_stack.pop()\n left = exp_stack.pop()\n right = exp_stack.pop()\n temp = TreeNode(op, left, right)\n if left.type == '!':\n temp.notleft = True\n elif right.type == '!':\n temp.notright = True\n exp_stack.append(temp)\n return exp_stack[-1]\n \n def search(self, word: str, notlist: list):\n wordlower = word.lower()\n for tweet, timestamp in self.list_of_tweets:\n if wordlower in tweet[0]:\n contain_not_word = False\n if notlist:\n for notword in notlist[0]:\n if notword[0] in tweet[0]:\n contain_not_word = True\n break\n if contain_not_word:\n continue\n else:\n return ([tweet[1]], timestamp)\n return ([], 0)\n \n def process_tweets(self, list_of_timestamps_and_tweets: List[Tuple[str, int]]) -> None:\n for row in list_of_timestamps_and_tweets:\n timestamp = int(row[0])\n tweet = row[1]\n self.list_of_tweets.append((tweet, timestamp))\n self.list_of_tweets.sort(key = lambda x:x[1], reverse = True)\n \n #debug use\n def traverse(self, root, lvl):\n if self.invalid:\n return\n if type(root.left) == str:\n print(lvl, root.left)\n return\n else:\n self.traverse(root.left, lvl+' ')\n print(lvl, root.type)\n if root.right:\n self.traverse(root.right, lvl+' ')\n \n\nif __name__ == \"__main__\":\n # A full list of tweets is available in data/tweets.csv for your use.\n tweet_csv_filename = \"tweets.csv\"\n list_of_tweets = []\n with open(tweet_csv_filename, \"r\") as f:\n csv_reader = csv.reader(f, delimiter=\",\")\n for i, row in enumerate(csv_reader):\n if i == 0:\n # header\n continue\n timestamp = int(row[0])\n tweet = str(row[1])\n lowercase_tweets = set()\n for word in tweet.split():\n lowercase_tweets.add(word.lower())\n list_of_tweets.append((timestamp, (lowercase_tweets, tweet)))\n \n cmd = \"(!hello & (yay | neeva)) & me\"\n ti = TweetIndex()\n ti.process_tweets(list_of_tweets)\n root = ti.constructTree(cmd)\n ti.traverse(root, \" \")\n for i in range(5):\n ret = ti.searchTree(root,[])\n print(ret[0])\n removed = set()\n for r in ret[0]:\n if r in removed:\n break\n for j in range(len(ti.list_of_tweets)):\n if r == ti.list_of_tweets[j][0][1]:\n removed.add(ti.list_of_tweets.pop(j)[0][1])\n break\n","sub_path":"myCode.py","file_name":"myCode.py","file_ext":"py","file_size_in_byte":7446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"208363541","text":"# First take the input phrase and split it into a list of its\n# constituent words, words[]. Then, take that list, and\n# create a second list that removes all of the duplicates,\n# deDupedWords[]. That way, we can see just the individual\n# words that make up the phrase, regardless of how many times\n# they occur. We then take that second, deduped list and use\n# the elemets of that list to count their occurence in the\n# first list that contains everything from the input phrase.\n# Then, add the words and their counts to the wordCount\n# dictionary and return that dictionary.\n\n\ndef word_count(phrase):\n \"\"\"Takes in a phrase and returns a dictionary listing\n each word in the phrase and the number of times it\n appears.\n \"\"\"\n words = phrase.split()\n deDupedWords = set(words)\n wordCount = {}\n\n for element in deDupedWords:\n wordCount.update({element: words.count(element)})\n\n return wordCount\n","sub_path":"all_data/exercism_data/python/word-count/de5d4600bb6046b7a4674c49aea3b033.py","file_name":"de5d4600bb6046b7a4674c49aea3b033.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"8589443","text":"import web\r\n# @\r\nfrom web import form\r\ndb = web.database(dbn='mysql', db='qgita32e92n4cdkh', user='mjgbfztb8gvczgwx', pw='d2yjba6ofcokmjix', host='tkck4yllxdrw0bhi.cbetxkdyhwsb.us-east-1.rds.amazonaws.com')\r\nrender=web.template.render('templates')\r\nurls = (\r\n \r\n '/','index',\r\n '/nuevo', 'nuevo',\r\n '/editar/(.+)','editar',\r\n '/ver/(.+)','ver',\r\n '/eliminar/(.+)','eliminar'\r\n)\r\n\r\n\r\n\r\nmyformAgendas=form.Form(\r\n form.Textbox('Nombre'), \r\n form.Textbox('Telefono'),\r\n form.Textbox('Email'),\r\n form.Textbox('Direccion'),\r\n \r\n)\r\nclass index:\r\n def GET(self):\r\n \r\n result=db.select('datos')\r\n return render.index(result)\r\n def POST(self): \r\n raise web.seeother(\"/nuevo\") \r\nclass nuevo:\r\n def GET(self):\r\n formNew=myformAgendas()\r\n return render.nuevo(formNew)\r\n def POST(self): \r\n formNew = myformAgendas()\r\n if not formNew.validates(): \r\n return render.nuevo(formNew)\r\n else:\r\n db.insert('datos', nombre=formNew.d.Nombre, \r\n telefono=formNew.d.Telefono, email=formNew.d.Email,\r\n direccion=formNew.d.Direccion)\r\n result=db.select('datos')\r\n raise web.seeother('/')\r\n \r\n\r\nclass editar:\r\n def GET(self,id_dato):\r\n formEdit=myformAgendas()\r\n \r\n \r\n result=db.select('datos', where= \"id_dato=%s\"%(id_dato))\r\n \r\n for row in result:\r\n formEdit['Nombre'].value=row.nombre\r\n formEdit['Telefono'].value=row.telefono\r\n formEdit['Email'].value=row.email\r\n formEdit['Direccion'].value=row.direccion\r\n \r\n return render.editar(formEdit) \r\n def POST(self,id_dato):\r\n formEdit=myformAgendas()\r\n if not formEdit.validates(): \r\n return render.editar(formEdit)\r\n else:\r\n db.update('datos', where='id_dato=%s'%(id_dato), nombre=formEdit.d.Nombre,\r\n telefono=formEdit.d.Telefono, email=formEdit.d.Email,\r\n direccion=formEdit.d.Direccion)\r\n result=db.select('datos')\r\n raise web.seeother('/')\r\nclass eliminar:\r\n def GET(self,id_dato):\r\n formEdit=myformAgendas()\r\n \r\n result=db.select('datos', where='id_dato=%s'%(id_dato))\r\n \r\n for row in result:\r\n formEdit['Nombre'].value=row.nombre\r\n formEdit['Telefono'].value=row.telefono\r\n formEdit['Email'].value=row.email\r\n formEdit['Direccion'].value=row.direccion\r\n \r\n return render.eliminar(formEdit) \r\n def POST(self,id_dato):\r\n formEdit=myformAgendas()\r\n if not formEdit.validates(): \r\n return render.eliminar(formEdit)\r\n else:\r\n db.delete('datos', where=\"id_dato=%s\"%(id_dato))\r\n raise web.seeother('/')\r\n\r\n\r\nif __name__ == \"__main__\":\r\n \r\n app = web.application(urls, globals())\r\n app.run()","sub_path":"webapp.py","file_name":"webapp.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"348294695","text":"from tqdm import tqdm\n\ndef play(cups, turns):\n maxcup = max(cups)\n curr = list(cups)[0]\n for i in tqdm(range(turns)):\n removed = (cups[curr], cups[cups[curr]], cups[cups[cups[curr]]])\n cups[curr] = cups[removed[-1]]\n dest = curr - 1\n while dest <= 0 or dest in removed:\n dest -= 1\n if dest <= 0:\n dest = maxcup\n cups[dest], cups[removed[-1]] = removed[0], cups[dest]\n curr = cups[curr]\n\nwith open(\"../../original_solutions/day_23/input_23.txt\") as input_file:\n cup_list = [int(i) for i in input_file.read().strip()]\n\n cups = {cup_list[i]:cup_list[(i+1) % len(cup_list)] for i in range(len(cup_list))}\n play(cups, 100)\n j = cups[1]\n l = []\n while j != 1:\n l.append(str(j))\n j = cups[j]\n print(\"part A:\", \"\".join(l))\n\n cup_list += list(range(max(cup_list)+1, 1_000_000+1))\n cups = {cup_list[i]:cup_list[(i+1) % len(cup_list)] for i in range(len(cup_list))}\n play(cups, 10_000_000)\n print(\"part B:\", cups[1] * cups[cups[1]])\n","sub_path":"improved_solutions/day_23/day_23.py","file_name":"day_23.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"170107804","text":"from utl.database.models.models import db, SavedOpportunity\nfrom .opportunities import getOpportunity\n\n\ndef getSavedOpportunities(userID):\n savedOpportunities = SavedOpportunity.query.filter_by(userID=userID).all()\n opportunities = []\n for savedOpportunity in savedOpportunities:\n opportunities.append(getOpportunity(savedOpportunity.opportunityID))\n return opportunities\n\n\ndef saveOpportunity(userID, opportunityID):\n exists = db.session.query(SavedOpportunity.query.filter(\n SavedOpportunity.userID == userID, SavedOpportunity.opportunityID == opportunityID).exists()).scalar()\n if exists:\n return False\n else:\n opportunity = SavedOpportunity(\n userID=userID, opportunityID=opportunityID, reminderDate=None)\n db.session.add(opportunity)\n db.session.commit()\n return True\n\n\ndef unsaveOpportunity(userID, opportunityID):\n SavedOpportunity.query.filter_by(\n userID=userID, opportunityID=opportunityID\n ).delete()\n db.session.commit()\n\n\ndef addOpportunityReminder(userID, opportunityID, reminderDate):\n opportunity = SavedOpportunity.query.filter_by(\n userID=userID, opportunityID=opportunityID\n ).first()\n opportunity.reminderDate = reminderDate\n db.session.commit()\n\n\ndef removeOpportunityReminder(userID, opportunityID):\n opportunity = SavedOpportunity.query.filter_by(\n userID=userID, opportunityID=opportunityID\n ).first()\n opportunity.reminderDate = None\n db.session.commit()\n","sub_path":"app/utl/database/functions/models/savedOpportunities.py","file_name":"savedOpportunities.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"166443498","text":"## Import libraries\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n\r\n## Variables\r\ndir='C:\\\\Users\\\\cleme\\\\Desktop\\\\APC_2021\\\\tmp\\\\' #chemin du directory\r\nband='V'\r\nLC=band+'.txt'\r\n\r\n\r\n## Functions\r\n\r\ndef read_lightcurves(path):\r\n time=[]\r\n mag=[]\r\n data=open(path,'r').read().split('\\n')\r\n for i in data:\r\n if i=='/' or i=='':\r\n continue\r\n else:\r\n tmp=i.split('\\t')\r\n time.append(float(tmp[0]))\r\n mag.append(float(tmp[1]))\r\n return time,mag\r\n\r\n##core\r\ntime,mag=read_lightcurves(dir+LC)\r\n\r\ntmin,tmax,dt=round(min(time),0),int(max(time)),0.5\r\ntimebins=np.array([round(tmin+i*dt,1) for i in range(int(1/dt*(tmax-tmin)+1))])\r\nmagbins=[[] for i in range(len(timebins))]\r\nmeanmag=[]\r\n\r\nfor i in range(len(time)):\r\n argument=np.where(abs(timebins-time[i])<0.5)\r\n if len(argument[0])==0:\r\n continue\r\n else:\r\n intargument=int(argument[0][0])\r\n magbins[intargument].append(mag[i])\r\n\r\nfor i in magbins:\r\n if len(i)>7:\r\n meanmag.append(np.mean(i))\r\n else:\r\n meanmag.append(np.nan)\r\n\r\nplt.plot(timebins,meanmag,'.',label=band+' mean')\r\nplt.gca().invert_yaxis()\r\n#plt.title('3e test de moyenne sur l\\'échantillon de SN')\r\nplt.xlabel('temps en jours')\r\nplt.ylabel('magnitude absolue')\r\nplt.legend()\r\nplt.show()","sub_path":"old/moyenne.py","file_name":"moyenne.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"460510677","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#-\n# set_code_style.py\n#\n# Created by vamirio on 2022 Aug 30\n#-\n\nimport sys\nimport subprocess\nimport os\n\nimport pylib.base as base\n\nif not base.checkArgsNum(sys.argv, 2, \"Args: srcStyleFile curDir.\"):\n exit(1)\n\nsrcStyleFile, curDir = sys.argv[1:]\nprojectRoot = base.getProjectRoot(curDir)\nif projectRoot == \"\":\n base.printError(\"Error: can't find the root directory of project, check if a\",\n base.projectRootFlag, \"file/directory in it.\")\n exit(1)\n\ndestStyleFile = os.path.join(projectRoot, \".clang-format\")\nif os.path.exists(destStyleFile):\n base.printError(\"Warn:\", destStyleFile,\n \"is already exists, remove it if you want to reset the code style.\")\n exit(1)\nsubprocess.run([\"cp\", srcStyleFile, destStyleFile])\n","sub_path":"utils/set_code_style.py","file_name":"set_code_style.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"}